@5minds/processcube_engine
Version:
The ProcessCube Engine. Stores and executes BPMNs.
274 lines • 11.5 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.startup = startup;
exports.shutdown = shutdown;
const fs_1 = __importDefault(require("fs"));
const inversify_1 = require("inversify");
const minimist_1 = __importDefault(require("minimist"));
const path_1 = __importDefault(require("path"));
const processcube_engine_sdk_1 = require("@5minds/processcube_engine_sdk");
const index_1 = require("./Contracts/InternalDataModels/index");
const IocRegistrations_1 = require("./Contracts/IocRegistrations");
require("./ExternalLibSettings");
const MainIocModule_1 = require("./MainIocModule");
const ArgumentParser_1 = __importDefault(require("./Tools/ArgumentParser"));
const Configurator_1 = __importDefault(require("./Tools/Configurator"));
const DatabaseIntegrityChecker_1 = __importDefault(require("./Tools/DatabaseAdaptersSequelize/Lib/DatabaseIntegrityChecker"));
const Migrator_1 = __importDefault(require("./Tools/DatabaseAdaptersSequelize/Migrator"));
const environment = __importStar(require("./Tools/Environment"));
const ExtensionModules_1 = require("./Tools/ExtensionModules");
const logger = new processcube_engine_sdk_1.Logger('application');
process.title = 'Engine Main';
let container;
process.on('exit', (code) => {
console.log(`Main Thread is exiting with code: ${code}`);
console.trace();
});
process.on('unhandledRejection', (error) => {
if (error.name === 'SequelizeConnectionRefusedError' || error.name === 'AssertionError') {
logger.error('-- An unhandled error was caught! --', {
err: error,
});
setTimeout(() => process.exit(1), 2000);
}
logger.warn('-- An unhandled error was caught! --', {
err: error,
});
});
process.on('SIGINT', shutdown);
process.on('SIGHUP', shutdown);
process.on('SIGTERM', shutdown);
async function startup(resumeProcessInstancesManually = false) {
const processArgs = (0, minimist_1.default)(process.argv.slice(2));
process.env.appRootDir = process.env.IS_INTEGRATION_TEST_RUN ? path_1.default.resolve(__dirname, '..', '..') : path_1.default.resolve(__dirname, '..');
showDeprecatedHints(processArgs);
checkForUnknownArgs(processArgs);
const startupArgs = mergeArgs(processArgs);
await initializeConfiguration(startupArgs);
process.env.engineId = Configurator_1.default.application().id;
logger.info('Configured engineId.', {
engineId: process.env.engineId,
});
validateConfiguration();
container = new inversify_1.Container();
container.bind(IocRegistrations_1.IocRegistrationKeys.internal.Container).toConstantValue(container);
(0, MainIocModule_1.createIocRegistrations)(container);
startupArgs.resumeProcessInstancesManually = resumeProcessInstancesManually || process.env.DEBUG_SKIP_RESUMING === 'true';
if (startupArgs.resumeProcessInstancesManually && !process.env.IS_INTEGRATION_TEST_RUN) {
logger.warn(`DEBUG_SKIP_RESUMING is set to true. Process Instances will not be resumed. Only use this for Debugging purposes, NEVER in production!`);
}
if (process.env.IS_INTEGRATION_TEST_RUN) {
global.__container__ = container;
ExtensionModules_1.eventMiddlewares.initialize(container);
// During integrationtests, these are run by the Main Thread, because the database adapters are also initialized there.
// In normal setups, these are run by the Runtime worker.
const pathToMigrations = path_1.default.resolve(process.env.appRootDir, 'dist_test', 'src', 'Tools', 'DatabaseAdaptersSequelize', 'Migrations');
await (0, Migrator_1.default)(pathToMigrations);
await (0, DatabaseIntegrityChecker_1.default)();
}
await initializeIocComponents();
const server = container.get(IocRegistrations_1.IocRegistrationKeys.internal.EngineServer);
await server.initialize();
const fileToTouch = Configurator_1.default.application().touchFileOnReady;
if (fileToTouch && fileToTouch !== '') {
await touchOnReadyFile(fileToTouch);
}
logger.info('Startup finished.');
}
async function shutdown(code) {
logger.info('Shutting down...');
const server = container.get(IocRegistrations_1.IocRegistrationKeys.internal.EngineServer);
await server.close();
const exitCode = typeof code === 'number' ? code : 0;
if (typeof code === 'string') {
logger.warn(`Cannot use String Argument '${code}' for process.exit(). NodeJS 20+ enforces numeric exit codes. Using 0 instead.`);
}
process.exit(exitCode);
}
async function touchOnReadyFile(fileToTouch) {
if (fs_1.default.existsSync(fileToTouch)) {
const time = new Date();
try {
await fs_1.default.promises.utimes(fileToTouch, time, time);
}
catch (error) {
logger.warn(`Could not touch onReady file at \`${fileToTouch}\`:`, error);
return;
}
}
else {
try {
const fileHandle = await fs_1.default.promises.open(fileToTouch, 'wx');
await fileHandle.close();
}
catch (error) {
logger.warn(`Could not create onReady file at \`${fileToTouch}\`:`, error);
return;
}
}
logger.info(`onReady file was successfully written to \`${fileToTouch}\`.`);
}
function showDeprecatedHints(args) {
if (!args) {
return;
}
if (args.sqlitePath != undefined) {
logger.warn('Deprecated: Argument "sqlitePath" is deprecated.Please use "sqlite-path" instead.');
}
if (args.logFilePath != undefined) {
logger.warn('Deprecated: Argument "logFilePath" is deprecated.');
}
if (args['log-file-path'] != undefined) {
logger.warn('Deprecated: Argument "log-file-path" is deprecated.');
}
if (args['logsDir'] != undefined) {
logger.warn('Deprecated: Argument "logsDir" is deprecated.');
}
if (args['logs-dir'] != undefined) {
logger.warn('Deprecated: Argument "logs-dir" is deprecated.');
}
if (args.minimalSetup != undefined) {
logger.warn('Deprecated: Argument "minimalSetup" is deprecated.');
}
if (args.workDir != undefined) {
logger.warn('Deprecated: Argument "workDir" is deprecated. Please use "work-dir" instead.');
}
if (args.enableHttp != undefined) {
logger.warn('Deprecated: Argument "enableHttp" is deprecated. Please use "enable-http" instead.');
}
if (args.extensionsDir != undefined) {
logger.warn('Deprecated: Argument "extensionsDir" is deprecated. Please use "extensions-dir" instead.');
}
if (args.seedDir != undefined) {
logger.warn('Deprecated: Argument "seedDir" is deprecated. Please use "seed-dir" instead.');
}
}
function checkForUnknownArgs(args) {
if (process.env.IS_INTEGRATION_TEST_RUN || !args) {
return;
}
const knownArgs = [
// Deprecated
'enableHttp',
'extensionsDir',
'logFilePath',
'log-file-path',
'logs-dir',
'logsDir',
'minimalSetup',
'sqlitePath',
'seedDir',
'workDir',
'enable-http',
'extensions-dir',
'seed-dir',
'sqlite-path',
'use-http-root-routes',
'work-dir',
'skip-db-integrity-checks',
'help',
'id',
'name',
'port',
'config-file',
'version',
];
for (const arg of Object.keys(args)) {
if (!knownArgs.includes(arg) && arg !== '_') {
throw new Error(`Failure in setup: Unkown argument ${arg}`);
}
}
}
function mergeArgs(args) {
if (!args) {
return undefined;
}
const mergedArgs = Object.assign({}, args);
if (args['skip-db-integrity-checks']) {
mergedArgs.skipDBIntegrityChecks = args['skip-db-integrity-checks'];
}
if (args['sqlite-path']) {
mergedArgs.sqlitePath = args['sqlite-path'];
}
if (args['minimal-setup']) {
mergedArgs.minimalSetup = args['minimal-setup'];
}
if (args['work-dir']) {
mergedArgs.workDir = args['work-dir'];
}
if (args['config-file']) {
mergedArgs.configFile = args['config-file'];
}
if (args['enable-http']) {
mergedArgs.enableHttp = args['enable-http'];
}
if (args['extensions-dir']) {
mergedArgs.extensionsDir = args['extensions-dir'];
}
if (args['seed-dir']) {
mergedArgs.seedDir = args['seed-dir'];
}
return mergedArgs;
}
async function initializeConfiguration(args) {
await (0, ArgumentParser_1.default)(args);
await environment.loadConfig(environment.workerThreadIds.main);
}
function validateConfiguration() {
// This can be a string value, because parameters provided through the console are always interpreted as strings.
const rootAccessTokenAllowed = Configurator_1.default.iam()?.allowAnonymousRootAccess == 'true' || Configurator_1.default.iam()?.allowAnonymousRootAccess == true;
const defaultCorsOrigin = Configurator_1.default.httpServer()?.allowedCorsOrigins.includes('*');
const isProductionNodeEnv = process.env.NODE_ENV?.indexOf('test') === -1;
if (isProductionNodeEnv && rootAccessTokenAllowed) {
logger.warn('allowAnonymousRootAccess is set to true. This allows unauthorized access with no restrictions. Never use this setting in a production environment!');
}
if (isProductionNodeEnv && defaultCorsOrigin) {
logger.warn('allowedCorsOrigins is set to ["*"]. This allows requests from any origin. Never use this setting in a production environment!');
}
}
async function initializeIocComponents() {
if (!container.isBound(index_1.initializableComponentTag)) {
return;
}
const initializableComponents = container.getAll(index_1.initializableComponentTag);
for (const initializableComponent of initializableComponents) {
await initializableComponent.initialize();
}
}
//# sourceMappingURL=Main.js.map