From f0d58cdda7280b0b046985039a7ac55135f074a7 Mon Sep 17 00:00:00 2001 From: Darko Draskovic Date: Thu, 28 Nov 2024 18:19:12 +0000 Subject: [PATCH] fix: [CODE-2833]: Ignore Redis related cache errors when get/set key (#3059) * Ignore Redis related cache errors when get/set key --- cache/redis_cache.go | 13 +++++++++---- git/api/last_commit_cache.go | 9 ++++++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/cache/redis_cache.go b/cache/redis_cache.go index d0b4a5bd2..d91914fdf 100644 --- a/cache/redis_cache.go +++ b/cache/redis_cache.go @@ -23,6 +23,8 @@ import ( "github.com/go-redis/redis/v8" ) +type LogErrFn func(context.Context, error) + type Redis[K any, V any] struct { client redis.UniversalClient duration time.Duration @@ -31,6 +33,7 @@ type Redis[K any, V any] struct { codec Codec[V] countHit int64 countMiss int64 + logErrFn LogErrFn } type Encoder[V any] interface { @@ -52,6 +55,7 @@ func NewRedis[K any, V any]( keyEncoder func(K) string, codec Codec[V], duration time.Duration, + logErrFn LogErrFn, ) *Redis[K, V] { return &Redis[K, V]{ client: client, @@ -61,6 +65,7 @@ func NewRedis[K any, V any]( codec: codec, countHit: 0, countMiss: 0, + logErrFn: logErrFn, } } @@ -82,8 +87,8 @@ func (c *Redis[K, V]) Get(ctx context.Context, key K) (V, error) { c.countHit++ return value, nil } - } else if !errors.Is(err, redis.Nil) { - return nothing, err + } else if !errors.Is(err, redis.Nil) && c.logErrFn != nil { + c.logErrFn(ctx, err) } c.countMiss++ @@ -94,8 +99,8 @@ func (c *Redis[K, V]) Get(ctx context.Context, key K) (V, error) { } err = c.client.Set(ctx, strKey, c.codec.Encode(item), c.duration).Err() - if err != nil { - return nothing, err + if err != nil && c.logErrFn != nil { + c.logErrFn(ctx, err) } return item, nil diff --git a/git/api/last_commit_cache.go b/git/api/last_commit_cache.go index e7cc66582..55e29fcdf 100644 --- a/git/api/last_commit_cache.go +++ b/git/api/last_commit_cache.go @@ -28,6 +28,7 @@ import ( "github.com/harness/gitness/git/sha" "github.com/go-redis/redis/v8" + "github.com/rs/zerolog/log" ) func NewInMemoryLastCommitCache( @@ -38,6 +39,10 @@ func NewInMemoryLastCommitCache( cacheDuration) } +func logCacheErrFn(ctx context.Context, err error) { + log.Ctx(ctx).Warn().Msgf("failed to use cache: %s", err.Error()) +} + func NewRedisLastCommitCache( redisClient redis.UniversalClient, cacheDuration time.Duration, @@ -55,7 +60,9 @@ func NewRedisLastCommitCache( return "last_commit:" + hex.EncodeToString(h.Sum(nil)) }, commitValueCodec{}, - cacheDuration), nil + cacheDuration, + logCacheErrFn, + ), nil } func NoLastCommitCache() cache.Cache[CommitEntryKey, *Commit] {