-
Notifications
You must be signed in to change notification settings - Fork 272
/
request.go
324 lines (286 loc) · 9.89 KB
/
request.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
package endpointgen
import (
"fmt"
"strings"
. "github.com/dave/jennifer/jen"
"encr.dev/v2/codegen/apigen/apigenutil"
"encr.dev/v2/codegen/internal/genutil"
"encr.dev/v2/internals/resourcepaths"
"encr.dev/v2/internals/schema"
"encr.dev/v2/internals/schema/schemautil"
"encr.dev/v2/parser/apis/api"
"encr.dev/v2/parser/apis/api/apienc"
)
const jsonIterPkg = "github.com/json-iterator/go"
// requestDesc describes the generated request type that contains the combined
// request data + path parameters for the request.
type requestDesc struct {
gu *genutil.Helper
ep *api.Endpoint
}
func (d *requestDesc) TypeName() string {
return "EncoreInternal_" + d.ep.Name + "Req"
}
func (d *requestDesc) Type() *Statement {
return Op("*").Id(d.TypeName())
}
func (d *requestDesc) TypeDecl() *Statement {
return Type().Id(d.TypeName()).StructFunc(func(g *Group) {
if d.ep.Request != nil {
g.Id(d.reqDataPayloadName()).Add(d.gu.Type(d.ep.Request))
}
for i, seg := range d.ep.Path.Params() {
g.Id(d.pathParamFieldName(i)).Add(d.gu.Builtin(d.ep.Decl.AST.Pos(), seg.ValueType))
}
})
}
func (d *requestDesc) DecodeRequest() *Statement {
return Func().Params(
d.httpReqExpr().Op("*").Qual("net/http", "Request"),
d.pathParamsName().Add(apiQ("UnnamedParams")),
Id("json").Qual(jsonIterPkg, "API"),
).Params(
d.reqDataExpr().Add(d.Type()),
Id("pathParams").Add(apiQ("UnnamedParams")),
Err().Error(),
).BlockFunc(func(g *Group) {
g.Add(d.reqDataExpr()).Op("=").New(Id(d.TypeName()))
if d.ep.Path.NumParams() == 0 && d.ep.Request == nil {
// Nothing to do; return an empty struct
g.Return(d.reqDataExpr(), Nil(), Nil())
return
}
dec := d.gu.NewTypeUnmarshaller("dec")
g.Add(dec.Init())
d.renderPathDecoding(g, dec)
d.renderRequestDecoding(g, dec)
g.If(Err().Op(":=").Add(dec.Err()), Err().Op("!=").Nil()).Block(
Return(Nil(), Nil(), Err()),
)
g.Return(d.reqDataExpr(), d.pathParamsName(), Nil())
})
}
// HandlerArgs returns the list of arguments to pass to the handler.
func (d *requestDesc) HandlerArgs() []Code {
numPathParams := d.ep.Path.NumParams()
args := make([]Code, 0, 1+numPathParams)
for i := 0; i < numPathParams; i++ {
args = append(args, d.reqDataPathParamExpr(i))
}
if d.ep.Request != nil {
args = append(args, d.reqDataPayloadExpr())
}
return args
}
// renderPathDecoding renders the code to decode the path parameters.
// The path parameters are accessible via the `pathParamsExpr` parameter.
//
// The generated code writes to the path segment fields in the request struct,
// which is accessed via the `reqDescExpr` parameter.
func (d *requestDesc) renderPathDecoding(g *Group, dec *genutil.TypeUnmarshaller) {
// Collect all the non-literal path segments, and keep track of the wildcard segment, if any.
segs := make([]resourcepaths.Segment, 0, len(d.ep.Path.Segments))
seenWildcard := false
wildcardIdx := 0
for _, s := range d.ep.Path.Segments {
if s.Type != resourcepaths.Literal {
segs = append(segs, s)
}
if !seenWildcard {
if s.Type == resourcepaths.Wildcard {
seenWildcard = true
} else if s.Type == resourcepaths.Param {
wildcardIdx++
}
}
}
if seenWildcard {
g.Comment("Trim the leading slash from wildcard parameter, as Encore's semantics excludes it,")
g.Comment("while the httprouter implementation includes it.")
g.Add(d.pathSegmentValue(wildcardIdx)).Op("=").Qual("strings", "TrimPrefix").Call(
d.pathSegmentValue(wildcardIdx), Lit("/"))
g.Line()
}
// Decode the path params
for segIdx, seg := range segs {
pathSegmentValue := d.pathSegmentValue(segIdx)
// If the segment type is a string, then we want to unescape it.
switch seg.ValueType {
case schema.String, schema.UUID:
g.If(
List(Id("value"), Err()).Op(":=").Qual("net/url", "PathUnescape").Call(pathSegmentValue),
Err().Op("==").Nil().Block(
d.pathSegmentValue(segIdx).Op("=").Id("value"),
),
)
}
g.Do(func(s *Statement) {
// If it's a raw endpoint the params are not used, but validate them regardless.
if d.ep.Raw {
s.Id("_").Op("=")
} else {
s.Add(d.reqDataPathParamExpr(segIdx).Op("="))
}
}).Add(dec.UnmarshalBuiltin(seg.ValueType, seg.Value, pathSegmentValue, true))
}
}
// httpReqExpr returns an expression to access the HTTP request variable
func (d *requestDesc) httpReqExpr() *Statement {
return Id("httpReq")
}
// reqDataExpr returns the expression to access the reqData variable.
func (d *requestDesc) reqDataExpr() *Statement {
return Id("reqData")
}
// reqDataPayloadName returns the name of the payload field in the reqData struct.
func (d *requestDesc) reqDataPayloadName() string {
return "Payload"
}
// reqDataPayloadExpr returns an expression for accessing the payload
// in the reqData variable.
func (d *requestDesc) reqDataPayloadExpr() *Statement {
return d.reqDataExpr().Dot(d.reqDataPayloadName())
}
// reqDataPathParamExpr returns an expression for accessing the i'th path parameter
// in the reqData variable.
func (d *requestDesc) reqDataPathParamExpr(i int) *Statement {
return d.reqDataExpr().Dot(d.pathParamFieldName(i))
}
// reqDataPathParamName returns the field name for the i'th path parameter
// in the reqData struct.
func (d *requestDesc) pathParamFieldName(i int) string {
return fmt.Sprintf("P%d", i)
}
// pathParamsName renders an expression for the name of the path parameters.
func (d *requestDesc) pathParamsName() *Statement {
return Id("ps")
}
// pathSegmentValue renders an expression to retrieve the value (as a string) of the i'th path segment.
func (d *requestDesc) pathSegmentValue(i int) *Statement {
return d.pathParamsName().Index(Lit(i))
}
func (d *requestDesc) renderRequestDecoding(g *Group, dec *genutil.TypeUnmarshaller) {
if d.ep.Request == nil {
return
}
if schemautil.IsPointer(d.ep.Request) {
g.Id("params").Op(":=").Add(d.gu.Initialize(d.ep.Request))
g.Add(d.reqDataPayloadExpr()).Op("=").Id("params")
} else {
g.Id("params").Op(":=").Op("&").Add(d.reqDataPayloadExpr())
}
// Parsing requests for HTTP methods without a body (GET, HEAD, DELETE) are handled by parsing the query string,
// while other methods are parsed by reading the body and unmarshalling it as JSON.
// If the same endpoint supports both, handle it with a switch.
reqs := apienc.DescribeRequest(d.gu.Errs, d.ep.Request, d.ep.HTTPMethods...)
g.Add(Switch(Id("m").Op(":=").Add(d.httpReqExpr()).Dot("Method"), Id("m")).BlockFunc(
func(g *Group) {
for _, r := range reqs {
g.CaseFunc(func(g *Group) {
for _, m := range r.HTTPMethods {
g.Lit(m)
}
}).BlockFunc(func(g *Group) {
d.decodeRequestParameters(g, dec, r)
})
}
g.Default().Add(Id("panic").Call(Lit("HTTP method is not supported")))
},
))
}
func (d *requestDesc) decodeRequestParameters(g *Group, dec *genutil.TypeUnmarshaller, req *apienc.RequestEncoding) {
apigenutil.DecodeHeaders(g, d.httpReqExpr(), Id("params"), dec, req.HeaderParameters)
apigenutil.DecodeQuery(g, d.httpReqExpr(), Id("params"), dec, req.QueryParameters)
d.decodeBody(g, dec, req.BodyParameters)
}
func (d *requestDesc) decodeBody(g *Group, dec *genutil.TypeUnmarshaller, params []*apienc.ParameterEncoding) {
if len(params) == 0 {
return
}
g.Comment("Decode request body")
g.Id("payload").Op(":=").Add(dec.ReadBody(d.httpReqExpr().Dot("Body")))
g.Id("iter").Op(":=").Qual(jsonIterPkg, "ParseBytes").Call(Id("json"), Id("payload"))
g.Line()
g.For(Id("iter").Dot("ReadObjectCB").Call(
Func().Params(Id("_").Op("*").Qual(jsonIterPkg, "Iterator"), Id("key").String()).Bool().Block(
Switch(Qual("strings", "ToLower").Call(Id("key"))).BlockFunc(func(g *Group) {
for _, f := range params {
g.Case(Lit(strings.ToLower(f.WireName))).Block(
dec.ParseJSON(f.SrcName, Id("iter"), Op("&").Id("params").Dot(f.SrcName)),
)
}
g.Default().Block(Id("_").Op("=").Id("iter").Dot("SkipAndReturnBytes").Call())
}),
Return(True()),
)).Block(),
)
g.Line()
}
// Clone returns the function literal to clone the request.
func (d *requestDesc) Clone() *Statement {
const recv = "r"
return Func().Params(Id(recv).Add(d.Type())).Params(d.Type(), Error()).BlockFunc(func(g *Group) {
// We could optimize the clone operation if there are no reference types (pointers, maps, slices)
// in the struct. For now, simply serialize it as JSON and back.
g.Var().Id("clone").Add(d.Type())
g.List(Id("bytes"), Id("err")).Op(":=").Qual(jsonIterPkg, "ConfigDefault").Dot("Marshal").Call(Id(recv))
g.If(Err().Op("==").Nil()).Block(
Err().Op("=").Qual(jsonIterPkg, "ConfigDefault").Dot("Unmarshal").Call(Id("bytes"), Op("&").Id("clone")),
)
g.Return(Id("clone"), Err())
})
}
// ReqPath returns the function literal to compute the request path.
func (d *requestDesc) ReqPath() *Statement {
return Func().Params(
d.reqDataExpr().Add(d.Type()),
).Params(
String(),
apiQ("UnnamedParams"),
Error(),
).BlockFunc(func(g *Group) {
pathParams := d.ep.Path.Params()
if len(pathParams) == 0 {
g.Return(Lit(d.ep.Path.String()), Nil(), Nil())
return
}
g.Id("params").Op(":=").Add(apiQ("UnnamedParams")).ValuesFunc(func(g *Group) {
for paramIdx, f := range pathParams {
g.Add(genutil.MarshalBuiltin(f.ValueType, d.reqDataPathParamExpr(paramIdx)))
}
})
// Construct the path as an expression in the form
// "/foo" + params[N].Value + "/bar"
pathExpr := CustomFunc(Options{
Separator: " + ",
}, func(g *Group) {
idx := 0
for _, seg := range d.ep.Path.Segments {
if seg.Type == resourcepaths.Literal {
g.Lit("/" + seg.Value)
} else {
g.Lit("/")
g.Id("params").Index(Lit(idx))
idx++
}
}
})
g.Return(pathExpr, Id("params"), Nil())
})
}
// UserPayload returns the function literal to compute the user payload.
func (d *requestDesc) UserPayload() *Statement {
return Func().Params(
// input
d.reqDataExpr().Add(d.Type()),
).Params(
// output
Any(),
).BlockFunc(func(g *Group) {
if d.ep.Request == nil {
g.Return(Nil())
} else {
g.Return(d.reqDataPayloadExpr())
}
})
}