-
Notifications
You must be signed in to change notification settings - Fork 7
/
stats.js
95 lines (73 loc) · 2.28 KB
/
stats.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
const logger = require('./logger');
class StatsAggregator {
constructor(clientId) {
this.clientId = clientId;
this.stats = {};
this.errors = {};
}
reset() {
this.stats = {};
this.errors = {};
}
recordSuccess(method, name, responseTime, contentLength) {
logger.info('Record success', method, name, responseTime, contentLength);
this.updateStats(method, name, responseTime);
this.stats[`${method}-${name}`].totalContentLength += contentLength;
}
recordFailure(method, name, responseTime, error) {
logger.info('Record failure', method, name, responseTime, error.message);
this.updateStats(method, name, responseTime);
const statsHash = `${method}-${name}`;
const errorHash = `${statsHash}-${error.message}`;
this.stats[statsHash].failedRequests += 1;
if (!this.errors[errorHash]) {
this.errors[errorHash] = {
name,
method,
occurences: 0,
error: error.message
};
}
this.errors[errorHash].occurences += 1;
}
updateStats(method, name, responseTime) {
const hash = `${method}-${name}`;
const now = Math.trunc(Date.now() / 1000);
if (!this.stats[hash]) {
this.stats[hash] = {
name,
method,
// Key must be a integer, not a string
requestsPerSecond: new Map(),
responseTimes: new Map(),
startTime: now,
lastRequestTime: null,
minResponseTime: responseTime,
maxResponseTime: responseTime,
failedRequests: 0,
totalRequests: 0,
totalContentLength: 0,
totalResponseTime: 0
};
}
const stats = this.stats[hash];
const secBucket = now;
const roundedResTime = Math.trunc(responseTime / 10) * 10;
stats.requestsPerSecond.set(secBucket,
(stats.requestsPerSecond.get(secBucket) || 0) + 1
);
stats.responseTimes.set(roundedResTime,
(stats.responseTimes.get(roundedResTime) || 0) + 1
);
stats.lastRequestTime = now;
if (responseTime < stats.minResponseTime) {
stats.minResponseTime = responseTime;
}
if (responseTime > stats.maxResponseTime) {
stats.maxResponseTime = responseTime;
}
stats.totalRequests += 1;
stats.totalResponseTime += responseTime;
}
}
module.exports = { StatsAggregator };