Skip to content

Commit

Permalink
feat: introduce default ttl on multi level cache
Browse files Browse the repository at this point in the history
  • Loading branch information
damianopetrungaro committed Jun 9, 2022
1 parent 22db0c0 commit 82ce598
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
30 changes: 25 additions & 5 deletions multilevel.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}

Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion multilevel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 82ce598

Please sign in to comment.