-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi-gateway.js
503 lines (421 loc) · 13.7 KB
/
api-gateway.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
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
const express = require("express");
const mongo = require("mongodb");
const http = require("http");
const ms = require("ms");
const request = require("request");
const { Promise: BPromise } = require("bluebird");
const log = require("fruster-log");
const bus = require("fruster-bus");
const utils = require("./utils");
const conf = require("./conf");
const constants = require("./lib/constants");
const ResponseTimeRepo = require("./lib/repos/ResponseTimeRepo");
const statzIndex = require("./web/statz/index");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const bearerToken = require("express-bearer-token");
const timeout = require("connect-timeout");
const bodyParser = require("body-parser");
const InfluxRepo = require("./lib/repos/InfluxRepo");
const favicon = require("express-favicon");
const reqIdMiddleware = require("./lib/middleware/reqid-middleware");
const httpMetricMiddleware = require("./lib/middleware/http-metric-middleware");
const noCacheMiddleware = require("./lib/middleware/no-cache-middleware");
const decodeTokenMiddleware = require("./lib/middleware/decode-token-middleware");
const dateStarted = new Date();
/**
* @type ResponseTimeRepo
*/
let responseTimeRepo;
/**
* @type InfluxRepo
*/
let influxRepo;
const interceptAction = {
respond: "respond",
next: "next",
};
const parsedRewriteRules = [];
/**
* Creates an Express app and adds middlewares and handlers
* so it can receive incoming requests and pass them thru to
* internal services.
*/
function createExpressApp() {
const app = express();
app.use(favicon(__dirname + "/favicon.ico"));
app.use(reqIdMiddleware());
app.use(httpMetricMiddleware({ influxRepo, responseTimeRepo }));
app.use(
cors({
origin: conf.allowOrigin,
credentials: true,
allowedHeaders: conf.allowedHeaders,
})
);
app.use(timeout(conf.httpTimeout));
app.use(
bodyParser.json({
type: (req) => {
const contentType = req.headers["content-type"] || "";
return contentType.includes("json");
},
limit: conf.maxRequestSize,
})
);
app.use(
bodyParser.text({
type: constants.TEXT_CONTENT_TYPES,
defaultCharset: "utf-8",
limit: conf.maxRequestSize,
})
);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(bearerToken());
app.use(noCacheMiddleware());
app.get(["/", "/health"], (req, res) => {
res.json({ status: "Alive since " + dateStarted });
});
app.get("/robots.txt", function (req, res) {
res.type("text/plain");
res.send("User-agent: *\nDisallow: /");
});
if (conf.enableStats) {
// Add endpoints serving UI for response time statistics
app.set("views", "./web/statz");
app.set("view engine", "pug");
app.get("/statz", statzIndex.index);
app.get("/statz/search", statzIndex.search);
}
app.use(decodeTokenMiddleware());
app.use(handleReq);
app.use((err, req, res, next) => {
res.status(err.status || 500);
let json = { message: err.message };
if (conf.printStacktrace) json.stacktrace = err.stack;
res.json(json);
if (res.status === 500) log.error(err.stack);
});
if (conf.rewriteRules) {
log.info("Rewrite rules enabled");
// {userId1|userId2|...}:{subject pattern to match}>{subject to rewrite to}
const rules = conf.rewriteRules.split(",");
rules.forEach((rule) => {
const [userId, rewrite] = rule.split(":");
const [from, to] = rewrite.split(">");
parsedRewriteRules.push({
userId: userId.split("|"),
match: new RegExp(from),
rewrite: to,
});
});
for (const rule of parsedRewriteRules) {
let i = 1;
log.debug(`Parsed rewrite rule (${i}/${parsedRewriteRules.length}):`);
log.debug(`User IDs: ${rule.userId.join(", ")}`);
log.debug(`Match: ${rule.match.toString()}`);
log.debug(`Rewrite: ${rule.rewrite}`);
i++;
}
}
return app;
}
/**
* Main handler for incoming http requests.
*
* @param {Object} httpReq
* @param {Object} httpRes
* @param {Function} next
*/
async function handleReq(httpReq, httpRes, next) {
// Note: reqId was added by reqid-middleware
const reqId = httpReq.reqId;
try {
// Translate http request to bus request and post it internally on bus
const internalRes = await sendInternalRequest(httpReq);
// Translate bus response to a HTTP response and send it
sendHttpResponse(reqId, internalRes, httpRes);
} catch (err) {
handleBusErrorResponse(err, httpRes, reqId);
}
}
function handleBusErrorResponse(err, httpRes, reqId) {
/*
* Translates 408 timeout to 404 since timeout indicates that no one
* subscribed on subject
*/
if (err.status === 408) {
err.status = 404;
httpRes.status(404);
} else {
httpRes.status(err.status || 500);
}
if (httpRes.statusCode > 499) log.error(err);
setRequestId(reqId, err);
httpRes.set(err.headers).json(err);
}
function invokeRequestInterceptors(subject, message) {
const matchedInterceptors = conf.interceptors.filter((interceptor) => {
return interceptor.type === "request" && interceptor.match(subject);
});
return BPromise.reduce(
matchedInterceptors,
(_message, interceptor) => {
if (_message.interceptAction === interceptAction.respond) {
return _message;
}
return bus.request({
subject: interceptor.targetSubject,
message: _message,
skipOptionsRequest: true,
});
},
message
);
}
function invokeResponseInterceptors(subject, message, messageIsException) {
const matchedInterceptors = conf.interceptors.filter((interceptor) => {
const typeIsResponse = interceptor.type === "response";
const subjectMatchesSubject = interceptor.match(subject);
const isNotExceptionOrConfiguredToAllowExceptions = !messageIsException
? true
: !!interceptor.options.allowExceptions;
return typeIsResponse && subjectMatchesSubject && isNotExceptionOrConfiguredToAllowExceptions;
});
/** If no interceptors allowing exceptions were found we throw the error for it to be taken care of normally */
if (matchedInterceptors.length === 0 && messageIsException) throw cleanInterceptedResponse(message, message);
return BPromise.reduce(
matchedInterceptors,
(_message, interceptor) => {
if (_message.interceptAction === interceptAction.respond) return _message;
return bus.request({
subject: interceptor.targetSubject,
message: _message,
skipOptionsRequest: true,
});
},
message
);
}
function sendInternalRequest(httpReq) {
const reqId = httpReq.reqId;
const user = httpReq.user;
const subject = utils.createSubject(httpReq);
const message = utils.createRequest(httpReq, reqId, user);
return invokeRequestInterceptors(subject, message).then((interceptedReq) => {
if (interceptedReq.interceptAction === interceptAction.respond) {
delete interceptedReq.interceptAction;
return interceptedReq;
}
let rewrittenSubject = subject;
if (parsedRewriteRules.length > 0) {
const userId = user ? user.id : null;
if (userId) {
const rules = parsedRewriteRules.filter((rule) => rule.userId.includes(userId));
for (const rule of rules) {
if (rule.match.test(subject)) {
if (rule.rewrite.includes("$1")) {
const [_, ...groups] = rule.match.exec(subject);
rewrittenSubject = rule.rewrite.replace(/\$(\d+)/g, (_match, number) => {
return groups[number - 1] || "";
});
} else {
rewrittenSubject = rule.rewrite;
}
continue;
}
}
}
}
if (subject !== rewrittenSubject) {
log.info(`Rewrote subject ${subject} to ${rewrittenSubject} for user ${user.id}`);
} else {
log.silly("Sending to subject", rewrittenSubject);
}
// Multipart requests are dealt with manually so that
// api gateway is able to stream the multipart body to
// its internal receiving service.
// Otherwise plain bus request is used, but note that
// depending on what the recieving service wants for protocol
// the resulting request may still be done via HTTP. However, this
// happens under the hood in fruster-bus-js and hence is transparent for
// the api gateway.
if (isMultipart(httpReq)) {
return sendInternalMultipartRequest(rewrittenSubject, interceptedReq, httpReq)
.then(interceptResponse)
.catch((err) => interceptResponse(err, true));
} else {
return bus
.request(rewrittenSubject, interceptedReq, ms(conf.busTimeout))
.then(interceptResponse)
.catch((err) => interceptResponse(err, true));
}
function interceptResponse(response, messageIsException) {
if (response.error) response.data = interceptedReq.data;
return invokeResponseInterceptors(
subject,
prepareInterceptResponseMessage(response, message),
messageIsException
)
.then((interceptedResponse) => cleanInterceptedResponse(response, interceptedResponse))
.catch((interceptedResponse) => cleanInterceptedResponse(response, interceptedResponse));
}
});
}
function prepareInterceptResponseMessage(response, message) {
const interceptMessage = Object.assign({}, response);
interceptMessage.query = message.query;
interceptMessage.params = message.params;
interceptMessage.path = message.path;
return interceptMessage;
}
function cleanInterceptedResponse(response, interceptedResponse) {
delete interceptedResponse.query;
delete interceptedResponse.params;
delete interceptedResponse.path;
/** If we get errors back we have the request data in the response as well */
if (response.error && interceptedResponse.error) {
delete interceptedResponse.data;
delete interceptedResponse.query;
delete interceptedResponse.path;
}
return interceptedResponse;
}
function sendInternalMultipartRequest(subject, message, httpReq) {
return bus.request(subject, message, ms(conf.busTimeout), true).then((optionsRes) => {
const { url } = optionsRes.data.http;
let requestOptions = { uri: url, qs: httpReq.query };
httpReq.headers.data = utils.convertJsonToHttpHeaderString(message);
return new Promise((resolve, reject) => {
httpReq.pipe(
request[httpReq.method.toLowerCase()](requestOptions, (error, response, returnBody) => {
if (!error) {
let body = typeof returnBody === "string" ? JSON.parse(returnBody) : returnBody;
body.headers = response.headers;
resolve(body);
} else {
log.error(
`Got error response when streaming multipart request to ${requestOptions.uri}:`,
error
);
reject({ status: 500, error });
}
})
);
});
});
}
/**
* Transfers status, headers and data from internal bus response to
* http response and sends it.
*
* Can handle text based and binary data if such content type is provided.
*
* @param {String} reqId
* @param {Object} busResponse
* @param {Object} httpResponse
*/
function sendHttpResponse(reqId, busResponse, httpResponse) {
setRequestId(reqId, busResponse);
httpResponse.status(busResponse.status).set(busResponse.headers);
if (isTextResponse(busResponse)) {
httpResponse.send(busResponse.data);
} else if (isBinaryResponse(busResponse)) {
const contentType = getContentType(busResponse);
httpResponse
.set("Content-Type", contentType + "; charset=binary")
.send(Buffer.from(busResponse.data, "base64"));
} else {
httpResponse.json(conf.unwrapMessageData ? busResponse.data : utils.sanitizeResponse(busResponse));
}
}
function setRequestId(reqId, resp) {
if (resp.reqId != reqId) {
log.warn(`Request id in bus response (${resp.reqId}) does not match the one set by API gateway (${reqId})`);
resp.reqId = reqId;
}
}
function isMultipart(httpReq) {
return httpReq.headers["content-type"] && httpReq.headers["content-type"].includes("multipart");
}
/**
* Checks if bus response contains text based content based on its content type.
*
* @param {Object} busResponse
*/
function isTextResponse(busResponse) {
const contentType = getContentType(busResponse);
return constants.TEXT_CONTENT_TYPES.includes(contentType);
}
/**
* Checks if bus response data is base64 encoded binary string.
*
* @param {Object} busResponse
*/
function isBinaryResponse(busResponse) {
const contentType = getContentType(busResponse);
return constants.BINARY_CONTENT_TYPES.includes(contentType);
}
function getContentType(busResponse) {
return (busResponse.headers && (busResponse.headers["content-type"] || busResponse.headers["Content-Type"])) || "";
}
module.exports = {
start: async (busAddress, mongoUrl, httpServerPort) => {
if (conf.enableStats) {
log.info("Enabling stats module, view by visiting /statz");
const client = new mongo.MongoClient(mongoUrl);
const db = (await client.connect()).db();
responseTimeRepo = new ResponseTimeRepo(db);
if (!process.env.CI) await createIndexes(db);
}
if (conf.influxDbUrl) {
log.info("Enabling InfluxDB");
influxRepo = await createInfluxRepo();
}
const startHttpServer = new Promise((resolve, reject) => {
const server = http
.createServer({ maxHeaderSize: conf.maxHeaderSize }, createExpressApp())
.listen(httpServerPort);
server.on("error", reject);
server.on("listening", () => {
log.info("HTTP server listening for on port", httpServerPort);
resolve();
});
return resolve(server);
});
const connectToBus = () => {
return bus.connect(busAddress);
};
return startHttpServer.then((server) => connectToBus().then(() => server));
},
};
async function createIndexes(db) {
try {
await db
.collection(constants.collections.RESPONSE_TIME)
.createIndex({ createdAt: 1 }, { expireAfterSeconds: conf.statsTTL });
} catch (err) {
log.warn(err);
}
}
/**
* Creates and initializes the influx client.
*/
async function createInfluxRepo() {
let influx = null;
try {
influx = await new InfluxRepo({
url: conf.influxDbUrl,
writeInterval: conf.influxWriteInterval,
ipLookup: conf.influxLookupIp,
ipLookupDbUrl: conf.ipLookUpDbUrl,
}).init();
} catch (err) {
log.warn(
"Failed to connect to InfluxDB, API Gateway will start anyways but metrics will not be written to InfluxDB"
);
log.error(err);
}
return influx;
}