generator.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. // Copyright 2020 Google LLC. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. package generator
  16. import (
  17. "fmt"
  18. "log"
  19. "net/url"
  20. "regexp"
  21. "sort"
  22. "strings"
  23. http2 "net/http"
  24. "google.golang.org/protobuf/types/descriptorpb"
  25. "google.golang.org/genproto/googleapis/api/annotations"
  26. status_pb "google.golang.org/genproto/googleapis/rpc/status"
  27. "google.golang.org/protobuf/compiler/protogen"
  28. "google.golang.org/protobuf/proto"
  29. "google.golang.org/protobuf/reflect/protoreflect"
  30. any_pb "google.golang.org/protobuf/types/known/anypb"
  31. "git.ikuban.com/server/kratos-utils/v2/transport/http/handler"
  32. wk "git.ikuban.com/server/swagger-api/v2/generator/wellknown"
  33. v3 "github.com/google/gnostic/openapiv3"
  34. )
  35. type Configuration struct {
  36. Version *string
  37. Title *string
  38. Description *string
  39. Naming *string
  40. FQSchemaNaming *bool
  41. EnumType *string
  42. CircularDepth *int
  43. DefaultResponse *bool
  44. OutputMode *string
  45. }
  46. const (
  47. infoURL = "git.ikuban.com/server/swagger-api"
  48. )
  49. // In order to dynamically add google.rpc.Status responses we need
  50. // to know the message descriptors for google.rpc.Status as well
  51. // as google.protobuf.Any.
  52. var statusProtoDesc = (&status_pb.Status{}).ProtoReflect().Descriptor()
  53. var anyProtoDesc = (&any_pb.Any{}).ProtoReflect().Descriptor()
  54. // OpenAPIv3Generator holds internal state needed to generate an OpenAPIv3 document for a transcoded Protocol Buffer service.
  55. type OpenAPIv3Generator struct {
  56. conf Configuration
  57. plugin *protogen.Plugin
  58. inputFiles []*protogen.File
  59. reflect *OpenAPIv3Reflector
  60. generatedSchemas []string // Names of schemas that have already been generated.
  61. linterRulePattern *regexp.Regexp
  62. pathPattern *regexp.Regexp
  63. namedPathPattern *regexp.Regexp
  64. }
  65. // NewOpenAPIv3Generator creates a new generator for a protoc plugin invocation.
  66. func NewOpenAPIv3Generator(plugin *protogen.Plugin, conf Configuration, inputFiles []*protogen.File) *OpenAPIv3Generator {
  67. return &OpenAPIv3Generator{
  68. conf: conf,
  69. plugin: plugin,
  70. inputFiles: inputFiles,
  71. reflect: NewOpenAPIv3Reflector(conf),
  72. generatedSchemas: make([]string, 0),
  73. linterRulePattern: regexp.MustCompile(`\(-- .* --\)`),
  74. pathPattern: regexp.MustCompile("{([^=}]+)}"),
  75. namedPathPattern: regexp.MustCompile("{(.+)=(.+)}"),
  76. }
  77. }
  78. // Run runs the generator.
  79. func (g *OpenAPIv3Generator) Run(outputFile *protogen.GeneratedFile) error {
  80. d := g.buildDocumentV3()
  81. bytes, err := d.YAMLValue("Generated with protoc-gen-openapi\n" + infoURL)
  82. if err != nil {
  83. return fmt.Errorf("failed to marshal yaml: %s", err.Error())
  84. }
  85. if _, err = outputFile.Write(bytes); err != nil {
  86. return fmt.Errorf("failed to write yaml: %s", err.Error())
  87. }
  88. return nil
  89. }
  90. func (g *OpenAPIv3Generator) RunV2() ([]byte, error) {
  91. d := g.buildDocumentV3()
  92. bytes, err := d.YAMLValue("Generated with protoc-gen-openapi\n" + infoURL)
  93. if err != nil {
  94. return bytes, fmt.Errorf("failed to marshal yaml: %s", err.Error())
  95. }
  96. return bytes, nil
  97. }
  98. // buildDocumentV3 builds an OpenAPIv3 document for a plugin request.
  99. func (g *OpenAPIv3Generator) buildDocumentV3() *v3.Document {
  100. d := &v3.Document{}
  101. d.Openapi = "3.0.3"
  102. d.Info = &v3.Info{
  103. Version: *g.conf.Version,
  104. Title: *g.conf.Title,
  105. Description: *g.conf.Description,
  106. }
  107. d.Paths = &v3.Paths{}
  108. d.Components = &v3.Components{
  109. Schemas: &v3.SchemasOrReferences{
  110. AdditionalProperties: []*v3.NamedSchemaOrReference{},
  111. },
  112. }
  113. // Go through the files and add the services to the documents, keeping
  114. // track of which schemas are referenced in the response so we can
  115. // add them later.
  116. for _, file := range g.inputFiles {
  117. if file.Generate {
  118. // Merge any `Document` annotations with the current
  119. extDocument := proto.GetExtension(file.Desc.Options(), v3.E_Document)
  120. if extDocument != nil {
  121. proto.Merge(d, extDocument.(*v3.Document))
  122. }
  123. g.addPathsToDocumentV3(d, file.Services)
  124. }
  125. }
  126. // While we have required schemas left to generate, go through the files again
  127. // looking for the related message and adding them to the document if required.
  128. for len(g.reflect.requiredSchemas) > 0 {
  129. count := len(g.reflect.requiredSchemas)
  130. for _, file := range g.plugin.Files {
  131. g.addSchemasForMessagesToDocumentV3(d, file.Messages, file.Proto.GetEdition())
  132. }
  133. g.reflect.requiredSchemas = g.reflect.requiredSchemas[count:len(g.reflect.requiredSchemas)]
  134. }
  135. // If there is only 1 service, then use it's title for the
  136. // document, if the document is missing it.
  137. if len(d.Tags) == 1 {
  138. if d.Info.Title == "" && d.Tags[0].Name != "" {
  139. d.Info.Title = d.Tags[0].Name + " API"
  140. }
  141. if d.Info.Description == "" {
  142. d.Info.Description = d.Tags[0].Description
  143. }
  144. d.Tags[0].Description = ""
  145. }
  146. allServers := []string{}
  147. // If paths methods has servers, but they're all the same, then move servers to path level
  148. for _, path := range d.Paths.Path {
  149. servers := []string{}
  150. // Only 1 server will ever be set, per method, by the generator
  151. if path.Value.Get != nil && len(path.Value.Get.Servers) == 1 {
  152. servers = appendUnique(servers, path.Value.Get.Servers[0].Url)
  153. allServers = appendUnique(servers, path.Value.Get.Servers[0].Url)
  154. }
  155. if path.Value.Post != nil && len(path.Value.Post.Servers) == 1 {
  156. servers = appendUnique(servers, path.Value.Post.Servers[0].Url)
  157. allServers = appendUnique(servers, path.Value.Post.Servers[0].Url)
  158. }
  159. if path.Value.Put != nil && len(path.Value.Put.Servers) == 1 {
  160. servers = appendUnique(servers, path.Value.Put.Servers[0].Url)
  161. allServers = appendUnique(servers, path.Value.Put.Servers[0].Url)
  162. }
  163. if path.Value.Delete != nil && len(path.Value.Delete.Servers) == 1 {
  164. servers = appendUnique(servers, path.Value.Delete.Servers[0].Url)
  165. allServers = appendUnique(servers, path.Value.Delete.Servers[0].Url)
  166. }
  167. if path.Value.Patch != nil && len(path.Value.Patch.Servers) == 1 {
  168. servers = appendUnique(servers, path.Value.Patch.Servers[0].Url)
  169. allServers = appendUnique(servers, path.Value.Patch.Servers[0].Url)
  170. }
  171. if path.Value.Head != nil && len(path.Value.Head.Servers) == 1 {
  172. servers = appendUnique(servers, path.Value.Head.Servers[0].Url)
  173. allServers = appendUnique(servers, path.Value.Head.Servers[0].Url)
  174. }
  175. if path.Value.Options != nil && len(path.Value.Options.Servers) == 1 {
  176. servers = appendUnique(servers, path.Value.Options.Servers[0].Url)
  177. allServers = appendUnique(servers, path.Value.Options.Servers[0].Url)
  178. }
  179. if path.Value.Trace != nil && len(path.Value.Trace.Servers) == 1 {
  180. servers = appendUnique(servers, path.Value.Trace.Servers[0].Url)
  181. allServers = appendUnique(servers, path.Value.Trace.Servers[0].Url)
  182. }
  183. if len(servers) == 1 {
  184. path.Value.Servers = []*v3.Server{{Url: servers[0]}}
  185. if path.Value.Get != nil {
  186. path.Value.Get.Servers = nil
  187. }
  188. if path.Value.Post != nil {
  189. path.Value.Post.Servers = nil
  190. }
  191. if path.Value.Put != nil {
  192. path.Value.Put.Servers = nil
  193. }
  194. if path.Value.Delete != nil {
  195. path.Value.Delete.Servers = nil
  196. }
  197. if path.Value.Patch != nil {
  198. path.Value.Patch.Servers = nil
  199. }
  200. if path.Value.Head != nil {
  201. path.Value.Head.Servers = nil
  202. }
  203. if path.Value.Options != nil {
  204. path.Value.Options.Servers = nil
  205. }
  206. if path.Value.Trace != nil {
  207. path.Value.Trace.Servers = nil
  208. }
  209. }
  210. }
  211. // Set all servers on API level
  212. if len(allServers) > 0 {
  213. d.Servers = []*v3.Server{}
  214. for _, server := range allServers {
  215. d.Servers = append(d.Servers, &v3.Server{Url: server})
  216. }
  217. }
  218. // If there is only 1 server, we can safely remove all path level servers
  219. if len(allServers) == 1 {
  220. for _, path := range d.Paths.Path {
  221. path.Value.Servers = nil
  222. }
  223. }
  224. // Sort the tags.
  225. {
  226. pairs := d.Tags
  227. sort.Slice(pairs, func(i, j int) bool {
  228. return pairs[i].Name < pairs[j].Name
  229. })
  230. d.Tags = pairs
  231. }
  232. // Sort the paths.
  233. {
  234. pairs := d.Paths.Path
  235. sort.Slice(pairs, func(i, j int) bool {
  236. return pairs[i].Name < pairs[j].Name
  237. })
  238. d.Paths.Path = pairs
  239. }
  240. // Sort the schemas.
  241. {
  242. pairs := d.Components.Schemas.AdditionalProperties
  243. sort.Slice(pairs, func(i, j int) bool {
  244. return pairs[i].Name < pairs[j].Name
  245. })
  246. d.Components.Schemas.AdditionalProperties = pairs
  247. }
  248. return d
  249. }
  250. // filterCommentString removes linter rules from comments.
  251. func (g *OpenAPIv3Generator) filterCommentString(c protogen.Comments) string {
  252. comment := g.linterRulePattern.ReplaceAllString(string(c), "")
  253. return strings.TrimSpace(comment)
  254. }
  255. func (g *OpenAPIv3Generator) findField(name string, inMessage *protogen.Message) *protogen.Field {
  256. for _, field := range inMessage.Fields {
  257. if string(field.Desc.Name()) == name || string(field.Desc.JSONName()) == name {
  258. return field
  259. }
  260. }
  261. return nil
  262. }
  263. func (g *OpenAPIv3Generator) findAndFormatFieldName(name string, inMessage *protogen.Message) string {
  264. field := g.findField(name, inMessage)
  265. if field != nil {
  266. return g.reflect.formatFieldName(field.Desc)
  267. }
  268. return name
  269. }
  270. // Note that fields which are mapped to URL query parameters must have a primitive type
  271. // or a repeated primitive type or a non-repeated message type.
  272. // In the case of a repeated type, the parameter can be repeated in the URL as ...?param=A&param=B.
  273. // In the case of a message type, each field of the message is mapped to a separate parameter,
  274. // such as ...?foo.a=A&foo.b=B&foo.c=C.
  275. // There are exceptions:
  276. // - for wrapper types it will use the same representation as the wrapped primitive type in JSON
  277. // - for google.protobuf.timestamp type it will be serialized as a string
  278. //
  279. // maps, Struct and Empty can NOT be used
  280. // messages can have any number of sub messages - including circular (e.g. sub.subsub.sub.subsub.id)
  281. // buildQueryParamsV3 extracts any valid query params, including sub and recursive messages
  282. func (g *OpenAPIv3Generator) buildQueryParamsV3(field *protogen.Field) []*v3.ParameterOrReference {
  283. depths := map[string]int{}
  284. return g._buildQueryParamsV3(field, depths)
  285. }
  286. // depths are used to keep track of how many times a message's fields has been seen
  287. func (g *OpenAPIv3Generator) _buildQueryParamsV3(field *protogen.Field, depths map[string]int) []*v3.ParameterOrReference {
  288. parameters := []*v3.ParameterOrReference{}
  289. queryFieldName := g.reflect.formatFieldName(field.Desc)
  290. fieldDescription := g.filterCommentString(field.Comments.Leading)
  291. if field.Desc.IsMap() {
  292. // Map types are not allowed in query parameteres
  293. return parameters
  294. } else if field.Desc.Kind() == protoreflect.MessageKind {
  295. typeName := g.reflect.fullMessageTypeName(field.Desc.Message())
  296. switch typeName {
  297. case ".google.protobuf.Value":
  298. fieldSchema := g.reflect.schemaOrReferenceForField(field.Desc)
  299. parameters = append(parameters,
  300. &v3.ParameterOrReference{
  301. Oneof: &v3.ParameterOrReference_Parameter{
  302. Parameter: &v3.Parameter{
  303. Name: queryFieldName,
  304. In: "query",
  305. Description: fieldDescription,
  306. Required: false,
  307. Schema: fieldSchema,
  308. },
  309. },
  310. })
  311. return parameters
  312. case ".google.protobuf.BoolValue", ".google.protobuf.BytesValue", ".google.protobuf.Int32Value", ".google.protobuf.UInt32Value",
  313. ".google.protobuf.StringValue", ".google.protobuf.Int64Value", ".google.protobuf.UInt64Value", ".google.protobuf.FloatValue",
  314. ".google.protobuf.DoubleValue":
  315. valueField := getValueField(field.Message.Desc)
  316. fieldSchema := g.reflect.schemaOrReferenceForField(valueField)
  317. parameters = append(parameters,
  318. &v3.ParameterOrReference{
  319. Oneof: &v3.ParameterOrReference_Parameter{
  320. Parameter: &v3.Parameter{
  321. Name: queryFieldName,
  322. In: "query",
  323. Description: fieldDescription,
  324. Required: false,
  325. Schema: fieldSchema,
  326. },
  327. },
  328. })
  329. return parameters
  330. case ".google.protobuf.Timestamp":
  331. fieldSchema := g.reflect.schemaOrReferenceForMessage(field.Message.Desc)
  332. parameters = append(parameters,
  333. &v3.ParameterOrReference{
  334. Oneof: &v3.ParameterOrReference_Parameter{
  335. Parameter: &v3.Parameter{
  336. Name: queryFieldName,
  337. In: "query",
  338. Description: fieldDescription,
  339. Required: false,
  340. Schema: fieldSchema,
  341. },
  342. },
  343. })
  344. return parameters
  345. case ".google.protobuf.Duration":
  346. fieldSchema := g.reflect.schemaOrReferenceForMessage(field.Message.Desc)
  347. parameters = append(parameters,
  348. &v3.ParameterOrReference{
  349. Oneof: &v3.ParameterOrReference_Parameter{
  350. Parameter: &v3.Parameter{
  351. Name: queryFieldName,
  352. In: "query",
  353. Description: fieldDescription,
  354. Required: false,
  355. Schema: fieldSchema,
  356. },
  357. },
  358. })
  359. return parameters
  360. }
  361. if field.Desc.IsList() {
  362. // Only non-repeated message types are valid
  363. return parameters
  364. }
  365. // Represent field masks directly as strings (don't expand them).
  366. if typeName == ".google.protobuf.FieldMask" {
  367. fieldSchema := g.reflect.schemaOrReferenceForField(field.Desc)
  368. parameters = append(parameters,
  369. &v3.ParameterOrReference{
  370. Oneof: &v3.ParameterOrReference_Parameter{
  371. Parameter: &v3.Parameter{
  372. Name: queryFieldName,
  373. In: "query",
  374. Description: fieldDescription,
  375. Required: false,
  376. Schema: fieldSchema,
  377. },
  378. },
  379. })
  380. return parameters
  381. }
  382. // Sub messages are allowed, even circular, as long as the final type is a primitive.
  383. // Go through each of the sub message fields
  384. for _, subField := range field.Message.Fields {
  385. subFieldFullName := string(subField.Desc.FullName())
  386. seen, ok := depths[subFieldFullName]
  387. if !ok {
  388. depths[subFieldFullName] = 0
  389. }
  390. if seen < *g.conf.CircularDepth {
  391. depths[subFieldFullName]++
  392. subParams := g._buildQueryParamsV3(subField, depths)
  393. for _, subParam := range subParams {
  394. if param, ok := subParam.Oneof.(*v3.ParameterOrReference_Parameter); ok {
  395. param.Parameter.Name = queryFieldName + "." + param.Parameter.Name
  396. parameters = append(parameters, subParam)
  397. }
  398. }
  399. }
  400. }
  401. } else if field.Desc.Kind() != protoreflect.GroupKind {
  402. // schemaOrReferenceForField also handles array types
  403. fieldSchema := g.reflect.schemaOrReferenceForField(field.Desc)
  404. parameters = append(parameters,
  405. &v3.ParameterOrReference{
  406. Oneof: &v3.ParameterOrReference_Parameter{
  407. Parameter: &v3.Parameter{
  408. Name: queryFieldName,
  409. In: "query",
  410. Description: fieldDescription,
  411. Required: false,
  412. Schema: fieldSchema,
  413. },
  414. },
  415. })
  416. }
  417. return parameters
  418. }
  419. // buildOperationV3 constructs an operation for a set of values.
  420. func (g *OpenAPIv3Generator) buildOperationV3(
  421. d *v3.Document,
  422. operationID string,
  423. tagName string,
  424. description string,
  425. defaultHost string,
  426. path string,
  427. bodyField string,
  428. inputMessage *protogen.Message,
  429. outputMessage *protogen.Message,
  430. ) (*v3.Operation, string) {
  431. // coveredParameters tracks the parameters that have been used in the body or path.
  432. coveredParameters := make([]string, 0)
  433. if bodyField != "" {
  434. coveredParameters = append(coveredParameters, bodyField)
  435. }
  436. // Initialize the list of operation parameters.
  437. parameters := []*v3.ParameterOrReference{}
  438. // Find simple path parameters like {id}
  439. if allMatches := g.pathPattern.FindAllStringSubmatch(path, -1); allMatches != nil {
  440. for _, matches := range allMatches {
  441. // Add the value to the list of covered parameters.
  442. coveredParameters = append(coveredParameters, matches[1])
  443. pathParameter := g.findAndFormatFieldName(matches[1], inputMessage)
  444. path = strings.Replace(path, matches[1], pathParameter, 1)
  445. // Add the path parameters to the operation parameters.
  446. var fieldSchema *v3.SchemaOrReference
  447. var fieldDescription string
  448. field := g.findField(pathParameter, inputMessage)
  449. if field != nil {
  450. fieldSchema = g.reflect.schemaOrReferenceForField(field.Desc)
  451. fieldDescription = g.filterCommentString(field.Comments.Leading)
  452. } else {
  453. // If field does not exist, it is safe to set it to string, as it is ignored downstream
  454. fieldSchema = &v3.SchemaOrReference{
  455. Oneof: &v3.SchemaOrReference_Schema{
  456. Schema: &v3.Schema{
  457. Type: "string",
  458. },
  459. },
  460. }
  461. }
  462. parameters = append(parameters,
  463. &v3.ParameterOrReference{
  464. Oneof: &v3.ParameterOrReference_Parameter{
  465. Parameter: &v3.Parameter{
  466. Name: pathParameter,
  467. In: "path",
  468. Description: fieldDescription,
  469. Required: true,
  470. Schema: fieldSchema,
  471. },
  472. },
  473. })
  474. }
  475. }
  476. // Find named path parameters like {name=shelves/*}
  477. if matches := g.namedPathPattern.FindStringSubmatch(path); matches != nil {
  478. // Build a list of named path parameters.
  479. namedPathParameters := make([]string, 0)
  480. // Add the "name=" "name" value to the list of covered parameters.
  481. coveredParameters = append(coveredParameters, matches[1])
  482. // Convert the path from the starred form to use named path parameters.
  483. starredPath := matches[2]
  484. parts := strings.Split(starredPath, "/")
  485. // The starred path is assumed to be in the form "things/*/otherthings/*".
  486. // We want to convert it to "things/{thingsId}/otherthings/{otherthingsId}".
  487. for i := 0; i < len(parts)-1; i += 2 {
  488. section := parts[i]
  489. namedPathParameter := g.findAndFormatFieldName(section, inputMessage)
  490. namedPathParameter = singular(namedPathParameter)
  491. parts[i+1] = "{" + namedPathParameter + "}"
  492. namedPathParameters = append(namedPathParameters, namedPathParameter)
  493. }
  494. // Rewrite the path to use the path parameters.
  495. newPath := strings.Join(parts, "/")
  496. path = strings.Replace(path, matches[0], newPath, 1)
  497. // Add the named path parameters to the operation parameters.
  498. for _, namedPathParameter := range namedPathParameters {
  499. parameters = append(parameters,
  500. &v3.ParameterOrReference{
  501. Oneof: &v3.ParameterOrReference_Parameter{
  502. Parameter: &v3.Parameter{
  503. Name: namedPathParameter,
  504. In: "path",
  505. Required: true,
  506. Description: "The " + namedPathParameter + " id.",
  507. Schema: &v3.SchemaOrReference{
  508. Oneof: &v3.SchemaOrReference_Schema{
  509. Schema: &v3.Schema{
  510. Type: "string",
  511. },
  512. },
  513. },
  514. },
  515. },
  516. })
  517. }
  518. }
  519. // Add any unhandled fields in the request message as query parameters.
  520. if bodyField != "*" && string(inputMessage.Desc.FullName()) != "google.api.HttpBody" {
  521. for _, field := range inputMessage.Fields {
  522. fieldName := string(field.Desc.Name())
  523. if !contains(coveredParameters, fieldName) && fieldName != bodyField {
  524. fieldParams := g.buildQueryParamsV3(field)
  525. parameters = append(parameters, fieldParams...)
  526. }
  527. }
  528. }
  529. // Create the response.
  530. name, content := g.reflect.responseContentForMessage(outputMessage.Desc)
  531. responses := &v3.Responses{
  532. ResponseOrReference: []*v3.NamedResponseOrReference{
  533. {
  534. Name: name,
  535. Value: &v3.ResponseOrReference{
  536. Oneof: &v3.ResponseOrReference_Response{
  537. Response: &v3.Response{
  538. Description: "OK",
  539. Content: content,
  540. },
  541. },
  542. },
  543. },
  544. },
  545. }
  546. // Add the default reponse if needed
  547. if *g.conf.DefaultResponse {
  548. anySchemaName := g.reflect.formatMessageName(anyProtoDesc)
  549. anySchema := wk.NewGoogleProtobufAnySchema(anySchemaName)
  550. g.addSchemaToDocumentV3(d, anySchema)
  551. statusSchemaName := g.reflect.formatMessageName(statusProtoDesc)
  552. statusSchema := wk.NewGoogleRpcStatusSchema(statusSchemaName, anySchemaName)
  553. g.addSchemaToDocumentV3(d, statusSchema)
  554. defaultResponse := &v3.NamedResponseOrReference{
  555. Name: "default",
  556. Value: &v3.ResponseOrReference{
  557. Oneof: &v3.ResponseOrReference_Response{
  558. Response: &v3.Response{
  559. Description: "Default error response",
  560. Content: wk.NewApplicationJsonMediaType(&v3.SchemaOrReference{
  561. Oneof: &v3.SchemaOrReference_Reference{
  562. Reference: &v3.Reference{XRef: "#/components/schemas/" + statusSchemaName}}}),
  563. },
  564. },
  565. },
  566. }
  567. responses.ResponseOrReference = append(responses.ResponseOrReference, defaultResponse)
  568. }
  569. // Create the operation.
  570. op := &v3.Operation{
  571. Tags: []string{tagName},
  572. Description: description,
  573. OperationId: operationID,
  574. Parameters: parameters,
  575. Responses: responses,
  576. }
  577. if defaultHost != "" {
  578. hostURL, err := url.Parse(defaultHost)
  579. if err == nil {
  580. hostURL.Scheme = "https"
  581. op.Servers = append(op.Servers, &v3.Server{Url: hostURL.String()})
  582. }
  583. }
  584. // If a body field is specified, we need to pass a message as the request body.
  585. if bodyField != "" {
  586. var requestSchema *v3.SchemaOrReference
  587. if bodyField == "*" {
  588. // Pass the entire request message as the request body.
  589. requestSchema = g.reflect.schemaOrReferenceForMessage(inputMessage.Desc)
  590. } else {
  591. // If body refers to a message field, use that type.
  592. for _, field := range inputMessage.Fields {
  593. if string(field.Desc.Name()) == bodyField {
  594. switch field.Desc.Kind() {
  595. case protoreflect.StringKind:
  596. requestSchema = &v3.SchemaOrReference{
  597. Oneof: &v3.SchemaOrReference_Schema{
  598. Schema: &v3.Schema{
  599. Type: "string",
  600. },
  601. },
  602. }
  603. case protoreflect.MessageKind:
  604. requestSchema = g.reflect.schemaOrReferenceForMessage(field.Message.Desc)
  605. default:
  606. log.Printf("unsupported field type %+v", field.Desc)
  607. }
  608. break
  609. }
  610. }
  611. }
  612. op.RequestBody = &v3.RequestBodyOrReference{
  613. Oneof: &v3.RequestBodyOrReference_RequestBody{
  614. RequestBody: &v3.RequestBody{
  615. Required: true,
  616. Content: &v3.MediaTypes{
  617. AdditionalProperties: []*v3.NamedMediaType{
  618. {
  619. Name: "application/json",
  620. Value: &v3.MediaType{
  621. Schema: requestSchema,
  622. },
  623. },
  624. },
  625. },
  626. },
  627. },
  628. }
  629. }
  630. return op, path
  631. }
  632. // addOperationToDocumentV3 adds an operation to the specified path/method.
  633. func (g *OpenAPIv3Generator) addOperationToDocumentV3(d *v3.Document, op *v3.Operation, path string, methodName string) {
  634. var selectedPathItem *v3.NamedPathItem
  635. for _, namedPathItem := range d.Paths.Path {
  636. if namedPathItem.Name == path {
  637. selectedPathItem = namedPathItem
  638. break
  639. }
  640. }
  641. // If we get here, we need to create a path item.
  642. if selectedPathItem == nil {
  643. selectedPathItem = &v3.NamedPathItem{Name: path, Value: &v3.PathItem{}}
  644. d.Paths.Path = append(d.Paths.Path, selectedPathItem)
  645. }
  646. // Set the operation on the specified method.
  647. switch methodName {
  648. case "GET":
  649. selectedPathItem.Value.Get = op
  650. case "POST":
  651. selectedPathItem.Value.Post = op
  652. case "PUT":
  653. selectedPathItem.Value.Put = op
  654. case "DELETE":
  655. selectedPathItem.Value.Delete = op
  656. case "PATCH":
  657. selectedPathItem.Value.Patch = op
  658. case http2.MethodHead:
  659. selectedPathItem.Value.Head = op
  660. case http2.MethodOptions:
  661. selectedPathItem.Value.Options = op
  662. case http2.MethodTrace:
  663. selectedPathItem.Value.Trace = op
  664. }
  665. }
  666. // addPathsToDocumentV3 adds paths from a specified file descriptor.
  667. func (g *OpenAPIv3Generator) addPathsToDocumentV3(d *v3.Document, services []*protogen.Service) {
  668. for _, service := range services {
  669. annotationsCount := 0
  670. for _, method := range service.Methods {
  671. comment := g.filterCommentString(method.Comments.Leading)
  672. inputMessage := method.Input
  673. outputMessage := method.Output
  674. operationID := service.GoName + "_" + method.GoName
  675. extOperation := proto.GetExtension(method.Desc.Options(), v3.E_Operation)
  676. if extOperation == nil || extOperation == v3.E_Operation.InterfaceOf(v3.E_Operation.Zero()) {
  677. continue
  678. }
  679. var path string
  680. var httpMethod string
  681. var bodyField string
  682. httpOperation := proto.GetExtension(method.Desc.Options(), annotations.E_Http)
  683. if httpOperation != nil && httpOperation != annotations.E_Http.InterfaceOf(annotations.E_Http.Zero()) {
  684. _httpOperation := httpOperation.(*annotations.HttpRule)
  685. switch httpRule := _httpOperation.GetPattern().(type) {
  686. case *annotations.HttpRule_Post:
  687. path = httpRule.Post
  688. httpMethod = http2.MethodPost
  689. bodyField = _httpOperation.GetBody()
  690. case *annotations.HttpRule_Get:
  691. path = httpRule.Get
  692. httpMethod = http2.MethodGet
  693. bodyField = ""
  694. case *annotations.HttpRule_Delete:
  695. path = httpRule.Delete
  696. httpMethod = http2.MethodDelete
  697. bodyField = ""
  698. case *annotations.HttpRule_Put:
  699. path = httpRule.Put
  700. httpMethod = http2.MethodPut
  701. bodyField = _httpOperation.GetBody()
  702. case *annotations.HttpRule_Patch:
  703. path = httpRule.Patch
  704. httpMethod = http2.MethodPatch
  705. bodyField = _httpOperation.GetBody()
  706. case *annotations.HttpRule_Custom:
  707. path = httpRule.Custom.Path
  708. httpMethod = httpRule.Custom.Kind
  709. bodyField = _httpOperation.GetBody()
  710. }
  711. }
  712. annotationsCount++
  713. if path == "" {
  714. path = handler.PathGenerator(string(service.Desc.FullName()), method.GoName)
  715. }
  716. if httpMethod == "" {
  717. httpMethod = http2.MethodPost
  718. }
  719. if bodyField == "" && (httpMethod == http2.MethodPost || httpMethod == http2.MethodPut || httpMethod == http2.MethodPatch) {
  720. bodyField = "*"
  721. }
  722. defaultHost := proto.GetExtension(service.Desc.Options(), annotations.E_DefaultHost).(string)
  723. op, path2 := g.buildOperationV3(
  724. d, operationID, service.GoName, comment, defaultHost, path, bodyField, inputMessage, outputMessage)
  725. // Merge any `Operation` annotations with the current
  726. proto.Merge(op, extOperation.(*v3.Operation))
  727. g.addOperationToDocumentV3(d, op, path2, httpMethod)
  728. }
  729. if annotationsCount > 0 {
  730. comment := g.filterCommentString(service.Comments.Leading)
  731. d.Tags = append(d.Tags, &v3.Tag{Name: service.GoName, Description: comment})
  732. }
  733. }
  734. }
  735. // addSchemaForMessageToDocumentV3 adds the schema to the document if required
  736. func (g *OpenAPIv3Generator) addSchemaToDocumentV3(d *v3.Document, schema *v3.NamedSchemaOrReference) {
  737. if contains(g.generatedSchemas, schema.Name) {
  738. return
  739. }
  740. g.generatedSchemas = append(g.generatedSchemas, schema.Name)
  741. d.Components.Schemas.AdditionalProperties = append(d.Components.Schemas.AdditionalProperties, schema)
  742. }
  743. // addSchemasForMessagesToDocumentV3 adds info from one file descriptor.
  744. func (g *OpenAPIv3Generator) addSchemasForMessagesToDocumentV3(d *v3.Document, messages []*protogen.Message, edition descriptorpb.Edition) {
  745. // For each message, generate a definition.
  746. for _, message := range messages {
  747. if message.Messages != nil {
  748. g.addSchemasForMessagesToDocumentV3(d, message.Messages, edition)
  749. }
  750. schemaName := g.reflect.formatMessageName(message.Desc)
  751. // Only generate this if we need it and haven't already generated it.
  752. if !contains(g.reflect.requiredSchemas, schemaName) ||
  753. contains(g.generatedSchemas, schemaName) {
  754. continue
  755. }
  756. typeName := g.reflect.fullMessageTypeName(message.Desc)
  757. messageDescription := g.filterCommentString(message.Comments.Leading)
  758. // `google.protobuf.Value` and `google.protobuf.Any` have special JSON transcoding
  759. // so we can't just reflect on the message descriptor.
  760. if typeName == ".google.protobuf.Value" {
  761. g.addSchemaToDocumentV3(d, wk.NewGoogleProtobufValueSchema(schemaName))
  762. continue
  763. } else if typeName == ".google.protobuf.Any" {
  764. g.addSchemaToDocumentV3(d, wk.NewGoogleProtobufAnySchema(schemaName))
  765. continue
  766. } else if typeName == ".google.rpc.Status" {
  767. anySchemaName := g.reflect.formatMessageName(anyProtoDesc)
  768. g.addSchemaToDocumentV3(d, wk.NewGoogleProtobufAnySchema(anySchemaName))
  769. g.addSchemaToDocumentV3(d, wk.NewGoogleRpcStatusSchema(schemaName, anySchemaName))
  770. continue
  771. }
  772. // Build an array holding the fields of the message.
  773. definitionProperties := &v3.Properties{
  774. AdditionalProperties: make([]*v3.NamedSchemaOrReference, 0),
  775. }
  776. var required []string
  777. for _, field := range message.Fields {
  778. // Get the field description from the comments.
  779. description := g.filterCommentString(field.Comments.Leading)
  780. // Check the field annotations to see if this is a readonly or writeonly field.
  781. inputOnly := false
  782. outputOnly := false
  783. isRequired := true
  784. extension := proto.GetExtension(field.Desc.Options(), annotations.E_FieldBehavior)
  785. if extension != nil {
  786. switch v := extension.(type) {
  787. case []annotations.FieldBehavior:
  788. for _, vv := range v {
  789. switch vv {
  790. case annotations.FieldBehavior_OUTPUT_ONLY:
  791. outputOnly = true
  792. case annotations.FieldBehavior_INPUT_ONLY:
  793. inputOnly = true
  794. case annotations.FieldBehavior_OPTIONAL:
  795. isRequired = false
  796. }
  797. }
  798. default:
  799. log.Printf("unsupported extension type %T", extension)
  800. }
  801. }
  802. if edition == descriptorpb.Edition_EDITION_2023 {
  803. if fieldOptions, ok := field.Desc.Options().(*descriptorpb.FieldOptions); ok {
  804. if fieldOptions.GetFeatures().GetFieldPresence() == descriptorpb.FeatureSet_EXPLICIT {
  805. isRequired = false
  806. }
  807. }
  808. }
  809. if isRequired {
  810. required = append(required, g.reflect.formatFieldName(field.Desc))
  811. }
  812. // The field is either described by a reference or a schema.
  813. fieldSchema := g.reflect.schemaOrReferenceForField(field.Desc)
  814. if fieldSchema == nil {
  815. continue
  816. }
  817. // If this field has siblings and is a $ref now, create a new schema use `allOf` to wrap it
  818. wrapperNeeded := inputOnly || outputOnly || description != ""
  819. if wrapperNeeded {
  820. if _, ok := fieldSchema.Oneof.(*v3.SchemaOrReference_Reference); ok {
  821. fieldSchema = &v3.SchemaOrReference{Oneof: &v3.SchemaOrReference_Schema{Schema: &v3.Schema{
  822. AllOf: []*v3.SchemaOrReference{fieldSchema},
  823. }}}
  824. }
  825. }
  826. if schema, ok := fieldSchema.Oneof.(*v3.SchemaOrReference_Schema); ok {
  827. schema.Schema.Description = description
  828. schema.Schema.ReadOnly = outputOnly
  829. schema.Schema.WriteOnly = inputOnly
  830. // Merge any `Property` annotations with the current
  831. extProperty := proto.GetExtension(field.Desc.Options(), v3.E_Property)
  832. if extProperty != nil {
  833. proto.Merge(schema.Schema, extProperty.(*v3.Schema))
  834. }
  835. }
  836. definitionProperties.AdditionalProperties = append(
  837. definitionProperties.AdditionalProperties,
  838. &v3.NamedSchemaOrReference{
  839. Name: g.reflect.formatFieldName(field.Desc),
  840. Value: fieldSchema,
  841. },
  842. )
  843. }
  844. schema := &v3.Schema{
  845. Type: "object",
  846. Description: messageDescription,
  847. Properties: definitionProperties,
  848. Required: required,
  849. }
  850. // Merge any `Schema` annotations with the current
  851. extSchema := proto.GetExtension(message.Desc.Options(), v3.E_Schema)
  852. if extSchema != nil {
  853. proto.Merge(schema, extSchema.(*v3.Schema))
  854. }
  855. // Add the schema to the components.schema list.
  856. g.addSchemaToDocumentV3(d, &v3.NamedSchemaOrReference{
  857. Name: schemaName,
  858. Value: &v3.SchemaOrReference{
  859. Oneof: &v3.SchemaOrReference_Schema{
  860. Schema: schema,
  861. },
  862. },
  863. })
  864. }
  865. }