forked from vdaas/vald
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
1125 lines (1082 loc) · 31.7 KB
/
client.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
//
// Copyright (C) 2019-2024 vdaas.org vald team <vald@vdaas.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Package grpc provides generic functionality for grpc
package grpc
import (
"context"
"math"
"sync/atomic"
"time"
"github.com/vdaas/vald/internal/backoff"
"github.com/vdaas/vald/internal/circuitbreaker"
"github.com/vdaas/vald/internal/errors"
"github.com/vdaas/vald/internal/log"
"github.com/vdaas/vald/internal/net"
"github.com/vdaas/vald/internal/net/grpc/codes"
"github.com/vdaas/vald/internal/net/grpc/logger"
"github.com/vdaas/vald/internal/net/grpc/pool"
"github.com/vdaas/vald/internal/net/grpc/status"
"github.com/vdaas/vald/internal/observability/trace"
"github.com/vdaas/vald/internal/safety"
"github.com/vdaas/vald/internal/strings"
"github.com/vdaas/vald/internal/sync"
"github.com/vdaas/vald/internal/sync/errgroup"
"github.com/vdaas/vald/internal/sync/singleflight"
"google.golang.org/grpc"
gbackoff "google.golang.org/grpc/backoff"
)
type (
CallOption = grpc.CallOption
DialOption = pool.DialOption
ClientConn = pool.ClientConn
)
type Client interface {
StartConnectionMonitor(ctx context.Context) (<-chan error, error)
Connect(ctx context.Context, addr string, dopts ...DialOption) (pool.Conn, error)
IsConnected(ctx context.Context, addr string) bool
Disconnect(ctx context.Context, addr string) error
Range(ctx context.Context,
f func(ctx context.Context,
addr string,
conn *ClientConn,
copts ...CallOption) error) error
RangeConcurrent(ctx context.Context,
concurrency int,
f func(ctx context.Context,
addr string,
conn *ClientConn,
copts ...CallOption) error) error
OrderedRange(ctx context.Context,
order []string,
f func(ctx context.Context,
addr string,
conn *ClientConn,
copts ...CallOption) error) error
OrderedRangeConcurrent(ctx context.Context,
order []string,
concurrency int,
f func(ctx context.Context,
addr string,
conn *ClientConn,
copts ...CallOption) error) error
Do(ctx context.Context, addr string,
f func(ctx context.Context,
conn *ClientConn,
copts ...CallOption) (any, error)) (any, error)
RoundRobin(ctx context.Context, f func(ctx context.Context,
conn *ClientConn,
copts ...CallOption) (any, error)) (any, error)
GetDialOption() []DialOption
GetCallOption() []CallOption
GetBackoff() backoff.Backoff
SetDisableResolveDNSAddr(addr string, disabled bool)
ConnectedAddrs() []string
Close(ctx context.Context) error
}
type gRPCClient struct {
addrs map[string]struct{}
poolSize uint64
clientCount uint64
conns sync.Map[string, pool.Conn]
hcDur time.Duration
prDur time.Duration
dialer net.Dialer
enablePoolRebalance bool
disableResolveDNSAddrs sync.Map[string, bool]
resolveDNS bool
dopts []DialOption
copts []CallOption
roccd string // reconnection old connection closing duration
eg errgroup.Group
bo backoff.Backoff
cb circuitbreaker.CircuitBreaker
gbo gbackoff.Config // grpc's original backoff configuration
mcd time.Duration // minimum connection timeout duration
group singleflight.Group[pool.Conn]
crl sync.Map[string, bool] // connection request list
ech <-chan error
monitorRunning atomic.Bool
stopMonitor context.CancelFunc
}
const (
apiName = "vald/internal/net/grpc"
defaultHealthCheckDuration = 10 * time.Second
)
func New(opts ...Option) (c Client) {
g := &gRPCClient{
group: singleflight.New[pool.Conn](),
addrs: make(map[string]struct{}),
}
for _, opt := range append(defaultOptions, opts...) {
opt(g)
}
g.dopts = append(g.dopts, grpc.WithConnectParams(
grpc.ConnectParams{
Backoff: gbackoff.Config{
MaxDelay: g.gbo.MaxDelay,
BaseDelay: g.gbo.BaseDelay,
Multiplier: g.gbo.Multiplier,
Jitter: g.gbo.Jitter,
},
MinConnectTimeout: g.mcd,
},
))
g.monitorRunning.Store(false)
return g
}
func (g *gRPCClient) StartConnectionMonitor(ctx context.Context) (<-chan error, error) {
logger.Init()
if g.monitorRunning.Load() {
return g.ech, nil
}
g.monitorRunning.Store(true)
addrs := make([]string, 0, len(g.addrs))
for addr := range g.addrs {
addrs = append(addrs, addr)
}
if g.dialer != nil {
g.dialer.StartDialerCache(ctx)
}
ech := make(chan error, len(addrs))
for _, addr := range addrs {
if addr != "" {
_, err := g.Connect(ctx, addr)
if err != nil {
if !errors.Is(err, context.Canceled) &&
!errors.Is(err, context.DeadlineExceeded) &&
!errors.Is(err, errors.ErrCircuitBreakerOpenState) &&
!errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) &&
!errors.Is(err, errors.ErrGRPCClientConnNotFound(addr)) &&
!errors.Is(err, errors.ErrGRPCClientNotFound) {
log.Errorf("failed to initial connection to %s,\terror: %v", addr, err)
ech <- err
} else {
log.Warn(err)
}
}
}
}
if len(addrs) != 0 && atomic.LoadUint64(&g.clientCount) == 0 {
err := errors.ErrGRPCClientConnNotFound(strings.Join(addrs, ",\t"))
log.Error(err)
return nil, err
}
ctx, g.stopMonitor = context.WithCancel(ctx)
g.eg.Go(safety.RecoverFunc(func() (err error) {
defer g.monitorRunning.Store(false)
defer close(ech)
defer func() {
if err := g.Close(context.Background()); err != nil {
log.Error(err)
}
}()
var hcTick, prTick *time.Ticker
// this duration is for timeout to prevent blocking health check loop, which should be minimum duration of hcDur and prDur
reconnLimitDuration := time.Second
if g.hcDur.Nanoseconds() <= 0 {
g.hcDur = defaultHealthCheckDuration
}
err = safety.RecoverFunc(func() error {
hcTick = time.NewTicker(g.hcDur) // health check ticker
return nil
})()
if err != nil || hcTick == nil {
ech <- err
return err
}
defer hcTick.Stop()
if g.enablePoolRebalance && g.prDur.Nanoseconds() > 0 {
err = safety.RecoverFunc(func() error {
prTick = time.NewTicker(g.prDur) // pool rebalance ticker
return nil
})()
reconnLimitDuration = time.Duration(int64(math.Min(float64(g.hcDur.Nanoseconds()), float64(g.prDur.Nanoseconds()))))
} else {
err = safety.RecoverFunc(func() error {
prTick = time.NewTicker(g.hcDur) // pool rebalance ticker
return nil
})()
reconnLimitDuration = g.hcDur
}
if err != nil || prTick == nil {
ech <- err
return err
}
defer prTick.Stop()
disconnectTargets := make([]string, 0, len(addrs))
for {
select {
case <-ctx.Done():
if err != nil {
return errors.Join(ctx.Err(), err)
}
return ctx.Err()
case <-prTick.C:
if g.enablePoolRebalance {
err = g.rangeConns(func(addr string, p pool.Conn) bool {
// if addr or pool is nil or empty the registration of conns is invalid let's disconnect them
if addr == "" || p == nil {
disconnectTargets = append(disconnectTargets, addr)
return true
}
var err error
// for rebalancing connection we don't need to check connection health
p, err = p.Connect(ctx)
if err != nil {
if !errors.Is(err, context.Canceled) &&
!errors.Is(err, context.DeadlineExceeded) &&
!errors.Is(err, errors.ErrCircuitBreakerOpenState) &&
!errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) &&
!errors.Is(err, errors.ErrGRPCClientConnNotFound(addr)) &&
!errors.Is(err, errors.ErrGRPCClientNotFound) {
log.Error(err)
ech <- err
} else {
log.Warn(err)
}
}
// if rebalanced connection pool is nil even error is nil we should disconnect and delete it
if err == nil && p == nil {
disconnectTargets = append(disconnectTargets, addr)
return true
}
// if connection pool could not recover we should try next connection loop
if err != nil || !p.IsHealthy(ctx) {
g.crl.Store(addr, false)
return true
}
g.conns.Store(addr, p)
return true
})
}
case <-hcTick.C:
err = g.rangeConns(func(addr string, p pool.Conn) bool {
// if addr or pool is nil or empty the registration of conns is invalid let's disconnect them
if addr == "" || p == nil {
disconnectTargets = append(disconnectTargets, addr)
return true
}
// for health check we don't need to reconnect when connection is healthy
if p.IsHealthy(ctx) {
return true
}
// if connection is not ip direct or unhealthy let's re-connect
var err error
// if not healthy we should try reconnect
p, err = p.Reconnect(ctx, false)
if err != nil {
if !errors.Is(err, context.Canceled) &&
!errors.Is(err, context.DeadlineExceeded) &&
!errors.Is(err, errors.ErrCircuitBreakerOpenState) &&
!errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) &&
!errors.Is(err, errors.ErrGRPCClientConnNotFound(addr)) &&
!errors.Is(err, errors.ErrGRPCClientNotFound) {
log.Error(err)
ech <- err
} else {
log.Warn(err)
}
}
// if rebalanced connection pool is nil even error is nil we should disconnect and delete it
if err == nil && p == nil {
disconnectTargets = append(disconnectTargets, addr)
return true
}
// if connection pool could not recover we should try next connection loop
if err != nil || !p.IsHealthy(ctx) {
g.crl.Store(addr, false)
return true
}
g.conns.Store(addr, p)
return true
})
}
if err != nil && errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) && len(addrs) != 0 {
for _, addr := range addrs {
if addr != "" {
log.Debugf("connection for %s not found in connection map will re-connect soon", addr)
g.crl.Store(addr, false)
}
}
}
clctx, cancel := context.WithTimeout(ctx, reconnLimitDuration)
g.crl.Range(func(addr string, enabled bool) bool {
select {
case <-clctx.Done():
return false
default:
defer g.crl.Delete(addr)
var p pool.Conn
if enabled && g.bo != nil {
_, err = g.bo.Do(clctx, func(ictx context.Context) (r any, ret bool, err error) {
p, err = g.Connect(ictx, addr)
return nil, err != nil, err
})
} else {
p, err = g.Connect(clctx, addr)
}
if err != nil || p == nil || !p.IsHealthy(ctx) {
log.Debugf("connection for %s is not healthy will delete soon,\terror: %v,\tpool: [%v]", addr, err, p)
disconnectTargets = append(disconnectTargets, addr)
} else {
g.conns.Store(addr, p)
}
return true
}
})
cancel()
var (
disconnectFlag bool
isIPv4, isIPv6 bool
host string
port uint16
disconnected = make(map[string]bool, len(disconnectTargets))
)
for _, addr := range disconnectTargets {
host, port, _, isIPv4, isIPv6, err = net.Parse(addr)
disconnectFlag = isIPv4 || isIPv6 // Disconnect only if the connection is a direct IP connection; do not delete connections via DNS due to retry.
if err != nil {
log.Warnf("failed to parse addr %s for disconnection checking, will disconnect soon: host: %s, port %d, err: %v", addr, host, port, err)
disconnectFlag = true // Disconnect if the address connected to is not parseable.
}
if disconnectFlag &&
!disconnected[addr] {
err = g.Disconnect(ctx, addr)
if err != nil {
if !errors.Is(err, context.Canceled) &&
!errors.Is(err, context.DeadlineExceeded) &&
!errors.Is(err, errors.ErrCircuitBreakerOpenState) &&
!errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) &&
!errors.Is(err, errors.ErrGRPCClientConnNotFound(addr)) &&
!errors.Is(err, errors.ErrGRPCClientNotFound) {
log.Error(err)
ech <- err
} else {
log.Warn(err)
}
}
disconnected[addr] = true
}
}
disconnectTargets = disconnectTargets[:0]
}
}))
g.ech = ech
return ech, nil
}
func (g *gRPCClient) Range(
ctx context.Context,
f func(ctx context.Context, addr string, conn *ClientConn, copts ...CallOption) error,
) (err error) {
sctx, span := trace.StartSpan(ctx, apiName+"/Client.Range")
defer func() {
if span != nil {
span.End()
}
}()
if g.conns.Len() == 0 {
return errors.ErrGRPCClientConnNotFound("*")
}
err = g.rangeConns(func(addr string, p pool.Conn) bool {
ssctx, sspan := trace.StartSpan(sctx, apiName+"/Client.Range/"+addr)
defer func() {
if sspan != nil {
sspan.End()
}
}()
select {
case <-ctx.Done():
return false
default:
_, err := g.connectWithBackoff(ssctx, p, addr, true, func(ictx context.Context, conn *ClientConn, copts ...CallOption,
) (any, error) {
return nil, f(ictx, addr, conn, copts...)
})
if err != nil {
if sspan != nil {
sspan.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
sspan.SetStatus(trace.StatusError, err.Error())
}
}
}
return true
})
if err != nil {
if span != nil {
span.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
span.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
span.SetStatus(trace.StatusError, err.Error())
}
if errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) {
return err
}
}
return nil
}
func (g *gRPCClient) RangeConcurrent(
ctx context.Context,
concurrency int,
f func(ctx context.Context, addr string, conn *ClientConn, copts ...CallOption) error,
) (err error) {
sctx, span := trace.StartSpan(ctx, apiName+"/Client.RangeConcurrent")
defer func() {
if span != nil {
span.End()
}
}()
if concurrency == 0 || concurrency == 1 {
return g.Range(ctx, f)
}
eg, egctx := errgroup.New(sctx)
eg.SetLimit(concurrency)
if g.conns.Len() == 0 {
return errors.ErrGRPCClientConnNotFound("*")
}
err = g.rangeConns(func(addr string, p pool.Conn) bool {
eg.Go(safety.RecoverFunc(func() (err error) {
ssctx, sspan := trace.StartSpan(egctx, apiName+"/Client.RangeConcurrent/"+addr)
defer func() {
if sspan != nil {
sspan.End()
}
}()
select {
case <-egctx.Done():
err = egctx.Err()
if err != nil && (errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded)) {
return err
}
return nil
default:
_, err = g.connectWithBackoff(ssctx, p, addr, true, func(ictx context.Context,
conn *ClientConn, copts ...CallOption,
) (any, error) {
err := f(ictx, addr, conn, copts...)
return nil, err
})
if err != nil {
if sspan != nil {
sspan.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
sspan.SetStatus(trace.StatusError, err.Error())
switch st.Code() {
case codes.Canceled, codes.DeadlineExceeded:
return err
}
} else if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) {
return err
}
}
return nil
}
}))
return true
})
err = errors.Join(err, eg.Wait())
if err != nil {
if span != nil {
span.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
span.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
span.SetStatus(trace.StatusError, err.Error())
}
if errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) {
return err
}
}
return nil
}
func (g *gRPCClient) OrderedRange(
ctx context.Context,
orders []string,
f func(ctx context.Context, addr string, conn *ClientConn, copts ...CallOption) error,
) (err error) {
sctx, span := trace.StartSpan(ctx, apiName+"/Client.OrderedRange")
defer func() {
if span != nil {
span.End()
}
}()
if len(orders) == 0 {
log.Warn("no order found for OrderedRange")
return g.Range(sctx, f)
}
if g.conns.Len() == 0 {
return errors.ErrGRPCClientConnNotFound("*")
}
var cnt int
for _, addr := range orders {
select {
case <-sctx.Done():
return nil
default:
p, ok := g.conns.Load(addr)
if !ok || p == nil {
g.crl.Store(addr, true)
log.Warnf("gRPCClient.OrderedRange operation failed, gRPC connection pool for %s is invalid,\terror: %v", addr, errors.ErrGRPCClientConnNotFound(addr))
continue
}
cnt++
ssctx, span := trace.StartSpan(sctx, apiName+"/Client.OrderedRange/"+addr)
defer func() {
if span != nil {
span.End()
}
}()
_, ierr := g.connectWithBackoff(ssctx, p, addr, true, func(ictx context.Context,
conn *ClientConn, copts ...CallOption,
) (any, error) {
return nil, f(ictx, addr, conn, copts...)
})
if ierr != nil {
err = errors.Join(err, ierr)
}
}
}
if cnt == 0 {
err = errors.ErrGRPCClientConnNotFound("*")
}
if err != nil {
if span != nil {
span.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
span.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
span.SetStatus(trace.StatusError, err.Error())
}
if errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) {
return err
}
}
return nil
}
func (g *gRPCClient) OrderedRangeConcurrent(
ctx context.Context,
orders []string,
concurrency int,
f func(ctx context.Context, addr string, conn *ClientConn, copts ...CallOption) error,
) (err error) {
sctx, span := trace.StartSpan(ctx, apiName+"/Client.OrderedRangeConcurrent")
defer func() {
if span != nil {
span.End()
}
}()
if len(orders) == 0 {
log.Warn("no order found for OrderedRangeConcurrent")
return g.RangeConcurrent(sctx, concurrency, f)
}
if g.conns.Len() == 0 {
return errors.ErrGRPCClientConnNotFound("*")
}
if concurrency == 0 || concurrency == 1 {
return g.OrderedRange(ctx, orders, f)
}
eg, egctx := errgroup.New(sctx)
eg.SetLimit(concurrency)
for _, order := range orders {
addr := order
eg.Go(safety.RecoverFunc(func() (err error) {
p, ok := g.conns.Load(addr)
if !ok || p == nil {
g.crl.Store(addr, true)
log.Warnf("gRPCClient.OrderedRangeConcurrent operation failed, gRPC connection pool for %s is invalid,\terror: %v", addr, errors.ErrGRPCClientConnNotFound(addr))
return nil
}
ssctx, sspan := trace.StartSpan(sctx, apiName+"/Client.OrderedRangeConcurrent/"+addr)
defer func() {
if sspan != nil {
sspan.End()
}
}()
select {
case <-egctx.Done():
return nil
default:
_, err = g.connectWithBackoff(ssctx, p, addr, true, func(ictx context.Context,
conn *ClientConn, copts ...CallOption,
) (any, error) {
return nil, f(ictx, addr, conn, copts...)
})
if err != nil {
if sspan != nil {
sspan.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
sspan.SetStatus(trace.StatusError, err.Error())
}
}
return nil
}
}))
}
err = eg.Wait()
if err != nil && span != nil {
span.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
span.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
span.SetStatus(trace.StatusError, err.Error())
}
return nil
}
func (g *gRPCClient) RoundRobin(
ctx context.Context,
f func(ctx context.Context,
conn *ClientConn, copts ...CallOption) (any, error),
) (data any, err error) {
sctx, span := trace.StartSpan(ctx, apiName+"/Client.RoundRobin")
defer func() {
if span != nil {
span.End()
}
}()
if g.conns.Len() == 0 {
return nil, errors.ErrGRPCClientConnNotFound("*")
}
var boName string
if boName = FromGRPCMethod(sctx); boName != "" {
sctx = backoff.WithBackoffName(sctx, boName)
}
do := func() (data any, err error) {
cerr := g.rangeConns(func(addr string, p pool.Conn) bool {
select {
case <-ctx.Done():
err = ctx.Err()
return false
default:
if p != nil && p.IsHealthy(sctx) {
ctx, span := trace.StartSpan(sctx, apiName+"/Client.RoundRobin/"+addr)
defer func() {
if span != nil {
span.End()
}
}()
var boName string
ctx = WrapGRPCMethod(ctx, addr)
if boName = FromGRPCMethod(ctx); boName != "" {
ctx = backoff.WithBackoffName(ctx, boName)
}
if g.cb != nil && len(boName) > 0 {
data, err = g.cb.Do(ctx, boName, func(ictx context.Context) (any, error) {
return g.connectWithBackoff(ictx, p, addr, false, f)
})
if err != nil {
if span != nil {
span.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
span.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
span.SetStatus(trace.StatusError, err.Error())
}
return true
}
return false
}
data, err = g.connectWithBackoff(ctx, p, addr, false, f)
if err != nil {
if span != nil {
span.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
span.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
span.SetStatus(trace.StatusError, err.Error())
}
return true
}
return false
}
g.crl.Store(addr, true)
}
return true
})
if cerr != nil {
return nil, cerr
}
return data, err
}
if g.bo != nil {
return g.bo.Do(sctx, func(ictx context.Context) (r any, ret bool, err error) {
r, err = do()
if err != nil {
if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, errors.ErrCircuitBreakerOpenState) ||
errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) ||
errors.Is(err, errors.ErrGRPCClientNotFound) {
return nil, false, err
}
st, ok := status.FromError(err)
if !ok || st == nil {
if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) {
return nil, false, err
}
return nil, err != nil, err
}
status.Log(st.Code(), err)
switch st.Code() {
case codes.Internal,
codes.Unavailable,
codes.ResourceExhausted:
return nil, err != nil, err
}
return nil, false, err
}
return r, false, nil
})
}
return do()
}
func (g *gRPCClient) Do(
ctx context.Context,
addr string,
f func(ctx context.Context,
conn *ClientConn, copts ...CallOption) (any, error),
) (data any, err error) {
sctx, span := trace.StartSpan(ctx, apiName+"/Client.Do/"+addr)
defer func() {
if span != nil {
span.End()
}
}()
p, ok := g.conns.Load(addr)
if !ok || p == nil {
g.crl.Store(addr, true)
err = errors.ErrGRPCClientConnNotFound(addr)
log.Warnf("gRPCClient.Do operation failed, gRPC connection pool for %s is invalid,\terror: %v", addr, err)
if span != nil {
span.RecordError(err)
span.SetAttributes(trace.StatusCodeUnavailable(err.Error())...)
span.SetStatus(trace.StatusError, err.Error())
}
return nil, err
}
data, err = g.connectWithBackoff(sctx, p, addr, true, f)
if err != nil && span != nil {
span.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
span.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
span.SetStatus(trace.StatusError, err.Error())
}
return data, err
}
func (g *gRPCClient) connectWithBackoff(
ctx context.Context,
p pool.Conn,
addr string,
enableBackoff bool,
f func(ctx context.Context,
conn *ClientConn, copts ...CallOption) (any, error),
) (data any, err error) {
if p == nil {
g.crl.Store(addr, true)
err = errors.ErrGRPCClientConnNotFound(addr)
log.Warnf("gRPCClient.do operation failed, gRPC connection pool for %s is invalid,\terror: %v", addr, err)
return nil, err
}
sctx, span := trace.StartSpan(ctx, apiName+"/Client.do/"+addr)
defer func() {
if span != nil {
span.End()
}
}()
if g.bo != nil && enableBackoff {
var boName string
sctx = WrapGRPCMethod(sctx, addr)
if boName = FromGRPCMethod(sctx); boName != "" {
sctx = backoff.WithBackoffName(sctx, boName)
}
do := func(ctx context.Context) (r any, ret bool, err error) {
err = p.Do(ctx, func(conn *ClientConn) (err error) {
if conn == nil {
return errors.ErrGRPCClientConnNotFound(addr)
}
r, err = f(ctx, conn, g.copts...)
return err
})
if err != nil {
if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, errors.ErrCircuitBreakerOpenState) ||
errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) ||
errors.Is(err, errors.ErrGRPCClientNotFound) ||
p.IsIPConn() && errors.Is(err, errors.ErrGRPCClientConnNotFound(addr)) {
return nil, false, err
}
st, ok := status.FromError(err)
if !ok || st == nil {
if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) {
return nil, false, err
}
return nil, err != nil, err
}
status.Log(st.Code(), err)
switch st.Code() {
case codes.Internal,
codes.Unavailable,
codes.ResourceExhausted:
return nil, err != nil, err
}
return nil, false, err
}
return r, false, nil
}
data, err = g.bo.Do(sctx, func(ictx context.Context) (r any, ret bool, err error) {
if g.cb != nil && len(boName) > 0 {
r, err = g.cb.Do(ictx, boName, func(ictx context.Context) (any, error) {
r, ret, err = do(ictx)
if err != nil && !ret {
return r, errors.NewErrCircuitBreakerIgnorable(err)
}
return r, err
})
if err != nil {
if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, errors.ErrCircuitBreakerOpenState) ||
errors.Is(err, errors.ErrGRPCClientConnNotFound("*")) ||
errors.Is(err, errors.ErrGRPCClientNotFound) {
return nil, false, err
}
}
return r, ret, err
}
return do(ictx)
})
} else {
err = p.Do(sctx, func(conn *ClientConn) (err error) {
if conn == nil {
return errors.ErrGRPCClientConnNotFound(addr)
}
data, err = f(sctx, conn, g.copts...)
return err
})
}
if err != nil {
if span != nil {
span.RecordError(err)
st, ok := status.FromError(err)
if ok && st != nil {
span.SetAttributes(trace.FromGRPCStatus(st.Code(), err.Error())...)
}
span.SetStatus(trace.StatusError, err.Error())
}
return nil, errors.ErrRPCCallFailed(addr, err)
}
return data, nil
}
func (g *gRPCClient) GetDialOption() []DialOption {
return g.dopts
}
func (g *gRPCClient) GetCallOption() []CallOption {
return g.copts
}
func (g *gRPCClient) GetBackoff() backoff.Backoff {
return g.bo
}
func (g *gRPCClient) SetDisableResolveDNSAddr(addr string, disabled bool) {
// NOTE: When connecting to multiple locations, it was necessary to switch dynamically, so implementation was added.
// There is no setting for disable on the helm chart side, so I used this implementation.
g.disableResolveDNSAddrs.Store(addr, disabled)
}
func (g *gRPCClient) Connect(
ctx context.Context, addr string, dopts ...DialOption,
) (conn pool.Conn, err error) {
ctx, span := trace.StartSpan(ctx, apiName+"/Client.Connect/"+addr)
defer func() {
if span != nil {
span.End()
}
}()
sconn, shared, err := g.group.Do(ctx, "connect-"+addr, func(ctx context.Context) (pool.Conn, error) {
var ok bool
conn, ok = g.conns.Load(addr)
if ok && conn != nil {
if conn.IsHealthy(ctx) {
return conn, nil
}
log.Debugf("connecting unhealthy pool addr= %s", addr)
conn, err = conn.Connect(ctx)
if err == nil && conn != nil && conn.IsHealthy(ctx) {
g.conns.Store(addr, conn)
return conn, nil
}
log.Warnf("failed to reconnect unhealthy pool conn=[%v]\terror= %v\t trying to disconnect", conn, err)
}
log.Warnf("creating new connection pool for addr = %s", addr)
opts := []pool.Option{
pool.WithAddr(addr),
pool.WithSize(g.poolSize),
pool.WithDialOptions(append(g.dopts, dopts...)...),
pool.WithResolveDNS(func() bool {
disabled, ok := g.disableResolveDNSAddrs.Load(addr)
if ok && disabled {
return false
}
return g.resolveDNS
}()),
}
if g.bo != nil {
opts = append(opts, pool.WithBackoff(g.bo))
}
conn, err = pool.New(ctx, opts...)
if err != nil || conn == nil {
derr := g.Disconnect(ctx, addr)
if derr != nil && !errors.Is(derr, errors.ErrGRPCClientConnNotFound(addr)) {