UNPKG

2.22 kBJavaScriptView Raw
1'use strit';
2
3const { sum } = require('lodash');
4const { method } = require('bluebird');
5// we remove entries after 15 minutes, note that this isn't accurate because
6// we remove the "fail"/"success" 10 minutes after we add them (and not the "call")
7// this is fine since these values are an estimation and not an accurate representation
8// we poll them when a test fails - so values older than 15 minutes (10 minutes is
9// the default timeout) are hardly relevant.
10const ttl = 60 * 1000 * 15;
11
12module.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 // we declare a test unhealthy network wise if
44 // 1. more than 10 requests failed and there are fewer than 100 requests
45 // 2. more than 10% of requests (out of finished requests) failed
46 // note that the network can be unhealthy but the test would still pass
47 if (allCalls < 100) {
48 return allFailed < 10;
49 }
50 return (allSuccess + allFailed) > allFailed * 10;
51 };
52 wrapWithMonitoring.counters = counters; // expose the counters used to the outside
53 wrapWithMonitoring.isNetworkHealthy.counters = wrapWithMonitoring.counters;
54 return wrapWithMonitoring;
55};