-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
71 lines (53 loc) · 1.97 KB
/
main.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
'use strict';
const requestIp = require('request-ip');
const config = require('./config');
const storage = require('./lib/storage');
const reporting = require('./lib/reporting');
const throttling = require('./lib/throttling');
const createSampleFromRequest = require('./lib/util/createSampleFromRequest');
/**
* Calculates ms difference from two process.hrtime points (high resolution time)
*/
function timeSinceInMs(startTime) {
const diff = process.hrtime(startTime);
const time = diff[0] * 1e3 + diff[1] * 1e-6;
return Math.ceil(time);
}
function generateTrafficManagerAgentMiddleware(appConfig) {
config.init(appConfig);
function trafficManagerAgentMiddleware(req, res, next) {
// start measuring time
const startAt = process.hrtime();
const startTimestamp = Number(Date.now().toString());
const ip = requestIp.getClientIp(req);
// override res.send function to register event just before sending response
const originalFn = res.send;
res.send = function trafficManagedSend(body) {
// console.log('Capturing stats');
const timeProcessing = timeSinceInMs(startAt);
const responseSize = body.length;
const statusCode = res.statusCode;
const metadata = {
timestamp: startTimestamp,
timeProcessing,
responseSize,
statusCode
};
const sample = createSampleFromRequest(req, metadata);
storage.add(sample);
reporting.sendEventImmediately(sample);
reporting.sendAggregatedFrameIfReady();
// console.log(`Sending response to client in ${timeProcessing}ms.`);
originalFn.apply(this, arguments);
};
// perform throttling
const shouldBlock = throttling.shouldBlock(ip);
if (shouldBlock) {
const sampleData = createSampleFromRequest(req, { statusCode: 429 });
return throttling.blockRequest(sampleData, res);
}
return next();
}
return trafficManagerAgentMiddleware;
}
module.exports = generateTrafficManagerAgentMiddleware;