linstrom/storage/cache/cache.go

99 lines
2.4 KiB
Go
Raw Normal View History

package cache
import (
2024-09-12 06:56:57 +00:00
"context"
"fmt"
"time"
"github.com/dgraph-io/ristretto"
"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/lib/v4/store"
redis_store "github.com/eko/gocache/store/redis/v4"
ristretto_store "github.com/eko/gocache/store/ristretto/v4"
"github.com/redis/go-redis/v9"
"github.com/rs/zerolog/log"
2024-09-15 13:18:05 +00:00
"gitlab.com/mstarongitlab/linstrom/config"
)
type Cache struct {
cache *cache.ChainCache[[]byte]
decoders *DecoderPool
encoders *EncoderPool
}
2024-09-12 06:56:57 +00:00
var ctxBackground = context.Background()
// TODO: Maybe also include metrics
func NewCache(maxSize int64, redisUrl *string) (*Cache, error) {
// ristretto is an in-memory cache
2024-09-12 06:56:57 +00:00
log.Debug().Int64("max-size", maxSize).Msg("Setting up ristretto")
ristrettoCache, err := ristretto.NewCache(&ristretto.Config{
// The *10 is a recommendation from ristretto
2024-09-12 06:56:57 +00:00
NumCounters: maxSize * 10,
MaxCost: maxSize,
BufferItems: 64, // Same here
})
if err != nil {
2024-09-12 06:56:57 +00:00
return nil, fmt.Errorf("ristretto cache error: %w", err)
}
ristrettoStore := ristretto_store.NewRistretto(
ristrettoCache,
2024-09-15 13:18:05 +00:00
store.WithExpiration(
time.Second*time.Duration(config.GlobalConfig.Storage.MaxInMemoryCacheSize),
),
)
var cacheManager *cache.ChainCache[[]byte]
2024-09-12 06:56:57 +00:00
if redisUrl != nil {
opts, err := redis.ParseURL(*redisUrl)
if err != nil {
return nil, err
}
redisClient := redis.NewClient(opts)
2024-09-15 13:18:05 +00:00
redisStore := redis_store.NewRedis(
redisClient,
store.WithExpiration(
time.Second*time.Duration(*config.GlobalConfig.Storage.MaxRedisCacheTTL),
),
)
cacheManager = cache.NewChain(
cache.New[[]byte](ristrettoStore),
cache.New[[]byte](redisStore),
)
} else {
cacheManager = cache.NewChain(cache.New[[]byte](ristrettoStore))
}
return &Cache{
cache: cacheManager,
decoders: NewDecoderPool(),
encoders: NewEncoderPool(),
}, nil
}
2024-09-12 06:56:57 +00:00
func (c *Cache) Get(key string, target any) (bool, error) {
data, err := c.cache.Get(ctxBackground, key)
if err != nil {
return false, err
}
err = c.decoders.Decode(data, target)
if err != nil {
return false, err
}
return true, err
}
func (c *Cache) Set(key string, value any) error {
data, err := c.encoders.Encode(value)
if err != nil {
return err
}
err = c.cache.Set(ctxBackground, key, data, nil)
return err
}
func (c *Cache) Delete(key string) {
// Error return doesn't matter here. Delete is delete is gone
_ = c.cache.Delete(ctxBackground, key)
}