Repository navigation
Feat: Introduce LRU cache. #138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
43158d2
9d0bd22
d60c329
b539a09
b761f7f
4bdf3b1
ed4a321
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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] { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit (comment cleanup): please use a normal Go doc, e.g. // NewLRUCache creates an LRU cache entry with the given value and TTL. |
||
| 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 { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit (comment cleanup): godoc name does not match the method. Please use: // IsExpired reports whether the cache entry's TTL has elapsed. |
||
| 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") | ||
| } | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If MaxBytes is set and SizeOf is nil we silently count everything as 0, so the byte cap does nothing. I'd rather return an error here. SizeOf should be required when MaxBytes > 0.
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This looks good now. Constructor errors when MaxBytes is set and SizeOf is missing. |
||
|
|
||
| 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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this has the same race we fixed on the TTL store. If a Put replaces this key between Peek and Remove, we delete the new value. Can we hold the lock across the expire check and remove, or only remove if the peeked entry is still the current one?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here it would be better to use the lock since for checking the previous value, we would again have to
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is addressed. Sweep now holds the lock across the expire check and remove, so a concurrent Put cannot get wiped. |
||
| } | ||
| } | ||
| 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() { | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||
| lc.evictionReason = EvictTTL | ||
| l.store.Remove(key) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same concern here. Get then Remove is not atomic with Put, so a refresh can get wiped.
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is addressed. Get now holds the lock for the expire check and remove. |
||
| 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) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: Overwriting an existing key invokes Prompt for AI agents
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Introduced
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||
| l.mu.Lock() | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Put holds mu while OnEvict runs, but Get, Delete, and sweep don't take mu at all. If OnEvict calls Put we can deadlock on this path, and byte accounting can still race on the others. Can we lock all mutating paths the same way and fire OnEvict after unlocking?
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is addressed in f200364. All mutating paths take the lock, and OnEvict runs after unlock via executeEviction. |
||
| 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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When we Remove before re-adding, OnEvict fires as capacity even though this is just an overwrite. Delete and Purge will look like capacity evictions too, and that will mess up helm metrics. Maybe skip OnEvict for explicit replace/delete, or add a distinct reason.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The hashicorp-lru always fires the
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added the |
||
| } | ||
|
|
||
| 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 { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit (comment cleanup): this comment only restates the next few lines. Prefer deleting it, or keep a short why note if needed (e.g. that we track bytes whenever |
||
| 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) | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit:
DefaultLRUCacheMemory/DefaultLRUCacheSizeare unused (nothing in this repo or the consumer PRs references them; kubevela hardcodes256 << 20instead).Please either drop them, or wire them as the real defaults in
NewLRUStore/ the Helm provider so they are not dead API surface.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Currently would be dropping these since in the follow-up, we are introducing cli flag for setting these fields and fallback to default in the kubevela repo would be a better option instead of using the constants from pkg repo