/
openapi.go
381 lines (337 loc) · 9.18 KB
/
openapi.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
package openapi
import (
"encoding/json"
"fmt"
"go/doc/comment"
"strings"
"github.com/cockroachdb/errors"
"github.com/getkin/kin-openapi/openapi3"
"encr.dev/internal/clientgen/clientgentypes"
"encr.dev/parser/encoding"
meta "encr.dev/proto/encore/parser/meta/v1"
)
type GenVersion int
const (
// Initial is the originally released OpenAPI client generator
Initial GenVersion = iota
// Experimental can be used to lock experimental or uncompleted features in the generated code
// It should always be the last item in the enum.
Experimental
LatestVersion GenVersion = Experimental - 1
)
type Generator struct {
ver GenVersion
spec *openapi3.T
md *meta.Data
seenDecls map[string]uint32
}
func New(version GenVersion) *Generator {
return &Generator{
ver: version,
seenDecls: make(map[string]uint32),
}
}
func (g *Generator) Version() int {
return int(g.ver)
}
func (g *Generator) Generate(p clientgentypes.GenerateParams) (err error) {
defer func() {
if r := recover(); r != nil {
if b, ok := r.(bailout); ok {
err = b.err
} else {
panic(r)
}
}
}()
g.md = p.Meta
g.spec = newSpec(p.AppSlug)
for _, svc := range p.Meta.Svcs {
if p.Services.Has(svc.Name) {
if err := g.addService(svc); err != nil {
return err
}
}
}
out, err := g.spec.MarshalJSON()
if err != nil {
return errors.Wrap(err, "marshal openapi spec")
}
// Pretty-print the JSON output
return json.Indent(p.Buf, out, "", " ")
}
func (g *Generator) addService(svc *meta.Service) error {
for _, rpc := range svc.Rpcs {
if err := g.addRPC(rpc); err != nil {
return err
}
}
return nil
}
func (g *Generator) addRPC(rpc *meta.RPC) error {
item := g.getOrCreatePath(rpc)
encodings, err := encoding.DescribeRPC(g.md, rpc, &encoding.Options{})
if err != nil {
return errors.Wrapf(err, "describe rpc %s.%s", rpc.ServiceName, rpc.Name)
}
for _, reqEnc := range encodings.RequestEncoding {
for _, m := range reqEnc.HTTPMethods {
op, err := g.newOperationForEncoding(rpc, m, reqEnc, encodings.ResponseEncoding)
if err != nil {
return errors.Wrapf(err, "create operation for rpc %s.%s", rpc.ServiceName, rpc.Name)
}
item.SetOperation(m, op)
}
}
g.spec.Paths[rpcPath(rpc)] = item
return nil
}
func (g *Generator) getOrCreatePath(rpc *meta.RPC) *openapi3.PathItem {
path := rpcPath(rpc)
if existing, ok := g.spec.Paths[path]; ok {
return existing
}
item := &openapi3.PathItem{}
g.spec.Paths[path] = item
return item
}
func (g *Generator) newOperationForEncoding(rpc *meta.RPC, method string, reqEnc *encoding.RequestEncoding, respEnc *encoding.ResponseEncoding) (*openapi3.Operation, error) {
summary, desc := "", ""
if rpc.Doc != nil {
summary, desc = splitDoc(*rpc.Doc)
}
op := &openapi3.Operation{
Summary: summary,
Description: desc,
OperationID: method + ":" + rpc.ServiceName + "." + rpc.Name,
Responses: make(openapi3.Responses),
}
// Add path parameters
for _, seg := range rpc.Path.Segments {
if seg.Type == meta.PathSegment_LITERAL {
continue
}
op.Parameters = append(op.Parameters, &openapi3.ParameterRef{
Value: &openapi3.Parameter{
Name: seg.Value,
In: openapi3.ParameterInPath,
Description: "",
Style: openapi3.SerializationSimple,
Explode: ptr(false),
AllowEmptyValue: true,
AllowReserved: false,
Deprecated: false,
Required: true,
Schema: g.pathParamType(seg.ValueType).NewRef(),
Example: nil,
Examples: nil,
Content: nil,
},
})
}
// Add header parameters
for _, param := range reqEnc.HeaderParameters {
op.Parameters = append(op.Parameters, &openapi3.ParameterRef{
Value: &openapi3.Parameter{
Name: param.WireFormat,
In: openapi3.ParameterInHeader,
Description: markdownDoc(param.Doc),
Style: openapi3.SerializationSimple,
Explode: ptr(true),
AllowEmptyValue: true,
AllowReserved: false,
Deprecated: false,
Required: !param.Optional,
Schema: g.schemaType(param.Type),
Example: nil,
Examples: nil,
Content: nil,
},
})
}
// Add query parameters
for _, param := range reqEnc.QueryParameters {
op.Parameters = append(op.Parameters, &openapi3.ParameterRef{
Value: &openapi3.Parameter{
Name: param.WireFormat,
In: openapi3.ParameterInQuery,
Description: markdownDoc(param.Doc),
Style: openapi3.SerializationForm,
Explode: ptr(true),
AllowEmptyValue: true,
AllowReserved: false,
Deprecated: false,
Required: !param.Optional,
Schema: g.schemaType(param.Type),
Example: nil,
Examples: nil,
Content: nil,
},
})
}
// Add request body
if len(reqEnc.BodyParameters) > 0 {
op.RequestBody = &openapi3.RequestBodyRef{
Value: &openapi3.RequestBody{
Description: "",
Required: false,
Content: g.bodyContent(reqEnc.BodyParameters),
},
}
}
// Encode the response
{
resp := &openapi3.Response{
Headers: make(openapi3.Headers),
Links: nil,
Description: ptr("Success response"),
}
if respEnc != nil {
for _, param := range respEnc.HeaderParameters {
resp.Headers[param.WireFormat] = &openapi3.HeaderRef{
Value: &openapi3.Header{Parameter: openapi3.Parameter{
Description: markdownDoc(param.Doc),
Style: openapi3.SerializationSimple,
Explode: ptr(true),
AllowEmptyValue: true,
AllowReserved: false,
Deprecated: false,
Required: !param.Optional,
Schema: g.schemaType(param.Type),
Example: nil,
Examples: nil,
Content: nil,
}},
}
}
if len(respEnc.BodyParameters) > 0 {
resp.Content = g.bodyContent(respEnc.BodyParameters)
}
}
op.Responses["200"] = &openapi3.ResponseRef{
Value: resp,
}
op.Responses["default"] = &openapi3.ResponseRef{
Ref: "#/components/responses/APIError",
}
}
return op, nil
}
func rpcPath(rpc *meta.RPC) string {
var b strings.Builder
for _, seg := range rpc.Path.Segments {
b.WriteString("/")
switch seg.Type {
case meta.PathSegment_LITERAL:
b.WriteString(seg.Value)
default:
b.WriteString("{")
b.WriteString(seg.Value)
b.WriteString("}")
}
}
return b.String()
}
func splitDoc(doc string) (plaintextSummary, markdownDescription string) {
firstLine, remaining := doc, ""
if idx := strings.Index(doc, "\n"); idx >= 0 {
firstLine = doc[:idx]
remaining = doc[idx+1:]
}
return plaintextDoc(firstLine), markdownDoc(remaining)
}
func plaintextDoc(doc string) string {
var parser comment.Parser
var pr comment.Printer
d := parser.Parse(doc)
return string(pr.Text(d))
}
func markdownDoc(doc string) string {
var parser comment.Parser
var pr comment.Printer
d := parser.Parse(doc)
return string(pr.Markdown(d))
}
func ptr[T any](t T) *T {
return &t
}
func newSpec(appSlug string) *openapi3.T {
t := &openapi3.T{
Components: &openapi3.Components{
RequestBodies: make(map[string]*openapi3.RequestBodyRef),
Responses: make(map[string]*openapi3.ResponseRef),
SecuritySchemes: make(map[string]*openapi3.SecuritySchemeRef),
Schemas: make(map[string]*openapi3.SchemaRef),
},
Info: &openapi3.Info{
Title: fmt.Sprintf("API for %s", appSlug),
Description: "Generated by encore",
Version: "1",
Extensions: map[string]any{
"x-logo": map[string]string{
"url": "https://encore.dev/assets/branding/logo/logo-black.png",
"backgroundColor": "#EEEEE1",
"altText": "Encore logo",
},
},
},
OpenAPI: "3.0.0",
Paths: make(openapi3.Paths),
}
// Add the local platform server:
t.AddServer(
&openapi3.Server{
URL: "http://localhost:4000",
Description: "Encore local dev environment",
},
)
t.Components.Responses["APIError"] = &openapi3.ResponseRef{
Value: &openapi3.Response{
Content: openapi3.Content{
"application/json": &openapi3.MediaType{
Schema: &openapi3.SchemaRef{
Value: &openapi3.Schema{
Type: openapi3.TypeObject,
Title: "APIError",
ExternalDocs: &openapi3.ExternalDocs{
URL: "https://pkg.go.dev/encore.dev/beta/errs#Error",
},
Properties: map[string]*openapi3.SchemaRef{
"code": {
Value: &openapi3.Schema{
Description: "Error code",
Example: "not_found",
Type: openapi3.TypeString,
ExternalDocs: &openapi3.ExternalDocs{
URL: "https://pkg.go.dev/encore.dev/beta/errs#ErrCode",
},
},
},
"message": {
Value: &openapi3.Schema{
Description: "Error message",
Type: openapi3.TypeString,
},
},
"details": {
Value: &openapi3.Schema{
Description: "Error details",
Type: openapi3.TypeObject,
},
},
},
},
},
},
},
Description: ptr("Error response"),
},
}
return t
}
type bailout struct {
err error
}
func doBailout(err error) {
panic(bailout{err})
}