-
-
Notifications
You must be signed in to change notification settings - Fork 793
/
ApiGatewayWebSocket.js
365 lines (286 loc) · 10.7 KB
/
ApiGatewayWebSocket.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
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
'use strict';
const fs = require('fs');
const path = require('path');
const hapi = require('@hapi/hapi');
const h2o2 = require('@hapi/h2o2');
const hapiPluginWebsocket = require('hapi-plugin-websocket');
const debugLog = require('./debugLog');
const createLambdaContext = require('./createLambdaContext');
const functionHelper = require('./functionHelper');
const { getUniqueId } = require('./utils');
const authFunctionNameExtractor = require('./authFunctionNameExtractor');
const wsHelpers = require('./websocketHelpers');
module.exports = class ApiGatewayWebSocket {
constructor(serverless, options) {
this.serverless = serverless;
this.service = serverless.service;
this.serverlessLog = serverless.cli.log.bind(serverless.cli);
this.options = options;
this.exitCode = 0;
this.clients = new Map();
this.actions = {};
this.websocketsApiRouteSelectionExpression = serverless.service.provider.websocketsApiRouteSelectionExpression || '$request.body.action';
}
printBlankLine() {
console.log();
}
_createWebSocket() {
// start COPY PASTE FROM HTTP SERVER CODE
const serverOptions = {
host: this.options.host,
port: this.options.websocketPort,
router: {
stripTrailingSlash: !this.options.preserveTrailingSlash, // removes trailing slashes on incoming paths.
},
};
const httpsDir = this.options.httpsProtocol;
// HTTPS support
if (typeof httpsDir === 'string' && httpsDir.length > 0) {
serverOptions.tls = {
key: fs.readFileSync(path.resolve(httpsDir, 'key.pem'), 'ascii'),
cert: fs.readFileSync(path.resolve(httpsDir, 'cert.pem'), 'ascii'),
};
}
serverOptions.state = this.options.enforceSecureCookies ? {
isHttpOnly: true,
isSameSite: false,
isSecure: true,
} : {
isHttpOnly: false,
isSameSite: false,
isSecure: false,
};
// Hapijs server creation
this.wsServer = hapi.server(serverOptions);
this.wsServer.register(h2o2).catch(err => err && this.serverlessLog(err));
// Enable CORS preflight response
this.wsServer.ext('onPreResponse', (request, h) => {
if (request.headers.origin) {
const response = request.response.isBoom ? request.response.output : request.response;
response.headers['access-control-allow-origin'] = request.headers.origin;
response.headers['access-control-allow-credentials'] = 'true';
if (request.method === 'options') {
response.statusCode = 200;
response.headers['access-control-expose-headers'] = 'content-type, content-length, etag';
response.headers['access-control-max-age'] = 60 * 10;
if (request.headers['access-control-request-headers']) {
response.headers['access-control-allow-headers'] = request.headers['access-control-request-headers'];
}
if (request.headers['access-control-request-method']) {
response.headers['access-control-allow-methods'] = request.headers['access-control-request-method'];
}
}
}
return h.continue;
});
// end COPY PASTE FROM HTTP SERVER CODE
this.wsServer.register(hapiPluginWebsocket).catch(err => err && this.serverlessLog(err));
const doAction = (ws, connectionId, name, event, doDefaultAction) => {
const sendError = err => {
if (ws.readyState === /* OPEN */1) {
ws.send(JSON.stringify({ message:'Internal server error', connectionId, requestId:'1234567890' }));
}
// mimic AWS behaviour (close connection) when the $connect action handler throws
if (name === '$connect') {
ws.close();
}
debugLog(`Error in handler of action ${action}`, err);
};
let action = this.actions[name];
if (!action && doDefaultAction) action = this.actions.$default;
if (!action) return;
function cb(err) {
if (!err) return;
sendError(err);
}
// TEMP
const func = {
...action.fun,
name,
};
const context = createLambdaContext(func, this.service.provider, cb);
let p = null;
try {
p = action.handler(event, context, cb);
}
catch (err) {
sendError(err);
}
if (p) {
p.catch(err => {
sendError(err);
});
}
};
this.wsServer.route({
method: 'POST',
path: '/',
config: {
payload: {
output: 'data',
parse: true,
allow: 'application/json',
},
plugins: {
websocket: {
only: true,
initially: false,
connect: ({ ws, req }) => {
const queryStringParameters = parseQuery(req.url);
const connection = { connectionId:getUniqueId(), connectionTime:Date.now() };
debugLog(`connect:${connection.connectionId}`);
this.clients.set(ws, connection);
let event = wsHelpers.createConnectEvent('$connect', 'CONNECT', connection, this.options);
if (Object.keys(queryStringParameters).length > 0) {
event = { queryStringParameters, ...event };
}
doAction(ws, connection.connectionId, '$connect', event, false);
},
disconnect: ({ ws }) => {
const connection = this.clients.get(ws);
debugLog(`disconnect:${connection.connectionId}`);
this.clients.delete(ws);
const event = wsHelpers.createDisconnectEvent('$disconnect', 'DISCONNECT', connection, this.options);
doAction(ws, connection.connectionId, '$disconnect', event, false);
},
},
},
},
handler: (request, h) => {
const { initially, ws } = request.websocket();
if (!request.payload || initially) {
return h.response().code(204);
}
const connection = this.clients.get(ws);
let actionName = null;
if (this.websocketsApiRouteSelectionExpression.startsWith('$request.body.')) {
actionName = request.payload;
if (typeof actionName === 'object') {
this.websocketsApiRouteSelectionExpression
.replace('$request.body.', '')
.split('.')
.forEach(key => {
if (actionName) {
actionName = actionName[key];
}
});
}
else actionName = null;
}
if (typeof actionName !== 'string') {
actionName = null;
}
const action = actionName || '$default';
debugLog(`action:${action} on connection=${connection.connectionId}`);
const event = wsHelpers.createEvent(action, 'MESSAGE', connection, request.payload, this.options);
doAction(ws, connection.connectionId, action, event, true);
return h.response().code(204);
},
});
this.wsServer.route({
method: 'GET',
path: '/{path*}',
handler: (request, h) => h.response().code(426),
});
this.wsServer.route({
method: 'POST',
path: '/@connections/{connectionId}',
config: { payload: { parse: false } },
handler: (request, h) => {
debugLog(`got POST to ${request.url}`);
const getByConnectionId = (map, searchValue) => {
for (const [key, connection] of map.entries()) {
if (connection.connectionId === searchValue) return key;
}
return undefined;
};
const ws = getByConnectionId(this.clients, request.params.connectionId);
if (!ws) return h.response().code(410);
if (!request.payload) return '';
ws.send(request.payload.toString());
debugLog(`sent data to connection:${request.params.connectionId}`);
return '';
},
});
this.wsServer.route({
method: 'DELETE',
path: '/@connections/{connectionId}',
config: { payload: { parse: false } },
handler: (request, h) => {
debugLog(`got DELETE to ${request.url}`);
const getByConnectionId = (map, searchValue) => {
for (const [key, connection] of map.entries()) {
if (connection.connectionId === searchValue) return key;
}
return undefined;
};
const ws = getByConnectionId(this.clients, request.params.connectionId);
if (!ws) return h.response().code(410);
ws.close();
debugLog(`closed connection:${request.params.connectionId}`);
return '';
},
});
}
_createWsAction(fun, funName, servicePath, funOptions, event) {
let handler; // The lambda function
Object.assign(process.env, this.originalEnvironment);
try {
if (this.options.noEnvironment) {
// This evict errors in server when we use aws services like ssm
const baseEnvironment = {
AWS_REGION: 'dev',
};
if (!process.env.AWS_PROFILE) {
baseEnvironment.AWS_ACCESS_KEY_ID = 'dev';
baseEnvironment.AWS_SECRET_ACCESS_KEY = 'dev';
}
process.env = Object.assign(baseEnvironment, process.env);
}
else {
Object.assign(
process.env,
{ AWS_REGION: this.service.provider.region },
this.service.provider.environment,
this.service.functions[funName].environment
);
}
process.env._HANDLER = fun.handler;
handler = functionHelper.createHandler(funOptions, this.options);
}
catch (error) {
return this.serverlessLog(`Error while loading ${funName}`, error);
}
const actionName = event.websocket.route;
const action = { funName, fun, funOptions, servicePath, handler };
this.actions[actionName] = action;
this.serverlessLog(`Action '${event.websocket.route}'`);
}
_extractAuthFunctionName(endpoint) {
const result = authFunctionNameExtractor(endpoint, this.serverlessLog);
return result.unsupportedAuth ? null : result.authorizerName;
}
// All done, we can listen to incomming requests
async _listen() {
try {
await this.wsServer.start();
}
catch (error) {
console.error(`Unexpected error while starting serverless-offline websocket server on port ${this.options.websocketPort}:`, error);
process.exit(1);
}
this.printBlankLine();
this.serverlessLog(`Offline [websocket] listening on ws${this.options.httpsProtocol ? 's' : ''}://${this.options.host}:${this.options.websocketPort}`);
}
};
function parseQuery(queryString) {
const query = {};
const parts = queryString.split('?');
if (parts.length < 2) return {};
const pairs = parts[1].split('&');
pairs.forEach(pair => {
const kv = pair.split('=');
query[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1] || '');
});
return query;
}