Skip to content

Commit

Permalink
Merge pull request #7556 from vmg/vmg/cache-init
Browse files Browse the repository at this point in the history
cache: handle all possible initialization cases
  • Loading branch information
deepthi authored Feb 26, 2021
2 parents 5dee786 + a5e24b3 commit f47f73c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
8 changes: 7 additions & 1 deletion go/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,21 @@ type cachedObject interface {
// implementation.
func NewDefaultCacheImpl(cfg *Config) Cache {
switch {
case cfg == nil || (cfg.MaxEntries == 0 && cfg.MaxMemoryUsage == 0):
case cfg == nil:
return &nullCache{}

case cfg.LFU:
if cfg.MaxEntries == 0 || cfg.MaxMemoryUsage == 0 {
return &nullCache{}
}
return NewRistrettoCache(cfg.MaxEntries, cfg.MaxMemoryUsage, func(val interface{}) int64 {
return val.(cachedObject).CachedSize(true)
})

default:
if cfg.MaxEntries == 0 {
return &nullCache{}
}
return NewLRUCache(cfg.MaxEntries, func(_ interface{}) int64 {
return 1
})
Expand Down
47 changes: 47 additions & 0 deletions go/cache/cache_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package cache

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"

"vitess.io/vitess/go/cache/ristretto"
)

func TestNewDefaultCacheImpl(t *testing.T) {
assertNullCache := func(t *testing.T, cache Cache) {
_, ok := cache.(*nullCache)
require.True(t, ok)
}

assertLFUCache := func(t *testing.T, cache Cache) {
_, ok := cache.(*ristretto.Cache)
require.True(t, ok)
}

assertLRUCache := func(t *testing.T, cache Cache) {
_, ok := cache.(*LRUCache)
require.True(t, ok)
}

tests := []struct {
cfg *Config
verify func(t *testing.T, cache Cache)
}{
{&Config{MaxEntries: 0, MaxMemoryUsage: 0, LFU: false}, assertNullCache},
{&Config{MaxEntries: 0, MaxMemoryUsage: 0, LFU: true}, assertNullCache},
{&Config{MaxEntries: 100, MaxMemoryUsage: 0, LFU: false}, assertLRUCache},
{&Config{MaxEntries: 0, MaxMemoryUsage: 1000, LFU: false}, assertNullCache},
{&Config{MaxEntries: 100, MaxMemoryUsage: 1000, LFU: false}, assertLRUCache},
{&Config{MaxEntries: 100, MaxMemoryUsage: 0, LFU: true}, assertNullCache},
{&Config{MaxEntries: 100, MaxMemoryUsage: 1000, LFU: true}, assertLFUCache},
{&Config{MaxEntries: 0, MaxMemoryUsage: 1000, LFU: true}, assertNullCache},
}
for _, tt := range tests {
t.Run(fmt.Sprintf("%d.%d.%v", tt.cfg.MaxEntries, tt.cfg.MaxMemoryUsage, tt.cfg.LFU), func(t *testing.T) {
cache := NewDefaultCacheImpl(tt.cfg)
tt.verify(t, cache)
})
}
}

0 comments on commit f47f73c

Please sign in to comment.