Skip to content

Commit a785a81

Browse files
authored
LocalCache: Support ttl per key (#55)
1 parent bab2620 commit a785a81

File tree

6 files changed

+52
-29
lines changed

6 files changed

+52
-29
lines changed

pkg/zcache/combined_cache_test.go

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,7 @@ func (suite *CombinedCacheTestSuite) SetupSuite() {
3535
prefix := os.Getenv("PREFIX")
3636
suite.cacheRemoteBrokenBestEffort, err = NewCombinedCache(
3737
&CombinedConfig{
38-
Local: &LocalConfig{
39-
EvictionInSeconds: 10,
40-
},
38+
Local: &LocalConfig{},
4139
Remote: &RemoteConfig{
4240
Addr: "0.0.0.0",
4341
},
@@ -48,9 +46,7 @@ func (suite *CombinedCacheTestSuite) SetupSuite() {
4846
suite.Nil(err)
4947

5048
suite.cacheOkNotBestEffort, err = NewCombinedCache(&CombinedConfig{
51-
Local: &LocalConfig{
52-
EvictionInSeconds: 10,
53-
},
49+
Local: &LocalConfig{},
5450
Remote: &RemoteConfig{
5551
Addr: mr.Addr(),
5652
},
@@ -62,9 +58,7 @@ func (suite *CombinedCacheTestSuite) SetupSuite() {
6258

6359
suite.cacheRemoteBrokenNotBestEffort, err = NewCombinedCache(
6460
&CombinedConfig{
65-
Local: &LocalConfig{
66-
EvictionInSeconds: 10,
67-
},
61+
Local: &LocalConfig{},
6862
Remote: &RemoteConfig{
6963
Addr: "0.0.0.0",
7064
},

pkg/zcache/config.go

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"github.com/allegro/bigcache/v3"
55
"github.com/go-redis/redis/v8"
66
"go.uber.org/zap"
7-
"math"
87
"time"
98
)
109

@@ -27,9 +26,8 @@ type RemoteConfig struct {
2726
}
2827

2928
type LocalConfig struct {
30-
EvictionInSeconds int
31-
Prefix string
32-
Logger *zap.Logger
29+
Prefix string
30+
Logger *zap.Logger
3331
}
3432

3533
func (c *RemoteConfig) ToRedisConfig() *redis.Options {
@@ -51,12 +49,8 @@ func (c *RemoteConfig) ToRedisConfig() *redis.Options {
5149
}
5250

5351
func (c *LocalConfig) ToBigCacheConfig() bigcache.Config {
54-
eviction := time.Duration(c.EvictionInSeconds) * time.Second
55-
if c.EvictionInSeconds < 0 {
56-
eviction = time.Duration(math.MaxInt64)
57-
}
58-
59-
return bigcache.DefaultConfig(eviction)
52+
evictionTime := time.Duration(100*365*24) * time.Hour // 100 years
53+
return bigcache.DefaultConfig(evictionTime)
6054
}
6155

6256
type CombinedConfig struct {

pkg/zcache/local_cache.go

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,22 @@ import (
1111
"time"
1212
)
1313

14+
type CacheItem struct {
15+
Value []byte `json:"value"`
16+
ExpiresAt int64 `json:"expires_at"`
17+
}
18+
19+
func NewCacheItem(value []byte, ttl time.Duration) CacheItem {
20+
return CacheItem{
21+
Value: value,
22+
ExpiresAt: time.Now().Add(ttl).Unix(),
23+
}
24+
}
25+
26+
func (item CacheItem) IsExpired() bool {
27+
return time.Now().Unix() > item.ExpiresAt
28+
}
29+
1430
type LocalCache interface {
1531
ZCache
1632
}
@@ -23,17 +39,24 @@ type localCache struct {
2339
appName string
2440
}
2541

26-
func (c *localCache) Set(_ context.Context, key string, value interface{}, _ time.Duration) error {
42+
func (c *localCache) Set(_ context.Context, key string, value interface{}, ttl time.Duration) error {
2743
realKey := getKeyWithPrefix(c.prefix, key)
2844

29-
c.logger.Sugar().Debugf("set key on local cache, fullKey: [%s], value: [%v]", realKey, value)
30-
val, err := json.Marshal(value)
45+
b, err := json.Marshal(value)
3146
if err != nil {
47+
c.logger.Sugar().Errorf("error marshalling cache item value, key: [%s], err: [%s]", realKey, err)
3248
return err
3349
}
3450

35-
err = c.client.Set(realKey, val)
51+
cacheItem := NewCacheItem(b, ttl)
52+
itemBytes, err := json.Marshal(cacheItem)
3653
if err != nil {
54+
c.logger.Sugar().Errorf("error marshalling cache item, key: [%s], err: [%s]", realKey, err)
55+
return err
56+
}
57+
58+
c.logger.Sugar().Debugf("set key on local cache with TTL, key: [%s], value: [%v], ttl: [%v]", realKey, value, ttl)
59+
if err = c.client.Set(realKey, itemBytes); err != nil {
3760
c.logger.Sugar().Errorf("error setting new key on local cache, fullKey: [%s], err: [%s]", realKey, err)
3861
}
3962

@@ -55,7 +78,21 @@ func (c *localCache) Get(_ context.Context, key string, data interface{}) error
5578

5679
return err
5780
}
58-
return json.Unmarshal(val, &data)
81+
82+
var cachedItem CacheItem
83+
if err := json.Unmarshal(val, &cachedItem); err != nil {
84+
c.logger.Sugar().Errorf("error unmarshalling cache item, key: [%s], err: [%s]", realKey, err)
85+
return err
86+
}
87+
88+
if cachedItem.IsExpired() {
89+
c.logger.Sugar().Debugf("key expired on local cache, key: [%s]", realKey)
90+
_ = c.client.Delete(realKey)
91+
return errors.New("cache item expired")
92+
}
93+
94+
c.logger.Sugar().Debugf("key retrieved from local cache, key: [%s]", realKey)
95+
return json.Unmarshal(cachedItem.Value, data)
5996
}
6097

6198
func (c *localCache) Delete(_ context.Context, key string) error {

pkg/zcache/local_cache_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,7 @@ func (suite *LocalCacheTestSuite) SetupSuite() {
2020
prefix := os.Getenv("PREFIX")
2121
var err error
2222
config := LocalConfig{
23-
EvictionInSeconds: 100000,
24-
Prefix: prefix,
23+
Prefix: prefix,
2524
}
2625
suite.cache, err = NewLocalCache(&config)
2726
suite.Nil(err)

pkg/zcache/readme.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ func main() {
6060

6161
```go
6262
func main() {
63-
config := zcache.LocalConfig{Eviction: 12}
63+
config := zcache.LocalConfig{}
6464
cache, err := zcache.NewLocalCache(config)
6565
if err != nil {
6666
// Handle error
@@ -82,7 +82,7 @@ func main() {
8282

8383
```go
8484
func main() {
85-
localConfig := zcache.LocalConfig{Eviction: 12}
85+
localConfig := zcache.LocalConfig{}
8686
remoteConfig := zcache.RemoteConfig{Addr: "localhost:6379"}
8787
config := zcache.CombinedConfig{Local: localConfig, Remote: remoteConfig, isRemoteBestEffort: false}
8888
cache, err := zcache.NewCombinedCache(config)

pkg/zcache/zcache.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,6 @@ func NewCombinedCache(combinedConfig *CombinedConfig) (CombinedCache, error) {
6969
}
7070

7171
// Set global configs on local cache config
72-
localCacheConfig.EvictionInSeconds = combinedConfig.GlobalTtlSeconds
7372
localCacheConfig.Prefix = combinedConfig.GlobalPrefix
7473
localCacheConfig.Logger = combinedConfig.GlobalLogger
7574

0 commit comments

Comments
 (0)