From 82ce598231ba17c595e8694a7f7c91aa58156f47 Mon Sep 17 00:00:00 2001 From: Damiano Petrungaro Date: Thu, 9 Jun 2022 19:50:52 +0200 Subject: [PATCH] feat: introduce default ttl on multi level cache --- multilevel.go | 30 +++++++++++++++++++++++++----- multilevel_test.go | 2 +- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/multilevel.go b/multilevel.go index 9512617..0ee6a7f 100644 --- a/multilevel.go +++ b/multilevel.go @@ -5,17 +5,31 @@ import ( "time" ) +var ( + // DefaultMultiLevelExpiration is a constant used to mark an item to expire to the default value passed to a MultiLevel + DefaultMultiLevelExpiration = time.Duration(-1) +) + // MultiLevel is a Cache implementation which allow a multi level usage cache type MultiLevel[K comparable, V any] struct { - local *InMem[K, V] - remote Cache[K, V] + local *InMem[K, V] + defaultLocalTTL time.Duration + remote Cache[K, V] + defaultRemoteTTL time.Duration } // NewMultiLevel returns a MultiLevel -func NewMultiLevel[K comparable, V any](local *InMem[K, V], remote Cache[K, V]) *MultiLevel[K, V] { +func NewMultiLevel[K comparable, V any]( + local *InMem[K, V], + defaultLocalTTL time.Duration, + remote Cache[K, V], + defaultRemoteTTL time.Duration, +) *MultiLevel[K, V] { return &MultiLevel[K, V]{ - local: local, - remote: remote, + local: local, + defaultLocalTTL: defaultLocalTTL, + remote: remote, + defaultRemoteTTL: defaultRemoteTTL, } } @@ -30,10 +44,16 @@ func (m *MultiLevel[K, V]) Get(ctx context.Context, k K) (V, error) { // Set traverse all the caches, if all of them fail it returns a generic ErrNotSet func (m *MultiLevel[K, V]) Set(ctx context.Context, k K, v V, ttl time.Duration) error { + if ttl == DefaultMultiLevelExpiration { + ttl = m.defaultRemoteTTL + } if err := m.remote.Set(ctx, k, v, ttl); err != nil { return err } + if ttl == DefaultMultiLevelExpiration { + ttl = m.defaultLocalTTL + } // in memory won't fail apart from having a ctx done. // passing a background to prevent it _ = m.local.Set(context.Background(), k, v, ttl) diff --git a/multilevel_test.go b/multilevel_test.go index d00d327..c953730 100644 --- a/multilevel_test.go +++ b/multilevel_test.go @@ -108,7 +108,7 @@ func newMultiLevel(t *testing.T) *MultiLevel[string, string] { t.Helper() inmem1 := NewInMemory[string, string](time.Second, 5) inmem2 := NewInMemory[string, string](time.Second, 5) - multiLlv := NewMultiLevel[string, string](inmem1, inmem2) + multiLlv := NewMultiLevel[string, string](inmem1, 10*time.Second, inmem2, 10*time.Second) t.Cleanup(func() { if err := inmem1.Close(); err != nil { t.Errorf("could not close inmem1 level: %s", err)