UNPKG

server-status-check

Version:

query the server periodically to check whether it is up

217 lines (216 loc) 11.4 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var Dev_ServerBugError_1 = __importDefault(require("../errors/Dev_ServerBugError")); var sleep_1 = __importDefault(require("swiss-army-knifey/build/src/utils/sleep")); var getStringDate_1 = require("swiss-army-knifey/build/src/utils/getStringDate"); function isWrappedStatusWithInitializedErrors(w) { return w.errors !== undefined && Array.isArray(w.errors); } var StatusCheckService = /** @class */ (function () { function StatusCheckService(_a) { var notifyAll = _a.notifyAll, serverUri = _a.serverUri, checkStatus = _a.checkStatus, checkInterval = _a.checkInterval, onFailNotifyHoursInterval = _a.onFailNotifyHoursInterval, notificationMessages = _a.notificationMessages; if (!notifyAll) { throw new Dev_ServerBugError_1.default('StatusCheck service needs notifyAll to operate'); } this.checkInterval = checkInterval; this.userProvidedCheckStatus = checkStatus; this.lastChecked = null; this.lastEmailSentTime = null; this.notifyAll = notifyAll; this.onFailNotifyHoursInterval = onFailNotifyHoursInterval; this.serverUri = serverUri; this.wrappedStatus = { status: null, errors: [] }; this.statusChecksCount = 0; if (notificationMessages.all !== undefined) { this.notificationMessages = { email: notificationMessages.all, sms: notificationMessages.all, }; } else { this.notificationMessages = notificationMessages; } } StatusCheckService.prototype.run = function () { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!1) return [3 /*break*/, 3]; _a = this.handleNewStatus; return [4 /*yield*/, this.checkStatus()]; case 1: _a.apply(this, [_b.sent()]); return [4 /*yield*/, (0, sleep_1.default)(this.checkInterval * 1000)]; case 2: _b.sent(); return [3 /*break*/, 0]; case 3: return [2 /*return*/]; } }); }); }; StatusCheckService.prototype.statusChanged = function (status) { return this.wrappedStatus.status !== status; }; StatusCheckService.prototype.changedStatusOrDownStatusForMoreThanOneHour = function (status) { var notifyOnlyOnStatusChanges = this.onFailNotifyHoursInterval === 0; var notifiedTooLongAgo = this.lastEmailSentTime !== null && this.lastEmailSentTime <= (0, getStringDate_1.hoursAgo)(this.onFailNotifyHoursInterval); return this.statusChanged(status) || (!notifyOnlyOnStatusChanges && (!status && notifiedTooLongAgo)); }; StatusCheckService.prototype.shouldNotifyCurrentStatus = function (status) { return this.changedStatusOrDownStatusForMoreThanOneHour(status); }; StatusCheckService.prototype.getStatusFriendlyPhrase = function (status) { return (status === null ? 'Please wait: system status' : status ? 'Good news: system' : 'Alert: system') + " is " + this.getStatusName(status) + "!"; }; StatusCheckService.prototype.notifyServiceStatus = function (_a) { var status = _a.status; return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_b) { switch (_b.label) { case 0: if (!(this.lastChecked !== null && status !== null)) return [3 /*break*/, 2]; return [4 /*yield*/, this.notifyAll({ email: __assign({}, this.notificationMessages.email[status ? "up" : "down"]), sms: __assign({}, this.notificationMessages.sms[status ? "up" : "down"]), })]; case 1: _b.sent(); _b.label = 2; case 2: return [2 /*return*/]; } }); }); }; StatusCheckService.prototype.handleNewStatus = function (w) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { if (this.shouldNotifyCurrentStatus(w.status)) { this.notifyServiceStatus(w); this.lastEmailSentTime = Date.now(); } this.wrappedStatus = isWrappedStatusWithInitializedErrors(w) ? w : __assign(__assign({}, w), { errors: [] }); return [2 /*return*/]; }); }); }; StatusCheckService.prototype.checkStatus = function () { return __awaiter(this, void 0, void 0, function () { var wrappedStatus, err_1; return __generator(this, function (_a) { switch (_a.label) { case 0: wrappedStatus = { status: false }; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this.userProvidedCheckStatus()]; case 2: wrappedStatus = _a.sent(); return [3 /*break*/, 4]; case 3: err_1 = _a.sent(); this.handleFailedRequest(err_1); return [3 /*break*/, 4]; case 4: this.statusChecksCount++; this.lastChecked = Date.now(); return [2 /*return*/, wrappedStatus]; } }); }); }; StatusCheckService.prototype.handleFailedRequest = function (err) { throw err; }; StatusCheckService.prototype.getCheckIntervalInMinutes = function () { return Math.ceil(this.checkInterval / 60); }; StatusCheckService.prototype.getStatusStats = function () { var dateLastChecked = this.lastChecked === null ? 'Never' : new Date(this.lastChecked).toLocaleDateString() + ", " + new Date(this.lastChecked).toLocaleTimeString(); var checkIntervalInMinutes = this.getCheckIntervalInMinutes(); var checksSpreeCount = this.statusChecksCount; var friendlyStatusPhrase = this.wrappedStatus.status === null ? 'Unknown' : this.getStatusFriendlyPhrase(this.wrappedStatus.status); var friendlyFullSentence = (this.lastChecked === null || this.wrappedStatus.status === null) ? "Not checked yet. Please wait " + checkIntervalInMinutes + " min. or so and refresh this page." : friendlyStatusPhrase + ". Last time I checked was on " + dateLastChecked.split(', ').join(' at ') + " (checked " + checksSpreeCount + " time" + (checksSpreeCount === 1 ? '' : 's') + " in a row without restarting). I check every " + checkIntervalInMinutes + " min."; var secondsBetweenLastCheckAndNow = Math.floor((Date.now() - (this.lastChecked || Date.now())) / 1000); var aliveSeconds = this.checkInterval * (this.statusChecksCount - 1) + (secondsBetweenLastCheckAndNow < this.checkInterval ? secondsBetweenLastCheckAndNow : 0); var aliveForYMDHMS = (0, getStringDate_1.secondsToYMWDHMSSentence)(aliveSeconds); return { errors: this.wrappedStatus.errors, friendlyFullSentence: friendlyFullSentence, friendlyStatusPhrase: friendlyStatusPhrase, checkIntervalInMinutes: checkIntervalInMinutes, dateLastChecked: dateLastChecked, checksSpreeCount: checksSpreeCount, statusName: this.getStatusName(this.wrappedStatus.status), aliveForYMDHMS: aliveForYMDHMS, }; }; StatusCheckService.prototype.getStatusName = function (status) { if (status === null) return 'unknown'; return status ? 'up' : 'down'; }; return StatusCheckService; }()); exports.default = StatusCheckService;