-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
bridge.js
332 lines (294 loc) · 9.09 KB
/
bridge.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
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
const { request } = require('http');
/**
* If the `http.Server` handler function throws an error asynchronously,
* then it ends up being an unhandled rejection which doesn't kill the node
* process which causes the HTTP request to hang indefinitely. So print the
* error here and force the process to exit so that the lambda invocation
* returns an Unhandled error quickly.
*/
process.on('unhandledRejection', err => {
console.error('Unhandled rejection:', err);
process.exit(1);
});
/**
* @param {import('./types').VercelProxyEvent} event
*/
function normalizeProxyEvent(event) {
let bodyBuffer;
const { method, path, headers, encoding, body, payloads } = JSON.parse(
event.body
);
/**
*
* @param {string | Buffer} b
* @returns Buffer
*/
const normalizeBody = b => {
if (b) {
if (encoding === 'base64') {
bodyBuffer = Buffer.from(b, encoding);
} else if (encoding === undefined) {
bodyBuffer = Buffer.from(b);
} else {
throw new Error(`Unsupported encoding: ${encoding}`);
}
} else {
bodyBuffer = Buffer.alloc(0);
}
return bodyBuffer;
};
if (payloads) {
/**
* @param {{ body: string | Buffer }} payload
*/
const normalizePayload = payload => {
payload.body = normalizeBody(payload.body);
};
payloads.forEach(normalizePayload);
}
bodyBuffer = normalizeBody(body);
return {
isApiGateway: false,
method,
path,
headers,
body: bodyBuffer,
payloads,
};
}
/**
* @param {import('aws-lambda').APIGatewayProxyEvent} event
*/
function normalizeAPIGatewayProxyEvent(event) {
let bodyBuffer;
const { httpMethod: method, path, headers, body } = event;
if (body) {
if (event.isBase64Encoded) {
bodyBuffer = Buffer.from(body, 'base64');
} else {
bodyBuffer = Buffer.from(body);
}
} else {
bodyBuffer = Buffer.alloc(0);
}
return { isApiGateway: true, method, path, headers, body: bodyBuffer };
}
/**
* @param {import('./types').VercelProxyEvent | import('aws-lambda').APIGatewayProxyEvent} event
*/
function normalizeEvent(event) {
if ('Action' in event) {
if (event.Action === 'Invoke') {
return normalizeProxyEvent(event);
} else {
throw new Error(`Unexpected event.Action: ${event.Action}`);
}
} else {
return normalizeAPIGatewayProxyEvent(event);
}
}
class Bridge {
/**
* @param {import('./types').ServerLike | null} server
* @param {boolean} shouldStoreEvents
*/
constructor(server = null, shouldStoreEvents = false) {
this.server = server;
this.shouldStoreEvents = shouldStoreEvents;
this.launcher = this.launcher.bind(this);
this.reqIdSeed = 1;
/**
* @type {{ [key: string]: import('./types').VercelProxyRequest }}
*/
this.events = {};
this.listening = new Promise(resolve => {
this.resolveListening = resolve;
});
}
/**
* @param {import('./types').ServerLike} server
*/
setServer(server) {
this.server = server;
}
/**
* @param {boolean} shouldStoreEvents
*/
setStoreEvents(shouldStoreEvents) {
this.shouldStoreEvents = shouldStoreEvents;
}
listen() {
const { server, resolveListening } = this;
if (!server) {
throw new Error('Server has not been set!');
}
if (typeof server.timeout === 'number' && server.timeout > 0) {
// Disable timeout (usually 2 minutes until Node 13).
// Instead, user should assign function `maxDuration`.
server.timeout = 0;
}
return server.listen(
{
host: '127.0.0.1',
port: 0,
},
function listeningCallback() {
if (!this || typeof this.address !== 'function') {
throw new Error(
'Missing server.address() function on `this` in server.listen()'
);
}
const addr = this.address();
if (!addr) {
throw new Error('`server.address()` returned `null`');
}
if (typeof addr === 'string') {
throw new Error(
`Unexpected string for \`server.address()\`: ${addr}`
);
}
resolveListening(addr);
}
);
}
/**
*
* @param {import('./types').VercelProxyEvent | import('aws-lambda').APIGatewayProxyEvent} event
* @param {import('aws-lambda').Context} context
* @return {Promise<{statusCode: number, headers: import('http').IncomingHttpHeaders, body: string, encoding: 'base64'}>}
*/
async launcher(event, context) {
context.callbackWaitsForEmptyEventLoop = false;
const normalizedEvent = normalizeEvent(event);
if (
'payloads' in normalizedEvent &&
Array.isArray(normalizedEvent.payloads)
) {
// statusCode and headers are required to match when using
// multiple payloads in a single invocation so we can use
// the first
let statusCode = 200;
/**
* @type {import('http').IncomingHttpHeaders}
*/
let headers = {};
/**
* @type {string}
*/
let combinedBody = '';
const multipartBoundary = 'payload-separator';
const CLRF = '\r\n';
// we execute the payloads one at a time to ensure
// lambda semantics
for (let i = 0; i < normalizedEvent.payloads.length; i++) {
const currentPayload = normalizedEvent.payloads[i];
const response = await this.handleEvent(currentPayload);
// build a combined body using multipart
// https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
combinedBody += `--${multipartBoundary}${CLRF}`;
if (response.headers['content-type']) {
combinedBody += `content-type: ${response.headers['content-type']}${CLRF}${CLRF}`;
}
combinedBody += response.body;
combinedBody += CLRF;
if (i === normalizedEvent.payloads.length - 1) {
combinedBody += `--${multipartBoundary}--${CLRF}`;
}
statusCode = response.statusCode;
headers = response.headers;
}
headers[
'content-type'
] = `multipart/mixed; boundary="${multipartBoundary}"`;
return {
headers,
statusCode,
body: combinedBody,
encoding: 'base64',
};
} else {
return this.handleEvent(normalizedEvent);
}
}
/**
*
* @param {ReturnType<typeof normalizeEvent>} normalizedEvent
* @return {Promise<{statusCode: number, headers: import('http').IncomingHttpHeaders, body: string, encoding: 'base64'}>}
*/
async handleEvent(normalizedEvent) {
const { port } = await this.listening;
const { isApiGateway, method, headers, body } = normalizedEvent;
let { path } = normalizedEvent;
if (this.shouldStoreEvents) {
const reqId = `${this.reqIdSeed++}`;
this.events[reqId] = normalizedEvent;
headers['x-now-bridge-request-id'] = reqId;
}
// eslint-disable-next-line consistent-return
return new Promise((resolve, reject) => {
// if the path is improperly encoded we need to encode it or
// http.request will throw an error (related check: https://github.com/nodejs/node/blob/4ece669c6205ec78abfdadfe78869bbb8411463e/lib/_http_client.js#L84)
if (path && /[^\u0021-\u00ff]/.test(path)) {
path = encodeURI(path);
}
const opts = { hostname: '127.0.0.1', port, path, method };
const req = request(opts, res => {
const response = res;
/**
* @type {Buffer[]}
*/
const respBodyChunks = [];
response.on('data', chunk => respBodyChunks.push(Buffer.from(chunk)));
response.on('error', reject);
response.on('end', () => {
const bodyBuffer = Buffer.concat(respBodyChunks);
delete response.headers.connection;
if (isApiGateway) {
delete response.headers['content-length'];
} else if (response.headers['content-length']) {
response.headers['content-length'] = String(bodyBuffer.length);
}
resolve({
statusCode: response.statusCode || 200,
headers: response.headers,
body: bodyBuffer.toString('base64'),
encoding: 'base64',
});
});
});
req.on('error', error => {
setTimeout(() => {
// this lets express print the true error of why the connection was closed.
// it is probably 'Cannot set headers after they are sent to the client'
reject(error);
}, 2);
});
for (const [name, value] of Object.entries(headers)) {
if (value === undefined) {
console.error(
`Skipping HTTP request header "${name}" because value is undefined`
);
continue;
}
try {
req.setHeader(name, value);
} catch (err) {
console.error(`Skipping HTTP request header: "${name}: ${value}"`);
console.error(err.message);
}
}
if (body) req.write(body);
req.end();
});
}
/**
* @param {string} reqId
* @return {import('./types').VercelProxyRequest}
*/
consumeEvent(reqId) {
const event = this.events[reqId];
delete this.events[reqId];
return event;
}
}
module.exports = { Bridge };