forked from dtm-labs/dtm
/
grpc_clients.go
79 lines (66 loc) · 2.1 KB
/
grpc_clients.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
/*
* Copyright (c) 2021 yedf. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
package dtmgimp
import (
"fmt"
"sync"
"github.com/10antz-inc/pf-dtm/client/dtmcli/dtmimp"
"github.com/10antz-inc/pf-dtm/client/dtmconn"
"github.com/10antz-inc/pf-dtm/client/dtmgrpc/dtmgpb"
"github.com/dtm-labs/dtmdriver"
"github.com/dtm-labs/logger"
grpc "google.golang.org/grpc"
)
type rawCodec struct{}
func (cb rawCodec) Marshal(v interface{}) ([]byte, error) {
return v.([]byte), nil
}
func (cb rawCodec) Unmarshal(data []byte, v interface{}) error {
ba, ok := v.(*[]byte)
dtmimp.PanicIf(!ok, fmt.Errorf("please pass in *[]byte"))
*ba = append(*ba, data...)
return nil
}
func (cb rawCodec) Name() string { return "dtm_raw" }
var normalClients, rawClients sync.Map
// ClientInterceptors declares grpc.UnaryClientInterceptors slice
var ClientInterceptors = []grpc.UnaryClientInterceptor{}
// MustGetDtmClient 1
func MustGetDtmClient(grpcServer string) dtmgpb.DtmClient {
return dtmgpb.NewDtmClient(MustGetGrpcConn(grpcServer, false))
}
// GetGrpcConn 1
func GetGrpcConn(grpcServer string, isRaw bool) (conn *grpc.ClientConn, rerr error) {
clients := &normalClients
if isRaw {
clients = &rawClients
}
grpcServer = dtmimp.MayReplaceLocalhost(grpcServer)
v, ok := clients.Load(grpcServer)
if !ok {
opts := grpc.WithDefaultCallOptions()
if isRaw {
opts = grpc.WithDefaultCallOptions(grpc.ForceCodec(rawCodec{}))
}
logger.Debugf("grpc client connecting %s", grpcServer)
interceptors := append(ClientInterceptors, GrpcClientLog)
interceptors = append(interceptors, dtmdriver.Middlewares.Grpc...)
inOpt := grpc.WithChainUnaryInterceptor(interceptors...)
conn, rerr := dtmconn.Dial(grpcServer, inOpt, opts)
if rerr == nil {
clients.Store(grpcServer, conn)
v = conn
logger.Debugf("grpc client inited for %s", grpcServer)
}
}
return v.(*grpc.ClientConn), rerr
}
// MustGetGrpcConn 1
func MustGetGrpcConn(grpcServer string, isRaw bool) *grpc.ClientConn {
conn, err := GetGrpcConn(grpcServer, isRaw)
dtmimp.E2P(err)
return conn
}