Progress meow

This commit is contained in:
Melody Becker 2024-09-12 08:56:57 +02:00
parent 490b788e7b
commit 814316ab1e
11 changed files with 279 additions and 35 deletions

View file

@ -1,6 +1,8 @@
package cache
import (
"context"
"fmt"
"time"
"github.com/dgraph-io/ristretto"
@ -10,7 +12,6 @@ import (
ristretto_store "github.com/eko/gocache/store/ristretto/v4"
"github.com/redis/go-redis/v9"
"github.com/rs/zerolog/log"
"gitlab.com/mstarongitlab/linstrom/config"
)
type Cache struct {
@ -19,16 +20,20 @@ type Cache struct {
encoders *EncoderPool
}
func NewCache() (*Cache, error) {
var ctxBackground = context.Background()
// TODO: Maybe also include metrics
func NewCache(maxSize int64, redisUrl *string) (*Cache, error) {
// ristretto is an in-memory cache
log.Debug().Int64("max-size", maxSize).Msg("Setting up ristretto")
ristrettoCache, err := ristretto.NewCache(&ristretto.Config{
// The *10 is a recommendation from ristretto
NumCounters: config.GlobalConfig.Storage.MaxInMemoryCacheSize * 10,
MaxCost: config.GlobalConfig.Storage.MaxInMemoryCacheSize,
NumCounters: maxSize * 10,
MaxCost: maxSize,
BufferItems: 64, // Same here
})
if err != nil {
return nil, err
return nil, fmt.Errorf("ristretto cache error: %w", err)
}
ristrettoStore := ristretto_store.NewRistretto(
ristrettoCache,
@ -36,12 +41,8 @@ func NewCache() (*Cache, error) {
)
var cacheManager *cache.ChainCache[[]byte]
if config.GlobalConfig.Storage.UseRedis {
if config.GlobalConfig.Storage.RedisUrl == nil {
log.Fatal().
Msg("Told to use redis in addition to in-memory store, but no redis url provided!")
}
opts, err := redis.ParseURL(*config.GlobalConfig.Storage.RedisUrl)
if redisUrl != nil {
opts, err := redis.ParseURL(*redisUrl)
if err != nil {
return nil, err
}
@ -61,3 +62,29 @@ func NewCache() (*Cache, error) {
encoders: NewEncoderPool(),
}, nil
}
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)
}