forked from weeaa/jito-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
63 lines (57 loc) · 1.35 KB
/
grpc.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
package pkg
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"time"
)
// CreateAndObserveGRPCConn creates a new gRPC connection and observes its conn status.
func CreateAndObserveGRPCConn(ctx context.Context, chErr chan error, target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
conn, err := grpc.NewClient(target, opts...)
if err != nil {
return nil, err
}
go func() {
var retries int
for {
select {
case <-ctx.Done():
if err = conn.Close(); err != nil {
chErr <- err
}
return
default:
state := conn.GetState()
if state == connectivity.Ready {
retries = 0
time.Sleep(1 * time.Second)
continue
}
if state == connectivity.TransientFailure || state == connectivity.Connecting || state == connectivity.Idle {
if retries < 5 {
time.Sleep(time.Duration(retries) * time.Second)
conn.ResetConnectBackoff()
retries++
} else {
conn.Close()
conn, err = grpc.NewClient(target, opts...)
if err != nil {
chErr <- err
}
retries = 0
}
} else if state == connectivity.Shutdown {
conn, err = grpc.NewClient(target, opts...)
if err != nil {
chErr <- err
}
retries = 0
}
if !conn.WaitForStateChange(ctx, state) {
continue
}
}
}
}()
return conn, nil
}