Skip to content

Commit 27e47b7

Browse files
committed
bugfix: Ensure proper shutdown process signal handling propagation
1 parent 3522f15 commit 27e47b7

1 file changed

Lines changed: 11 additions & 9 deletions

File tree

app/server.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
/** Module dependencies */
44
import config from 'config';
5-
import http from 'node:http';
5+
import { createServer } from 'node:http';
66

77
import app from './app';
88
import getLogger from './src/components/log';
@@ -19,14 +19,13 @@ process.on('unhandledRejection', (err: Error): void => {
1919
});
2020

2121
// Graceful shutdown support
22-
['SIGTERM', 'SIGINT', 'SIGUSR1', 'SIGUSR2'].forEach((signal) => {
22+
['SIGHUP', 'SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach((signal) => {
2323
process.on(signal, () => shutdown(signal as NodeJS.Signals));
2424
});
2525
process.on('exit', () => log.info('Exiting...'));
2626

2727
// Create HTTP server and listen on provided port, on all network interfaces.
28-
// eslint-disable-next-line @typescript-eslint/no-misused-promises
29-
const server = http.createServer(app);
28+
const server = createServer(app);
3029
server.listen(port, () => {
3130
log.info(`Server running on http://localhost:${port}`);
3231
});
@@ -72,11 +71,11 @@ function onError(error: { syscall?: string; code: string }): void {
7271
switch (error.code) {
7372
case 'EACCES':
7473
log.error(`${bind} requires elevated privileges`);
75-
process.exit(1);
74+
shutdown('SIGABRT');
7675
break;
7776
case 'EADDRINUSE':
7877
log.error(`${bind} is already in use`);
79-
process.exit(1);
78+
shutdown('SIGABRT');
8079
break;
8180
default:
8281
throw error; // eslint-disable-line @typescript-eslint/only-throw-error
@@ -86,13 +85,16 @@ function onError(error: { syscall?: string; code: string }): void {
8685
/**
8786
* Gracefully shuts down the server and exits the process.
8887
* @see https://nodejs.org/api/http.html#servercloseallconnections
88+
* @param signal - Optional termination signal (e.g., 'SIGINT', 'SIGTERM').
8989
*/
90-
function cleanup(): void {
90+
function cleanup(signal?: NodeJS.Signals): void {
9191
state.ready = false;
9292
server.close(() => {
93+
log.debug('Closing all server connections...');
9394
server.closeAllConnections();
9495
log.info('Server shut down');
95-
process.exit(0);
96+
if (signal) process.kill(process.pid, signal);
97+
else process.exit();
9698
});
9799
}
98100

@@ -106,7 +108,7 @@ function shutdown(signal: NodeJS.Signals): void {
106108

107109
// Stop periodic 10 second connection probes
108110
if (probeId) clearInterval(probeId);
109-
cleanup();
111+
cleanup(signal);
110112
}
111113

112114
/**

0 commit comments

Comments
 (0)