diff --git a/cache/cache.go b/cache/cache.go index 60df253..b2e1d12 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -1,6 +1,8 @@ package cache -import "time" +import ( + "time" +) // Cache interface defines the methods for a cache implementation. type Cache[K comparable] interface { @@ -13,3 +15,45 @@ type Cache[K comparable] interface { // Delete removes a value from the cache by key. Delete(key K) } + +// LRUCache interface defines the methods for a Least Recently Used (LRU) cache implementation. +type LRUCache[K comparable, V any] interface { + // Get retrieves a value from the cache by key. + Get(key K) (value V, found bool) + + // Put adds a value to the cache with the specified key and expiration time. + Put(key K, value V, expiration time.Duration) + + // Delete removes a value from the cache by key. + Delete(key K) +} + +// EvictionReason represents the reason for evicting an item from the cache. +type EvictionReason string + +const ( + // EvictCapacity indicates that the item was evicted due to reaching the maximum capacity of the cache. + EvictCapacity EvictionReason = "capacity" + // EvictTTL indicates that the item was evicted due to exceeding its time-to-live (TTL). + EvictTTL EvictionReason = "TTL" + // EvictReplace indicates that the item was evicted due to being replaced by a new value. + EvictReplace EvictionReason = "replace" + // EvictDelete indicates that the item was evicted due to being explicitly deleted from the cache. + EvictDelete EvictionReason = "delete" + // EvictPurge indicates that the item was evicted due to a purge operation on the cache. + EvictPurge EvictionReason = "purge" +) + +// Options struct defines the configuration options for the LRU cache. +type Options[K comparable, V any] struct { + // MaxSize defines the maximum number of items the cache can hold. + MaxSize int // 0 = unlimited count + // MaxBytes defines the maximum bytes the cache can hold. + MaxBytes int64 // 0 = unlimited bytes + // SizeOf is a function that calculates the byte usage of the value + SizeOf func(key K, value V) int64 // required if MaxBytes > 0 + // OnEvict is a callback function that is called when an item is evicted from the cache. + OnEvict func(key K, value V, reason EvictionReason) + // SweepInterval defines the interval at which the cache will sweep for expired items. + SweepInterval time.Duration +} diff --git a/cache/lru.go b/cache/lru.go new file mode 100644 index 0000000..bf28f48 --- /dev/null +++ b/cache/lru.go @@ -0,0 +1,235 @@ +package cache + +import ( + "context" + "fmt" + "math" + "sync" + "sync/atomic" + "time" + + hashicorp "github.com/hashicorp/golang-lru/v2" +) + +const ( + // DefaultMemoryCacheSweepInterval is the default interval for sweeping expired items from the cache. + DefaultMemoryCacheSweepInterval = time.Minute * 5 +) + +type lruCache[V any] struct { + data V + cacheDuration time.Duration + startTime time.Time + memorySize int64 + evictionReason EvictionReason +} + +type evictionEvent[K comparable, V any] struct { + key K + value *lruCache[V] +} + +// NewLRUCache creates a new lruCache entry with the given value and TTL +func NewLRUCache[V any](data V, cacheDuration time.Duration) *lruCache[V] { + lc := &lruCache[V]{data: data, cacheDuration: cacheDuration, startTime: time.Now(), evictionReason: EvictCapacity} + + return lc +} + +// IsExpired checks if the cache entry's TTL has elapsed. +func (l *lruCache[V]) IsExpired() bool { + if l.cacheDuration <= 0 { + return false + } + return time.Now().After(l.startTime.Add(l.cacheDuration)) +} + +// LRUStore is a thread-safe LRU cache implementation that supports expiration and memory size limits. +type LRUStore[K comparable, V any] struct { + store *hashicorp.Cache[K, *lruCache[V]] + // maximumMemory Maximum Memory byte size of the cache + maximumMemory int64 // 0 = unlimited bytes + // sizeOf computes memory usage for each key/value entry. + sizeOf func(key K, value V) int64 + // sweepInterval controls how often expired entries are removed. + sweepInterval time.Duration + // onEvict callback when an entry is evicted. + OnEvict func(key K, value V, reason EvictionReason) + // currentMemory Memory used by the cache + currentMemory int64 + // mu mutex for synchronizing access to the cache + mu sync.Mutex + // pendingEvicts holds the list of eviction events to be processed after releasing the lock + pendingEvicts []evictionEvent[K, V] +} + +// NewLRUStore creates a new LRUStore with the given options. +func NewLRUStore[K comparable, V any](ctx context.Context, opts Options[K, V]) (*LRUStore[K, V], error) { + if opts.MaxSize <= 0 { + // 0 = unlimited count: use the largest possible size so that only + // the byte budget (MaxBytes) drives eviction. + opts.MaxSize = math.MaxInt + } + + if opts.MaxBytes < 0 { + opts.MaxBytes = 0 + } + + if opts.MaxBytes > 0 && opts.SizeOf == nil { + return nil, fmt.Errorf("SizeOf function must be provided when MaxBytes is greater than 0") + } + + if opts.SweepInterval <= 0 { + opts.SweepInterval = DefaultMemoryCacheSweepInterval + } + + lc := &LRUStore[K, V]{ + maximumMemory: opts.MaxBytes, + sizeOf: opts.SizeOf, + sweepInterval: opts.SweepInterval, + OnEvict: opts.OnEvict, + currentMemory: 0, + } + + lru, err := hashicorp.NewWithEvict(opts.MaxSize, func(key K, value *lruCache[V]) { + if value != nil { + atomic.AddInt64(&lc.currentMemory, -value.memorySize) + } + if lc.OnEvict != nil && value != nil { + lc.pendingEvicts = append(lc.pendingEvicts, evictionEvent[K, V]{ + key: key, + value: value, + }) + } + }) + + if err != nil { + return nil, err + } + + lc.store = lru + + go lc.run(ctx) + + return lc, nil + +} + +// run starts a goroutine that periodically sweeps the cache for expired items. +func (l *LRUStore[K, V]) run(ctx context.Context) { + ticker := time.NewTicker(l.sweepInterval) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + l.mu.Lock() + for _, key := range l.store.Keys() { + val, ok := l.store.Peek(key) + if ok && val != nil && val.IsExpired() { + val.evictionReason = EvictTTL + l.store.Remove(key) + } + } + l.executeEviction() + } + } +} + +// Get retrieves a value from the cache by key. +func (l *LRUStore[K, V]) Get(key K) (value V, found bool) { + l.mu.Lock() + defer l.executeEviction() + lc, ok := l.store.Get(key) + + if !ok { + return + } + + if lc.IsExpired() { + lc.evictionReason = EvictTTL + l.store.Remove(key) + return + } + + return lc.data, true +} + +// Put adds a value to the cache with the specified key and expiration time. +func (l *LRUStore[K, V]) Put(key K, value V, cacheDuration time.Duration) { + l.mu.Lock() + defer l.executeEviction() + lc := NewLRUCache(value, cacheDuration) + + if l.sizeOf != nil { + lc.memorySize = l.sizeOf(key, value) + } + + if l.maximumMemory != 0 && lc.memorySize > l.maximumMemory { + return + } + + if prevValue, ok := l.store.Peek(key); ok && prevValue != nil { + prevValue.evictionReason = EvictReplace + l.store.Remove(key) + } + + if l.maximumMemory != 0 { + for atomic.LoadInt64(&l.currentMemory)+lc.memorySize > l.maximumMemory { + _, _, ok := l.store.RemoveOldest() + if !ok { + // If there is nothing left to evict, refuse the write. + return + } + } + } + + // track bytes whenever sizeOf is provided, even if maximumMemory is 0. + if l.sizeOf != nil { + atomic.AddInt64(&l.currentMemory, lc.memorySize) + } + + l.store.Add(key, lc) + +} + +// Delete removes a value from the cache by key. +func (l *LRUStore[K, V]) Delete(key K) { + l.mu.Lock() + defer l.executeEviction() + if val, ok := l.store.Peek(key); ok && val != nil { + val.evictionReason = EvictDelete + l.store.Remove(key) + } +} + +// CurrentBytes returns the current memory usage of the cache in bytes. +func (l *LRUStore[K, V]) CurrentBytes() int64 { + return atomic.LoadInt64(&l.currentMemory) +} + +// Purge removes all items from the cache. +func (l *LRUStore[K, V]) Purge() { + l.mu.Lock() + defer l.executeEviction() + for _, key := range l.store.Keys() { + if val, ok := l.store.Peek(key); ok && val != nil { + val.evictionReason = EvictPurge + } + } + l.store.Purge() +} + +func (l *LRUStore[K, V]) executeEviction() { + evicts := l.pendingEvicts + l.pendingEvicts = nil + l.mu.Unlock() + + for _, evict := range evicts { + if l.OnEvict != nil && evict.value != nil { + l.OnEvict(evict.key, evict.value.data, evict.value.evictionReason) + } + } +} diff --git a/cache/lru_test.go b/cache/lru_test.go new file mode 100644 index 0000000..5c09780 --- /dev/null +++ b/cache/lru_test.go @@ -0,0 +1,314 @@ +package cache + +import ( + "context" + "strconv" + "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("Test LRU cache utils", func() { + It("should return false for isExpired() when duration is zero", func() { + c := NewLRUCache("test", 0) + Expect(c.IsExpired()).Should(BeFalse()) + }) + + It("should return false for isExpired() before duration elapses", func() { + c := NewLRUCache("test", 10*time.Hour) + Expect(c.IsExpired()).Should(BeFalse()) + }) + + It("should return true for isExpired() after duration elapses", func() { + c := NewLRUCache("test", time.Millisecond*100) + time.Sleep(200 * time.Millisecond) + Expect(c.IsExpired()).Should(BeTrue()) + }) + + It("test lru cache store basic put and get", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{}) + Expect(err).Should(BeNil()) + + store.Put("test", "test data", time.Second*2) + store.Put("test2", "test data", 0) + store.Put("test3", "test data", -1) + time.Sleep(3 * time.Second) + + value, found := store.Get("test") + Expect(value).Should(BeZero()) + Expect(found).Should(BeFalse()) + + value, found = store.Get("test2") + Expect(value).Should(Equal("test data")) + Expect(found).Should(BeTrue()) + + value, found = store.Get("test3") + Expect(value).Should(Equal("test data")) + Expect(found).Should(BeTrue()) + }) + + It("test lru cache store delete key", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{}) + Expect(err).Should(BeNil()) + + store.Put("test", "test data", time.Minute*2) + store.Delete("test") + value, found := store.Get("test") + Expect(value).Should(BeZero()) + Expect(found).Should(BeFalse()) + }) + + It("test lru cache store with multiple keys", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, int](ctx, Options[string, int]{}) + Expect(err).Should(BeNil()) + + for i := 0; i < 100; i++ { + key := "key-" + strconv.Itoa(i) + store.Put(key, i, 0) + } + + for i := 0; i < 100; i++ { + key := "key-" + strconv.Itoa(i) + value, found := store.Get(key) + Expect(found).Should(BeTrue()) + Expect(value).Should(Equal(i)) + } + }) + + It("treats zero max size as unlimited", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{MaxSize: 0}) + Expect(err).Should(BeNil()) + + for i := 0; i < 1001; i++ { + store.Put(strconv.Itoa(i), "value", 0) + } + + for i := 0; i < 1001; i++ { + value, found := store.Get(strconv.Itoa(i)) + Expect(found).Should(BeTrue()) + Expect(value).Should(Equal("value")) + } + }) + + It("treats zero max bytes as unlimited", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{MaxBytes: 0, SizeOf: func(_ string, value string) int64 { + return int64(len(value)) + }}) + Expect(err).Should(BeNil()) + + store.Put("first", "value", 0) + store.Put("second", "value2", 0) + + value, found := store.Get("first") + Expect(found).Should(BeTrue()) + Expect(value).Should(Equal("value")) + + value, found = store.Get("second") + Expect(found).Should(BeTrue()) + Expect(value).Should(Equal("value2")) + }) + + It("test lru cache store overwrite value", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{}) + Expect(err).Should(BeNil()) + + store.Put("rw", "v1", time.Second) + value, found := store.Get("rw") + Expect(found).Should(BeTrue()) + Expect(value).Should(Equal("v1")) + + store.Put("rw", "v2", time.Second) + value, found = store.Get("rw") + Expect(found).Should(BeTrue()) + Expect(value).Should(Equal("v2")) + }) + + It("test lru cache store rejects value exceeding max memory", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{ + MaxBytes: 1, + SizeOf: func(_ string, value string) int64 { + return int64(len(value)) + }, + }) + Expect(err).Should(BeNil()) + + store.Put("big", "abc", 0) + value, found := store.Get("big") + Expect(value).Should(BeZero()) + Expect(found).Should(BeFalse()) + }) + + It("test lru cache store evicts oldest entry when memory is full", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{ + MaxBytes: 1, + SizeOf: func(_ string, value string) int64 { + return int64(len(value)) + }, + }) + Expect(err).Should(BeNil()) + + store.Put("first", "a", 0) + value, found := store.Get("first") + Expect(found).Should(BeTrue()) + Expect(value).Should(Equal("a")) + + store.Put("second", "b", 0) + + value, found = store.Get("first") + Expect(found).Should(BeFalse()) + Expect(value).Should(BeZero()) + + value, found = store.Get("second") + Expect(found).Should(BeTrue()) + Expect(value).Should(Equal("b")) + }) + + It("test lru cache store evicts oldest entry when max size is reached", func() { + evicted := make(chan struct { + key string + value string + reason EvictionReason + }, 1) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{ + MaxSize: 1, + OnEvict: func(key string, value string, reason EvictionReason) { + evicted <- struct { + key string + value string + reason EvictionReason + }{key: key, value: value, reason: reason} + }, + }) + Expect(err).Should(BeNil()) + + store.Put("first", "a", 0) + store.Put("second", "b", 0) + + value, found := store.Get("first") + Expect(found).Should(BeFalse()) + Expect(value).Should(BeZero()) + + select { + case evictedItem := <-evicted: + Expect(evictedItem.key).Should(Equal("first")) + Expect(evictedItem.value).Should(Equal("a")) + Expect(evictedItem.reason).Should(Equal(EvictCapacity)) + default: + Fail("expected eviction callback to be invoked") + } + }) + + It("test lru cache store get on missing key", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{}) + Expect(err).Should(BeNil()) + + value, found := store.Get("nonexistent") + Expect(value).Should(BeZero()) + Expect(found).Should(BeFalse()) + }) + + It("test lru cache store context cancellation stops sweep goroutine", func() { + ctx, cancel := context.WithCancel(context.Background()) + store, err := NewLRUStore[string, string](ctx, Options[string, string]{}) + Expect(err).Should(BeNil()) + + store.Put("key", "value", 0) + cancel() + + // After cancellation the store should still serve already-cached data + value, found := store.Get("key") + Expect(found).Should(BeTrue()) + Expect(value).Should(Equal("value")) + }) + + It("purge removes all entries", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{ + MaxBytes: 100, + SizeOf: func(_ string, value string) int64 { return int64(len(value)) }, + }) + Expect(err).Should(BeNil()) + + store.Put("a", "hello", 0) + store.Put("b", "world", 0) + store.Purge() + + _, found := store.Get("a") + Expect(found).Should(BeFalse()) + _, found = store.Get("b") + Expect(found).Should(BeFalse()) + }) + + It("CurrentBytes tracks memory across puts, deletes, and purge", func() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{ + MaxBytes: 100, + SizeOf: func(_ string, value string) int64 { return int64(len(value)) }, + }) + Expect(err).Should(BeNil()) + + Expect(store.CurrentBytes()).Should(BeZero()) + + store.Put("a", "hello", 0) // 5 bytes + Expect(store.CurrentBytes()).Should(Equal(int64(5))) + + store.Put("b", "hi", 0) // 2 bytes + Expect(store.CurrentBytes()).Should(Equal(int64(7))) + + store.Delete("a") + Expect(store.CurrentBytes()).Should(Equal(int64(2))) + + store.Purge() + Expect(store.CurrentBytes()).Should(BeZero()) + }) + + It("sweep goroutine evicts expired entries with EvictTTL reason", func() { + evicted := make(chan EvictionReason, 1) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := NewLRUStore[string, string](ctx, Options[string, string]{ + SweepInterval: 50 * time.Millisecond, + OnEvict: func(_ string, _ string, reason EvictionReason) { + select { + case evicted <- reason: + default: + } + }, + }) + Expect(err).Should(BeNil()) + + store.Put("k", "v", 30*time.Millisecond) + time.Sleep(200 * time.Millisecond) // let sweep fire at least once after TTL expires + + select { + case reason := <-evicted: + Expect(reason).Should(Equal(EvictTTL)) + case <-time.After(time.Second): + Fail("timed out waiting for sweep to evict with EvictTTL") + } + }) +}) diff --git a/go.mod b/go.mod index 98cb5ff..2c26c1a 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/evanphx/json-patch v5.6.0+incompatible github.com/go-stack/stack v1.8.1 github.com/google/go-cmp v0.7.0 + github.com/hashicorp/golang-lru/v2 v2.0.7 github.com/jellydator/ttlcache/v3 v3.0.1 github.com/klauspost/compress v1.17.10 github.com/mitchellh/hashstructure/v2 v2.0.2 diff --git a/go.sum b/go.sum index 71b2ddd..3378a4b 100644 --- a/go.sum +++ b/go.sum @@ -104,6 +104,8 @@ github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4 github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 h1:bkypFPDjIYGfCYD5mRBvpqxfYX1YCS1PXdKYWi8FsN0= github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0/go.mod h1:P+Lt/0by1T8bfcF3z737NnSbmxQAppXMRziHUxPOC8k= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=