-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
template.go
1495 lines (1390 loc) · 47.6 KB
/
template.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package genswagger
import (
"fmt"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"github.com/golang/protobuf/proto"
pbdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
swagger_options "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"
)
var wktSchemas = map[string]schemaCore{
".google.protobuf.Timestamp": schemaCore{
Type: "string",
Format: "date-time",
},
".google.protobuf.Duration": schemaCore{
Type: "string",
},
".google.protobuf.StringValue": schemaCore{
Type: "string",
},
".google.protobuf.BytesValue": schemaCore{
Type: "string",
Format: "byte",
},
".google.protobuf.Int32Value": schemaCore{
Type: "integer",
Format: "int32",
},
".google.protobuf.UInt32Value": schemaCore{
Type: "integer",
Format: "int64",
},
".google.protobuf.Int64Value": schemaCore{
Type: "string",
Format: "int64",
},
".google.protobuf.UInt64Value": schemaCore{
Type: "string",
Format: "uint64",
},
".google.protobuf.FloatValue": schemaCore{
Type: "number",
Format: "float",
},
".google.protobuf.DoubleValue": schemaCore{
Type: "number",
Format: "double",
},
".google.protobuf.BoolValue": schemaCore{
Type: "boolean",
Format: "boolean",
},
}
func listEnumNames(enum *descriptor.Enum) (names []string) {
for _, value := range enum.GetValue() {
names = append(names, value.GetName())
}
return names
}
func getEnumDefault(enum *descriptor.Enum) string {
for _, value := range enum.GetValue() {
if value.GetNumber() == 0 {
return value.GetName()
}
}
return ""
}
// messageToQueryParameters converts a message to a list of swagger query parameters.
func messageToQueryParameters(message *descriptor.Message, reg *descriptor.Registry, pathParams []descriptor.Parameter) (params []swaggerParameterObject, err error) {
for _, field := range message.Fields {
p, err := queryParams(message, field, "", reg, pathParams)
if err != nil {
return nil, err
}
params = append(params, p...)
}
return params, nil
}
// queryParams converts a field to a list of swagger query parameters recuresively.
func queryParams(message *descriptor.Message, field *descriptor.Field, prefix string, reg *descriptor.Registry, pathParams []descriptor.Parameter) (params []swaggerParameterObject, err error) {
// make sure the parameter is not already listed as a path parameter
for _, pathParam := range pathParams {
if pathParam.Target == field {
return nil, nil
}
}
schema := schemaOfField(field, reg, nil)
fieldType := field.GetTypeName()
if message.File != nil {
comments := fieldProtoComments(reg, message, field)
if err := updateSwaggerDataFromComments(&schema, comments); err != nil {
return nil, err
}
}
isEnum := field.GetType() == pbdescriptor.FieldDescriptorProto_TYPE_ENUM
items := schema.Items
if schema.Type != "" || isEnum {
if schema.Type == "object" {
return nil, nil // TODO: currently, mapping object in query parameter is not supported
}
if items != nil && (items.Type == "" || items.Type == "object") && !isEnum {
return nil, nil // TODO: currently, mapping object in query parameter is not supported
}
desc := schema.Description
if schema.Title != "" { // merge title because title of parameter object will be ignored
desc = strings.TrimSpace(schema.Title + ". " + schema.Description)
}
param := swaggerParameterObject{
Name: prefix + field.GetName(),
Description: desc,
In: "query",
Type: schema.Type,
Items: schema.Items,
Format: schema.Format,
}
if isEnum {
enum, err := reg.LookupEnum("", fieldType)
if err != nil {
return nil, fmt.Errorf("unknown enum type %s", fieldType)
}
if items != nil { // array
param.Items = &swaggerItemsObject{
Type: "string",
Enum: listEnumNames(enum),
}
} else {
param.Type = "string"
param.Enum = listEnumNames(enum)
param.Default = getEnumDefault(enum)
}
valueComments := enumValueProtoComments(reg, enum)
if valueComments != "" {
param.Description = strings.TrimLeft(param.Description+"\n\n "+valueComments, "\n")
}
}
return []swaggerParameterObject{param}, nil
}
// nested type, recurse
msg, err := reg.LookupMsg("", fieldType)
if err != nil {
return nil, fmt.Errorf("unknown message type %s", fieldType)
}
for _, nestedField := range msg.Fields {
p, err := queryParams(msg, nestedField, prefix+field.GetName()+".", reg, pathParams)
if err != nil {
return nil, err
}
params = append(params, p...)
}
return params, nil
}
// findServicesMessagesAndEnumerations discovers all messages and enums defined in the RPC methods of the service.
func findServicesMessagesAndEnumerations(s []*descriptor.Service, reg *descriptor.Registry, m messageMap, e enumMap, refs refMap) {
for _, svc := range s {
for _, meth := range svc.Methods {
// Request may be fully included in query
if _, ok := refs[fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg))]; ok {
m[fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg)] = meth.RequestType
}
findNestedMessagesAndEnumerations(meth.RequestType, reg, m, e)
m[fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg)] = meth.ResponseType
findNestedMessagesAndEnumerations(meth.ResponseType, reg, m, e)
}
}
}
// findNestedMessagesAndEnumerations those can be generated by the services.
func findNestedMessagesAndEnumerations(message *descriptor.Message, reg *descriptor.Registry, m messageMap, e enumMap) {
// Iterate over all the fields that
for _, t := range message.Fields {
fieldType := t.GetTypeName()
// If the type is an empty string then it is a proto primitive
if fieldType != "" {
if _, ok := m[fieldType]; !ok {
msg, err := reg.LookupMsg("", fieldType)
if err != nil {
enum, err := reg.LookupEnum("", fieldType)
if err != nil {
panic(err)
}
e[fieldType] = enum
continue
}
m[fieldType] = msg
findNestedMessagesAndEnumerations(msg, reg, m, e)
}
}
}
}
func renderMessagesAsDefinition(messages messageMap, d swaggerDefinitionsObject, reg *descriptor.Registry, customRefs refMap) {
for name, msg := range messages {
switch name {
case ".google.protobuf.Timestamp":
continue
case ".google.protobuf.Duration":
continue
case ".google.protobuf.StringValue":
continue
case ".google.protobuf.BytesValue":
continue
case ".google.protobuf.Int32Value":
continue
case ".google.protobuf.UInt32Value":
continue
case ".google.protobuf.Int64Value":
continue
case ".google.protobuf.UInt64Value":
continue
case ".google.protobuf.FloatValue":
continue
case ".google.protobuf.DoubleValue":
continue
case ".google.protobuf.BoolValue":
continue
}
if opt := msg.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry {
continue
}
schema := swaggerSchemaObject{
schemaCore: schemaCore{
Type: "object",
},
}
msgComments := protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index))
if err := updateSwaggerDataFromComments(&schema, msgComments); err != nil {
panic(err)
}
opts, err := extractSchemaOptionFromMessageDescriptor(msg.DescriptorProto)
if err != nil {
panic(err)
}
if opts != nil {
protoSchema := swaggerSchemaFromProtoSchema(opts, reg, customRefs)
// Warning: Make sure not to overwrite any fields already set on the schema type.
schema.ExternalDocs = protoSchema.ExternalDocs
schema.MultipleOf = protoSchema.MultipleOf
schema.Maximum = protoSchema.Maximum
schema.ExclusiveMaximum = protoSchema.ExclusiveMaximum
schema.Minimum = protoSchema.Minimum
schema.ExclusiveMinimum = protoSchema.ExclusiveMinimum
schema.MaxLength = protoSchema.MaxLength
schema.MinLength = protoSchema.MinLength
schema.Pattern = protoSchema.Pattern
schema.MaxItems = protoSchema.MaxItems
schema.MinItems = protoSchema.MinItems
schema.UniqueItems = protoSchema.UniqueItems
schema.MaxProperties = protoSchema.MaxProperties
schema.MinProperties = protoSchema.MinProperties
schema.Required = protoSchema.Required
if protoSchema.schemaCore.Type != "" || protoSchema.schemaCore.Ref != "" {
schema.schemaCore = protoSchema.schemaCore
}
if protoSchema.Title != "" {
schema.Title = protoSchema.Title
}
if protoSchema.Description != "" {
schema.Description = protoSchema.Description
}
}
for _, f := range msg.Fields {
fieldValue := schemaOfField(f, reg, customRefs)
comments := fieldProtoComments(reg, msg, f)
if err := updateSwaggerDataFromComments(&fieldValue, comments); err != nil {
panic(err)
}
kv := keyVal{Value: fieldValue}
if reg.GetUseJSONNamesForFields() {
kv.Key = f.GetJsonName()
} else {
kv.Key = f.GetName()
}
schema.Properties = append(schema.Properties, kv)
}
d[fullyQualifiedNameToSwaggerName(msg.FQMN(), reg)] = schema
}
}
// schemaOfField returns a swagger Schema Object for a protobuf field.
func schemaOfField(f *descriptor.Field, reg *descriptor.Registry, refs refMap) swaggerSchemaObject {
const (
singular = 0
array = 1
object = 2
)
var (
core schemaCore
aggregate int
)
fd := f.FieldDescriptorProto
if m, err := reg.LookupMsg("", f.GetTypeName()); err == nil {
if opt := m.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry {
fd = m.GetField()[1]
aggregate = object
}
}
if fd.GetLabel() == pbdescriptor.FieldDescriptorProto_LABEL_REPEATED {
aggregate = array
}
switch ft := fd.GetType(); ft {
case pbdescriptor.FieldDescriptorProto_TYPE_ENUM, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE, pbdescriptor.FieldDescriptorProto_TYPE_GROUP:
if wktSchema, ok := wktSchemas[fd.GetTypeName()]; ok {
core = wktSchema
} else {
core = schemaCore{
Ref: "#/definitions/" + fullyQualifiedNameToSwaggerName(fd.GetTypeName(), reg),
}
if refs != nil {
refs[fd.GetTypeName()] = struct{}{}
}
}
default:
ftype, format, ok := primitiveSchema(ft)
if ok {
core = schemaCore{Type: ftype, Format: format}
} else {
core = schemaCore{Type: ft.String(), Format: "UNKNOWN"}
}
}
switch aggregate {
case array:
return swaggerSchemaObject{
schemaCore: schemaCore{
Type: "array",
Items: (*swaggerItemsObject)(&core),
},
}
case object:
return swaggerSchemaObject{
schemaCore: schemaCore{
Type: "object",
},
AdditionalProperties: &swaggerSchemaObject{schemaCore: core},
}
default:
ret := swaggerSchemaObject{
schemaCore: core,
}
if j, err := extractJSONSchemaFromFieldDescriptor(fd); err == nil {
updateSwaggerObjectFromJSONSchema(&ret, j)
}
return ret
}
}
// primitiveSchema returns a pair of "Type" and "Format" in JSON Schema for
// the given primitive field type.
// The last return parameter is true iff the field type is actually primitive.
func primitiveSchema(t pbdescriptor.FieldDescriptorProto_Type) (ftype, format string, ok bool) {
switch t {
case pbdescriptor.FieldDescriptorProto_TYPE_DOUBLE:
return "number", "double", true
case pbdescriptor.FieldDescriptorProto_TYPE_FLOAT:
return "number", "float", true
case pbdescriptor.FieldDescriptorProto_TYPE_INT64:
return "string", "int64", true
case pbdescriptor.FieldDescriptorProto_TYPE_UINT64:
// 64bit integer types are marshaled as string in the default JSONPb marshaler.
// TODO(yugui) Add an option to declare 64bit integers as int64.
//
// NOTE: uint64 is not a predefined format of integer type in Swagger spec.
// So we cannot expect that uint64 is commonly supported by swagger processor.
return "string", "uint64", true
case pbdescriptor.FieldDescriptorProto_TYPE_INT32:
return "integer", "int32", true
case pbdescriptor.FieldDescriptorProto_TYPE_FIXED64:
// Ditto.
return "string", "uint64", true
case pbdescriptor.FieldDescriptorProto_TYPE_FIXED32:
// Ditto.
return "integer", "int64", true
case pbdescriptor.FieldDescriptorProto_TYPE_BOOL:
return "boolean", "boolean", true
case pbdescriptor.FieldDescriptorProto_TYPE_STRING:
// NOTE: in swagger specifition, format should be empty on string type
return "string", "", true
case pbdescriptor.FieldDescriptorProto_TYPE_BYTES:
return "string", "byte", true
case pbdescriptor.FieldDescriptorProto_TYPE_UINT32:
// Ditto.
return "integer", "int64", true
case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED32:
return "integer", "int32", true
case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED64:
return "string", "int64", true
case pbdescriptor.FieldDescriptorProto_TYPE_SINT32:
return "integer", "int32", true
case pbdescriptor.FieldDescriptorProto_TYPE_SINT64:
return "string", "int64", true
default:
return "", "", false
}
}
// renderEnumerationsAsDefinition inserts enums into the definitions object.
func renderEnumerationsAsDefinition(enums enumMap, d swaggerDefinitionsObject, reg *descriptor.Registry) {
for _, enum := range enums {
enumComments := protoComments(reg, enum.File, enum.Outers, "EnumType", int32(enum.Index))
// it may be necessary to sort the result of the GetValue function.
enumNames := listEnumNames(enum)
defaultValue := getEnumDefault(enum)
valueComments := enumValueProtoComments(reg, enum)
if valueComments != "" {
enumComments = strings.TrimLeft(enumComments+"\n\n "+valueComments, "\n")
}
enumSchemaObject := swaggerSchemaObject{
schemaCore: schemaCore{
Type: "string",
Enum: enumNames,
Default: defaultValue,
},
}
if err := updateSwaggerDataFromComments(&enumSchemaObject, enumComments); err != nil {
panic(err)
}
d[fullyQualifiedNameToSwaggerName(enum.FQEN(), reg)] = enumSchemaObject
}
}
// Take in a FQMN or FQEN and return a swagger safe version of the FQMN
func fullyQualifiedNameToSwaggerName(fqn string, reg *descriptor.Registry) string {
registriesSeenMutex.Lock()
defer registriesSeenMutex.Unlock()
if mapping, present := registriesSeen[reg]; present {
return mapping[fqn]
}
mapping := resolveFullyQualifiedNameToSwaggerNames(append(reg.GetAllFQMNs(), reg.GetAllFQENs()...))
registriesSeen[reg] = mapping
return mapping[fqn]
}
// registriesSeen is used to memoise calls to resolveFullyQualifiedNameToSwaggerNames so
// we don't repeat it unnecessarily, since it can take some time.
var registriesSeen = map[*descriptor.Registry]map[string]string{}
var registriesSeenMutex sync.Mutex
// Take the names of every proto and "uniq-ify" them. The idea is to produce a
// set of names that meet a couple of conditions. They must be stable, they
// must be unique, and they must be shorter than the FQN.
//
// This likely could be made better. This will always generate the same names
// but may not always produce optimal names. This is a reasonably close
// approximation of what they should look like in most cases.
func resolveFullyQualifiedNameToSwaggerNames(messages []string) map[string]string {
packagesByDepth := make(map[int][][]string)
uniqueNames := make(map[string]string)
hierarchy := func(pkg string) []string {
return strings.Split(pkg, ".")
}
for _, p := range messages {
h := hierarchy(p)
for depth := range h {
if _, ok := packagesByDepth[depth]; !ok {
packagesByDepth[depth] = make([][]string, 0)
}
packagesByDepth[depth] = append(packagesByDepth[depth], h[len(h)-depth:])
}
}
count := func(list [][]string, item []string) int {
i := 0
for _, element := range list {
if reflect.DeepEqual(element, item) {
i++
}
}
return i
}
for _, p := range messages {
h := hierarchy(p)
for depth := 0; depth < len(h); depth++ {
if count(packagesByDepth[depth], h[len(h)-depth:]) == 1 {
uniqueNames[p] = strings.Join(h[len(h)-depth-1:], "")
break
}
if depth == len(h)-1 {
uniqueNames[p] = strings.Join(h, "")
}
}
}
return uniqueNames
}
// Swagger expects paths of the form /path/{string_value} but grpc-gateway paths are expected to be of the form /path/{string_value=strprefix/*}. This should reformat it correctly.
func templateToSwaggerPath(path string) string {
// It seems like the right thing to do here is to just use
// strings.Split(path, "/") but that breaks badly when you hit a url like
// /{my_field=prefix/*}/ and end up with 2 sections representing my_field.
// Instead do the right thing and write a small pushdown (counter) automata
// for it.
var parts []string
depth := 0
buffer := ""
for _, char := range path {
switch char {
case '{':
// Push on the stack
depth++
buffer += string(char)
break
case '}':
if depth == 0 {
panic("Encountered } without matching { before it.")
}
// Pop from the stack
depth--
buffer += string(char)
case '/':
if depth == 0 {
parts = append(parts, buffer)
buffer = ""
// Since the stack was empty when we hit the '/' we are done with this
// section.
continue
}
buffer += string(char)
default:
buffer += string(char)
break
}
}
// Now append the last element to parts
parts = append(parts, buffer)
// Parts is now an array of segments of the path. Interestingly, since the
// syntax for this subsection CAN be handled by a regexp since it has no
// memory.
re := regexp.MustCompile("{([a-zA-Z][a-zA-Z0-9_.]*).*}")
for index, part := range parts {
// If part is a resource name such as "parent", "name", "user.name", the format info must be retained.
prefix := re.ReplaceAllString(part, "$1")
if isResourceName(prefix) {
continue
}
parts[index] = re.ReplaceAllString(part, "{$1}")
}
return strings.Join(parts, "/")
}
func isResourceName(prefix string) bool {
words := strings.Split(prefix, ".")
l := len(words)
field := words[l-1]
return field == "parent" || field == "name"
}
func renderServices(services []*descriptor.Service, paths swaggerPathsObject, reg *descriptor.Registry, requestResponseRefs, customRefs refMap) error {
// Correctness of svcIdx and methIdx depends on 'services' containing the services in the same order as the 'file.Service' array.
for svcIdx, svc := range services {
for methIdx, meth := range svc.Methods {
for bIdx, b := range meth.Bindings {
// Iterate over all the swagger parameters
parameters := swaggerParametersObject{}
for _, parameter := range b.PathParams {
var paramType, paramFormat, desc, collectionFormat string
var enumNames []string
var items *swaggerItemsObject
var minItems *int
switch pt := parameter.Target.GetType(); pt {
case pbdescriptor.FieldDescriptorProto_TYPE_GROUP, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE:
if descriptor.IsWellKnownType(parameter.Target.GetTypeName()) {
if parameter.IsRepeated() {
return fmt.Errorf("only primitive and enum types are allowed in repeated path parameters")
}
schema := schemaOfField(parameter.Target, reg, customRefs)
paramType = schema.Type
paramFormat = schema.Format
desc = schema.Description
} else {
return fmt.Errorf("only primitive and well-known types are allowed in path parameters")
}
case pbdescriptor.FieldDescriptorProto_TYPE_ENUM:
paramType = "string"
paramFormat = ""
enum, err := reg.LookupEnum("", parameter.Target.GetTypeName())
if err != nil {
return err
}
enumNames = listEnumNames(enum)
default:
var ok bool
paramType, paramFormat, ok = primitiveSchema(pt)
if !ok {
return fmt.Errorf("unknown field type %v", pt)
}
}
if parameter.IsRepeated() {
core := schemaCore{Type: paramType, Format: paramFormat}
if parameter.IsEnum() {
var s []string
core.Enum = enumNames
enumNames = s
}
items = (*swaggerItemsObject)(&core)
paramType = "array"
paramFormat = ""
collectionFormat = reg.GetRepeatedPathParamSeparatorName()
minItems = new(int)
*minItems = 1
}
if desc == "" {
desc = fieldProtoComments(reg, parameter.Target.Message, parameter.Target)
}
parameters = append(parameters, swaggerParameterObject{
Name: parameter.String(),
Description: desc,
In: "path",
Required: true,
// Parameters in gRPC-Gateway can only be strings?
Type: paramType,
Format: paramFormat,
Enum: enumNames,
Items: items,
CollectionFormat: collectionFormat,
MinItems: minItems,
})
}
// Now check if there is a body parameter
if b.Body != nil {
var schema swaggerSchemaObject
desc := ""
if len(b.Body.FieldPath) == 0 {
schema = swaggerSchemaObject{
schemaCore: schemaCore{
Ref: fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg)),
},
}
} else {
lastField := b.Body.FieldPath[len(b.Body.FieldPath)-1]
schema = schemaOfField(lastField.Target, reg, customRefs)
if schema.Description != "" {
desc = schema.Description
} else {
desc = fieldProtoComments(reg, lastField.Target.Message, lastField.Target)
}
}
if meth.GetClientStreaming() {
desc += " (streaming inputs)"
}
parameters = append(parameters, swaggerParameterObject{
Name: "body",
Description: desc,
In: "body",
Required: true,
Schema: &schema,
})
} else if b.HTTPMethod == "GET" || b.HTTPMethod == "DELETE" {
// add the parameters to the query string
queryParams, err := messageToQueryParameters(meth.RequestType, reg, b.PathParams)
if err != nil {
return err
}
parameters = append(parameters, queryParams...)
}
pathItemObject, ok := paths[templateToSwaggerPath(b.PathTmpl.Template)]
if !ok {
pathItemObject = swaggerPathItemObject{}
}
methProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.ServiceDescriptorProto)(nil)), "Method")
desc := ""
var responseSchema swaggerSchemaObject
if b.ResponseBody == nil || len(b.ResponseBody.FieldPath) == 0 {
responseSchema = swaggerSchemaObject{
schemaCore: schemaCore{
Ref: fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg)),
},
}
} else {
// This is resolving the value of response_body in the google.api.HttpRule
lastField := b.ResponseBody.FieldPath[len(b.ResponseBody.FieldPath)-1]
responseSchema = schemaOfField(lastField.Target, reg, customRefs)
if responseSchema.Description != "" {
desc = responseSchema.Description
} else {
desc = fieldProtoComments(reg, lastField.Target.Message, lastField.Target)
}
}
if meth.GetServerStreaming() {
desc += "(streaming responses)"
}
operationObject := &swaggerOperationObject{
Tags: []string{svc.GetName()},
Parameters: parameters,
Responses: swaggerResponsesObject{
"200": swaggerResponseObject{
Description: desc,
Schema: responseSchema,
},
},
}
if bIdx == 0 {
operationObject.OperationID = fmt.Sprintf("%s", meth.GetName())
} else {
// OperationID must be unique in an OpenAPI v2 definition.
operationObject.OperationID = fmt.Sprintf("%s%d", meth.GetName(), bIdx+1)
}
// Fill reference map with referenced request messages
for _, param := range operationObject.Parameters {
if param.Schema != nil && param.Schema.Ref != "" {
requestResponseRefs[param.Schema.Ref] = struct{}{}
}
}
methComments := protoComments(reg, svc.File, nil, "Method", int32(svcIdx), methProtoPath, int32(methIdx))
if err := updateSwaggerDataFromComments(operationObject, methComments); err != nil {
panic(err)
}
opts, err := extractOperationOptionFromMethodDescriptor(meth.MethodDescriptorProto)
if opts != nil {
if err != nil {
panic(err)
}
operationObject.ExternalDocs = protoExternalDocumentationToSwaggerExternalDocumentation(opts.ExternalDocs)
// TODO(ivucica): this would be better supported by looking whether the method is deprecated in the proto file
operationObject.Deprecated = opts.Deprecated
if opts.Summary != "" {
operationObject.Summary = opts.Summary
}
if opts.Description != "" {
operationObject.Description = opts.Description
}
if len(opts.Tags) > 0 {
operationObject.Tags = make([]string, len(opts.Tags))
copy(operationObject.Tags, opts.Tags)
}
if opts.Security != nil {
newSecurity := []swaggerSecurityRequirementObject{}
if operationObject.Security != nil {
newSecurity = *operationObject.Security
}
for _, secReq := range opts.Security {
newSecReq := swaggerSecurityRequirementObject{}
for secReqKey, secReqValue := range secReq.SecurityRequirement {
if secReqValue == nil {
continue
}
newSecReqValue := make([]string, len(secReqValue.Scope))
copy(newSecReqValue, secReqValue.Scope)
newSecReq[secReqKey] = newSecReqValue
}
if len(newSecReq) > 0 {
newSecurity = append(newSecurity, newSecReq)
}
}
operationObject.Security = &newSecurity
}
if opts.Responses != nil {
for name, resp := range opts.Responses {
operationObject.Responses[name] = swaggerResponseObject{
Description: resp.Description,
Schema: swaggerSchemaFromProtoSchema(resp.Schema, reg, customRefs),
}
}
}
// TODO(ivucica): add remaining fields of operation object
}
switch b.HTTPMethod {
case "DELETE":
pathItemObject.Delete = operationObject
break
case "GET":
pathItemObject.Get = operationObject
break
case "POST":
pathItemObject.Post = operationObject
break
case "PUT":
pathItemObject.Put = operationObject
break
case "PATCH":
pathItemObject.Patch = operationObject
break
}
paths[templateToSwaggerPath(b.PathTmpl.Template)] = pathItemObject
}
}
}
// Success! return nil on the error object
return nil
}
// This function is called with a param which contains the entire definition of a method.
func applyTemplate(p param) (*swaggerObject, error) {
// Create the basic template object. This is the object that everything is
// defined off of.
s := swaggerObject{
// Swagger 2.0 is the version of this document
Swagger: "2.0",
Schemes: []string{"http", "https"},
Consumes: []string{"application/json"},
Produces: []string{"application/json"},
Paths: make(swaggerPathsObject),
Definitions: make(swaggerDefinitionsObject),
Info: swaggerInfoObject{
Title: *p.File.Name,
Version: "version not set",
},
}
// Loops through all the services and their exposed GET/POST/PUT/DELETE definitions
// and create entries for all of them.
// Also adds custom user specified references to second map.
requestResponseRefs, customRefs := refMap{}, refMap{}
if err := renderServices(p.Services, s.Paths, p.reg, requestResponseRefs, customRefs); err != nil {
panic(err)
}
// Find all the service's messages and enumerations that are defined (recursively)
// and write request, response and other custom (but referenced) types out as definition objects.
m := messageMap{}
e := enumMap{}
findServicesMessagesAndEnumerations(p.Services, p.reg, m, e, requestResponseRefs)
renderMessagesAsDefinition(m, s.Definitions, p.reg, customRefs)
renderEnumerationsAsDefinition(e, s.Definitions, p.reg)
// File itself might have some comments and metadata.
packageProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package")
packageComments := protoComments(p.reg, p.File, nil, "Package", packageProtoPath)
if err := updateSwaggerDataFromComments(&s, packageComments); err != nil {
panic(err)
}
// There may be additional options in the swagger option in the proto.
spb, err := extractSwaggerOptionFromFileDescriptor(p.FileDescriptorProto)
if err != nil {
panic(err)
}
if spb != nil {
if spb.Swagger != "" {
s.Swagger = spb.Swagger
}
if spb.Info != nil {
if spb.Info.Title != "" {
s.Info.Title = spb.Info.Title
}
if spb.Info.Description != "" {
s.Info.Description = spb.Info.Description
}
if spb.Info.TermsOfService != "" {
s.Info.TermsOfService = spb.Info.TermsOfService
}
if spb.Info.Version != "" {
s.Info.Version = spb.Info.Version
}
if spb.Info.Contact != nil {
if s.Info.Contact == nil {
s.Info.Contact = &swaggerContactObject{}
}
if spb.Info.Contact.Name != "" {
s.Info.Contact.Name = spb.Info.Contact.Name
}
if spb.Info.Contact.Url != "" {
s.Info.Contact.URL = spb.Info.Contact.Url
}
if spb.Info.Contact.Email != "" {
s.Info.Contact.Email = spb.Info.Contact.Email
}
}
}
if spb.Host != "" {
s.Host = spb.Host
}
if spb.BasePath != "" {
s.BasePath = spb.BasePath
}
if len(spb.Schemes) > 0 {
s.Schemes = make([]string, len(spb.Schemes))
for i, scheme := range spb.Schemes {
s.Schemes[i] = strings.ToLower(scheme.String())
}
}
if len(spb.Consumes) > 0 {
s.Consumes = make([]string, len(spb.Consumes))
copy(s.Consumes, spb.Consumes)
}
if len(spb.Produces) > 0 {
s.Produces = make([]string, len(spb.Produces))
copy(s.Produces, spb.Produces)
}
if spb.SecurityDefinitions != nil && spb.SecurityDefinitions.Security != nil {
if s.SecurityDefinitions == nil {
s.SecurityDefinitions = swaggerSecurityDefinitionsObject{}
}
for secDefKey, secDefValue := range spb.SecurityDefinitions.Security {
var newSecDefValue swaggerSecuritySchemeObject
if oldSecDefValue, ok := s.SecurityDefinitions[secDefKey]; !ok {
newSecDefValue = swaggerSecuritySchemeObject{}
} else {
newSecDefValue = oldSecDefValue
}
if secDefValue.Type != swagger_options.SecurityScheme_TYPE_INVALID {
switch secDefValue.Type {
case swagger_options.SecurityScheme_TYPE_BASIC:
newSecDefValue.Type = "basic"
case swagger_options.SecurityScheme_TYPE_API_KEY:
newSecDefValue.Type = "apiKey"
case swagger_options.SecurityScheme_TYPE_OAUTH2:
newSecDefValue.Type = "oauth2"
}
}
if secDefValue.Description != "" {
newSecDefValue.Description = secDefValue.Description
}
if secDefValue.Name != "" {
newSecDefValue.Name = secDefValue.Name
}
if secDefValue.In != swagger_options.SecurityScheme_IN_INVALID {
switch secDefValue.In {
case swagger_options.SecurityScheme_IN_QUERY:
newSecDefValue.In = "query"
case swagger_options.SecurityScheme_IN_HEADER:
newSecDefValue.In = "header"
}
}
if secDefValue.Flow != swagger_options.SecurityScheme_FLOW_INVALID {
switch secDefValue.Flow {
case swagger_options.SecurityScheme_FLOW_IMPLICIT:
newSecDefValue.Flow = "implicit"
case swagger_options.SecurityScheme_FLOW_PASSWORD:
newSecDefValue.Flow = "password"
case swagger_options.SecurityScheme_FLOW_APPLICATION:
newSecDefValue.Flow = "application"
case swagger_options.SecurityScheme_FLOW_ACCESS_CODE:
newSecDefValue.Flow = "accessCode"
}
}
if secDefValue.AuthorizationUrl != "" {
newSecDefValue.AuthorizationURL = secDefValue.AuthorizationUrl
}
if secDefValue.TokenUrl != "" {
newSecDefValue.TokenURL = secDefValue.TokenUrl
}
if secDefValue.Scopes != nil {
if newSecDefValue.Scopes == nil {
newSecDefValue.Scopes = swaggerScopesObject{}
}
for scopeKey, scopeDesc := range secDefValue.Scopes.Scope {
newSecDefValue.Scopes[scopeKey] = scopeDesc
}
}
s.SecurityDefinitions[secDefKey] = newSecDefValue
}
}
if spb.Security != nil {
newSecurity := []swaggerSecurityRequirementObject{}
if s.Security == nil {
newSecurity = []swaggerSecurityRequirementObject{}
} else {
newSecurity = s.Security
}
for _, secReq := range spb.Security {
newSecReq := swaggerSecurityRequirementObject{}
for secReqKey, secReqValue := range secReq.SecurityRequirement {
newSecReqValue := make([]string, len(secReqValue.Scope))