/
grpc.go
136 lines (126 loc) · 4.26 KB
/
grpc.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
package appmgr
import (
"context"
"crypto/tls"
"crypto/x509"
"math"
"os"
"time"
"github.com/fullstorydev/grpchan/inprocgrpc"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
"google.golang.org/protobuf/encoding/protojson"
"github.com/frame-go/framego/errors"
"github.com/frame-go/framego/grpcex"
"github.com/frame-go/framego/log"
)
const ServerConnMaxIdle = time.Duration(math.MaxInt64)
const ServerConnMaxAge = time.Duration(math.MaxInt64)
const ServerConnMaxAgeGrace = time.Duration(math.MaxInt64)
const KeepaliveMinTime = 10 * time.Second
const KeepaliveTime = 1 * time.Minute
const KeepaliveTimeout = 20 * time.Second
func initGrpc() {
grpcex.SetZeroLogger()
grpcex.RegisterJsonCodec()
}
func newGrpcServerWithChannel(tlsConfig *tls.Config, middlewares *middlewareApplier) (*grpc.Server, *inprocgrpc.Channel) {
chainUnaryInterceptor, chainStreamInterceptor := middlewares.GrpcServerInterceptor()
serverOptions := []grpc.ServerOption{
grpc.UnaryInterceptor(chainUnaryInterceptor),
grpc.StreamInterceptor(chainStreamInterceptor),
grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionIdle: ServerConnMaxIdle,
MaxConnectionAge: ServerConnMaxAge,
MaxConnectionAgeGrace: ServerConnMaxAgeGrace,
Time: KeepaliveTime,
Timeout: KeepaliveTimeout,
}),
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: KeepaliveMinTime,
PermitWithoutStream: true,
}),
}
if tlsConfig != nil {
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
creds := credentials.NewTLS(tlsConfig)
serverOptions = append(serverOptions, grpc.Creds(creds))
}
server := grpc.NewServer(serverOptions...)
grpcChannel := &inprocgrpc.Channel{}
grpcChannel.WithServerUnaryInterceptor(chainUnaryInterceptor)
grpcChannel.WithServerStreamInterceptor(chainStreamInterceptor)
return server, grpcChannel
}
func newGrpcClient(ctx context.Context, name string, endpoint string, tlsConfig *tls.Config, middlewares *middlewareApplier) grpc.ClientConnInterface {
var creds credentials.TransportCredentials
if tlsConfig == nil {
creds = insecure.NewCredentials()
} else {
tlsConfig.ServerName = name
creds = credentials.NewTLS(tlsConfig)
}
chainUnaryInterceptor, chainStreamInterceptor := middlewares.GrpcClientInterceptor()
conn, err := grpc.Dial(
endpoint,
grpc.WithTransportCredentials(creds),
grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
grpc.WithUnaryInterceptor(chainUnaryInterceptor),
grpc.WithStreamInterceptor(chainStreamInterceptor),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: KeepaliveTime,
Timeout: KeepaliveTimeout,
PermitWithoutStream: true,
}),
)
if err != nil {
log.Logger.Error().Err(err).Str("endpoint", endpoint).Msg("new_grpc_client_dial_error")
return nil
}
return conn
}
func newGrpcHttpMux() *runtime.ServeMux {
return runtime.NewServeMux(
runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
UseProtoNames: true,
UseEnumNumbers: true,
EmitUnpopulated: true,
},
UnmarshalOptions: protojson.UnmarshalOptions{
DiscardUnknown: true,
},
}),
runtime.WithIncomingHeaderMatcher(grpcex.DefaultHeaderMatcher),
)
}
func newTLSConfig(certFile string, keyFile string, caFile string) (*tls.Config, error) {
if certFile == "" && keyFile == "" && caFile == "" {
return nil, nil
}
tlsConfig := &tls.Config{}
if certFile != "" && keyFile != "" {
certificate, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, errors.Wrap(err, "load_cert_key_pair_error").
With("cert_file", certFile).With("key_file", keyFile)
}
tlsConfig.Certificates = []tls.Certificate{certificate}
}
if caFile != "" {
certPool := x509.NewCertPool()
ca, err := os.ReadFile(caFile)
if err != nil {
return nil, errors.Wrap(err, "read_ca_file_error").With("ca_file", caFile)
}
if !certPool.AppendCertsFromPEM(ca) {
return nil, errors.New("add_ca_cert_error").With("ca_file", caFile)
}
tlsConfig.RootCAs = certPool
tlsConfig.ClientCAs = certPool
}
return tlsConfig, nil
}