eko/gocache

Redis Get silently returns an empty []byte for stored []byte values

butaca opened this issue · 3 comments

butaca commented

The issue is similar to #166 but for Redis with []byte values. When getting a []byte value the cache returns an empty []byte without an error. This is because the Redis implementation always returns strings and fails when trying to convert the value to string. Since it silently fails, it was difficult to debug.

Steps for Reproduction

  1. Set up a cache manager with a Redis store:
redisStore := redis_store.NewRedis(redis.NewClient(&redis.Options{
	Addr: "127.0.0.1:6379",
}))
cacheManager := cache.New[[]byte](redisStore)
  1. Set a []byte value
value := []byte{1, 2, 3, 4}
err := cacheManager.Set(ctx, "key", value, store.WithExpiration(15*time.Second))
if err != nil {
	panic(err)
}
  1. Get the value
cachedValue, err := cacheManager.Get(ctx, "key")
if err != nil {
	panic(err)
}
  1. Check how the returned value has len = 0
fmt.Printf("cached value len: %v\n", len(cachedValue))

Expected behavior:
The returned value is the stored []byte not and empty value

Actual behavior:
It silently returns an empty []byte instead of the stored value

Platforms:
macOS and dockerized Linux from scratch

Versions:
gocache v4.1.3
go 1.21
Redis store v4.2.0
Redis client v9.0.5
Redis server 7.0.12

@eko Maybe we can add a Mashaler and Unmashaler to the cache and allow users to choose whether to use them or not? This will solve the problem of this type mismatch.

update:
The Marshaler package has implemented encapsulation logic for cached data.

Redis cache apparently only supports strings not []byte
Even if implemented encoding.BinaryMarshaller and Unmarshaller it uses only marshaller and never calls unmarshaller thus fails to assert types later in this piece of code

func (c *Cache[T]) Get(ctx context.Context, key any) (T, error) {
	cacheKey := c.getCacheKey(key)

	value, err := c.codec.Get(ctx, cacheKey)
	if err != nil {
		return *new(T), err
	}

	if v, ok := value.(T); ok { // value is always string for redis
		return v, nil
	}

	return *new(T), nil // returns nil, nil or empty, nil for any non string type
}

And with interface of codec that doesn't receive and type information in parameters it's not really possible to properly assert anything unless interface is changed to allow this:
err := c.codec.Get(ctx, cacheKey, &value)
this way type information can be passed down into redis store to be handled properly on that level