generator.go 29 KB

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