-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpersistent_test.go
More file actions
1904 lines (1591 loc) · 48.2 KB
/
persistent_test.go
File metadata and controls
1904 lines (1591 loc) · 48.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fido
import (
"context"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
)
// mockStore is a simple in-memory store for testing.
type mockStore[K comparable, V any] struct {
mu sync.RWMutex
data map[string]mockEntry[V]
closed bool
failGet bool
failSet bool
}
type mockEntry[V any] struct {
value V
expiry time.Time
updatedAt time.Time
}
func newMockStore[K comparable, V any]() *mockStore[K, V] {
return &mockStore[K, V]{
data: make(map[string]mockEntry[V]),
}
}
func (m *mockStore[K, V]) setFailGet(v bool) {
m.mu.Lock()
m.failGet = v
m.mu.Unlock()
}
func (m *mockStore[K, V]) setFailSet(v bool) {
m.mu.Lock()
m.failSet = v
m.mu.Unlock()
}
func (m *mockStore[K, V]) ValidateKey(key K) error {
return nil
}
func (m *mockStore[K, V]) Get(ctx context.Context, key K) (v V, expiry time.Time, found bool, err error) {
m.mu.RLock()
defer m.mu.RUnlock()
var zero V
if m.failGet {
return zero, time.Time{}, false, fmt.Errorf("mock get error")
}
keyStr := fmt.Sprintf("%v", key)
entry, found := m.data[keyStr]
if !found {
return zero, time.Time{}, false, nil
}
// Check expiration
if !entry.expiry.IsZero() && time.Now().After(entry.expiry) {
return zero, time.Time{}, false, nil
}
return entry.value, entry.expiry, true, nil
}
func (m *mockStore[K, V]) Set(ctx context.Context, key K, value V, expiry time.Time) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.failSet {
return fmt.Errorf("mock store error")
}
keyStr := fmt.Sprintf("%v", key)
m.data[keyStr] = mockEntry[V]{
value: value,
expiry: expiry,
updatedAt: time.Now(),
}
return nil
}
func (m *mockStore[K, V]) Delete(ctx context.Context, key K) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.failSet { // Reuse failSet for Delete errors
return fmt.Errorf("mock delete error")
}
keyStr := fmt.Sprintf("%v", key)
delete(m.data, keyStr)
return nil
}
func (m *mockStore[K, V]) Cleanup(ctx context.Context, maxAge time.Duration) (int, error) {
m.mu.Lock()
defer m.mu.Unlock()
cutoff := time.Now().Add(-maxAge)
count := 0
for keyStr, entry := range m.data {
if !entry.expiry.IsZero() && entry.expiry.Before(cutoff) {
delete(m.data, keyStr)
count++
}
}
return count, nil
}
func (m *mockStore[K, V]) Location(key K) string {
return fmt.Sprintf("mock://%v", key)
}
func (m *mockStore[K, V]) Flush(ctx context.Context) (int, error) {
m.mu.Lock()
defer m.mu.Unlock()
count := len(m.data)
m.data = make(map[string]mockEntry[V])
return count, nil
}
func (m *mockStore[K, V]) Len(ctx context.Context) (int, error) {
m.mu.RLock()
defer m.mu.RUnlock()
return len(m.data), nil
}
func (m *mockStore[K, V]) Close() error {
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return fmt.Errorf("mock close error: already closed")
}
m.closed = true
return nil
}
// sequenceMockStore is a mock that can change behavior based on call count.
type sequenceMockStore[K comparable, V any] struct {
mu sync.RWMutex
data map[string]mockEntry[V]
getCalls int
failOnGetN int // Fail on Nth Get call (0 = never fail)
returnOnGetN int // Return value on Nth Get call (0 = never)
valueToReturn V
}
func newSequenceMockStore[K comparable, V any]() *sequenceMockStore[K, V] {
return &sequenceMockStore[K, V]{
data: make(map[string]mockEntry[V]),
}
}
func (m *sequenceMockStore[K, V]) ValidateKey(key K) error {
return nil
}
func (m *sequenceMockStore[K, V]) Get(ctx context.Context, key K) (v V, expiry time.Time, found bool, err error) {
m.mu.Lock()
m.getCalls++
callNum := m.getCalls
m.mu.Unlock()
m.mu.RLock()
defer m.mu.RUnlock()
var zero V
if m.failOnGetN > 0 && callNum == m.failOnGetN {
return zero, time.Time{}, false, fmt.Errorf("mock get error on call %d", callNum)
}
if m.returnOnGetN > 0 && callNum == m.returnOnGetN {
return m.valueToReturn, time.Now().Add(time.Hour), true, nil
}
keyStr := fmt.Sprintf("%v", key)
entry, found := m.data[keyStr]
if !found {
return zero, time.Time{}, false, nil
}
return entry.value, entry.expiry, true, nil
}
func (m *sequenceMockStore[K, V]) Set(ctx context.Context, key K, value V, expiry time.Time) error {
m.mu.Lock()
defer m.mu.Unlock()
keyStr := fmt.Sprintf("%v", key)
m.data[keyStr] = mockEntry[V]{
value: value,
expiry: expiry,
updatedAt: time.Now(),
}
return nil
}
func (m *sequenceMockStore[K, V]) Delete(ctx context.Context, key K) error {
m.mu.Lock()
defer m.mu.Unlock()
keyStr := fmt.Sprintf("%v", key)
delete(m.data, keyStr)
return nil
}
func (m *sequenceMockStore[K, V]) Cleanup(ctx context.Context, maxAge time.Duration) (int, error) {
return 0, nil
}
func (m *sequenceMockStore[K, V]) Location(key K) string {
return fmt.Sprintf("mock://%v", key)
}
func (m *sequenceMockStore[K, V]) Len(ctx context.Context) (int, error) {
m.mu.RLock()
defer m.mu.RUnlock()
return len(m.data), nil
}
func (m *sequenceMockStore[K, V]) Flush(ctx context.Context) (int, error) {
m.mu.Lock()
defer m.mu.Unlock()
count := len(m.data)
m.data = make(map[string]mockEntry[V])
return count, nil
}
func (m *sequenceMockStore[K, V]) Close() error {
return nil
}
// injectingMockStore is a mock that can inject values into cache memory during Get.
type injectingMockStore[K comparable, V any] struct {
*mockStore[K, V]
cache *TieredCache[K, V] // Set after cache creation
injectKey K
injectValue V
injectOnGet int // Inject on Nth Get call
getCalls atomic.Int32
}
func newInjectingMockStore[K comparable, V any]() *injectingMockStore[K, V] {
return &injectingMockStore[K, V]{
mockStore: newMockStore[K, V](),
}
}
func (m *injectingMockStore[K, V]) Get(ctx context.Context, key K) (v V, expiry time.Time, found bool, err error) {
callNum := m.getCalls.Add(1)
// Inject value into cache memory at specified call
if m.cache != nil && m.injectOnGet > 0 && int(callNum) == m.injectOnGet {
m.cache.memory.set(m.injectKey, m.injectValue, 0)
}
return m.mockStore.Get(ctx, key)
}
func TestTieredCache_Fetch_SecondMemoryCheck(t *testing.T) {
// This test triggers the second memory check path in getSet (line 166-171)
// by injecting a value into memory during the first store.Get call.
store := newInjectingMockStore[string, int]()
store.injectKey = "key1"
store.injectValue = 77
store.injectOnGet = 1 // Inject during first Get
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered failed: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
store.cache = cache // Link store to cache for injection
ctx := context.Background()
loaderCalled := false
val, err := cache.Fetch(ctx, "key1", func(context.Context) (int, error) {
loaderCalled = true
return 42, nil
})
if err != nil {
t.Fatalf("Fetch failed: %v", err)
}
// Should return injected value from second memory check
if val != 77 {
t.Errorf("val = %d; want 77 (from second memory check)", val)
}
if loaderCalled {
t.Error("loader should not be called when second memory check finds value")
}
}
func TestTieredCache_Basic(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Set should persist
if err := cache.Set(ctx, "key1", 42); err != nil {
t.Fatalf("Set: %v", err)
}
// Verify it's in persistence
val, _, found, err := store.Get(ctx, "key1")
if err != nil {
t.Fatalf("store.Get: %v", err)
}
if !found {
t.Error("key1 should be persisted")
}
if val != 42 {
t.Errorf("persisted value = %d; want 42", val)
}
// Delete should remove from persistence
if err := cache.Delete(ctx, "key1"); err != nil {
t.Fatalf("cache.Delete: %v", err)
}
_, _, found, err = store.Get(ctx, "key1")
if err != nil {
t.Fatalf("store.Get after delete: %v", err)
}
if found {
t.Error("key1 should be deleted from persistence")
}
}
func TestTieredCache_GetFromPersistence(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
// Pre-populate persistence
_ = store.Set(ctx, "key1", 42, time.Time{}) //nolint:errcheck // Test fixture
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Get should load from persistence
val, found, err := cache.Get(ctx, "key1")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found {
t.Error("key1 should be found in persistence")
}
if val != 42 {
t.Errorf("Get value = %d; want 42", val)
}
}
func TestTieredCache_PromotesToMemory(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
// Pre-populate persistence only (not memory)
_ = store.Set(ctx, "key1", 42, time.Time{}) //nolint:errcheck // Test fixture
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Memory should be empty initially
if cache.Len() != 0 {
t.Errorf("initial memory cache length = %d; want 0", cache.Len())
}
// First Get: should load from persistence
val, found, err := cache.Get(ctx, "key1")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found || val != 42 {
t.Error("key1 should be found from persistence")
}
// Memory should now have the entry (promoted)
if cache.Len() != 1 {
t.Errorf("memory cache length after Get = %d; want 1 (should be promoted)", cache.Len())
}
// Make persistence fail - subsequent Get should still work from memory
store.setFailGet(true)
val, found, err = cache.Get(ctx, "key1")
if err != nil {
t.Fatalf("Get from memory: %v", err)
}
if !found || val != 42 {
t.Error("key1 should be found from memory (promoted from persistence)")
}
}
func TestTieredCache_GetFromPersistenceExpired(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
// Pre-populate with expired entry
_ = store.Set(ctx, "key1", 42, time.Now().Add(-1*time.Hour)) //nolint:errcheck // Test fixture
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Get should return not found for expired entry
_, found, err := cache.Get(ctx, "key1")
if err != nil {
t.Fatalf("Get: %v", err)
}
if found {
t.Error("expired key should not be found")
}
}
func TestTieredCache_SetAsync(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// SetAsync should not block but value should be available immediately
if err := cache.SetAsync(ctx, "key1", 42); err != nil {
t.Fatalf("SetAsync: %v", err)
}
// Value should be in memory
val, found, err := cache.Get(ctx, "key1")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found || val != 42 {
t.Error("key1 should be available immediately after SetAsync")
}
// Give async persistence time to complete
time.Sleep(50 * time.Millisecond)
// Should also be persisted
val, _, found, err = store.Get(ctx, "key1")
if err != nil {
t.Fatalf("store.Get: %v", err)
}
if !found || val != 42 {
t.Error("key1 should be persisted after SetAsync")
}
}
func TestTieredCache_Close(t *testing.T) {
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
// Close should close the store
if err := cache.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
if !store.closed {
t.Error("store should be closed")
}
}
func TestTieredCache_Errors(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Set returns error when persistence fails (by design)
// Value is still in memory, but error is returned to caller
store.setFailSet(true)
if err := cache.Set(ctx, "key1", 42); err == nil {
t.Error("Set should return error when persistence fails")
}
// Value should still be in memory despite persistence error
val, found, err := cache.Get(ctx, "key1")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found || val != 42 {
t.Error("key1 should be in memory even though persistence failed")
}
// SetAsync logs persistence errors but doesn't return them
store.setFailSet(true)
if err := cache.SetAsync(ctx, "key3", 300); err != nil {
t.Fatalf("SetAsync should not fail synchronously: %v", err)
}
// Value should be in memory immediately
val, found, err = cache.Get(ctx, "key3")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found || val != 300 {
t.Error("key3 should be in memory after SetAsync")
}
// Give async persistence time to attempt (and fail with logged error)
time.Sleep(50 * time.Millisecond)
// Get should work from memory even if persistence fails
store.setFailGet(true)
store.setFailSet(false)
if err := cache.Set(ctx, "key2", 100); err != nil {
t.Fatalf("Set: %v", err)
}
val, found, err = cache.Get(ctx, "key2")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found || val != 100 {
t.Error("Get should work from memory even if persistence load fails")
}
}
func TestTieredCache_Delete_Errors(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Store a value (with failSet = false)
store.setFailSet(false)
if err := cache.Set(ctx, "key1", 42); err != nil {
t.Fatalf("Set: %v", err)
}
// Verify it's in memory
val, found, err := cache.Get(ctx, "key1")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found || val != 42 {
t.Fatal("key1 should be in memory before delete")
}
// Now make persistence delete fail
store.setFailSet(true) // failSet affects Delete too in mock
err = cache.Delete(ctx, "key1")
if err == nil {
t.Error("Delete should return error when persistence fails")
}
// Note: Even though persistence delete failed, key is deleted from memory.
// However, Get will load it back from persistence since it's still there.
// This tests that memory is always cleaned even if persistence fails.
val2, found2, err := cache.Get(ctx, "key1")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found2 || val2 != 42 {
// Get loads from persistence, so key is found again
t.Logf("key1 found from persistence after failed delete (expected): %v, %v", val2, found2)
}
// Delete with invalid key should return error
err = cache.Delete(ctx, "")
if err == nil {
t.Error("Delete with empty key should return error")
}
}
func TestTieredCache_Get_InvalidKey(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Get with empty key (invalid)
_, found, err := cache.Get(ctx, "")
if err != nil {
t.Errorf("Get with invalid key should not return error: %v", err)
}
if found {
t.Error("invalid key should not be found")
}
}
func TestTieredCache_Get_PersistenceLoadError(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Pre-populate persistence (not in memory)
_ = store.Set(ctx, "key1", 42, time.Time{}) //nolint:errcheck // Test fixture
// Make persistence Load fail
store.setFailGet(true)
// Get should return error on persistence failure
_, found, err := cache.Get(ctx, "key1")
if err == nil {
t.Error("Get should return error on persistence failure")
}
if found {
t.Error("key should not be found when persistence fails")
}
}
func TestTieredCache_Close_PersistenceError(t *testing.T) {
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
// Make store.Close() fail
store.closed = true // This will cause some error condition
// Close should return error
if err := cache.Close(); err != nil {
// Expected - persistence close can fail
t.Logf("Close error (expected): %v", err)
}
}
func TestTieredCache_Flush(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Add entries
for i := range 10 {
if err := cache.Set(ctx, fmt.Sprintf("key%d", i), i*100); err != nil {
t.Fatalf("Set: %v", err)
}
}
// Verify entries exist in both memory and persistence
if cache.Len() != 10 {
t.Errorf("memory cache length = %d; want 10", cache.Len())
}
for i := range 10 {
if _, _, found, err := store.Get(ctx, fmt.Sprintf("key%d", i)); err != nil || !found {
t.Fatalf("key%d should exist in persistence", i)
}
}
// Flush
removed, err := cache.Flush(ctx)
if err != nil {
t.Fatalf("Flush: %v", err)
}
// Should remove 10 from memory + 10 from persistence = 20 total
if removed != 20 {
t.Errorf("Flush removed %d items; want 20", removed)
}
// Memory cache should be empty
if cache.Len() != 0 {
t.Errorf("memory cache length after flush = %d; want 0", cache.Len())
}
// Persistence should be empty
for i := range 10 {
if _, _, found, err := store.Get(ctx, fmt.Sprintf("key%d", i)); err != nil {
t.Fatalf("Load: %v", err)
} else if found {
t.Errorf("key%d should not exist in persistence after flush", i)
}
}
// Get should return not found for all keys
for i := range 10 {
_, found, err := cache.Get(ctx, fmt.Sprintf("key%d", i))
if err != nil {
t.Fatalf("Get: %v", err)
}
if found {
t.Errorf("key%d should not be found after flush", i)
}
}
}
func TestTieredCache_StoreAccess(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Add some entries
for i := range 5 {
if err := cache.Set(ctx, fmt.Sprintf("key%d", i), i*10); err != nil {
t.Fatalf("Set: %v", err)
}
}
// Access Store directly via public field
storeLen, err := cache.Store.Len(ctx)
if err != nil {
t.Fatalf("Store.Len: %v", err)
}
if storeLen != 5 {
t.Errorf("Store.Len() = %d; want 5", storeLen)
}
// Verify memory Len() also works
if cache.Len() != 5 {
t.Errorf("Len() = %d; want 5", cache.Len())
}
// Flush via Store
flushed, err := cache.Store.Flush(ctx)
if err != nil {
t.Fatalf("Store.Flush: %v", err)
}
if flushed != 5 {
t.Errorf("Store.Flush() = %d; want 5", flushed)
}
// Store should be empty now
storeLen, err = cache.Store.Len(ctx)
if err != nil {
t.Fatalf("Store.Len: %v", err)
}
if storeLen != 0 {
t.Errorf("Store.Len() after flush = %d; want 0", storeLen)
}
}
func TestTieredCache_WithOptions(t *testing.T) {
store := newMockStore[string, int]()
// Test Size
cache, err := NewTiered[string, int](store, Size(500))
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
if cache.memory == nil {
t.Error("memory should be initialized")
}
_ = cache.Close() //nolint:errcheck // Test cleanup
// Recreate store since it was closed
store = newMockStore[string, int]()
// Test WithTTL
cache, err = NewTiered[string, int](store, TTL(5*time.Minute))
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
if cache.defaultTTL != 5*time.Minute {
t.Errorf("default TTL = %v; want 5m", cache.defaultTTL)
}
_ = cache.Close() //nolint:errcheck // Test cleanup
}
func TestTieredCache_Set_VariadicTTL(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store, TTL(time.Hour))
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// Set without TTL - uses default (1 hour, won't expire during test)
if err := cache.Set(ctx, "default-ttl", 1); err != nil {
t.Fatalf("Set: %v", err)
}
_, found, err := cache.Get(ctx, "default-ttl")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found {
t.Error("default-ttl should be found")
}
// Set with explicit short TTL (1 second granularity)
if err := cache.SetTTL(ctx, "short-ttl", 2, 1*time.Second); err != nil {
t.Fatalf("Set: %v", err)
}
_, found, err = cache.Get(ctx, "short-ttl")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found {
t.Error("short-ttl should be found immediately")
}
// Wait for short TTL to expire
time.Sleep(2 * time.Second)
// short-ttl should be expired in memory, default-ttl should still exist
_, found, err = cache.Get(ctx, "short-ttl")
if err != nil {
t.Fatalf("Get: %v", err)
}
if found {
// Note: might still be found if persistence doesn't check expiry
t.Log("short-ttl may still be found from persistence (expected)")
}
_, found, err = cache.Get(ctx, "default-ttl")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found {
t.Error("default-ttl should still exist (1 hour TTL)")
}
}
func TestTieredCache_SetAsync_VariadicTTL(t *testing.T) {
ctx := context.Background()
store := newMockStore[string, int]()
cache, err := NewTiered[string, int](store, TTL(time.Hour))
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
// SetAsync without TTL - uses default
if err := cache.SetAsync(ctx, "async-default", 1); err != nil {
t.Fatalf("SetAsync: %v", err)
}
// SetAsync with explicit TTL
if err := cache.SetAsyncTTL(ctx, "async-explicit", 2, 5*time.Minute); err != nil {
t.Fatalf("SetAsync: %v", err)
}
// Both should be in memory immediately
_, found, err := cache.Get(ctx, "async-default")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found {
t.Error("async-default should be found")
}
_, found, err = cache.Get(ctx, "async-explicit")
if err != nil {
t.Fatalf("Get: %v", err)
}
if !found {
t.Error("async-explicit should be found")
}
// Give async persistence time to complete
time.Sleep(50 * time.Millisecond)
// Both should be persisted
_, _, found, err = store.Get(ctx, "async-default")
if err != nil {
t.Fatalf("store.Get: %v", err)
}
if !found {
t.Error("async-default should be persisted")
}
_, _, found, err = store.Get(ctx, "async-explicit")
if err != nil {
t.Fatalf("store.Get: %v", err)
}
if !found {
t.Error("async-explicit should be persisted")
}
}
func TestTieredCache_Concurrent(t *testing.T) {
store := newMockStore[int, int]()
cache, err := NewTiered[int, int](store, Size(1000))
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
ctx := context.Background()
var wg sync.WaitGroup
// Concurrent writers
for i := range 10 {
wg.Add(1)
go func(offset int) {
defer wg.Done()
for j := range 100 {
_ = cache.Set(ctx, offset*100+j, j) //nolint:errcheck // Test concurrent access
}
}(i)
}
// Concurrent readers
for range 10 {
wg.Go(func() {
for j := range 100 {
_, _, _ = cache.Get(ctx, j) //nolint:errcheck // Test concurrent access
}
})
}
wg.Wait()
// Cache should be functional after concurrent access
if err := cache.Set(ctx, 9999, 9999); err != nil {
t.Errorf("Set after concurrent access failed: %v", err)
}
val, found, err := cache.Get(ctx, 9999)
if err != nil || !found || val != 9999 {
t.Errorf("Get after concurrent access: val=%d, found=%v, err=%v", val, found, err)
}
}
func TestTieredCache_Set_KeyValidationError(t *testing.T) {
store := &validatingMockStore[string, int]{
mockStore: newMockStore[string, int](),
}
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup
ctx := context.Background()
// Set with invalid key should return error
err = cache.Set(ctx, "invalid/key", 42)
if err == nil {
t.Error("Set with invalid key should return error")
}
// Value should NOT be in memory (validation happens before memory write)
if cache.Len() != 0 {
t.Errorf("memory cache should be empty after validation error, got %d", cache.Len())
}
}
func TestTieredCache_SetAsync_KeyValidationError(t *testing.T) {
store := &validatingMockStore[string, int]{
mockStore: newMockStore[string, int](),
}
cache, err := NewTiered[string, int](store)
if err != nil {
t.Fatalf("NewTiered: %v", err)
}
defer func() { _ = cache.Close() }() //nolint:errcheck // Test cleanup