Debian Codegraph @

cache_test.go

raw
1 package sturdyc_test
2
3 import (
4 "strconv"
5 "strings"
6 "testing"
7 "time"
8
9 "github.com/viccon/sturdyc"
10 )
11
12 type distributionTestCase struct {
13 name string
14 capacity int
15 numShards int
16 tolerancePercentage int
17 keyLength int
18 }
19
20 func TestShardDistribution(t *testing.T) {
21 t.Parallel()
22
23 testCases := []distributionTestCase{
24 {
25 name: "1_000_000 capacity, 100 shards, 12% tolerance, 16 key length",
26 capacity: 1_000_000,
27 numShards: 100,
28 tolerancePercentage: 12,
29 keyLength: 16,
30 },
31 {
32 name: "1000 capacity, 2 shards, 12% tolerance, 14 key length",
33 capacity: 1000,
34 numShards: 2,
35 tolerancePercentage: 12,
36 keyLength: 14,
37 },
38 }
39
40 for _, tc := range testCases {
41 tc := tc
42 t.Run(tc.name, func(t *testing.T) {
43 t.Parallel()
44 recorder := newTestMetricsRecorder(tc.numShards)
45 c := sturdyc.New[string](tc.capacity, tc.numShards, time.Hour, 5,
46 sturdyc.WithNoContinuousEvictions(),
47 sturdyc.WithMetrics(recorder),
48 )
49 for i := 0; i < tc.capacity; i++ {
50 key := randKey(tc.keyLength)
51 c.Set(key, "value")
52 }
53 recorder.validateShardDistribution(t, tc.tolerancePercentage)
54 })
55 }
56 }
57
58 func TestTimeBasedEviction(t *testing.T) {
59 t.Parallel()
60 capacity := 10_000
61 numShards := 100
62 ttl := time.Hour
63 evictionPercentage := 5
64 evictionInterval := time.Second
65 clock := sturdyc.NewTestClock(time.Now())
66 metricRecorder := newTestMetricsRecorder(numShards)
67 c := sturdyc.New[string](
68 capacity,
69 numShards,
70 ttl,
71 evictionPercentage,
72 sturdyc.WithMetrics(metricRecorder),
73 sturdyc.WithClock(clock),
74 sturdyc.WithEvictionInterval(evictionInterval),
75 )
76
77 for i := 0; i < capacity; i++ {
78 c.Set(randKey(12), "value")
79 }
80
81 // Expire all entries.
82 clock.Add(ttl + 1)
83
84 // Next, we'll loop through each shard while moving the clock by the evictionInterval. We'll
85 // sleep for a brief duration to allow the goroutines that were waiting for the timer to run.
86 for i := 0; i < numShards; i++ {
87 clock.Add(time.Second + 1)
88 time.Sleep(5 * time.Millisecond)
89 }
90
91 metricRecorder.Lock()
92 defer metricRecorder.Unlock()
93 if metricRecorder.evictedEntries != capacity {
94 t.Errorf("expected %d evicted entries, got %d", capacity, metricRecorder.evictedEntries)
95 }
96 }
97
98 type forcedEvictionTestCase struct {
99 name string
100 capacity int
101 writes int
102 numShards int
103 evictionPercentage int
104 minEvictions int
105 maxEvictions int
106 }
107
108 func TestForcedEvictions(t *testing.T) {
109 t.Parallel()
110
111 testCases := []forcedEvictionTestCase{
112 {
113 name: "1000 capacity, 100_000 writes, 100 shards, 5% forced evictions",
114 capacity: 10_000,
115 writes: 100_000,
116 numShards: 100,
117 evictionPercentage: 5,
118 minEvictions: 20_000, // Perfect shard distribution.
119 maxEvictions: 20_800, // Accounting for a 4% tolerance.
120 },
121 {
122 name: "100 capacity, 10_000 writes, 10 shards, 1% forced evictions",
123 capacity: 100,
124 writes: 10_000,
125 numShards: 10,
126 evictionPercentage: 1,
127 minEvictions: 9999,
128 maxEvictions: 10001,
129 },
130 {
131 name: "100 capacity, 1000 writes, 10 shards, 100% forced evictions",
132 capacity: 100,
133 writes: 1000,
134 numShards: 10,
135 evictionPercentage: 100,
136 minEvictions: 100,
137 maxEvictions: 120,
138 },
139 }
140
141 for _, tc := range testCases {
142 tc := tc
143 t.Run(tc.name, func(t *testing.T) {
144 t.Parallel()
145
146 recorder := newTestMetricsRecorder(tc.numShards)
147 c := sturdyc.New[string](tc.capacity,
148 tc.numShards,
149 time.Hour,
150 tc.evictionPercentage,
151 sturdyc.WithMetrics(recorder),
152 sturdyc.WithNoContinuousEvictions(),
153 )
154
155 // Start by filling the sturdyc.
156 for i := 0; i < tc.capacity; i++ {
157 key := randKey(12)
158 c.Set(key, "value")
159 }
160
161 // Next, we'll write to the cache to force evictions.
162 for i := 0; i < tc.writes; i++ {
163 key := randKey(12)
164 c.Set(key, "value")
165 }
166
167 if recorder.forcedEvictions < tc.minEvictions || recorder.forcedEvictions > tc.maxEvictions {
168 t.Errorf(
169 "expected forced evictions between %d and %d, got %d",
170 tc.minEvictions, tc.maxEvictions, recorder.forcedEvictions,
171 )
172 }
173 })
174 }
175 }
176
177 func TestForceEvictAllEntries(t *testing.T) {
178 t.Parallel()
179 capacity := 100
180 numShards := 1
181 ttl := time.Hour
182 evictionpercentage := 100
183 clock := sturdyc.NewTestClock(time.Now())
184 metricRecorder := newTestMetricsRecorder(numShards)
185 c := sturdyc.New[string](capacity, numShards, ttl, evictionpercentage,
186 sturdyc.WithClock(clock),
187 sturdyc.WithMetrics(metricRecorder),
188 )
189
190 // Fill the cache to capacity
191 for i := 0; i < capacity; i++ {
192 c.Set(strconv.Itoa(i), strconv.Itoa(i))
193 }
194
195 // Record metrics before eviction
196 preEvictionCount := metricRecorder.evictedEntries
197
198 // Trigger eviction by adding one more entry
199 // When the eviction is triggered by the 100th write, we expect the cache to
200 // be emptied. Therefore, the 101th write should mean that the size is now 1.
201 c.Set("trigger", "value")
202
203 // When the eviction is triggered, we expect the cache to be emptied
204 // and only contain the trigger value
205 if c.Size() != 1 {
206 t.Errorf("expected cache size to be 1, got %d", c.Size())
207 }
208
209 // Verify eviction metrics
210 metricRecorder.Lock()
211 defer metricRecorder.Unlock()
212 evictedEntries := metricRecorder.evictedEntries - preEvictionCount
213 if evictedEntries != capacity {
214 t.Errorf("got %d evicted entries, want %d", evictedEntries, capacity)
215 }
216 if metricRecorder.forcedEvictions != 1 {
217 t.Errorf("got %d forced eviction events, want 1", metricRecorder.forcedEvictions)
218 }
219 }
220
221 func TestForceEvictionSameTime(t *testing.T) {
222 t.Parallel()
223 capacity := 100
224 numShards := 2
225 ttl := time.Hour
226 evictionpercentage := 50
227 clock := sturdyc.NewTestClock(time.Now())
228 c := sturdyc.New[string](capacity, numShards, ttl, evictionpercentage,
229 sturdyc.WithClock(clock),
230 )
231
232 // Now we're going to write 1000 records to the cache which should
233 // exceed its capacity and trigger a couple of forced evictions.
234 for i := 0; i < 1000; i++ {
235 c.Set(strconv.Itoa(i), strconv.Itoa(i))
236 }
237
238 // Assert that even though we're writing 1000
239 // records we never exceed the capacity of 100.
240 if c.Size() > 100 {
241 t.Errorf("exceeded the cache size of 100, got %d", c.Size())
242 }
243 }
244
245 func TestForceEvictionTwoDifferentTimes(t *testing.T) {
246 t.Parallel()
247 capacity := 100
248 numShards := 1
249 ttl := time.Hour
250 evictionpercentage := 10
251 clock := sturdyc.NewTestClock(time.Now())
252 c := sturdyc.New[string](capacity, numShards, ttl, evictionpercentage,
253 sturdyc.WithClock(clock),
254 )
255
256 // We're going to write 50 records, then move the clock forward
257 // and write another 50 to reach the capacity of the cache.
258 for i := 0; i < 50; i++ {
259 c.Set(strconv.Itoa(i), strconv.Itoa(i))
260 }
261 clock.Add(time.Hour)
262 for i := 0; i < 50; i++ {
263 c.Set(strconv.Itoa(i+50), strconv.Itoa(i+50))
264 }
265
266 // At this point, the cache should be at its capacity so
267 // adding another item should trigger a forced eviction.
268 // Given our eviction percentage of 10%, we expect the
269 // cache to first remove 10 items, and then write this
270 // record afterwards.
271 c.Set(strconv.Itoa(100), strconv.Itoa(100))
272 if c.Size() != 91 {
273 t.Errorf("expected cache size to be 91, got %d", c.Size())
274 }
275 }
276
277 func TestDisablingForcedEvictionMakesSetANoop(t *testing.T) {
278 t.Parallel()
279
280 capacity := 100
281 numShards := 10
282 ttl := time.Hour
283 // Setting the eviction percentage to 0 should disable forced evictions.
284 evictionpercentage := 0
285 metricRecorder := newTestMetricsRecorder(numShards)
286 c := sturdyc.New[string](
287 capacity,
288 numShards,
289 ttl,
290 evictionpercentage,
291 sturdyc.WithMetrics(metricRecorder),
292 )
293
294 for i := 0; i < capacity*10; i++ {
295 c.Set(randKey(12), "value")
296 }
297
298 metricRecorder.Lock()
299 defer metricRecorder.Unlock()
300 if metricRecorder.forcedEvictions > 0 {
301 t.Errorf("expected no forced evictions, got %d", metricRecorder.forcedEvictions)
302 }
303 }
304
305 func TestSetMany(t *testing.T) {
306 t.Parallel()
307
308 c := sturdyc.New[int](1000, 10, time.Hour, 5)
309
310 if c.Size() != 0 {
311 t.Errorf("expected cache size to be 0, got %d", c.Size())
312 }
313
314 records := make(map[string]int, 10)
315 for i := 0; i < 10; i++ {
316 records[strconv.Itoa(i)] = i
317 }
318 c.SetMany(records)
319
320 if c.Size() != 10 {
321 t.Errorf("expected cache size to be 10, got %d", c.Size())
322 }
323
324 keys := c.ScanKeys()
325 if len(keys) != 10 {
326 t.Errorf("expected 10 keys, got %d", len(keys))
327 }
328 for _, key := range keys {
329 if _, ok := records[key]; !ok {
330 t.Errorf("expected key %s to be in the cache", key)
331 }
332 }
333 }
334
335 func TestSetManyKeyFn(t *testing.T) {
336 t.Parallel()
337
338 c := sturdyc.New[int](1000, 10, time.Hour, 5)
339
340 if c.Size() != 0 {
341 t.Errorf("expected cache size to be 0, got %d", c.Size())
342 }
343
344 records := make(map[string]int, 10)
345 for i := 0; i < 10; i++ {
346 records[strconv.Itoa(i)] = i
347 }
348 c.SetManyKeyFn(records, c.BatchKeyFn("foo"))
349
350 if c.Size() != 10 {
351 t.Errorf("expected cache size to be 10, got %d", c.Size())
352 }
353
354 keys := c.ScanKeys()
355 if len(keys) != 10 {
356 t.Errorf("expected 10 keys, got %d", len(keys))
357 }
358 for _, key := range keys {
359 if !strings.HasPrefix(key, "foo") {
360 t.Errorf("expected key %s to start with foo", key)
361 }
362 }
363 }
364
365 func TestGetMany(t *testing.T) {
366 t.Parallel()
367
368 c := sturdyc.New[int](1000, 10, time.Hour, 5)
369
370 if c.Size() != 0 {
371 t.Errorf("expected cache size to be 0, got %d", c.Size())
372 }
373
374 records := make(map[string]int, 10)
375 for i := 0; i < 10; i++ {
376 records[strconv.Itoa(i)] = i
377 }
378 c.SetMany(records)
379
380 keys := make([]string, 0, 10)
381 for key := range records {
382 keys = append(keys, key)
383 }
384
385 cacheHits := c.GetMany(keys)
386 if len(cacheHits) != 10 {
387 for key := range records {
388 if _, ok := cacheHits[key]; !ok {
389 t.Errorf("expected key %s to be in the cache", key)
390 }
391 }
392 }
393 }
394
395 func TestEvictsAndReturnsTheCorrectSize(t *testing.T) {
396 t.Parallel()
397
398 // Let's create a cache with a capacity of 100 and a
399 // single shard. We'll set the eviction percentage to 10%.
400 client := sturdyc.New[int](100, 1, time.Hour, 10)
401
402 // Now, if we were to write 101 items, which is 1 more
403 // than our capacity, we expect 10% to have been evicted.
404 for i := 0; i < 101; i++ {
405 client.Set(strconv.Itoa(i), i)
406 }
407
408 if client.Size() != 91 {
409 t.Errorf("expected cache size to be 91, got %d", client.Size())
410 }
411 }
412
413 func TestDeletesAllItemsAcrossMultipleShards(t *testing.T) {
414 t.Parallel()
415
416 client := sturdyc.New[string](1_000_000, 1000, time.Hour, 10)
417
418 ids := make([]string, 0, 10_000)
419 for i := 0; i < 10_000; i++ {
420 id := randKey(12)
421 ids = append(ids, id)
422 client.Set(id, "value")
423 }
424
425 if client.Size() != 10_000 {
426 t.Errorf("expected cache size to be 10_000, got %d", client.Size())
427 }
428
429 for _, id := range ids {
430 client.Delete(id)
431 }
432
433 if client.Size() != 0 {
434 t.Errorf("expected cache size to be 0, got %d", client.Size())
435 }
436 }
437
438 func TestReportsMetricsForHitsAndMisses(t *testing.T) {
439 t.Parallel()
440
441 metricsRecorder := newTestMetricsRecorder(10)
442 client := sturdyc.New[string](100, 10, time.Hour, 5,
443 sturdyc.WithMetrics(metricsRecorder),
444 )
445
446 client.Set("existing-key", "value")
447 client.Get("existing-key")
448 client.Get("non-existent-key")
449
450 if metricsRecorder.cacheHits != 1 {
451 t.Errorf("expected 1 cache hit, got %d", metricsRecorder.cacheHits)
452 }
453
454 if metricsRecorder.cacheMisses != 1 {
455 t.Errorf("expected 1 cache miss, got %d", metricsRecorder.cacheMisses)
456 }
457 }