ttl.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /*
  2. * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package ristretto
  6. import (
  7. "sync"
  8. "time"
  9. )
  10. var (
  11. // TODO: find the optimal value or make it configurable.
  12. bucketDurationSecs = int64(5)
  13. )
  14. func storageBucket(t time.Time) int64 {
  15. return (t.Unix() / bucketDurationSecs) + 1
  16. }
  17. func cleanupBucket(t time.Time) int64 {
  18. // The bucket to cleanup is always behind the storage bucket by one so that
  19. // no elements in that bucket (which might not have expired yet) are deleted.
  20. return storageBucket(t) - 1
  21. }
  22. // bucket type is a map of key to conflict.
  23. type bucket map[uint64]uint64
  24. // expirationMap is a map of bucket number to the corresponding bucket.
  25. type expirationMap[V any] struct {
  26. sync.RWMutex
  27. buckets map[int64]bucket
  28. lastCleanedBucketNum int64
  29. }
  30. func newExpirationMap[V any]() *expirationMap[V] {
  31. return &expirationMap[V]{
  32. buckets: make(map[int64]bucket),
  33. lastCleanedBucketNum: cleanupBucket(time.Now()),
  34. }
  35. }
  36. func (m *expirationMap[_]) add(key, conflict uint64, expiration time.Time) {
  37. if m == nil {
  38. return
  39. }
  40. // Items that don't expire don't need to be in the expiration map.
  41. if expiration.IsZero() {
  42. return
  43. }
  44. bucketNum := storageBucket(expiration)
  45. m.Lock()
  46. defer m.Unlock()
  47. b, ok := m.buckets[bucketNum]
  48. if !ok {
  49. b = make(bucket)
  50. m.buckets[bucketNum] = b
  51. }
  52. b[key] = conflict
  53. }
  54. func (m *expirationMap[_]) update(key, conflict uint64, oldExpTime, newExpTime time.Time) {
  55. if m == nil {
  56. return
  57. }
  58. m.Lock()
  59. defer m.Unlock()
  60. oldBucketNum := storageBucket(oldExpTime)
  61. oldBucket, ok := m.buckets[oldBucketNum]
  62. if ok {
  63. delete(oldBucket, key)
  64. }
  65. // Items that don't expire don't need to be in the expiration map.
  66. if newExpTime.IsZero() {
  67. return
  68. }
  69. newBucketNum := storageBucket(newExpTime)
  70. newBucket, ok := m.buckets[newBucketNum]
  71. if !ok {
  72. newBucket = make(bucket)
  73. m.buckets[newBucketNum] = newBucket
  74. }
  75. newBucket[key] = conflict
  76. }
  77. func (m *expirationMap[_]) del(key uint64, expiration time.Time) {
  78. if m == nil {
  79. return
  80. }
  81. bucketNum := storageBucket(expiration)
  82. m.Lock()
  83. defer m.Unlock()
  84. _, ok := m.buckets[bucketNum]
  85. if !ok {
  86. return
  87. }
  88. delete(m.buckets[bucketNum], key)
  89. }
  90. // cleanup removes all the items in the bucket that was just completed. It deletes
  91. // those items from the store, and calls the onEvict function on those items.
  92. // This function is meant to be called periodically.
  93. func (m *expirationMap[V]) cleanup(store store[V], policy *defaultPolicy[V], onEvict func(item *Item[V])) int {
  94. if m == nil {
  95. return 0
  96. }
  97. m.Lock()
  98. now := time.Now()
  99. currentBucketNum := cleanupBucket(now)
  100. // Clean up all buckets up to and including currentBucketNum, starting from
  101. // (but not including) the last one that was cleaned up
  102. var buckets []bucket
  103. for bucketNum := m.lastCleanedBucketNum + 1; bucketNum <= currentBucketNum; bucketNum++ {
  104. // With an empty bucket, we don't need to add it to the Clean list
  105. if b := m.buckets[bucketNum]; b != nil {
  106. buckets = append(buckets, b)
  107. }
  108. delete(m.buckets, bucketNum)
  109. }
  110. m.lastCleanedBucketNum = currentBucketNum
  111. m.Unlock()
  112. for _, keys := range buckets {
  113. for key, conflict := range keys {
  114. expr := store.Expiration(key)
  115. // Sanity check. Verify that the store agrees that this key is expired.
  116. if expr.After(now) {
  117. continue
  118. }
  119. cost := policy.Cost(key)
  120. policy.Del(key)
  121. _, value := store.Del(key, conflict)
  122. if onEvict != nil {
  123. onEvict(&Item[V]{Key: key,
  124. Conflict: conflict,
  125. Value: value,
  126. Cost: cost,
  127. Expiration: expr,
  128. })
  129. }
  130. }
  131. }
  132. cleanedBucketsCount := len(buckets)
  133. return cleanedBucketsCount
  134. }
  135. // clear clears the expirationMap, the caller is responsible for properly
  136. // evicting the referenced items
  137. func (m *expirationMap[V]) clear() {
  138. if m == nil {
  139. return
  140. }
  141. m.Lock()
  142. m.buckets = make(map[int64]bucket)
  143. m.lastCleanedBucketNum = cleanupBucket(time.Now())
  144. m.Unlock()
  145. }