forked from fullstorydev/grpcui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
504 lines (441 loc) · 14.5 KB
/
handlers.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
package grpcui
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/dynamic/grpcdynamic"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/fullstorydev/grpcurl"
)
// RPCInvokeHandler returns an HTTP handler that can be used to invoke RPCs. The
// request includes request data, header metadata, and an optional timeout.
//
// The handler accepts POST requests with JSON bodies and returns a JSON payload
// in response. The URI path should name an RPC method ("/service/method"). The
// format of the request and response bodies matches the formats sent and
// expected by the JavaScript client code embedded in WebFormContents.
//
// The returned handler expects to serve "/". If it will instead be handling a
// sub-path (e.g. handling "/rpc/invoke/") then use http.StripPrefix.
//
// Note that the returned handler does not implement any CSRF protection. To
// provide that, you will need to wrap the returned handler with one that first
// enforces CSRF checks.
func RPCInvokeHandler(ch grpcdynamic.Channel, descs []*desc.MethodDescriptor) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.Header().Set("Allow", "POST")
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "Request must be JSON", http.StatusUnsupportedMediaType)
return
}
method := r.URL.Path
if method[0] == '/' {
method = method[1:]
}
for _, md := range descs {
if md.GetFullyQualifiedName() == method {
descSource, err := grpcurl.DescriptorSourceFromFileDescriptors(md.GetFile())
if err != nil {
http.Error(w, "Failed to create descriptor source: "+err.Error(), http.StatusInternalServerError)
return
}
results, err := invokeRPC(r.Context(), method, ch, descSource, r.Body)
if err != nil {
if _, ok := err.(errReadFail); ok {
http.Error(w, "Failed to read request", 499)
return
}
if _, ok := err.(errBadInput); ok {
http.Error(w, "Failed to parse JSON: "+err.Error(), http.StatusBadRequest)
return
}
http.Error(w, "Unexpected error: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
enc.Encode(results)
return
}
}
http.NotFound(w, r)
})
}
// RPCMetadataHandler returns an HTTP handler that can be used to get metadata
// for a specified method.
//
// The handler accepts GET requests, using a query parameter to indicate the
// method whose schema metadata should be fetched. The response payload will be
// JSON. The format of the response body matches the format expected by the
// JavaScript client code embedded in WebFormContents.
func RPCMetadataHandler(methods []*desc.MethodDescriptor, files []*desc.FileDescriptor) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.Header().Set("Allow", "GET")
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
method := r.URL.Query().Get("method")
var results *schema
if method == "*" {
// This means gather *all* message types. This is used to
// provide a drop-down for Any messages.
results = gatherAllMessageMetadata(files)
} else {
for _, md := range methods {
if md.GetFullyQualifiedName() == method {
results = gatherMetadata(md)
break
}
}
}
if results == nil {
http.Error(w, "Unknown RPC Method", http.StatusUnprocessableEntity)
return
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
// TODO: what if enc.Encode returns a non-I/O error?
enc.Encode(results)
})
}
type schema struct {
RequestType string `json:"requestType"`
RequestStream bool `json:"requestStream"`
MessageTypes map[string][]fieldDef `json:"messageTypes"`
EnumTypes map[string][]string `json:"enumTypes"`
}
type fieldDef struct {
Name string `json:"name"`
Type fieldType `json:"type"`
OneOfFields []fieldDef `json:"oneOfFields"`
IsMessage bool `json:"isMessage"`
IsEnum bool `json:"isEnum"`
IsArray bool `json:"isArray"`
IsMap bool `json:"isMap"`
IsRequired bool `json:"isRequired"`
DefaultVal interface{} `json:"defaultVal"`
}
type fieldType string
const (
typeString fieldType = "string"
typeBytes fieldType = "bytes"
typeInt32 fieldType = "int32"
typeInt64 fieldType = "int64"
typeSint32 fieldType = "sint32"
typeSint64 fieldType = "sint64"
typeUint32 fieldType = "uint32"
typeUint64 fieldType = "uint64"
typeFixed32 fieldType = "fixed32"
typeFixed64 fieldType = "fixed64"
typeSfixed32 fieldType = "sfixed32"
typeSfixed64 fieldType = "sfixed64"
typeFloat fieldType = "float"
typeDouble fieldType = "double"
typeBool fieldType = "bool"
typeOneOf fieldType = "oneof"
)
var typeMap = map[descriptor.FieldDescriptorProto_Type]fieldType{
descriptor.FieldDescriptorProto_TYPE_STRING: typeString,
descriptor.FieldDescriptorProto_TYPE_BYTES: typeBytes,
descriptor.FieldDescriptorProto_TYPE_INT32: typeInt32,
descriptor.FieldDescriptorProto_TYPE_INT64: typeInt64,
descriptor.FieldDescriptorProto_TYPE_SINT32: typeSint32,
descriptor.FieldDescriptorProto_TYPE_SINT64: typeSint64,
descriptor.FieldDescriptorProto_TYPE_UINT32: typeUint32,
descriptor.FieldDescriptorProto_TYPE_UINT64: typeUint64,
descriptor.FieldDescriptorProto_TYPE_FIXED32: typeFixed32,
descriptor.FieldDescriptorProto_TYPE_FIXED64: typeFixed64,
descriptor.FieldDescriptorProto_TYPE_SFIXED32: typeSfixed32,
descriptor.FieldDescriptorProto_TYPE_SFIXED64: typeSfixed64,
descriptor.FieldDescriptorProto_TYPE_FLOAT: typeFloat,
descriptor.FieldDescriptorProto_TYPE_DOUBLE: typeDouble,
descriptor.FieldDescriptorProto_TYPE_BOOL: typeBool,
}
func gatherAllMessageMetadata(files []*desc.FileDescriptor) *schema {
result := &schema{
MessageTypes: map[string][]fieldDef{},
EnumTypes: map[string][]string{},
}
for _, fd := range files {
gatherAllMessages(fd.GetMessageTypes(), result)
}
return result
}
func gatherAllMessages(msgs []*desc.MessageDescriptor, result *schema) {
for _, md := range msgs {
result.visitMessage(md)
gatherAllMessages(md.GetNestedMessageTypes(), result)
}
}
func gatherMetadata(md *desc.MethodDescriptor) *schema {
msg := md.GetInputType()
result := &schema{
RequestType: msg.GetFullyQualifiedName(),
RequestStream: md.IsClientStreaming(),
MessageTypes: map[string][]fieldDef{},
EnumTypes: map[string][]string{},
}
result.visitMessage(msg)
return result
}
func (s *schema) visitMessage(md *desc.MessageDescriptor) {
if _, ok := s.MessageTypes[md.GetFullyQualifiedName()]; ok {
// already visited
return
}
fields := make([]fieldDef, 0, len(md.GetFields()))
s.MessageTypes[md.GetFullyQualifiedName()] = fields
oneOfsSeen := map[*desc.OneOfDescriptor]struct{}{}
for _, fd := range md.GetFields() {
ood := fd.GetOneOf()
if ood != nil {
if _, ok := oneOfsSeen[ood]; ok {
// already processed this one
continue
}
oneOfsSeen[ood] = struct{}{}
fields = append(fields, s.processOneOf(ood))
} else {
fields = append(fields, s.processField(fd))
}
}
s.MessageTypes[md.GetFullyQualifiedName()] = fields
}
func (s *schema) processField(fd *desc.FieldDescriptor) fieldDef {
def := fieldDef{
Name: fd.GetName(),
IsEnum: fd.GetEnumType() != nil,
IsMessage: fd.GetMessageType() != nil,
IsArray: fd.IsRepeated() && !fd.IsMap(),
IsMap: fd.IsMap(),
IsRequired: fd.IsRequired(),
DefaultVal: fd.GetDefaultValue(),
}
if def.IsMap {
// fd.GetDefaultValue returns empty map[interface{}]interface{}
// as the default for map fields, but "encoding/json" refuses
// to encode a map with interface{} keys (even if it's empty).
// So we fix up the key type here.
def.DefaultVal = map[string]interface{}{}
}
// 64-bit int values are represented as strings in JSON
if i, ok := def.DefaultVal.(int64); ok {
def.DefaultVal = fmt.Sprintf("%d", i)
} else if u, ok := def.DefaultVal.(uint64); ok {
def.DefaultVal = fmt.Sprintf("%d", u)
} else if b, ok := def.DefaultVal.([]byte); ok && b == nil {
// bytes fields may have []byte(nil) as default value, but
// that gets rendered as JSON null, not empty array
def.DefaultVal = []byte{}
}
switch fd.GetType() {
case descriptor.FieldDescriptorProto_TYPE_ENUM:
def.Type = fieldType(fd.GetEnumType().GetFullyQualifiedName())
s.visitEnum(fd.GetEnumType())
// DefaultVal will be int32 for enums, but we want to instead
// send enum name as string
if val, ok := def.DefaultVal.(int32); ok {
valDesc := fd.GetEnumType().FindValueByNumber(val)
if valDesc != nil {
def.DefaultVal = valDesc.GetName()
}
}
case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE:
def.Type = fieldType(fd.GetMessageType().GetFullyQualifiedName())
s.visitMessage(fd.GetMessageType())
default:
def.Type = typeMap[fd.GetType()]
}
return def
}
func (s *schema) processOneOf(ood *desc.OneOfDescriptor) fieldDef {
choices := make([]fieldDef, len(ood.GetChoices()))
for i, fd := range ood.GetChoices() {
choices[i] = s.processField(fd)
}
return fieldDef{
Name: ood.GetName(),
Type: typeOneOf,
OneOfFields: choices,
}
}
func (s *schema) visitEnum(ed *desc.EnumDescriptor) {
if _, ok := s.EnumTypes[ed.GetFullyQualifiedName()]; ok {
// already visited
return
}
enumVals := make([]string, len(ed.GetValues()))
for i, evd := range ed.GetValues() {
enumVals[i] = evd.GetName()
}
s.EnumTypes[ed.GetFullyQualifiedName()] = enumVals
}
type errBadInput struct {
err error
}
func (e errBadInput) Error() string {
return e.err.Error()
}
type errReadFail struct {
err error
}
func (e errReadFail) Error() string {
return e.err.Error()
}
func invokeRPC(ctx context.Context, methodName string, ch grpcdynamic.Channel, descSource grpcurl.DescriptorSource, body io.Reader) (*rpcResult, error) {
js, err := ioutil.ReadAll(body)
if err != nil {
return nil, errReadFail{err: err}
}
var input rpcInput
if err := json.Unmarshal(js, &input); err != nil {
return nil, errBadInput{err: err}
}
reqStats := rpcRequestStats{
Total: len(input.Data),
}
requestFunc := func(m proto.Message) error {
if len(input.Data) == 0 {
return io.EOF
}
reqStats.Sent++
req := input.Data[0]
input.Data = input.Data[1:]
if err := jsonpb.Unmarshal(bytes.NewReader([]byte(req)), m); err != nil {
return status.Errorf(codes.InvalidArgument, err.Error())
}
return nil
}
hdrs := make([]string, len(input.Metadata))
for i, hdr := range input.Metadata {
hdrs[i] = fmt.Sprintf("%s: %s", hdr.Name, hdr.Value)
}
if input.TimeoutSeconds > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, time.Duration(input.TimeoutSeconds)*time.Second)
defer cancel()
}
result := rpcResult{
descSource: descSource,
Requests: &reqStats,
}
if err := grpcurl.InvokeRPC(ctx, descSource, ch, methodName, hdrs, &result, requestFunc); err != nil {
return nil, err
}
return &result, nil
}
type rpcMetadata struct {
Name string `json:"name"`
Value string `json:"value"`
}
type rpcInput struct {
TimeoutSeconds int `json:"timeout_seconds"`
Metadata []rpcMetadata `json:"metadata"`
Data []json.RawMessage `json:"data"`
}
type rpcResponseElement struct {
Data json.RawMessage `json:"message"`
IsError bool `json:"isError"`
}
type rpcRequestStats struct {
Total int `json:"total"`
Sent int `json:"sent"`
}
type rpcError struct {
Code uint32 `json:"code"`
Name string `json:"name"`
Message string `json:"message"`
Details []rpcResponseElement `json:"details"`
}
type rpcResult struct {
descSource grpcurl.DescriptorSource
Headers []rpcMetadata `json:"headers"`
Error *rpcError `json:"error"`
Responses []rpcResponseElement `json:"responses"`
Requests *rpcRequestStats `json:"requests"`
Trailers []rpcMetadata `json:"trailers"`
}
func (*rpcResult) OnResolveMethod(*desc.MethodDescriptor) {}
func (*rpcResult) OnSendHeaders(metadata.MD) {}
func (r *rpcResult) OnReceiveHeaders(md metadata.MD) {
r.Headers = responseMetadata(md)
}
func (r *rpcResult) OnReceiveResponse(m proto.Message) {
r.Responses = append(r.Responses, responseToJSON(r.descSource, m))
}
func (r *rpcResult) OnReceiveTrailers(stat *status.Status, md metadata.MD) {
r.Trailers = responseMetadata(md)
r.Error = toRpcError(r.descSource, stat)
}
func responseMetadata(md metadata.MD) []rpcMetadata {
keys := make([]string, 0, len(md))
for k := range md {
keys = append(keys, k)
}
sort.Strings(keys)
ret := make([]rpcMetadata, 0, len(md))
for _, k := range keys {
vals := md[k]
for _, v := range vals {
if strings.HasSuffix(k, "-bin") {
v = base64.StdEncoding.EncodeToString([]byte(v))
}
ret = append(ret, rpcMetadata{Name: k, Value: v})
}
}
return ret
}
func toRpcError(descSource grpcurl.DescriptorSource, stat *status.Status) *rpcError {
if stat.Code() == codes.OK {
return nil
}
details := stat.Proto().Details
msgs := make([]rpcResponseElement, len(details))
for i, d := range details {
msgs[i] = responseToJSON(descSource, d)
}
return &rpcError{
Code: uint32(stat.Code()),
Name: stat.Code().String(),
Message: stat.Message(),
Details: msgs,
}
}
func responseToJSON(descSource grpcurl.DescriptorSource, msg proto.Message) rpcResponseElement {
anyResolver := grpcurl.AnyResolverFromDescriptorSourceWithFallback(descSource)
jsm := jsonpb.Marshaler{EmitDefaults: true, OrigName: true, Indent: " ", AnyResolver: anyResolver}
var b bytes.Buffer
if err := jsm.Marshal(&b, msg); err == nil {
return rpcResponseElement{Data: json.RawMessage(b.Bytes())}
} else {
b, err := json.Marshal(err.Error())
if err != nil {
// unable to marshal err message to JSON?
// should never happen... here's a dumb fallback
b = []byte(strconv.Quote(err.Error()))
}
return rpcResponseElement{Data: json.RawMessage(b), IsError: true}
}
}