-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
client.go
72 lines (63 loc) · 2.12 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
package client
import (
"fmt"
"github.com/plgd-dev/hub/v2/pkg/fsnotify"
"github.com/plgd-dev/hub/v2/pkg/log"
"github.com/plgd-dev/hub/v2/pkg/security/certManager/client"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
)
// GRPC Client.
type Client struct {
client *grpc.ClientConn
closeFunc []func()
}
func (c *Client) GRPC() *grpc.ClientConn {
return c.client
}
// AddCloseFunc adds a function to be called by the Close method.
// This eliminates the need for wrapping the Client.
func (c *Client) AddCloseFunc(f func()) {
c.closeFunc = append(c.closeFunc, f)
}
func (c *Client) Close() error {
err := c.client.Close()
for _, f := range c.closeFunc {
f()
}
return err
}
func New(config Config, fileWatcher *fsnotify.Watcher, logger log.Logger, tracerProvider trace.TracerProvider, opts ...grpc.DialOption) (*Client, error) {
err := config.Validate()
if err != nil {
return nil, fmt.Errorf("invalid config: %w", err)
}
certManager, err := client.New(config.TLS, fileWatcher, logger)
if err != nil {
return nil, fmt.Errorf("cannot create cert manager: %w", err)
}
v := []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewTLS(certManager.GetTLSConfig())),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: config.KeepAlive.Time,
Timeout: config.KeepAlive.Timeout,
PermitWithoutStream: config.KeepAlive.PermitWithoutStream,
}),
grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor(otelgrpc.WithTracerProvider(tracerProvider))),
grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor(otelgrpc.WithTracerProvider(tracerProvider))),
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(config.SendMsgSize), grpc.MaxCallRecvMsgSize(config.RecvMsgSize)),
}
if len(opts) > 0 {
v = append(v, opts...)
}
conn, err := grpc.Dial(config.Addr, v...)
if err != nil {
return nil, fmt.Errorf("cannot dial: %w", err)
}
return &Client{
client: conn, closeFunc: []func(){certManager.Close},
}, nil
}