From 70edfb9a87c4dc57d284bfd51d2a5bddb9e59db9 Mon Sep 17 00:00:00 2001 From: Vincent Boutour Date: Sat, 12 Aug 2023 18:20:32 +0200 Subject: [PATCH] feat(cache): Adding extendOnHit Signed-off-by: Vincent Boutour --- pkg/cache/cache.go | 9 ++++++++- pkg/cache/cache_test.go | 3 +++ pkg/cache/list.go | 4 ++-- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index 8bb194ae..fef6f96f 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -43,6 +43,7 @@ type App[K comparable, V any] struct { onMissMany fetchMany[K, V] ttl time.Duration concurrency int + extendOnHit bool } func New[K comparable, V any](client RedisClient, toKey func(K) string, onMiss fetch[K, V], tracer trace.Tracer) *App[K, V] { @@ -82,6 +83,12 @@ func (a *App[K, V]) WithTTL(ttl time.Duration) *App[K, V] { return a } +func (a *App[K, V]) WithExtendOnHit() *App[K, V] { + a.extendOnHit = true + + return a +} + func (a *App[K, V]) WithMaxConcurrency(concurrency int) *App[K, V] { a.concurrency = concurrency @@ -176,7 +183,7 @@ func (a *App[K, V]) decode(content []byte) (value V, ok bool, err error) { } func (a *App[K, V]) extendTTL(ctx context.Context, keys ...string) { - if a.write == nil || len(keys) == 0 || a.ttl == 0 { + if a.write == nil || !a.extendOnHit || a.ttl == 0 || len(keys) == 0 { return } diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index f46517b6..d6f3c0a3 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -159,6 +159,9 @@ func TestGet(t *testing.T) { } instance := New(mockRedisClient, strconv.Itoa, testCase.args.onMiss, nil).WithTTL(testCase.args.duration) + if intention == "cached" { + instance = instance.WithExtendOnHit() + } got, gotErr := instance.Get(context.Background(), testCase.args.key) diff --git a/pkg/cache/list.go b/pkg/cache/list.go index 4a25d39b..903e9707 100644 --- a/pkg/cache/list.go +++ b/pkg/cache/list.go @@ -96,7 +96,7 @@ func (a App[K, V]) handleListSingle(ctx context.Context, onMissError func(K, err if ok { output[index] = value - if a.ttl != 0 { + if a.ttl != 0 && a.extendOnHit { extendKeys = append(extendKeys, keys[index]) } @@ -131,7 +131,7 @@ func (a App[K, V]) handleListMany(ctx context.Context, items []K, keys, values [ if value, ok, err := a.decode([]byte(values[index])); ok { output[index] = value - if a.ttl != 0 { + if a.ttl != 0 && a.extendOnHit { extendKeys = append(extendKeys, keys[index]) }