2020-08-25 15:17:11 +00:00
|
|
|
const { StatusCodes } = require("http-status-codes");
|
2020-06-22 09:54:01 +00:00
|
|
|
const { sum, sumBy } = require("lodash");
|
|
|
|
const db = require("./db");
|
|
|
|
|
2020-08-14 15:46:38 +00:00
|
|
|
// getStatus returns the server's current health check status
|
2020-06-22 09:54:01 +00:00
|
|
|
function getStatus() {
|
2020-08-14 15:46:38 +00:00
|
|
|
// Grab entry element from DB
|
2020-06-22 09:54:01 +00:00
|
|
|
const entry = db.get("entries").orderBy("date", "desc").head().value();
|
|
|
|
|
2020-08-14 15:46:38 +00:00
|
|
|
// Check that every critical check entry is up
|
|
|
|
if (entry && entry.checks.every(({ up, critical }) => up && critical)) {
|
2020-08-25 15:17:11 +00:00
|
|
|
return StatusCodes.OK;
|
2020-06-22 09:54:01 +00:00
|
|
|
}
|
|
|
|
|
2020-08-14 15:46:38 +00:00
|
|
|
// At least one check failed
|
2020-08-25 15:17:11 +00:00
|
|
|
return StatusCodes.SERVICE_UNAVAILABLE;
|
2020-06-22 09:54:01 +00:00
|
|
|
}
|
|
|
|
|
2020-08-14 15:46:38 +00:00
|
|
|
// getTimeout returns the average time out from a sample of 10 health check
|
|
|
|
// entries.
|
2020-06-22 09:54:01 +00:00
|
|
|
function getTimeout() {
|
2020-08-25 15:17:11 +00:00
|
|
|
if (getStatus() === StatusCodes.SERVICE_UNAVAILABLE) {
|
2020-06-22 09:54:01 +00:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2020-08-14 15:46:38 +00:00
|
|
|
// Grab 10 entries from the database as a sample to determine the average
|
|
|
|
// timeout for the server.
|
2020-06-22 09:54:01 +00:00
|
|
|
const sample = db
|
|
|
|
.get("entries")
|
|
|
|
.orderBy("date", "desc")
|
2020-08-14 15:46:38 +00:00
|
|
|
.filter(({ checks }) => checks.every(({ up, critical }) => up && critical))
|
2020-06-22 09:54:01 +00:00
|
|
|
.take(10)
|
|
|
|
.value();
|
|
|
|
|
2020-08-14 15:46:38 +00:00
|
|
|
// Return average timeout
|
2020-06-22 09:54:01 +00:00
|
|
|
return Math.round(sum(sample.map(({ checks }) => sumBy(checks, "time"))) / sample.size);
|
|
|
|
}
|
|
|
|
|
2020-08-14 15:46:38 +00:00
|
|
|
// getEntriesSinceYesterday gets the health check entries since yesterday
|
2020-06-22 09:54:01 +00:00
|
|
|
function getEntriesSinceYesterday() {
|
|
|
|
const yesterday = new Date();
|
|
|
|
|
|
|
|
yesterday.setDate(yesterday.getDate() - 1);
|
|
|
|
|
|
|
|
return db
|
|
|
|
.get("entries")
|
|
|
|
.orderBy("date", "desc")
|
|
|
|
.filter(({ date }) => date >= yesterday.toISOString())
|
|
|
|
.value();
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = (req, res) => {
|
|
|
|
setTimeout(() => {
|
|
|
|
res.status(getStatus()).send(getEntriesSinceYesterday());
|
|
|
|
}, getTimeout());
|
|
|
|
};
|