UNPKG

redis-smq-common

Version:

RedisSMQ Common Library provides many components that are mainly used by RedisSMQ and RedisSMQ Monitor.

104 lines 2.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Runnable = void 0; const uuid_1 = require("uuid"); const index_js_1 = require("../async/index.js"); const index_js_2 = require("../errors/index.js"); const index_js_3 = require("../event/index.js"); const index_js_4 = require("../power-switch/index.js"); class Runnable extends index_js_3.EventEmitter { constructor() { super(); this.forceShutdownOnError = true; this.cleanUpBeforeShutdown = false; this.id = (0, uuid_1.v4)(); this.powerSwitch = new index_js_4.PowerSwitch(); } goingUp() { return []; } goingDown() { return []; } up(cb) { this.powerSwitch.commit(); cb(null, true); } down(cb) { this.powerSwitch.commit(); cb(null, true); } handleError(err) { if (this.isRunning()) { this.getLogger().error(err); this.shutdown(() => void 0); } } isRunning() { return this.powerSwitch.isRunning() || this.powerSwitch.isGoingUp(); } isGoingUp() { return this.powerSwitch.isGoingUp(); } isGoingDown() { return this.powerSwitch.isGoingDown(); } isUp() { return this.powerSwitch.isUp(); } isDown() { return this.powerSwitch.isDown(); } run(cb) { const r = this.powerSwitch.goingUp(); if (r) { const tasks = this.goingUp().map((task) => (cb) => { if (this.isGoingUp()) { this.cleanUpBeforeShutdown = true; task(cb); } else cb(new index_js_2.AbortError()); }); index_js_1.async.series(tasks, (err) => { if (this.isRunning()) { if (err) { if (this.forceShutdownOnError) this.shutdown(() => cb(err)); else cb(err); } else this.up(cb); } else this.shutdown(() => cb(new index_js_2.AbortError())); }); } else cb(null, r); } shutdown(cb) { if (this.isRunning()) { if (this.isGoingUp()) this.powerSwitch.rollback(); if (this.isUp()) this.powerSwitch.goingDown(); const tasks = this.goingDown(); this.cleanUpBeforeShutdown = false; index_js_1.async.series(tasks, () => { if (this.cleanUpBeforeShutdown) this.shutdown(cb); else this.down(() => cb()); }); } else cb(); } getId() { return this.id; } } exports.Runnable = Runnable; //# sourceMappingURL=runnable.js.map