This repository has been archived by the owner on May 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 346
/
grpc.go
54 lines (45 loc) · 1.69 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
package rpc
import (
"fmt"
"runtime/debug"
"github.com/hyperledger/burrow/encoding"
"github.com/hyperledger/burrow/logging"
"github.com/hyperledger/burrow/logging/structure"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
func NewGRPCServer(logger *logging.Logger) *grpc.Server {
return grpc.NewServer(grpc.UnaryInterceptor(unaryInterceptor(logger)),
grpc.StreamInterceptor(streamInterceptor(logger.WithScope("NewGRPCServer"))),
grpc.CustomCodec(&encoding.GRPCCodec{}))
}
func unaryInterceptor(logger *logging.Logger) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (resp interface{}, err error) {
logger = logger.With("method", info.FullMethod)
defer func() {
if r := recover(); r != nil {
logger.InfoMsg("panic in GRPC unary call", structure.ErrorKey, fmt.Sprintf("%v", r))
err = fmt.Errorf("panic in GRPC unary call %s: %v: %s", info.FullMethod, r, debug.Stack())
}
}()
logger.TraceMsg("GRPC unary call")
return handler(ctx, req)
}
}
func streamInterceptor(logger *logging.Logger) grpc.StreamServerInterceptor {
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo,
handler grpc.StreamHandler) (err error) {
logger = logger.With("method", info.FullMethod,
"is_client_stream", info.IsClientStream,
"is_server_stream", info.IsServerStream)
defer func() {
if r := recover(); r != nil {
logger.InfoMsg("panic in GRPC stream", structure.ErrorKey, fmt.Sprintf("%v", r))
err = fmt.Errorf("panic in GRPC stream %s: %v: %s", info.FullMethod, r, debug.Stack())
}
}()
logger.TraceMsg("GRPC stream call")
return handler(srv, ss)
}
}