@glandjs/core
Version:
Glands is a web framework for Node.js (@core)
72 lines (71 loc) • 2.75 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApplicationLifecycle = void 0;
const hooks_1 = require("../hooks");
class ApplicationLifecycle {
constructor(modulesContainer, logger) {
this.isBootstrapped = false;
this.isShuttingDown = false;
this.shutdownSignals = ['SIGTERM', 'SIGINT', 'SIGHUP'];
this.logger = logger?.child('ApplicationLifecycle');
this.lifecycleScanner = new hooks_1.LifecycleScanner(modulesContainer, logger);
this.setupShutdownHooks();
}
setupShutdownHooks() {
if (typeof process !== 'undefined' && process) {
for (const signal of this.shutdownSignals) {
process.on(signal, async () => {
await this.shutdown(signal);
process.exit(0);
});
}
process.on('uncaughtException', async (error) => {
this.logger?.error(`Uncaught exception: ${error.message}`);
this.logger?.error(error.stack);
await this.shutdown('uncaughtException');
process.exit(1);
});
process.on('unhandledRejection', async (reason) => {
this.logger?.error(`Unhandled rejection: ${reason}`);
await this.shutdown('unhandledRejection');
process.exit(1);
});
}
}
async init() {
this.logger?.info('Initializing modules');
this.lifecycleScanner.scanForHooks();
await this.lifecycleScanner.onModuleInit();
this.logger?.info('Modules initialized');
}
async initChannels() {
this.logger?.info('Initializing channels');
await this.lifecycleScanner.onChannelInit();
this.logger?.info('Channels initialized');
}
async bootstrap() {
if (this.isBootstrapped) {
return;
}
this.logger?.info('Bootstrapping application');
await this.lifecycleScanner.onAppBootstrap();
this.isBootstrapped = true;
this.logger?.info('Application bootstrapped successfully');
}
async shutdown(signal) {
if (this.isShuttingDown) {
return;
}
this.isShuttingDown = true;
this.logger?.info(`Shutting down application${signal ? ` (signal: ${signal})` : ''}`);
try {
await this.lifecycleScanner.onAppShutdown(signal);
await this.lifecycleScanner.onModuleDestroy();
this.logger?.info('Application shutdown complete');
}
catch (error) {
this.logger?.error(`Error during shutdown: ${error.message}`);
}
}
}
exports.ApplicationLifecycle = ApplicationLifecycle;