Debian Codegraph @

distribution_test.go

raw
1 package sturdyc_test
2
3 import (
4 "context"
5 "errors"
6 "strconv"
7 "sync"
8 "testing"
9 "time"
10
11 "github.com/viccon/sturdyc"
12 )
13
14 type mockStorage struct {
15 sync.Mutex
16 getCount int
17 setCount int
18 deleteCount int
19 records map[string][]byte
20 cancelFunc *context.CancelFunc
21 }
22
23 func (m *mockStorage) Get(_ context.Context, key string) ([]byte, bool) {
24 m.Lock()
25 defer func() {
26 if m.cancelFunc != nil {
27 (*m.cancelFunc)()
28 }
29 m.Unlock()
30 }()
31 m.getCount++
32
33 bytes, ok := m.records[key]
34 return bytes, ok
35 }
36
37 func (m *mockStorage) Set(_ context.Context, key string, bytes []byte) {
38 m.Lock()
39 defer m.Unlock()
40 m.setCount++
41
42 if m.records == nil {
43 m.records = make(map[string][]byte)
44 }
45 m.records[key] = bytes
46 }
47
48 func (m *mockStorage) Delete(_ context.Context, key string) {
49 m.Lock()
50 defer m.Unlock()
51 m.deleteCount++
52 delete(m.records, key)
53 }
54
55 func (m *mockStorage) GetBatch(_ context.Context, _ []string) map[string][]byte {
56 m.Lock()
57 defer func() {
58 if m.cancelFunc != nil {
59 (*m.cancelFunc)()
60 }
61 m.Unlock()
62 }()
63 m.getCount++
64 return m.records
65 }
66
67 func (m *mockStorage) SetBatch(_ context.Context, records map[string][]byte) {
68 m.Lock()
69 defer m.Unlock()
70 m.setCount++
71
72 if m.records == nil {
73 m.records = records
74 return
75 }
76
77 for key, value := range records {
78 m.records[key] = value
79 }
80 }
81
82 func (m *mockStorage) DeleteBatch(_ context.Context, keys []string) {
83 m.Lock()
84 defer m.Unlock()
85 for _, key := range keys {
86 m.deleteCount++
87 delete(m.records, key)
88 }
89 }
90
91 func (m *mockStorage) assertRecord(t *testing.T, key string) {
92 t.Helper()
93
94 m.Lock()
95 defer m.Unlock()
96
97 if _, ok := m.records[key]; !ok {
98 t.Errorf("expected key %s to be in records", key)
99 }
100 }
101
102 func (m *mockStorage) assertRecords(t *testing.T, ids []string, keyFn sturdyc.KeyFn) {
103 t.Helper()
104
105 m.Lock()
106 defer m.Unlock()
107
108 keys := make([]string, 0, len(ids))
109 for _, id := range ids {
110 keys = append(keys, keyFn(id))
111 }
112
113 for _, key := range keys {
114 if _, ok := m.records[key]; !ok {
115 t.Errorf("expected key %s to be in records", key)
116 }
117 }
118 }
119
120 func (m *mockStorage) assertGetCount(t *testing.T, count int) {
121 t.Helper()
122 m.Lock()
123 defer m.Unlock()
124 if m.getCount != count {
125 t.Errorf("expected get count %d, got %d", count, m.getCount)
126 }
127 }
128
129 func (m *mockStorage) assertSetCount(t *testing.T, count int) {
130 t.Helper()
131 m.Lock()
132 defer m.Unlock()
133 if m.setCount != count {
134 t.Errorf("expected set count %d, got %d", count, m.setCount)
135 }
136 }
137
138 func (m *mockStorage) assertDeleteCount(t *testing.T, count int) {
139 t.Helper()
140 m.Lock()
141 defer m.Unlock()
142 if m.deleteCount != count {
143 t.Errorf("expected delete count %d, got %d", count, m.deleteCount)
144 }
145 }
146
147 func TestDistributedStorage(t *testing.T) {
148 t.Parallel()
149
150 ctx := context.Background()
151 ttl := time.Minute
152 distributedStorage := &mockStorage{}
153 c := sturdyc.New[string](1000, 10, ttl, 30,
154 sturdyc.WithNoContinuousEvictions(),
155 sturdyc.WithDistributedStorage(distributedStorage),
156 )
157 fetchObserver := NewFetchObserver(1)
158
159 key := "key1"
160 fetchObserver.Response(key)
161 _, err := sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
162 if err != nil {
163 t.Fatalf("expected no error, got %v", err)
164 }
165
166 <-fetchObserver.FetchCompleted
167 fetchObserver.AssertFetchCount(t, 1)
168 fetchObserver.Clear()
169
170 // The keys are written asynchronously to the distributed storage.
171 time.Sleep(100 * time.Millisecond)
172 distributedStorage.assertRecord(t, key)
173 distributedStorage.assertGetCount(t, 1)
174 distributedStorage.assertSetCount(t, 1)
175
176 // Next, we'll delete the records from the in-memory cache to simulate that they were evicted.
177 c.Delete(key)
178 if c.Size() != 0 {
179 t.Fatalf("expected cache size to be 0, got %d", c.Size())
180 }
181
182 // Now we can request the same key again. The underlying data source should not be called.
183 res, err := sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
184 if err != nil {
185 t.Fatalf("expected no error, got %v", err)
186 }
187 if res != "valuekey1" {
188 t.Errorf("expected valuekey1, got %s", res)
189 }
190
191 // The keys are written asynchronously to the distributed storage.
192 time.Sleep(100 * time.Millisecond)
193 fetchObserver.AssertFetchCount(t, 1)
194 distributedStorage.assertGetCount(t, 2)
195 distributedStorage.assertSetCount(t, 1)
196 distributedStorage.assertDeleteCount(t, 0)
197 }
198
199 func TestDistributedStaleStorage(t *testing.T) {
200 t.Parallel()
201
202 clock := sturdyc.NewTestClock(time.Now())
203 ctx := context.Background()
204 ttl := time.Minute
205 distributedStorage := &mockStorage{}
206 c := sturdyc.New[string](1000, 10, ttl, 30,
207 sturdyc.WithNoContinuousEvictions(),
208 sturdyc.WithClock(clock),
209 sturdyc.WithDistributedStorageEarlyRefreshes(distributedStorage, time.Minute),
210 )
211 fetchObserver := NewFetchObserver(1)
212
213 key := "key1"
214 fetchObserver.Response(key)
215 _, err := sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
216 if err != nil {
217 t.Fatalf("expected no error, got %v", err)
218 }
219
220 <-fetchObserver.FetchCompleted
221 fetchObserver.AssertFetchCount(t, 1)
222 fetchObserver.Clear()
223
224 time.Sleep(100 * time.Millisecond)
225 distributedStorage.assertRecord(t, key)
226 distributedStorage.assertGetCount(t, 1)
227 distributedStorage.assertSetCount(t, 1)
228
229 // Next, we'll move the clock to make the record expire in the
230 // in-memory cache, and become stale in the distributed storage.
231 clock.Add(time.Minute * 2)
232
233 // Now we can request the same key again, but we'll make the fetchFn error.
234 // This is going to result in an ErrOnlyCachedRecords error.
235 fetchObserver.Err(errors.New("error"))
236 res, err := sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
237 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
238 t.Fatalf("expected ErrOnlyCachedRecords, got %v", err)
239 }
240 if !errors.Is(err, fetchObserver.err) {
241 t.Fatal("expected the original error to have been joined with ErrOnlyCachedRecords")
242 }
243 if res != "valuekey1" {
244 t.Errorf("expected valuekey1, got %s", res)
245 }
246
247 // We'll want to assert that the fetch observer was called again.
248 time.Sleep(100 * time.Millisecond)
249 fetchObserver.AssertFetchCount(t, 2)
250 distributedStorage.assertGetCount(t, 2)
251 distributedStorage.assertSetCount(t, 1)
252 distributedStorage.assertDeleteCount(t, 0)
253
254 // Getting the key now should not result in another error since we took the
255 // stale value from the distributed storage, and wrote it to the in-memory
256 // cache.
257 res, err = sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
258 if err != nil {
259 t.Fatalf("expected no error, got %v", err)
260 }
261 if res != "valuekey1" {
262 t.Errorf("expected valuekey1, got %s", res)
263 }
264 }
265
266 func TestDistributedStaleStorageDeletes(t *testing.T) {
267 t.Parallel()
268
269 clock := sturdyc.NewTestClock(time.Now())
270 ctx := context.Background()
271 ttl := time.Minute
272 distributedStorage := &mockStorage{}
273 c := sturdyc.New[string](1000, 10, ttl, 30,
274 sturdyc.WithNoContinuousEvictions(),
275 sturdyc.WithClock(clock),
276 sturdyc.WithDistributedStorageEarlyRefreshes(distributedStorage, time.Minute),
277 )
278 fetchObserver := NewFetchObserver(1)
279
280 key := "key1"
281 fetchObserver.Response(key)
282 _, err := sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
283 if err != nil {
284 t.Fatalf("expected no error, got %v", err)
285 }
286
287 <-fetchObserver.FetchCompleted
288 fetchObserver.AssertFetchCount(t, 1)
289 fetchObserver.Clear()
290
291 time.Sleep(100 * time.Millisecond)
292 distributedStorage.assertRecord(t, key)
293 distributedStorage.assertGetCount(t, 1)
294 distributedStorage.assertSetCount(t, 1)
295
296 // Next, we'll move the clock to make the record expire in the
297 // in-memory cache, and become stale in the distributed storage.
298 clock.Add(time.Minute * 2)
299
300 // Now we can request the same key again, but we'll make the fetchFn return a
301 // ErrNotFound. This should signal to the cache that the record has been
302 // deleted at the underlying data source.
303 fetchObserver.Err(sturdyc.ErrNotFound)
304 res, err := sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
305 if !errors.Is(err, sturdyc.ErrNotFound) {
306 t.Fatalf("expected ErrNotFound, got %v", err)
307 }
308 if res != "" {
309 t.Errorf("expected empty string (zero value), got %s", res)
310 }
311
312 // We'll want to assert that the fetch observer was called again.
313 time.Sleep(100 * time.Millisecond)
314 fetchObserver.AssertFetchCount(t, 2)
315 distributedStorage.assertGetCount(t, 2)
316 distributedStorage.assertSetCount(t, 1)
317 distributedStorage.assertDeleteCount(t, 1)
318 }
319
320 func TestDistributedStaleStorageConvertsToMissingRecord(t *testing.T) {
321 t.Parallel()
322
323 clock := sturdyc.NewTestClock(time.Now())
324 ctx := context.Background()
325 ttl := time.Minute
326 distributedStorage := &mockStorage{}
327 c := sturdyc.New[string](1000, 10, ttl, 30,
328 sturdyc.WithNoContinuousEvictions(),
329 sturdyc.WithClock(clock),
330 sturdyc.WithDistributedStorageEarlyRefreshes(distributedStorage, time.Minute),
331 sturdyc.WithMissingRecordStorage(),
332 )
333 fetchObserver := NewFetchObserver(1)
334
335 key := "key1"
336 fetchObserver.Response(key)
337 _, err := sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
338 if err != nil {
339 t.Fatalf("expected no error, got %v", err)
340 }
341
342 <-fetchObserver.FetchCompleted
343 fetchObserver.AssertFetchCount(t, 1)
344 fetchObserver.Clear()
345
346 time.Sleep(100 * time.Millisecond)
347 distributedStorage.assertRecord(t, key)
348 distributedStorage.assertGetCount(t, 1)
349 distributedStorage.assertSetCount(t, 1)
350
351 // Next, we'll move the clock to make the record expire in the
352 // in-memory cache, and become stale in the distributed storage.
353 clock.Add(time.Minute * 2)
354
355 // Now we can request the same key again, but we'll make the fetchFn return a
356 // ErrNotFound. This should signal to the cache that the record has been
357 // deleted at the underlying data source.
358 fetchObserver.Err(sturdyc.ErrNotFound)
359 res, err := sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
360 if !errors.Is(err, sturdyc.ErrMissingRecord) {
361 t.Fatalf("expected ErrMissingRecord, got %v", err)
362 }
363 if res != "" {
364 t.Errorf("expected empty string (zero value), got %s", res)
365 }
366
367 // We'll want to assert that the fetch observer was called again.
368 <-fetchObserver.FetchCompleted
369 time.Sleep(100 * time.Millisecond)
370 fetchObserver.AssertFetchCount(t, 2)
371 distributedStorage.assertGetCount(t, 2)
372 distributedStorage.assertSetCount(t, 2)
373 distributedStorage.assertDeleteCount(t, 0)
374
375 // Lastly, we'll want to ensure that the record can be brought back into
376 // existence if the fetchFn returns it from a refresh.
377 fetchObserver.Clear()
378 fetchObserver.Response(key)
379 c.Delete(key)
380 clock.Add(time.Minute * 2)
381
382 res, err = sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
383 if err != nil {
384 t.Fatalf("expected no error, got %v", err)
385 }
386 if res != "valuekey1" {
387 t.Errorf("expected valuekey1, got %s", res)
388 }
389
390 time.Sleep(100 * time.Millisecond)
391 <-fetchObserver.FetchCompleted
392 fetchObserver.AssertFetchCount(t, 3)
393 distributedStorage.assertGetCount(t, 3)
394 distributedStorage.assertSetCount(t, 3)
395 distributedStorage.assertDeleteCount(t, 0)
396
397 // And now we'll get it from the distributed storage without
398 // a fetch to ensure that the conversion propagated.
399 c.Delete(key)
400 res, err = sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
401 if err != nil {
402 t.Fatalf("expected no error, got %v", err)
403 }
404 if res != "valuekey1" {
405 t.Errorf("expected valuekey1, got %s", res)
406 }
407
408 time.Sleep(100 * time.Millisecond)
409 fetchObserver.AssertFetchCount(t, 3)
410 distributedStorage.assertGetCount(t, 4)
411 distributedStorage.assertSetCount(t, 3)
412 distributedStorage.assertDeleteCount(t, 0)
413 }
414
415 func TestDistributedStorageBatch(t *testing.T) {
416 t.Parallel()
417
418 ctx := context.Background()
419 ttl := time.Minute
420 distributedStorage := &mockStorage{}
421 c := sturdyc.New[string](1000, 10, ttl, 30,
422 sturdyc.WithNoContinuousEvictions(),
423 sturdyc.WithDistributedStorage(distributedStorage),
424 )
425 fetchObserver := NewFetchObserver(1)
426
427 keyFn := c.BatchKeyFn("item")
428 firstBatchOfIDs := []string{"1", "2", "3"}
429 fetchObserver.BatchResponse(firstBatchOfIDs)
430 _, err := sturdyc.GetOrFetchBatch(ctx, c, firstBatchOfIDs, keyFn, fetchObserver.FetchBatch)
431 if err != nil {
432 t.Fatalf("expected no error, got %v", err)
433 }
434
435 <-fetchObserver.FetchCompleted
436 fetchObserver.AssertRequestedRecords(t, firstBatchOfIDs)
437 fetchObserver.AssertFetchCount(t, 1)
438 fetchObserver.Clear()
439
440 // The keys are written asynchronously to the distributed storage.
441 time.Sleep(100 * time.Millisecond)
442 distributedStorage.assertRecords(t, firstBatchOfIDs, keyFn)
443 distributedStorage.assertGetCount(t, 1)
444 distributedStorage.assertSetCount(t, 1)
445
446 // Next, we'll delete the records from the in-memory cache to simulate that they were evicted.
447 for _, id := range firstBatchOfIDs {
448 c.Delete(keyFn(id))
449 }
450 if c.Size() != 0 {
451 t.Fatalf("expected cache size to be 0, got %d", c.Size())
452 }
453
454 // Now we can request a second batch of IDs. The fetchObservers
455 // FetchBatch function should not get called for IDs 1-3.
456 fetchObserver.BatchResponse([]string{"4", "5", "6"})
457 secondBatchOfIDs := []string{"1", "2", "3", "4", "5", "6"}
458 res, err := sturdyc.GetOrFetchBatch(ctx, c, secondBatchOfIDs, keyFn, fetchObserver.FetchBatch)
459 if err != nil {
460 t.Fatalf("expected no error, got %v", err)
461 }
462
463 for _, id := range secondBatchOfIDs {
464 if _, ok := res[id]; !ok {
465 t.Errorf("expected id %s to be in the response", id)
466 }
467 }
468
469 <-fetchObserver.FetchCompleted
470 fetchObserver.AssertRequestedRecords(t, []string{"4", "5", "6"})
471 fetchObserver.AssertFetchCount(t, 2)
472
473 // The keys are written asynchronously to the distributed storage.
474 time.Sleep(100 * time.Millisecond)
475 distributedStorage.assertRecords(t, secondBatchOfIDs, keyFn)
476 distributedStorage.assertGetCount(t, 2)
477 distributedStorage.assertSetCount(t, 2)
478 distributedStorage.assertDeleteCount(t, 0)
479 }
480
481 func TestDistributedStaleStorageBatch(t *testing.T) {
482 t.Parallel()
483
484 clock := sturdyc.NewTestClock(time.Now())
485 staleDuration := time.Minute
486 ctx := context.Background()
487 ttl := time.Minute
488 distributedStorage := &mockStorage{}
489 c := sturdyc.New[string](1000, 10, ttl, 30,
490 sturdyc.WithNoContinuousEvictions(),
491 sturdyc.WithClock(clock),
492 sturdyc.WithDistributedStorageEarlyRefreshes(distributedStorage, staleDuration),
493 )
494 fetchObserver := NewFetchObserver(1)
495
496 keyFn := c.BatchKeyFn("item")
497 firstBatchOfIDs := []string{"1", "2", "3"}
498 fetchObserver.BatchResponse(firstBatchOfIDs)
499 _, err := sturdyc.GetOrFetchBatch(ctx, c, firstBatchOfIDs, keyFn, fetchObserver.FetchBatch)
500 if err != nil {
501 t.Fatalf("expected no error, got %v", err)
502 }
503
504 <-fetchObserver.FetchCompleted
505 fetchObserver.AssertRequestedRecords(t, firstBatchOfIDs)
506 fetchObserver.AssertFetchCount(t, 1)
507 fetchObserver.Clear()
508
509 // The keys are written asynchronously to the distributed storage.
510 time.Sleep(100 * time.Millisecond)
511 distributedStorage.assertRecords(t, firstBatchOfIDs, keyFn)
512 distributedStorage.assertGetCount(t, 1)
513 distributedStorage.assertSetCount(t, 1)
514
515 // Next, we'll delete the records from the in-memory cache to simulate that they were evicted.
516 for _, id := range firstBatchOfIDs {
517 c.Delete(keyFn(id))
518 }
519 if c.Size() != 0 {
520 t.Fatalf("expected cache size to be 0, got %d", c.Size())
521 }
522
523 // Make the records stale by moving the clock, and then make the next fetch call return an error.
524 clock.Add(staleDuration + 1)
525 fetchObserver.Err(errors.New("error"))
526
527 res, err := sturdyc.GetOrFetchBatch(ctx, c, firstBatchOfIDs, keyFn, fetchObserver.FetchBatch)
528 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
529 t.Fatalf("expected ErrOnlyCachedRecords, got %v", err)
530 }
531 for id, value := range res {
532 if value != "value"+id {
533 t.Errorf("expected value%s, got %s", id, value)
534 }
535 }
536
537 <-fetchObserver.FetchCompleted
538 fetchObserver.AssertRequestedRecords(t, firstBatchOfIDs)
539 fetchObserver.AssertFetchCount(t, 2)
540
541 time.Sleep(100 * time.Millisecond)
542 distributedStorage.assertGetCount(t, 2)
543 distributedStorage.assertSetCount(t, 1)
544 distributedStorage.assertDeleteCount(t, 0)
545 }
546
547 func TestDistributedStorageBatchDeletes(t *testing.T) {
548 t.Parallel()
549
550 staleDuration := time.Minute
551 clock := sturdyc.NewTestClock(time.Now())
552 ctx := context.Background()
553 ttl := time.Minute
554 distributedStorage := &mockStorage{}
555 c := sturdyc.New[string](1000, 10, ttl, 30,
556 sturdyc.WithNoContinuousEvictions(),
557 sturdyc.WithClock(clock),
558 sturdyc.WithDistributedStorageEarlyRefreshes(distributedStorage, staleDuration),
559 )
560 fetchObserver := NewFetchObserver(1)
561
562 keyFn := c.BatchKeyFn("item")
563 batchOfIDs := []string{"1", "2", "3"}
564 fetchObserver.BatchResponse(batchOfIDs)
565 _, err := sturdyc.GetOrFetchBatch(ctx, c, batchOfIDs, keyFn, fetchObserver.FetchBatch)
566 if err != nil {
567 t.Fatalf("expected no error, got %v", err)
568 }
569
570 <-fetchObserver.FetchCompleted
571 fetchObserver.AssertRequestedRecords(t, batchOfIDs)
572 fetchObserver.AssertFetchCount(t, 1)
573 fetchObserver.Clear()
574
575 // The keys are written asynchronously to the distributed storage.
576 time.Sleep(100 * time.Millisecond)
577 distributedStorage.assertRecords(t, batchOfIDs, keyFn)
578 distributedStorage.assertGetCount(t, 1)
579 distributedStorage.assertSetCount(t, 1)
580
581 // Next, we'll delete the records from the in-memory cache to simulate that they were evicted.
582 for _, id := range batchOfIDs {
583 c.Delete(keyFn(id))
584 }
585 if c.Size() != 0 {
586 t.Fatalf("expected cache size to be 0, got %d", c.Size())
587 }
588
589 // Now we'll want to go past the stale time, and setup the fetch observer so
590 // that it only returns the first two IDs. This will simulate that the last
591 // ID has been deleted at the underlying data source.
592 clock.Add(staleDuration + 1)
593 fetchObserver.BatchResponse([]string{"1", "2"})
594 res, err := sturdyc.GetOrFetchBatch(ctx, c, batchOfIDs, keyFn, fetchObserver.FetchBatch)
595 if err != nil {
596 t.Fatalf("expected no error, got %v", err)
597 }
598
599 if len(res) != 2 {
600 t.Fatalf("expected 2 records, got %d", len(res))
601 }
602
603 <-fetchObserver.FetchCompleted
604 fetchObserver.AssertRequestedRecords(t, batchOfIDs)
605 fetchObserver.AssertFetchCount(t, 2)
606
607 // The keys are written asynchronously to the distributed storage.
608 time.Sleep(100 * time.Millisecond)
609 distributedStorage.assertRecords(t, []string{"1", "2"}, keyFn)
610 distributedStorage.assertGetCount(t, 2)
611 distributedStorage.assertSetCount(t, 2)
612 distributedStorage.assertDeleteCount(t, 1)
613 }
614
615 func TestDistributedStorageBatchConvertsToMissingRecord(t *testing.T) {
616 t.Parallel()
617
618 staleDuration := time.Minute
619 clock := sturdyc.NewTestClock(time.Now())
620 ctx := context.Background()
621 ttl := time.Minute
622 distributedStorage := &mockStorage{}
623 c := sturdyc.New[string](1000, 10, ttl, 30,
624 sturdyc.WithNoContinuousEvictions(),
625 sturdyc.WithClock(clock),
626 sturdyc.WithMissingRecordStorage(),
627 sturdyc.WithDistributedStorageEarlyRefreshes(distributedStorage, staleDuration),
628 )
629 fetchObserver := NewFetchObserver(1)
630
631 keyFn := c.BatchKeyFn("item")
632 batchOfIDs := []string{"1", "2", "3"}
633 fetchObserver.BatchResponse(batchOfIDs)
634 _, err := sturdyc.GetOrFetchBatch(ctx, c, batchOfIDs, keyFn, fetchObserver.FetchBatch)
635 if err != nil {
636 t.Fatalf("expected no error, got %v", err)
637 }
638
639 <-fetchObserver.FetchCompleted
640 fetchObserver.AssertRequestedRecords(t, batchOfIDs)
641 fetchObserver.AssertFetchCount(t, 1)
642 fetchObserver.Clear()
643
644 // The keys are written asynchronously to the distributed storage.
645 time.Sleep(100 * time.Millisecond)
646 distributedStorage.assertRecords(t, batchOfIDs, keyFn)
647 distributedStorage.assertGetCount(t, 1)
648 distributedStorage.assertSetCount(t, 1)
649
650 // Next, we'll delete the records from the in-memory cache to simulate that they were evicted.
651 for _, id := range batchOfIDs {
652 c.Delete(keyFn(id))
653 }
654 if c.Size() != 0 {
655 t.Fatalf("expected cache size to be 0, got %d", c.Size())
656 }
657
658 // Now we'll want to go past the stale time, and setup the fetch observer so
659 // that it only returns the first two IDs. This will simulate that the last
660 // ID has been deleted at the underlying data source.
661 clock.Add(staleDuration + 1)
662 fetchObserver.BatchResponse([]string{"1", "2"})
663 res, err := sturdyc.GetOrFetchBatch(ctx, c, batchOfIDs, keyFn, fetchObserver.FetchBatch)
664 if err != nil {
665 t.Fatalf("expected no error, got %v", err)
666 }
667
668 if len(res) != 2 {
669 t.Fatalf("expected 2 records, got %d", len(res))
670 }
671
672 <-fetchObserver.FetchCompleted
673 fetchObserver.AssertRequestedRecords(t, batchOfIDs)
674 fetchObserver.AssertFetchCount(t, 2)
675 fetchObserver.Clear()
676
677 // The keys are written asynchronously to the distributed storage.
678 time.Sleep(100 * time.Millisecond)
679 distributedStorage.assertRecords(t, []string{"1", "2"}, keyFn)
680 distributedStorage.assertGetCount(t, 2)
681 distributedStorage.assertSetCount(t, 2)
682 distributedStorage.assertDeleteCount(t, 0)
683
684 // Next, we'll want to assert that the records can be restored from missing to existing.
685 for _, id := range batchOfIDs {
686 c.Delete(keyFn(id))
687 }
688
689 clock.Add(staleDuration + 1)
690 fetchObserver.BatchResponse(batchOfIDs)
691
692 res, err = sturdyc.GetOrFetchBatch(ctx, c, batchOfIDs, keyFn, fetchObserver.FetchBatch)
693 if err != nil {
694 t.Fatalf("expected no error, got %v", err)
695 }
696 if len(res) != 3 {
697 t.Fatalf("expected 3 records, got %d", len(res))
698 }
699
700 <-fetchObserver.FetchCompleted
701 fetchObserver.AssertRequestedRecords(t, batchOfIDs)
702 fetchObserver.AssertFetchCount(t, 3)
703
704 // The keys are written asynchronously to the distributed storage.
705 time.Sleep(100 * time.Millisecond)
706 time.Sleep(100 * time.Millisecond)
707 distributedStorage.assertRecords(t, batchOfIDs, keyFn)
708 distributedStorage.assertGetCount(t, 3)
709 distributedStorage.assertSetCount(t, 3)
710 distributedStorage.assertDeleteCount(t, 0)
711
712 // Delete the ids to make sure that we get them from the distributed cache.
713 for _, id := range batchOfIDs {
714 c.Delete(keyFn(id))
715 }
716 res, err = sturdyc.GetOrFetchBatch(ctx, c, batchOfIDs, keyFn, fetchObserver.FetchBatch)
717 if err != nil {
718 t.Fatalf("expected no error, got %v", err)
719 }
720 if len(res) != 3 {
721 t.Fatalf("expected 3 records, got %d", len(res))
722 }
723
724 time.Sleep(50 * time.Millisecond)
725 fetchObserver.AssertFetchCount(t, 3)
726 }
727
728 func TestDistributedStorageDoesNotCachePartialResponseAsMissingRecords(t *testing.T) {
729 t.Parallel()
730
731 refreshAfter := time.Minute
732 clock := sturdyc.NewTestClock(time.Now())
733 ctx := context.Background()
734 ttl := time.Second * 30
735 distributedStorage := &mockStorage{}
736 c := sturdyc.New[string](1000, 10, ttl, 30,
737 sturdyc.WithNoContinuousEvictions(),
738 sturdyc.WithClock(clock),
739 sturdyc.WithMissingRecordStorage(),
740 sturdyc.WithDistributedStorageEarlyRefreshes(distributedStorage, refreshAfter),
741 )
742 fetchObserver := NewFetchObserver(1)
743
744 keyFn := c.BatchKeyFn("item")
745 batchOfIDs := []string{"1", "2", "3"}
746 fetchObserver.BatchResponse(batchOfIDs)
747 _, err := sturdyc.GetOrFetchBatch(ctx, c, batchOfIDs, keyFn, fetchObserver.FetchBatch)
748 if err != nil {
749 t.Fatalf("expected no error, got %v", err)
750 }
751
752 <-fetchObserver.FetchCompleted
753 fetchObserver.AssertRequestedRecords(t, batchOfIDs)
754 fetchObserver.AssertFetchCount(t, 1)
755 fetchObserver.Clear()
756
757 // The keys are written asynchronously to the distributed storage.
758 time.Sleep(100 * time.Millisecond)
759 distributedStorage.assertRecords(t, batchOfIDs, keyFn)
760 distributedStorage.assertGetCount(t, 1)
761 distributedStorage.assertSetCount(t, 1)
762
763 // Next, we'll delete the records from the in-memory cache to simulate that they were evicted.
764 for _, id := range batchOfIDs {
765 c.Delete(keyFn(id))
766 }
767 if c.Size() != 0 {
768 t.Fatalf("expected cache size to be 0, got %d", c.Size())
769 }
770
771 // Now we'll add a new id to the batch that we're going to fetch. Next, we'll
772 // set up the fetch observer so that it errors. We should still be able to
773 // retrieve the records that we have in the distributed cache, and assert
774 // that the remaining ID should not be stored as a missing record.
775 secondBatchOfIDs := []string{"1", "2", "3", "4"}
776 fetchObserver.Err(errors.New("boom"))
777 res, err := sturdyc.GetOrFetchBatch(ctx, c, secondBatchOfIDs, keyFn, fetchObserver.FetchBatch)
778 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
779 t.Fatalf("expected ErrOnlyCachedRecords, got %v", err)
780 }
781 if len(res) != 3 {
782 t.Fatalf("expected 3 records, got %d", len(res))
783 }
784
785 <-fetchObserver.FetchCompleted
786 fetchObserver.AssertRequestedRecords(t, []string{"4"})
787 fetchObserver.AssertFetchCount(t, 2)
788 fetchObserver.Clear()
789
790 // The 3 records we had in the distributed cache should have been synced to
791 // the in-memory cache. If we had 4 records here, it would mean that we
792 // cached the last record as a missing record when the fetch observer errored
793 // out. That is not the behaviour we want.
794 if c.Size() != 3 {
795 t.Fatalf("expected 3 records, got %d", c.Size())
796 }
797 }
798
799 func TestPartialResponseForRefreshesDoesNotResultInMissingRecords(t *testing.T) {
800 t.Parallel()
801
802 ctx := context.Background()
803 capacity := 1000
804 numShards := 50
805 evictionPercentage := 10
806 ttl := time.Hour
807 minRefreshDelay := time.Minute * 5
808 maxRefreshDelay := time.Minute * 10
809 synchronousRefreshDelay := time.Minute * 30
810 refreshRetryInterval := time.Millisecond * 10
811 batchSize := 10
812 batchBufferTimeout := time.Minute
813 refreshAfter := minRefreshDelay
814 distributedStorage := &mockStorage{}
815 clock := sturdyc.NewTestClock(time.Now())
816
817 c := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
818 sturdyc.WithNoContinuousEvictions(),
819 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, refreshRetryInterval),
820 sturdyc.WithMissingRecordStorage(),
821 sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout),
822 sturdyc.WithDistributedStorageEarlyRefreshes(distributedStorage, refreshAfter),
823 sturdyc.WithClock(clock),
824 )
825
826 keyFn := c.BatchKeyFn("item")
827 ids := make([]string, 0, 100)
828 for i := 1; i <= 100; i++ {
829 ids = append(ids, strconv.Itoa(i))
830 }
831
832 fetchObserver := NewFetchObserver(1)
833 fetchObserver.BatchResponse(ids)
834 res, err := sturdyc.GetOrFetchBatch(ctx, c, ids, keyFn, fetchObserver.FetchBatch)
835 if err != nil {
836 t.Fatalf("expected no error, got %v", err)
837 }
838 if len(res) != 100 {
839 t.Fatalf("expected 100 records, got %d", len(res))
840 }
841
842 <-fetchObserver.FetchCompleted
843 fetchObserver.AssertFetchCount(t, 1)
844 fetchObserver.AssertRequestedRecords(t, ids)
845 fetchObserver.Clear()
846
847 // We need to add a sleep because the keys are written asynchronously to the
848 // distributed storage. We expect that the distributed storage was queried
849 // for the ids before we went to the underlying data source, and then written
850 // to when it resulted in a cache miss and the data was in fact fetched.
851 time.Sleep(100 * time.Millisecond)
852 distributedStorage.assertRecords(t, ids, keyFn)
853 distributedStorage.assertGetCount(t, 1)
854 distributedStorage.assertSetCount(t, 1)
855
856 // Next, we'll move the clock past the maxRefreshDelay. This should guarantee
857 // that the next records we request gets scheduled for a refresh. We're also
858 // going to add two more ids to the batch and make the fetchObserver error.
859 // What should happen is the following: The cache queries the distributed
860 // storage and sees that ID 1-100 are due for a refresh, and that ID 101 and
861 // 102 are missing. Hence, it queries the underlying data source for all of
862 // them. When the underlying data source returns an error, we should get the
863 // records we have in the distributed cache back. The cache should still only
864 // contain 100 records because we can't tell if ID 101 and 102 are missing or
865 // not.
866 clock.Add(maxRefreshDelay + time.Second)
867 fetchObserver.Err(errors.New("boom"))
868 secondBatchOfIDs := make([]string, 0, 102)
869 for i := 1; i <= 102; i++ {
870 secondBatchOfIDs = append(secondBatchOfIDs, strconv.Itoa(i))
871 }
872 res, err = sturdyc.GetOrFetchBatch(ctx, c, secondBatchOfIDs, keyFn, fetchObserver.FetchBatch)
873 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
874 t.Fatalf("expected ErrOnlyCachedRecords, got %v", err)
875 }
876 if len(res) != 100 {
877 t.Fatalf("expected 100 records, got %d", len(res))
878 }
879
880 // The fetch observer should be called 11 times. 10 times for the batches of
881 // ids that we tried to refresh, and once for id 101 and 102 which we didn't
882 // have in the cache.
883 for i := 0; i < 11; i++ {
884 <-fetchObserver.FetchCompleted
885 }
886 fetchObserver.AssertFetchCount(t, 12)
887
888 // Assert that the distributed storage was queried when we
889 // tried to refresh the records we had in the memory cache.
890 distributedStorage.assertGetCount(t, 12)
891 distributedStorage.assertSetCount(t, 1)
892
893 // The in-memory cache should only have 100 records because we can't tell if
894 // ID 101 and 102 are missing or not because the fetch observer errored out
895 // when we tried to fetch them.
896 if c.Size() != 100 {
897 t.Fatalf("expected cache size to be 100, got %d", c.Size())
898 }
899 }
900
901 func TestReturnsDataSourceErrorsWhenThereAreNoDistributedRecords(t *testing.T) {
902 t.Parallel()
903
904 ctx := context.Background()
905 ttl := time.Minute
906 distributedStorage := &mockStorage{}
907 c := sturdyc.New[string](1000, 10, ttl, 30,
908 sturdyc.WithNoContinuousEvictions(),
909 sturdyc.WithDistributedStorage(distributedStorage),
910 )
911
912 keyFn := c.BatchKeyFn("item")
913 ids := make([]string, 0, 100)
914 for i := 1; i <= 100; i++ {
915 ids = append(ids, strconv.Itoa(i))
916 }
917
918 fetchObserver := NewFetchObserver(1)
919 fetchObserver.err = context.Canceled
920 res, err := sturdyc.GetOrFetchBatch(ctx, c, ids, keyFn, fetchObserver.FetchBatch)
921 <-fetchObserver.FetchCompleted
922
923 fetchObserver.AssertFetchCount(t, 1)
924 fetchObserver.AssertRequestedRecords(t, ids)
925 distributedStorage.assertGetCount(t, 1)
926
927 if len(res) != 0 {
928 t.Fatalf("expected 0 records, got %d", len(res))
929 }
930
931 if !errors.Is(err, context.Canceled) {
932 t.Fatalf("expected context.Canceled, got %v", err)
933 }
934
935 if errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
936 t.Error("expected no ErrOnlyCachedRecords since the response was empty")
937 }
938 }
939
940 func TestReturnsPartialResultsAndJoinedErrorsOnDataSourceFailure(t *testing.T) {
941 t.Parallel()
942
943 ctx := context.Background()
944 ttl := time.Minute
945 distributedStorage := &mockStorage{}
946 c := sturdyc.New[string](1000, 10, ttl, 30,
947 sturdyc.WithNoContinuousEvictions(),
948 sturdyc.WithDistributedStorage(distributedStorage),
949 )
950 fetchObserver := NewFetchObserver(1)
951
952 keyFn := c.BatchKeyFn("item")
953 firstBatchOfIDs := []string{"1", "2", "3"}
954 fetchObserver.BatchResponse(firstBatchOfIDs)
955 _, err := sturdyc.GetOrFetchBatch(ctx, c, firstBatchOfIDs, keyFn, fetchObserver.FetchBatch)
956 <-fetchObserver.FetchCompleted
957
958 if err != nil {
959 t.Fatalf("expected no error, got %v", err)
960 }
961
962 fetchObserver.AssertRequestedRecords(t, firstBatchOfIDs)
963 fetchObserver.AssertFetchCount(t, 1)
964 fetchObserver.Clear()
965
966 // The keys are written asynchronously to the distributed storage.
967 time.Sleep(100 * time.Millisecond)
968 distributedStorage.assertRecords(t, firstBatchOfIDs, keyFn)
969 distributedStorage.assertGetCount(t, 1)
970 distributedStorage.assertSetCount(t, 1)
971
972 // Next, we'll delete the records from the in-memory cache to ensure that we
973 // get them from the distributed storage on the next GetOrFetchBatchCall.
974 for _, id := range firstBatchOfIDs {
975 c.Delete(keyFn(id))
976 }
977 if c.Size() != 0 {
978 t.Fatalf("expected cache size to be 0, got %d", c.Size())
979 }
980
981 // Now we can request a second batch of IDs. This time though, we'll make the
982 // underlying data source error out. This means that we're only going to get
983 // ids 1-3 from the distributed storage.
984 secondBatchOfIDs := []string{"1", "2", "3", "4", "5", "6"}
985 fetchObserver.err = context.Canceled
986 res, err := sturdyc.GetOrFetchBatch(ctx, c, secondBatchOfIDs, keyFn, fetchObserver.FetchBatch)
987 <-fetchObserver.FetchCompleted
988
989 // Assert that we got the 3 records which were stored in the distributed storage after the first request.
990 if len(res) != 3 {
991 t.Fatalf("expected 3 records, got %d", len(res))
992 }
993
994 // Assert that we're returning an ErrOnlyCachedRecords error to
995 // inform that the call to the underlying data source failed.
996 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
997 t.Fatalf("expected err to be ErrOnlyCachedRecords, got %v", err)
998 }
999
1000 // Assert that the error from the request to fetch the additional IDs is returned as well.
1001 if !errors.Is(err, context.Canceled) {
1002 t.Fatalf("expected err to be context.Canceled, got %v", err)
1003 }
1004
1005 // Let's also make sure that we don't lose any data source errors when
1006 // there is multiple joined errors returned from the fetch function.
1007 fetchObserver.Clear()
1008 fetchObserver.err = errors.Join(context.Canceled, context.DeadlineExceeded)
1009
1010 // Clear the in-memory cache.
1011 for _, id := range firstBatchOfIDs {
1012 c.Delete(keyFn(id))
1013 }
1014 if c.Size() != 0 {
1015 t.Fatalf("expected cache size to be 0, got %d", c.Size())
1016 }
1017
1018 res, err = sturdyc.GetOrFetchBatch(ctx, c, secondBatchOfIDs, keyFn, fetchObserver.FetchBatch)
1019 <-fetchObserver.FetchCompleted
1020
1021 if len(res) != 3 {
1022 t.Fatalf("expected 3 records, got %d", len(res))
1023 }
1024
1025 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
1026 t.Fatalf("expected err to be ErrOnlyCachedRecords, got %v", err)
1027 }
1028
1029 // Lastly, let's assert that we got both the context.Canceled and context.DeadlineExceeded errors.
1030 if !errors.Is(err, context.Canceled) {
1031 t.Fatalf("expected err to be context.Canceled, got %v", err)
1032 }
1033
1034 if !errors.Is(err, context.DeadlineExceeded) {
1035 t.Fatalf("expected err to be context.DeadlineExceeded, got %v", err)
1036 }
1037 }
1038
1039 func TestGetOrFetchDoesNotProceedToCallTheFetchFunctionIfTheContextIsCancelled(t *testing.T) {
1040 t.Parallel()
1041
1042 ctx, cancel := context.WithCancel(context.Background())
1043 ttl := time.Minute
1044 distributedStorage := &mockStorage{}
1045 clock := sturdyc.NewTestClock(time.Now())
1046 refreshAfter := time.Second * 10
1047 c := sturdyc.New[string](1000, 10, ttl, 30,
1048 sturdyc.WithNoContinuousEvictions(),
1049 sturdyc.WithDistributedStorageEarlyRefreshes(distributedStorage, refreshAfter),
1050 sturdyc.WithClock(clock),
1051 )
1052 fetchObserver := NewFetchObserver(1)
1053
1054 key := "1"
1055 fetchObserver.Response(key)
1056 val, err := sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
1057 if val != "value1" {
1058 t.Fatalf("expected value1, got %s", val)
1059 }
1060 if err != nil {
1061 t.Fatalf("expected no error, got %v", err)
1062 }
1063
1064 <-fetchObserver.FetchCompleted
1065 fetchObserver.AssertFetchCount(t, 1)
1066 fetchObserver.Clear()
1067
1068 // The key is written asynchronously to the distributed storage.
1069 time.Sleep(100 * time.Millisecond)
1070 distributedStorage.assertRecord(t, key)
1071 distributedStorage.assertGetCount(t, 1)
1072 distributedStorage.assertSetCount(t, 1)
1073
1074 // Next, we'll delete the key from the in-memory cache.
1075 c.Delete(key)
1076 if c.Size() != 0 {
1077 t.Fatalf("expected cache size to be 0, got %d", c.Size())
1078 }
1079
1080 // Now we'll request the key again. This time though, we'll move the clock
1081 // forward to indicate that the request has to be refreshed, but before that
1082 // is done we'll cancel the context.
1083 clock.Add(refreshAfter + time.Second)
1084 distributedStorage.cancelFunc = &cancel
1085 val, err = sturdyc.GetOrFetch(ctx, c, key, fetchObserver.Fetch)
1086
1087 // Assert that we got the key from the distributed storage.
1088 distributedStorage.assertGetCount(t, 2)
1089
1090 // Assert that we didn't call the fetch function again.
1091 if fetchObserver.fetchCount != 1 {
1092 t.Fatalf("expected fetch count to be 1, got %d", fetchObserver.fetchCount)
1093 }
1094
1095 if val != "value1" {
1096 t.Fatalf("expected value1, got %s", val)
1097 }
1098
1099 if !errors.Is(err, context.Canceled) {
1100 t.Fatalf("expected err to be context.Canceled, got %v", err)
1101 }
1102
1103 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
1104 t.Fatalf("expected err to be context.Canceled, got %v", err)
1105 }
1106
1107 // Assert that we wrote the value from the distributed cache back to the in-memory cache.
1108 if c.Size() != 1 {
1109 t.Fatalf("expected cache size to be 1, got %d", c.Size())
1110 }
1111 }
1112
1113 func TestGetOrFetchBatchDoesNotProceedToCallTheFetchFunctionIfTheContextIsCancelled(t *testing.T) {
1114 t.Parallel()
1115
1116 ctx, cancel := context.WithCancel(context.Background())
1117 ttl := time.Minute
1118 distributedStorage := &mockStorage{}
1119 c := sturdyc.New[string](1000, 10, ttl, 30,
1120 sturdyc.WithNoContinuousEvictions(),
1121 sturdyc.WithDistributedStorage(distributedStorage),
1122 )
1123 fetchObserver := NewFetchObserver(1)
1124
1125 keyFn := c.BatchKeyFn("item")
1126 firstBatchOfIDs := []string{"1", "2", "3"}
1127 fetchObserver.BatchResponse(firstBatchOfIDs)
1128 _, err := sturdyc.GetOrFetchBatch(ctx, c, firstBatchOfIDs, keyFn, fetchObserver.FetchBatch)
1129 <-fetchObserver.FetchCompleted
1130
1131 if err != nil {
1132 t.Fatalf("expected no error, got %v", err)
1133 }
1134
1135 fetchObserver.AssertRequestedRecords(t, firstBatchOfIDs)
1136 fetchObserver.AssertFetchCount(t, 1)
1137 fetchObserver.Clear()
1138
1139 // The keys are written asynchronously to the distributed storage.
1140 time.Sleep(100 * time.Millisecond)
1141 distributedStorage.assertRecords(t, firstBatchOfIDs, keyFn)
1142 distributedStorage.assertGetCount(t, 1)
1143 distributedStorage.assertSetCount(t, 1)
1144
1145 // Next, we'll delete the records from the in-memory cache to ensure that we
1146 // get them from the distributed storage on the next GetOrFetchBatchCall.
1147 for _, id := range firstBatchOfIDs {
1148 c.Delete(keyFn(id))
1149 }
1150 if c.Size() != 0 {
1151 t.Fatalf("expected cache size to be 0, got %d", c.Size())
1152 }
1153
1154 // Now we can request a second batch of IDs. This time though, we'll cancel
1155 // the context after the distributed cache has been called.
1156 secondBatchOfIDs := []string{"1", "2", "3", "4", "5", "6"}
1157 distributedStorage.cancelFunc = &cancel
1158 res, err := sturdyc.GetOrFetchBatch(ctx, c, secondBatchOfIDs, keyFn, fetchObserver.FetchBatch)
1159
1160 // Assert that we got the 3 records which were stored in the distributed storage after the first request.
1161 if len(res) != 3 {
1162 t.Fatalf("expected 3 records, got %d", len(res))
1163 }
1164
1165 // Assert that we didn't call the fetch function again.
1166 if fetchObserver.fetchCount != 1 {
1167 t.Fatalf("expected fetch count to be 1, got %d", fetchObserver.fetchCount)
1168 }
1169
1170 // Assert that the error is both an ErrOnlyCachedRecords and a context.Canceled error.
1171 if !errors.Is(err, sturdyc.ErrOnlyCachedRecords) {
1172 t.Fatalf("expected err to be ErrOnlyCachedRecords, got %v", err)
1173 }
1174 if !errors.Is(err, context.Canceled) {
1175 t.Fatalf("expected err to be context.Canceled, got %v", err)
1176 }
1177 }