1 | 'use strit';
|
2 |
|
3 | const { sum } = require('lodash');
|
4 | const { method } = require('bluebird');
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | const ttl = 60 * 1000 * 15;
|
11 |
|
12 | module.exports.makeCounters = () => {
|
13 | const counters = {
|
14 | call: new Map(),
|
15 | success: new Map(),
|
16 | fail: new Map(),
|
17 | };
|
18 | function update(counter, key) {
|
19 | const result = counter.get(key) || 0;
|
20 | counter.set(key, result + 1);
|
21 | setTimeout(() => {
|
22 | const result = counter.get(key) || 1;
|
23 | counter.set(key, result - 1);
|
24 | }, ttl);
|
25 | }
|
26 | function wrapWithMonitoring(fn, name = fn.name) {
|
27 | return method(async function (...args) {
|
28 | update(counters.call, name);
|
29 | try {
|
30 | const result = await fn.call(this, ...args);
|
31 | update(counters.success, name);
|
32 | return result;
|
33 | } catch (e) {
|
34 | update(counters.fail, name);
|
35 | throw e;
|
36 | }
|
37 | });
|
38 | }
|
39 | wrapWithMonitoring.isNetworkHealthy = function isNetworkHealthy() {
|
40 | const allFailed = sum([...counters.fail.values()]);
|
41 | const allSuccess = sum([...counters.success.values()]);
|
42 | const allCalls = sum([...counters.call.values()]);
|
43 |
|
44 |
|
45 |
|
46 |
|
47 | if (allCalls < 100) {
|
48 | return allFailed < 10;
|
49 | }
|
50 | return (allSuccess + allFailed) > allFailed * 10;
|
51 | };
|
52 | wrapWithMonitoring.counters = counters;
|
53 | wrapWithMonitoring.isNetworkHealthy.counters = wrapWithMonitoring.counters;
|
54 | return wrapWithMonitoring;
|
55 | };
|