-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc_connection.go
64 lines (53 loc) · 1.82 KB
/
rpc_connection.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
package danube
import (
"context"
"net"
"strings"
"time"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
)
// RpcConnection wraps a gRPC client connection.
type rpcConnection struct {
grpcConn *grpc.ClientConn
}
// DialOption is a function that configures gRPC dial options.
type DialOption func(*[]grpc.DialOption)
// WithKeepAliveInterval configures the keepalive interval for the connection.
func WithKeepAliveInterval(interval time.Duration) DialOption {
return func(opts *[]grpc.DialOption) {
*opts = append(*opts, grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: interval,
}))
}
}
// WithConnectionTimeout configures the connection timeout for the connection.
func WithConnectionTimeout(timeout time.Duration) DialOption {
return func(opts *[]grpc.DialOption) {
*opts = append(*opts, grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
dialer := &net.Dialer{Timeout: timeout}
return dialer.DialContext(ctx, "tcp", addr)
}))
}
}
// NewRpcConnection creates a new RpcConnection with the given options.
func newRpcConnection(connectURL string, options ...DialOption) (*rpcConnection, error) {
var dialOptions []grpc.DialOption
// Apply default options
dialOptions = append(dialOptions, grpc.WithTransportCredentials(insecure.NewCredentials()))
// Apply additional options
for _, opt := range options {
opt(&dialOptions)
}
// the server send the address with http, required by Rust tonic client
// therefore needs to be trimmed here
prefix := "http://"
url_trimmed := strings.TrimPrefix(connectURL, prefix)
conn, err := grpc.NewClient(url_trimmed, dialOptions...)
if err != nil {
return nil, errors.Wrap(err, "failed to connect")
}
return &rpcConnection{grpcConn: conn}, nil
}