UNPKG

redis-smq-common

Version:

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

102 lines 2.79 kB
import { v4 as uuid } from 'uuid'; import { async } from '../async/index.js'; import { AbortError } from '../errors/index.js'; import { EventEmitter } from '../event/index.js'; import { PowerSwitch } from '../power-switch/index.js'; export class Runnable extends EventEmitter { id; powerSwitch; forceShutdownOnError = true; cleanUpBeforeShutdown = false; constructor() { super(); this.id = uuid(); this.powerSwitch = new 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 AbortError()); }); 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 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; async.series(tasks, () => { if (this.cleanUpBeforeShutdown) this.shutdown(cb); else this.down(() => cb()); }); } else cb(); } getId() { return this.id; } } //# sourceMappingURL=runnable.js.map