-
Notifications
You must be signed in to change notification settings - Fork 1
/
options.go
78 lines (65 loc) · 2 KB
/
options.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
package grpcx
import (
"context"
"time"
"github.com/msales/pkg/v3/grpcx/middleware"
"github.com/msales/pkg/v3/log"
"github.com/msales/pkg/v3/stats"
"google.golang.org/grpc"
"google.golang.org/grpc/balancer/roundrobin"
)
// UnaryClientCommonOpts returns commonly options for an unary client.
func UnaryClientCommonOpts(ctx context.Context, timeout time.Duration, additional ...grpc.UnaryClientInterceptor) []grpc.DialOption {
l, s := getLoggerAndStats(ctx)
interceptors := []grpc.UnaryClientInterceptor{
middleware.WithUnaryClientLogger(l),
middleware.WithUnaryClientStats(s),
middleware.WithUnaryClientRecovery(),
middleware.WithUnaryClientContextTimeout(timeout),
}
interceptors = append(interceptors, additional...)
return []grpc.DialOption{
grpc.WithInsecure(),
grpc.WithBalancerName(roundrobin.Name),
middleware.WithUnaryClientInterceptors(interceptors...),
}
}
// UnaryServerCommonOpts returns commonly options for an unary server.
func UnaryServerCommonOpts(ctx context.Context, statsTagsFns ...TagsFunc) []grpc.ServerOption {
l, s := getLoggerAndStats(ctx)
return []grpc.ServerOption{
middleware.WithUnaryServerInterceptors(
middleware.WithUnaryServerLogger(l),
middleware.WithUnaryServerStats(s),
middleware.WithUnaryServerRecovery(),
),
grpc.StatsHandler(
WithRPCStats(s, statsTagsFns...),
),
}
}
// StreamServerCommonOpts returns commonly options for a stream server.
func StreamServerCommonOpts(ctx context.Context, statsTagsFns ...TagsFunc) []grpc.ServerOption {
l, s := getLoggerAndStats(ctx)
return []grpc.ServerOption{
middleware.WithStreamServerInterceptors(
middleware.WithStreamServerLogger(l),
middleware.WithStreamServerStats(s),
middleware.WithStreamServerRecovery(),
),
grpc.StatsHandler(
WithRPCStats(s, statsTagsFns...),
),
}
}
func getLoggerAndStats(ctx context.Context) (log.Logger, stats.Stats) {
l, ok := log.FromContext(ctx)
if !ok {
l = log.Null
}
s, ok := stats.FromContext(ctx)
if !ok {
s = stats.Null
}
return l, s
}