-
Notifications
You must be signed in to change notification settings - Fork 232
/
api.go
375 lines (327 loc) · 10.2 KB
/
api.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
package api
import (
"fmt"
"go/ast"
"go/token"
"strings"
"sync"
"golang.org/x/exp/slices"
"encr.dev/pkg/errors"
"encr.dev/pkg/option"
"encr.dev/v2/internals/perr"
"encr.dev/v2/internals/pkginfo"
"encr.dev/v2/internals/resourcepaths"
"encr.dev/v2/internals/schema"
"encr.dev/v2/internals/schema/schemautil"
"encr.dev/v2/parser/apis/api/apienc"
"encr.dev/v2/parser/apis/internal/directive"
"encr.dev/v2/parser/apis/selector"
"encr.dev/v2/parser/resource"
)
type AccessType string
const (
Public AccessType = "public"
Private AccessType = "private"
// Auth is like public but requires authentication.
Auth AccessType = "auth"
)
type Endpoint struct {
errs *perr.List
Name string
Doc string
File *pkginfo.File
Decl *schema.FuncDecl
Access AccessType
AccessField option.Option[directive.Field]
Raw bool
Path *resourcepaths.Path
HTTPMethods []string
Request schema.Type // request data; nil for Raw Endpoints
Response schema.Type // response data; nil for Raw Endpoints
Tags selector.Set
Recv option.Option[*schema.Receiver] // None if not a method
reqEncOnce sync.Once
reqEncoding []*apienc.RequestEncoding
respEncOnce sync.Once
respEncoding *apienc.ResponseEncoding
}
func (ep *Endpoint) GoString() string {
if ep == nil {
return "(*api.Endpoint)(nil)"
}
return fmt.Sprintf("&api.Endpoint{Name: %q}", ep.Name)
}
func (ep *Endpoint) Kind() resource.Kind { return resource.APIEndpoint }
func (ep *Endpoint) Package() *pkginfo.Package { return ep.File.Pkg }
func (ep *Endpoint) Pos() token.Pos { return ep.Decl.AST.Pos() }
func (ep *Endpoint) End() token.Pos { return ep.Decl.AST.End() }
func (ep *Endpoint) SortKey() string { return ep.File.Pkg.ImportPath.String() + "." + ep.Name }
func (ep *Endpoint) RequestEncoding() []*apienc.RequestEncoding {
ep.reqEncOnce.Do(func() {
ep.reqEncoding = apienc.DescribeRequest(ep.errs, ep.Request, ep.HTTPMethods...)
})
return ep.reqEncoding
}
func (ep *Endpoint) ResponseEncoding() *apienc.ResponseEncoding {
ep.respEncOnce.Do(func() {
ep.respEncoding = apienc.DescribeResponse(ep.errs, ep.Response)
})
return ep.respEncoding
}
type ParseData struct {
Errs *perr.List
Schema *schema.Parser
File *pkginfo.File
Func *ast.FuncDecl
Dir *directive.Directive
Doc string
}
// Parse parses an API endpoint. It may return nil on errors.
func Parse(d ParseData) *Endpoint {
rpc, ok := validateDirective(d.Errs, d.Dir)
if !ok {
return nil
}
rpc.errs = d.Errs
// If there was no path, default to "pkg.Decl".
if rpc.Path == nil {
rpc.Path = &resourcepaths.Path{
StartPos: d.Func.Name.Pos(),
Segments: []resourcepaths.Segment{{
Type: resourcepaths.Literal,
Value: d.File.Pkg.Name + "." + d.Func.Name.Name,
ValueType: schema.String,
StartPos: d.Func.Name.Pos(),
EndPos: d.Func.Name.End(),
}},
}
}
decl, ok := d.Schema.ParseFuncDecl(d.File, d.Func)
if !ok {
return nil
}
rpc.Name = d.Func.Name.Name
rpc.Doc = d.Doc
rpc.Decl = decl
rpc.File = d.File
rpc.Recv = decl.Recv
// Validate the API.
if rpc.Raw {
initRawRPC(d.Errs, rpc)
} else {
initTypedRPC(d.Errs, rpc)
}
// If we didn't get any HTTP methods, set a reasonable default.
// TODO(andre) Replace this with the API encoding.
if len(rpc.HTTPMethods) == 0 {
if rpc.Raw {
rpc.HTTPMethods = []string{"*"}
} else {
// For non-raw endpoints, if there's a request payload
// default to POST-only.
if rpc.Request != nil {
rpc.HTTPMethods = []string{"POST"}
} else {
rpc.HTTPMethods = []string{"GET", "POST"}
}
}
}
return rpc
}
func initTypedRPC(errs *perr.List, endpoint *Endpoint) {
decl := endpoint.Decl
sig := decl.Type
numParams := len(sig.Params)
if numParams == 0 {
errs.Add(errWrongNumberParams(numParams).AtGoNode(sig.AST.Params))
return
}
numResults := len(sig.Results)
if numResults == 0 || numResults > 2 {
errs.Add(errWrongNumberResults(numResults).AtGoNode(sig.AST.Results))
return
}
// First type should always be context.Context
ctxParam := sig.Params[0]
if !schemautil.IsNamed(ctxParam.Type, "context", "Context") {
errs.Add(errInvalidFirstParam.AtGoNode(ctxParam.AST))
return
}
// For each path parameter, expect a parameter to match it
var pathParams []*resourcepaths.Segment
for i := 0; i < len(endpoint.Path.Segments); i++ {
if s := &endpoint.Path.Segments[i]; s.Type != resourcepaths.Literal {
pathParams = append(pathParams, s)
}
}
seenParams := 0
for i := 0; i < numParams-1; i++ {
param := sig.Params[i+1] // +1 to skip context.Context
// Is it a path parameter?
if i < len(pathParams) {
seg := pathParams[i]
b := validatePathParam(errs, param, seg)
pathParams[seenParams].ValueType = b
seenParams++
} else {
// Otherwise it must be a payload parameter
payloadIdx := i - len(pathParams)
if payloadIdx > 0 {
errs.Add(errMultiplePayloads.AtGoNode(param.AST))
continue
}
endpoint.Request = param.Type
}
}
if seenParams < len(pathParams) {
var missing []string
var missingParams []*resourcepaths.Segment
for i := seenParams; i < len(pathParams); i++ {
missing = append(missing, pathParams[i].Value)
missingParams = append(missingParams, pathParams[i])
}
err := errInvalidPathParams(strings.Join(missing, "', '")).AtGoNode(sig.AST.Params)
for _, p := range missingParams {
err = err.AtGoNode(p)
}
errs.Add(err)
}
// First return value must be *T or *pkg.T
if numResults >= 2 {
result := sig.Results[0]
endpoint.Response = result.Type
}
// Make sure the last return is of type error.
if err := sig.Results[numResults-1]; !schemautil.IsBuiltinKind(err.Type, schema.Error) {
errs.Add(errLastResultMustBeError.AtGoNode(err.AST))
return
}
}
func initRawRPC(errs *perr.List, endpoint *Endpoint) {
decl := endpoint.Decl
sig := decl.Type
params := sig.Params
if len(params) < 2 {
errs.Add(errInvalidRawParams(len(params)).AtGoNode(sig.AST.Params))
return
} else if len(params) > 2 {
errs.Add(errInvalidRawParams(len(params)).AtGoNode(sig.AST.Params))
} else if len(sig.Results) > 0 {
errs.Add(errInvalidRawResults(len(sig.Results)).AtGoNode(sig.AST.Results))
return
}
// Ensure signature is func(http.ResponseWriter, *http.Request).
if !schemautil.IsNamed(params[0].Type, "net/http", "ResponseWriter") {
errs.Add(errRawNotResponeWriter.AtGoNode(params[0].AST))
}
if deref, n := schemautil.Deref(params[1].Type); n != 1 || !schemautil.IsNamed(deref, "net/http", "Request") {
errs.Add(errRawNotRequest.AtGoNode(params[1].AST))
}
}
// validatePathParam validates that the given func parameter is compatible with the given path segment.
// It checks that the names match and that the func parameter is of a permissible type.
// It returns the func parameter's builtin kind.
func validatePathParam(errs *perr.List, param schema.Param, seg *resourcepaths.Segment) schema.BuiltinKind {
if !option.Contains(param.Name, seg.Value) {
errs.Add(errUnexpectedParameterName(param.Name, seg.Value, seg.String()).AtGoNode(seg).AtGoNode(param.AST))
}
builtin, _ := param.Type.(schema.BuiltinType)
b := builtin.Kind
// Wildcard path parameters must be strings.
if b != schema.String && (seg.Type == resourcepaths.Wildcard || seg.Type == resourcepaths.Fallback) {
errs.Add(errWildcardMustBeString(param.Name).AtGoNode(seg).AtGoNode(param.AST))
}
switch b {
case schema.String, schema.Bool,
schema.Int, schema.Int8, schema.Int16, schema.Int32, schema.Int64,
schema.Uint, schema.Uint8, schema.Uint16, schema.Uint32, schema.Uint64,
schema.UUID:
return b
default:
errs.Add(errInvalidPathParamType(param.Name).AtGoNode(seg).AtGoNode(param.AST))
return schema.Invalid
}
}
// validateDirective validates the given encore:api directive
// and returns an API with the respective fields set.
func validateDirective(errs *perr.List, dir *directive.Directive) (*Endpoint, bool) {
endpoint := &Endpoint{
Raw: dir.HasOption("raw"),
}
var accessField directive.Field
var rawTag directive.Field
accessOptions := []string{"public", "private", "auth"}
ok := directive.Validate(errs, dir, directive.ValidateSpec{
AllowedOptions: append([]string{"raw"}, accessOptions...),
AllowedFields: []string{"path", "method"},
ValidateOption: func(errs *perr.List, opt directive.Field) (ok bool) {
// If this is an access option, check for duplicates.
if slices.Contains(accessOptions, opt.Value) {
if endpoint.Access != "" {
errs.Add(errDuplicateAccessOptions(endpoint.Access, opt.Value, strings.Join(accessOptions, ", ")).AtGoNode(opt).AtGoNode(accessField))
return false
}
accessField = opt
endpoint.Access = AccessType(opt.Value)
endpoint.AccessField = option.Some(opt)
}
if opt.Value == "raw" {
rawTag = opt
}
return true
},
ValidateField: func(errs *perr.List, f directive.Field) (ok bool) {
switch f.Key {
case "path":
endpoint.Path, ok = resourcepaths.Parse(
errs,
f.End()-token.Pos(len([]byte(f.Value))-1),
f.Value,
resourcepaths.Options{
AllowWildcard: true,
AllowFallback: true,
PrefixSlash: true,
},
)
if !ok {
return false
}
case "method":
endpoint.HTTPMethods = f.List()
for _, m := range endpoint.HTTPMethods {
for _, c := range m {
if !(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z') {
errs.Add(errInvalidEndpointMethod(m).AtGoNode(f))
return false
} else if !(c >= 'A' && c <= 'Z') {
errs.Add(errEndpointMethodMustBeAllCaps.AtGoNode(f))
return false
}
}
}
}
return true
},
ValidateTag: func(errs *perr.List, tag directive.Field) (ok bool) {
sel, ok := selector.Parse(errs, tag.Pos(), tag.Value)
if !ok {
return false
}
endpoint.Tags.Add(sel)
return true
},
})
if !ok {
return nil, false
}
// Access defaults to private if not provided.
if endpoint.Access == "" {
endpoint.Access = Private
}
if endpoint.Access == Private && endpoint.Raw {
// We don't support private raw APIs for now.
errs.Add(errRawEndpointCantBePrivate.AtGoNode(rawTag, errors.AsError("declared as raw here")).AtGoNode(accessField, errors.AsError("set as private here")))
return nil, false
}
return endpoint, true
}