-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
300 lines (284 loc) · 10.4 KB
/
index.js
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
"use strict"
const path = require("path")
const { existsSync } = require("fs")
const fsPromises = require("fs/promises")
const Serverless = require("serverless")
const { wrap } = require("lambda-wrapper")
const assert = require("assert")
const url = require("url")
const querystring = require("querystring")
const YAML = require("yaml")
class ServerlessInvoker {
/**
* Initializes an instance of the class.
* @param {*string} servicePath Path to the directory containing the serverless file.
*/
constructor(servicePath) {
this.servicePath = servicePath || ServerlessInvoker.findServicePath()
this.serverless = null
this.serverlessEvents = null
}
static findServicePath() {
let dir = process.cwd()
while (dir !== "/" && !existsSync(path.join(dir, "serverless.yml"))) {
dir = path.dirname(dir)
}
if (dir === "/") {
throw new Error(
`Cannot find serverless.yml. Started search in working directory ${process.cwd()}`
)
}
return dir
}
static async loadServerlessYaml(path) {
const file = await fsPromises.readFile(path, "utf8")
return YAML.parse(file)
}
async initializeServerless() {
process.env.SLS_DEBUG = "*"
// Serverless v3 requires us to load the config manually: https://www.serverless.com/framework/docs/deprecations#serverless-constructor-service-configuration-dependency
// see also https://www.serverless.com/framework/docs/guides/upgrading-v3#low-level-changes
// https://www.serverless.com/framework/docs/deprecations#serverless-constructor-configcommands-and-configoptions-requirement
const slsService = await ServerlessInvoker.loadServerlessYaml(
path.join(this.servicePath, "serverless.yml")
)
const config = {
serviceDir: path.dirname(this.servicePath),
configurationFilename: "serverless.yml",
configuration: slsService,
commands: [],
options: {},
}
const sls = new Serverless(config)
// NOTE: I've seen sls.init() run very slowly; nearly 500ms!
return sls.init().then(() => {
return sls.service.load().then(() => {
sls.service.setFunctionNames({})
sls.service.mergeArrays()
sls.service.validate()
this.serverless = sls
})
})
}
/**
* Invokes the serverless function bound to the HTTP event with the provided specification.
* @param {*string} httpRequest A method+path like 'GET api/users/me'.
* @param {*object} event The event that should be submitted to the http endpoint.
* @param {*object} context The context passed to the lambda function
*/
async invoke(httpRequest, event, context) {
// Read the serverless.yml file
return this.initializeServerless()
.then(() => this.loadServerlessEvents())
.then((httpEvents) => {
// find the event that matches the specified httpRequest
let httpEvent = httpEvents.find((e) => e.test(httpRequest))
if (!httpEvent) {
throw new Error(
`Serverless http event not found for HTTP request "${httpRequest}" in service path "${this.servicePath}".`
)
}
const parsedPath = ServerlessInvoker.parsePath(httpRequest)
event = Object.assign({}, event, {
path: parsedPath,
resource: parsedPath,
pathParameters: ServerlessInvoker.parsePathParameters(
httpEvent,
httpRequest
),
queryStringParameters:
ServerlessInvoker.parseQueryStringParameters(httpRequest),
httpMethod: ServerlessInvoker.parseHttpMethod(httpRequest),
})
return this.loadServerlessEnvironment().then(() => {
return this.invokeWithLambdaWrapper(httpEvent, event, context)
.then((response) => {
if (
response &&
response.headers &&
Object.keys(response.headers).includes("Content-Type") &&
response.headers["Content-Type"] === "application/json"
) {
if (response.body && typeof response.body === "string") {
response.body = JSON.parse(response.body)
}
}
return response
})
.catch((eLambdaFuncError) => {
// In this situation API Gateway returns 502 (bad gateway) and sets the response body to `{"message": "Internal server error"}`. We are adding a bit more detail to the error.
console.error(
"serverless-http-invoker error invoking function:",
eLambdaFuncError
)
const response = {
statusCode: 502,
body: {
message: "Internal server error",
test_debug_error_message: eLambdaFuncError.toString(),
test_debug_error_stack: eLambdaFuncError.stack,
},
}
return response
})
})
})
}
static parseHttpMethod(httpRequest) {
const parts = httpRequest.split(" ")
assert(
parts.length >= 1,
"expected httpRequest to be a method seperated by a space and then the request path"
)
return parts[0]
}
static parsePathParameters(httpEvent, httpRequest) {
let pathParamValues = httpEvent.matcher.exec(httpRequest)
if (pathParamValues.length > 0) {
pathParamValues = pathParamValues.slice(1)
}
const pathParametersMap = {}
assert(
httpEvent.pathParamNames.length === pathParamValues.length,
`expected param names and param values to have same length, but were: \n\tnames: ${JSON.stringify(
httpEvent.pathParamNames
)}\n\t!==\n\tvalues: ${JSON.stringify(pathParamValues)}`
)
for (let i = 0; i < httpEvent.pathParamNames.length; i++) {
let paramName = httpEvent.pathParamNames[i]
pathParametersMap[paramName] = pathParamValues[i]
}
return pathParametersMap
}
static parseQueryStringParameters(requestUrl) {
const myURL = url.parse(
"https://fakehost.com/" + requestUrl.split(" ")[1],
true
)
const search =
myURL.search && myURL.search.length > 0
? myURL.search.slice(1)
: myURL.search
return querystring.parse(search)
}
static parsePath(requestUrl) {
const myURL = url.parse("https://fakehost.com/" + requestUrl.split(" ")[1])
return myURL.pathname
}
async loadServerlessEnvironment() {
let env = this.serverless.service.provider.environment
Object.assign(process.env, env)
return env
}
async invokeWithLambdaWrapper(httpEvent, event, context) {
const handlerModule = require(path.join(
this.servicePath,
httpEvent.handlerPath
))
const lambda = wrap(handlerModule, { handler: httpEvent.handlerName })
return lambda.runHandler(event, context || {})
}
async loadServerlessEvents() {
let funcs = this.serverless.service
.getAllFunctions()
.map((fname) => {
let funcObj = this.serverless.service.getFunction(fname)
let events = this.serverless.service.getAllEventsInFunction(fname)
let f = {
name: fname,
handler: funcObj.handler,
events: events.filter(
(e) => Object.keys(e).includes("http") && e.http !== null
),
}
return f
})
.filter((f) => f.events.length > 0)
.map((f) => {
f.events = f.events.map((evt) => {
// add a path parser regex:
RegExp.escape = function (s) {
// https://stackoverflow.com/a/3561711/51061
return s.replace(/[-/\\^$*+?.()|[\]]/g, "\\$&")
}
let path = null
let method = null
if (typeof evt.http === "object") {
path = evt.http.path
method = evt.http.method
} else {
assert(
typeof evt.http === "string",
`Expected http event to have a type of object or string but was ${typeof evt.http}.`
)
method = evt.http.split(" ")[0]
path = evt.http.split(" ")[1]
}
let pattern = RegExp.escape(path)
// collect the pathParamNames:
// first the "greedy" path params like {pname+} (with a '+' postfix)
let matchPathParamNamesPattern = pattern.replace(
/\/\{[^}]*\+\}/gi,
"/(.*)"
)
// then the normal path params
matchPathParamNamesPattern = pattern.replace(
/\/\{[^}]*\}/gi,
"/([^/]*)"
)
let matchPathParamNames = new RegExp(matchPathParamNamesPattern, "gi")
let pathParamNames = matchPathParamNames.exec(path).slice(1) // the first element is full matched text so slice it off
// remove the surrounding bracket characters:
pathParamNames = pathParamNames.map((p) =>
p.replace(/^\{([^}]+)\}$/, "$1")
)
// remove the '+' postfix if it exists
pathParamNames = pathParamNames.map((p) =>
p.endsWith("+") ? p.substring(0, p.length - 1) : p
)
// console.log('pathParamNames:', pathParamNames, 'path:', path)
// now collect the values for the params:
let optionalQueryStringPattern = "(?:\\?.*)?$"
// first match greedy, then the normal ones again:
let matchPathParamValuesPattern = pattern.replace(
/\/\{[^}]*\+\}/gi,
"/(.+)"
)
matchPathParamValuesPattern = matchPathParamValuesPattern.replace(
/\/\{[^}]*\}/gi,
"/([^/\\?]+)"
)
let matcher = new RegExp(
"^" +
method +
"\\s+" +
matchPathParamValuesPattern +
optionalQueryStringPattern,
"i"
)
// console.log('path:', path, 'matcher:', matcher)
return Object.assign(evt.http, {
matcher: matcher,
pathParamNames: pathParamNames,
test: (request) => {
const result = matcher.test(request)
// console.log(`${method} ${path}: ${request} == ${result} \n pattern:${matcher.source}`)
return result
},
})
})
return f
})
let events = []
for (let f of funcs) {
for (let e of f.events) {
e.function = f.name
e.handlerPath = f.handler.split(".")[0]
e.handlerName = f.handler.split(".")[1]
events.push(e)
}
}
return events
}
}
module.exports = ServerlessInvoker