-
Notifications
You must be signed in to change notification settings - Fork 175
/
connection_factory.go
245 lines (208 loc) · 7.26 KB
/
connection_factory.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
package backend
import (
"context"
"fmt"
"net"
"sync"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/onflow/flow/protobuf/go/flow/access"
"github.com/onflow/flow/protobuf/go/flow/execution"
"github.com/rs/zerolog"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/utils/grpcutils"
)
// DefaultClientTimeout is used when making a GRPC request to a collection node or an execution node
const DefaultClientTimeout = 3 * time.Second
// ConnectionFactory is used to create an access api client
type ConnectionFactory interface {
GetAccessAPIClient(address string) (access.AccessAPIClient, error)
InvalidateAccessAPIClient(address string)
GetExecutionAPIClient(address string) (execution.ExecutionAPIClient, error)
InvalidateExecutionAPIClient(address string)
}
type ProxyConnectionFactory struct {
ConnectionFactory
targetAddress string
}
func (p *ProxyConnectionFactory) GetAccessAPIClient(address string) (access.AccessAPIClient, error) {
return p.ConnectionFactory.GetAccessAPIClient(p.targetAddress)
}
func (p *ProxyConnectionFactory) GetExecutionAPIClient(address string) (execution.ExecutionAPIClient, error) {
return p.ConnectionFactory.GetExecutionAPIClient(p.targetAddress)
}
type ConnectionFactoryImpl struct {
CollectionGRPCPort uint
ExecutionGRPCPort uint
CollectionNodeGRPCTimeout time.Duration
ExecutionNodeGRPCTimeout time.Duration
ConnectionsCache *lru.Cache
CacheSize uint
AccessMetrics module.AccessMetrics
Log zerolog.Logger
mutex sync.Mutex
}
type CachedClient struct {
ClientConn *grpc.ClientConn
Address string
mutex sync.Mutex
timeout time.Duration
}
// createConnection creates new gRPC connections to remote node
func (cf *ConnectionFactoryImpl) createConnection(address string, timeout time.Duration) (*grpc.ClientConn, error) {
if timeout == 0 {
timeout = DefaultClientTimeout
}
keepaliveParams := keepalive.ClientParameters{
// how long the client will wait before sending a keepalive to the server if there is no activity
Time: 10 * time.Second,
// how long the client will wait for a response from the keepalive before closing
Timeout: timeout,
}
// ClientConn's default KeepAlive on connections is indefinite, assuming the timeout isn't reached
// The connections should be safe to be persisted and reused
// https://pkg.go.dev/google.golang.org/grpc#WithKeepaliveParams
// https://grpc.io/blog/grpc-on-http2/#keeping-connections-alive
conn, err := grpc.Dial(
address,
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(grpcutils.DefaultMaxMsgSize)),
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithKeepaliveParams(keepaliveParams),
WithClientUnaryInterceptor(timeout))
if err != nil {
return nil, fmt.Errorf("failed to connect to address %s: %w", address, err)
}
return conn, nil
}
func (cf *ConnectionFactoryImpl) retrieveConnection(grpcAddress string, timeout time.Duration) (*grpc.ClientConn, error) {
var conn *grpc.ClientConn
var store *CachedClient
cacheHit := false
cf.mutex.Lock()
if res, ok := cf.ConnectionsCache.Get(grpcAddress); ok {
cacheHit = true
store = res.(*CachedClient)
conn = store.ClientConn
} else {
store = &CachedClient{
ClientConn: nil,
Address: grpcAddress,
timeout: timeout,
}
cf.Log.Debug().Str("cached_client_added", grpcAddress).Msg("adding new cached client to pool")
cf.ConnectionsCache.Add(grpcAddress, store)
if cf.AccessMetrics != nil {
cf.AccessMetrics.ConnectionAddedToPool()
}
}
cf.mutex.Unlock()
store.mutex.Lock()
defer store.mutex.Unlock()
if conn == nil || conn.GetState() == connectivity.Shutdown {
var err error
conn, err = cf.createConnection(grpcAddress, timeout)
if err != nil {
return nil, err
}
store.ClientConn = conn
if cf.AccessMetrics != nil {
if cacheHit {
cf.AccessMetrics.ConnectionFromPoolUpdated()
}
cf.AccessMetrics.NewConnectionEstablished()
cf.AccessMetrics.TotalConnectionsInPool(uint(cf.ConnectionsCache.Len()), cf.CacheSize)
}
} else if cf.AccessMetrics != nil {
cf.AccessMetrics.ConnectionFromPoolReused()
}
return conn, nil
}
func (cf *ConnectionFactoryImpl) GetAccessAPIClient(address string) (access.AccessAPIClient, error) {
grpcAddress, err := getGRPCAddress(address, cf.CollectionGRPCPort)
if err != nil {
return nil, err
}
conn, err := cf.retrieveConnection(grpcAddress, cf.CollectionNodeGRPCTimeout)
if err != nil {
return nil, err
}
accessAPIClient := access.NewAccessAPIClient(conn)
return accessAPIClient, nil
}
func (cf *ConnectionFactoryImpl) InvalidateAccessAPIClient(address string) {
cf.Log.Debug().Str("cached_access_client_invalidated", address).Msg("invalidating cached access client")
cf.invalidateAPIClient(address, cf.CollectionGRPCPort)
}
func (cf *ConnectionFactoryImpl) GetExecutionAPIClient(address string) (execution.ExecutionAPIClient, error) {
grpcAddress, err := getGRPCAddress(address, cf.ExecutionGRPCPort)
if err != nil {
return nil, err
}
conn, err := cf.retrieveConnection(grpcAddress, cf.ExecutionNodeGRPCTimeout)
if err != nil {
return nil, err
}
executionAPIClient := execution.NewExecutionAPIClient(conn)
return executionAPIClient, nil
}
func (cf *ConnectionFactoryImpl) InvalidateExecutionAPIClient(address string) {
cf.Log.Debug().Str("cached_execution_client_invalidated", address).Msg("invalidating cached execution client")
cf.invalidateAPIClient(address, cf.ExecutionGRPCPort)
}
func (cf *ConnectionFactoryImpl) invalidateAPIClient(address string, port uint) {
grpcAddress, _ := getGRPCAddress(address, port)
if res, ok := cf.ConnectionsCache.Get(grpcAddress); ok {
store := res.(*CachedClient)
store.Close()
if cf.AccessMetrics != nil {
cf.AccessMetrics.ConnectionFromPoolInvalidated()
}
}
}
func (s *CachedClient) Close() {
s.mutex.Lock()
conn := s.ClientConn
s.ClientConn = nil
s.mutex.Unlock()
if conn == nil {
return
}
// allow time for any existing requests to finish before closing the connection
time.Sleep(s.timeout)
conn.Close()
}
// getExecutionNodeAddress translates flow.Identity address to the GRPC address of the node by switching the port to the
// GRPC port from the libp2p port
func getGRPCAddress(address string, grpcPort uint) (string, error) {
// split hostname and port
hostnameOrIP, _, err := net.SplitHostPort(address)
if err != nil {
return "", err
}
// use the hostname from identity list and port number as the one passed in as argument
grpcAddress := fmt.Sprintf("%s:%d", hostnameOrIP, grpcPort)
return grpcAddress, nil
}
func WithClientUnaryInterceptor(timeout time.Duration) grpc.DialOption {
clientTimeoutInterceptor := func(
ctx context.Context,
method string,
req interface{},
reply interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) error {
// create a context that expires after timeout
ctxWithTimeout, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// call the remote GRPC using the short context
err := invoker(ctxWithTimeout, method, req, reply, cc, opts...)
return err
}
return grpc.WithUnaryInterceptor(clientTimeoutInterceptor)
}