Skip to content

Commit

Permalink
fix: improve shutdown handlers (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
aapolkovsky authored May 22, 2023
1 parent 21d5d3e commit 68a9120
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
40 changes: 25 additions & 15 deletions src/nodekit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,25 +95,35 @@ export class NodeKit {

this.ctx.stats = prepareClickhouseClient(this.ctx);

this.addShutdownHandler(() => {
return new Promise((resolve) => {
this.tracer.close?.(() => resolve());
});
});
this.addShutdownHandler(() => new Promise<void>((resolve) => this.tracer.close(resolve)));

['SIGTERM', 'SIGINT'].forEach((signal) => {
process.on(signal, () => {
Promise.all(this.shutdownHandlers.map((handler) => handler()))
.then(() => process.exit(0))
.catch((error) => {
this.ctx.logError('Error executing shutdown handlers', error);
process.exit(1);
});
});
});
this.setupShutdownSignals();
}

addShutdownHandler(handler: ShutdownHandler) {
this.shutdownHandlers.push(handler);
}

private setupShutdownSignals() {
const signals = ['SIGTERM', 'SIGINT'] as const;

const handleSignal: ShutdownHandler = (signal) => {
signals.forEach((signalName) => process.off(signalName, handleSignal));

let code = 0;

const promises = this.shutdownHandlers.map((handler) => {
const handlePromise = new Promise((resolve) => resolve(handler(signal)));

return handlePromise.catch((error) => {
code = 1;
this.ctx.logError('Error executing shutdown handler', error);
});
});

Promise.allSettled(promises).then(() => process.exit(code));
};

signals.forEach((signal) => process.on(signal, handleSignal));
}
}
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export interface AppContextParams {}
export type Dict = {[key: string]: unknown};

export interface ShutdownHandler {
(): Promise<void>;
(signal: 'SIGTERM' | 'SIGINT'): Promise<unknown> | void;
}
export interface TelemetryClickhouseTableDescription {
[name: string]: 'number' | 'string' | 'timestamp';
Expand Down

0 comments on commit 68a9120

Please sign in to comment.