Debian Codegraph @

cache.go

raw
1 package sturdyc
2
3 import (
4 "context"
5 "log/slog"
6 "sync"
7 "time"
8
9 xxhash "github.com/cespare/xxhash/v2"
10 )
11
12 // FetchFn Fetch represents a function that can be used to fetch a single record from a data source.
13 type FetchFn[T any] func(ctx context.Context) (T, error)
14
15 // BatchFetchFn represents a function that can be used to fetch multiple records from a data source.
16 type BatchFetchFn[T any] func(ctx context.Context, ids []string) (map[string]T, error)
17
18 type BatchResponse[T any] map[string]T
19
20 // KeyFn is called invoked for each record that a batch fetch
21 // operation returns. It is used to create unique cache keys.
22 type KeyFn func(id string) string
23
24 // Config represents the configuration that can be applied to the cache.
25 type Config struct {
26 clock Clock
27 evictionInterval time.Duration
28 disableContinuousEvictions bool
29 metricsRecorder DistributedMetricsRecorder
30 log Logger
31
32 earlyRefreshes bool
33 minAsyncRefreshTime time.Duration
34 maxAsyncRefreshTime time.Duration
35 syncRefreshTime time.Duration
36 retryBaseDelay time.Duration
37 storeMissingRecords bool
38
39 bufferRefreshes bool
40 batchMutex sync.Mutex
41 bufferSize int
42 bufferTimeout time.Duration
43 permutationBufferMap map[string]*buffer
44
45 useRelativeTimeKeyFormat bool
46 keyTruncation time.Duration
47 getSize func() int
48
49 distributedStorage DistributedStorageWithDeletions
50 distributedEarlyRefreshes bool
51 distributedRefreshAfterDuration time.Duration
52 }
53
54 // Client represents a cache client that can be used to store and retrieve values.
55 type Client[T any] struct {
56 *Config
57 shards []*shard[T]
58 nextShard int
59 inFlightMutex sync.Mutex
60 inFlightBatchMutex sync.Mutex
61 inFlightMap map[string]*inFlightCall[T]
62 inFlightBatchMap map[string]*inFlightCall[map[string]T]
63 }
64
65 // New creates a new Client instance with the specified configuration.
66 //
67 // `capacity` defines the maximum number of entries that the cache can store.
68 // `numShards` Is used to set the number of shards. Has to be greater than 0.
69 // `ttl` Sets the time to live for each entry in the cache. Has to be greater than 0.
70 // `evictionPercentage` Percentage of items to evict when the cache exceeds its capacity.
71 // `opts` allows for additional configurations to be applied to the cache client.
72 func New[T any](capacity, numShards int, ttl time.Duration, evictionPercentage int, opts ...Option) *Client[T] {
73 client := &Client[T]{
74 inFlightMap: make(map[string]*inFlightCall[T]),
75 inFlightBatchMap: make(map[string]*inFlightCall[map[string]T]),
76 }
77
78 // Create a default configuration, and then apply the options.
79 cfg := &Config{
80 clock: NewClock(),
81 evictionInterval: ttl / time.Duration(numShards),
82 getSize: client.Size,
83 log: slog.Default(),
84 }
85 // Apply the options to the configuration.
86 client.Config = cfg
87 for _, opt := range opts {
88 opt(cfg)
89 }
90 validateConfig(capacity, numShards, ttl, evictionPercentage, cfg)
91
92 shardSize := capacity / numShards
93 shards := make([]*shard[T], numShards)
94 for i := 0; i < numShards; i++ {
95 shards[i] = newShard[T](shardSize, ttl, evictionPercentage, cfg)
96 }
97 client.shards = shards
98 client.nextShard = 0
99
100 // Run evictions on the shards in a separate goroutine.
101 if !cfg.disableContinuousEvictions {
102 client.performContinuousEvictions()
103 }
104
105 return client
106 }
107
108 // performContinuousEvictions is going to be running in a separate goroutine that we're going to prevent from ever exiting.
109 func (c *Client[T]) performContinuousEvictions() {
110 // Create the ticker before starting the goroutine so that the eviction
111 // schedule starts when the client is created, and not whenever the
112 // scheduler first gets around to running the goroutine.
113 ticker, stop := c.clock.NewTicker(c.evictionInterval)
114 go func() {
115 defer stop()
116 for range ticker {
117 c.shards[c.nextShard].evictExpired()
118 c.nextShard = (c.nextShard + 1) % len(c.shards)
119 }
120 }()
121 }
122
123 // getShard returns the shard that should be used for the specified key.
124 func (c *Client[T]) getShard(key string) *shard[T] {
125 hash := xxhash.Sum64String(key)
126 shardIndex := hash % uint64(len(c.shards))
127 //nolint:gosec // we'll ignore potential integer overflows here.
128 c.reportShardIndex(int(shardIndex))
129 return c.shards[shardIndex]
130 }
131
132 // getWithState retrieves a single value from the cache and returns additional
133 // information about the state of the record. The state includes whether the record
134 // exists, if it has been marked as missing, and if it is due for a refresh.
135 func (c *Client[T]) getWithState(key string) (value T, exists, markedAsMissing, backgroundRefresh, synchronousRefresh bool) {
136 shard := c.getShard(key)
137 val, exists, markedAsMissing, backgroundRefresh, synchronousRefresh := shard.get(key)
138 c.reportCacheHits(exists, markedAsMissing, backgroundRefresh, synchronousRefresh)
139 return val, exists, markedAsMissing, backgroundRefresh, synchronousRefresh
140 }
141
142 // Get retrieves a single value from the cache.
143 //
144 // Parameters:
145 //
146 // key - The key to be retrieved.
147 //
148 // Returns:
149 //
150 // The value corresponding to the key and a boolean indicating if the value was found.
151 func (c *Client[T]) Get(key string) (T, bool) {
152 shard := c.getShard(key)
153 val, ok, markedAsMissing, backgroundRefresh, synchronousRefresh := shard.get(key)
154 c.reportCacheHits(ok, markedAsMissing, backgroundRefresh, synchronousRefresh)
155 return val, ok && !markedAsMissing
156 }
157
158 // GetMany retrieves multiple values from the cache.
159 //
160 // Parameters:
161 //
162 // keys - The list of keys to be retrieved.
163 //
164 // Returns:
165 //
166 // A map of keys to their corresponding values.
167 func (c *Client[T]) GetMany(keys []string) map[string]T {
168 records := make(map[string]T, len(keys))
169 for _, key := range keys {
170 if value, ok := c.Get(key); ok {
171 records[key] = value
172 }
173 }
174 return records
175 }
176
177 // GetManyKeyFn follows the same API as GetOrFetchBatch and PassthroughBatch.
178 // You provide it with a slice of IDs and a keyFn, which is applied to create
179 // the cache key. The returned map uses the IDs as keys instead of the cache
180 // key. If you've used ScanKeys to retrieve the actual keys, you can retrieve
181 // the records using GetMany instead.
182 //
183 // Parameters:
184 //
185 // ids - The list of IDs to be retrieved.
186 // keyFn - A function that generates the cache key for each ID.
187 //
188 // Returns:
189 //
190 // A map of IDs to their corresponding values.
191 func (c *Client[T]) GetManyKeyFn(ids []string, keyFn KeyFn) map[string]T {
192 records := make(map[string]T, len(ids))
193 for _, id := range ids {
194 if value, ok := c.Get(keyFn(id)); ok {
195 records[id] = value
196 }
197 }
198 return records
199 }
200
201 // Set writes a single value to the cache.
202 //
203 // Parameters:
204 //
205 // key - The key to be set.
206 // value - The value to be associated with the key.
207 //
208 // Returns:
209 //
210 // A boolean indicating if the set operation triggered an eviction.
211 func (c *Client[T]) Set(key string, value T) bool {
212 shard := c.getShard(key)
213 return shard.set(key, value, false)
214 }
215
216 // StoreMissingRecord writes a single value to the cache. Returns true if it triggered an eviction.
217 func (c *Client[T]) StoreMissingRecord(key string) bool {
218 shard := c.getShard(key)
219 var zero T
220 return shard.set(key, zero, true)
221 }
222
223 // SetMany writes a map of key-value pairs to the cache.
224 //
225 // Parameters:
226 //
227 // records - A map of keys to values to be set in the cache.
228 //
229 // Returns:
230 //
231 // A boolean indicating if any of the set operations triggered an eviction.
232 func (c *Client[T]) SetMany(records map[string]T) bool {
233 var triggeredEviction bool
234 for key, value := range records {
235 evicted := c.Set(key, value)
236 if evicted {
237 triggeredEviction = true
238 }
239 }
240 return triggeredEviction
241 }
242
243 // SetManyKeyFn follows the same API as GetOrFetchBatch and PassthroughBatch.
244 // It takes a map of records where the keyFn is applied to each key in the map
245 // before it's stored in the cache.
246 //
247 // Parameters:
248 //
249 // records - A map of IDs to values to be set in the cache.
250 // cacheKeyFn - A function that generates the cache key for each ID.
251 //
252 // Returns:
253 //
254 // A boolean indicating if any of the set operations triggered an eviction.
255 func (c *Client[T]) SetManyKeyFn(records map[string]T, cacheKeyFn KeyFn) bool {
256 var triggeredEviction bool
257 for id, value := range records {
258 evicted := c.Set(cacheKeyFn(id), value)
259 if evicted {
260 triggeredEviction = true
261 }
262 }
263 return triggeredEviction
264 }
265
266 // ScanKeys returns a list of all keys in the cache.
267 //
268 // Returns:
269 //
270 // A slice of strings representing all the keys in the cache.
271 func (c *Client[T]) ScanKeys() []string {
272 keys := make([]string, 0, c.Size())
273 for _, shard := range c.shards {
274 keys = append(keys, shard.keys()...)
275 }
276 return keys
277 }
278
279 // Size returns the number of entries in the cache.
280 //
281 // Returns:
282 //
283 // An integer representing the total number of entries in the cache.
284 func (c *Client[T]) Size() int {
285 var sum int
286 for _, shard := range c.shards {
287 sum += shard.size()
288 }
289 return sum
290 }
291
292 // Delete removes a single entry from the cache.
293 //
294 // Parameters:
295 //
296 // key: The key of the entry to be removed.
297 func (c *Client[T]) Delete(key string) {
298 shard := c.getShard(key)
299 shard.delete(key)
300 }
301
302 // NumKeysInflight returns the number of keys that are currently being fetched.
303 //
304 // Returns:
305 //
306 // An integer representing the total number of keys that are currently being fetched.
307 func (c *Client[T]) NumKeysInflight() int {
308 c.inFlightMutex.Lock()
309 defer c.inFlightMutex.Unlock()
310 c.inFlightBatchMutex.Lock()
311 defer c.inFlightBatchMutex.Unlock()
312 return len(c.inFlightMap) + len(c.inFlightBatchMap)
313 }