{{ message }}
Repository navigation
Expand file tree
/
Copy pathcommand_metadata.go
More file actions
1369 lines (1272 loc) · 41.4 KB
/
Copy pathcommand_metadata.go
File metadata and controls
1369 lines (1272 loc) · 41.4 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 (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"maps"
"math/rand"
"reflect"
"slices"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/redis/go-redis/v9/internal"
)
// Per-client command-metadata resolution. A client resolves COMMAND metadata
// records into an immutable commandMetadataView (app overrides > built-in
// corrections > live COMMAND output > shipped snapshot) and publishes it
// through an atomic pointer. Every command invocation reads exactly one view.
// In PreferLive mode a background worker upgrades the static view with the
// server's live COMMAND output.
// CommandMetadataMode selects metadata resolution for CSC and Cluster routing.
//
// Experimental: this API may change in a minor release.
type CommandMetadataMode int
const (
// CommandMetadataStatic uses the snapshot and overrides without network
// calls or goroutines, unless a ClusterClient's Dynamic Resolver is used.
CommandMetadataStatic CommandMetadataMode = iota
// CommandMetadataPreferLive starts static and fetches live metadata after
// the first connection. Older Redis versions and servers not identified as
// Redis get conservative CSC exclusions.
//
// Security: live metadata controls routing and caching. Use TLS because a
// compromised source can misroute commands, serve stale data, or suppress a
// write by falsely classifying it as cacheable. Redis 8.10+ records are
// authoritative except for built-in corrections.
CommandMetadataPreferLive
)
// CommandMetadataConfig configures metadata for Options and ClusterOptions.
// Its zero value is static.
//
// Experimental: this API may change in a minor release.
type CommandMetadataConfig struct {
Mode CommandMetadataMode
// Overrides take precedence over every other metadata source. Keys are
// case-insensitive; use "parent|child" for subcommands. Nil marks a command
// unknown. Unsafe cacheable overrides can serve stale data. The map and
// records are copied at client creation.
Overrides map[string]*CommandInfo
// RefreshInterval periodically refreshes live metadata with jitter.
// Zero disables periodic refresh; detected server or topology changes
// still trigger a refresh.
RefreshInterval time.Duration
}
// commandMetadataView is one immutable resolution of command metadata.
type commandMetadataView struct {
// generation identifies this view across clients and refreshes.
generation uint64
// records holds resolved metadata by lowercase command name.
records map[string]*CommandInfo
// tombstones block fallback for malformed or explicitly disabled commands.
tombstones map[string]struct{}
// shadowedParents are bare records pruned to expose their subcommands.
subcommandParents map[string]struct{}
shadowedParents map[string]struct{}
// CSC and routing derive separate decisions from the shared records.
cscTable map[string]cscCommandMeta
routingTable map[string]*routingCommandMeta
// cscFingerprint identifies the eligibility decisions. It is part of
// every cache-entry key — never of the Redis-key invalidation index — so
// entries cached under different metadata never mix, while invalidations
// keep reaching every generation.
cscFingerprint string
// live is true when the view was built from live COMMAND output.
live bool
serverVersion string
}
// defaultCommandMetadataView is built only when CSC or metadata routing needs
// it, and is shared by clients without overrides or live mode.
var defaultCommandMetadataView = sync.OnceValue(func() *commandMetadataView {
return buildCommandMetadataView(nil, nil)
})
var commandMetadataGeneration atomic.Uint64
// The snapshot itself is static data. Only live compatibility resolution needs
// a name index; ordinary static view construction can iterate the records.
var commandInfoSnapshotByName = sync.OnceValue(func() map[string]*CommandInfo {
index := make(map[string]*CommandInfo, len(commandInfoSnapshotRecords))
for i := range commandInfoSnapshotRecords {
info := &commandInfoSnapshotRecords[i]
index[info.Name] = info
}
return index
})
// commandMetadataCompatibilityCorrection adds CSC exclusions missing before
// Redis 8.10.
type commandMetadataCompatibilityCorrection struct {
flags []string
tips []string
}
// commandMetadataPre810Corrections contains only pre-8.10 CSC exclusions.
// Redis 8.10+ metadata stays authoritative except for built-in corrections.
var commandMetadataPre810Corrections = sync.OnceValue(func() map[string]commandMetadataCompatibilityCorrection {
corrections := make(map[string]commandMetadataCompatibilityCorrection)
for i := range commandInfoSnapshotRecords {
info := &commandInfoSnapshotRecords[i]
var correction commandMetadataCompatibilityCorrection
if !commandRecordHas(info, "readonly", false) {
// Do not let old metadata make a known write command cacheable.
correction.tips = append(correction.tips, "dont_cache")
}
for _, flag := range info.Flags {
switch flag {
case "script_runner", "blocking":
correction.flags = append(correction.flags, flag)
}
}
for _, tip := range info.Tips {
switch tip {
case "dont_cache", "nondeterministic_output":
correction.tips = append(correction.tips, tip)
}
}
if len(correction.flags) > 0 || len(correction.tips) > 0 {
corrections[info.Name] = correction
}
}
return corrections
})
// buildCommandMetadataView builds a view, treating live input as Redis 8.10.
func buildCommandMetadataView(live, overrides map[string]*CommandInfo) *commandMetadataView {
return buildCommandMetadataViewForServer(live, overrides, "redis", "8.10")
}
// buildCommandMetadataViewForServer resolves records and derived decisions.
func buildCommandMetadataViewForServer(
live, overrides map[string]*CommandInfo,
serverName, serverVersion string,
) *commandMetadataView {
return buildCommandMetadataViewForServerWithLegacy(
live,
overrides,
serverName,
serverVersion,
nil,
)
}
func buildCommandMetadataViewForServerWithLegacy(
live, overrides map[string]*CommandInfo,
serverName, serverVersion string,
liveLegacyRecords map[string]struct{},
) *commandMetadataView {
records := make(map[string]*CommandInfo, len(commandInfoSnapshotRecords)+len(overrides))
tombstones := make(map[string]struct{})
parents := make(map[string]struct{})
markParent := func(name string) {
for offset := 0; ; {
i := strings.IndexByte(name[offset:], '|')
if i < 0 {
break
}
offset += i
if offset > 0 {
parents[name[:offset]] = struct{}{}
}
offset++
}
}
for i := range commandInfoSnapshotRecords {
// Generated records are normalized and immutable. Mutable layers below
// copy their inputs before applying changes.
info := &commandInfoSnapshotRecords[i]
records[info.Name] = info
markParent(info.Name)
}
legacyLive := make(map[string]struct{}, len(liveLegacyRecords))
for name := range liveLegacyRecords {
legacyLive[internal.ToLower(name)] = struct{}{}
}
liveSupportsCSC := commandMetadataSupportsCSC(serverName, serverVersion)
seenLive := make(map[string]struct{}, len(live))
for name, info := range live {
lower := internal.ToLower(name)
// Tombstoned children still prevent their parent from shadowing them.
markParent(lower)
if _, duplicate := seenLive[lower]; duplicate {
delete(records, lower)
tombstones[lower] = struct{}{}
continue
}
seenLive[lower] = struct{}{}
if info == nil {
// Live nil explicitly blocks snapshot fallback and corrections.
delete(records, lower)
tombstones[lower] = struct{}{}
continue
}
_, legacy := legacyLive[lower]
records[lower] = resolveLiveCommandMetadata(
lower,
info,
liveSupportsCSC,
legacy,
)
}
// Apply built-in corrections before deriving CSC and routing decisions.
for name, correction := range commandMetadataCorrections {
markParent(name)
if _, tombstoned := tombstones[name]; tombstoned {
continue
}
rec := &CommandInfo{Name: name}
if base := records[name]; base != nil {
rec = cloneCommandInfo(base)
}
rec.Tips = appendCommandMetadataTokens(rec.Tips, correction.tips...)
rec.Flags = removeCommandMetadataTokens(rec.Flags, correction.removeFlags...)
if correction.keySpecs != nil {
rec.KeySpecs = cloneCommandInfo(&CommandInfo{KeySpecs: correction.keySpecs}).KeySpecs
rec.FirstKeyPos = correction.firstKeyPos
rec.LastKeyPos = correction.lastKeyPos
rec.StepCount = correction.stepCount
}
rec.ReadOnly = commandRecordHas(rec, "readonly", false)
records[name] = rec
}
seenOverrides := make(map[string]struct{}, len(overrides))
for name, info := range overrides {
lower := internal.ToLower(name)
markParent(lower)
if _, duplicate := seenOverrides[lower]; duplicate {
delete(records, lower)
tombstones[lower] = struct{}{}
continue
}
seenOverrides[lower] = struct{}{}
if info == nil {
// nil means "unknown": fail closed, don't expose lower layers.
delete(records, lower)
tombstones[lower] = struct{}{}
continue
}
// Overrides replace all lower-priority records and corrections.
delete(tombstones, lower)
records[lower] = cloneCommandInfoForName(lower, info)
}
table := make(map[string]cscCommandMeta, len(records))
for name, info := range records {
table[name] = cscDeriveMeta(info)
}
// Keep only parents whose arity permits a bare invocation. Lookup still
// checks subcommands first, so a parent cannot shadow its children.
shadowedParents := make(map[string]struct{})
for parent := range parents {
if _, shadowed := table[parent]; shadowed && !commandMetadataAllowsBareInvocation(records[parent]) {
delete(table, parent)
shadowedParents[parent] = struct{}{}
}
}
view := &commandMetadataView{
generation: commandMetadataGeneration.Add(1),
records: records,
tombstones: tombstones,
subcommandParents: parents,
shadowedParents: shadowedParents,
cscTable: table,
routingTable: deriveRoutingTable(records, shadowedParents),
cscFingerprint: cscTableFingerprint(table),
serverVersion: serverVersion,
}
linkRoutingTemplates(view)
return view
}
func commandMetadataAllowsBareInvocation(info *CommandInfo) bool {
return info != nil && (info.Arity == 1 || info.Arity == -1)
}
// commandMetadataSupportsCSC reports whether live metadata has all CSC
// exclusion signals. Only Redis 8.10+ defines the complete set.
func commandMetadataSupportsCSC(serverName, version string) bool {
if serverName != "redis" {
return false
}
parts := strings.SplitN(version, ".", 3)
if len(parts) < 2 {
return false
}
major, err := strconv.Atoi(parts[0])
if err != nil {
return false
}
minor, err := strconv.Atoi(parts[1])
if err != nil {
return false
}
return major > 8 || major == 8 && minor >= 10
}
// resolveLiveCommandMetadata applies server-specific restrictions to the
// shared record before consumers derive decisions.
func resolveLiveCommandMetadata(
name string,
info *CommandInfo,
liveSupportsCSC bool,
legacy bool,
) *CommandInfo {
resolved := cloneCommandInfoForName(name, info)
snapshot, snapshotKnown := commandInfoSnapshotByName()[name]
if legacy && snapshotKnown {
// Redis 5/6 COMMAND records cannot advertise routing policies. Keep
// the known policies while retaining the server's flags and key positions.
for _, tip := range snapshot.Tips {
if strings.HasPrefix(tip, requestPolicy+":") || strings.HasPrefix(tip, responsePolicy+":") {
resolved.Tips = appendCommandMetadataTokens(resolved.Tips, tip)
}
}
}
if !liveSupportsCSC {
if correction, ok := commandMetadataPre810Corrections()[name]; ok {
resolved.Flags = appendCommandMetadataTokens(resolved.Flags, correction.flags...)
resolved.Tips = appendCommandMetadataTokens(resolved.Tips, correction.tips...)
}
}
// Preserve legacy records for routing, but exclude unprovable records from
// CSC. Snapshot-known pre-8.10 records keep their known exclusions above.
if (!liveSupportsCSC && !snapshotKnown) || (liveSupportsCSC && legacy) {
resolved.Tips = appendCommandMetadataTokens(resolved.Tips, "dont_cache")
}
return resolved
}
func cloneCommandInfoForName(name string, info *CommandInfo) *CommandInfo {
cloned := cloneCommandInfo(info)
cloned.Name = internal.ToLower(name)
for i, flag := range cloned.Flags {
cloned.Flags[i] = normalizeCommandMetadataFlag(flag)
}
for i, tip := range cloned.Tips {
cloned.Tips[i] = normalizeCommandMetadataTip(tip)
}
for i := range cloned.KeySpecs {
spec := &cloned.KeySpecs[i]
spec.BeginSearch = normalizeCommandMetadataEnum(
spec.BeginSearch,
"index", "keyword", "unknown",
)
spec.FindKeys = normalizeCommandMetadataEnum(
spec.FindKeys,
"range", "keynum", "unknown",
)
for j, flag := range spec.Flags {
spec.Flags[j] = normalizeCommandMetadataKeyFlag(flag)
}
}
cloned.ReadOnly = commandRecordHas(cloned, "readonly", false)
return cloned
}
func normalizeCommandMetadataFlag(flag string) string {
key, _, hasValue := strings.Cut(flag, ":")
lowerKey := internal.ToLower(key)
switch lowerKey {
case "blocking", "script_runner":
// Preserve malformed negative signals conservatively.
return lowerKey
case "readonly":
if !hasValue {
return lowerKey
}
return flag
default:
return flag
}
}
func normalizeCommandMetadataTip(tip string) string {
key, value, hasValue := strings.Cut(tip, ":")
lowerKey := internal.ToLower(key)
switch lowerKey {
case "dont_cache", "nondeterministic_output":
// Preserve malformed negative signals conservatively.
return lowerKey
case requestPolicy:
if hasValue {
return lowerKey + ":" + normalizeCommandMetadataEnum(
value,
"", "default", "none", "all_nodes", "all_shards", "multi_shard", "special",
)
}
return lowerKey
case responsePolicy:
if hasValue {
return lowerKey + ":" + normalizeCommandMetadataEnum(
value,
"default(keyless)", "default(hashslot)", "all_succeeded", "one_succeeded",
"agg_sum", "agg_min", "agg_max", "agg_logical_and", "agg_logical_or", "special",
)
}
return lowerKey
}
return tip
}
func normalizeCommandMetadataEnum(value string, known ...string) string {
lower := internal.ToLower(value)
if slices.Contains(known, lower) {
return lower
}
return value
}
func normalizeCommandMetadataKeyFlag(flag string) string {
upper := strings.ToUpper(flag)
switch upper {
case "RO", "RW", "OW", "RM":
return upper
}
lower := internal.ToLower(flag)
switch lower {
case "access", "update", "insert", "delete", "not_key", "incomplete", "variable_flags", "prefix":
return lower
default:
return flag
}
}
// commandMetadataKeySpecFlags is the validated key-spec meaning shared by CSC
// and Cluster routing. Unknown and prefix flags fail closed.
type commandMetadataKeySpecFlags struct {
routingUsable bool
cscComplete bool
planComplete bool
}
func classifyCommandMetadataKeySpecFlags(flags []string) commandMetadataKeySpecFlags {
seen := make(map[string]struct{}, len(flags))
accessModes := 0
actions := 0
incomplete := false
notKey := false
for _, flag := range flags {
if _, duplicate := seen[flag]; duplicate {
return commandMetadataKeySpecFlags{}
}
seen[flag] = struct{}{}
switch flag {
case "RO", "RW", "OW", "RM":
accessModes++
case "access", "update", "insert", "delete":
actions++
case "variable_flags":
case "incomplete":
incomplete = true
case "not_key":
notKey = true
case "prefix":
return commandMetadataKeySpecFlags{}
default:
return commandMetadataKeySpecFlags{}
}
}
// not_key arguments can route by slot but cannot prove CSC invalidation.
if notKey {
if accessModes != 0 || actions != 0 {
return commandMetadataKeySpecFlags{}
}
return commandMetadataKeySpecFlags{
routingUsable: true,
planComplete: !incomplete,
}
}
// Ordinary key specs require exactly one access mode.
if accessModes != 1 {
return commandMetadataKeySpecFlags{}
}
return commandMetadataKeySpecFlags{
routingUsable: true,
cscComplete: !incomplete,
planComplete: !incomplete,
}
}
func appendCommandMetadataTokens(tokens []string, additions ...string) []string {
for _, addition := range additions {
if !slices.Contains(tokens, addition) {
tokens = append(tokens, addition)
}
}
return tokens
}
func removeCommandMetadataTokens(tokens []string, removals ...string) []string {
if len(removals) == 0 {
return tokens
}
return slices.DeleteFunc(tokens, func(token string) bool {
return slices.Contains(removals, token)
})
}
// cloneCommandInfo deep-copies a record so the copy can be mutated or
// published independently of the source.
func cloneCommandInfo(info *CommandInfo) *CommandInfo {
cp := *info
cp.Flags = append([]string(nil), info.Flags...)
cp.ACLFlags = append([]string(nil), info.ACLFlags...)
cp.Tips = append([]string(nil), info.Tips...)
if info.KeySpecs != nil {
cp.KeySpecs = make([]KeySpec, len(info.KeySpecs))
for i, ks := range info.KeySpecs {
cp.KeySpecs[i] = ks
cp.KeySpecs[i].Flags = append([]string(nil), ks.Flags...)
}
}
if info.CommandPolicy != nil {
cp.CommandPolicy = cloneRoutingPolicy(info.CommandPolicy)
}
return &cp
}
// cscTableFingerprint hashes the derived eligibility table into a short
// stable token. Cryptographic (truncated SHA-256): in PreferLive mode the
// input is server-influenced, and a forged collision with an honest view's
// fingerprint would let a poisoned generation's entries survive a refresh.
func cscTableFingerprint(table map[string]cscCommandMeta) string {
names := make([]string, 0, len(table))
for name := range table {
names = append(names, name)
}
sort.Strings(names)
h := sha256.New()
buf := make([]byte, 0, 128)
for _, name := range names {
m := table[name]
buf = append(buf[:0], name...)
buf = append(buf, 0)
for _, value := range [...]int64{
int64(m.bits), int64(m.extract), int64(m.guard),
int64(m.firstKey), int64(m.lastKey), int64(m.step), int64(m.numkeysAt),
} {
buf = strconv.AppendInt(buf, value, 10)
buf = append(buf, ' ')
}
buf[len(buf)-1] = '\n'
h.Write(buf)
}
var digest [sha256.Size]byte
return hex.EncodeToString(h.Sum(digest[:0])[:16])
}
// commandMetadataFetchResult separates publication identity from the server
// name and version used for compatibility rules.
type commandMetadataFetchResult struct {
records map[string]*CommandInfo
legacyRecords map[string]struct{}
serverName string
serverVersion string
serverFingerprint string
}
func (m commandMetadataFetchResult) equal(other commandMetadataFetchResult) bool {
return m.serverName == other.serverName &&
m.serverVersion == other.serverVersion &&
m.serverFingerprint == other.serverFingerprint &&
maps.Equal(m.legacyRecords, other.legacyRecords) &&
maps.EqualFunc(m.records, other.records, func(a, b *CommandInfo) bool {
return reflect.DeepEqual(a, b)
})
}
// A successful fetch transfers ownership of its records to the store.
type commandMetadataFetchFunc func(context.Context) (commandMetadataFetchResult, error)
// commandMetadataStore publishes immutable views for one client. Its pointer
// is shared with clones; the attaching client owns the worker.
type commandMetadataStore struct {
current atomic.Pointer[commandMetadataView]
// A dynamic resolver activates live tracking on its first lookup, including
// for a statically configured store. Constructing an unused resolver does not.
liveRequested atomic.Bool
mode CommandMetadataMode
overrides map[string]*CommandInfo
refreshInterval time.Duration
fetch commandMetadataFetchFunc
// static is the initial and fallback view.
static *commandMetadataView
// lastFetch is the source of the last successfully published live view.
// Only the active refresh attempt reads or replaces it.
lastFetch commandMetadataFetchResult
// fetchCtx is cancelled by signalStop so Close never waits out an
// in-flight fetch's own timeout.
fetchCtx context.Context
fetchCancel context.CancelFunc
mu sync.Mutex
refreshDone chan struct{} // guarded by mu; non-nil while one attempt owns lastFetch
initialDone bool // one completed attempt ends foreground verification
retryAt time.Time // background cooldown survives new refresh requests
backoff time.Duration
started bool
refresh chan struct{}
refreshLive atomic.Bool // A node identity observation also needs a live-view refresh.
stop chan struct{}
done chan struct{}
stopOnce sync.Once
// serverFp identifies the current server. serverEpoch also rejects ABA
// changes during a refresh. Both are guarded by mu.
serverFp string
serverEpoch uint64
}
// newCommandMetadataStore returns nil for configs equivalent to the static
// default, letting those clients share defaultCommandMetadataView with zero
// allocations.
func newCommandMetadataStore(
cfg *CommandMetadataConfig,
fetch commandMetadataFetchFunc,
) *commandMetadataStore {
return newCommandMetadataStoreWithLiveRequirement(cfg, fetch, false)
}
// newCommandMetadataStoreForLive creates a store even for static configuration.
func newCommandMetadataStoreForLive(
cfg *CommandMetadataConfig,
fetch commandMetadataFetchFunc,
) *commandMetadataStore {
return newCommandMetadataStoreWithLiveRequirement(cfg, fetch, true)
}
func newCommandMetadataStoreWithLiveRequirement(
cfg *CommandMetadataConfig,
fetch commandMetadataFetchFunc,
requireLive bool,
) *commandMetadataStore {
if cfg == nil {
cfg = &CommandMetadataConfig{}
}
if !requireLive && cfg.Mode == CommandMetadataStatic && len(cfg.Overrides) == 0 {
return nil
}
// Deep-copy the overrides: refreshOnce re-reads them on every rebuild,
// and an application mutating its config map would race the worker.
var overrides map[string]*CommandInfo
if len(cfg.Overrides) > 0 {
overrides = make(map[string]*CommandInfo, len(cfg.Overrides))
for name, info := range cfg.Overrides {
name = internal.ToLower(name)
if _, duplicate := overrides[name]; duplicate {
// Tombstone ambiguous case-colliding overrides.
overrides[name] = nil
continue
}
if info == nil {
overrides[name] = nil
continue
}
overrides[name] = cloneCommandInfo(info)
}
}
s := &commandMetadataStore{
mode: cfg.Mode,
overrides: overrides,
refreshInterval: cfg.RefreshInterval,
fetch: fetch,
refresh: make(chan struct{}, 1),
stop: make(chan struct{}),
done: make(chan struct{}),
}
s.fetchCtx, s.fetchCancel = context.WithCancel(context.Background())
if len(overrides) == 0 {
s.static = defaultCommandMetadataView()
} else {
s.static = buildCommandMetadataView(nil, overrides)
}
s.current.Store(s.static)
// An override keyed by a bare container name ("memory") is pruned in
// favor of its subcommand entries and would otherwise vanish silently.
for name, info := range overrides {
if info == nil {
continue
}
if _, shadowed := s.static.shadowedParents[name]; shadowed {
internal.Logger.Printf(context.Background(),
"redis: CommandMetadata override %q targets a container command and has no effect; key it \"parent|child\"", name)
}
}
return s
}
func (s *commandMetadataStore) view() *commandMetadataView {
return s.current.Load()
}
func (s *commandMetadataStore) wantsServerHello() bool {
return s != nil && (s.mode == CommandMetadataPreferLive || s.liveRequested.Load())
}
// onConnInit runs after each successful connection initialization: in
// live mode it schedules the upgrade until one succeeds. Later drift without
// a new connection (module loads, upgrades) is covered by RefreshInterval.
func (s *commandMetadataStore) onConnInit() {
if !s.wantsServerHello() {
return
}
if v := s.current.Load(); v != nil && v.live {
return
}
s.requestRefresh()
}
// ensureLive waits for one initial verification. Later calls use the conservative
// view immediately while background retries finish compatibility checks.
func (s *commandMetadataStore) ensureLive(ctx context.Context) error {
if s == nil || s.fetch == nil {
return fmt.Errorf("redis: live command metadata fetch is unavailable")
}
if err := ctx.Err(); err != nil {
return err
}
if !s.liveRequested.Load() && s.liveRequested.CompareAndSwap(false, true) && s.refreshInterval > 0 {
// Periodic refresh is opt-in, including after an explicit dynamic lookup.
s.startWorker()
}
if v := s.current.Load(); v != nil && v.live {
return nil
}
err := s.refreshMetadata(ctx, commandMetadataInitialRefresh)
if err != nil {
s.requestRefresh()
}
return err
}
// onServerHello retires live metadata when the server identity changes.
func (s *commandMetadataStore) onServerHello(fp string) {
if !s.wantsServerHello() {
return
}
s.mu.Lock()
changed := fp != s.serverFp
if changed {
s.serverFp = fp
s.serverEpoch++
if v := s.current.Load(); v != nil && v.live {
// Decide on static metadata until the new server's arrives.
s.current.Store(s.static)
}
}
s.mu.Unlock()
if !changed {
s.onConnInit()
return
}
s.requestRefresh()
}
// onClusterServerHelloReply keeps node callbacks dormant until live metadata
// is requested. A nil reply represents a connection initialized without HELLO.
func (s *commandMetadataStore) onClusterServerHelloReply(hello map[string]interface{}) {
if !s.wantsServerHello() {
return
}
fingerprint := ""
if hello != nil {
fingerprint = helloServerFingerprint(hello)
}
s.onClusterServerHello(fingerprint)
}
// onClusterServerHello schedules verification without adopting one node's
// identity. The cluster fetch checks siblings before retiring the live view.
// An empty fingerprint always requests verification, including during a fetch.
func (s *commandMetadataStore) onClusterServerHello(fp string) {
if !s.wantsServerHello() {
return
}
if fp != "" && fp == s.serverFingerprint() {
s.onConnInit()
return
}
s.requestVerification()
}
// requestVerification checks identity even when metadata is already live.
// HELLO-fallback reconnects cannot prove that the previous identity still holds.
func (s *commandMetadataStore) requestVerification() {
if !s.wantsServerHello() {
return
}
s.refreshLive.Store(true)
s.requestRefresh()
}
func (s *commandMetadataStore) serverFingerprint() string {
fp, _ := s.serverIdentity()
return fp
}
func (s *commandMetadataStore) serverIdentity() (string, uint64) {
s.mu.Lock()
defer s.mu.Unlock()
return s.serverFp, s.serverEpoch
}
// publishLiveView atomically validates the server identity and publishes the
// fetched view. It adopts the fetched identity when none was known.
func (s *commandMetadataStore) publishLiveView(
expectedFp string,
expectedEpoch uint64,
fetchedFp string,
view *commandMetadataView,
) bool {
s.mu.Lock()
defer s.mu.Unlock()
if s.serverFp != expectedFp || s.serverEpoch != expectedEpoch {
return false
}
// Never publish metadata without a verifiable source identity.
if fetchedFp == "" || expectedFp != "" && expectedFp != fetchedFp {
return false
}
if expectedFp == "" && fetchedFp != "" {
s.serverFp = fetchedFp
}
s.current.Store(view)
return true
}
// requestRefresh schedules one background refresh; pending requests coalesce.
func (s *commandMetadataStore) requestRefresh() {
if !s.wantsServerHello() || s.fetch == nil {
return
}
s.startWorker()
select {
case s.refresh <- struct{}{}:
default:
}
}
// invalidateLiveAndRequestRefresh retires old metadata and schedules a refresh.
func (s *commandMetadataStore) invalidateLiveAndRequestRefresh() {
s.invalidateLive()
s.requestRefresh()
}
// beginParentSourceChange blocks refresh publication across a topology change.
func (s *commandMetadataStore) beginParentSourceChange() {
if s == nil {
return
}
s.mu.Lock()
s.invalidateLiveLocked()
}
func (s *commandMetadataStore) finishParentSourceChange() {
if s == nil {
return
}
s.mu.Unlock()
s.requestRefresh()
}
// invalidateLive retires the live view without starting a fetch.
func (s *commandMetadataStore) invalidateLive() {
if s == nil {
return
}
s.mu.Lock()
s.invalidateLiveLocked()
s.mu.Unlock()
}
func (s *commandMetadataStore) invalidateLiveLocked() {
s.serverFp = ""
s.serverEpoch++
if view := s.current.Load(); view != nil && view.live {
s.current.Store(s.static)
}
}
func (s *commandMetadataStore) startWorker() {
s.mu.Lock()
defer s.mu.Unlock()
if s.started {
return
}
select {
case <-s.stop:
return // already stopped; never start after Close
default:
}
s.started = true
go s.run()
}
// cmdMetaBackoffMin/Max bound the retry backoff after a failed refresh, and
// cmdMetaRetryCap bounds automatic retries (later external triggers —
// conn init, periodic refresh — still attempt once each). Vars so tests can
// shrink them.
var (
cmdMetaBackoffMin = time.Second
cmdMetaBackoffMax = 30 * time.Second
cmdMetaRetryCap = 5
)
const cmdMetaFetchTimeout = 30 * time.Second
var errCommandMetadataNotReady = errors.New("redis: live command metadata verification is pending")
type commandMetadataRefreshMode uint8
const (
commandMetadataInitialRefresh commandMetadataRefreshMode = iota
commandMetadataUpgrade
commandMetadataVerify
)
func (s *commandMetadataStore) run() {
defer close(s.done)
var periodicC <-chan time.Time
var periodic *time.Timer
if s.refreshInterval > 0 {
periodic = time.NewTimer(cmdMetaJitter(s.refreshInterval))
defer periodic.Stop()
periodicC = periodic.C
}
consecFail := 0
attempt := func(verifyLive bool) {
for {
mode := commandMetadataUpgrade
if verifyLive {
mode = commandMetadataVerify
}
err := s.refreshMetadata(s.fetchCtx, mode)
if err == nil {
consecFail = 0
return
}
consecFail++
// Damp the log for persistent failures (e.g. COMMAND denied by ACL).
if consecFail <= cmdMetaRetryCap || consecFail%10 == 0 {
internal.Logger.Printf(context.Background(),
"redis: command metadata refresh failed (attempt %d): %v", consecFail, err)
}
if consecFail >= cmdMetaRetryCap {
// Stop self-retrying; the next external trigger tries again.
return
}
}
}
for {
select {
case <-s.stop:
return
case <-periodicC:
periodic.Reset(cmdMetaJitter(s.refreshInterval))
attempt(true)
case <-s.refresh:
// Stop wins over a pending token, so Close never runs one more fetch.
select {
You can’t perform that action at this time.
