-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
template.go
3034 lines (2806 loc) · 98.8 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 genopenapi
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"net/textproto"
"os"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/v2/internal/casing"
"github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor"
openapi_options "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/options"
"google.golang.org/genproto/googleapis/api/annotations"
"google.golang.org/genproto/googleapis/api/visibility"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/known/structpb"
)
// The OpenAPI specification does not allow for more than one endpoint with the same HTTP method and path.
// This prevents multiple gRPC service methods from sharing the same stripped version of the path and method.
// For example: `GET /v1/{name=organizations/*}/roles` and `GET /v1/{name=users/*}/roles` both get stripped to `GET /v1/{name}/roles`.
// We must make the URL unique by adding a suffix and an incrementing index to each path parameter
// to differentiate the endpoints.
// Since path parameter names do not affect the request contents (i.e. they're replaced in the path)
// this will be hidden from the real grpc gateway consumer.
const pathParamUniqueSuffixDeliminator = "_"
const paragraphDeliminator = "\n\n"
// wktSchemas are the schemas of well-known-types.
// The schemas must match with the behavior of the JSON unmarshaler in
// https://github.com/protocolbuffers/protobuf-go/blob/v1.25.0/encoding/protojson/well_known_types.go
var wktSchemas = map[string]schemaCore{
".google.protobuf.FieldMask": {
Type: "string",
},
".google.protobuf.Timestamp": {
Type: "string",
Format: "date-time",
},
".google.protobuf.Duration": {
Type: "string",
},
".google.protobuf.StringValue": {
Type: "string",
},
".google.protobuf.BytesValue": {
Type: "string",
Format: "byte",
},
".google.protobuf.Int32Value": {
Type: "integer",
Format: "int32",
},
".google.protobuf.UInt32Value": {
Type: "integer",
Format: "int64",
},
".google.protobuf.Int64Value": {
Type: "string",
Format: "int64",
},
".google.protobuf.UInt64Value": {
Type: "string",
Format: "uint64",
},
".google.protobuf.FloatValue": {
Type: "number",
Format: "float",
},
".google.protobuf.DoubleValue": {
Type: "number",
Format: "double",
},
".google.protobuf.BoolValue": {
Type: "boolean",
},
".google.protobuf.Empty": {
Type: "object",
},
".google.protobuf.Struct": {
Type: "object",
},
".google.protobuf.Value": {},
".google.protobuf.ListValue": {
Type: "array",
Items: (*openapiItemsObject)(&openapiSchemaObject{
schemaCore: schemaCore{
Type: "object",
}}),
},
".google.protobuf.NullValue": {
Type: "string",
},
}
func listEnumNames(reg *descriptor.Registry, enum *descriptor.Enum) (names []string) {
for _, value := range enum.GetValue() {
if !isVisible(getEnumValueVisibilityOption(value), reg) {
continue
}
if reg.GetOmitEnumDefaultValue() && value.GetNumber() == 0 {
continue
}
names = append(names, value.GetName())
}
if len(names) > 0 {
return names
}
return nil
}
func listEnumNumbers(reg *descriptor.Registry, enum *descriptor.Enum) (numbers []int) {
for _, value := range enum.GetValue() {
if reg.GetOmitEnumDefaultValue() && value.GetNumber() == 0 {
continue
}
if !isVisible(getEnumValueVisibilityOption(value), reg) {
continue
}
numbers = append(numbers, int(value.GetNumber()))
}
if len(numbers) > 0 {
return numbers
}
return nil
}
func getEnumDefault(reg *descriptor.Registry, enum *descriptor.Enum) interface{} {
if !reg.GetOmitEnumDefaultValue() {
for _, value := range enum.GetValue() {
if value.GetNumber() == 0 {
return value.GetName()
}
}
}
return nil
}
func getEnumDefaultNumber(reg *descriptor.Registry, enum *descriptor.Enum) interface{} {
if !reg.GetOmitEnumDefaultValue() {
for _, value := range enum.GetValue() {
if value.GetNumber() == 0 {
return int(value.GetNumber())
}
}
}
return nil
}
// messageToQueryParameters converts a message to a list of OpenAPI query parameters.
func messageToQueryParameters(message *descriptor.Message, reg *descriptor.Registry, pathParams []descriptor.Parameter, body *descriptor.Body, httpMethod string) (params []openapiParameterObject, err error) {
for _, field := range message.Fields {
if !isVisible(getFieldVisibilityOption(field), reg) {
continue
}
if reg.GetAllowPatchFeature() && field.GetTypeName() == ".google.protobuf.FieldMask" && field.GetName() == "update_mask" && httpMethod == "PATCH" && len(body.FieldPath) != 0 {
continue
}
p, err := queryParams(message, field, "", reg, pathParams, body, reg.GetRecursiveDepth())
if err != nil {
return nil, err
}
params = append(params, p...)
}
return params, nil
}
// queryParams converts a field to a list of OpenAPI query parameters recursively through the use of nestedQueryParams.
func queryParams(message *descriptor.Message, field *descriptor.Field, prefix string, reg *descriptor.Registry, pathParams []descriptor.Parameter, body *descriptor.Body, recursiveCount int) (params []openapiParameterObject, err error) {
return nestedQueryParams(message, field, prefix, reg, pathParams, body, newCycleChecker(recursiveCount))
}
type cycleChecker struct {
m map[string]int
count int
}
func newCycleChecker(recursive int) *cycleChecker {
return &cycleChecker{
m: make(map[string]int),
count: recursive,
}
}
// Check returns whether name is still within recursion
// toleration
func (c *cycleChecker) Check(name string) bool {
count, ok := c.m[name]
count += 1
isCycle := count > c.count
if isCycle {
return false
}
// provision map entry if not available
if !ok {
c.m[name] = 1
return true
}
c.m[name] = count
return true
}
func (c *cycleChecker) Branch() *cycleChecker {
copy := &cycleChecker{
count: c.count,
m: make(map[string]int, len(c.m)),
}
for k, v := range c.m {
copy.m[k] = v
}
return copy
}
// nestedQueryParams converts a field to a list of OpenAPI query parameters recursively.
// This function is a helper function for queryParams, that keeps track of cyclical message references
// through the use of
//
// touched map[string]int
//
// If a cycle is discovered, an error is returned, as cyclical data structures are dangerous
// in query parameters.
func nestedQueryParams(message *descriptor.Message, field *descriptor.Field, prefix string, reg *descriptor.Registry, pathParams []descriptor.Parameter, body *descriptor.Body, cycle *cycleChecker) (params []openapiParameterObject, 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
}
}
// make sure the parameter is not already listed as a body parameter
if body != nil {
if body.FieldPath == nil {
return nil, nil
}
for _, fieldPath := range body.FieldPath {
if fieldPath.Target == field {
return nil, nil
}
}
}
schema := schemaOfField(field, reg, nil)
fieldType := field.GetTypeName()
if message.File != nil {
comments := fieldProtoComments(reg, message, field)
if err := updateOpenAPIDataFromComments(reg, &schema, message, comments, false); err != nil {
return nil, err
}
}
isEnum := field.GetType() == descriptorpb.FieldDescriptorProto_TYPE_ENUM
items := schema.Items
if schema.Type != "" || isEnum {
if schema.Type == "object" {
location := ""
if ix := strings.LastIndex(field.Message.FQMN(), "."); ix > 0 {
location = field.Message.FQMN()[0:ix]
}
if m, err := reg.LookupMsg(location, field.GetTypeName()); err == nil {
if opt := m.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry {
k := m.GetField()[0]
kType, err := getMapParamKey(k.GetType())
if err != nil {
return nil, err
}
// This will generate a query in the format map_name[key_type]
fName := fmt.Sprintf("%s[%s]", *field.Name, kType)
field.Name = proto.String(fName)
schema.Type = schema.AdditionalProperties.schemaCore.Type
schema.Description = `This is a request variable of the map type. The query format is "map_name[key]=value", e.g. If the map name is Age, the key type is string, and the value type is integer, the query parameter is expressed as Age["bob"]=18`
}
}
}
if items != nil && (items.Type == "" || items.Type == "object") && !isEnum {
return nil, nil // TODO: currently, mapping object in query parameter is not supported
}
desc := mergeDescription(schema)
// verify if the field is required
required := false
for _, fieldName := range schema.Required {
if fieldName == reg.FieldName(field) {
required = true
break
}
}
// verify if the field is required in message options
if messageSchema, err := extractSchemaOptionFromMessageDescriptor(message.DescriptorProto); err == nil {
for _, fieldName := range messageSchema.GetJsonSchema().GetRequired() {
// Required fields can be field names or json_name values
if fieldName == field.GetJsonName() || fieldName == field.GetName() {
required = true
break
}
}
}
param := openapiParameterObject{
Description: desc,
In: "query",
Default: schema.Default,
Type: schema.Type,
Items: schema.Items,
Format: schema.Format,
Pattern: schema.Pattern,
Required: required,
extensions: schema.extensions,
}
if param.Type == "array" {
param.CollectionFormat = "multi"
}
param.Name = prefix + reg.FieldName(field)
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 = &openapiItemsObject{
schemaCore: schemaCore{
Type: "string",
Enum: listEnumNames(reg, enum),
},
}
if reg.GetEnumsAsInts() {
param.Items.Type = "integer"
param.Items.Enum = listEnumNumbers(reg, enum)
}
} else {
param.Type = "string"
param.Enum = listEnumNames(reg, enum)
param.Default = getEnumDefault(reg, enum)
if reg.GetEnumsAsInts() {
param.Type = "integer"
param.Enum = listEnumNumbers(reg, enum)
param.Default = getEnumDefaultNumber(reg, enum)
}
}
valueComments := enumValueProtoComments(reg, enum)
if valueComments != "" {
param.Description = strings.TrimLeft(param.Description+"\n\n "+valueComments, "\n")
}
}
return []openapiParameterObject{param}, nil
}
// nested type, recurse
msg, err := reg.LookupMsg("", fieldType)
if err != nil {
return nil, fmt.Errorf("unknown message type %s", fieldType)
}
// Check for cyclical message reference:
if ok := cycle.Check(*msg.Name); !ok {
return nil, fmt.Errorf("exceeded recursive count (%d) for query parameter %q", cycle.count, fieldType)
}
// Construct a new map with the message name so a cycle further down the recursive path can be detected.
// Do not keep anything in the original touched reference and do not pass that reference along. This will
// prevent clobbering adjacent records while recursing.
touchedOut := cycle.Branch()
for _, nestedField := range msg.Fields {
if !isVisible(getFieldVisibilityOption(nestedField), reg) {
continue
}
fieldName := reg.FieldName(field)
p, err := nestedQueryParams(msg, nestedField, prefix+fieldName+".", reg, pathParams, body, touchedOut)
if err != nil {
return nil, err
}
params = append(params, p...)
}
return params, nil
}
func getMapParamKey(t descriptorpb.FieldDescriptorProto_Type) (string, error) {
tType, f, ok := primitiveSchema(t)
if !ok || f == "byte" || f == "float" || f == "double" {
return "", fmt.Errorf("unsupported type: %q", f)
}
return tType, 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, ms messageMap, e enumMap, refs refMap) {
for _, svc := range s {
for _, meth := range svc.Methods {
// Request may be fully included in query
{
if !isVisible(getMethodVisibilityOption(meth), reg) {
continue
}
swgReqName, ok := fullyQualifiedNameToOpenAPIName(meth.RequestType.FQMN(), reg)
if !ok {
glog.Errorf("couldn't resolve OpenAPI name for FQMN %q", meth.RequestType.FQMN())
continue
}
if _, ok := refs[fmt.Sprintf("#/definitions/%s", swgReqName)]; ok {
if !skipRenderingRef(meth.RequestType.FQMN()) {
m[swgReqName] = meth.RequestType
}
}
}
swgRspName, ok := fullyQualifiedNameToOpenAPIName(meth.ResponseType.FQMN(), reg)
if !ok && !skipRenderingRef(meth.ResponseType.FQMN()) {
glog.Errorf("couldn't resolve OpenAPI name for FQMN %q", meth.ResponseType.FQMN())
continue
}
findNestedMessagesAndEnumerations(meth.RequestType, reg, m, e)
if !skipRenderingRef(meth.ResponseType.FQMN()) {
m[swgRspName] = 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 {
if !isVisible(getFieldVisibilityOption(t), reg) {
continue
}
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 skipRenderingRef(refName string) bool {
_, ok := wktSchemas[refName]
return ok
}
func renderMessageAsDefinition(msg *descriptor.Message, reg *descriptor.Registry, customRefs refMap, pathParams []descriptor.Parameter) (openapiSchemaObject, error) {
schema := openapiSchemaObject{
schemaCore: schemaCore{
Type: "object",
},
}
msgComments := protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index))
if err := updateOpenAPIDataFromComments(reg, &schema, msg, msgComments, false); err != nil {
return openapiSchemaObject{}, err
}
opts, err := getMessageOpenAPIOption(reg, msg)
if err != nil {
return openapiSchemaObject{}, err
}
if opts != nil {
protoSchema := openapiSchemaFromProtoSchema(opts, reg, customRefs, msg)
// Warning: Make sure not to overwrite any fields already set on the schema type.
schema.ExternalDocs = protoSchema.ExternalDocs
schema.ReadOnly = protoSchema.ReadOnly
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.Default = protoSchema.Default
schema.MaxItems = protoSchema.MaxItems
schema.MinItems = protoSchema.MinItems
schema.UniqueItems = protoSchema.UniqueItems
schema.MaxProperties = protoSchema.MaxProperties
schema.MinProperties = protoSchema.MinProperties
schema.Required = protoSchema.Required
schema.XNullable = protoSchema.XNullable
schema.extensions = protoSchema.extensions
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
}
if protoSchema.Example != nil {
schema.Example = protoSchema.Example
}
}
schema.Required = filterOutExcludedFields(schema.Required, pathParams)
for _, f := range msg.Fields {
if !isVisible(getFieldVisibilityOption(f), reg) {
continue
}
if shouldExcludeField(f.GetName(), pathParams) {
continue
}
subPathParams := subPathParams(f.GetName(), pathParams)
fieldSchema, err := renderFieldAsDefinition(f, reg, customRefs, subPathParams)
if err != nil {
return openapiSchemaObject{}, err
}
comments := fieldProtoComments(reg, msg, f)
if err := updateOpenAPIDataFromComments(reg, &fieldSchema, f, comments, false); err != nil {
return openapiSchemaObject{}, err
}
if requiredIdx := find(schema.Required, *f.Name); requiredIdx != -1 && reg.GetUseJSONNamesForFields() {
schema.Required[requiredIdx] = f.GetJsonName()
}
if fieldSchema.Required != nil {
schema.Required = getUniqueFields(schema.Required, fieldSchema.Required)
schema.Required = append(schema.Required, fieldSchema.Required...)
// To avoid populating both the field schema require and message schema require, unset the field schema require.
// See issue #2635.
fieldSchema.Required = nil
}
if reg.GetUseAllOfForRefs() {
if fieldSchema.Ref != "" {
// Per the JSON Reference syntax: Any members other than "$ref" in a JSON Reference object SHALL be ignored.
// https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3
// However, use allOf to specify Title/Description/Example/readOnly fields.
if fieldSchema.Title != "" || fieldSchema.Description != "" || len(fieldSchema.Example) > 0 || fieldSchema.ReadOnly {
fieldSchema = openapiSchemaObject{
Title: fieldSchema.Title,
Description: fieldSchema.Description,
schemaCore: schemaCore{
Example: fieldSchema.Example,
},
ReadOnly: fieldSchema.ReadOnly,
AllOf: []allOfEntry{{Ref: fieldSchema.Ref}},
}
} else {
fieldSchema = openapiSchemaObject{schemaCore: schemaCore{Ref: fieldSchema.Ref}}
}
}
}
kv := keyVal{Value: fieldSchema}
kv.Key = reg.FieldName(f)
if schema.Properties == nil {
schema.Properties = &openapiSchemaObjectProperties{}
}
*schema.Properties = append(*schema.Properties, kv)
}
if msg.FQMN() == ".google.protobuf.Any" {
transformAnyForJSON(&schema, reg.GetUseJSONNamesForFields())
}
return schema, nil
}
func renderFieldAsDefinition(f *descriptor.Field, reg *descriptor.Registry, refs refMap, pathParams []descriptor.Parameter) (openapiSchemaObject, error) {
if len(pathParams) == 0 {
return schemaOfField(f, reg, refs), nil
}
location := ""
if ix := strings.LastIndex(f.Message.FQMN(), "."); ix > 0 {
location = f.Message.FQMN()[0:ix]
}
msg, err := reg.LookupMsg(location, f.GetTypeName())
if err != nil {
return openapiSchemaObject{}, err
}
schema, err := renderMessageAsDefinition(msg, reg, refs, pathParams)
if err != nil {
return openapiSchemaObject{}, err
}
comments := fieldProtoComments(reg, f.Message, f)
if len(comments) > 0 {
// Use title and description from field instead of nested message if present.
paragraphs := strings.Split(comments, paragraphDeliminator)
schema.Title = strings.TrimSpace(paragraphs[0])
schema.Description = strings.TrimSpace(strings.Join(paragraphs[1:], paragraphDeliminator))
}
return schema, nil
}
// transformAnyForJSON should be called when the schema object represents a google.protobuf.Any, and will replace the
// Properties slice with a single value for '@type'. We mutate the incorrectly named field so that we inherit the same
// documentation as specified on the original field in the protobuf descriptors.
func transformAnyForJSON(schema *openapiSchemaObject, useJSONNames bool) {
var typeFieldName string
if useJSONNames {
typeFieldName = "typeUrl"
} else {
typeFieldName = "type_url"
}
for _, property := range *schema.Properties {
if property.Key == typeFieldName {
schema.AdditionalProperties = &openapiSchemaObject{}
schema.Properties = &openapiSchemaObjectProperties{keyVal{
Key: "@type",
Value: property.Value,
}}
break
}
}
}
func renderMessagesAsDefinition(messages messageMap, d openapiDefinitionsObject, reg *descriptor.Registry, customRefs refMap, pathParams []descriptor.Parameter) error {
for name, msg := range messages {
swgName, ok := fullyQualifiedNameToOpenAPIName(msg.FQMN(), reg)
if !ok {
return fmt.Errorf("can't resolve OpenAPI name from %q", msg.FQMN())
}
if skipRenderingRef(name) {
continue
}
if opt := msg.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry {
continue
}
var err error
d[swgName], err = renderMessageAsDefinition(msg, reg, customRefs, pathParams)
if err != nil {
return err
}
}
return nil
}
// isVisible checks if a field/RPC is visible based on the visibility restriction
// combined with the `visibility_restriction_selectors`.
// Elements with an overlap on `visibility_restriction_selectors` are visible, those without are not visible.
// Elements without `google.api.VisibilityRule` annotations entirely are always visible.
func isVisible(r *visibility.VisibilityRule, reg *descriptor.Registry) bool {
if r == nil {
return true
}
restrictions := strings.Split(strings.TrimSpace(r.Restriction), ",")
// No restrictions results in the element always being visible
if len(restrictions) == 0 {
return true
}
for _, restriction := range restrictions {
if reg.GetVisibilityRestrictionSelectors()[strings.TrimSpace(restriction)] {
return true
}
}
return false
}
func shouldExcludeField(name string, excluded []descriptor.Parameter) bool {
for _, p := range excluded {
if len(p.FieldPath) == 1 && name == p.FieldPath[0].Name {
return true
}
}
return false
}
func filterOutExcludedFields(fields []string, excluded []descriptor.Parameter) []string {
var filtered []string
for _, f := range fields {
if !shouldExcludeField(f, excluded) {
filtered = append(filtered, f)
}
}
return filtered
}
// schemaOfField returns a OpenAPI Schema Object for a protobuf field.
func schemaOfField(f *descriptor.Field, reg *descriptor.Registry, refs refMap) openapiSchemaObject {
const (
singular = 0
array = 1
object = 2
)
var (
core schemaCore
aggregate int
)
fd := f.FieldDescriptorProto
location := ""
if ix := strings.LastIndex(f.Message.FQMN(), "."); ix > 0 {
location = f.Message.FQMN()[0:ix]
}
if m, err := reg.LookupMsg(location, f.GetTypeName()); err == nil {
if opt := m.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry {
fd = m.GetField()[1]
aggregate = object
}
}
if fd.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED {
aggregate = array
}
var props *openapiSchemaObjectProperties
switch ft := fd.GetType(); ft {
case descriptorpb.FieldDescriptorProto_TYPE_ENUM, descriptorpb.FieldDescriptorProto_TYPE_MESSAGE, descriptorpb.FieldDescriptorProto_TYPE_GROUP:
if wktSchema, ok := wktSchemas[fd.GetTypeName()]; ok {
core = wktSchema
if fd.GetTypeName() == ".google.protobuf.Empty" {
props = &openapiSchemaObjectProperties{}
}
} else {
swgRef, ok := fullyQualifiedNameToOpenAPIName(fd.GetTypeName(), reg)
if !ok {
panic(fmt.Sprintf("can't resolve OpenAPI ref from typename %q", fd.GetTypeName()))
}
core = schemaCore{
Ref: "#/definitions/" + swgRef,
}
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"}
}
}
ret := openapiSchemaObject{}
switch aggregate {
case array:
if _, ok := wktSchemas[fd.GetTypeName()]; !ok && fd.GetType() == descriptorpb.FieldDescriptorProto_TYPE_MESSAGE {
core.Type = "object"
}
ret = openapiSchemaObject{
schemaCore: schemaCore{
Type: "array",
Items: (*openapiItemsObject)(&openapiSchemaObject{schemaCore: core}),
},
}
case object:
ret = openapiSchemaObject{
schemaCore: schemaCore{
Type: "object",
},
AdditionalProperties: &openapiSchemaObject{Properties: props, schemaCore: core},
}
default:
ret = openapiSchemaObject{
schemaCore: core,
Properties: props,
}
}
if j, err := getFieldOpenAPIOption(reg, f); err == nil {
updateswaggerObjectFromJSONSchema(&ret, j, reg, f)
}
if j, err := getFieldBehaviorOption(reg, f); err == nil {
updateSwaggerObjectFromFieldBehavior(&ret, j, reg, f)
}
for i, required := range ret.Required {
if required == f.GetName() {
ret.Required[i] = reg.FieldName(f)
}
}
if reg.GetProto3OptionalNullable() && f.GetProto3Optional() {
ret.XNullable = true
}
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 descriptorpb.FieldDescriptorProto_Type) (ftype, format string, ok bool) {
switch t {
case descriptorpb.FieldDescriptorProto_TYPE_DOUBLE:
return "number", "double", true
case descriptorpb.FieldDescriptorProto_TYPE_FLOAT:
return "number", "float", true
case descriptorpb.FieldDescriptorProto_TYPE_INT64:
return "string", "int64", true
case descriptorpb.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 OpenAPI spec.
// So we cannot expect that uint64 is commonly supported by OpenAPI processor.
return "string", "uint64", true
case descriptorpb.FieldDescriptorProto_TYPE_INT32:
return "integer", "int32", true
case descriptorpb.FieldDescriptorProto_TYPE_FIXED64:
// Ditto.
return "string", "uint64", true
case descriptorpb.FieldDescriptorProto_TYPE_FIXED32:
// Ditto.
return "integer", "int64", true
case descriptorpb.FieldDescriptorProto_TYPE_BOOL:
// NOTE: in OpenAPI specification, format should be empty on boolean type
return "boolean", "", true
case descriptorpb.FieldDescriptorProto_TYPE_STRING:
// NOTE: in OpenAPI specification, can be empty on string type
// see: https://swagger.io/specification/v2/#data-types
return "string", "", true
case descriptorpb.FieldDescriptorProto_TYPE_BYTES:
return "string", "byte", true
case descriptorpb.FieldDescriptorProto_TYPE_UINT32:
// Ditto.
return "integer", "int64", true
case descriptorpb.FieldDescriptorProto_TYPE_SFIXED32:
return "integer", "int32", true
case descriptorpb.FieldDescriptorProto_TYPE_SFIXED64:
return "string", "int64", true
case descriptorpb.FieldDescriptorProto_TYPE_SINT32:
return "integer", "int32", true
case descriptorpb.FieldDescriptorProto_TYPE_SINT64:
return "string", "int64", true
default:
return "", "", false
}
}
// renderEnumerationsAsDefinition inserts enums into the definitions object.
func renderEnumerationsAsDefinition(enums enumMap, d openapiDefinitionsObject, reg *descriptor.Registry) {
for _, enum := range enums {
swgName, ok := fullyQualifiedNameToOpenAPIName(enum.FQEN(), reg)
if !ok {
panic(fmt.Sprintf("can't resolve OpenAPI name from FQEN %q", enum.FQEN()))
}
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(reg, enum)
defaultValue := getEnumDefault(reg, enum)
valueComments := enumValueProtoComments(reg, enum)
if valueComments != "" {
enumComments = strings.TrimLeft(enumComments+"\n\n "+valueComments, "\n")
}
enumSchemaObject := openapiSchemaObject{
schemaCore: schemaCore{
Type: "string",
Enum: enumNames,
Default: defaultValue,
},
}
if reg.GetEnumsAsInts() {
enumSchemaObject.Type = "integer"
enumSchemaObject.Format = "int32"
enumSchemaObject.Default = getEnumDefaultNumber(reg, enum)
enumSchemaObject.Enum = listEnumNumbers(reg, enum)
}
if err := updateOpenAPIDataFromComments(reg, &enumSchemaObject, enum, enumComments, false); err != nil {
panic(err)
}
d[swgName] = enumSchemaObject
}
}
// Take in a FQMN or FQEN and return a OpenAPI safe version of the FQMN and
// a boolean indicating if FQMN was properly resolved.
func fullyQualifiedNameToOpenAPIName(fqn string, reg *descriptor.Registry) (string, bool) {
registriesSeenMutex.Lock()
defer registriesSeenMutex.Unlock()
if mapping, present := registriesSeen[reg]; present {
ret, ok := mapping[fqn]
return ret, ok
}
mapping := resolveFullyQualifiedNameToOpenAPINames(append(reg.GetAllFQMNs(), reg.GetAllFQENs()...), reg.GetOpenAPINamingStrategy())
registriesSeen[reg] = mapping
ret, ok := mapping[fqn]
return ret, ok
}
// Lookup message type by location.name and return a openapiv2-safe version
// of its FQMN.
func lookupMsgAndOpenAPIName(location, name string, reg *descriptor.Registry) (*descriptor.Message, string, error) {
msg, err := reg.LookupMsg(location, name)
if err != nil {
return nil, "", err
}
swgName, ok := fullyQualifiedNameToOpenAPIName(msg.FQMN(), reg)
if !ok {
return nil, "", fmt.Errorf("can't map OpenAPI name from FQMN %q", msg.FQMN())
}
return msg, swgName, nil
}
// registriesSeen is used to memoise calls to resolveFullyQualifiedNameToOpenAPINames 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 message and generate a unique reference for each, according to the given strategy.
func resolveFullyQualifiedNameToOpenAPINames(messages []string, namingStrategy string) map[string]string {
strategyFn := LookupNamingStrategy(namingStrategy)
if strategyFn == nil {
return nil
}
return strategyFn(messages)
}
var canRegexp = regexp.MustCompile("{([a-zA-Z][a-zA-Z0-9_.]*)([^}]*)}")
// templateToParts will split a URL template as defined by https://github.com/googleapis/googleapis/blob/master/google/api/http.proto
// into a string slice with each part as an element of the slice for use by `partsToOpenAPIPath` and `partsToRegexpMap`.
func templateToParts(path string, reg *descriptor.Registry, fields []*descriptor.Field, msgs []*descriptor.Message) []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 := ""
jsonBuffer := ""
pathLoop:
for i, char := range path {
switch char {
case '{':
// Push on the stack
depth++
buffer += string(char)
jsonBuffer = ""
jsonBuffer += string(char)
case '}':
if depth == 0 {
panic("Encountered } without matching { before it.")
}
// Pop from the stack
depth--
buffer += string(char)
if reg.GetUseJSONNamesForFields() &&
len(jsonBuffer) > 1 {
jsonSnakeCaseName := string(jsonBuffer[1:])
jsonCamelCaseName := string(lowerCamelCase(jsonSnakeCaseName, fields, msgs))
prev := string(buffer[:len(buffer)-len(jsonSnakeCaseName)-2])
buffer = strings.Join([]string{prev, "{", jsonCamelCaseName, "}"}, "")
jsonBuffer = ""
}
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)
jsonBuffer += string(char)
case ':':
if depth == 0 {
// As soon as we find a ":" outside a variable,