cache icon indicating copy to clipboard operation
cache copied to clipboard

Crashed if tiny lfu size is 1 or 2

Open haunt98 opened this issue 2 years ago • 0 comments

My code goes like:

type WrapCache struct {
	internalCache *cache.Cache
}

func NewWrapCache(
	client redis.UniversalClient,
	size int,
	localExpired time.Duration,
) *WrapCache {
	internalCache := cache.New(&cache.Options{
		Redis:      client,
		LocalCache: cache.NewTinyLFU(size, localExpired),
		Marshal:    json.Marshal,
		Unmarshal:  json.Unmarshal,
	})

	return &WrapCache{
		internalCache: internalCache,
	}
}

func (c *WrapCache) GetJSON(ctx context.Context, key string, value any) error {
	if err := c.internalCache.Get(ctx, key, value); err != nil {
		// Treat err cache miss as redis nil because higher layer only care about redis error
		if errors.Is(err, cache.ErrCacheMiss) {
			return errors.Join(err, redis.Nil)
		}

		return fmt.Errorf("internal cache: failed to get: %w", err)
	}

	return nil
}

When I try to use tiny lfu size 1, it's panic when I try to get.

panic: runtime error: index out of range [0] with length 0

goroutine 1 [running]:
github.com/vmihailenco/go-tinylfu.nvec.inc(...)
        /Users/anon/go/pkg/mod/github.com/vmihailenco/[email protected]/cm4.go:72
github.com/vmihailenco/go-tinylfu.(*cm4).add(...)
        /Users/anon/go/pkg/mod/github.com/vmihailenco/[email protected]/cm4.go:33
github.com/vmihailenco/go-tinylfu.(*T).Get(0x1400043e240, {0x100adfcd1, 0x16})
        /Users/anon/go/pkg/mod/github.com/vmihailenco/[email protected]/tinylfu.go:89 +0x36c
github.com/go-redis/cache/v9.(*TinyLFU).Get(0x14000190390?, {0x100adfcd1?, 0x28?})
        /Users/anon/go/pkg/mod/github.com/go-redis/cache/[email protected]/local.go:67 +0xc8
github.com/go-redis/cache/v9.(*Cache).getBytes(0x1400043e2c0, {0x100d7fcb0, 0x10131f0e0}, {0x100adfcd1, 0x16}, 0x0)
        /Users/anon/go/pkg/mod/github.com/go-redis/cache/[email protected]/cache.go:219 +0x5c
github.com/go-redis/cache/v9.(*Cache).get(0x1400043e2c0, {0x100d7fcb0?, 0x10131f0e0?}, {0x100adfcd1?, 0x8?}, {0x100ca4d80, 0x101321a40}, 0x0?)
        /Users/anon/go/pkg/mod/github.com/go-redis/cache/[email protected]/cache.go:210 +0x38
github.com/go-redis/cache/v9.(*Cache).Get(...)
        /Users/anon/go/pkg/mod/github.com/go-redis/cache/[email protected]/cache.go:194

Not panic if size is >= 3. Is there a doc about this behaviour?

haunt98 avatar Jan 15 '24 04:01 haunt98