Skip to content

Commit

Permalink
call addShutdownHooks multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
dragos-rebegea committed Nov 20, 2024
1 parent 5a500e2 commit 2e174a1
Showing 1 changed file with 20 additions and 13 deletions.
33 changes: 20 additions & 13 deletions packages/common/src/common/shutdown-aware/shutdown-aware.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export class ShutdownAwareHandler {
private static isShuttingDown = false;
private static defaultTimeout = 30_000; // Default timeout of 30 seconds
private static logger = new OriginLogger(ShutdownAwareHandler.name);
private static apps: Set<(INestApplication | INestMicroservice)> = new Set();

static setDefaultTimeout(timeoutMs: number) {
this.defaultTimeout = timeoutMs;
Expand Down Expand Up @@ -49,25 +50,31 @@ export class ShutdownAwareHandler {
}

static addShutdownHooks(...apps: (INestApplication | INestMicroservice)[]) {
async function handleShutdown(signal: string) {
ShutdownAwareHandler.logger.log(`Received ${signal}. Cleaning up...`);
try {
await ShutdownAwareHandler.signalShutdownAndWait();
ShutdownAwareHandler.logger.log('Shutdown process completed.');
} finally {
for (const app of apps) {
await app.close();
}
process.exit(0); // Ensure the process exits after cleanup
}
apps.forEach(app => this.apps.add(app));

if (this.isInitialized) {
return;
}

readline.createInterface({
input: process.stdin,
output: process.stdout,
}).on('SIGINT', async () => await handleShutdown('SIGINT'));
process.on('SIGTERM', async () => await handleShutdown('SIGTERM'));
}).on('SIGINT', async () => await this.handleShutdown('SIGINT'));
process.on('SIGTERM', async () => await this.handleShutdown('SIGTERM'));

this.isInitialized = true;
}

private static async handleShutdown(signal: string) {
ShutdownAwareHandler.logger.log(`Received ${signal}. Cleaning up...`);
try {
await ShutdownAwareHandler.signalShutdownAndWait();
ShutdownAwareHandler.logger.log('Shutdown process completed.');
} finally {
for (const app of this.apps) {
await app.close();
}
process.exit(0); // Ensure the process exits after cleanup
}
}
}

0 comments on commit 2e174a1

Please sign in to comment.