-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathbootstrap.js
207 lines (171 loc) · 5.31 KB
/
bootstrap.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
const http = require('http')
const RUNTIME_PATH = '/2018-06-01/runtime'
const CALLBACK_USED = Symbol('CALLBACK_USED')
const {
AWS_LAMBDA_FUNCTION_NAME,
AWS_LAMBDA_FUNCTION_VERSION,
AWS_LAMBDA_FUNCTION_MEMORY_SIZE,
AWS_LAMBDA_LOG_GROUP_NAME,
AWS_LAMBDA_LOG_STREAM_NAME,
LAMBDA_TASK_ROOT,
_HANDLER,
AWS_LAMBDA_RUNTIME_API,
} = process.env
const [HOST, PORT] = AWS_LAMBDA_RUNTIME_API.split(':')
start()
async function start() {
let handler
try {
handler = getHandler()
} catch (e) {
await initError(e)
return process.exit(1)
}
tryProcessEvents(handler)
}
async function tryProcessEvents(handler) {
try {
await processEvents(handler)
} catch (e) {
console.error(e)
return process.exit(1)
}
}
async function processEvents(handler) {
while (true) {
const { event, context } = await nextInvocation()
let result
try {
result = await handler(event, context)
} catch (e) {
await invokeError(e, context)
continue
}
const callbackUsed = context[CALLBACK_USED]
await invokeResponse(result, context)
if (callbackUsed && context.callbackWaitsForEmptyEventLoop) {
return process.prependOnceListener('beforeExit', () => tryProcessEvents(handler))
}
}
}
function initError(err) {
return postError(`${RUNTIME_PATH}/init/error`, err)
}
async function nextInvocation() {
const res = await request({ path: `${RUNTIME_PATH}/invocation/next` })
if (res.statusCode !== 200) {
throw new Error(`Unexpected /invocation/next response: ${JSON.stringify(res)}`)
}
if (res.headers['lambda-runtime-trace-id']) {
process.env._X_AMZN_TRACE_ID = res.headers['lambda-runtime-trace-id']
} else {
delete process.env._X_AMZN_TRACE_ID
}
const deadlineMs = +res.headers['lambda-runtime-deadline-ms']
const context = {
awsRequestId: res.headers['lambda-runtime-aws-request-id'],
invokedFunctionArn: res.headers['lambda-runtime-invoked-function-arn'],
logGroupName: AWS_LAMBDA_LOG_GROUP_NAME,
logStreamName: AWS_LAMBDA_LOG_STREAM_NAME,
functionName: AWS_LAMBDA_FUNCTION_NAME,
functionVersion: AWS_LAMBDA_FUNCTION_VERSION,
memoryLimitInMB: AWS_LAMBDA_FUNCTION_MEMORY_SIZE,
getRemainingTimeInMillis: () => deadlineMs - Date.now(),
callbackWaitsForEmptyEventLoop: true,
}
if (res.headers['lambda-runtime-client-context']) {
context.clientContext = JSON.parse(res.headers['lambda-runtime-client-context'])
}
if (res.headers['lambda-runtime-cognito-identity']) {
context.identity = JSON.parse(res.headers['lambda-runtime-cognito-identity'])
}
const event = JSON.parse(res.body)
return { event, context }
}
async function invokeResponse(result, context) {
const res = await request({
method: 'POST',
path: `${RUNTIME_PATH}/invocation/${context.awsRequestId}/response`,
body: JSON.stringify(result === undefined ? null : result),
})
if (res.statusCode !== 202) {
throw new Error(`Unexpected /invocation/response response: ${JSON.stringify(res)}`)
}
}
function invokeError(err, context) {
return postError(`${RUNTIME_PATH}/invocation/${context.awsRequestId}/error`, err)
}
async function postError(path, err) {
const lambdaErr = toLambdaErr(err)
const res = await request({
method: 'POST',
path,
headers: {
'Content-Type': 'application/json',
'Lambda-Runtime-Function-Error-Type': lambdaErr.errorType,
},
body: JSON.stringify(lambdaErr),
})
if (res.statusCode !== 202) {
throw new Error(`Unexpected ${path} response: ${JSON.stringify(res)}`)
}
}
function getHandler() {
const appParts = _HANDLER.split('.')
if (appParts.length !== 2) {
throw new Error(`Bad handler ${_HANDLER}`)
}
const [modulePath, handlerName] = appParts
// Let any errors here be thrown as-is to aid debugging
const app = require(LAMBDA_TASK_ROOT + '/' + modulePath)
const userHandler = app[handlerName]
if (userHandler == null) {
throw new Error(`Handler '${handlerName}' missing on module '${modulePath}'`)
} else if (typeof userHandler !== 'function') {
throw new Error(`Handler '${handlerName}' from '${modulePath}' is not a function`)
}
return (event, context) => new Promise((resolve, reject) => {
context.succeed = resolve
context.fail = reject
context.done = (err, data) => err ? reject(err) : resolve(data)
const callback = (err, data) => {
context[CALLBACK_USED] = true
context.done(err, data)
}
let result
try {
result = userHandler(event, context, callback)
} catch (e) {
return reject(e)
}
if (result != null && typeof result.then === 'function') {
result.then(resolve, reject)
}
})
}
function request(options) {
options.host = HOST
options.port = PORT
return new Promise((resolve, reject) => {
const req = http.request(options, res => {
const bufs = []
res.on('data', data => bufs.push(data))
res.on('end', () => resolve({
statusCode: res.statusCode,
headers: res.headers,
body: Buffer.concat(bufs).toString(),
}))
res.on('error', reject)
})
req.on('error', reject)
req.end(options.body)
})
}
function toLambdaErr(err) {
const { name, message, stack } = err
return {
errorType: name || typeof err,
errorMessage: message || ('' + err),
stackTrace: (stack || '').split('\n').slice(1),
}
}