package cache import ( "context" "errors" "time" "github.com/dgraph-io/ristretto/v2" ) var _ Cache = (*_mem)(nil) type _mem struct { ctx context.Context cache *ristretto.Cache[string, []byte] } func newMemory(ctx context.Context, ins *ristretto.Cache[string, []byte]) Cache { return &_mem{ ctx: ctx, cache: ins, } } func (m *_mem) Client() any { return m.cache } func (c *_mem) Close() { c.cache.Close() } func (c *_mem) Del(ctx context.Context, keys ...string) error { for _, key := range keys { c.cache.Del(key) } return nil } func (c *_mem) Get(ctx context.Context, key string) ([]byte, error) { val, ok := c.cache.Get(key) if !ok { return val, ErrorKeyNotFound } return val, nil } func (c *_mem) GetDel(ctx context.Context, key string) ([]byte, error) { val, err := c.Get(ctx, key) if err != nil { return val, err } c.cache.Del(key) return val, err } func (c *_mem) GetDelScan(ctx context.Context, key string) Scanner { val, err := c.GetDel(ctx, key) return newScan(val, err) } func (c *_mem) GetEx(ctx context.Context, key string, duration time.Duration) ([]byte, error) { val, err := c.Get(ctx, key) if err != nil { return val, err } c.cache.SetWithTTL(key, val, 1, duration) return val, err } func (m *_mem) GetExScan(ctx context.Context, key string, duration time.Duration) Scanner { val, err := m.GetEx(ctx, key, duration) return newScan(val, err) } func (m *_mem) GetScan(ctx context.Context, key string) Scanner { val, err := m.Get(ctx, key) return newScan(val, err) } func (m *_mem) Gets(ctx context.Context, keys ...string) ([][]byte, error) { vals := make([][]byte, 0, len(keys)) for _, key := range keys { val, err := m.Get(ctx, key) if err != nil { if errors.Is(err, ErrorKeyNotFound) { continue } return vals, err } vals = append(vals, val) } if len(vals) != len(keys) { return vals, ErrorKeyNotFound } return vals, nil } func (m *_mem) Set(ctx context.Context, key string, value any) error { val, err := handleValue(value) if err != nil { return err } if ok := m.cache.Set(key, val, 1); !ok { return ErrorStoreFailed } m.cache.Wait() return nil } func (m *_mem) SetEx(ctx context.Context, key string, value any, duration time.Duration) error { val, err := handleValue(value) if err != nil { return err } if ok := m.cache.SetWithTTL(key, val, 1, duration); !ok { return ErrorStoreFailed } m.cache.Wait() return nil } func (m *_mem) Sets(ctx context.Context, vm map[string]any) error { for key, value := range vm { val, err := handleValue(value) if err != nil { return err } if ok := m.cache.Set(key, val, 1); !ok { return ErrorStoreFailed } } m.cache.Wait() return nil }