-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
218 lines (180 loc) · 5.47 KB
/
server.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
213
214
215
216
217
218
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"github.com/vadimi/grpc-ditto/internal/dittomock"
"github.com/vadimi/grpc-ditto/internal/logger"
"github.com/golang/protobuf/jsonpb"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/dynamic"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoregistry"
_ "google.golang.org/grpc/health/grpc_health_v1"
)
// MockServer is an interface that grpc reflection expects to register types
type MockServer interface {
}
type mockServer struct {
logger logger.Logger
descrs []*desc.FileDescriptor
matcher *dittomock.RequestMatcher
}
func (s *mockServer) findMethodByName(method string) *desc.MethodDescriptor {
if method == "" {
return nil
}
serviceName := strings.Trim(method[0:strings.LastIndex(method, "/")], "/")
methodName := method[strings.LastIndex(method, "/")+1:]
for _, d := range s.descrs {
s := d.FindService(serviceName)
if s == nil {
continue
}
methodDesc := s.FindMethodByName(methodName)
if methodDesc != nil {
return methodDesc
}
}
return nil
}
func (s *mockServer) fileDescriptors() (map[string][]byte, error) {
result := map[string][]byte{}
err := s.processDescriptors(s.descrs, result)
return result, err
}
func (s *mockServer) processDescriptors(descrs []*desc.FileDescriptor, result map[string][]byte) error {
for _, d := range descrs {
if _, ok := result[d.GetName()]; ok {
continue
}
fd := d.AsFileDescriptorProto()
fDescBytes, err := proto.MarshalOptions{}.Marshal(fd)
if err != nil {
return err
}
result[fd.GetName()] = fDescBytes
err = s.processDescriptors(d.GetDependencies(), result)
if err != nil {
return err
}
}
return nil
}
func (s *mockServer) serviceDescriptors() []*grpc.ServiceDesc {
result := []*grpc.ServiceDesc{}
for _, d := range s.descrs {
for _, service := range d.GetServices() {
grpcSvcDesc := &grpc.ServiceDesc{
ServiceName: service.GetFullyQualifiedName(),
HandlerType: (*MockServer)(nil),
Metadata: d.AsFileDescriptorProto().GetName(),
Streams: []grpc.StreamDesc{},
}
for _, m := range service.GetMethods() {
// in grpc-go all methods are implemented as streams
// so we just need one handler to rule them all
grpcSvcDesc.Streams = append(grpcSvcDesc.Streams, grpc.StreamDesc{
StreamName: m.GetName(),
Handler: mockServerStreamHandler,
ServerStreams: m.IsServerStreaming(),
})
}
result = append(result, grpcSvcDesc)
}
}
return result
}
func mockServerStreamHandler(srv interface{}, stream grpc.ServerStream) error {
fullMethodName, ok := grpc.Method(stream.Context())
if !ok {
return errors.New("something is really wrong, method name not found in the request")
}
mockSrv := srv.(*mockServer)
mockSrv.logger.Infow("grpc call", "method", fullMethodName)
methodDesc := mockSrv.findMethodByName(fullMethodName)
if methodDesc == nil {
return status.Errorf(codes.Unimplemented, "unimplemented mock for method: %s", fullMethodName)
}
inputJS, err := readInput(stream, methodDesc, mockSrv.logger)
if err != nil {
mockSrv.logger.Error(fmt.Errorf("input message json marshaling: %w", err))
return err
}
mockSrv.logger.Debugw("matching request", "req", string(inputJS))
mock, err := mockSrv.matcher.Match(fullMethodName, inputJS)
if err != nil {
if errors.Is(err, dittomock.ErrNotMatched) {
mockSrv.logger.Warn("no match found")
} else {
mockSrv.logger.Error(err)
}
return status.Errorf(codes.Unimplemented, "unimplemented mock for method: %s", fullMethodName)
}
for _, resp := range mock.Response {
if resp.Status != nil {
return status.Error(resp.Status.Code, resp.Status.Message)
}
output := dynamic.NewMessage(methodDesc.GetOutputType())
err = output.UnmarshalJSON(resp.Body)
if err != nil {
mockSrv.logger.Error(err)
return err
}
err = stream.SendMsg(output)
if err != nil {
return err
}
}
return nil
}
func readInput(stream grpc.ServerStream, methodDesc *desc.MethodDescriptor, log logger.Logger) ([]byte, error) {
inputType := methodDesc.GetInputType()
log.Debugw("read input", "type", inputType.GetFullyQualifiedName(), "client_stream", methodDesc.IsClientStreaming())
// for loop supports both client streaming and unary messages
// io.EOF means it's the last message on the stream
var inMessages []json.RawMessage
for {
in := dynamic.NewMessage(inputType)
err := stream.RecvMsg(in)
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
js, err := in.MarshalJSONPB(&jsonpb.Marshaler{OrigName: true, EmitDefaults: true})
if err != nil {
return nil, status.Errorf(codes.Unknown, "input message json marshaling: %s", err)
}
inMessages = append(inMessages, js)
}
var inputJS []byte
if methodDesc.IsClientStreaming() {
res, err := json.Marshal(inMessages)
if err != nil {
return nil, err
}
inputJS = res
} else {
inputJS = inMessages[0]
}
return inputJS, nil
}
func healthCheckFileDescriptor() (*desc.FileDescriptor, error) {
return findFileDescriptor("grpc/health/v1/health.proto")
}
func findFileDescriptor(name string) (*desc.FileDescriptor, error) {
fileDesc, err := protoregistry.GlobalFiles.FindFileByPath(name)
if err != nil {
return nil, fmt.Errorf("%s: %w", name, err)
}
fdproto := protodesc.ToFileDescriptorProto(fileDesc)
return desc.CreateFileDescriptor(fdproto)
}