-
Notifications
You must be signed in to change notification settings - Fork 10
/
conn.go
121 lines (106 loc) · 2 KB
/
conn.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
package ydb
import (
"context"
"sync"
"time"
"github.com/yandex-cloud/ydb-go-sdk/v2/internal/stats"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
)
type conn struct {
addr connAddr
dial func(ctx context.Context, address string) (*grpc.ClientConn, error)
m sync.RWMutex
cc *grpc.ClientConn
runtime connRuntime
}
// Deprecated: will be removed at next major release
func (c *conn) Conn() *conn {
return c
}
func (c *conn) isBroken() bool {
if c == nil {
return true
}
c.m.RLock()
defer c.m.RUnlock()
return c._isBroken()
}
func (c *conn) _isBroken() bool {
if c.cc == nil {
return true
}
switch c.cc.GetState() {
case connectivity.Shutdown, connectivity.TransientFailure:
return true
default:
return false
}
}
func (c *conn) isReady() bool {
if c == nil {
return false
}
c.m.RLock()
defer c.m.RUnlock()
return c._isReady()
}
func (c *conn) _isReady() bool {
if c.cc == nil {
return false
}
switch c.cc.GetState() {
case connectivity.Ready:
return true
default:
return false
}
}
func (c *conn) close() error {
if c == nil {
return nil
}
c.m.Lock()
defer c.m.Unlock()
if c.cc == nil {
return nil
}
return c.cc.Close()
}
func (c *conn) _close() error {
if c.cc == nil {
return nil
}
return c.cc.Close()
}
func (c *conn) getConn(ctx context.Context) (_ *grpc.ClientConn, err error) {
c.m.Lock()
defer c.m.Unlock()
if c._isBroken() {
_ = c._close()
c.cc, err = c.dial(ctx, c.addr.String())
}
return c.cc, err
}
func (c *conn) Address() string {
if c == nil {
return ""
}
return c.addr.String()
}
func newConn(addr connAddr, dial func(ctx context.Context, address string) (*grpc.ClientConn, error)) *conn {
const (
statsDuration = time.Minute
statsBuckets = 12
)
return &conn{
dial: dial,
addr: addr,
runtime: connRuntime{
state: ConnOffline,
opTime: stats.NewSeries(statsDuration, statsBuckets),
opRate: stats.NewSeries(statsDuration, statsBuckets),
errRate: stats.NewSeries(statsDuration, statsBuckets),
},
}
}