-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathhandler.go
More file actions
207 lines (188 loc) · 6.81 KB
/
handler.go
File metadata and controls
207 lines (188 loc) · 6.81 KB
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
// Copyright © 2016 Tom Maiaroto <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package framework
import (
"context"
"errors"
"log"
"time"
"github.com/aws/aws-lambda-go/lambda"
"github.com/mitchellh/mapstructure"
"github.com/sirupsen/logrus"
)
// Handlers defines a set of Aegis framework Lambda handlers
type Handlers struct {
Router *Router
Tasker *Tasker
RPCRouter *RPCRouter
S3ObjectRouter *S3ObjectRouter
SESRouter *SESRouter
SQSRouter *SQSRouter
CognitoRouter *CognitoRouter
DefaultHandler DefaultHandler
}
// HandlerDependencies defines dependencies to be injected into each handler
type HandlerDependencies struct {
Services *Services
Log *logrus.Logger
Tracer TraceStrategy
Custom map[string]interface{}
}
// DefaultHandler is used when the message type can't be identified as anything else, completely optional to use
type DefaultHandler func(context.Context, *HandlerDependencies, *map[string]interface{}) (interface{}, error)
// getType will determine which type of event is being sent
func getType(evt map[string]interface{}) string {
// if APIGatewayProxyRequest
if keyInMap("httpMethod", evt) && keyInMap("path", evt) {
return "APIGatewayProxyRequest"
}
// if S3Event or SimpleEmailEvent
if keyInMap("Records", evt) {
records := evt["Records"].([]interface{})
if len(records) > 0 {
// S3
if keyInMap("s3", records[0].(map[string]interface{})) {
return "S3Event"
}
// SES
if keyInMap("ses", records[0].(map[string]interface{})) {
return "SimpleEmailEvent"
}
// SQS
if keyInMap("eventSource", records[0].(map[string]interface{})) {
record := records[0].(map[string]interface{})
if record != nil && record["eventSource"].(string) == "aws:sqs" {
return "SQSEvent"
}
}
}
}
// The convention will be that tasks are named with a `_taskName` key.
// This is known as an "AegisTask" and gets handled by Tasker.
if keyInMap("_taskName", evt) {
return "AegisTask"
}
if keyInMap("_rpcName", evt) {
return "AegisRPC"
}
// if Cognito trigger
if keyInMap("userPoolId", evt) && keyInMap("triggerSource", evt) {
return "CognitoTrigger"
}
// if CognitoEvent
if keyInMap("identityPoolId", evt) && keyInMap("datasetRecords", evt) {
return "CognitoEvent"
}
return ""
}
// keyInMap will simply check for the existence of a key in a given map
func keyInMap(k string, m map[string]interface{}) bool {
if _, ok := m[k]; ok {
return true
}
return false
}
// eventHandler is a general handler that accepts an interface and determines which hanlder to use based on the event.
// See: https://godoc.org/github.com/aws/aws-lambda-go/lambda#Start
func (h *Handlers) eventHandler(ctx context.Context, d *HandlerDependencies, evt map[string]interface{}) (interface{}, error) {
// log.Println("Determining type of event for:", evt)
var err error
// TODO: This isn't exactly reflection, it's a map.
// But we do need to look at the signature to make a determination.
evtType := getType(evt)
// log.Println("Incoming Lambda event type: ", evtType)
switch evtType {
case "APIGatewayProxyRequest":
var e APIGatewayProxyRequest
// The event contains no time/date, should decode just fine
err = mapstructure.Decode(evt, &e)
if err == nil {
return h.Router.LambdaHandler(ctx, d, e)
}
log.Println("Could not decode APIGatewayProxyRequest event", err)
case "AegisTask":
// Task handlers have no return
// Tasker takes a simple map[string]interface{} - not a struct (like some other events).
h.Tasker.LambdaHandler(ctx, d, evt)
return nil, nil
case "AegisRPC":
return h.RPCRouter.LambdaHandler(ctx, d, evt)
case "S3Event":
var e S3Event
decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
// Event time format: 2018-04-02T17:09:32.273Z
// mapstructure does not handle string to time.Time automatically so we need to use a hook
DecodeHook: mapstructure.StringToTimeHookFunc(time.RFC3339Nano),
Result: &e,
})
// decodeErr := mapstructure.Decode(evt, &e)
decodeErr := decoder.Decode(evt)
if decodeErr == nil {
err = h.S3ObjectRouter.LambdaHandler(ctx, d, e)
} else {
log.Println("Could not decode S3Event", decodeErr)
}
case "SimpleEmailEvent":
var e SimpleEmailEvent
decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
// Event time format: 2018-04-02T17:09:32.273Z
// mapstructure does not handle string to time.Time automatically so we need to use a hook
DecodeHook: mapstructure.StringToTimeHookFunc(time.RFC3339Nano),
Result: &e,
})
decodeErr := decoder.Decode(evt)
if decodeErr == nil {
err = h.SESRouter.LambdaHandler(ctx, d, e)
} else {
log.Println("Could not decode SimpleEmailEvent", decodeErr)
}
case "SQSEvent":
var e SQSEvent
err = mapstructure.Decode(evt, &e)
if err == nil {
return nil, h.SQSRouter.LambdaHandler(ctx, d, e)
}
log.Println("Could not decode SQSEvent", err)
case "CognitoTrigger":
// There's so many different formats here, routing for each is a bit silly.
// So send map[string]interface{}
// The handler itself can unmarshal using structs found in cognito_trigger_types.go
return h.CognitoRouter.LambdaHandler(ctx, d, evt)
default:
log.Println("Could not determine Lambda event type, using DefaultHandler.")
// If a default handler is not set, return an error about it.
// It's essentially an unhandled Lambda invocation at this point.
if h.DefaultHandler == nil {
h.DefaultHandler = func(context.Context, *HandlerDependencies, *map[string]interface{}) (interface{}, error) {
return nil, errors.New("unhandled event")
}
}
return h.DefaultHandler(ctx, d, &evt)
}
if err != nil {
log.Println(err)
}
return nil, err
}
// lambdaHandler is a handler used directly with AWS Lambda. It must match this signature.
// However, it uses eventHandler which injects dependencies. In this case, there are no configured dependencies to inject.
func (h *Handlers) lambdaHandler(ctx context.Context, evt map[string]interface{}) (interface{}, error) {
d := HandlerDependencies{}
return h.eventHandler(ctx, &d, evt)
}
// Listen will start a general listener which determines the proper handler to used based on incoming events.
// NOTE: Using handlers directly this way skips on injecting dependencies into the handlers.
func (h *Handlers) Listen() {
lambda.Start(h.lambdaHandler)
}