-
Notifications
You must be signed in to change notification settings - Fork 10
/
cluster.go
1356 lines (1236 loc) · 32.4 KB
/
cluster.go
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 valkey
import (
"context"
"errors"
"io"
"net"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/valkey-io/valkey-go/internal/cmds"
"github.com/valkey-io/valkey-go/internal/util"
)
// ErrNoSlot indicates that there is no valkey node owns the key slot.
var ErrNoSlot = errors.New("the slot has no valkey node")
var ErrReplicaOnlyConflict = errors.New("ReplicaOnly conflicts with SendToReplicas option")
var ErrInvalidShardsRefreshInterval = errors.New("ShardsRefreshInterval must be greater than or equal to 0")
type clusterClient struct {
pslots [16384]conn
rslots []conn
sc call
rOpt *ClientOption
conns map[string]connrole
connFn connFn
opt *ClientOption
retryHandler retryHandler
stopCh chan struct{}
cmd Builder
mu sync.RWMutex
stop uint32
retry bool
}
// NOTE: connrole and conn must be initialized at the same time
type connrole struct {
conn conn
replica bool
}
func newClusterClient(opt *ClientOption, connFn connFn, retryer retryHandler) (*clusterClient, error) {
client := &clusterClient{
cmd: cmds.NewBuilder(cmds.InitSlot),
connFn: connFn,
opt: opt,
conns: make(map[string]connrole),
retry: !opt.DisableRetry,
retryHandler: retryer,
stopCh: make(chan struct{}),
}
if opt.ReplicaOnly && opt.SendToReplicas != nil {
return nil, ErrReplicaOnlyConflict
}
if opt.SendToReplicas != nil {
rOpt := *opt
rOpt.ReplicaOnly = true
client.rOpt = &rOpt
}
client.connFn = func(dst string, opt *ClientOption) conn {
cc := connFn(dst, opt)
cc.SetOnCloseHook(func(err error) {
client.lazyRefresh()
})
return cc
}
if err := client.init(); err != nil {
return nil, err
}
if err := client.refresh(context.Background()); err != nil {
return client, err
}
if opt.ClusterOption.ShardsRefreshInterval > 0 {
go client.runClusterTopologyRefreshment()
} else if opt.ClusterOption.ShardsRefreshInterval < 0 {
return nil, ErrInvalidShardsRefreshInterval
}
return client, nil
}
func (c *clusterClient) init() error {
if len(c.opt.InitAddress) == 0 {
return ErrNoAddr
}
results := make(chan error, len(c.opt.InitAddress))
for _, addr := range c.opt.InitAddress {
cc := c.connFn(addr, c.opt)
go func(addr string, cc conn) {
if err := cc.Dial(); err == nil {
c.mu.Lock()
if _, ok := c.conns[addr]; ok {
go cc.Close() // abort the new connection instead of closing the old one which may already been used
} else {
c.conns[addr] = connrole{
conn: cc,
}
}
c.mu.Unlock()
results <- nil
} else {
results <- err
}
}(addr, cc)
}
es := make([]error, cap(results))
for i := 0; i < cap(results); i++ {
if err := <-results; err == nil {
return nil
} else {
es[i] = err
}
}
return es[0]
}
func (c *clusterClient) refresh(ctx context.Context) (err error) {
return c.sc.Do(ctx, c._refresh)
}
func (c *clusterClient) lazyRefresh() {
c.sc.LazyDo(time.Second, c._refresh)
}
type clusterslots struct {
addr string
reply ValkeyResult
ver int
}
func (s clusterslots) parse(tls bool) map[string]group {
if s.ver < 8 {
return parseSlots(s.reply.val, s.addr)
}
return parseShards(s.reply.val, s.addr, tls)
}
func getClusterSlots(c conn, timeout time.Duration) clusterslots {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
v := c.Version()
if v < 8 {
return clusterslots{reply: c.Do(ctx, cmds.SlotCmd), addr: c.Addr(), ver: v}
}
return clusterslots{reply: c.Do(ctx, cmds.ShardsCmd), addr: c.Addr(), ver: v}
}
func (c *clusterClient) _refresh() (err error) {
c.mu.RLock()
results := make(chan clusterslots, len(c.conns))
pending := make([]conn, 0, len(c.conns))
for _, cc := range c.conns {
pending = append(pending, cc.conn)
}
c.mu.RUnlock()
var result clusterslots
for i := 0; i < cap(results); i++ {
if i&3 == 0 { // batch CLUSTER SLOTS/CLUSTER SHARDS for every 4 connections
for j := i; j < i+4 && j < len(pending); j++ {
go func(c conn, timeout time.Duration) {
results <- getClusterSlots(c, timeout)
}(pending[j], c.opt.ConnWriteTimeout)
}
}
result = <-results
err = result.reply.Error()
if len(result.reply.val.values) != 0 {
break
}
}
if err != nil {
return err
}
pending = nil
groups := result.parse(c.opt.TLSConfig != nil)
conns := make(map[string]connrole, len(groups))
for master, g := range groups {
conns[master] = connrole{conn: c.connFn(master, c.opt), replica: false}
for _, addr := range g.nodes[1:] {
if c.rOpt != nil {
conns[addr] = connrole{conn: c.connFn(addr, c.rOpt), replica: true}
} else {
conns[addr] = connrole{conn: c.connFn(addr, c.opt), replica: true}
}
}
}
// make sure InitAddress always be present
for _, addr := range c.opt.InitAddress {
if _, ok := conns[addr]; !ok {
conns[addr] = connrole{
conn: c.connFn(addr, c.opt),
}
}
}
var removes []conn
c.mu.RLock()
for addr, cc := range c.conns {
fresh, ok := conns[addr]
if ok && (cc.replica == fresh.replica || c.rOpt == nil) {
conns[addr] = connrole{
conn: cc.conn,
replica: fresh.replica,
}
} else {
removes = append(removes, cc.conn)
}
}
c.mu.RUnlock()
pslots := [16384]conn{}
var rslots []conn
for master, g := range groups {
switch {
case c.opt.ReplicaOnly && len(g.nodes) > 1:
nodesCount := len(g.nodes)
for _, slot := range g.slots {
for i := slot[0]; i <= slot[1]; i++ {
pslots[i] = conns[g.nodes[1+util.FastRand(nodesCount-1)]].conn
}
}
case c.rOpt != nil: // implies c.opt.SendToReplicas != nil
if len(rslots) == 0 { // lazy init
rslots = make([]conn, 16384)
}
if len(g.nodes) > 1 {
for _, slot := range g.slots {
for i := slot[0]; i <= slot[1]; i++ {
pslots[i] = conns[master].conn
rslots[i] = conns[g.nodes[1+util.FastRand(len(g.nodes)-1)]].conn
}
}
} else {
for _, slot := range g.slots {
for i := slot[0]; i <= slot[1]; i++ {
pslots[i] = conns[master].conn
rslots[i] = conns[master].conn
}
}
}
default:
for _, slot := range g.slots {
for i := slot[0]; i <= slot[1]; i++ {
pslots[i] = conns[master].conn
}
}
}
}
c.mu.Lock()
c.pslots = pslots
c.rslots = rslots
c.conns = conns
c.mu.Unlock()
if len(removes) > 0 {
go func(removes []conn) {
time.Sleep(time.Second * 5)
for _, cc := range removes {
cc.Close()
}
}(removes)
}
return nil
}
func (c *clusterClient) single() (conn conn) {
return c._pick(cmds.InitSlot, false)
}
func (c *clusterClient) nodes() []string {
c.mu.RLock()
nodes := make([]string, 0, len(c.conns))
for addr := range c.conns {
nodes = append(nodes, addr)
}
c.mu.RUnlock()
return nodes
}
type group struct {
nodes []string
slots [][2]int64
}
func parseEndpoint(fallback, endpoint string, port int64) string {
switch endpoint {
case "":
endpoint, _, _ = net.SplitHostPort(fallback)
case "?":
return ""
}
return net.JoinHostPort(endpoint, strconv.FormatInt(port, 10))
}
// parseSlots - map valkey slots for each valkey nodes/addresses
// defaultAddr is needed in case the node does not know its own IP
func parseSlots(slots ValkeyMessage, defaultAddr string) map[string]group {
groups := make(map[string]group, len(slots.values))
for _, v := range slots.values {
master := parseEndpoint(defaultAddr, v.values[2].values[0].string, v.values[2].values[1].integer)
if master == "" {
continue
}
g, ok := groups[master]
if !ok {
g.slots = make([][2]int64, 0)
g.nodes = make([]string, 0, len(v.values)-2)
for i := 2; i < len(v.values); i++ {
if dst := parseEndpoint(defaultAddr, v.values[i].values[0].string, v.values[i].values[1].integer); dst != "" {
g.nodes = append(g.nodes, dst)
}
}
}
g.slots = append(g.slots, [2]int64{v.values[0].integer, v.values[1].integer})
groups[master] = g
}
return groups
}
// parseShards - map valkey shards for each valkey nodes/addresses
// defaultAddr is needed in case the node does not know its own IP
func parseShards(shards ValkeyMessage, defaultAddr string, tls bool) map[string]group {
groups := make(map[string]group, len(shards.values))
for _, v := range shards.values {
m := -1
shard, _ := v.AsMap()
slots := shard["slots"].values
nodes := shard["nodes"].values
g := group{
nodes: make([]string, 0, len(nodes)),
slots: make([][2]int64, len(slots)/2),
}
for i := range g.slots {
g.slots[i][0], _ = slots[i*2].AsInt64()
g.slots[i][1], _ = slots[i*2+1].AsInt64()
}
for _, n := range nodes {
dict, _ := n.AsMap()
if dict["health"].string == "fail" {
continue
}
port := dict["port"].integer
if tls && dict["tls-port"].integer > 0 {
port = dict["tls-port"].integer
}
if dst := parseEndpoint(defaultAddr, dict["endpoint"].string, port); dst != "" {
if dict["role"].string == "master" && dict["health"].string == "online" {
m = len(g.nodes)
}
g.nodes = append(g.nodes, dst)
}
}
if m >= 0 {
g.nodes[0], g.nodes[m] = g.nodes[m], g.nodes[0]
groups[g.nodes[0]] = g
}
}
return groups
}
func (c *clusterClient) runClusterTopologyRefreshment() {
ticker := time.NewTicker(c.opt.ClusterOption.ShardsRefreshInterval)
defer ticker.Stop()
for {
select {
case <-c.stopCh:
return
case <-ticker.C:
c.lazyRefresh()
}
}
}
func (c *clusterClient) _pick(slot uint16, toReplica bool) (p conn) {
c.mu.RLock()
if slot == cmds.InitSlot {
for _, cc := range c.conns {
if cc.replica {
continue
}
p = cc.conn
break
}
} else if toReplica && c.rslots != nil {
p = c.rslots[slot]
} else {
p = c.pslots[slot]
}
c.mu.RUnlock()
return p
}
func (c *clusterClient) pick(ctx context.Context, slot uint16, toReplica bool) (p conn, err error) {
if p = c._pick(slot, toReplica); p == nil {
if err := c.refresh(ctx); err != nil {
return nil, err
}
if p = c._pick(slot, toReplica); p == nil {
return nil, ErrNoSlot
}
}
return p, nil
}
func (c *clusterClient) redirectOrNew(addr string, prev conn, slot uint16, mode RedirectMode) conn {
c.mu.RLock()
cc := c.conns[addr]
c.mu.RUnlock()
if cc.conn != nil && prev != cc.conn {
return cc.conn
}
c.mu.Lock()
if cc = c.conns[addr]; cc.conn == nil {
p := c.connFn(addr, c.opt)
cc = connrole{conn: p, replica: false}
c.conns[addr] = cc
if mode == RedirectMove {
c.pslots[slot] = p
}
} else if prev == cc.conn {
// try reconnection if the MOVED redirects to the same host,
// because the same hostname may actually be resolved into another destination
// depending on the fail-over implementation. ex: AWS MemoryDB's resize process.
go func(prev conn) {
time.Sleep(time.Second * 5)
prev.Close()
}(prev)
p := c.connFn(addr, c.opt)
cc = connrole{conn: p, replica: cc.replica}
c.conns[addr] = cc
if mode == RedirectMove {
if cc.replica {
c.rslots[slot] = p
} else {
c.pslots[slot] = p
}
}
}
c.mu.Unlock()
return cc.conn
}
func (c *clusterClient) B() Builder {
return c.cmd
}
func (c *clusterClient) Do(ctx context.Context, cmd Completed) (resp ValkeyResult) {
if resp = c.do(ctx, cmd); resp.NonValkeyError() == nil { // not recycle cmds if error, since cmds may be used later in pipe. consider recycle them by pipe
cmds.PutCompleted(cmd)
}
return resp
}
func (c *clusterClient) do(ctx context.Context, cmd Completed) (resp ValkeyResult) {
attempts := 1
retry:
cc, err := c.pick(ctx, cmd.Slot(), c.toReplica(cmd))
if err != nil {
return newErrResult(err)
}
resp = cc.Do(ctx, cmd)
process:
switch addr, mode := c.shouldRefreshRetry(resp.Error(), ctx); mode {
case RedirectMove:
resp = c.redirectOrNew(addr, cc, cmd.Slot(), mode).Do(ctx, cmd)
goto process
case RedirectAsk:
results := c.redirectOrNew(addr, cc, cmd.Slot(), mode).DoMulti(ctx, cmds.AskingCmd, cmd)
resp = results.s[1]
resultsp.Put(results)
goto process
case RedirectRetry:
if c.retry && cmd.IsReadOnly() {
shouldRetry := c.retryHandler.WaitOrSkipRetry(ctx, attempts, cmd, resp.Error())
if shouldRetry {
attempts++
goto retry
}
}
}
return resp
}
func (c *clusterClient) toReplica(cmd Completed) bool {
if c.opt.SendToReplicas != nil {
return c.opt.SendToReplicas(cmd)
}
return false
}
func (c *clusterClient) _pickMulti(multi []Completed) (retries *connretry, last uint16, toReplica bool) {
last = cmds.InitSlot
init := false
for _, cmd := range multi {
if cmd.Slot() == cmds.InitSlot {
init = true
break
}
}
c.mu.RLock()
defer c.mu.RUnlock()
count := conncountp.Get(len(c.conns), len(c.conns))
if !init && c.rslots != nil && c.opt.SendToReplicas != nil {
for _, cmd := range multi {
var p conn
if c.opt.SendToReplicas(cmd) {
p = c.rslots[cmd.Slot()]
} else {
p = c.pslots[cmd.Slot()]
}
if p == nil {
return nil, 0, false
}
count.m[p]++
}
retries = connretryp.Get(len(count.m), len(count.m))
for cc, n := range count.m {
retries.m[cc] = retryp.Get(0, n)
}
conncountp.Put(count)
for i, cmd := range multi {
last = cmd.Slot()
var cc conn
if c.opt.SendToReplicas(cmd) {
toReplica = true
cc = c.rslots[cmd.Slot()]
} else {
cc = c.pslots[cmd.Slot()]
}
re := retries.m[cc]
re.commands = append(re.commands, cmd)
re.cIndexes = append(re.cIndexes, i)
}
return retries, last, toReplica
}
for _, cmd := range multi {
if cmd.Slot() == cmds.InitSlot {
continue
}
p := c.pslots[cmd.Slot()]
if p == nil {
return nil, 0, false
}
count.m[p]++
}
retries = connretryp.Get(len(count.m), len(count.m))
for cc, n := range count.m {
retries.m[cc] = retryp.Get(0, n)
}
conncountp.Put(count)
for i, cmd := range multi {
if cmd.Slot() != cmds.InitSlot {
if last == cmds.InitSlot {
last = cmd.Slot()
} else if init && last != cmd.Slot() {
panic(panicMixCxSlot)
}
cc := c.pslots[cmd.Slot()]
re := retries.m[cc]
re.commands = append(re.commands, cmd)
re.cIndexes = append(re.cIndexes, i)
}
}
return retries, last, false
}
func (c *clusterClient) pickMulti(ctx context.Context, multi []Completed) (*connretry, uint16, bool, error) {
conns, slot, toReplica := c._pickMulti(multi)
if conns == nil {
if err := c.refresh(ctx); err != nil {
return nil, 0, false, err
}
if conns, slot, toReplica = c._pickMulti(multi); conns == nil {
return nil, 0, false, ErrNoSlot
}
}
return conns, slot, toReplica, nil
}
func (c *clusterClient) doresultfn(
ctx context.Context, results *valkeyresults, retries *connretry, mu *sync.Mutex, cc conn, cIndexes []int, commands []Completed, resps []ValkeyResult, attempts int,
) {
for i, resp := range resps {
ii := cIndexes[i]
cm := commands[i]
results.s[ii] = resp
addr, mode := c.shouldRefreshRetry(resp.Error(), ctx)
if mode != RedirectNone {
nc := cc
retryDelay := time.Duration(-1)
if mode == RedirectRetry {
if !c.retry || !cm.IsReadOnly() {
continue
}
retryDelay = c.retryHandler.RetryDelay(attempts, cm, resp.Error())
} else {
nc = c.redirectOrNew(addr, cc, cm.Slot(), mode)
}
mu.Lock()
if mode != RedirectRetry {
retries.Redirects++
}
if mode == RedirectRetry && retryDelay >= 0 {
retries.RetryDelay = max(retries.RetryDelay, retryDelay)
}
nr := retries.m[nc]
if nr == nil {
nr = retryp.Get(0, len(commands))
retries.m[nc] = nr
}
if mode == RedirectAsk {
nr.aIndexes = append(nr.aIndexes, ii)
nr.cAskings = append(nr.cAskings, cm)
} else {
nr.cIndexes = append(nr.cIndexes, ii)
nr.commands = append(nr.commands, cm)
}
mu.Unlock()
}
}
}
func (c *clusterClient) doretry(
ctx context.Context, cc conn, results *valkeyresults, retries *connretry, re *retry, mu *sync.Mutex, wg *sync.WaitGroup, attempts int,
) {
if len(re.commands) != 0 {
resps := cc.DoMulti(ctx, re.commands...)
c.doresultfn(ctx, results, retries, mu, cc, re.cIndexes, re.commands, resps.s, attempts)
resultsp.Put(resps)
}
if len(re.cAskings) != 0 {
resps := askingMulti(cc, ctx, re.cAskings)
c.doresultfn(ctx, results, retries, mu, cc, re.aIndexes, re.cAskings, resps.s, attempts)
resultsp.Put(resps)
}
if ctx.Err() == nil {
retryp.Put(re)
}
wg.Done()
}
func (c *clusterClient) DoMulti(ctx context.Context, multi ...Completed) []ValkeyResult {
if len(multi) == 0 {
return nil
}
retries, slot, toReplica, err := c.pickMulti(ctx, multi)
if err != nil {
return fillErrs(len(multi), err)
}
defer connretryp.Put(retries)
if len(retries.m) <= 1 {
for _, re := range retries.m {
retryp.Put(re)
}
return c.doMulti(ctx, slot, multi, toReplica)
}
var wg sync.WaitGroup
var mu sync.Mutex
results := resultsp.Get(len(multi), len(multi))
attempts := 1
retry:
retries.RetryDelay = -1 // Assume no retry. Because client retry flag can be set to false.
wg.Add(len(retries.m))
mu.Lock()
for cc, re := range retries.m {
delete(retries.m, cc)
go c.doretry(ctx, cc, results, retries, re, &mu, &wg, attempts)
}
mu.Unlock()
wg.Wait()
if len(retries.m) != 0 {
if retries.Redirects > 0 {
retries.Redirects = 0
goto retry
}
if retries.RetryDelay >= 0 {
c.retryHandler.WaitForRetry(ctx, retries.RetryDelay)
attempts++
goto retry
}
}
for i, cmd := range multi {
if results.s[i].NonValkeyError() == nil {
cmds.PutCompleted(cmd)
}
}
return results.s
}
func fillErrs(n int, err error) (results []ValkeyResult) {
results = resultsp.Get(n, n).s
for i := range results {
results[i] = newErrResult(err)
}
return results
}
func (c *clusterClient) doMulti(ctx context.Context, slot uint16, multi []Completed, toReplica bool) []ValkeyResult {
attempts := 1
retry:
cc, err := c.pick(ctx, slot, toReplica)
if err != nil {
return fillErrs(len(multi), err)
}
resps := cc.DoMulti(ctx, multi...)
process:
for i, resp := range resps.s {
switch addr, mode := c.shouldRefreshRetry(resp.Error(), ctx); mode {
case RedirectMove:
if c.retry && allReadOnly(multi) {
resultsp.Put(resps)
resps = c.redirectOrNew(addr, cc, multi[i].Slot(), mode).DoMulti(ctx, multi...)
goto process
}
case RedirectAsk:
if c.retry && allReadOnly(multi) {
resultsp.Put(resps)
resps = askingMulti(c.redirectOrNew(addr, cc, multi[i].Slot(), mode), ctx, multi)
goto process
}
case RedirectRetry:
if c.retry && allReadOnly(multi) {
shouldRetry := c.retryHandler.WaitOrSkipRetry(ctx, attempts, multi[i], resp.Error())
if shouldRetry {
resultsp.Put(resps)
attempts++
goto retry
}
}
}
}
return resps.s
}
func (c *clusterClient) doCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp ValkeyResult) {
attempts := 1
retry:
cc, err := c.pick(ctx, cmd.Slot(), c.toReplica(Completed(cmd)))
if err != nil {
return newErrResult(err)
}
resp = cc.DoCache(ctx, cmd, ttl)
process:
switch addr, mode := c.shouldRefreshRetry(resp.Error(), ctx); mode {
case RedirectMove:
resp = c.redirectOrNew(addr, cc, cmd.Slot(), mode).DoCache(ctx, cmd, ttl)
goto process
case RedirectAsk:
results := askingMultiCache(c.redirectOrNew(addr, cc, cmd.Slot(), mode), ctx, []CacheableTTL{CT(cmd, ttl)})
resp = results.s[0]
resultsp.Put(results)
goto process
case RedirectRetry:
if c.retry {
shouldRetry := c.retryHandler.WaitOrSkipRetry(ctx, attempts, Completed(cmd), resp.Error())
if shouldRetry {
attempts++
goto retry
}
}
}
return resp
}
func (c *clusterClient) DoCache(ctx context.Context, cmd Cacheable, ttl time.Duration) (resp ValkeyResult) {
resp = c.doCache(ctx, cmd, ttl)
if err := resp.NonValkeyError(); err == nil || err == ErrDoCacheAborted {
cmds.PutCacheable(cmd)
}
return resp
}
func askingMulti(cc conn, ctx context.Context, multi []Completed) *valkeyresults {
commands := make([]Completed, 0, len(multi)*2)
for _, cmd := range multi {
commands = append(commands, cmds.AskingCmd, cmd)
}
results := resultsp.Get(0, len(multi))
resps := cc.DoMulti(ctx, commands...)
for i := 1; i < len(resps.s); i += 2 {
results.s = append(results.s, resps.s[i])
}
resultsp.Put(resps)
return results
}
func askingMultiCache(cc conn, ctx context.Context, multi []CacheableTTL) *valkeyresults {
commands := make([]Completed, 0, len(multi)*6)
for _, cmd := range multi {
ck, _ := cmds.CacheKey(cmd.Cmd)
commands = append(commands, cmds.OptInCmd, cmds.MultiCmd, cmds.AskingCmd, cmds.NewCompleted([]string{"PTTL", ck}), Completed(cmd.Cmd), cmds.ExecCmd)
}
results := resultsp.Get(0, len(multi))
resps := cc.DoMulti(ctx, commands...)
for i := 5; i < len(resps.s); i += 6 {
if arr, err := resps.s[i].ToArray(); err != nil {
results.s = append(results.s, newErrResult(err))
} else {
results.s = append(results.s, newResult(arr[len(arr)-1], nil))
}
}
resultsp.Put(resps)
return results
}
func (c *clusterClient) _pickMultiCache(multi []CacheableTTL) *connretrycache {
c.mu.RLock()
defer c.mu.RUnlock()
count := conncountp.Get(len(c.conns), len(c.conns))
if c.opt.SendToReplicas == nil || c.rslots == nil {
for _, cmd := range multi {
p := c.pslots[cmd.Cmd.Slot()]
if p == nil {
return nil
}
count.m[p]++
}
retries := connretrycachep.Get(len(count.m), len(count.m))
for cc, n := range count.m {
retries.m[cc] = retrycachep.Get(0, n)
}
conncountp.Put(count)
for i, cmd := range multi {
cc := c.pslots[cmd.Cmd.Slot()]
re := retries.m[cc]
re.commands = append(re.commands, cmd)
re.cIndexes = append(re.cIndexes, i)
}
return retries
} else {
for _, cmd := range multi {
var p conn
if c.opt.SendToReplicas(Completed(cmd.Cmd)) {
p = c.rslots[cmd.Cmd.Slot()]
} else {
p = c.pslots[cmd.Cmd.Slot()]
}
if p == nil {
return nil
}
count.m[p]++
}
retries := connretrycachep.Get(len(count.m), len(count.m))
for cc, n := range count.m {
retries.m[cc] = retrycachep.Get(0, n)
}
conncountp.Put(count)
for i, cmd := range multi {
var cc conn
if c.opt.SendToReplicas(Completed(cmd.Cmd)) {
cc = c.rslots[cmd.Cmd.Slot()]
} else {
cc = c.pslots[cmd.Cmd.Slot()]
}
re := retries.m[cc]
re.commands = append(re.commands, cmd)
re.cIndexes = append(re.cIndexes, i)
}
return retries
}
}
func (c *clusterClient) pickMultiCache(ctx context.Context, multi []CacheableTTL) (*connretrycache, error) {
conns := c._pickMultiCache(multi)
if conns == nil {
if err := c.refresh(ctx); err != nil {
return nil, err
}
if conns = c._pickMultiCache(multi); conns == nil {
return nil, ErrNoSlot
}
}
return conns, nil
}
func (c *clusterClient) resultcachefn(
ctx context.Context, results *valkeyresults, retries *connretrycache, mu *sync.Mutex, cc conn, cIndexes []int, commands []CacheableTTL, resps []ValkeyResult, attempts int,
) {
for i, resp := range resps {
ii := cIndexes[i]
cm := commands[i]
results.s[ii] = resp
addr, mode := c.shouldRefreshRetry(resp.Error(), ctx)
if mode != RedirectNone {
nc := cc
retryDelay := time.Duration(-1)
if mode == RedirectRetry {
if !c.retry {
continue
}
retryDelay = c.retryHandler.RetryDelay(attempts, Completed(cm.Cmd), resp.Error())
} else {
nc = c.redirectOrNew(addr, cc, cm.Cmd.Slot(), mode)
}
mu.Lock()
if mode != RedirectRetry {
retries.Redirects++
}
if mode == RedirectRetry && retryDelay >= 0 {
retries.RetryDelay = max(retries.RetryDelay, retryDelay)
}
nr := retries.m[nc]
if nr == nil {
nr = retrycachep.Get(0, len(commands))
retries.m[nc] = nr
}
if mode == RedirectAsk {
nr.aIndexes = append(nr.aIndexes, ii)
nr.cAskings = append(nr.cAskings, cm)
} else {
nr.cIndexes = append(nr.cIndexes, ii)
nr.commands = append(nr.commands, cm)
}
mu.Unlock()
}
}
}
func (c *clusterClient) doretrycache(
ctx context.Context, cc conn, results *valkeyresults, retries *connretrycache, re *retrycache, mu *sync.Mutex, wg *sync.WaitGroup, attempts int,
) {
if len(re.commands) != 0 {
resps := cc.DoMultiCache(ctx, re.commands...)
c.resultcachefn(ctx, results, retries, mu, cc, re.cIndexes, re.commands, resps.s, attempts)
resultsp.Put(resps)
}
if len(re.cAskings) != 0 {
resps := askingMultiCache(cc, ctx, re.cAskings)
c.resultcachefn(ctx, results, retries, mu, cc, re.aIndexes, re.cAskings, resps.s, attempts)
resultsp.Put(resps)
}
if ctx.Err() == nil {
retrycachep.Put(re)
}
wg.Done()
}
func (c *clusterClient) DoMultiCache(ctx context.Context, multi ...CacheableTTL) []ValkeyResult {
if len(multi) == 0 {
return nil
}
retries, err := c.pickMultiCache(ctx, multi)
if err != nil {
return fillErrs(len(multi), err)
}
defer connretrycachep.Put(retries)
var wg sync.WaitGroup
var mu sync.Mutex
results := resultsp.Get(len(multi), len(multi))
attempts := 1