UNPKG

container.ts

Version:
365 lines 17.2 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); 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 }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var awilix_1 = require("awilix"); var Debug = require("debug"); var lodash_1 = require("lodash"); var rxjs_1 = require("rxjs"); var operators_1 = require("rxjs/operators"); var error_1 = require("../lib/error"); var environment_1 = require("./environment"); var log_1 = require("./log"); /** Container error codes. */ var EContainerError; (function (EContainerError) { EContainerError["Up"] = "ContainerError.Up"; EContainerError["Down"] = "ContainerError.Down"; EContainerError["ModuleRegistered"] = "ContainerError.ModuleRegistered"; })(EContainerError = exports.EContainerError || (exports.EContainerError = {})); /** Container error class. */ var ContainerError = /** @class */ (function (_super) { __extends(ContainerError, _super); function ContainerError(code, cause, context) { return _super.call(this, { name: "ContainerError", value: __assign({ code: code }, context) }, cause) || this; } return ContainerError; }(error_1.ErrorChain)); exports.ContainerError = ContainerError; /** Log message class for stream of module logs. */ var ContainerLogMessage = /** @class */ (function () { function ContainerLogMessage(level, message, metadata, args) { this.level = level; this.message = message; this.metadata = metadata; this.args = args; } return ContainerLogMessage; }()); exports.ContainerLogMessage = ContainerLogMessage; /** Metric message class for stream of module metrics. */ var ContainerMetricMessage = /** @class */ (function () { function ContainerMetricMessage(type, name, value, tags, args) { this.type = type; this.name = name; this.value = value; this.tags = tags; this.args = args; } return ContainerMetricMessage; }()); exports.ContainerMetricMessage = ContainerMetricMessage; /** Container log names. */ var EContainerLog; (function (EContainerLog) { EContainerLog["Up"] = "Container.Up"; EContainerLog["Down"] = "Container.Down"; })(EContainerLog = exports.EContainerLog || (exports.EContainerLog = {})); /** Container scope keys. */ var EContainerScope; (function (EContainerScope) { /** Container reference name resolved internally by modules. */ EContainerScope["Container"] = "Container"; })(EContainerScope = exports.EContainerScope || (exports.EContainerScope = {})); /** * Container class. * Wrapper around awilix library. */ var Container = /** @class */ (function () { /** Creates a new container in proxy resolution mode. */ function Container( /** Required container name, used to namespace modules. */ name, /** Optional container environment. */ environment, /** Optional command line arguments. */ argv) { if (environment === void 0) { environment = new environment_1.Environment(); } if (argv === void 0) { argv = { arguments: [], options: {} }; } this.name = name; this.environment = environment; this.argv = argv; /** Observable module state. */ this.modules$ = new rxjs_1.BehaviorSubject({}); /** Container module logs. */ this.logs$ = new rxjs_1.Subject(); /** Container module metrics. */ this.metrics$ = new rxjs_1.Subject(); this.debug = Debug(this.name); this.container = awilix_1.createContainer({ injectionMode: awilix_1.InjectionMode.PROXY }); this.registerValue(EContainerScope.Container, this); } Object.defineProperty(Container.prototype, "moduleNames", { /** Array of registered module names. */ get: function () { return lodash_1.keys(this.modules$.value); }, enumerable: true, configurable: true }); Object.defineProperty(Container.prototype, "modules", { /** Array of registered modules. */ get: function () { var _this = this; return this.moduleNames.map(function (n) { return _this.container.resolve(n); }); }, enumerable: true, configurable: true }); /** Create scoped container from root container. */ Container.prototype.createScope = function () { return this.container.createScope(); }; /** * Register a module in container. * Throws an error if module of name is already registered. */ Container.prototype.registerModule = function (moduleClass) { var _a; var _this = this; if (this.containerModuleRegistered(moduleClass.moduleName)) { throw new ContainerError(EContainerError.ModuleRegistered, undefined, { moduleName: moduleClass.moduleName }); } var factoryFunction = function (opts) { return _this.containerModuleFactory(moduleClass, opts); }; this.container.register((_a = {}, _a[moduleClass.moduleName] = awilix_1.asFunction(factoryFunction).singleton(), _a)); this.containerModuleState(moduleClass.moduleName, false); return this; }; /** Register named modules in container. */ Container.prototype.registerModules = function (modules) { var _this = this; modules.map(function (mod) { return _this.registerModule(mod); }); return this; }; /** Register a value of type in container. */ Container.prototype.registerValue = function (name, value) { var _a; this.container.register((_a = {}, _a[name] = awilix_1.asValue(value), _a)); return this; }; /** Resolve value or module of type from container by name. */ Container.prototype.resolve = function (name) { return this.container.resolve(name); }; /** Send log message of level for module. */ Container.prototype.sendLog = function (level, message, metadata, args) { this.logs$.next(new ContainerLogMessage(level, message, metadata, args)); }; /** Send metric message of type for module. */ Container.prototype.sendMetric = function (type, name, value, tags, args) { this.metrics$.next(new ContainerMetricMessage(type, name, value, tags, args)); }; /** Observable stream of module logs filtered by level. */ Container.prototype.filterLogs = function (level) { return this.logs$.pipe(operators_1.filter(function (m) { return m.level <= level; })); }; /** Observable stream of module metrics filtered by type. */ Container.prototype.filterMetrics = function (type) { return this.metrics$.pipe(operators_1.filter(function (m) { return m.type === type; })); }; /** * Signal modules to enter operational state. * Module hook method `moduleUp` called in order of dependencies. */ Container.prototype.up = function (timeout) { return __awaiter(this, void 0, void 0, function () { var hooks; var _this = this; return __generator(this, function (_a) { hooks = this.modules.map(function (mod) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: // Wait for module dependencies and then call module up hooks. return [4 /*yield*/, this.containerWhenModulesUp.apply(this, this.containerModuleDependencies(mod))]; case 1: // Wait for module dependencies and then call module up hooks. _a.sent(); return [2 /*return*/, this.containerModuleStateTimeout(mod.moduleUp(), mod.moduleName, true, timeout)]; } }); }); }); return [2 /*return*/, this.containerState(hooks, true)]; }); }); }; /** * Signal modules to leave operational state. * Module hook method `moduleDown` called in order of dependents. */ Container.prototype.down = function (timeout) { return __awaiter(this, void 0, void 0, function () { var hooks; var _this = this; return __generator(this, function (_a) { hooks = this.modules.map(function (mod) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: // Wait for module dependents and then call module down hooks. return [4 /*yield*/, this.containerWhenModulesDown.apply(this, this.containerModuleDependents(mod))]; case 1: // Wait for module dependents and then call module down hooks. _a.sent(); return [2 /*return*/, this.containerModuleStateTimeout(mod.moduleDown(), mod.moduleName, false, timeout)]; } }); }); }); return [2 /*return*/, this.containerState(hooks, false)]; }); }); }; /** Call modules destroy hooks before process exit. */ Container.prototype.destroy = function () { this.modules.map(function (mod) { return mod.moduleDestroy(); }); // Observables clean up. this.modules$.complete(); this.logs$.complete(); this.metrics$.complete(); }; /** Wait for modules to enter operational state before calling next. */ Container.prototype.containerWhenModulesUp = function () { var modules = []; for (var _i = 0; _i < arguments.length; _i++) { modules[_i] = arguments[_i]; } return this.modules$ .pipe(operators_1.filter(function (states) { return modules.reduce(function (previous, current) { return previous && states[current]; }, true); }), operators_1.map(function () { return undefined; }), operators_1.take(1)) .toPromise(); }; /** Wait for modules to leave operational state before calling next. */ Container.prototype.containerWhenModulesDown = function () { var modules = []; for (var _i = 0; _i < arguments.length; _i++) { modules[_i] = arguments[_i]; } return this.modules$ .pipe(operators_1.filter(function (states) { return !modules.reduce(function (previous, current) { return previous || states[current]; }, false); }), operators_1.map(function () { return undefined; }), operators_1.take(1)) .toPromise(); }; /** Create a new instance of module class. */ Container.prototype.containerModuleFactory = function (moduleClass, opts) { return new moduleClass({ moduleName: moduleClass.moduleName, opts: opts }); }; /** Returns list of module names which are dependencies of target module. */ Container.prototype.containerModuleDependencies = function (mod) { var dependencies = mod.moduleDependencies(); return lodash_1.keys(dependencies).map(function (k) { return dependencies[k].moduleName; }); }; /** Returns list of module names which are dependents of target module. */ Container.prototype.containerModuleDependents = function (mod) { var dependents = []; this.modules.map(function (m) { var dependencies = m.moduleDependencies(); var dependent = lodash_1.keys(dependencies).reduce(function (previous, key) { return previous || dependencies[key].moduleName === mod.moduleName; }, false); if (dependent) { dependents.push(m.moduleName); } }); return dependents; }; /** Returns true if module is already registered in container. */ Container.prototype.containerModuleRegistered = function (name) { return this.modules$.value[name] != null; }; /** Wrap module hook promise with timeout operator, call containerModuleState on next. */ Container.prototype.containerModuleStateTimeout = function (hook, moduleName, state, timeout) { var _this = this; if (timeout === void 0) { timeout = 10000; } return rxjs_1.from(hook) .pipe(operators_1.timeout(timeout), operators_1.catchError(function (error) { // Catch and wrap timeout errors with ContainerError. var errorName = state ? EContainerError.Up : EContainerError.Down; return rxjs_1.throwError(new ContainerError(errorName, error, { moduleName: moduleName })); }), operators_1.map(function () { return _this.containerModuleState(moduleName, state); })) .toPromise(); }; /** Update observable modules state for target module. */ Container.prototype.containerModuleState = function (name, state) { var _a; var next = __assign(__assign({}, this.modules$.value), (_a = {}, _a[name] = state, _a)); this.modules$.next(next); }; /** Internal handler for `up` and `down` methods of class. */ Container.prototype.containerState = function (hooks, state) { var _this = this; return rxjs_1.from(Promise.all(hooks)) .pipe(operators_1.map(function () { var message = state ? EContainerLog.Up : EContainerLog.Down; _this.sendLog(log_1.ELogLevel.Informational, message, { name: _this.name }, []); return _this.moduleNames.length; })) .toPromise(); }; return Container; }()); exports.Container = Container; //# sourceMappingURL=container.js.map