-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
541 lines (458 loc) · 15 KB
/
app.js
File metadata and controls
541 lines (458 loc) · 15 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
// API Gateway
//
// Written By Thomas Jay
//
// Copyright 2020, All Rights Reserved
//
// Permission is granted to anyone to use this code for any purpose.
//
// No gaurantee is made for its usefullness or correctness.
const express = require("express");
const compression = require("compression");
const cors = require("cors");
const bodyParser = require("body-parser");
const axios = require("axios");
const CronJob = require("cron").CronJob;
const { v4: uuidv4 } = require("uuid");
const redis = require("ioredis");
const fs = require("fs");
const app = express();
app.use(compression());
app.use(cors());
app.use(bodyParser.json());
const dotEnvLoadStatus = require("dotenv").config();
// Check load of .env parameters, fail if not loaded
if (dotEnvLoadStatus.error) {
// logger.errorRed("Failed to load env params");
throw dotEnvLoadStatus.error;
}
// Loaded from Config File
var serviceMappings;
// Default Server port
const SERVER_PORT = process.env.SERVER_PORT || 8100;
const REDIS_PORT = process.env.REDIS_PORT || 6379;
const REDIS_HOST = process.env.REDIS_HOST || "localhost";
const HEALTH_CHECK_INTERVAL = process.env.HEALTH_CHECK_INTERVAL || 60;
const GATEWAY_ROUTES_CONFIG =
process.env.GATEWAY_ROUTES_CONFIG || defaultgatewayroutes.json;
//configure redis client
const redis_client = redis.createClient({
port: REDIS_PORT,
host: REDIS_HOST,
});
redis_client.on("connect", function () {
//console.log("Redis Connected");
});
app.get("/status", async (req, res) => {
let now = new Date().toLocaleString();
var apiCallReport = [];
try {
redis_client.keys("API*", async function (err, keys) {
if (err) {
res.status(400);
res.send("Report Failed");
}
for (var i = 0, len = keys.length; i < len; i++) {
const key = keys[i];
const value = await redis_client.get(key);
apiCallReport.push({ api: key, calls: value });
}
// Sort results highest to lowest calls
apiCallReport.sort(function (a, b) {
return b.calls > a.calls;
});
res.status(200);
res.json({
title: "API Gateway Analytics",
totalApiCalls: apiCallReport,
});
});
} catch {
res.status(400);
res.send("Report Failed to collect data");
}
});
app.post("/clearredis", async (req, res) => {
redis_client.flushall();
res.status(200);
res.send("Redis Cache Cleared");
});
//Middleware Function to Check Redis Cache
const checkRedisCache = async (req, res, next) => {
const fullURL = req.url;
const shortMatches = fullURL.split("/");
let match = "";
let remainingURL = "";
if (shortMatches.length > 0) {
match = "/" + shortMatches[1];
}
// console.log("match=" + match);
// If we have a match, check for cachable data
if (serviceMappings[match]) {
const serviceMap = serviceMappings[match];
if (serviceMap.cacheable) {
redis_client.get(fullURL, (err, data) => {
if (err) {
console.log(err);
res.status(500).send(err);
}
if (data != null) {
res.status(200).send(data);
} else {
next();
}
});
next();
} else {
next();
}
} else {
next();
}
};
const checkRateLimit = async (req, res, next) => {
const fullURL = req.url;
const ip = req.ip;
const rateLimitKey = fullURL + ":" + ip;
const shortMatches = fullURL.split("/");
let match = "";
let remainingURL = "";
if (shortMatches.length > 0) {
match = "/" + shortMatches[1];
}
// console.log("match=" + match);
// If we have a match, check for ratelimit data
if (serviceMappings[match]) {
const serviceMap = serviceMappings[match];
var currentRateLimitValue = 0;
if (serviceMap.rateLimit > 0) {
try {
currentRateLimitValue = await redis_client.incr(rateLimitKey);
} catch (err) {
console.error("checkRateLimit: could not increment key");
throw err;
}
}
// console.log(
// `Inc Done. ${rateLimitKey} has value: ${currentRateLimitValue}`
// );
if (currentRateLimitValue > serviceMap.rateLimit) {
console.log(
"checkRateLimit: over the limit: " +
currentRateLimitValue +
" of " +
serviceMap.rateLimit
);
return res.status(429).send("Too many requests - try again later");
}
// console.log(
// "Extending rateLimit time. key: " +
// rateLimitKey +
// " value " +
// currentRateLimitValue
// );
redis_client.expire(rateLimitKey, serviceMap.rateLimitDuration);
}
next();
};
app.get("*", checkRateLimit, checkRedisCache, async function (req, res, next) {
processHTTPRequest(req, res, next);
});
app.post("*", checkRateLimit, checkRedisCache, async function (req, res, next) {
processHTTPRequest(req, res, next);
});
app.put("*", checkRateLimit, checkRedisCache, async function (req, res, next) {
processHTTPRequest(req, res, next);
});
app.patch("*", checkRateLimit, checkRedisCache, async function (
req,
res,
next
) {
processHTTPRequest(req, res, next);
});
app.delete("*", checkRateLimit, checkRedisCache, async function (
req,
res,
next
) {
processHTTPRequest(req, res, next);
});
const processHTTPRequest = async function (req, res, next) {
const fullURL = req.url;
//console.log("URL Called: " + fullURL + " " + req.method);
// console.log(req.headers);
// Add / Increment Analytics for # of Calls of API End Point
redis_client.incr("API-" + fullURL.split("?")[0] + ":" + req.method);
const shortMatches = fullURL.split("/");
let match = "";
let remainingURL = "";
if (shortMatches.length > 0) {
match = "/" + shortMatches[1];
remainingURL = fullURL.substr(match.length);
}
// console.log("match=" + match);
if (serviceMappings[match]) {
const serviceMap = serviceMappings[match];
// console.log("Request Type:", req.method);
// Get end point
var endPointURL = serviceMap.endPoints[serviceMap.nextEndPoint].url;
// console.log("nextEndPoint:", serviceMap.nextEndPoint);
// Check for a healthy end point
if (
serviceMap.endPoints[serviceMap.nextEndPoint].lastHealthStatus === false
) {
// If this is the only end point and its down then let caller know
if (serviceMap.endPoints.length == 1) {
console.log("Single Service not available 1");
res.status(500);
res.send("Service not available");
return;
}
// Now we need to look at the other end points, if the have all failed
// then let the caller know of the issue
// otherwise move to the next healthy end point
let failCount = 1;
const maxFails = serviceMap.endPoints.length;
for (let i = 1; i < maxFails; i++) {
// Inc to next end point and check
if (serviceMap.nextEndPoint + 1 < serviceMap.endPoints.length) {
serviceMap.nextEndPoint = serviceMap.nextEndPoint + 1;
} else {
serviceMap.nextEndPoint = 0;
}
endPointURL = serviceMap.endPoints[serviceMap.nextEndPoint].url;
if (
serviceMap.endPoints[serviceMap.nextEndPoint].lastHealthStatus ===
false
) {
// console.log(
// "Found failed health end point " + serviceMap.nextEndPoint
// );
failCount++;
} else {
// Found good healthy end point
// console.log("Found good health end point " + serviceMap.nextEndPoint);
break;
}
}
if (failCount == maxFails) {
console.log("No Services Service not available ");
res.status(500);
res.send("Service not available");
return;
}
}
// Increment end point if more then 1
if (serviceMap.endPoints.length > 1) {
if (serviceMap.nextEndPoint + 1 < serviceMap.endPoints.length) {
serviceMap.nextEndPoint = serviceMap.nextEndPoint + 1;
} else {
serviceMap.nextEndPoint = 0;
}
}
if (req.method === "GET") {
// console.log("Process GET");
// Pass all headers from caller to the new end point
axios
.get(endPointURL + remainingURL, { headers: req.headers })
.then(function (response) {
res.status(response.status);
//console.log(response.headers);
// Pass response headers to caller
res.headers = response.headers;
res.send(response.data);
//add data to Redis
// redis_client.setex(id, 3600, JSON.stringify(starShipInfoData));
})
.catch(function (error) {
if (error.response && error.response.status) {
// handle error
res.status(error.response.status);
res.send(error.response.data);
} else {
console.log("Service not available 2");
res.status(500);
res.send("Service Unavailable");
}
});
}
if (req.method === "POST") {
// Pass all headers from caller to the new end point
const bodyData = req.body;
// console.log("Process POST : " + bodyData);
axios
.post(endPointURL + remainingURL, bodyData, { headers: req.headers })
.then(function (response) {
res.status(response.status);
//console.log(response.headers);
// Pass response headers to caller
res.headers = response.headers;
res.send(response.data);
//add data to Redis
// redis_client.setex(id, 3600, JSON.stringify(starShipInfoData));
})
.catch(function (error) {
if (error.response && error.response.status) {
// handle error
res.status(error.response.status);
res.send(error.response.data);
} else {
console.log("Service not available 2");
res.status(500);
res.send("Service Unavailable");
}
});
}
if (req.method === "PUT") {
// Pass all headers from caller to the new end point
const bodyData = req.body;
// console.log("Process POST : " + bodyData);
axios
.put(endPointURL + remainingURL, bodyData, {
headers: req.headers,
})
.then(function (response) {
res.status(response.status);
//console.log(response.headers);
// Pass response headers to caller
res.headers = response.headers;
res.send(response.data);
//add data to Redis
// redis_client.setex(id, 3600, JSON.stringify(starShipInfoData));
})
.catch(function (error) {
if (error.response && error.response.status) {
// handle error
res.status(error.response.status);
res.send(error.response.data);
} else {
console.log("Service not available 2");
res.status(500);
res.send("Service Unavailable");
}
});
}
if (req.method === "PATCH") {
// Pass all headers from caller to the new end point
const bodyData = req.body;
// console.log("Process POST : " + bodyData);
axios
.patch(endPointURL + remainingURL, bodyData, {
headers: req.headers,
})
.then(function (response) {
res.status(response.status);
//console.log(response.headers);
// Pass response headers to caller
res.headers = response.headers;
res.send(response.data);
//add data to Redis
// redis_client.setex(id, 3600, JSON.stringify(starShipInfoData));
})
.catch(function (error) {
if (error.response && error.response.status) {
// handle error
res.status(error.response.status);
res.send(error.response.data);
} else {
console.log("Service not available 2");
res.status(500);
res.send("Service Unavailable");
}
});
}
if (req.method === "DELETE") {
// Pass all headers from caller to the new end point
const bodyData = req.body;
// console.log("Process POST : " + bodyData);
axios
.delete(endPointURL + remainingURL, bodyData, {
headers: req.headers,
})
.then(function (response) {
res.status(response.status);
//console.log(response.headers);
// Pass response headers to caller
res.headers = response.headers;
res.send(response.data);
//add data to Redis
// redis_client.setex(id, 3600, JSON.stringify(starShipInfoData));
})
.catch(function (error) {
if (error.response && error.response.status) {
// handle error
res.status(error.response.status);
res.send(error.response.data);
} else {
console.log("Service not available 2");
res.status(500);
res.send("Service Unavailable");
}
});
}
} else {
res.status(400);
res.send("Failed to resolve mapping");
}
};
// Health Check processing
const processHealthCheck = async function () {
// console.log(
// "Health Check Processing every " + HEALTH_CHECK_INTERVAL + " seconds"
// );
for (const serviceMappingKey in serviceMappings) {
// console.log(" Key: " + serviceMappingKey);
// console.log(`${serviceMappingKey}: ${object[property]}`);
const serviceMapping = serviceMappings[serviceMappingKey];
for (const endPoint of serviceMapping.endPoints) {
//console.log("healthURL: " + endPoint.healthURL);
try {
const healthResponse = await axios.get(endPoint.healthURL);
// console.log("Health status=" + healthResponse.status);
// Check for healthy status
if (healthResponse.status === 200) {
// console.log("Health true");
endPoint.lastHealthStatus = true;
} else {
endPoint.lastHealthStatus = false;
// console.log("Health false");
console.log("Failed healthURL: " + endPoint.healthURL);
}
} catch (error) {
console.log("Failed healthURL: " + endPoint.healthURL);
// console.log("Health Failure: " + endPoint.healthURL);
endPoint.lastHealthStatus = false;
// console.log("Health false");
}
}
}
};
// Fire health check in 1 second
setTimeout(processHealthCheck, 1000);
// Run health Check for each end point that has a health check url
var healthCheckCronJob = new CronJob(
"*/" + HEALTH_CHECK_INTERVAL + " * * * * *",
processHealthCheck,
null,
true,
"America/Los_Angeles"
);
healthCheckCronJob.start();
// Read Config json file
fs.readFile(GATEWAY_ROUTES_CONFIG, function (err, data) {
// Check for errors
if (err) {
console.log("Config file error");
throw err;
}
// Converting to JSON
const configJSON = JSON.parse(data);
serviceMappings = configJSON;
console.log(JSON.stringify(serviceMappings)); // Print Config
});
// Start server
var server = app.listen(SERVER_PORT, function () {
var port = server.address().port;
console.log("API Gateway Server started... port:" + port);
});