Debian Codegraph @

internal/lru/lru.go

raw
1 package lru
2
3 // golang -lru
4 // https://github.com/hashicorp/golang-lru
5 import (
6 "sync"
7 "time"
8 )
9
10 // EvictCallback is used to get a callback when a cache entry is evicted
11 type EvictCallback[K comparable, V any] func(key K, value V)
12
13 // LRU implements a thread-safe LRU with expirable entries.
14 type LRU[K comparable, V any] struct {
15 size int
16 evictList *LruList[K, V]
17 items map[K]*Entry[K, V]
18 onEvict EvictCallback[K, V]
19
20 // expirable options
21 mu sync.Mutex
22 ttl time.Duration
23 done chan struct{}
24
25 // buckets for expiration
26 buckets []bucket[K, V]
27 // uint8 because it's number between 0 and numBuckets
28 nextCleanupBucket uint8
29 }
30
31 // bucket is a container for holding entries to be expired
32 type bucket[K comparable, V any] struct {
33 entries map[K]*Entry[K, V]
34 newestEntry time.Time
35 }
36
37 // noEvictionTTL - very long ttl to prevent eviction
38 const noEvictionTTL = time.Hour * 24 * 365 * 10
39
40 // because of uint8 usage for nextCleanupBucket, should not exceed 256.
41 // casting it as uint8 explicitly requires type conversions in multiple places
42 const numBuckets = 100
43
44 // NewLRU returns a new thread-safe cache with expirable entries.
45 //
46 // Size parameter set to 0 makes cache of unlimited size, e.g. turns LRU mechanism off.
47 //
48 // Providing 0 TTL turns expiring off.
49 //
50 // Delete expired entries every 1/100th of ttl value. Goroutine which deletes expired entries runs indefinitely.
51 func NewLRU[K comparable, V any](size int, onEvict EvictCallback[K, V], ttl time.Duration) *LRU[K, V] {
52 if size < 0 {
53 size = 0
54 }
55 if ttl <= 0 {
56 ttl = noEvictionTTL
57 }
58
59 res := LRU[K, V]{
60 ttl: ttl,
61 size: size,
62 evictList: NewList[K, V](),
63 items: make(map[K]*Entry[K, V]),
64 onEvict: onEvict,
65 done: make(chan struct{}),
66 }
67
68 // initialize the buckets
69 res.buckets = make([]bucket[K, V], numBuckets)
70 for i := 0; i < numBuckets; i++ {
71 res.buckets[i] = bucket[K, V]{entries: make(map[K]*Entry[K, V])}
72 }
73
74 // enable deleteExpired() running in separate goroutine for cache with non-zero TTL
75 //
76 // Important: done channel is never closed, so deleteExpired() goroutine will never exit,
77 // it's decided to add functionality to close it in the version later than v2.
78 if res.ttl != noEvictionTTL {
79 go func(done <-chan struct{}) {
80 ticker := time.NewTicker(res.ttl / numBuckets)
81 defer ticker.Stop()
82 for {
83 select {
84 case <-done:
85 return
86 case <-ticker.C:
87 res.deleteExpired()
88 }
89 }
90 }(res.done)
91 }
92 return &res
93 }
94
95 // Purge clears the cache completely.
96 // onEvict is called for each evicted key.
97 func (c *LRU[K, V]) Purge() {
98 c.mu.Lock()
99 defer c.mu.Unlock()
100 for k, v := range c.items {
101 if c.onEvict != nil {
102 c.onEvict(k, v.Value)
103 }
104 delete(c.items, k)
105 }
106 for _, b := range c.buckets {
107 for _, ent := range b.entries {
108 delete(b.entries, ent.Key)
109 }
110 }
111 c.evictList.Init()
112 }
113
114 // Add adds a value to the cache. Returns true if an eviction occurred.
115 // Returns false if there was no eviction: the item was already in the cache,
116 // or the size was not exceeded.
117 func (c *LRU[K, V]) Add(key K, value V) (evicted bool) {
118 c.mu.Lock()
119 defer c.mu.Unlock()
120 now := time.Now()
121
122 // Check for existing item
123 if ent, ok := c.items[key]; ok {
124 c.evictList.MoveToFront(ent)
125 c.removeFromBucket(ent) // remove the entry from its current bucket as expiresAt is renewed
126 ent.Value = value
127 ent.ExpiresAt = now.Add(c.ttl)
128 c.addToBucket(ent)
129 return false
130 }
131
132 // Add new item
133 ent := c.evictList.PushFrontExpirable(key, value, now.Add(c.ttl))
134 c.items[key] = ent
135 c.addToBucket(ent) // adds the entry to the appropriate bucket and sets entry.expireBucket
136
137 evict := c.size > 0 && c.evictList.Length() > c.size
138 // Verify size not exceeded
139 if evict {
140 c.removeOldest()
141 }
142 return evict
143 }
144
145 // Get looks up a key's value from the cache.
146 func (c *LRU[K, V]) Get(key K) (value V, ok bool) {
147 c.mu.Lock()
148 defer c.mu.Unlock()
149 var ent *Entry[K, V]
150 if ent, ok = c.items[key]; ok {
151 // Expired item check
152 if time.Now().After(ent.ExpiresAt) {
153 return value, false
154 }
155 c.evictList.MoveToFront(ent)
156 return ent.Value, true
157 }
158 return
159 }
160
161 // Contains checks if a key is in the cache, without updating the recent-ness
162 // or deleting it for being stale.
163 func (c *LRU[K, V]) Contains(key K) (ok bool) {
164 c.mu.Lock()
165 defer c.mu.Unlock()
166 _, ok = c.items[key]
167 return ok
168 }
169
170 // Peek returns the key value (or undefined if not found) without updating
171 // the "recently used"-ness of the key.
172 func (c *LRU[K, V]) Peek(key K) (value V, ok bool) {
173 c.mu.Lock()
174 defer c.mu.Unlock()
175 var ent *Entry[K, V]
176 if ent, ok = c.items[key]; ok {
177 // Expired item check
178 if time.Now().After(ent.ExpiresAt) {
179 return value, false
180 }
181 return ent.Value, true
182 }
183 return
184 }
185
186 // Remove removes the provided key from the cache, returning if the
187 // key was contained.
188 func (c *LRU[K, V]) Remove(key K) bool {
189 c.mu.Lock()
190 defer c.mu.Unlock()
191 if ent, ok := c.items[key]; ok {
192 c.removeElement(ent)
193 return true
194 }
195 return false
196 }
197
198 // RemoveOldest removes the oldest item from the cache.
199 func (c *LRU[K, V]) RemoveOldest() (key K, value V, ok bool) {
200 c.mu.Lock()
201 defer c.mu.Unlock()
202 if ent := c.evictList.Back(); ent != nil {
203 c.removeElement(ent)
204 return ent.Key, ent.Value, true
205 }
206 return
207 }
208
209 // GetOldest returns the oldest entry
210 func (c *LRU[K, V]) GetOldest() (key K, value V, ok bool) {
211 c.mu.Lock()
212 defer c.mu.Unlock()
213 if ent := c.evictList.Back(); ent != nil {
214 return ent.Key, ent.Value, true
215 }
216 return
217 }
218
219 func (c *LRU[K, V]) KeyValues() map[K]V {
220 c.mu.Lock()
221 defer c.mu.Unlock()
222 maps := make(map[K]V)
223 now := time.Now()
224 for ent := c.evictList.Back(); ent != nil; ent = ent.PrevEntry() {
225 if now.After(ent.ExpiresAt) {
226 continue
227 }
228 maps[ent.Key] = ent.Value
229 // keys = append(keys, ent.Key)
230 }
231 return maps
232 }
233
234 // Keys returns a slice of the keys in the cache, from oldest to newest.
235 // Expired entries are filtered out.
236 func (c *LRU[K, V]) Keys() []K {
237 c.mu.Lock()
238 defer c.mu.Unlock()
239 keys := make([]K, 0, len(c.items))
240 now := time.Now()
241 for ent := c.evictList.Back(); ent != nil; ent = ent.PrevEntry() {
242 if now.After(ent.ExpiresAt) {
243 continue
244 }
245 keys = append(keys, ent.Key)
246 }
247 return keys
248 }
249
250 // Values returns a slice of the values in the cache, from oldest to newest.
251 // Expired entries are filtered out.
252 func (c *LRU[K, V]) Values() []V {
253 c.mu.Lock()
254 defer c.mu.Unlock()
255 values := make([]V, 0, len(c.items))
256 now := time.Now()
257 for ent := c.evictList.Back(); ent != nil; ent = ent.PrevEntry() {
258 if now.After(ent.ExpiresAt) {
259 continue
260 }
261 values = append(values, ent.Value)
262 }
263 return values
264 }
265
266 // Len returns the number of items in the cache.
267 func (c *LRU[K, V]) Len() int {
268 c.mu.Lock()
269 defer c.mu.Unlock()
270 return c.evictList.Length()
271 }
272
273 // Resize changes the cache size. Size of 0 means unlimited.
274 func (c *LRU[K, V]) Resize(size int) (evicted int) {
275 c.mu.Lock()
276 defer c.mu.Unlock()
277 if size <= 0 {
278 c.size = 0
279 return 0
280 }
281 diff := c.evictList.Length() - size
282 if diff < 0 {
283 diff = 0
284 }
285 for i := 0; i < diff; i++ {
286 c.removeOldest()
287 }
288 c.size = size
289 return diff
290 }
291
292 // Close destroys cleanup goroutine. To clean up the cache, run Purge() before Close().
293 // func (c *LRU[K, V]) Close() {
294 // c.mu.Lock()
295 // defer c.mu.Unlock()
296 // select {
297 // case <-c.done:
298 // return
299 // default:
300 // }
301 // close(c.done)
302 // }
303
304 // removeOldest removes the oldest item from the cache. Has to be called with lock!
305 func (c *LRU[K, V]) removeOldest() {
306 if ent := c.evictList.Back(); ent != nil {
307 c.removeElement(ent)
308 }
309 }
310
311 // removeElement is used to remove a given list element from the cache. Has to be called with lock!
312 func (c *LRU[K, V]) removeElement(e *Entry[K, V]) {
313 c.evictList.Remove(e)
314 delete(c.items, e.Key)
315 c.removeFromBucket(e)
316 if c.onEvict != nil {
317 c.onEvict(e.Key, e.Value)
318 }
319 }
320
321 // deleteExpired deletes expired records from the oldest bucket, waiting for the newest entry
322 // in it to expire first.
323 func (c *LRU[K, V]) deleteExpired() {
324 c.mu.Lock()
325 bucketIdx := c.nextCleanupBucket
326 timeToExpire := time.Until(c.buckets[bucketIdx].newestEntry)
327 // wait for newest entry to expire before cleanup without holding lock
328 if timeToExpire > 0 {
329 c.mu.Unlock()
330 time.Sleep(timeToExpire)
331 c.mu.Lock()
332 }
333 for _, ent := range c.buckets[bucketIdx].entries {
334 c.removeElement(ent)
335 }
336 c.nextCleanupBucket = (c.nextCleanupBucket + 1) % numBuckets
337 c.mu.Unlock()
338 }
339
340 // addToBucket adds entry to expire bucket so that it will be cleaned up when the time comes. Has to be called with lock!
341 func (c *LRU[K, V]) addToBucket(e *Entry[K, V]) {
342 bucketID := (numBuckets + c.nextCleanupBucket - 1) % numBuckets
343 e.ExpireBucket = bucketID
344 c.buckets[bucketID].entries[e.Key] = e
345 if c.buckets[bucketID].newestEntry.Before(e.ExpiresAt) {
346 c.buckets[bucketID].newestEntry = e.ExpiresAt
347 }
348 }
349
350 // removeFromBucket removes the entry from its corresponding bucket. Has to be called with lock!
351 func (c *LRU[K, V]) removeFromBucket(e *Entry[K, V]) {
352 delete(c.buckets[e.ExpireBucket].entries, e.Key)
353 }
354
355 // Cap returns the capacity of the cache
356 func (c *LRU[K, V]) Cap() int {
357 return c.size
358 }
359
360 // Entry is an LRU Entry
361 type Entry[K comparable, V any] struct {
362 // Next and previous pointers in the doubly-linked list of elements.
363 // To simplify the implementation, internally a list l is implemented
364 // as a ring, such that &l.root is both the next element of the last
365 // list element (l.Back()) and the previous element of the first list
366 // element (l.Front()).
367 next, prev *Entry[K, V]
368
369 // The list to which this element belongs.
370 list *LruList[K, V]
371
372 // The LRU Key of this element.
373 Key K
374
375 // The Value stored with this element.
376 Value V
377
378 // The time this element would be cleaned up, optional
379 ExpiresAt time.Time
380
381 // The expiry bucket item was put in, optional
382 ExpireBucket uint8
383 }
384
385 // PrevEntry returns the previous list element or nil.
386 func (e *Entry[K, V]) PrevEntry() *Entry[K, V] {
387 if p := e.prev; e.list != nil && p != &e.list.root {
388 return p
389 }
390 return nil
391 }
392
393 // LruList represents a doubly linked list.
394 // The zero Value for LruList is an empty list ready to use.
395 type LruList[K comparable, V any] struct {
396 root Entry[K, V] // sentinel list element, only &root, root.prev, and root.next are used
397 len int // current list Length excluding (this) sentinel element
398 }
399
400 // Init initializes or clears list l.
401 func (l *LruList[K, V]) Init() *LruList[K, V] {
402 l.root.next = &l.root
403 l.root.prev = &l.root
404 l.len = 0
405 return l
406 }
407
408 // NewList returns an initialized list.
409 func NewList[K comparable, V any]() *LruList[K, V] { return new(LruList[K, V]).Init() }
410
411 // Length returns the number of elements of list l.
412 // The complexity is O(1).
413 func (l *LruList[K, V]) Length() int { return l.len }
414
415 // Back returns the last element of list l or nil if the list is empty.
416 func (l *LruList[K, V]) Back() *Entry[K, V] {
417 if l.len == 0 {
418 return nil
419 }
420 return l.root.prev
421 }
422
423 // lazyInit lazily initializes a zero List Value.
424 func (l *LruList[K, V]) lazyInit() {
425 if l.root.next == nil {
426 l.Init()
427 }
428 }
429
430 // insert inserts e after at, increments l.len, and returns e.
431 func (l *LruList[K, V]) insert(e, at *Entry[K, V]) *Entry[K, V] {
432 e.prev = at
433 e.next = at.next
434 e.prev.next = e
435 e.next.prev = e
436 e.list = l
437 l.len++
438 return e
439 }
440
441 // insertValue is a convenience wrapper for insert(&Entry{Value: v, ExpiresAt: ExpiresAt}, at).
442 func (l *LruList[K, V]) insertValue(k K, v V, expiresAt time.Time, at *Entry[K, V]) *Entry[K, V] {
443 return l.insert(&Entry[K, V]{Value: v, Key: k, ExpiresAt: expiresAt}, at)
444 }
445
446 // Remove removes e from its list, decrements l.len
447 func (l *LruList[K, V]) Remove(e *Entry[K, V]) V {
448 e.prev.next = e.next
449 e.next.prev = e.prev
450 e.next = nil // avoid memory leaks
451 e.prev = nil // avoid memory leaks
452 e.list = nil
453 l.len--
454
455 return e.Value
456 }
457
458 // move moves e to next to at.
459 func (l *LruList[K, V]) move(e, at *Entry[K, V]) {
460 if e == at {
461 return
462 }
463 e.prev.next = e.next
464 e.next.prev = e.prev
465
466 e.prev = at
467 e.next = at.next
468 e.prev.next = e
469 e.next.prev = e
470 }
471
472 // PushFront inserts a new element e with value v at the front of list l and returns e.
473 func (l *LruList[K, V]) PushFront(k K, v V) *Entry[K, V] {
474 l.lazyInit()
475 return l.insertValue(k, v, time.Time{}, &l.root)
476 }
477
478 // PushFrontExpirable inserts a new expirable element e with Value v at the front of list l and returns e.
479 func (l *LruList[K, V]) PushFrontExpirable(k K, v V, expiresAt time.Time) *Entry[K, V] {
480 l.lazyInit()
481 return l.insertValue(k, v, expiresAt, &l.root)
482 }
483
484 // MoveToFront moves element e to the front of list l.
485 // If e is not an element of l, the list is not modified.
486 // The element must not be nil.
487 func (l *LruList[K, V]) MoveToFront(e *Entry[K, V]) {
488 if e.list != l || l.root.next == e {
489 return
490 }
491 // see comment in List.Remove about initialization of l
492 l.move(e, &l.root)
493 }