| 1 |
package sturdyc |
| 2 |
|
| 3 |
import ( |
| 4 |
"math/rand/v2" |
| 5 |
"sync" |
| 6 |
"time" |
| 7 |
) |
| 8 |
|
| 9 |
// entry represents a single cache entry. |
| 10 |
type entry[T any] struct { |
| 11 |
key string |
| 12 |
value T |
| 13 |
expiresAt time.Time |
| 14 |
backgroundRefreshAt time.Time |
| 15 |
synchronousRefreshAt time.Time |
| 16 |
numOfRefreshRetries int |
| 17 |
isMissingRecord bool |
| 18 |
} |
| 19 |
|
| 20 |
// shard is a thread-safe data structure that holds a subset of the cache entries. |
| 21 |
type shard[T any] struct { |
| 22 |
sync.RWMutex |
| 23 |
*Config |
| 24 |
capacity int |
| 25 |
ttl time.Duration |
| 26 |
entries map[string]*entry[T] |
| 27 |
evictionPercentage int |
| 28 |
} |
| 29 |
|
| 30 |
// newShard creates a new shard and returns a pointer to it. |
| 31 |
func newShard[T any](capacity int, ttl time.Duration, evictionPercentage int, cfg *Config) *shard[T] { |
| 32 |
return &shard[T]{ |
| 33 |
Config: cfg, |
| 34 |
capacity: capacity, |
| 35 |
ttl: ttl, |
| 36 |
entries: make(map[string]*entry[T]), |
| 37 |
evictionPercentage: evictionPercentage, |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
// size returns the number of entries in the shard. |
| 42 |
func (s *shard[T]) size() int { |
| 43 |
s.RLock() |
| 44 |
defer s.RUnlock() |
| 45 |
return len(s.entries) |
| 46 |
} |
| 47 |
|
| 48 |
// evictExpired evicts all the expired entries in the shard. |
| 49 |
func (s *shard[T]) evictExpired() { |
| 50 |
s.Lock() |
| 51 |
defer s.Unlock() |
| 52 |
|
| 53 |
var entriesEvicted int |
| 54 |
for _, e := range s.entries { |
| 55 |
if s.clock.Now().After(e.expiresAt) { |
| 56 |
delete(s.entries, e.key) |
| 57 |
entriesEvicted++ |
| 58 |
} |
| 59 |
} |
| 60 |
s.reportEntriesEvicted(entriesEvicted) |
| 61 |
} |
| 62 |
|
| 63 |
// forceEvict evicts a certain percentage of the entries in the shard |
| 64 |
// based on the expiration time. Should be called with a lock. |
| 65 |
func (s *shard[T]) forceEvict() { |
| 66 |
s.reportForcedEviction() |
| 67 |
|
| 68 |
// Check if we should evict all entries. |
| 69 |
if s.evictionPercentage == 100 { |
| 70 |
evictedCount := len(s.entries) |
| 71 |
s.entries = make(map[string]*entry[T]) |
| 72 |
s.reportEntriesEvicted(evictedCount) |
| 73 |
return |
| 74 |
} |
| 75 |
|
| 76 |
expirationTimes := make([]time.Time, 0, len(s.entries)) |
| 77 |
for _, e := range s.entries { |
| 78 |
expirationTimes = append(expirationTimes, e.expiresAt) |
| 79 |
} |
| 80 |
|
| 81 |
// We could have a lumpy distribution of expiration times. As an example, we |
| 82 |
// might have 100 entries in the cache but only 2 unique expiration times. In |
| 83 |
// order to not over-evict when trying to remove 10%, we'll have to keep |
| 84 |
// track of the number of entries that we've evicted. |
| 85 |
percentage := float64(s.evictionPercentage) / 100 |
| 86 |
cutoff := FindCutoff(expirationTimes, percentage) |
| 87 |
entriesToEvict := int(float64(len(expirationTimes)) * percentage) |
| 88 |
entriesEvicted := 0 |
| 89 |
for key, e := range s.entries { |
| 90 |
// Here we're essentially saying: if e.expiresAt <= cutoff. |
| 91 |
if !e.expiresAt.After(cutoff) { |
| 92 |
delete(s.entries, key) |
| 93 |
entriesEvicted++ |
| 94 |
|
| 95 |
if entriesEvicted == entriesToEvict { |
| 96 |
break |
| 97 |
} |
| 98 |
} |
| 99 |
} |
| 100 |
s.reportEntriesEvicted(entriesEvicted) |
| 101 |
} |
| 102 |
|
| 103 |
// get attempts to retrieve a value from the shard. |
| 104 |
// |
| 105 |
// Parameters: |
| 106 |
// |
| 107 |
// key: The key for which the value is to be retrieved. |
| 108 |
// |
| 109 |
// Returns: |
| 110 |
// |
| 111 |
// val: The value associated with the key, if it exists. |
| 112 |
// exists: A boolean indicating if the value exists in the shard. |
| 113 |
// markedAsMissing: A boolean indicating if the key has been marked as a missing record. |
| 114 |
// refresh: A boolean indicating if the value should be refreshed in the background. |
| 115 |
func (s *shard[T]) get(key string) (val T, exists, markedAsMissing, backgroundRefresh, synchronousRefresh bool) { |
| 116 |
s.RLock() |
| 117 |
item, ok := s.entries[key] |
| 118 |
if !ok { |
| 119 |
s.RUnlock() |
| 120 |
return val, false, false, false, false |
| 121 |
} |
| 122 |
|
| 123 |
if s.clock.Now().After(item.expiresAt) { |
| 124 |
s.RUnlock() |
| 125 |
return val, false, false, false, false |
| 126 |
} |
| 127 |
|
| 128 |
// Check if the record should be synchronously refreshed. |
| 129 |
if s.earlyRefreshes && s.clock.Now().After(item.synchronousRefreshAt) { |
| 130 |
s.RUnlock() |
| 131 |
return item.value, true, item.isMissingRecord, false, true |
| 132 |
} |
| 133 |
|
| 134 |
shouldRefresh := s.earlyRefreshes && s.clock.Now().After(item.backgroundRefreshAt) |
| 135 |
if shouldRefresh { |
| 136 |
// Release the read lock, and switch to a write lock. |
| 137 |
s.RUnlock() |
| 138 |
s.Lock() |
| 139 |
|
| 140 |
// However, during the time it takes to switch locks, another goroutine |
| 141 |
// might have acquired it and moved the refreshAt. Therefore, we'll have to |
| 142 |
// check if this operation should still be performed. |
| 143 |
if !s.clock.Now().After(item.backgroundRefreshAt) { |
| 144 |
s.Unlock() |
| 145 |
return item.value, true, item.isMissingRecord, false, false |
| 146 |
} |
| 147 |
|
| 148 |
// Update the "refreshAt" so no other goroutines attempts to refresh the same entry. |
| 149 |
nextRefresh := s.retryBaseDelay * (1 << item.numOfRefreshRetries) |
| 150 |
item.backgroundRefreshAt = s.clock.Now().Add(nextRefresh) |
| 151 |
item.numOfRefreshRetries++ |
| 152 |
|
| 153 |
s.Unlock() |
| 154 |
return item.value, true, item.isMissingRecord, shouldRefresh, false |
| 155 |
} |
| 156 |
|
| 157 |
s.RUnlock() |
| 158 |
return item.value, true, item.isMissingRecord, false, false |
| 159 |
} |
| 160 |
|
| 161 |
// set writes a key-value pair to the shard and returns a |
| 162 |
// boolean indicating whether an eviction was performed. |
| 163 |
func (s *shard[T]) set(key string, value T, isMissingRecord bool) bool { |
| 164 |
s.Lock() |
| 165 |
defer s.Unlock() |
| 166 |
|
| 167 |
// Check we need to perform an eviction first. |
| 168 |
evict := len(s.entries) >= s.capacity |
| 169 |
|
| 170 |
// If the cache is configured to not evict any entries, |
| 171 |
// and we're att full capacity, we'll return early. |
| 172 |
if s.evictionPercentage < 1 && evict { |
| 173 |
return false |
| 174 |
} |
| 175 |
|
| 176 |
if evict { |
| 177 |
s.forceEvict() |
| 178 |
} |
| 179 |
|
| 180 |
now := s.clock.Now() |
| 181 |
newEntry := &entry[T]{ |
| 182 |
key: key, |
| 183 |
value: value, |
| 184 |
expiresAt: now.Add(s.ttl), |
| 185 |
isMissingRecord: isMissingRecord, |
| 186 |
} |
| 187 |
|
| 188 |
if s.earlyRefreshes { |
| 189 |
// If there is a difference between the min- and maxRefreshTime we'll use that to |
| 190 |
// set a random padding so that the refreshes get spread out evenly over time. |
| 191 |
var padding time.Duration |
| 192 |
if s.minAsyncRefreshTime != s.maxAsyncRefreshTime { |
| 193 |
padding = time.Duration(rand.Int64N(int64(s.maxAsyncRefreshTime - s.minAsyncRefreshTime))) |
| 194 |
} |
| 195 |
newEntry.backgroundRefreshAt = now.Add(s.minAsyncRefreshTime + padding) |
| 196 |
newEntry.synchronousRefreshAt = now.Add(s.syncRefreshTime) |
| 197 |
newEntry.numOfRefreshRetries = 0 |
| 198 |
} |
| 199 |
|
| 200 |
s.entries[key] = newEntry |
| 201 |
return evict |
| 202 |
} |
| 203 |
|
| 204 |
// delete removes a key from the shard. |
| 205 |
func (s *shard[T]) delete(key string) { |
| 206 |
s.Lock() |
| 207 |
defer s.Unlock() |
| 208 |
delete(s.entries, key) |
| 209 |
} |
| 210 |
|
| 211 |
// keys returns all non-expired keys in the shard. |
| 212 |
func (s *shard[T]) keys() []string { |
| 213 |
s.RLock() |
| 214 |
defer s.RUnlock() |
| 215 |
keys := make([]string, 0, len(s.entries)) |
| 216 |
for k, v := range s.entries { |
| 217 |
if s.clock.Now().After(v.expiresAt) { |
| 218 |
continue |
| 219 |
} |
| 220 |
keys = append(keys, k) |
| 221 |
} |
| 222 |
return keys |
| 223 |
} |