-
Notifications
You must be signed in to change notification settings - Fork 0
/
status.js
87 lines (65 loc) · 2.25 KB
/
status.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
/* Constructor */
var status = function (config)
{
var self = this;
self.config = config ||
{};
self.models = self.config.models;
self.cachedCount;
self.okStatus = self.config.okStatus || 200; // A-O-K
self.nokStatus = self.config.nokStatus || 503; // Service Unavailable
self.slowStatus = self.config.slowStatus || 408; // Request timeout
self.cacheTimer = self.config.cacheTimer || 30000; // 30 seconds
self.dbTimeout = self.config.dbTimeout || 10000; // 10 seconds
// Cache invalidator
setInterval(function ()
{
self.cachedCount = 0;
}, self.cacheTimer);
self.healthStatus = function (callback)
{
if (!self.models || !self.models.length) return callback(self.okStatus);
if (self.cachedCount >= self.models.length) return callback(self.okStatus);
var cancelled, done = false;
Promise.all(self.models.map(function (Model)
{
return Model.count().reflect();
})).then(function (results)
{
done = true;
if (cancelled) return;
if (!results || !results.length) throw new Error();
self.cachedCount = 0;
results.forEach(function (res)
{
if (!res.isFulfilled()) throw new Error('DB not fulfilling requests');
else if (res.value() >= 0) self.cachedCount++;
else throw new Error();
});
if (self.cachedCount < self.models.length) throw new Error();
callback(self.okStatus);
}).catch(function (err)
{
done = true;
if (cancelled) return;
if (self.cachedCount >= self.models.length) callback(self.okStatus);
else callback(self.nokStatus);
});
// Manual timer for DB queries for health check
// -- in order to get accurate info on when the service is slow
setTimeout(function ()
{
if (done) return;
cancelled = true;
callback(self.slowStatus);
}, self.dbTimeout);
};
self.health = function (req, res)
{
self.healthStatus(function (status)
{
res.sendStatus(status);
});
};
}
module.exports = status;