-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathcsc_test.go
More file actions
3149 lines (2837 loc) · 100 KB
/
Copy pathcsc_test.go
File metadata and controls
3149 lines (2837 loc) · 100 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 redis
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/redis/go-redis/v9/auth"
"github.com/redis/go-redis/v9/internal/pool"
"github.com/redis/go-redis/v9/internal/proto"
"github.com/redis/go-redis/v9/maintnotifications"
"github.com/redis/go-redis/v9/push"
)
// helper to create a Cmd with the given args.
func makeCmd(args ...interface{}) Cmder {
return NewCmd(context.Background(), args...)
}
// --- isCacheable -----------------------------------------------------------
func TestIsCacheable_AllowedCommands(t *testing.T) {
allowed := []string{
"GET", "MGET", "HGET", "HMGET", "HGETALL",
"HKEYS", "HVALS", "HLEN", "HEXISTS", "HSTRLEN",
"LINDEX", "LLEN", "LPOS", "LRANGE",
"SCARD", "SISMEMBER", "SMEMBERS", "SMISMEMBER",
"SDIFF", "SINTER", "SINTERCARD", "SUNION",
"ZCARD", "ZCOUNT", "ZLEXCOUNT", "ZMSCORE",
"ZRANGE", "ZRANGEBYLEX", "ZRANGEBYSCORE",
"ZRANK", "ZREVRANGE", "ZREVRANGEBYLEX",
"ZREVRANGEBYSCORE", "ZREVRANK", "ZSCORE",
"ZDIFF", "ZINTER", "ZUNION",
"STRLEN", "GETBIT", "GETRANGE", "SUBSTR",
"BITCOUNT", "BITFIELD_RO", "BITPOS",
"EXISTS", "TYPE", "SORT_RO", "LCS",
"GEODIST", "GEOHASH", "GEOPOS", "GEOSEARCH",
"GEORADIUSBYMEMBER_RO", "GEORADIUS_RO",
"XLEN", "XRANGE", "XREVRANGE",
"JSON.GET", "JSON.MGET", "JSON.ARRINDEX", "JSON.ARRLEN",
"JSON.OBJKEYS", "JSON.OBJLEN", "JSON.RESP",
"JSON.STRLEN", "JSON.TYPE",
"TS.GET", "TS.INFO", "TS.RANGE", "TS.REVRANGE",
}
for _, name := range allowed {
// Use lower-case name as first arg (matching how go-redis sends commands)
cmd := makeCmd(name, "mykey")
if !isCacheable(cmd) {
t.Errorf("expected %q to be cacheable", name)
}
}
}
func TestIsCacheable_CaseInsensitive(t *testing.T) {
for _, name := range []string{"get", "Get", "GET", "gEt"} {
cmd := makeCmd(name, "k")
if !isCacheable(cmd) {
t.Errorf("expected %q to be cacheable (case-insensitive)", name)
}
}
}
func TestIsCacheable_WriteCommandsRejected(t *testing.T) {
writes := []string{"SET", "DEL", "HSET", "LPUSH", "SADD", "ZADD", "EXPIRE", "FLUSHDB"}
for _, name := range writes {
cmd := makeCmd(name, "k")
if isCacheable(cmd) {
t.Errorf("expected %q to NOT be cacheable", name)
}
}
}
func TestIsCacheable_XReadRejected(t *testing.T) {
// XREAD supports BLOCK and state-relative $/+ IDs, so it must not be cached.
cmd := makeCmd("XREAD", "COUNT", "5", "STREAMS", "s", "0")
if isCacheable(cmd) {
t.Error("expected XREAD to NOT be cacheable")
}
}
// TestExtractRedisKeys_WireFaithfulTypesOnly: the invalidation index must hold
// keys exactly as proto.Writer sends them, or the server's invalidation pushes
// never match and stale entries are served forever. Types whose fmt.Sprint
// rendering diverges from the wire form (pointers, bools, durations, floats...)
// must make extraction fail (want nil) so the command is served uncached.
func TestExtractRedisKeys_WireFaithfulTypesOnly(t *testing.T) {
key := "real-key"
cases := []struct {
name string
cmd Cmder
want []string
}{
{"string key", makeCmd("get", "k"), []string{"k"}},
{"[]byte key", makeCmd("get", []byte("k")), []string{"k"}},
{"int key", makeCmd("get", 123), []string{"123"}},
{"uint64 key", makeCmd("get", uint64(7)), []string{"7"}},
{"pointer key", makeCmd("get", &key), nil},
{"bool key", makeCmd("get", true), nil},
{"float key", makeCmd("get", 1.5), nil},
// Multi-key commands: one divergent key poisons the whole extraction.
{"mget with pointer key", makeCmd("mget", "a", &key, "b"), nil},
{"mget with string keys", makeCmd("mget", "a", "b"), []string{"a", "b"}},
}
for _, tc := range cases {
got := extractRedisKeys(tc.cmd)
if len(got) != len(tc.want) {
t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
continue
}
for i := range got {
if got[i] != tc.want[i] {
t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
break
}
}
}
}
func TestIsCacheable_XPendingRejected(t *testing.T) {
// XPENDING's extended form returns wall-clock-relative idle times and its
// IDLE filter is time-dependent, so it must not be cached.
for _, cmd := range []Cmder{
makeCmd("XPENDING", "s", "grp"),
makeCmd("XPENDING", "s", "grp", "IDLE", "9000", "-", "+", "10"),
} {
if isCacheable(cmd) {
t.Errorf("expected %v to NOT be cacheable", cmd.Args())
}
}
}
func TestIsCacheable_KeylessCommandRejected(t *testing.T) {
// PING has no keys; even if someone added it to the allow-list it
// should be rejected because cmdFirstKeyPos returns 0.
cmd := makeCmd("ping")
if isCacheable(cmd) {
t.Error("expected keyless command PING to NOT be cacheable")
}
}
func TestIsCacheable_RawWriteToRejected(t *testing.T) {
cmd := NewRawWriteToCmd(context.Background(), &bytes.Buffer{}, "get", "k")
if isCacheable(cmd) {
t.Fatal("RawWriteToCmd must bypass CSC to preserve direct streaming")
}
}
func TestIsSelectCmd(t *testing.T) {
for _, cmd := range []Cmder{
makeCmd("select", 1),
makeCmd("SELECT", 1),
makeCmd([]byte("select"), 1),
} {
if !isSelectCmd(cmd) {
t.Errorf("expected %v to match SELECT", cmd.Args())
}
}
for _, cmd := range []Cmder{
makeCmd("get", "select"),
makeCmd("swapdb", 0, 1),
} {
if isSelectCmd(cmd) {
t.Errorf("expected %v not to match SELECT", cmd.Args())
}
}
}
func TestCSCStateCommandMatchers(t *testing.T) {
for _, cmd := range []Cmder{
makeCmd("auth", "password"),
makeCmd("AUTH", "user", "password"),
makeCmd([]byte("auth"), "password"),
} {
if !isAuthCmd(cmd) {
t.Errorf("expected %v to match AUTH", cmd.Args())
}
}
if isAuthCmd(makeCmd("get", "auth")) {
t.Fatal("GET auth must not match AUTH")
}
for _, cmd := range []Cmder{
makeCmd("hello", 2),
makeCmd("HELLO", 3),
makeCmd([]byte("hello"), []byte("2")),
} {
if !isProtocolChangingHelloCmd(cmd) {
t.Errorf("expected %v to match state-changing HELLO", cmd.Args())
}
}
for _, cmd := range []Cmder{
makeCmd("hello"),
makeCmd("get", "hello"),
} {
if isProtocolChangingHelloCmd(cmd) {
t.Errorf("expected %v not to match state-changing HELLO", cmd.Args())
}
}
for _, cmd := range []Cmder{
makeCmd("reset"),
makeCmd("RESET"),
makeCmd([]byte("reset")),
} {
if !isResetCmd(cmd) {
t.Errorf("expected %v to match RESET", cmd.Args())
}
}
if isResetCmd(makeCmd("config", "resetstat")) {
t.Fatal("CONFIG RESETSTAT must not match RESET")
}
}
func TestIsCacheable_EmptyArgs(t *testing.T) {
cmd := makeCmd()
if isCacheable(cmd) {
t.Error("expected empty command to NOT be cacheable")
}
}
// --- buildCacheKey ---------------------------------------------------------
func TestBuildCacheKey_SimpleGet(t *testing.T) {
cmd := makeCmd("GET", "foo")
key, ok := buildCacheKey(cmd)
if !ok || key == "" {
t.Fatal("expected non-empty cache key")
}
// Same command must produce identical keys.
if key2, _ := buildCacheKey(makeCmd("GET", "foo")); key != key2 {
t.Errorf("identical commands produced different keys: %q vs %q", key, key2)
}
}
func TestBuildCacheKey_DifferentArgsDiffer(t *testing.T) {
k1, _ := buildCacheKey(makeCmd("GET", "foo"))
k2, _ := buildCacheKey(makeCmd("GET", "bar"))
if k1 == k2 {
t.Error("different keys must produce different cache keys")
}
}
func TestBuildCacheKey_CollisionSafety(t *testing.T) {
// "a|b" as one arg vs "a" and "b" as two args must differ.
k1, _ := buildCacheKey(makeCmd("GET", "a|b"))
k2, _ := buildCacheKey(makeCmd("GET", "a", "b"))
if k1 == k2 {
t.Error("length-prefixing should prevent separator collision")
}
}
func TestBuildCacheKey_BinaryData(t *testing.T) {
cmd := makeCmd("GET", []byte{0x00, 0x01, 0xff})
key, ok := buildCacheKey(cmd)
if !ok || key == "" {
t.Fatal("expected non-empty cache key for binary argument")
}
}
func TestBuildCacheKey_MultiKey(t *testing.T) {
k1, _ := buildCacheKey(makeCmd("MGET", "a", "b"))
k2, _ := buildCacheKey(makeCmd("MGET", "a", "b", "c"))
if k1 == k2 {
t.Error("different arg counts must produce different cache keys")
}
}
func TestBuildCacheKey_EmptyArgs(t *testing.T) {
cmd := makeCmd()
if key, ok := buildCacheKey(cmd); ok || key != "" {
t.Errorf("expected empty cache key for no-args command, got %q (ok=%v)", key, ok)
}
}
// --- extractRedisKeys ------------------------------------------------------
func TestExtractRedisKeys_SingleKey(t *testing.T) {
cmd := makeCmd("GET", "mykey")
keys := extractRedisKeys(cmd)
if len(keys) != 1 || keys[0] != "mykey" {
t.Errorf("expected [mykey], got %v", keys)
}
}
func TestExtractRedisKeys_SingleKeyWithExtraArgs(t *testing.T) {
// LRANGE has one key followed by start/stop — only the key should be extracted.
cmd := makeCmd("LRANGE", "mylist", "0", "10")
keys := extractRedisKeys(cmd)
if len(keys) != 1 || keys[0] != "mylist" {
t.Errorf("LRANGE: expected [mylist], got %v", keys)
}
// HGET has one key followed by a field name.
cmd = makeCmd("HGET", "myhash", "field1")
keys = extractRedisKeys(cmd)
if len(keys) != 1 || keys[0] != "myhash" {
t.Errorf("HGET: expected [myhash], got %v", keys)
}
// ZCOUNT has one key followed by min/max.
cmd = makeCmd("ZCOUNT", "myset", "-inf", "+inf")
keys = extractRedisKeys(cmd)
if len(keys) != 1 || keys[0] != "myset" {
t.Errorf("ZCOUNT: expected [myset], got %v", keys)
}
// GETRANGE has one key followed by start/end offsets.
cmd = makeCmd("GETRANGE", "mystr", "0", "5")
keys = extractRedisKeys(cmd)
if len(keys) != 1 || keys[0] != "mystr" {
t.Errorf("GETRANGE: expected [mystr], got %v", keys)
}
}
func TestExtractRedisKeys_MultiKey(t *testing.T) {
cmd := makeCmd("MGET", "a", "b", "c")
keys := extractRedisKeys(cmd)
if len(keys) != 3 {
t.Fatalf("expected 3 keys, got %d: %v", len(keys), keys)
}
want := []string{"a", "b", "c"}
for i, k := range keys {
if k != want[i] {
t.Errorf("key[%d] = %q, want %q", i, k, want[i])
}
}
}
func TestExtractRedisKeys_MultiKeyExists(t *testing.T) {
cmd := makeCmd("EXISTS", "k1", "k2", "k3")
keys := extractRedisKeys(cmd)
if len(keys) != 3 {
t.Fatalf("EXISTS: expected 3 keys, got %d: %v", len(keys), keys)
}
}
func TestExtractRedisKeys_NumKeysPattern(t *testing.T) {
// ZDIFF numkeys key [key ...]
cmd := makeCmd("ZDIFF", 2, "zs1", "zs2")
cmd.(*Cmd).SetFirstKeyPos(2)
keys := extractRedisKeys(cmd)
if len(keys) != 2 || keys[0] != "zs1" || keys[1] != "zs2" {
t.Errorf("ZDIFF: expected [zs1 zs2], got %v", keys)
}
// SINTERCARD numkeys key [key ...] LIMIT limit
cmd = makeCmd("SINTERCARD", 2, "s1", "s2", "LIMIT", 10)
keys = extractRedisKeys(cmd)
if len(keys) != 2 || keys[0] != "s1" || keys[1] != "s2" {
t.Errorf("SINTERCARD: expected [s1 s2], got %v", keys)
}
}
func TestExtractRedisKeys_LCS(t *testing.T) {
cmd := makeCmd("LCS", "key1", "key2")
keys := extractRedisKeys(cmd)
if len(keys) != 2 || keys[0] != "key1" || keys[1] != "key2" {
t.Errorf("LCS: expected [key1 key2], got %v", keys)
}
}
func TestExtractRedisKeys_JSONMGet(t *testing.T) {
// JSON.MGET key [key ...] path
cmd := makeCmd("JSON.MGET", "j1", "j2", "$.name")
keys := extractRedisKeys(cmd)
if len(keys) != 2 || keys[0] != "j1" || keys[1] != "j2" {
t.Errorf("JSON.MGET: expected [j1 j2], got %v", keys)
}
}
func TestExtractRedisKeys_KeylessCommand(t *testing.T) {
cmd := makeCmd("ping")
keys := extractRedisKeys(cmd)
if keys != nil {
t.Errorf("expected nil for keyless command, got %v", keys)
}
}
func TestIsCacheable_SortRO_ByGetExcluded(t *testing.T) {
// Plain SORT_RO reads only the sorted key: cacheable.
if cmd := makeCmd("sort_ro", "mylist", "LIMIT", "0", "10", "ALPHA"); !isCacheable(cmd) {
t.Error("plain SORT_RO should be cacheable")
}
// BY/GET forms read pattern-derived keys the reverse index cannot cover:
// their invalidations would be dropped, serving stale results forever.
if cmd := makeCmd("sort_ro", "mylist", "BY", "weight_*"); isCacheable(cmd) {
t.Error("SORT_RO ... BY must not be cacheable")
}
if cmd := makeCmd("sort_ro", "mylist", "get", "obj_*"); isCacheable(cmd) {
t.Error("SORT_RO ... GET must not be cacheable (case-insensitive)")
}
if cmd := makeCmd("sort_ro", "mylist", "LIMIT", "0", "10", "By", "weight_*", "ALPHA"); isCacheable(cmd) {
t.Error("SORT_RO with BY among other options must not be cacheable")
}
by := "BY"
if cmd := makeCmd("sort_ro", "mylist", &by, "weight_*"); isCacheable(cmd) {
t.Error("SORT_RO with pointer-encoded BY must not be cacheable")
}
}
type nonComparableCache struct {
Cache
marker []byte
}
type typedNilCache struct{ Cache }
type operationDurationRecorder struct {
OTelRecorder
calls atomic.Int32
attempts atomic.Int32
}
func (r *operationDurationRecorder) RecordOperationDuration(
_ context.Context,
_ time.Duration,
_ Cmder,
attempts int,
_ error,
_ ConnInfo,
_ int,
) {
r.calls.Add(1)
r.attempts.Store(int32(attempts))
}
func testCSCNamespacedKey(db int, key string) string {
return cscNamespacedKey(cscNamespacePrefix(db, ""), key)
}
type unusedStreamingProvider struct{}
func (unusedStreamingProvider) Subscribe(auth.CredentialsListener) (auth.Credentials, auth.UnsubscribeFunc, error) {
panic("Subscribe must not be called without a connection")
}
func TestAttachCSC_EnabledForExplicitCache(t *testing.T) {
client := NewClient(&Options{
Addr: "127.0.0.1:0",
Protocol: 3,
ClientSideCache: NewLocalCache(CacheConfig{MaxEntries: 16}),
})
defer client.Close()
if client.csc == nil {
t.Fatal("CSC must be enabled for an owner-aware cache")
}
}
func TestAttachCSC_DisablesForTypedNilCache(t *testing.T) {
var cache *typedNilCache
client := NewClient(&Options{
Addr: "127.0.0.1:0",
Protocol: 3,
ClientSideCache: cache,
})
defer client.Close()
if client.csc != nil || client.cscTrackingRequested() {
t.Fatal("a typed-nil cache must leave CSC disabled")
}
}
func TestAttachCSC_DisabledForCredentialProviders(t *testing.T) {
tests := []struct {
name string
configure func(*Options)
}{
{
name: "streaming",
configure: func(opt *Options) {
opt.StreamingCredentialsProvider = unusedStreamingProvider{}
},
},
{
name: "context",
configure: func(opt *Options) {
opt.CredentialsProviderContext = func(context.Context) (string, string, error) {
panic("provider must not be called without a connection")
}
},
},
{
name: "legacy",
configure: func(opt *Options) {
opt.CredentialsProvider = func() (string, string) {
panic("provider must not be called without a connection")
}
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
opt := &Options{
Addr: "127.0.0.1:0", // never dialed
Protocol: 3,
ClientSideCacheConfig: &ClientSideCacheConfig{MaxEntries: 16},
}
tc.configure(opt)
client := NewClient(opt)
t.Cleanup(func() { _ = client.Close() })
if client.csc != nil || client.cscActive != nil {
t.Fatal("CSC must stay detached when credentials can vary by identity")
}
if client.cscTrackingRequested() {
t.Fatal("dynamic credentials must not enable CLIENT TRACKING for CSC")
}
})
}
}
func TestAttachCSC_AllowsFixedCredentials(t *testing.T) {
client := NewClient(&Options{
Addr: "127.0.0.1:0", // never dialed
Protocol: 3,
Username: "fixed-user",
Password: "fixed-password",
ClientSideCacheConfig: &ClientSideCacheConfig{MaxEntries: 16},
})
t.Cleanup(func() { _ = client.Close() })
if client.csc == nil || client.cscActive == nil || !client.cscActive.Load() {
t.Fatal("fixed Username/Password must remain compatible with CSC")
}
}
func TestSharedCacheSeparatesFixedCredentialIdentities(t *testing.T) {
cache := NewLocalCache(CacheConfig{MaxEntries: 16})
clientA := NewClient(&Options{
Addr: "127.0.0.1:0",
Protocol: 3,
Username: "privileged",
Password: "secret-a",
ClientSideCache: cache,
})
clientB := NewClient(&Options{
Addr: "127.0.0.1:0",
Protocol: 3,
Username: "restricted",
Password: "secret-b",
ClientSideCache: cache,
})
t.Cleanup(func() {
_ = clientA.Close()
_ = clientB.Close()
})
if clientA.cscKeyPrefix == clientB.cscKeyPrefix {
t.Fatal("different fixed ACL identities must not share a cache namespace")
}
if strings.Contains(clientA.cscKeyPrefix, "secret-a") ||
strings.Contains(clientB.cscKeyPrefix, "secret-b") {
t.Fatal("cache namespaces must not retain plaintext passwords")
}
redisKeyA := cscNamespacedKey(clientA.cscKeyPrefix, "secret")
redisKeyB := cscNamespacedKey(clientB.cscKeyPrefix, "secret")
cacheKeyA := cscNamespacedKey(clientA.cscKeyPrefix, "get-secret")
cacheKeyB := cscNamespacedKey(clientB.cscKeyPrefix, "get-secret")
if !cache.set(cacheKeyA, []string{redisKeyA}, []byte("a")) ||
!cache.set(cacheKeyB, []string{redisKeyB}, []byte("b")) {
t.Fatal("failed to seed identity-scoped cache entries")
}
handlerA := lookupInvalidateHandler(clientA.pushProcessor)
if handlerA == nil {
t.Fatal("client A invalidate handler is missing")
}
if err := handlerA.HandlePushNotification(
context.Background(),
push.NotificationHandlerContext{},
[]interface{}{invalidatePushName, []interface{}{"secret"}},
); err != nil {
t.Fatalf("handle identity-scoped invalidation: %v", err)
}
if _, ok := cache.Get(context.Background(), cacheKeyA); ok {
t.Fatal("client A invalidation did not delete its identity-scoped entry")
}
if value, ok := cache.Get(context.Background(), cacheKeyB); !ok || string(value) != "b" {
t.Fatal("client A invalidation crossed into client B's identity namespace")
}
}
func TestAttachCSC_HandlerConflictDoesNotEnableTracking(t *testing.T) {
proc := push.NewProcessor()
if err := proc.RegisterHandler(invalidatePushName, &recordingHandler{}, true); err != nil {
t.Fatalf("register foreign invalidate handler: %v", err)
}
client := NewClient(&Options{
Addr: "127.0.0.1:0",
Protocol: 3,
PushNotificationProcessor: proc,
ClientSideCacheConfig: &ClientSideCacheConfig{MaxEntries: 16},
})
t.Cleanup(func() { _ = client.Close() })
if client.csc != nil || client.cscActive != nil {
t.Fatal("a handler conflict must leave CSC fully detached")
}
if client.cscTrackingRequested() {
t.Fatal("a configured cache whose attachment failed must not enable tracking")
}
if err := client.cscCommandError(NewCmd(context.Background(), "select", 1)); err != nil {
t.Fatalf("a configured cache whose attachment failed rejected SELECT: %v", err)
}
}
// TestFulfillCached_FailsClosedOnZeroConnID: with an active eviction hook a real
// serving conn id is an invariant; a zero id would leave the entry unattributed
// and never evicted on close, so fulfillCached must fail closed (not cache it).
func TestFulfillCached_FailsClosedOnZeroConnID(t *testing.T) {
cache := NewLocalCache(CacheConfig{MaxEntries: 16})
hook := &cscEvictOnRemoveHook{evictor: cache}
c := &baseClient{opt: &Options{Protocol: 3}, csc: cache, cscPoolHook: hook}
tok, sf := cache.Reserve("get:k", []string{"k"})
if !sf {
t.Fatal("Reserve should fetch")
}
if c.fulfillCached("get:k", tok, &cscFetchCapture{raw: []byte("v")}) {
t.Fatal("fulfillCached must fail closed when an eviction hook is active and connID==0")
}
if _, ok := cache.Get(context.Background(), "get:k"); ok {
t.Fatal("unattributed entry must not be cached")
}
}
func TestProcessCached_HitHonorsCanceledContext(t *testing.T) {
cache := NewLocalCache(CacheConfig{MaxEntries: 16})
c := &baseClient{
opt: &Options{Protocol: 3},
csc: cache,
cscKeyPrefix: cscNamespacePrefix(0, ""),
}
ctx, cancel := context.WithCancel(context.Background())
cmd := NewStringCmd(ctx, "get", "k")
rawKey, ok := buildCacheKey(cmd)
if !ok {
t.Fatal("buildCacheKey failed")
}
cacheKey := testCSCNamespacedKey(0, rawKey)
if !cache.set(cacheKey, []string{testCSCNamespacedKey(0, "k")}, []byte("$1\r\nv\r\n")) {
t.Fatal("failed to seed cache")
}
cancel()
if err := c.processCached(ctx, cmd, nil); !errors.Is(err, context.Canceled) {
t.Fatalf("cached hit with canceled context: got %v, want context.Canceled", err)
}
}
func TestProcessCached_NilHitIsTerminal(t *testing.T) {
cache := NewLocalCache(CacheConfig{MaxEntries: 16})
c := &baseClient{
opt: &Options{Protocol: 3},
csc: cache,
cscKeyPrefix: cscNamespacePrefix(0, ""),
}
ctx := context.Background()
cmd := NewStringCmd(ctx, "get", "missing")
rawKey, ok := buildCacheKey(cmd)
if !ok {
t.Fatal("buildCacheKey failed")
}
cacheKey := testCSCNamespacedKey(0, rawKey)
if !cache.set(cacheKey, []string{testCSCNamespacedKey(0, "missing")}, []byte("$-1\r\n")) {
t.Fatal("failed to seed negative cache entry")
}
if err := c.processCached(ctx, cmd, nil); err != Nil {
t.Fatalf("negative cache hit: got %v, want redis.Nil", err)
}
if cache.Len() != 1 {
t.Fatal("a valid redis.Nil cache hit must not be deleted")
}
}
func TestProcessCached_RecordsCacheHitDuration(t *testing.T) {
cache := NewLocalCache(CacheConfig{MaxEntries: 16})
client := NewClient(&Options{
Addr: "127.0.0.1:0",
Protocol: 3,
ClientSideCache: cache,
})
t.Cleanup(func() {
SetOTelRecorder(nil)
_ = client.Close()
})
cmd := NewStringCmd(context.Background(), "get", "key")
rawKey, ok := buildCacheKey(cmd)
if !ok {
t.Fatal("buildCacheKey failed")
}
cacheKey := cscNamespacedKey(client.cscKeyPrefix, rawKey)
if !cache.set(cacheKey, []string{cscNamespacedKey(client.cscKeyPrefix, "key")},
[]byte("$5\r\nvalue\r\n")) {
t.Fatal("failed to seed cache")
}
recorder := &operationDurationRecorder{}
SetOTelRecorder(recorder)
if got, err := client.Get(context.Background(), "key").Result(); err != nil || got != "value" {
t.Fatalf("cached GET: value=%q err=%v", got, err)
}
if got := recorder.calls.Load(); got != 1 {
t.Fatalf("operation duration calls: got %d, want 1", got)
}
if got := recorder.attempts.Load(); got != 0 {
t.Fatalf("cache hit attempts: got %d, want 0", got)
}
}
// TestCSCActive_ClonesStopServingWhenDrainerStops: a WithTimeout clone shares the
// owner's cscActive flag; stopping the owner's drainer (Close, or the GC cleanup)
// flips it, so the clone stops serving hits nothing is invalidating.
func TestCSCActive_ClonesStopServingWhenDrainerStops(t *testing.T) {
client := NewClient(&Options{
Addr: "127.0.0.1:0",
Protocol: 3,
ClientSideCacheConfig: &ClientSideCacheConfig{MaxEntries: 16},
})
defer client.Close()
if client.cscActive == nil || !client.cscActive.Load() {
t.Fatal("precondition: cscActive must be set true when CSC is enabled")
}
clone := client.WithTimeout(time.Second)
if clone.cscActive != client.cscActive {
t.Fatal("WithTimeout clone must share the owner's cscActive flag")
}
client.baseClient.stopBackgroundDrainer()
if clone.cscActive.Load() {
t.Fatal("clone must observe cscActive=false once the owner's drainer stops")
}
}
func TestStopBackgroundDrainerEvictsSharedCacheCoverage(t *testing.T) {
cache := NewLocalCache(CacheConfig{MaxEntries: 16})
client := NewClient(&Options{
Addr: "127.0.0.1:0",
Protocol: 3,
ClientSideCache: cache,
})
t.Cleanup(func() { _ = client.Close() })
hook := client.cscHook()
if hook == nil {
t.Fatal("precondition: shared-cache client must install its coverage hook")
}
const connID = uint64(44)
hook.bumpInitGen(connID)
token, _ := cache.Reserve("get:k", []string{"k"})
if !cache.FulfillOwned("get:k", token, connID, []byte("v")) {
t.Fatal("failed to seed shared cache entry")
}
client.stopBackgroundDrainer()
if _, ok := cache.Get(context.Background(), "get:k"); ok {
t.Fatal("stopping one client's drainer must evict that pool's shared-cache entries")
}
}
// TestCSCActive_CloneKeepsOwnerAlive: a surviving WithTimeout clone retains the
// canonical wrapper whose GC cleanup owns the shared drainer.
func TestCSCActive_CloneKeepsOwnerAlive(t *testing.T) {
clone, active := func() (*Client, *atomic.Bool) {
owner := NewClient(&Options{
Addr: "127.0.0.1:0",
Protocol: 3,
ClientSideCacheConfig: &ClientSideCacheConfig{MaxEntries: 16},
})
cl := owner.WithTimeout(time.Second)
// owner falls out of lexical scope here, but cl must keep it reachable
// because its cleanup owns the drainer cl relies on.
return cl, owner.cscActive
}()
if active == nil {
t.Fatal("precondition: cscActive must be set")
}
for range 20 {
runtime.GC()
time.Sleep(20 * time.Millisecond)
}
if !active.Load() {
t.Fatal("a reachable clone must keep its CSC drainer owner alive")
}
if clone.cscLifecycleOwner == nil {
t.Fatal("CSC clone must retain its canonical lifecycle owner")
}
if err := clone.Close(); err != nil {
t.Fatalf("close clone: %v", err)
}
if active.Load() {
t.Fatal("closing a CSC clone must stop its canonical owner's drainer")
}
}
// TestReadBufferSize_ClampedForRESP3: a read buffer too small to hold a push
// header is clamped for RESP3 so client-reserved Pub/Sub frames are never
// consumed before their name is known.
func TestReadBufferSize_ClampedForRESP3(t *testing.T) {
opt := &Options{Addr: "x:1", Protocol: 3, ReadBufferSize: 16}
opt.init()
if opt.ReadBufferSize != proto.MinRESP3ReadBufferSize {
t.Fatalf("RESP3 ReadBufferSize should clamp to %d, got %d",
proto.MinRESP3ReadBufferSize, opt.ReadBufferSize)
}
}
// TestReadBufferSize_NotClampedForRESP2: RESP2 has no push frames, so a small
// buffer is left as configured.
func TestReadBufferSize_NotClampedForRESP2(t *testing.T) {
opt := &Options{Addr: "x:1", Protocol: 2, ReadBufferSize: 16}
opt.init()
if opt.ReadBufferSize != 16 {
t.Fatalf("RESP2 ReadBufferSize should not be clamped, got %d", opt.ReadBufferSize)
}
}
// TestProcessCached_CachesServerNilReply exercises the complete miss/fill/hit
// path. The second GET must be answered locally even though the cached command
// still returns redis.Nil to its caller.
func TestProcessCached_CachesServerNilReply(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
t.Cleanup(func() { _ = ln.Close() })
var getCalls atomic.Int32
go func() {
for {
netConn, err := ln.Accept()
if err != nil {
return
}
go serveNegativeCacheTestConn(netConn, &getCalls)
}
}()
cache := NewLocalCache(CacheConfig{MaxEntries: 16})
client := NewClient(&Options{
Addr: ln.Addr().String(),
Protocol: 3,
PoolSize: 1,
MaxRetries: -1,
DisableIdentity: true,
MaintNotificationsConfig: &maintnotifications.Config{
Mode: maintnotifications.ModeDisabled,
},
ClientSideCache: cache,
})
t.Cleanup(func() { _ = client.Close() })
for i := 0; i < 2; i++ {
if err := client.Get(context.Background(), "missing").Err(); err != Nil {
t.Fatalf("GET %d: got %v, want redis.Nil", i+1, err)
}
}
if got := getCalls.Load(); got != 1 {
t.Fatalf("server received %d GETs, want 1 (second lookup should hit CSC)", got)
}
if cache.Len() != 1 {
t.Fatalf("negative lookup was not retained in CSC, Len=%d", cache.Len())
}
}
func serveNegativeCacheTestConn(netConn net.Conn, getCalls *atomic.Int32) {
serveTestRESPConn(netConn, func(command string) string {
switch command {
case "hello":
return "%0\r\n"
case "get":
getCalls.Add(1)
return "$-1\r\n"
default:
return "+OK\r\n"
}
})
}
func serveTestRESPConn(netConn net.Conn, replyFor func(command string) string) {
defer netConn.Close()
scanner := bufio.NewScanner(netConn)
for scanner.Scan() {
header := scanner.Text()
if !strings.HasPrefix(header, "*") {
return
}
n, err := strconv.Atoi(strings.TrimPrefix(header, "*"))
if err != nil || n <= 0 {
return
}
command := ""
for i := 0; i < n; i++ {
if !scanner.Scan() || !strings.HasPrefix(scanner.Text(), "$") || !scanner.Scan() {
return
}
if i == 0 {
command = strings.ToLower(scanner.Text())
}
}
if _, err := netConn.Write([]byte(replyFor(command))); err != nil {
return
}
}
}
// TestIsClientTrackingCmd pins the guard's matcher: any CLIENT TRACKING
// subcommand matches, other CLIENT subcommands (incl. TRACKINGINFO) do not.
func TestIsClientTrackingCmd(t *testing.T) {
tracking := "tracking"
matching := []Cmder{
makeCmd("client", "tracking", "on"),
makeCmd("client", "tracking", "off"),
makeCmd("CLIENT", "TRACKING", "on", "bcast"),
makeCmd("Client", "Tracking"),
makeCmd([]byte("client"), []byte("tracking"), "off"), // raw []byte args
makeCmd("client", &tracking, "off"), // proto.Writer dereferences *string
}
for _, cmd := range matching {
if !isClientTrackingCmd(cmd) {
t.Errorf("expected %v to match CLIENT TRACKING", cmd.Args())
}
}
nonMatching := []Cmder{
makeCmd("client", "trackinginfo"),
makeCmd("client", "info"),
makeCmd("client", "kill", "id", "1"),
makeCmd("get", "tracking"),
makeCmd("client"),
}
for _, cmd := range nonMatching {
if isClientTrackingCmd(cmd) {
t.Errorf("expected %v NOT to match CLIENT TRACKING", cmd.Args())
}
}
}
// TestClientTrackingRejectedWithCSC: on a client with the built-in cache
// configured, CLIENT TRACKING must be rejected before it reaches a connection —
// it would flip an arbitrary pool conn's tracking state and leave it filling
// the cache with entries the server never invalidates. The guard fires without
// dialing, so no server is needed.
func TestClientTrackingRejectedWithCSC(t *testing.T) {
ctx := context.Background()
c := NewClient(&Options{
Addr: "localhost:1", // never dialed: the guard fires first
Protocol: 3,
ClientSideCacheConfig: &ClientSideCacheConfig{MaxEntries: 16},
})
t.Cleanup(func() { _ = c.Close() })
if err := c.ClientTrackingOff(ctx).Err(); !errors.Is(err, errClientTrackingWithCSC) {
t.Fatalf("ClientTrackingOff must be rejected with CSC enabled, got %v", err)
}
if err := c.ClientTrackingOn(ctx, nil).Err(); !errors.Is(err, errClientTrackingWithCSC) {
t.Fatalf("ClientTrackingOn must be rejected with CSC enabled, got %v", err)
}
// The raw escape hatch is caught too: the guard matches leading args.
// (Non-tracking CLIENT subcommands are covered by TestIsClientTrackingCmd's
// non-matching cases — probing one here would dial for seconds.)
if err := c.Do(ctx, "client", "tracking", "off").Err(); !errors.Is(err, errClientTrackingWithCSC) {
t.Fatalf("raw Do(client tracking off) must be rejected with CSC enabled, got %v", err)
}
tracking := "tracking"
if err := c.Do(ctx, "client", &tracking, "off").Err(); !errors.Is(err, errClientTrackingWithCSC) {
t.Fatalf("pointer-encoded CLIENT TRACKING must be rejected with CSC enabled, got %v", err)
}
}
// TestClientTrackingRejectedWithCSC_Pipeline: pipelines bypass process(), so
// generalProcessPipeline mirrors the guard — a CLIENT TRACKING frame inside a
// Pipeline or TxPipeline must be rejected on a CSC client too.
func TestClientTrackingRejectedWithCSC_Pipeline(t *testing.T) {
ctx := context.Background()
c := NewClient(&Options{
Addr: "localhost:1", // never dialed: the guard fires first
Protocol: 3,
ClientSideCacheConfig: &ClientSideCacheConfig{MaxEntries: 16},