Skip to content

Commit 4546900

Browse files
authored
LocalCache: Implement non-expiring cache with negative TTL (#56)
* LocalCache: Implement non-expiring cache with negative TTL * Change NewCacheItem to support negative expiresAt * Set neverExpires as const * tests
1 parent 148da40 commit 4546900

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

pkg/zcache/local_cache.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,31 @@ import (
1111
"time"
1212
)
1313

14+
const (
15+
neverExpires = -1
16+
)
17+
1418
type CacheItem struct {
1519
Value []byte `json:"value"`
1620
ExpiresAt int64 `json:"expires_at"`
1721
}
1822

1923
func NewCacheItem(value []byte, ttl time.Duration) CacheItem {
24+
expiresAt := time.Now().Add(ttl).Unix()
25+
if ttl < 0 {
26+
expiresAt = neverExpires
27+
}
28+
2029
return CacheItem{
2130
Value: value,
22-
ExpiresAt: time.Now().Add(ttl).Unix(),
31+
ExpiresAt: expiresAt,
2332
}
2433
}
2534

2635
func (item CacheItem) IsExpired() bool {
36+
if item.ExpiresAt < 0 {
37+
return false
38+
}
2739
return time.Now().Unix() > item.ExpiresAt
2840
}
2941

pkg/zcache/local_cache_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"github.com/stretchr/testify/suite"
66
"os"
77
"testing"
8+
"time"
89
)
910

1011
func TestLocalCacheTestSuite(t *testing.T) {
@@ -53,3 +54,19 @@ func (suite *LocalCacheTestSuite) TestDelete() {
5354
err = suite.cache.Get(ctx, key, new(string))
5455
suite.Error(err)
5556
}
57+
58+
func (suite *LocalCacheTestSuite) TestCacheItemExpiration() {
59+
item := NewCacheItem([]byte("testValue"), 1*time.Second)
60+
suite.False(item.IsExpired(), "CacheItem should not be expired right after creation")
61+
time.Sleep(2 * time.Second)
62+
63+
suite.True(item.IsExpired(), "CacheItem should be expired after its TTL")
64+
}
65+
66+
func (suite *LocalCacheTestSuite) TestCacheItemNeverExpires() {
67+
item := NewCacheItem([]byte("testValue"), -1)
68+
suite.False(item.IsExpired(), "CacheItem with negative TTL should never expire")
69+
time.Sleep(2 * time.Second)
70+
71+
suite.False(item.IsExpired(), "CacheItem with negative TTL should never expire, even after some time")
72+
}

0 commit comments

Comments
 (0)