forked from TeamCodeStream/codestream-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.js
More file actions
567 lines (519 loc) · 17.8 KB
/
Copy pathapi_server.js
File metadata and controls
567 lines (519 loc) · 17.8 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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// The APIServer object manages the components of an API Server module
// While APIServerModules does the module pre-processing, the modules are
// ultimately processed here
'use strict';
const APIServerModules = require('./api_server_modules.js');
const ApiConfig = require(process.env.CSSVC_BACKEND_ROOT + '/api_server/config/config');
const Express = require('express');
const HTTPS = require('https');
const HTTP = require('http');
const AwaitUtils = require(process.env.CSSVC_BACKEND_ROOT + '/shared/server_utils/await_utils');
const IPCResponse = require('./ipc_response');
const Constants = require('constants');
// The APIServer is instantiated via the cluster wrapper.
// Options are passed through from the ClusterWrapper() call made in the
// main block.
//
// These options are required and are promoted to first class properties
// of the server object:
// config: the global configuration
// logger: a simple_file_logger object
class APIServer {
constructor (options) {
this.serverOptions = options;
this.config = options.config || {};
this.logger = options.logger || console;
this.express = Express();
this.services = {};
this.integrations = {};
this.data = {};
}
// start 'er up
async start () {
this.setListeners();
this.loadModules();
await this.registerServices();
this.registerMiddleware();
this.registerRoutes();
this.registerDataSources();
await this.modules.initializeModules();
this.makeHelp();
await AwaitUtils.callbackWrap(this.listen.bind(this));
}
// set relevant event listeners
setListeners () {
process.on('message', this.handleMessage.bind(this));
process.on('SIGINT', this.onSigint.bind(this));
process.on('SIGTERM', this.onSigterm.bind(this));
}
// load all the modules in the modules directory, we'll let APIServerModules handle all that
loadModules () {
this.log('Loading modules...');
this.modules = new APIServerModules({
api: this
});
this.modules.loadModules();
}
// register whatever services we need, the modules provide us with "service functions",
// these get executed and return to us the actual services that become available to the app
async registerServices () {
this.log('Registering services...');
const serviceFunctions = this.modules.getServiceFunctions();
await Promise.all(serviceFunctions.map(async serviceFunction => {
await this.registerModuleServices(serviceFunction);
}));
}
// start the service indicated by the passed service function ... starting a service
// really means making it available to the app through the API Server's services object
async registerModuleServices (serviceFunction) {
const services = await serviceFunction();
// registering a service really means just making it available in our
// services object ... or integrations object if specified
for (let serviceName in services) {
const service = services[serviceName];
if (typeof service.isIntegration === 'function' &&
service.isIntegration()
) {
this.integrations[serviceName] = service;
}
else {
this.services[serviceName] = service;
}
}
}
// register all middleware functions
registerMiddleware () {
this.log('Registering middleware...');
if (this.config.apiServer.mockMode) {
return this.registerMiddlewareForIpc();
}
this.express.use(this.setupRequest.bind(this)); // this is always first in the middleware chain
const middlewareFunctions = this.modules.getMiddlewareFunctions();
middlewareFunctions.forEach(middlewareFunction => {
this.express.use(middlewareFunction);
});
this.registerErrorHandler();
}
// register the master error handler, this happens if there is an express js error
// of some sort ... it goes last in the middleware chain
registerErrorHandler () {
this.express.use((error, request, response, next) => {
this.error('Express error: ' + error.message + '\n' + error.stack);
if (!response.headersSent) {
response.sendStatus(500);
}
request.connection.destroy();
return next;
});
}
// first in the middleware chain, we'll set up the request so it's properly
// initialized
setupRequest (request, response, next) {
request.api = this;
request.apiModules = this.modules;
if (this.shutdownPending) {
return next(new Error('shutdown pending'));
}
(async function() {
if (await ApiConfig.isDirty()) {
this.config = await ApiConfig.loadPreferredConfig();
if (ApiConfig.restartRequired()) {
this.log('new config requires a restart or full re-initialization');
// uh oh!
}
}
process.nextTick(next);
})();
}
// register all DataSources, which really means making collections available
// in our data object
registerDataSources () {
this.log('Registering data sources...');
const dataSourceFunctions = this.modules.getDataSourceFunctions();
dataSourceFunctions.forEach(dataSourceFunction => {
const dataSource = dataSourceFunction();
Object.assign(this.data, dataSource);
});
}
// regiser all routes
registerRoutes () {
this.log('Registering routes...');
const routeObjects = this.modules.getRouteObjects();
routeObjects.forEach(this.registerRouteObject.bind(this));
// register a special route for services interacting with the API server to obtain
// mock mongo data, as a mock-mode replacement for direct access to mongo
if (this.config.apiServer.mockMode) {
this.registerRouteForIpc({
method: 'get',
path: '/mock-data',
func: this.handleMockDataRequest.bind(this)
});
}
}
// register a single route object, the route object can itself have middleware
// functions, but ultimately calls the function as indicated by func
registerRouteObject (routeObject) {
let middleware = routeObject.middleware || [];
if (typeof middleware === 'function') {
middleware = middleware(this);
}
if (!(middleware instanceof Array)) {
middleware = [middleware];
}
if (this.config.apiServer.mockMode) {
return this.registerRouteForIpc(routeObject, middleware);
}
const args = [ routeObject.path, ...middleware, routeObject.func];
this.express[routeObject.method].apply(this.express, args);
}
// start listening for requests!
listen (callback) {
if (this.config.apiServer.mockMode) {
this.listenToIpc();
}
const serverOptions = this.getServerOptions();
if (typeof serverOptions === 'string') {
return callback('failed to make server options: ' + serverOptions);
}
if (this.config.ssl && !this.config.apiServer.ignoreHttps) {
this.log('Creating HTTPS server...');
this.expressServer = HTTPS.createServer(
serverOptions,
this.express
).listen(this.config.apiServer.port);
}
else {
this.log('Creating HTTP server...');
this.expressServer = HTTP.createServer(
this.express
).listen(this.config.apiServer.port);
}
this.expressServer.on('error', (error) => {
return callback(`Unable to start server on port ${this.config.apiServer.port}: ${error}`);
});
this.expressServer.on('listening', () => {
this.log(`Listening on port ${this.config.apiServer.port}...`);
callback();
});
}
// listen on IPC instead, for "mock-mode", testing in local environment
listenToIpc () {
this.services.ipc.on('request', this.handleIpcRequest.bind(this));
}
// get options for express js to listen for requests
getServerOptions () {
let options = {};
const error = this.makeHttpsOptions(options);
if (error) {
return error;
}
return options;
}
// make https options, so we know how to listen to requests over https
makeHttpsOptions (options) {
if (!this.config.apiServer.ignoreHttps) {
options.key = this.config.apiServer.sslCert.key;
options.cert = this.config.apiServer.sslCert.cert;
if (this.config.apiServer.sslCert.caChain) options.ca = this.config.apiServer.sslCert.caChain;
if (this.config.apiServer.requireTLS12) {
// this list was taken from the AWS ELBSecurityPolicy-TLS-1-2-2017-01 policy
// AWS Security policies
// https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html#describe-ssl-policies
// protos & ciphers in Node 12:
// https://developer.ibm.com/blogs/migrating-to-tls13-in-nodejs/
options.ciphers = [
"ECDHE-ECDSA-AES128-GCM-SHA256",
"ECDHE-RSA-AES128-GCM-SHA256",
"ECDHE-ECDSA-AES128-SHA256",
"ECDHE-RSA-AES128-SHA256",
"ECDHE-ECDSA-AES256-GCM-SHA384",
"ECDHE-RSA-AES256-GCM-SHA384",
"ECDHE-ECDSA-AES256-SHA384",
"ECDHE-RSA-AES256-SHA384",
"AES128-GCM-SHA256",
"AES128-SHA256",
"AES256-GCM-SHA384",
"AES256-SHA256",
// TLS 1.3 ciphers
"TLS_AES_256_GCM_SHA384",
"TLS_CHACHA20_POLY1305_SHA256",
"TLS_AES_128_GCM_SHA256",
"TLS_AES_128_CCM_8_SHA256",
"TLS_AES_128_CCM_SHA256"
].join(':'),
options.secureOptions = Constants.SSL_OP_NO_SSLv2 | Constants.SSL_OP_NO_SSLv3 | Constants.SSL_OP_NO_TLSv1 | Constants.SSL_OP_NO_TLSv1_1;
if (this.logger) this.logger.log('setting TLS 1.2 restrictions for express server');
}
}
}
// handle a message from the master
handleMessage (message) {
if (typeof message !== 'object') { return; }
if (message.shutdown) {
// master is making us shut down, whether gracefully or not
this.shutdown();
}
else if (message.wantShutdown) {
// master wants us to shut down, but is giving us the chance to do it gracefully
this.wantShutdown(message.signal || 'signal');
}
else if (message.youAre) {
// master is telling us our worker ID and helping us identify ourselves in the logs
this.workerId = message.youAre;
this.amFirstWorker = message.firstWorker;
if (this.logger && this.logger.setLoggerId) {
this.logger.setLoggerId('W' + this.workerId);
}
}
}
// forced shutdown ... boom!
shutdown () {
if (this.shuttingDown) { return; }
this.shuttingDown = true;
setTimeout(() => {
process.exit(0);
}, 100);
}
// master wants us to shutdown, but is giving us the chance to finish all open
// requests first ... if the master sends another signal within five seoncds,
// we're going to commit suicide regardless ... meanie master
wantShutdown (signal) {
// how many open requests do we have right now?
let myOpenRequests =
this.services.requestTracker &&
this.services.requestTracker.myOpenRequests();
if (myOpenRequests.length && !this.killReceived) {
// we've got some open requests, and no additional commands to die
this.critical(`Worker ${this.workerId} received ${signal}, waiting for these requests to complete ... ${myOpenRequests} ... send ${signal} again to kill`);
this.killReceived = true;
// give the user 5 seconds to force-kill us, otherwise their chance to do so expires
setTimeout(
() => { this.killReceived = false; },
5000
);
this.shutdownPending = true;
}
else {
if (myOpenRequests.length) {
// the user is impatient, we'll die even though we have open requests
this.critical(`Worker ${this.workerId} received ${signal}, shutting down despite ${myOpenRequests.length} open requests...`);
}
else {
// we have no open requests, so we can just die
this.critical(`Worker ${this.workerId} received ${signal} and has no open requests, shutting down...`);
}
// seppuku
this.shutdown();
}
this.critical(`Worker ${this.workerId} will no longer respond to requests`);
this.expressServer && this.expressServer.close();
}
// is this worker waiting to shutdown?
waitingToShutdown () {
return this.shutdownPending;
}
// worker tells us they are waiting for these requests
waitingForRequests (requestIds, currentRequestId) {
this.critical(`Worker ${this.workerId} completed request ${currentRequestId}, still waiting for these requests to finish: ${requestIds}`);
}
// signal that there are currently no open requests
noMoreRequests () {
// if there is a shutdown pending (the master commanded us to shutdown, but is allowing all requests to finish),
// then since there are no more requests, we can just die
if (this.shutdownPending) {
this.critical(`Worker ${this.workerId} has no more open requests, shutting down...`);
this.shutdown();
}
}
// based on information collected from the modules, form data related to help on api server routines
makeHelp () {
this.log('Generating documentation for routes...');
this.documentedRoutes = [];
const routeObjects = this.modules.getRouteObjects();
routeObjects.forEach(this.documentRouteObject.bind(this));
this.documentedModels = this.modules.describeModels();
this.documentedErrors = this.modules.describeErrors();
}
// given a route object, form description information for help
documentRouteObject (routeObject) {
if (!routeObject.describe) { return; }
const description = routeObject.describe();
if (description) {
description.method = routeObject.method;
description.path = routeObject.path;
description.route = `${routeObject.method.toUpperCase()} ${routeObject.path}`;
this.documentedRoutes.push(description);
}
}
// register a route for IPC requests, which simulate HTTP requests for testing purposes
registerRouteForIpc (routeObject, middleware) {
this.ipcRoutes = this.ipcRoutes || {};
this.ipcRoutes[routeObject.path] = this.ipcRoutes[routeObject.path] || {};
this.ipcRoutes[routeObject.path][routeObject.method] = {
middleware,
func: routeObject.func
};
}
// register middleware for IPC requests, which simulate HTTP requests for testing purposes
registerMiddlewareForIpc () {
this.ipcMiddleware = [];
this.ipcMiddleware.push(this.setupRequest.bind(this));
const middlewareFunctions = this.modules.getMiddlewareFunctions();
middlewareFunctions.forEach(middlewareFunction => {
this.ipcMiddleware.push(middlewareFunction);
});
}
// handle an inbound IPC request, which simulates an HTTP request for testing purposes
handleIpcRequest (request, socket) {
request.params = {};
request.body = request.body || {};
request.headers = Object.keys(request.headers || {}).reduce((headers, headerKey) => {
headers[headerKey.toLowerCase()] = request.headers[headerKey];
return headers;
}, {});
this.handleIpcRequestCookies(request);
request.url = request.path;
request.path = request.url.split('?')[0];
request.query = (request.url.split('?')[1] || '').split('&').reduce((query, param) => {
if (param.indexOf('=') !== -1) {
const keyValue = param.split('=');
query[decodeURIComponent(keyValue[0])] = decodeURIComponent(keyValue[1]);
} else {
query[decodeURIComponent(param)] = true;
}
return query;
}, {});
const response = new IPCResponse({
ipc: this.services.ipc,
socket,
clientRequestId: request.clientRequestId
});
let pathRoute = this.ipcRoutes[request.path];
if (!pathRoute) {
pathRoute = this.findIpcRoute(request);
if (!pathRoute) {
return response.sendStatus(404);
}
}
const route = pathRoute[request.method];
if (!route) {
return response.sendStatus(404);
}
this.ipcMiddleware = this.ipcMiddleware || [];
let i = 0;
const next = () => {
i++;
if (i === this.ipcMiddleware.length) {
route.func(request, response);
}
else {
this.ipcMiddleware[i](request, response, next);
}
};
this.ipcMiddleware[0](request, response, next);
}
// handle a service-to-service request for data, that would normally be stored in mongo,
// used only for tests running in mock mode
async handleMockDataRequest (request, response) {
const { secret, collection, func, data } = request.query;
if (secret !== this.config.broadcastEngine.codestreamBroadcaster.secrets.api) {
return response.sendStatus(401);
}
const result = await this.data[collection][func](data);
response.send(result);
}
// handle any cookies in an incoming IPC request
handleIpcRequestCookies (request) {
request.cookies = {};
request.signedCookies = {};
if (!request.headers.cookie) {
return;
}
const cookies = request.headers.cookie.split('; ');
for (let cookie of cookies) {
let [name, value] = cookie.split('=');
if (name && value) {
name = name.trim();
value = value.trim();
request.cookies[name] = value;
if (value.startsWith('s:')) {
request.signedCookies[name] = value.substring(2);
}
}
}
}
// find a matching route to a path given in an IPC request
findIpcRoute (request) {
const { path } = request;
const routeKey = Object.keys(this.ipcRoutes).find(routeKey => {
return this.routeMatchesPath(routeKey, path, request);
});
if (routeKey) {
return this.ipcRoutes[routeKey];
}
}
// determine whether the given route matches the given path
routeMatchesPath (route, path, request) {
const pathParts = path.split('/');
const routeParts = route.split('/');
if (pathParts.length !== routeParts.length) {
return false;
}
let i = -1;
const params = {};
const matches = !routeParts.find(routePart => {
i++;
const pathPart = pathParts[i];
return !this.routePartMatchesPathPart(routePart, pathPart, params);
});
if (matches) {
Object.assign(request.params, params);
}
return matches;
}
// determine whether the given part of a route matches the given part of a path
routePartMatchesPathPart (routePart, pathPart, params) {
if (routePart.startsWith(':')) {
if (pathPart) {
params[routePart.slice(1)] = pathPart;
return true;
}
else {
return false;
}
}
else {
return routePart === pathPart;
}
}
onSigint () {
}
onSigterm () {
}
critical (message) {
if (this.logger && typeof this.logger.critical === 'function') {
this.logger.critical(message);
}
}
error (message) {
if (this.logger && typeof this.logger.error === 'function') {
this.logger.error(message);
}
}
warn (message) {
if (this.logger && typeof this.logger.warn === 'function') {
this.logger.warn(message);
}
}
log (message, a, b, c, d) {
if (this.logger && typeof this.logger.log === 'function') {
this.logger.log(message, a, b, c, d);
}
}
debug (message) {
if (this.logger && typeof this.logger.debug === 'function') {
this.logger.debug(message);
}
}
}
module.exports = APIServer;