Skip to content

Commit

Permalink
feat(cache): Adding extendOnHit
Browse files Browse the repository at this point in the history
Signed-off-by: Vincent Boutour <[email protected]>
  • Loading branch information
ViBiOh committed Aug 12, 2023
1 parent d6c5719 commit 70edfb9
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
9 changes: 8 additions & 1 deletion pkg/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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] {
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
}

Expand Down
3 changes: 3 additions & 0 deletions pkg/cache/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions pkg/cache/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -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])
}

Expand Down Expand Up @@ -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])
}

Expand Down

0 comments on commit 70edfb9

Please sign in to comment.