@sha1n/fungus
Version:
A dependency based service graph controller library
88 lines (87 loc) • 3.08 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceController = void 0;
const assert_1 = __importDefault(require("assert"));
const events_1 = require("events");
const logger_1 = require("./logger");
const logger = (0, logger_1.createLogger)('srv-ctrl');
class ServiceController extends events_1.EventEmitter {
service;
startPendingDependencies = new Set();
startPromise;
meta = undefined;
constructor(service) {
super();
this.service = service;
}
get id() {
return this.service.id;
}
addDependency(dependency) {
this.startPendingDependencies.add(dependency.id);
dependency.once('started', (metadata, ctx) => {
// An event emitter should trigger a promise rejection up the stack
this.onDependencyStarted(metadata, ctx).catch(logger.error);
});
}
start = async (ctx) => {
if (this.isStarted()) {
return;
}
return this.startPromise || (this.startPromise = this.doStart(ctx));
};
async doStart(ctx) {
try {
this.meta = await this.service.start(ctx);
ctx.register(this.meta);
this.emit('started', this.meta, ctx);
}
catch (e) {
const hasListeners = this.emit('error', e);
(0, assert_1.default)(hasListeners, 'A service controller is expected to have a listener at this point');
throw e;
}
finally {
this.startPromise = undefined;
}
}
stop = async (ctx) => {
logger.debug('%s: going to shutdown...', this.id);
if (!this.isStarted() && !this.startPromise) {
return;
}
try {
if (this.startPromise) {
logger.debug('%s: waiting for startup to finish...', this.id);
await this.startPromise;
}
logger.debug('%s: stopping...', this.id);
await this.service.stop(ctx);
this.emit('stopped', this.service.id, ctx);
this.meta = undefined;
}
catch (e) {
this.emit('error', e);
throw e;
}
finally {
this.meta = undefined;
}
};
async onDependencyStarted(metadata, ctx) {
logger.debug('%s: dependency started -> %s', this.id, metadata.id);
this.startPendingDependencies.delete(metadata.id);
(0, assert_1.default)(!this.isStarted() && !this.startPromise, `Unexpected internal state. starting=${this.startPromise !== undefined}, started=${this.isStarted()}`);
if (this.startPendingDependencies.size === 0 && !ctx.shuttingDown) {
logger.debug('%s: all dependencies are started', this.id);
await this.start(ctx);
}
}
isStarted() {
return this.meta !== undefined;
}
}
exports.ServiceController = ServiceController;