This repository has been archived by the owner on Sep 24, 2022. It is now read-only.
forked from carousell/Orion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
212 lines (180 loc) · 7.07 KB
/
utils.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package handlers
import (
"context"
"reflect"
"github.com/go-orion/Orion/interceptors"
"github.com/go-orion/Orion/orion/modifiers"
"github.com/go-orion/Orion/utils/errors"
"github.com/go-orion/Orion/utils/errors/notifier"
"github.com/go-orion/Orion/utils/log"
"github.com/go-orion/Orion/utils/log/loggers"
"github.com/go-orion/Orion/utils/options"
"google.golang.org/grpc"
)
// ChainUnaryServer creates a single interceptor out of a chain of many interceptors.
//
// Execution is done in left-to-right order, including passing of context.
// For example ChainUnaryServer(one, two, three) will execute one before two before three, and three
// will see context changes of one and two.
func chainUnaryServer(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
n := len(interceptors)
if n > 1 {
lastI := n - 1
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
var (
chainHandler grpc.UnaryHandler
curI int
)
chainHandler = func(currentCtx context.Context, currentReq interface{}) (interface{}, error) {
if curI == lastI {
return handler(currentCtx, currentReq)
}
curI++
return interceptors[curI](currentCtx, currentReq, info, chainHandler)
}
return interceptors[0](ctx, req, info, chainHandler)
}
}
if n == 1 {
return interceptors[0]
}
// n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil.
return func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
return handler(ctx, req)
}
}
// ChainStreamServer creates a single interceptor out of a chain of many interceptors.
//
// Execution is done in left-to-right order, including passing of context.
// For example ChainUnaryServer(one, two, three) will execute one before two before three.
// If you want to pass context between interceptors, use WrapServerStream.
func chainStreamServer(interceptors ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor {
n := len(interceptors)
if n > 1 {
lastI := n - 1
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
var (
chainHandler grpc.StreamHandler
curI int
)
chainHandler = func(currentSrv interface{}, currentStream grpc.ServerStream) error {
if curI == lastI {
return handler(currentSrv, currentStream)
}
curI++
err := interceptors[curI](currentSrv, currentStream, info, chainHandler)
curI--
return err
}
return interceptors[0](srv, stream, info, chainHandler)
}
}
if n == 1 {
return interceptors[0]
}
// n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil.
return func(srv interface{}, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return handler(srv, stream)
}
}
//GetInterceptors fetches interceptors from a given GRPC service
func GetInterceptors(svc interface{}, config CommonConfig) grpc.UnaryServerInterceptor {
return chainUnaryServer(getInterceptors(svc, config, []string{})...)
}
//GetStreamInterceptors fetches stream interceptors from a given GRPC service
func GetStreamInterceptors(svc interface{}, config CommonConfig) grpc.StreamServerInterceptor {
return chainStreamServer(getStreamInterceptors(svc, config)...)
}
//GetInterceptorsWithMethodMiddlewares fetchs all middleware including those provided by method middlewares
func GetInterceptorsWithMethodMiddlewares(svc interface{}, config CommonConfig, middlewares []string) grpc.UnaryServerInterceptor {
return chainUnaryServer(getInterceptors(svc, config, middlewares)...)
}
func getInterceptors(svc interface{}, config CommonConfig, middlewares []string) []grpc.UnaryServerInterceptor {
opts := []grpc.UnaryServerInterceptor{optionsInterceptor}
// check and add default interceptors
if !config.NoDefaultInterceptors {
// Add default interceptors
opts = append(opts, interceptors.DefaultInterceptors()...)
}
// check and add service interceptors
interceptor, ok := svc.(Interceptor)
if ok {
opts = append(opts, interceptor.GetInterceptors()...)
}
// check and add method interceptors
opts = append(opts, GetMethodInterceptors(svc, config, middlewares)...)
return opts
}
func getStreamInterceptors(svc interface{}, config CommonConfig) []grpc.StreamServerInterceptor {
opts := []grpc.StreamServerInterceptor{optionsStreamInterceptor}
// check and add default interceptors
if !config.NoDefaultInterceptors {
// Add default interceptors
opts = append(opts, interceptors.DefaultStreamInterceptors()...)
}
// check and add service interceptors
interceptor, ok := svc.(StreamInterceptor)
if ok {
opts = append(opts, interceptor.GetStreamInterceptors()...)
}
return opts
}
func getMiddleware(svc interface{}, middleware string) (grpc.UnaryServerInterceptor, error) {
r := reflect.TypeOf(svc)
if m, ok := r.MethodByName(middleware); ok {
if m.Type.NumIn() == 1 && m.Type.NumOut() == 1 && !m.Type.IsVariadic() {
t := reflect.TypeOf(grpc.UnaryServerInterceptor(nil))
if r.ConvertibleTo(m.Type.In(0)) && m.Type.Out(0).ConvertibleTo(t) {
v := m.Func.Call([]reflect.Value{reflect.ValueOf(svc)})
return v[0].Interface().(grpc.UnaryServerInterceptor), nil
}
}
return nil, errors.New("middleware should be defined as 'func (" + r.String() + ") " + middleware + "() grpc.UnaryServerInterceptor'")
}
return nil, errors.New("could not find middleware " + middleware)
}
//GetMethodInterceptors fetches all interceptors including method middlewares
func GetMethodInterceptors(svc interface{}, config CommonConfig, middlewares []string) []grpc.UnaryServerInterceptor {
interceptors := make([]grpc.UnaryServerInterceptor, 0)
for _, middleware := range middlewares {
interceptor, err := getMiddleware(svc, middleware)
if err != nil {
log.Error(context.Background(), "error", err, "middleware", "could not fetch middleware")
notifier.NotifyWithLevel(err, "critical")
} else {
if interceptor != nil {
interceptors = append(interceptors, interceptor)
}
}
}
return interceptors
}
type streamServer struct {
grpc.ServerStream
ctx context.Context
}
func (ss *streamServer) Context() context.Context {
if ss.ctx == nil {
return ss.ServerStream.Context()
}
return ss.ctx
}
func optionsStreamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
ctx := ss.Context()
ctx = options.AddToOptions(ctx, "", "")
ctx = loggers.AddToLogContext(ctx, "grpcMethod", info.FullMethod)
newServer := &streamServer{
ServerStream: ss,
ctx: ctx,
}
return handler(srv, newServer)
}
func optionsInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
ctx = options.AddToOptions(ctx, "", "")
ctx = loggers.AddToLogContext(ctx, "grpcMethod", info.FullMethod)
if !modifiers.IsHTTPRequest(ctx) {
loggers.AddToLogContext(ctx, "transport", "gRPC")
options.AddToOptions(ctx, modifiers.RequestGRPC, true)
}
return handler(ctx, req)
}