Debian Codegraph @

fetch_test.go

raw
1 package sturdyc_test
2
3 import (
4 "context"
5 "errors"
6 "math/rand/v2"
7 "strconv"
8 "sync"
9 "sync/atomic"
10 "testing"
11 "time"
12
13 "github.com/viccon/sturdyc"
14 )
15
16 func TestGetOrFetch(t *testing.T) {
17 t.Parallel()
18
19 ctx := context.Background()
20 capacity := 5
21 numShards := 2
22 ttl := time.Minute
23 evictionPercentage := 10
24 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
25 sturdyc.WithNoContinuousEvictions(),
26 )
27
28 id := "1"
29 fetchObserver := NewFetchObserver(1)
30 fetchObserver.Response(id)
31
32 // The first time we call Get, it should call the fetchFn to retrieve the value.
33 firstValue, err := sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
34 if err != nil {
35 t.Fatalf("expected no error, got %v", err)
36 }
37 if firstValue != "value1" {
38 t.Errorf("expected value1, got %v", firstValue)
39 }
40
41 <-fetchObserver.FetchCompleted
42 fetchObserver.AssertFetchCount(t, 1)
43
44 // The second time we call Get, we expect to have it served from the sturdyc.
45 secondValue, err := sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
46 if err != nil {
47 t.Fatalf("expected no error, got %v", err)
48 }
49 if secondValue != "value1" {
50 t.Errorf("expected value1, got %v", secondValue)
51 }
52 time.Sleep(time.Millisecond * 10)
53 fetchObserver.AssertFetchCount(t, 1)
54 }
55
56 func TestGetOrFetchStampedeProtection(t *testing.T) {
57 t.Parallel()
58
59 ctx := context.Background()
60 capacity := 10
61 numShards := 2
62 ttl := time.Second * 2
63 evictionPercentage := 10
64 clock := sturdyc.NewTestClock(time.Now())
65 minRefreshDelay := time.Millisecond * 500
66 maxRefreshDelay := time.Millisecond * 500
67 synchronousRefreshDelay := time.Second
68 refreshRetryInterval := time.Millisecond * 10
69
70 // The cache is going to have a 2 second TTL, and the first refresh should happen within a second.
71 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
72 sturdyc.WithNoContinuousEvictions(),
73 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
74 sturdyc.WithMissingRecordStorage(),
75 sturdyc.WithClock(clock),
76 )
77
78 id := "1"
79 fetchObserver := NewFetchObserver(1)
80 fetchObserver.Response(id)
81
82 // We will start the test by trying to get key1, which wont exist in the sturdyc. Hence,
83 // the fetch function is going to get called and we'll set the initial value to val1.
84 sturdyc.GetOrFetch[string](ctx, c, id, fetchObserver.Fetch)
85
86 <-fetchObserver.FetchCompleted
87 fetchObserver.AssertFetchCount(t, 1)
88
89 // Now, we're going to go past the refresh delay and try to refresh it from 1000 goroutines at once.
90 numGoroutines := 1000
91 clock.Add(maxRefreshDelay + 1)
92 var wg sync.WaitGroup
93 wg.Add(numGoroutines)
94 for i := 0; i < numGoroutines; i++ {
95 go func() {
96 defer wg.Done()
97 _, err := sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
98 if err != nil {
99 panic(err)
100 }
101 }()
102 }
103 wg.Wait()
104
105 <-fetchObserver.FetchCompleted
106 fetchObserver.AssertFetchCount(t, 2)
107 }
108
109 func TestGetOrFetchRefreshRetries(t *testing.T) {
110 t.Parallel()
111
112 ctx := context.Background()
113 capacity := 5
114 numShards := 1
115 ttl := time.Minute
116 evictionPercentage := 10
117 minRefreshDelay := time.Second
118 maxRefreshDelay := time.Second * 2
119 synchronousRefreshDelay := time.Second * 10
120 retryInterval := time.Millisecond * 10
121 clock := sturdyc.NewTestClock(time.Now())
122
123 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
124 sturdyc.WithNoContinuousEvictions(),
125 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, retryInterval),
126 sturdyc.WithMissingRecordStorage(),
127 sturdyc.WithClock(clock),
128 )
129
130 id := "1"
131 fetchObserver := NewFetchObserver(6)
132 fetchObserver.Response(id)
133
134 _, err := sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
135 if err != nil {
136 t.Fatalf("expected no error, got %v", err)
137 }
138
139 <-fetchObserver.FetchCompleted
140 fetchObserver.AssertFetchCount(t, 1)
141 fetchObserver.Clear()
142
143 // Now, we'll move the clock passed the refresh delay which should make the
144 // next call to GetOrFetchBatch result in a call to refresh the record.
145 clock.Add(maxRefreshDelay + 1)
146 fetchObserver.Err(errors.New("error"))
147 _, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
148 if err != nil {
149 t.Fatalf("expected no error, got %v", err)
150 }
151
152 // Next, we'll assert that the retries grows exponentially. Even though we're
153 // making 100 requests with 1 second between them, we only expect 6 calls to
154 // go through.
155 for i := 0; i < 100; i++ {
156 clock.Add(retryInterval)
157 sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
158 }
159 for i := 0; i < 6; i++ {
160 <-fetchObserver.FetchCompleted
161 }
162 fetchObserver.AssertMaxFetchCount(t, 8)
163 }
164
165 func TestGetOrFetchMissingRecord(t *testing.T) {
166 t.Parallel()
167
168 ctx := context.Background()
169 capacity := 5
170 numShards := 1
171 ttl := time.Minute
172 evictionPercentage := 20
173 minRefreshDelay := time.Second
174 maxRefreshDelay := time.Second * 2
175 synchronousRefreshDelay := time.Second * 10
176 retryInterval := time.Millisecond * 10
177 clock := sturdyc.NewTestClock(time.Now())
178 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
179 sturdyc.WithNoContinuousEvictions(),
180 sturdyc.WithClock(clock),
181 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, retryInterval),
182 sturdyc.WithMissingRecordStorage(),
183 )
184
185 fetchObserver := NewFetchObserver(1)
186 fetchObserver.Err(sturdyc.ErrNotFound)
187 _, err := sturdyc.GetOrFetch(ctx, c, "1", fetchObserver.Fetch)
188 if !errors.Is(err, sturdyc.ErrMissingRecord) {
189 t.Fatalf("expected ErrMissingRecord, got %v", err)
190 }
191 <-fetchObserver.FetchCompleted
192 fetchObserver.AssertFetchCount(t, 1)
193 fetchObserver.Clear()
194
195 // Make the request again. It should trigger the refresh of the missing record to happen in the background.
196 clock.Add(maxRefreshDelay * 1)
197 fetchObserver.Response("1")
198 _, err = sturdyc.GetOrFetch(ctx, c, "1", fetchObserver.Fetch)
199 if !errors.Is(err, sturdyc.ErrMissingRecord) {
200 t.Fatalf("expected ErrMissingRecordCooldown, got %v", err)
201 }
202 <-fetchObserver.FetchCompleted
203 fetchObserver.AssertFetchCount(t, 2)
204
205 // The next time we call the cache, the record should be there.
206 val, err := sturdyc.GetOrFetch(ctx, c, "1", fetchObserver.Fetch)
207 if err != nil {
208 t.Fatalf("expected no error, got %v", err)
209 }
210 if val != "value1" {
211 t.Errorf("expected value to be value1, got %v", val)
212 }
213 fetchObserver.AssertFetchCount(t, 2)
214 }
215
216 func TestGetOrFetchMissingRecordError(t *testing.T) {
217 t.Parallel()
218
219 ctx := context.Background()
220 capacity := 5
221 numShards := 2
222 ttl := time.Minute
223 evictionPercentage := 10
224 c := sturdyc.New[any](capacity, numShards, ttl, evictionPercentage,
225 sturdyc.WithNoContinuousEvictions(),
226 sturdyc.WithMissingRecordStorage(),
227 )
228
229 // We'll make the fetch observer return an ErrNotFound error
230 // to indicate that the record should be stored as missing.
231 fetchObserver := NewFetchObserver(1)
232 fetchObserver.Err(sturdyc.ErrNotFound)
233 id := "1"
234
235 _, err := sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
236 if !errors.Is(err, sturdyc.ErrMissingRecord) {
237 t.Fatalf("expected missing record error, got %v", err)
238 }
239
240 <-fetchObserver.FetchCompleted
241 fetchObserver.AssertFetchCount(t, 1)
242 fetchObserver.Err(sturdyc.ErrNotFound)
243
244 // The second time we call Get, we should still get the missing record
245 _, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
246 if !errors.Is(err, sturdyc.ErrMissingRecord) {
247 t.Fatalf("expected missing record error, got %v", err)
248 }
249
250 // And only no more fetch should have been made
251 fetchObserver.AssertFetchCount(t, 1)
252 }
253
254 func TestGetOrFetchBatch(t *testing.T) {
255 t.Parallel()
256
257 ctx := context.Background()
258 c := sturdyc.New[string](5, 1, time.Minute, 30,
259 sturdyc.WithNoContinuousEvictions(),
260 )
261 fetchObserver := NewFetchObserver(1)
262
263 firstBatchOfIDs := []string{"1", "2", "3"}
264 fetchObserver.BatchResponse(firstBatchOfIDs)
265 _, err := sturdyc.GetOrFetchBatch(ctx, c, firstBatchOfIDs, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
266 if err != nil {
267 t.Fatalf("expected no error, got %v", err)
268 }
269
270 <-fetchObserver.FetchCompleted
271 fetchObserver.AssertRequestedRecords(t, firstBatchOfIDs)
272 fetchObserver.AssertFetchCount(t, 1)
273 fetchObserver.Clear()
274
275 // At this point, id 1, 2, and 3 should be in the sturdyc. Therefore, if we make a second
276 // request where we'll request item 1, 2, 3, and 4, we'll only expect that item 4 is fetched.
277 secondBatchOfIDs := []string{"1", "2", "3", "4"}
278 fetchObserver.BatchResponse([]string{"4"})
279 _, err = sturdyc.GetOrFetchBatch(ctx, c, secondBatchOfIDs, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
280 if err != nil {
281 t.Fatalf("expected no error, got %v", err)
282 }
283
284 <-fetchObserver.FetchCompleted
285 fetchObserver.AssertRequestedRecords(t, []string{"4"})
286 fetchObserver.AssertFetchCount(t, 2)
287 fetchObserver.Clear()
288
289 // The last scenario we want to test is for partial responses. This time, we'll request ids 2, 4, and 6. The item with
290 // id 6 isn't in our cache yet, so the fetch function should get invoked. However, we'll make the fetch function error.
291 // This should give us a ErrOnlyCachedRecords error, along with the records we could retrieve from the sturdyc.
292 thirdBatchOfIDs := []string{"2", "4", "6"}
293 fetchObserver.Err(errors.New("error"))
294 records, err := sturdyc.GetOrFetchBatch(ctx, c, thirdBatchOfIDs, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
295 <-fetchObserver.FetchCompleted
296 fetchObserver.AssertRequestedRecords(t, []string{"6"})
297 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
298 t.Errorf("expected ErrPartialBatchResponse, got %v", err)
299 }
300 if len(records) != 2 {
301 t.Errorf("expected to get the two records we had cached, got %v", len(records))
302 }
303 }
304
305 func TestBatchGetOrFetchNilMapMissingRecords(t *testing.T) {
306 t.Parallel()
307
308 ctx := context.Background()
309 capacity := 5
310 numShards := 1
311 ttl := time.Minute
312 evictionPercentage := 50
313 minRefreshDelay := time.Second
314 maxRefreshDelay := time.Second * 2
315 synchronousRefreshDelay := time.Second * 10
316 retryInterval := time.Second
317 clock := sturdyc.NewTestClock(time.Now())
318 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
319 sturdyc.WithNoContinuousEvictions(),
320 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, retryInterval),
321 sturdyc.WithMissingRecordStorage(),
322 sturdyc.WithClock(clock),
323 )
324
325 fetchObserver := NewFetchObserver(1)
326 ids := []string{"1", "2", "3", "4"}
327 records, err := sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
328 if err != nil {
329 t.Fatalf("expected no error, got %v", err)
330 }
331 if len(records) != 0 {
332 t.Fatalf("expected no records, got %v", records)
333 }
334 <-fetchObserver.FetchCompleted
335 fetchObserver.AssertRequestedRecords(t, ids)
336 fetchObserver.AssertFetchCount(t, 1)
337
338 // The request didn't return any records, and we have configured the cache to
339 // store these ids as cache misses. Hence, performing the request again,
340 // should not result in another call before the refresh delay has passed.
341 clock.Add(minRefreshDelay - 1)
342 records, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
343 if err != nil {
344 t.Fatalf("expected no error, got %v", err)
345 }
346 if len(records) != 0 {
347 t.Fatalf("expected no records, got %v", records)
348 }
349 time.Sleep(time.Millisecond * 10)
350 fetchObserver.AssertRequestedRecords(t, ids)
351 fetchObserver.AssertFetchCount(t, 1)
352 }
353
354 func TestGetOrFetchBatchRetries(t *testing.T) {
355 t.Parallel()
356
357 ctx := context.Background()
358 capacity := 5
359 numShards := 1
360 ttl := time.Hour * 24
361 evictionPercentage := 10
362 minRefreshDelay := time.Hour
363 maxRefreshDelay := time.Hour * 2
364 synchronousRefreshDelay := time.Hour * 4
365 retryInterval := time.Second
366 clock := sturdyc.NewTestClock(time.Now())
367 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
368 sturdyc.WithNoContinuousEvictions(),
369 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, retryInterval),
370 sturdyc.WithMissingRecordStorage(),
371 sturdyc.WithClock(clock),
372 )
373 fetchObserver := NewFetchObserver(6)
374
375 ids := []string{"1", "2", "3"}
376 fetchObserver.BatchResponse(ids)
377
378 // Assert that all records were requested, and that we retrieved each one of them.
379 _, err := sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
380 if err != nil {
381 t.Fatalf("expected no error, got %v", err)
382 }
383
384 <-fetchObserver.FetchCompleted
385 fetchObserver.AssertRequestedRecords(t, ids)
386 fetchObserver.AssertFetchCount(t, 1)
387 fetchObserver.Clear()
388
389 // Now, we'll move the clock passed the refresh delay which should make the
390 // next call to GetOrFetchBatch result in a call to refresh the record.
391 clock.Add(maxRefreshDelay + 1)
392 fetchObserver.Err(errors.New("error"))
393 _, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
394 if err != nil {
395 t.Fatalf("expected no error, got %v", err)
396 }
397
398 <-fetchObserver.FetchCompleted
399 fetchObserver.AssertRequestedRecords(t, ids)
400 fetchObserver.AssertFetchCount(t, 2)
401
402 // Next, we'll assert that the retries grows exponentially. Even though we're
403 // making 100 requests with 1 second between them, we only expect 6 calls to
404 // go through.
405 for i := 0; i < 100; i++ {
406 clock.Add(retryInterval)
407 sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
408 }
409 for i := 0; i < 6; i++ {
410 <-fetchObserver.FetchCompleted
411 }
412 fetchObserver.AssertFetchCount(t, 8)
413 }
414
415 func TestBatchGetOrFetchOnlyCachedRecordsErr(t *testing.T) {
416 t.Parallel()
417
418 ctx := context.Background()
419 capacity := 5
420 numShards := 1
421 ttl := time.Minute
422 evictionPercentage := 10
423 clock := sturdyc.NewTestClock(time.Now())
424 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
425 sturdyc.WithNoContinuousEvictions(),
426 sturdyc.WithClock(clock),
427 )
428 fetchObserver := NewFetchObserver(1)
429
430 // We'll start by fetching a couple of ids without any errors to fill the sturdyc.
431 ids := []string{"1", "2", "3", "4"}
432 fetchObserver.BatchResponse(ids)
433 _, firstBatchErr := sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
434 if firstBatchErr != nil {
435 t.Errorf("expected no error, got %v", firstBatchErr)
436 }
437
438 <-fetchObserver.FetchCompleted
439 fetchObserver.AssertRequestedRecords(t, ids)
440 fetchObserver.AssertFetchCount(t, 1)
441 fetchObserver.Clear()
442
443 // Now, we'll append "5" to our slice of ids. After that we'll try to fetch the
444 // records again. This time with a BatchFn that returns an error. That should give
445 // us a ErrOnlyCachedRecords error along with the records we had in the sturdyc.
446 // This allows the caller to decide if they want to proceed or not.
447 ids = append(ids, "5")
448 fetchObserver.Err(errors.New("error"))
449 records, secondBatchErr := sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
450
451 if !errors.Is(secondBatchErr, sturdyc.ErrOnlyCachedRecords) {
452 t.Errorf("expected ErrPartialBatchResponse, got %v", secondBatchErr)
453 }
454 // We should have a record for every id except the last one.
455 if len(records) != len(ids)-1 {
456 t.Errorf("expected to get %v records, got %v", len(ids)-1, len(records))
457 }
458
459 <-fetchObserver.FetchCompleted
460 fetchObserver.AssertRequestedRecords(t, []string{"5"})
461 fetchObserver.AssertFetchCount(t, 2)
462 }
463
464 func TestGetOrFetchBatchStampedeProtection(t *testing.T) {
465 t.Parallel()
466
467 // We're going to fetch the same list of ids in 1000 goroutines.
468 numGoroutines := 1000
469 ctx := context.Background()
470 capacity := 10
471 shards := 2
472 ttl := time.Second * 2
473 evictionPercentage := 5
474 clock := sturdyc.NewTestClock(time.Now())
475 minRefreshDelay := time.Millisecond * 500
476 maxRefreshDelay := time.Millisecond * 1000
477 synchronousRefreshDelay := time.Millisecond * 1500
478 refreshRetryInterval := time.Millisecond * 10
479 c := sturdyc.New[string](capacity, shards, ttl, evictionPercentage,
480 sturdyc.WithNoContinuousEvictions(),
481 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
482 sturdyc.WithMissingRecordStorage(),
483 sturdyc.WithClock(clock),
484 sturdyc.WithMetrics(newTestMetricsRecorder(shards)),
485 )
486
487 ids := []string{"1", "2", "3"}
488 fetchObserver := NewFetchObserver(1000)
489 fetchObserver.BatchResponse(ids)
490
491 _, err := sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
492 if err != nil {
493 t.Fatalf("expected no error, got %v", err)
494 }
495
496 <-fetchObserver.FetchCompleted
497 fetchObserver.AssertRequestedRecords(t, ids)
498 fetchObserver.AssertFetchCount(t, 1)
499
500 // Set the clock to be just before the min cache refresh threshold.
501 // This should not be enough to make the cache call our fetchFn.
502 clock.Add(minRefreshDelay - 1)
503 _, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
504 if err != nil {
505 t.Fatalf("expected no error, got %v", err)
506 }
507
508 // We don't expect fetchObserver.Fetch to have been called. Therfore, we'll
509 // sleep for a brief duration and asser that the fetch count is still 1.
510 time.Sleep(time.Millisecond * 10)
511 fetchObserver.AssertFetchCount(t, 1)
512
513 // Now, let's go past the threshold. This should make the next GetOrFetchBatch
514 // call schedule a refresh in the background, and with that we're going to
515 // test that the stampede protection works as intended. Invoking it from 1000
516 // goroutines at the same time should not make us schedule multiple refreshes.
517 clock.Add((maxRefreshDelay - minRefreshDelay) + 1)
518 var wg sync.WaitGroup
519 wg.Add(numGoroutines)
520 for i := 0; i < numGoroutines; i++ {
521 go func() {
522 defer wg.Done()
523 _, goroutineErr := sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
524 if goroutineErr != nil {
525 panic(goroutineErr)
526 }
527 }()
528 }
529 wg.Wait()
530
531 // Even though we called GetOrFetch 1000 times, it should only result in a
532 // maximum of 3 outgoing requests. Most likely, it should just be one
533 // additional request but without having a top level lock in GetOrFetchBatch we
534 // can't guarantee that the first goroutine moves the refreshAt of all 3 ids.
535 // The first goroutine might get a lock for the first index, and then get paused.
536 // During that time a second goroutine could have refreshed id 2 and 3.
537 <-fetchObserver.FetchCompleted
538 fetchObserver.AssertMaxFetchCount(t, 4)
539 }
540
541 func TestGetOrFetchDeletesRecordsThatHaveBeenRemovedAtTheSource(t *testing.T) {
542 t.Parallel()
543
544 ctx := context.Background()
545 capacity := 1000
546 numShards := 10
547 ttl := time.Hour
548 evictionPercentage := 10
549 clock := sturdyc.NewTestClock(time.Now())
550 minRefreshDelay := time.Millisecond * 500
551 maxRefreshDelay := time.Second
552 synchronousRefreshDelay := time.Minute
553 refreshRetryInterval := time.Millisecond * 10
554
555 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
556 sturdyc.WithNoContinuousEvictions(),
557 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
558 sturdyc.WithClock(clock),
559 )
560
561 id := "1"
562 fetchObserver := NewFetchObserver(1)
563 fetchObserver.Response(id)
564
565 c.GetOrFetch(ctx, id, fetchObserver.Fetch)
566 <-fetchObserver.FetchCompleted
567 fetchObserver.AssertFetchCount(t, 1)
568 time.Sleep(time.Millisecond * 10)
569
570 if c.Size() != 1 {
571 t.Errorf("expected cache to have 1 records, got %v", c.Size())
572 }
573
574 // Now we're going to go past the refresh delay, and return an error
575 // that indicates that the record has been deleted at the source.
576 fetchObserver.Clear()
577 fetchObserver.Err(sturdyc.ErrNotFound)
578 clock.Add(maxRefreshDelay + 1)
579 c.GetOrFetch(ctx, id, fetchObserver.Fetch)
580 <-fetchObserver.FetchCompleted
581 time.Sleep(time.Millisecond * 10)
582
583 if c.Size() != 0 {
584 t.Errorf("expected cache to have 0 records, got %v", c.Size())
585 }
586 }
587
588 func TestGetOrFetchConvertsDeletedRecordsToMissingRecords(t *testing.T) {
589 t.Parallel()
590
591 ctx := context.Background()
592 capacity := 1000
593 numShards := 10
594 ttl := time.Hour
595 evictionPercentage := 10
596 clock := sturdyc.NewTestClock(time.Now())
597 minRefreshDelay := time.Millisecond * 500
598 maxRefreshDelay := time.Second
599 synchronousRefreshDelay := time.Minute
600 refreshRetryInterval := time.Millisecond * 10
601
602 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
603 sturdyc.WithNoContinuousEvictions(),
604 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
605 sturdyc.WithMissingRecordStorage(),
606 sturdyc.WithClock(clock),
607 )
608
609 id := "1"
610 fetchObserver := NewFetchObserver(1)
611 fetchObserver.Response(id)
612
613 c.GetOrFetch(ctx, id, fetchObserver.Fetch)
614 <-fetchObserver.FetchCompleted
615 fetchObserver.AssertFetchCount(t, 1)
616 time.Sleep(time.Millisecond * 10)
617
618 if c.Size() != 1 {
619 t.Errorf("expected cache to have 1 records, got %v", c.Size())
620 }
621 if _, ok := c.Get(id); !ok {
622 t.Errorf("expected item to exist in the cache")
623 }
624
625 // Now we're going to go past the refresh delay, and return an error
626 // that indicates that the record should now be stored as missing.
627 fetchObserver.Clear()
628 fetchObserver.Err(sturdyc.ErrNotFound)
629 clock.Add(maxRefreshDelay + 1)
630 c.GetOrFetch(ctx, id, fetchObserver.Fetch)
631 <-fetchObserver.FetchCompleted
632 time.Sleep(time.Millisecond * 10)
633
634 if c.Size() != 1 {
635 t.Errorf("expected cache to have 1 record, got %v", c.Size())
636 }
637 if _, ok := c.Get(id); ok {
638 t.Errorf("expected item to not be returned by the Get call because it's a missing record")
639 }
640 }
641
642 func TestGetOrFetchBatchDeletesRecordsThatHaveBeenRemovedAtTheSource(t *testing.T) {
643 t.Parallel()
644
645 ctx := context.Background()
646 capacity := 1000
647 numShards := 10
648 ttl := time.Hour
649 evictionPercentage := 10
650 clock := sturdyc.NewTestClock(time.Now())
651 minRefreshDelay := time.Millisecond * 500
652 maxRefreshDelay := time.Second
653 synchronousRefreshDelay := time.Minute
654 refreshRetryInterval := time.Millisecond * 10
655
656 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
657 sturdyc.WithNoContinuousEvictions(),
658 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
659 sturdyc.WithClock(clock),
660 )
661
662 ids := []string{"1", "2", "3", "4", "5"}
663 fetchObserver := NewFetchObserver(1)
664 fetchObserver.BatchResponse(ids)
665
666 c.GetOrFetchBatch(ctx, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
667 <-fetchObserver.FetchCompleted
668 fetchObserver.AssertFetchCount(t, 1)
669 time.Sleep(time.Millisecond * 10)
670
671 if c.Size() != 5 {
672 t.Errorf("expected cache to have 5 records, got %v", c.Size())
673 }
674
675 // Now we're going to go past the refresh delay, and
676 // only return the first 3 records from the source.
677 fetchObserver.BatchResponse([]string{"1", "2", "3"})
678 clock.Add(maxRefreshDelay + 1)
679 c.GetOrFetchBatch(ctx, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
680 <-fetchObserver.FetchCompleted
681 fetchObserver.AssertFetchCount(t, 2)
682 time.Sleep(time.Millisecond * 10)
683
684 // The other two records should have been deleted.
685 if c.Size() != 3 {
686 t.Errorf("expected cache to have 3 records, got %v", c.Size())
687 }
688 }
689
690 func TestGetFetchBatchConvertsDeletedRecordsToMissingRecords(t *testing.T) {
691 t.Parallel()
692
693 ctx := context.Background()
694 capacity := 1000
695 numShards := 10
696 ttl := time.Hour
697 evictionPercentage := 10
698 clock := sturdyc.NewTestClock(time.Now())
699 minRefreshDelay := time.Millisecond * 500
700 maxRefreshDelay := time.Second
701 synchronousRefreshDelay := time.Minute
702 refreshRetryInterval := time.Millisecond * 10
703
704 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
705 sturdyc.WithNoContinuousEvictions(),
706 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
707 sturdyc.WithMissingRecordStorage(),
708 sturdyc.WithClock(clock),
709 )
710
711 ids := []string{"1", "2", "3"}
712 fetchObserver := NewFetchObserver(1)
713 fetchObserver.BatchResponse(ids)
714
715 c.GetOrFetchBatch(ctx, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
716 <-fetchObserver.FetchCompleted
717 fetchObserver.AssertFetchCount(t, 1)
718 time.Sleep(time.Millisecond * 10)
719
720 if c.Size() != 3 {
721 t.Errorf("expected cache to have 3 records, got %v", c.Size())
722 }
723
724 if _, ok := c.Get(c.BatchKeyFn("item")("3")); !ok {
725 t.Errorf("expected key3 to exist in the cache")
726 }
727
728 // Now we're going to go past the refresh delay, and
729 // only return the first 2 records from the source.
730 fetchObserver.BatchResponse([]string{"1", "2"})
731 clock.Add(maxRefreshDelay + 1)
732 c.GetOrFetchBatch(ctx, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
733 <-fetchObserver.FetchCompleted
734 fetchObserver.AssertFetchCount(t, 2)
735 time.Sleep(time.Millisecond * 10)
736
737 // The record should now exist as a missing record. Hence, the size should still be
738 // 3. However, we should not be able to pull this item out of the cache using Get.
739 if c.Size() != 3 {
740 t.Errorf("expected cache to have 3 records, got %v", c.Size())
741 }
742 if _, ok := c.Get(c.BatchKeyFn("item")("3")); ok {
743 t.Errorf("expected key3 to not be returned by Get")
744 }
745 }
746
747 func TestGetFetchSynchronousRefreshes(t *testing.T) {
748 t.Parallel()
749
750 ctx := context.Background()
751 capacity := 1000
752 numShards := 10
753 ttl := time.Hour
754 evictionPercentage := 10
755 minBackgroundRefreshDelay := time.Second
756 maxBackgroundRefreshDelay := time.Second * 2
757 synchronousRefreshDelay := time.Second * 10
758 retryInterval := time.Millisecond * 10
759 clock := sturdyc.NewTestClock(time.Now())
760
761 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
762 sturdyc.WithNoContinuousEvictions(),
763 sturdyc.WithEarlyRefreshes(minBackgroundRefreshDelay, maxBackgroundRefreshDelay, synchronousRefreshDelay, retryInterval),
764 sturdyc.WithMissingRecordStorage(),
765 sturdyc.WithClock(clock),
766 )
767
768 id := "1"
769 fetchObserver := NewFetchObserver(1)
770 fetchObserver.Response(id)
771
772 res, err := sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
773 <-fetchObserver.FetchCompleted
774 if err != nil {
775 t.Fatalf("expected no error, got %v", err)
776 }
777 if res != "value1" {
778 t.Errorf("expected value1, got %v", res)
779 }
780
781 // Now, let's make the fetchObserver return a new value, and only move the
782 // clock enough to warrant a background refresh. The value we get should
783 // still be the same as the previous one because the refresh happens in the
784 // background.
785 fetchObserver.Clear()
786 fetchObserver.Response("2")
787 clock.Add(maxBackgroundRefreshDelay + 1)
788 res, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
789 <-fetchObserver.FetchCompleted
790 if err != nil {
791 t.Fatalf("expected no error, got %v", err)
792 }
793 if res != "value1" {
794 t.Errorf("expected value1, got %v", res)
795 }
796
797 // Now we can wait for the background refresh to complete, and then assert
798 // that the next time we ask for this ID we'll get the new value.
799 time.Sleep(time.Millisecond * 100)
800 res, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
801 if err != nil {
802 t.Fatalf("expected no error, got %v", err)
803 }
804 if res != "value2" {
805 t.Errorf("expected value2, got %v", res)
806 }
807
808 // Let's do this again, but this time we'll move the clock passed the synchronous refresh delay.
809 // This should result in a synchronous refresh and we should get the new value right away.
810 fetchObserver.Clear()
811 fetchObserver.Response("3")
812 clock.Add(synchronousRefreshDelay + 1)
813 res, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
814 <-fetchObserver.FetchCompleted
815 if err != nil {
816 t.Fatalf("expected no error, got %v", err)
817 }
818 if res != "value3" {
819 t.Errorf("expected value3, got %v", res)
820 }
821 fetchObserver.AssertFetchCount(t, 3)
822 }
823
824 func TestGetFetchBatchSynchronousRefreshes(t *testing.T) {
825 t.Parallel()
826
827 ctx := context.Background()
828 capacity := 1000
829 numShards := 10
830 ttl := time.Hour
831 evictionPercentage := 10
832 minBackgroundRefreshDelay := time.Second
833 maxBackgroundRefreshDelay := time.Second * 2
834 synchronousRefreshDelay := time.Second * 10
835 retryInterval := time.Millisecond * 10
836 clock := sturdyc.NewTestClock(time.Now())
837
838 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
839 sturdyc.WithNoContinuousEvictions(),
840 sturdyc.WithEarlyRefreshes(minBackgroundRefreshDelay, maxBackgroundRefreshDelay, synchronousRefreshDelay, retryInterval),
841 sturdyc.WithMissingRecordStorage(),
842 sturdyc.WithClock(clock),
843 )
844
845 firstBatchOfIDs := []string{"1", "2", "3"}
846 fetchObserver := NewFetchObserver(2)
847 fetchObserver.BatchResponse(firstBatchOfIDs)
848
849 _, err := sturdyc.GetOrFetchBatch(ctx, c, firstBatchOfIDs, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
850 <-fetchObserver.FetchCompleted
851 if err != nil {
852 t.Fatalf("expected no error, got %v", err)
853 }
854
855 fetchObserver.AssertRequestedRecords(t, firstBatchOfIDs)
856 fetchObserver.AssertFetchCount(t, 1)
857
858 // Now, let's move the clock 5 seconds and then request another batch of IDs.
859 clock.Add(time.Second * 5)
860 secondBatchOfIDs := []string{"4", "5", "6"}
861 fetchObserver.BatchResponse(secondBatchOfIDs)
862 _, err = sturdyc.GetOrFetchBatch(ctx, c, secondBatchOfIDs, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
863 <-fetchObserver.FetchCompleted
864 if err != nil {
865 t.Fatalf("expected no error, got %v", err)
866 }
867
868 fetchObserver.AssertRequestedRecords(t, secondBatchOfIDs)
869 fetchObserver.AssertFetchCount(t, 2)
870
871 // At this point, we should have IDs 1-3 in the cache that are 5 seconds
872 // old, and IDs 4-6 that are completely new. If we now move the clock another
873 // 5 seconds, we should reach the point where IDs 1-3 are due for a
874 // synchronous refresh, and IDs 4-6 are due for a background refresh.
875 clock.Add((time.Second * 5) + 1)
876
877 fullBatchOfIDs := []string{"1", "2", "3", "4", "5", "6"}
878 fetchObserver.BatchResponse(firstBatchOfIDs)
879 _, err = sturdyc.GetOrFetchBatch(ctx, c, fullBatchOfIDs, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
880 // We'll assert that two refreshes happened. One synchronous refresh and one background refresh.
881 <-fetchObserver.FetchCompleted
882 <-fetchObserver.FetchCompleted
883 if err != nil {
884 t.Fatalf("expected no error, got %v", err)
885 }
886 fetchObserver.AssertFetchCount(t, 4)
887 }
888
889 func TestGetFetchSynchronousRefreshConvertsToMissingRecord(t *testing.T) {
890 t.Parallel()
891
892 ctx := context.Background()
893 capacity := 1000
894 numShards := 10
895 ttl := time.Hour
896 evictionPercentage := 10
897 minBackgroundRefreshDelay := time.Second
898 maxBackgroundRefreshDelay := time.Second * 2
899 synchronousRefreshDelay := time.Second * 10
900 retryInterval := time.Millisecond * 10
901 clock := sturdyc.NewTestClock(time.Now())
902
903 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
904 sturdyc.WithNoContinuousEvictions(),
905 sturdyc.WithEarlyRefreshes(minBackgroundRefreshDelay, maxBackgroundRefreshDelay, synchronousRefreshDelay, retryInterval),
906 sturdyc.WithMissingRecordStorage(),
907 sturdyc.WithClock(clock),
908 )
909
910 id := "1"
911 fetchObserver := NewFetchObserver(1)
912 fetchObserver.Response(id)
913
914 res, err := sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
915 <-fetchObserver.FetchCompleted
916 if err != nil {
917 t.Fatalf("expected no error, got %v", err)
918 }
919 if res != "value1" {
920 t.Errorf("expected value1, got %v", res)
921 }
922
923 // Here, we'll set up the next request to return a not found error. Given
924 // that we have missing record storage enabled, we'll expect that the
925 // synchronous refresh returns a sturdyc.MissingRecord error.
926 fetchObserver.Clear()
927 fetchObserver.Err(sturdyc.ErrNotFound)
928 clock.Add(synchronousRefreshDelay + 1)
929
930 _, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
931 if !errors.Is(err, sturdyc.ErrMissingRecord) {
932 t.Fatalf("expected ErrMissingRecord, got %v", err)
933 }
934 <-fetchObserver.FetchCompleted
935 fetchObserver.AssertFetchCount(t, 2)
936 if c.Size() != 1 {
937 t.Errorf("expected cache size to be 1, got %d", c.Size())
938 }
939
940 // Let's also make sure that the record can reappear again.
941 fetchObserver.Clear()
942 fetchObserver.Response("2")
943 clock.Add(synchronousRefreshDelay + 1)
944
945 res, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
946 <-fetchObserver.FetchCompleted
947 if err != nil {
948 t.Fatalf("expected no error, got %v", err)
949 }
950 if res != "value2" {
951 t.Errorf("expected value2, got %v", res)
952 }
953 fetchObserver.AssertFetchCount(t, 3)
954 }
955
956 func TestGetFetchBatchSynchronousRefreshConvertsToMissingRecord(t *testing.T) {
957 t.Parallel()
958
959 ctx := context.Background()
960 capacity := 1000
961 numShards := 10
962 ttl := time.Hour
963 evictionPercentage := 10
964 minBackgroundRefreshDelay := time.Second
965 maxBackgroundRefreshDelay := time.Second * 2
966 synchronousRefreshDelay := time.Second * 10
967 retryInterval := time.Millisecond * 10
968 clock := sturdyc.NewTestClock(time.Now())
969
970 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
971 sturdyc.WithNoContinuousEvictions(),
972 sturdyc.WithEarlyRefreshes(minBackgroundRefreshDelay, maxBackgroundRefreshDelay, synchronousRefreshDelay, retryInterval),
973 sturdyc.WithMissingRecordStorage(),
974 sturdyc.WithClock(clock),
975 )
976
977 ids := []string{"1", "2", "3", "4", "5", "6"}
978 fetchObserver := NewFetchObserver(1)
979 fetchObserver.BatchResponse(ids)
980
981 res, err := sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
982 <-fetchObserver.FetchCompleted
983 if err != nil {
984 t.Fatalf("expected no error, got %v", err)
985 }
986 if len(res) != 6 {
987 t.Fatalf("expected 6 records, got %d", len(res))
988 }
989 if c.Size() != 6 {
990 t.Errorf("expected cache size to be 6, got %d", c.Size())
991 }
992 fetchObserver.AssertRequestedRecords(t, ids)
993 fetchObserver.AssertFetchCount(t, 1)
994
995 // Now, let's move the clock passed the synchronous refresh delay,
996 // and make the refresh only return values for IDs 1-3.
997 clock.Add(synchronousRefreshDelay + 1)
998 fetchObserver.Clear()
999 fetchObserver.BatchResponse([]string{"1", "2", "3"})
1000
1001 res, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1002 <-fetchObserver.FetchCompleted
1003 if err != nil {
1004 t.Fatalf("expected no error, got %v", err)
1005 }
1006 if len(res) != 3 {
1007 t.Fatalf("expected 3 records, got %d", len(res))
1008 }
1009 if c.Size() != 6 {
1010 t.Errorf("expected cache size to be 6, got %d", c.Size())
1011 }
1012 fetchObserver.AssertRequestedRecords(t, ids)
1013 fetchObserver.AssertFetchCount(t, 2)
1014
1015 // Next, let's assert that the records were successfully stored as missing.
1016 clock.Add(minBackgroundRefreshDelay - 1)
1017 res, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1018 if err != nil {
1019 t.Fatalf("expected no error, got %v", err)
1020 }
1021 if len(res) != 3 {
1022 t.Fatalf("expected 3 records, got %d", len(res))
1023 }
1024 if c.Size() != 6 {
1025 t.Errorf("expected cache size to be 6, got %d", c.Size())
1026 }
1027
1028 // And finally, let's make sure that the records can reappear again.
1029 clock.Add(synchronousRefreshDelay)
1030 fetchObserver.Clear()
1031 fetchObserver.BatchResponse(ids)
1032
1033 res, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1034 <-fetchObserver.FetchCompleted
1035 if err != nil {
1036 t.Fatalf("expected no error, got %v", err)
1037 }
1038 if len(res) != 6 {
1039 t.Fatalf("expected 6 records, got %d", len(res))
1040 }
1041 if c.Size() != 6 {
1042 t.Errorf("expected cache size to be 6, got %d", c.Size())
1043 }
1044 fetchObserver.AssertRequestedRecords(t, ids)
1045 }
1046
1047 func TestGetFetchSynchronousRefreshDeletion(t *testing.T) {
1048 t.Parallel()
1049
1050 ctx := context.Background()
1051 capacity := 1000
1052 numShards := 10
1053 ttl := time.Hour
1054 evictionPercentage := 10
1055 minBackgroundRefreshDelay := time.Second
1056 maxBackgroundRefreshDelay := time.Second * 2
1057 synchronousRefreshDelay := time.Second * 10
1058 retryInterval := time.Millisecond * 10
1059 clock := sturdyc.NewTestClock(time.Now())
1060
1061 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
1062 sturdyc.WithNoContinuousEvictions(),
1063 sturdyc.WithEarlyRefreshes(minBackgroundRefreshDelay, maxBackgroundRefreshDelay, synchronousRefreshDelay, retryInterval),
1064 sturdyc.WithClock(clock),
1065 )
1066
1067 id := "1"
1068 fetchObserver := NewFetchObserver(1)
1069 fetchObserver.Response(id)
1070
1071 res, err := sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
1072 <-fetchObserver.FetchCompleted
1073 if err != nil {
1074 t.Fatalf("expected no error, got %v", err)
1075 }
1076 if res != "value1" {
1077 t.Errorf("expected value1, got %v", res)
1078 }
1079
1080 // Here, we'll set up the next request to return a not found error. Given
1081 // that we have missing record storage enabled, we'll expect that the
1082 // synchronous refresh returns a sturdyc.MissingRecord error.
1083 fetchObserver.Clear()
1084 fetchObserver.Err(sturdyc.ErrNotFound)
1085 clock.Add(synchronousRefreshDelay + 1)
1086
1087 _, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
1088 if !errors.Is(err, sturdyc.ErrNotFound) {
1089 t.Fatalf("expected ErrNotFound, got %v", err)
1090 }
1091 <-fetchObserver.FetchCompleted
1092 fetchObserver.AssertFetchCount(t, 2)
1093 if c.Size() != 0 {
1094 t.Errorf("expected cache size to be 0, got %d", c.Size())
1095 }
1096
1097 // Let's also make sure that the record can reappear again.
1098 clock.Add(synchronousRefreshDelay)
1099 fetchObserver.Clear()
1100 fetchObserver.Response(id)
1101 res, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
1102 <-fetchObserver.FetchCompleted
1103 if err != nil {
1104 t.Fatalf("expected no error, got %v", err)
1105 }
1106 if res != "value1" {
1107 t.Errorf("expected value1, got %v", res)
1108 }
1109 if c.Size() != 1 {
1110 t.Errorf("expected cache size to be 1, got %d", c.Size())
1111 }
1112 fetchObserver.AssertFetchCount(t, 3)
1113 }
1114
1115 func TestGetFetchBatchSynchronousRefreshDeletion(t *testing.T) {
1116 t.Parallel()
1117
1118 ctx := context.Background()
1119 capacity := 1000
1120 numShards := 10
1121 ttl := time.Hour
1122 evictionPercentage := 10
1123 minBackgroundRefreshDelay := time.Second
1124 maxBackgroundRefreshDelay := time.Second * 2
1125 synchronousRefreshDelay := time.Second * 10
1126 retryInterval := time.Millisecond * 10
1127 clock := sturdyc.NewTestClock(time.Now())
1128
1129 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
1130 sturdyc.WithNoContinuousEvictions(),
1131 sturdyc.WithEarlyRefreshes(minBackgroundRefreshDelay, maxBackgroundRefreshDelay, synchronousRefreshDelay, retryInterval),
1132 sturdyc.WithClock(clock),
1133 )
1134
1135 ids := []string{"1", "2", "3", "4", "5", "6"}
1136 fetchObserver := NewFetchObserver(1)
1137 fetchObserver.BatchResponse(ids)
1138
1139 res, err := sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1140 <-fetchObserver.FetchCompleted
1141 if err != nil {
1142 t.Fatalf("expected no error, got %v", err)
1143 }
1144 if len(res) != 6 {
1145 t.Fatalf("expected 6 records, got %d", len(res))
1146 }
1147 if c.Size() != 6 {
1148 t.Errorf("expected cache size to be 6, got %d", c.Size())
1149 }
1150 fetchObserver.AssertRequestedRecords(t, ids)
1151 fetchObserver.AssertFetchCount(t, 1)
1152
1153 // Now, let's move the clock passed the synchronous refresh delay,
1154 // and make the refresh only return values for IDs 1-3.
1155 clock.Add(synchronousRefreshDelay + 1)
1156 fetchObserver.Clear()
1157 fetchObserver.BatchResponse([]string{"1", "2", "3"})
1158
1159 res, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1160 <-fetchObserver.FetchCompleted
1161 if err != nil {
1162 t.Fatalf("expected no error, got %v", err)
1163 }
1164 if len(res) != 3 {
1165 t.Fatalf("expected 3 records, got %d", len(res))
1166 }
1167 // IDs 4-6 should not have been deleted.
1168 if c.Size() != 3 {
1169 t.Errorf("expected cache size to be 3, got %d", c.Size())
1170 }
1171 fetchObserver.AssertRequestedRecords(t, ids)
1172 fetchObserver.AssertFetchCount(t, 2)
1173
1174 // Next, let's assert that the records doesn't reappear the next time we ask for the same IDs.
1175 fetchObserver.Clear()
1176 fetchObserver.BatchResponse([]string{})
1177 clock.Add(minBackgroundRefreshDelay - 1)
1178
1179 res, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1180 <-fetchObserver.FetchCompleted
1181 if err != nil {
1182 t.Fatalf("expected no error, got %v", err)
1183 }
1184 if len(res) != 3 {
1185 t.Fatalf("expected 3 records, got %d", len(res))
1186 }
1187 if c.Size() != 3 {
1188 t.Errorf("expected cache size to be 3, got %d", c.Size())
1189 }
1190 // IDs 4-6 should have been deleted, hence we should get another outgoing request.
1191 fetchObserver.AssertFetchCount(t, 3)
1192 fetchObserver.AssertRequestedRecords(t, []string{"4", "5", "6"})
1193
1194 // Finally, let's make sure that the records can reappear again.
1195 clock.Add(synchronousRefreshDelay)
1196 fetchObserver.Clear()
1197 fetchObserver.BatchResponse(ids)
1198
1199 res, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1200 if err != nil {
1201 t.Fatalf("expected no error, got %v", err)
1202 }
1203 if len(res) != 6 {
1204 t.Fatalf("expected 6 records, got %d", len(res))
1205 }
1206 if c.Size() != 6 {
1207 t.Errorf("expected cache size to be 6, got %d", c.Size())
1208 }
1209 fetchObserver.AssertRequestedRecords(t, ids)
1210 fetchObserver.AssertFetchCount(t, 4)
1211 }
1212
1213 func TestGetFetchSynchronousRefreshFailureGivesLatestValue(t *testing.T) {
1214 t.Parallel()
1215
1216 ctx := context.Background()
1217 capacity := 1000
1218 numShards := 10
1219 ttl := time.Hour
1220 evictionPercentage := 10
1221 minBackgroundRefreshDelay := time.Second
1222 maxBackgroundRefreshDelay := time.Second * 2
1223 synchronousRefreshDelay := time.Second * 10
1224 retryInterval := time.Millisecond * 10
1225 clock := sturdyc.NewTestClock(time.Now())
1226
1227 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
1228 sturdyc.WithNoContinuousEvictions(),
1229 sturdyc.WithEarlyRefreshes(minBackgroundRefreshDelay, maxBackgroundRefreshDelay, synchronousRefreshDelay, retryInterval),
1230 sturdyc.WithMissingRecordStorage(),
1231 sturdyc.WithClock(clock),
1232 )
1233
1234 id := "1"
1235 fetchObserver := NewFetchObserver(1)
1236 fetchObserver.Response(id)
1237
1238 res, err := sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
1239 <-fetchObserver.FetchCompleted
1240 if err != nil {
1241 t.Fatalf("expected no error, got %v", err)
1242 }
1243 if res != "value1" {
1244 t.Errorf("expected value1, got %v", res)
1245 }
1246
1247 // Here, we'll set up the next request to return an error. Given that
1248 // we still have this key cached, we expect the cache to give us an
1249 // ErrOnlyCachedRecords error along with the cached value.
1250 fetchObserver.Clear()
1251 fetchObserver.Err(errors.New("error"))
1252 clock.Add(synchronousRefreshDelay + 1)
1253
1254 res, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
1255 <-fetchObserver.FetchCompleted
1256 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
1257 t.Fatalf("expected ErrOnlyCachedRecords, got %v", err)
1258 }
1259 if res != "value1" {
1260 t.Errorf("expected value1, got %v", res)
1261 }
1262 fetchObserver.AssertFetchCount(t, 2)
1263
1264 // Now, requesting the same ID again should result in another synchronous
1265 // refresh without us having to move the clock. Let's set this one up to return
1266 // an actual value.
1267 fetchObserver.Clear()
1268 fetchObserver.Response("2")
1269
1270 res, err = sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
1271 <-fetchObserver.FetchCompleted
1272 if err != nil {
1273 t.Fatalf("expected no error, got %v", err)
1274 }
1275 if res != "value2" {
1276 t.Errorf("expected value2, got %v", res)
1277 }
1278 fetchObserver.AssertFetchCount(t, 3)
1279 }
1280
1281 func TestGetFetchBatchSynchronousRefreshFailureGivesLatestValue(t *testing.T) {
1282 t.Parallel()
1283
1284 ctx := context.Background()
1285 capacity := 1000
1286 numShards := 10
1287 ttl := time.Hour
1288 evictionPercentage := 10
1289 minBackgroundRefreshDelay := time.Second
1290 maxBackgroundRefreshDelay := time.Second * 2
1291 synchronousRefreshDelay := time.Second * 10
1292 retryInterval := time.Millisecond * 10
1293 clock := sturdyc.NewTestClock(time.Now())
1294
1295 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
1296 sturdyc.WithNoContinuousEvictions(),
1297 sturdyc.WithEarlyRefreshes(minBackgroundRefreshDelay, maxBackgroundRefreshDelay, synchronousRefreshDelay, retryInterval),
1298 sturdyc.WithMissingRecordStorage(),
1299 sturdyc.WithClock(clock),
1300 )
1301
1302 ids := []string{"1", "2", "3", "4", "5"}
1303 fetchObserver := NewFetchObserver(1)
1304 fetchObserver.BatchResponse(ids)
1305
1306 res, err := sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1307 <-fetchObserver.FetchCompleted
1308 if err != nil {
1309 t.Fatalf("expected no error, got %v", err)
1310 }
1311 if len(res) != 5 {
1312 t.Fatalf("expected 5 records, got %d", len(res))
1313 }
1314 fetchObserver.AssertRequestedRecords(t, ids)
1315 fetchObserver.AssertFetchCount(t, 1)
1316
1317 // Now, let's move the clock passed the synchronous refresh
1318 // delay, and make the next call return an error.
1319 clock.Add(synchronousRefreshDelay + 1)
1320 fetchObserver.Clear()
1321 fetchObserver.Err(errors.New("error"))
1322
1323 res, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1324 <-fetchObserver.FetchCompleted
1325 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
1326 t.Fatalf("expected no error, got %v", err)
1327 }
1328 if len(res) != 5 {
1329 t.Fatalf("expected 5 records, got %d", len(res))
1330 }
1331 fetchObserver.AssertRequestedRecords(t, ids)
1332 fetchObserver.AssertFetchCount(t, 2)
1333
1334 // If a synchronous refresh fails, we won't do any exponential backoff.
1335 clock.Add(time.Millisecond)
1336 res, err = sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1337 <-fetchObserver.FetchCompleted
1338 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
1339 t.Fatalf("expected no error, got %v", err)
1340 }
1341 if len(res) != 5 {
1342 t.Fatalf("expected 5 records, got %d", len(res))
1343 }
1344 fetchObserver.AssertRequestedRecords(t, ids)
1345 fetchObserver.AssertFetchCount(t, 3)
1346 }
1347
1348 func TestGetFetchSynchronousRefreshStampedeProtection(t *testing.T) {
1349 t.Parallel()
1350
1351 ctx := context.Background()
1352 capacity := 10
1353 numShards := 2
1354 ttl := time.Second * 2
1355 evictionPercentage := 10
1356 clock := sturdyc.NewTestClock(time.Now())
1357 minRefreshDelay := time.Millisecond * 500
1358 maxRefreshDelay := time.Millisecond * 500
1359 synchronousRefreshDelay := time.Second
1360 refreshRetryInterval := time.Millisecond * 10
1361
1362 // The cache is going to have a 2 second TTL, and the first refresh should happen within a second.
1363 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
1364 sturdyc.WithNoContinuousEvictions(),
1365 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
1366 sturdyc.WithMissingRecordStorage(),
1367 sturdyc.WithClock(clock),
1368 )
1369
1370 id := "1"
1371 fetchObserver := NewFetchObserver(1000)
1372 fetchObserver.Response(id)
1373
1374 // We will start the test by trying to get key1, which wont exist in the sturdyc. Hence,
1375 // the fetch function is going to get called and we'll set the initial value to val1.
1376 sturdyc.GetOrFetch[string](ctx, c, id, fetchObserver.Fetch)
1377
1378 <-fetchObserver.FetchCompleted
1379 fetchObserver.AssertFetchCount(t, 1)
1380
1381 // Now, we're going to go past the synchronous refresh delay and try to retrieve the key from 1000 goroutines at once.
1382 numGoroutines := 1000
1383 clock.Add(synchronousRefreshDelay + 1)
1384 var wg sync.WaitGroup
1385 wg.Add(numGoroutines)
1386 for i := 0; i < numGoroutines; i++ {
1387 go func() {
1388 defer wg.Done()
1389 _, err := sturdyc.GetOrFetch(ctx, c, id, fetchObserver.Fetch)
1390 if err != nil {
1391 panic(err)
1392 }
1393 }()
1394 }
1395 wg.Wait()
1396
1397 <-fetchObserver.FetchCompleted
1398 fetchObserver.AssertFetchCount(t, 2)
1399 }
1400
1401 func TestGetFetchBatchSynchronousRefreshStampedeProtection(t *testing.T) {
1402 t.Parallel()
1403
1404 ctx := context.Background()
1405 capacity := 10
1406 numShards := 2
1407 ttl := time.Second * 2
1408 evictionPercentage := 10
1409 clock := sturdyc.NewTestClock(time.Now())
1410 minRefreshDelay := time.Millisecond * 500
1411 maxRefreshDelay := time.Millisecond * 500
1412 synchronousRefreshDelay := time.Second
1413 refreshRetryInterval := time.Millisecond * 10
1414
1415 // The cache is going to have a 2 second TTL, and the first refresh should happen within a second.
1416 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
1417 sturdyc.WithNoContinuousEvictions(),
1418 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
1419 sturdyc.WithMissingRecordStorage(),
1420 sturdyc.WithClock(clock),
1421 )
1422
1423 ids := []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}
1424 fetchObserver := NewFetchObserver(1)
1425 fetchObserver.BatchResponse(ids)
1426
1427 res, err := sturdyc.GetOrFetchBatch(ctx, c, ids, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1428 <-fetchObserver.FetchCompleted
1429 if err != nil {
1430 t.Fatalf("expected no error, got %v", err)
1431 }
1432 if len(res) != 10 {
1433 t.Fatalf("expected 10 records, got %d", len(res))
1434 }
1435 fetchObserver.AssertRequestedRecords(t, ids)
1436 fetchObserver.AssertFetchCount(t, 1)
1437 fetchObserver.Clear()
1438
1439 // Now, we're going to go past the synchronous refresh delay and try to
1440 // retrieve 3 random keys (without duplicates) from 1000 goroutines at once.
1441 // In an ideal world, this should lead to 4 outgoing requests, e.g:
1442 // 1, 2, 3
1443 // 4, 5, 6
1444 // 7, 8, 9
1445 // However, we're not using delaying these requests, hence we could get a
1446 // maximum of 10 outgoing requests if the batches were to get spread out
1447 // something like this:
1448 // 1, 2, 3
1449 // 1, 2, 4
1450 // 1, 2, 5
1451 // 1, 2, 6
1452 // 1, 2, 7
1453 // 1, 2, ...
1454 clock.Add(synchronousRefreshDelay + 1)
1455 numGoroutines := 1000
1456 var wg sync.WaitGroup
1457 wg.Add(numGoroutines)
1458
1459 // We need to create another fetch mock because the fetchObserver resolves
1460 // the response immediately. However, we want to delay the response in order to
1461 // check that the deduplication works as expected. If we don't delay the
1462 // function responding, we'll have other goroutines with synchronous refresh
1463 // ids that are going to send of another request right after.
1464 signal := make(chan struct{})
1465 var callCount atomic.Int32
1466 fetchMock := func(_ context.Context, ids []string) (map[string]string, error) {
1467 <-signal
1468 callCount.Add(1)
1469 responseMap := make(map[string]string, len(ids))
1470 for _, id := range ids {
1471 responseMap[id] = "value" + id
1472 }
1473 return responseMap, nil
1474 }
1475
1476 for i := 0; i < numGoroutines; i++ {
1477 go func() {
1478 defer wg.Done()
1479 uniqueIDs := make(map[string]struct{})
1480 for len(uniqueIDs) < 3 {
1481 id := ids[rand.IntN(len(ids))]
1482 if _, ok := uniqueIDs[id]; ok {
1483 continue
1484 }
1485 uniqueIDs[id] = struct{}{}
1486 }
1487 idsToFetch := make([]string, 0, 3)
1488 for id := range uniqueIDs {
1489 idsToFetch = append(idsToFetch, id)
1490 }
1491 res, err := sturdyc.GetOrFetchBatch(ctx, c, idsToFetch, c.BatchKeyFn("item"), fetchMock)
1492 if err != nil {
1493 panic(err)
1494 }
1495 if len(res) != 3 {
1496 panic("expected 3 records, got " + strconv.Itoa(len(res)))
1497 }
1498 for _, id := range idsToFetch {
1499 if _, ok := res[id]; !ok {
1500 panic("expected id " + id + " to be in the response")
1501 }
1502 }
1503 }()
1504 }
1505 // Allow all of the goroutines to start and get some CPU time.
1506 time.Sleep(time.Millisecond * 500)
1507 // Now, we'll close the channel which should give all of the goroutines their response.
1508 close(signal)
1509 // Wait for the wait group so that we can run the assertions within the goroutines.
1510 wg.Wait()
1511 if callCount.Load() > 10 {
1512 t.Errorf("expected no more than 10 calls, got %d", callCount.Load())
1513 }
1514 }
1515
1516 func TestGetFetchBatchMixOfSynchronousAndAsynchronousRefreshes(t *testing.T) {
1517 t.Parallel()
1518
1519 ctx := context.Background()
1520 capacity := 10
1521 numShards := 2
1522 ttl := time.Second * 2
1523 evictionPercentage := 10
1524 clock := sturdyc.NewTestClock(time.Now())
1525 minRefreshDelay := time.Millisecond * 500
1526 maxRefreshDelay := time.Millisecond * 500
1527 synchronousRefreshDelay := time.Second
1528 refreshRetryInterval := time.Millisecond * 10
1529 batchSize := 20
1530 batchBufferTimeout := time.Millisecond * 50
1531
1532 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
1533 sturdyc.WithNoContinuousEvictions(),
1534 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
1535 sturdyc.WithMissingRecordStorage(),
1536 sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout),
1537 sturdyc.WithClock(clock),
1538 )
1539
1540 // We'll start by fetching one batch of IDs, and make some assertions.
1541 firstBatchOfIDs := []string{"1", "2", "3"}
1542 fetchObserver := NewFetchObserver(2)
1543 fetchObserver.BatchResponse(firstBatchOfIDs)
1544 res, err := sturdyc.GetOrFetchBatch(ctx, c, firstBatchOfIDs, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1545 <-fetchObserver.FetchCompleted
1546 if err != nil {
1547 t.Fatalf("expected no error, got %v", err)
1548 }
1549 if len(res) != 3 {
1550 t.Fatalf("expected 3 records, got %d", len(res))
1551 }
1552 fetchObserver.AssertRequestedRecords(t, firstBatchOfIDs)
1553 fetchObserver.Clear()
1554
1555 // Next, we'll move the clock past the synchronous refresh delay, and
1556 // make a call for a second batch of IDs. The first batch of IDs should
1557 // now be a second old, and due for a synchronous refresh the next time
1558 // any of the IDs are requested.
1559 clock.Add(synchronousRefreshDelay + 1)
1560 secondBatchOfIDs := []string{"4", "5", "6"}
1561 fetchObserver.BatchResponse(secondBatchOfIDs)
1562 res, err = sturdyc.GetOrFetchBatch(ctx, c, secondBatchOfIDs, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1563 <-fetchObserver.FetchCompleted
1564 if err != nil {
1565 t.Fatalf("expected no error, got %v", err)
1566 }
1567 if len(res) != 3 {
1568 t.Fatalf("expected 3 records, got %d", len(res))
1569 }
1570 fetchObserver.AssertRequestedRecords(t, secondBatchOfIDs)
1571 fetchObserver.Clear()
1572
1573 // Now we'll move the clock passed the maxRefreshDelay, which should make
1574 // the second batch of IDs due for a refresh, but not a synchronous one.
1575 clock.Add(maxRefreshDelay + 1)
1576
1577 // Here we create a third batch of IDs which contains one of the IDs from the
1578 // first batch, and another ID from the second batch, and an additional ID
1579 // that we haven't seen before.
1580 thirdBatchOfIDs := []string{"1", "4", "23"}
1581 fetchObserver.BatchResponse([]string{"1", "23"})
1582 res, err = sturdyc.GetOrFetchBatch(ctx, c, thirdBatchOfIDs, c.BatchKeyFn("item"), fetchObserver.FetchBatch)
1583 <-fetchObserver.FetchCompleted
1584 if err != nil {
1585 t.Fatalf("expected no error, got %v", err)
1586 }
1587 if len(res) != 3 {
1588 t.Fatalf("expected 3 records, got %d", len(res))
1589 }
1590 // We only expect to have called the underlying data source with the
1591 // ID from the first batch, and the ID we haven't seen before.
1592 fetchObserver.AssertRequestedRecords(t, []string{"1", "23"})
1593 fetchObserver.AssertFetchCount(t, 3)
1594 fetchObserver.Clear()
1595
1596 // Since we're using the WithRefreshCoalescing option, the cache will have created
1597 // an internal buffer where it's trying to gather 10 IDs before sending them off
1598 // to the underlying data source. However, we're only asking for one ID from the
1599 // second batch. Therefore, we'll have to move the clock in order to make the cache
1600 // exceed the buffering timeout.
1601 fetchObserver.BatchResponse([]string{"4"})
1602 // Give the buffering goroutine a chance to run before we move the clock.
1603 time.Sleep(time.Millisecond * 200)
1604 clock.Add(batchBufferTimeout + 1)
1605 <-fetchObserver.FetchCompleted
1606 fetchObserver.AssertRequestedRecords(t, []string{"4"})
1607 fetchObserver.AssertFetchCount(t, 4)
1608 }
1609
1610 func TestGetOrFetchGenerics(t *testing.T) {
1611 t.Parallel()
1612
1613 capacity := 10
1614 numShards := 2
1615 ttl := time.Second * 2
1616 evictionPercentage := 10
1617 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
1618 sturdyc.WithNoContinuousEvictions(),
1619 )
1620
1621 fetchFuncInt := func(_ context.Context) (int, error) {
1622 return 1, nil
1623 }
1624
1625 _, err := sturdyc.GetOrFetch(context.Background(), c, "1", fetchFuncInt)
1626 if !errors.Is(err, sturdyc.ErrInvalidType) {
1627 t.Errorf("expected ErrInvalidType, got %v", err)
1628 }
1629
1630 if _, ok := c.Get("1"); ok {
1631 t.Error("we should not have cached anything given that the value was of the wrong type")
1632 }
1633
1634 if c.Size() != 0 {
1635 t.Errorf("expected cache size to be 0, got %d", c.Size())
1636 }
1637
1638 fetchFuncString := func(_ context.Context) (string, error) {
1639 return "value", nil
1640 }
1641
1642 val, err := sturdyc.GetOrFetch(context.Background(), c, "1", fetchFuncString)
1643 if err != nil {
1644 t.Fatalf("expected no error, got %v", err)
1645 }
1646 if val != "value" {
1647 t.Errorf("expected value to be value, got %v", val)
1648 }
1649
1650 cachedValue, ok := c.Get("1")
1651 if !ok {
1652 t.Error("expected value to be in the cache")
1653 }
1654 if cachedValue != "value" {
1655 t.Errorf("expected value to be value, got %v", cachedValue)
1656 }
1657 if c.Size() != 1 {
1658 t.Errorf("expected cache size to be 1, got %d", c.Size())
1659 }
1660 }
1661
1662 func TestGetOrFetchBatchGenerics(t *testing.T) {
1663 t.Parallel()
1664
1665 capacity := 10
1666 numShards := 2
1667 ttl := time.Second * 2
1668 evictionPercentage := 10
1669 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
1670 sturdyc.WithNoContinuousEvictions(),
1671 )
1672
1673 fetchFuncInt := func(_ context.Context, ids []string) (map[string]int, error) {
1674 response := make(map[string]int, len(ids))
1675 for i, id := range ids {
1676 response[id] = i
1677 }
1678 return response, nil
1679 }
1680
1681 ids := []string{"1", "2", "3"}
1682 _, err := sturdyc.GetOrFetchBatch(context.Background(), c, ids, c.BatchKeyFn("item"), fetchFuncInt)
1683 if !errors.Is(err, sturdyc.ErrInvalidType) {
1684 t.Errorf("expected ErrInvalidType, got %v", err)
1685 }
1686 if c.Size() != 0 {
1687 t.Errorf("expected cache size to be 0, got %d", c.Size())
1688 }
1689
1690 fetchFuncString := func(_ context.Context, ids []string) (map[string]string, error) {
1691 response := make(map[string]string, len(ids))
1692 for _, id := range ids {
1693 response[id] = "value" + id
1694 }
1695 return response, nil
1696 }
1697
1698 keyFunc := c.BatchKeyFn("item")
1699 values, err := sturdyc.GetOrFetchBatch(context.Background(), c, ids, keyFunc, fetchFuncString)
1700 if err != nil {
1701 t.Fatalf("expected no error, got %v", err)
1702 }
1703 if len(values) != 3 {
1704 t.Errorf("expected 3 values, got %d", len(values))
1705 }
1706 if values["1"] != "value1" {
1707 t.Errorf("expected value to be value1, got %v", values["1"])
1708 }
1709 if values["2"] != "value2" {
1710 t.Errorf("expected value to be value2, got %v", values["2"])
1711 }
1712 if values["3"] != "value3" {
1713 t.Errorf("expected value to be value3, got %v", values["3"])
1714 }
1715
1716 cacheKeys := make([]string, 0, len(ids))
1717 for _, id := range ids {
1718 cacheKeys = append(cacheKeys, keyFunc(id))
1719 }
1720 cachedValues := c.GetMany(cacheKeys)
1721 if len(cachedValues) != 3 {
1722 t.Errorf("expected 3 values, got %d", len(cachedValues))
1723 }
1724 if cachedValues[cacheKeys[0]] != "value1" {
1725 t.Errorf("expected value to be value1, got %v", cachedValues["1"])
1726 }
1727 if cachedValues[cacheKeys[1]] != "value2" {
1728 t.Errorf("expected value to be value2, got %v", cachedValues["2"])
1729 }
1730 if cachedValues[cacheKeys[2]] != "value3" {
1731 t.Errorf("expected value to be value3, got %v", cachedValues["3"])
1732 }
1733 }
1734
1735 func TestGetOrFetchGenericsClashingTypes(t *testing.T) {
1736 t.Parallel()
1737
1738 capacity := 10
1739 numShards := 2
1740 ttl := time.Second * 2
1741 evictionPercentage := 10
1742 c := sturdyc.New[any](capacity, numShards, ttl, evictionPercentage,
1743 sturdyc.WithNoContinuousEvictions(),
1744 )
1745
1746 resolve := make(chan struct{})
1747 fetchFuncInt := func(_ context.Context) (int, error) {
1748 <-resolve
1749 return 1, nil
1750 }
1751 fetchFuncString := func(_ context.Context) (string, error) {
1752 return "value", nil
1753 }
1754
1755 go func() {
1756 time.Sleep(time.Millisecond * 500)
1757 resolve <- struct{}{}
1758 }()
1759 resOne, errOne := sturdyc.GetOrFetch(context.Background(), c, "1", fetchFuncInt)
1760 _, errTwo := sturdyc.GetOrFetch(context.Background(), c, "1", fetchFuncString)
1761
1762 if errOne != nil {
1763 t.Errorf("expected no error, got %v", errOne)
1764 }
1765 if resOne != 1 {
1766 t.Errorf("expected value to be 1, got %v", resOne)
1767 }
1768
1769 if !errors.Is(errTwo, sturdyc.ErrInvalidType) {
1770 t.Errorf("expected ErrInvalidType, got %v", errTwo)
1771 }
1772 }
1773
1774 func TestGetOrFetchBatchGenericsClashingTypes(t *testing.T) {
1775 t.Parallel()
1776
1777 capacity := 10
1778 numShards := 2
1779 ttl := time.Second * 2
1780 evictionPercentage := 10
1781 c := sturdyc.New[any](capacity, numShards, ttl, evictionPercentage,
1782 sturdyc.WithNoContinuousEvictions(),
1783 )
1784
1785 // We are going to test the behaviour for when the same IDs are passed to
1786 // fetch functions which return different types.
1787 cacheKeyFunc := c.BatchKeyFn("item")
1788 firstCallIDs := []string{"1", "2", "3"}
1789 secondCallIDs := []string{"1", "2", "3", "4"}
1790
1791 // First, we'll create a fetch function which returns integers. This fetch
1792 // function is going to wait for a message on the resolve channel before
1793 // returning. This is so that we're able to create an in-flight batch for the
1794 // first set of IDs.
1795 resolve := make(chan struct{})
1796 fetchFuncInt := func(_ context.Context, ids []string) (map[string]int, error) {
1797 if len(ids) != 3 {
1798 t.Fatalf("expected 3 IDs, got %d", len(ids))
1799 }
1800 response := make(map[string]int, len(ids))
1801 for i, id := range ids {
1802 response[id] = i + 1
1803 }
1804 <-resolve
1805 return response, nil
1806 }
1807
1808 // Next, we'll create a fetch function which returns strings. This fetch
1809 // function should only be called with ID "4" because IDs 1-3 are picked from
1810 // the first batch.
1811 fetchFuncString := func(_ context.Context, ids []string) (map[string]string, error) {
1812 if len(ids) != 1 {
1813 t.Fatalf("expected 1 ID, got %d", len(ids))
1814 }
1815 response := make(map[string]string, len(ids))
1816 for _, id := range ids {
1817 response[id] = "value" + id
1818 }
1819 return response, nil
1820 }
1821
1822 go func() {
1823 time.Sleep(time.Millisecond * 500)
1824 resolve <- struct{}{}
1825 }()
1826 firstCallValues, firstCallErr := sturdyc.GetOrFetchBatch(context.Background(), c, firstCallIDs, cacheKeyFunc, fetchFuncInt)
1827 _, secondCallErr := sturdyc.GetOrFetchBatch(context.Background(), c, secondCallIDs, cacheKeyFunc, fetchFuncString)
1828
1829 if firstCallErr != nil {
1830 t.Errorf("expected no error, got %v", firstCallErr)
1831 }
1832 if len(firstCallValues) != 3 {
1833 t.Errorf("expected 3 values, got %d", len(firstCallValues))
1834 }
1835 if firstCallValues["1"] != 1 {
1836 t.Errorf("expected value to be 1, got %v", firstCallValues["1"])
1837 }
1838 if firstCallValues["2"] != 2 {
1839 t.Errorf("expected value to be 2, got %v", firstCallValues["2"])
1840 }
1841 if firstCallValues["3"] != 3 {
1842 t.Errorf("expected value to be 3, got %v", firstCallValues["3"])
1843 }
1844
1845 if !errors.Is(secondCallErr, sturdyc.ErrInvalidType) {
1846 t.Errorf("expected ErrInvalidType, got %v", secondCallErr)
1847 }
1848 }