porting all github actions from bluesky-social/indigo to tangled CI
1package cachestore
2
3import (
4 "context"
5 "time"
6
7 "github.com/go-redis/cache/v9"
8 "github.com/redis/go-redis/v9"
9)
10
11type RedisCacheStore struct {
12 Data *cache.Cache
13 TTL time.Duration
14}
15
16var _ CacheStore = (*RedisCacheStore)(nil)
17
18func NewRedisCacheStore(redisURL string, ttl time.Duration) (*RedisCacheStore, error) {
19 ctx := context.Background()
20 opt, err := redis.ParseURL(redisURL)
21 if err != nil {
22 return nil, err
23 }
24 rdb := redis.NewClient(opt)
25 // check redis connection
26 _, err = rdb.Ping(ctx).Result()
27 if err != nil {
28 return nil, err
29 }
30 data := cache.New(&cache.Options{
31 Redis: rdb,
32 LocalCache: cache.NewTinyLFU(10_000, ttl),
33 })
34 return &RedisCacheStore{
35 Data: data,
36 TTL: ttl,
37 }, nil
38}
39
40func redisCacheKey(name, key string) string {
41 return "cache/" + name + "/" + key
42}
43
44func (s RedisCacheStore) Get(ctx context.Context, name, key string) (string, error) {
45 var val string
46 err := s.Data.Get(ctx, redisCacheKey(name, key), &val)
47 if err == cache.ErrCacheMiss {
48 return "", nil
49 }
50 if err != nil {
51 return "", err
52 }
53 return val, nil
54}
55
56func (s RedisCacheStore) Set(ctx context.Context, name, key string, val string) error {
57 return s.Data.Set(&cache.Item{
58 Ctx: ctx,
59 Key: redisCacheKey(name, key),
60 Value: val,
61 TTL: s.TTL,
62 })
63}
64
65func (s RedisCacheStore) Purge(ctx context.Context, name, key string) error {
66 err := s.Data.Delete(ctx, redisCacheKey(name, key))
67 if err == cache.ErrCacheMiss {
68 return nil
69 }
70 return err
71}