@@ -27,6 +27,10 @@ function forkWorkers() {
2727}
2828
2929function installPrimarySignalHandlers ( ) {
30+ let didHandleSigterm = false ;
31+ let didHandleSigint = false ;
32+ let didGracefulExit = false ;
33+
3034 const forward = ( signal : NodeJS . Signals ) => {
3135 for ( const id in cluster . workers ) {
3236 const w = cluster . workers [ id ] ;
@@ -39,21 +43,28 @@ function installPrimarySignalHandlers() {
3943 } ;
4044
4145 const gracefulExit = ( ) => {
42- const timeoutMs = Number ( process . env . GRACEFUL_SHUTDOWN_TIMEOUT || 30_000 ) * 1000 ;
46+ if ( didGracefulExit ) return ;
47+ didGracefulExit = true ;
48+
49+ const timeoutMs = Number ( process . env . GRACEFUL_SHUTDOWN_TIMEOUT || 30_000 ) ;
4350 // wait for workers to exit, then exit the primary too
4451 const maybeExit = ( ) => {
4552 const alive = Object . values ( cluster . workers || { } ) . some ( ( w ) => w && ! w . isDead ( ) ) ;
4653 if ( ! alive ) process . exit ( 0 ) ;
4754 } ;
4855 setInterval ( maybeExit , 1000 ) ;
49- setTimeout ( ( ) => process . exit ( 0 ) , timeoutMs ) . unref ( ) ;
56+ setTimeout ( ( ) => process . exit ( 0 ) , timeoutMs ) ;
5057 } ;
5158
5259 process . on ( "SIGTERM" , ( ) => {
60+ if ( didHandleSigterm ) return ;
61+ didHandleSigterm = true ;
5362 forward ( "SIGTERM" ) ;
5463 gracefulExit ( ) ;
5564 } ) ;
5665 process . on ( "SIGINT" , ( ) => {
66+ if ( didHandleSigint ) return ;
67+ didHandleSigint = true ;
5768 forward ( "SIGINT" ) ;
5869 gracefulExit ( ) ;
5970 } ) ;
@@ -193,25 +204,29 @@ if (ENABLE_CLUSTER && cluster.isPrimary) {
193204 // headers will instead be limited by the maxHeaderSize
194205 server . maxHeadersCount = 0 ;
195206
196- process . on ( "SIGTERM" , ( ) => {
207+ let didCloseServer = false ;
208+
209+ function closeServer ( signal : NodeJS . Signals ) {
210+ if ( didCloseServer ) return ;
211+ didCloseServer = true ;
212+
197213 server . close ( ( err ) => {
198214 if ( err ) {
199215 console . error ( "Error closing express server:" , err ) ;
200216 } else {
201217 console . log ( "Express server closed gracefully." ) ;
202218 }
203219 } ) ;
204- } ) ;
220+ }
221+
222+ process . on ( "SIGTERM" , closeServer ) ;
223+ process . on ( "SIGINT" , closeServer ) ;
205224
206225 socketIo ?. io . attach ( server ) ;
207226 server . removeAllListeners ( "upgrade" ) ; // prevent duplicate upgrades from listeners created by io.attach()
208227
209228 server . on ( "upgrade" , async ( req , socket , head ) => {
210- console . log (
211- `Attemping to upgrade connection at url ${ req . url } with headers: ${ JSON . stringify (
212- req . headers
213- ) } `
214- ) ;
229+ console . log ( `Attemping to upgrade connection at url ${ req . url } ` ) ;
215230
216231 socket . on ( "error" , ( err ) => {
217232 console . error ( "Connection upgrade error:" , err ) ;
0 commit comments