-
Notifications
You must be signed in to change notification settings - Fork 556
/
handler.go
395 lines (355 loc) · 11.2 KB
/
handler.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package lambda
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil" // nolint:staticcheck
"reflect"
"strings"
"github.com/aws/aws-lambda-go/lambda/handlertrace"
)
type Handler interface {
Invoke(ctx context.Context, payload []byte) ([]byte, error)
}
type handlerOptions struct {
handlerFunc
baseContext context.Context
contextValues map[interface{}]interface{}
jsonRequestUseNumber bool
jsonRequestDisallowUnknownFields bool
jsonResponseEscapeHTML bool
jsonResponseIndentPrefix string
jsonResponseIndentValue string
enableSIGTERM bool
sigtermCallbacks []func()
}
type Option func(*handlerOptions)
// WithContext is a HandlerOption that sets the base context for all invocations of the handler.
//
// Usage:
//
// lambda.StartWithOptions(
// func (ctx context.Context) (string, error) {
// return ctx.Value("foo"), nil
// },
// lambda.WithContext(context.WithValue(context.Background(), "foo", "bar"))
// )
func WithContext(ctx context.Context) Option {
return Option(func(h *handlerOptions) {
h.baseContext = ctx
})
}
// WithContextValue adds a value to the handler context.
// If a base context was set using WithContext, that base is used as the parent.
//
// Usage:
//
// lambda.StartWithOptions(
// func (ctx context.Context) (string, error) {
// return ctx.Value("foo"), nil
// },
// lambda.WithContextValue("foo", "bar")
// )
func WithContextValue(key interface{}, value interface{}) Option {
return Option(func(h *handlerOptions) {
h.contextValues[key] = value
})
}
// WithSetEscapeHTML sets the SetEscapeHTML argument on the underlying json encoder
//
// Usage:
//
// lambda.StartWithOptions(
// func () (string, error) {
// return "<html><body>hello!></body></html>", nil
// },
// lambda.WithSetEscapeHTML(true),
// )
func WithSetEscapeHTML(escapeHTML bool) Option {
return Option(func(h *handlerOptions) {
h.jsonResponseEscapeHTML = escapeHTML
})
}
// WithSetIndent sets the SetIndent argument on the underling json encoder
//
// Usage:
//
// lambda.StartWithOptions(
// func (event any) (any, error) {
// return event, nil
// },
// lambda.WithSetIndent(">"," "),
// )
func WithSetIndent(prefix, indent string) Option {
return Option(func(h *handlerOptions) {
h.jsonResponseIndentPrefix = prefix
h.jsonResponseIndentValue = indent
})
}
// WithUseNumber sets the UseNumber option on the underlying json decoder
//
// Usage:
//
// lambda.StartWithOptions(
// func (event any) (any, error) {
// return event, nil
// },
// lambda.WithUseNumber(true)
// )
func WithUseNumber(useNumber bool) Option {
return Option(func(h *handlerOptions) {
h.jsonRequestUseNumber = useNumber
})
}
// WithUseNumber sets the DisallowUnknownFields option on the underlying json decoder
//
// Usage:
//
// lambda.StartWithOptions(
// func (event any) (any, error) {
// return event, nil
// },
// lambda.WithDisallowUnknownFields(true)
// )
func WithDisallowUnknownFields(disallowUnknownFields bool) Option {
return Option(func(h *handlerOptions) {
h.jsonRequestDisallowUnknownFields = disallowUnknownFields
})
}
// WithEnableSIGTERM enables SIGTERM behavior within the Lambda platform on container spindown.
// SIGKILL will occur ~500ms after SIGTERM.
// Optionally, an array of callback functions to run on SIGTERM may be provided.
//
// Usage:
//
// lambda.StartWithOptions(
// func (event any) (any, error) {
// return event, nil
// },
// lambda.WithEnableSIGTERM(func() {
// log.Print("function container shutting down...")
// })
// )
func WithEnableSIGTERM(callbacks ...func()) Option {
return Option(func(h *handlerOptions) {
h.sigtermCallbacks = append(h.sigtermCallbacks, callbacks...)
h.enableSIGTERM = true
})
}
// handlerTakesContext returns whether the handler takes a context.Context as its first argument.
func handlerTakesContext(handler reflect.Type) (bool, error) {
switch handler.NumIn() {
case 0:
return false, nil
case 1:
contextType := reflect.TypeOf((*context.Context)(nil)).Elem()
argumentType := handler.In(0)
if argumentType.Kind() != reflect.Interface {
return false, nil
}
// handlers like func(event any) are valid.
if argumentType.NumMethod() == 0 {
return false, nil
}
if !contextType.Implements(argumentType) || !argumentType.Implements(contextType) {
return false, fmt.Errorf("handler takes an interface, but it is not context.Context: %q", argumentType.Name())
}
return true, nil
case 2:
contextType := reflect.TypeOf((*context.Context)(nil)).Elem()
argumentType := handler.In(0)
if argumentType.Kind() != reflect.Interface || !contextType.Implements(argumentType) || !argumentType.Implements(contextType) {
return false, fmt.Errorf("handler takes two arguments, but the first is not Context. got %s", argumentType.Kind())
}
return true, nil
}
return false, fmt.Errorf("handlers may not take more than two arguments, but handler takes %d", handler.NumIn())
}
func validateReturns(handler reflect.Type) error {
errorType := reflect.TypeOf((*error)(nil)).Elem()
switch n := handler.NumOut(); {
case n > 2:
return fmt.Errorf("handler may not return more than two values")
case n > 1:
if !handler.Out(1).Implements(errorType) {
return fmt.Errorf("handler returns two values, but the second does not implement error")
}
case n == 1:
if !handler.Out(0).Implements(errorType) {
return fmt.Errorf("handler returns a single value, but it does not implement error")
}
}
return nil
}
// NewHandler creates a base lambda handler from the given handler function. The
// returned Handler performs JSON serialization and deserialization, and
// delegates to the input handler function. The handler function parameter must
// satisfy the rules documented by Start. If handlerFunc is not a valid
// handler, the returned Handler simply reports the validation error.
func NewHandler(handlerFunc interface{}) Handler {
return NewHandlerWithOptions(handlerFunc)
}
// NewHandlerWithOptions creates a base lambda handler from the given handler function. The
// returned Handler performs JSON serialization and deserialization, and
// delegates to the input handler function. The handler function parameter must
// satisfy the rules documented by Start. If handlerFunc is not a valid
// handler, the returned Handler simply reports the validation error.
func NewHandlerWithOptions(handlerFunc interface{}, options ...Option) Handler {
return newHandler(handlerFunc, options...)
}
func newHandler(handlerFunc interface{}, options ...Option) *handlerOptions {
if h, ok := handlerFunc.(*handlerOptions); ok {
return h
}
h := &handlerOptions{
baseContext: context.Background(),
contextValues: map[interface{}]interface{}{},
jsonResponseEscapeHTML: false,
jsonResponseIndentPrefix: "",
jsonResponseIndentValue: "",
}
for _, option := range options {
option(h)
}
for k, v := range h.contextValues {
h.baseContext = context.WithValue(h.baseContext, k, v)
}
if h.enableSIGTERM {
enableSIGTERM(h.sigtermCallbacks)
}
h.handlerFunc = reflectHandler(handlerFunc, h)
return h
}
type handlerFunc func(context.Context, []byte) (io.Reader, error)
// back-compat for the rpc mode
func (h handlerFunc) Invoke(ctx context.Context, payload []byte) ([]byte, error) {
response, err := h(ctx, payload)
if err != nil {
return nil, err
}
// if the response needs to be closed (ex: net.Conn, os.File), ensure it's closed before the next invoke to prevent a resource leak
if response, ok := response.(io.Closer); ok {
defer response.Close()
}
// optimization: if the response is a *bytes.Buffer, a copy can be eliminated
switch response := response.(type) {
case *jsonOutBuffer:
return response.Bytes(), nil
case *bytes.Buffer:
return response.Bytes(), nil
}
b, err := ioutil.ReadAll(response)
if err != nil {
return nil, err
}
return b, nil
}
func errorHandler(err error) handlerFunc {
return func(_ context.Context, _ []byte) (io.Reader, error) {
return nil, err
}
}
type jsonOutBuffer struct {
*bytes.Buffer
}
func (j *jsonOutBuffer) ContentType() string {
return contentTypeJSON
}
func reflectHandler(f interface{}, h *handlerOptions) handlerFunc {
if f == nil {
return errorHandler(errors.New("handler is nil"))
}
// back-compat: types with reciever `Invoke(context.Context, []byte) ([]byte, error)` need the return bytes wrapped
if handler, ok := f.(Handler); ok {
return func(ctx context.Context, payload []byte) (io.Reader, error) {
b, err := handler.Invoke(ctx, payload)
if err != nil {
return nil, err
}
return bytes.NewBuffer(b), nil
}
}
handler := reflect.ValueOf(f)
handlerType := reflect.TypeOf(f)
if handlerType.Kind() != reflect.Func {
return errorHandler(fmt.Errorf("handler kind %s is not %s", handlerType.Kind(), reflect.Func))
}
takesContext, err := handlerTakesContext(handlerType)
if err != nil {
return errorHandler(err)
}
if err := validateReturns(handlerType); err != nil {
return errorHandler(err)
}
out := &jsonOutBuffer{bytes.NewBuffer(nil)}
return func(ctx context.Context, payload []byte) (io.Reader, error) {
out.Reset()
in := bytes.NewBuffer(payload)
decoder := json.NewDecoder(in)
if h.jsonRequestUseNumber {
decoder.UseNumber()
}
if h.jsonRequestDisallowUnknownFields {
decoder.DisallowUnknownFields()
}
encoder := json.NewEncoder(out)
encoder.SetEscapeHTML(h.jsonResponseEscapeHTML)
encoder.SetIndent(h.jsonResponseIndentPrefix, h.jsonResponseIndentValue)
trace := handlertrace.FromContext(ctx)
// construct arguments
var args []reflect.Value
if takesContext {
args = append(args, reflect.ValueOf(ctx))
}
if (handlerType.NumIn() == 1 && !takesContext) || handlerType.NumIn() == 2 {
eventType := handlerType.In(handlerType.NumIn() - 1)
event := reflect.New(eventType)
if err := decoder.Decode(event.Interface()); err != nil {
return nil, err
}
if nil != trace.RequestEvent {
trace.RequestEvent(ctx, event.Elem().Interface())
}
args = append(args, event.Elem())
}
response := handler.Call(args)
// return the error, if any
if len(response) > 0 {
if errVal, ok := response[len(response)-1].Interface().(error); ok && errVal != nil {
return nil, errVal
}
}
// set the response value, if any
var val interface{}
if len(response) > 1 {
val = response[0].Interface()
if nil != trace.ResponseEvent {
trace.ResponseEvent(ctx, val)
}
}
// encode to JSON
if err := encoder.Encode(val); err != nil {
// if response is not JSON serializable, but the response type is a reader, return it as-is
if reader, ok := val.(io.Reader); ok {
return reader, nil
}
return nil, err
}
// if response value is an io.Reader, return it as-is
if reader, ok := val.(io.Reader); ok {
// back-compat, don't return the reader if the value serialized to a non-empty json
if strings.HasPrefix(out.String(), "{}") {
return reader, nil
}
}
// back-compat, strip the encoder's trailing newline unless WithSetIndent was used
if h.jsonResponseIndentValue == "" && h.jsonResponseIndentPrefix == "" {
out.Truncate(out.Len() - 1)
}
return out, nil
}
}