From 45a1478210b68a46a33952c5137b319829ba098d Mon Sep 17 00:00:00 2001 From: Sosthene Date: Sun, 24 Aug 2025 15:39:42 +0200 Subject: [PATCH] [bug] make shutdown reliable --- src/simple-server.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/simple-server.ts b/src/simple-server.ts index 1d9269d..93cdb79 100644 --- a/src/simple-server.ts +++ b/src/simple-server.ts @@ -377,25 +377,50 @@ export class Server { public shutdown() { console.log('šŸ›‘ Shutting down server...'); + + // Close all active client connections first + for (const [ws, clientId] of this.clients.entries()) { + console.log(`šŸ”Œ Closing connection to ${clientId}...`); + ws.close(1000, 'Server shutting down'); + } + this.clients.clear(); + + // Close the WebSocket server this.wss.close(() => { console.log('āœ… Server shutdown complete'); process.exit(0); }); + + // Force exit after a timeout if graceful shutdown fails + setTimeout(() => { + console.log('āš ļø Force shutdown after timeout'); + process.exit(1); + }, 5000); } } // Handle graceful shutdown +let isShuttingDown = false; + process.on('SIGINT', () => { + if (isShuttingDown) return; + isShuttingDown = true; console.log('\nšŸ›‘ Received SIGINT, shutting down gracefully...'); if (server) { server.shutdown(); + } else { + process.exit(0); } }); process.on('SIGTERM', () => { + if (isShuttingDown) return; + isShuttingDown = true; console.log('\nšŸ›‘ Received SIGTERM, shutting down gracefully...'); if (server) { server.shutdown(); + } else { + process.exit(0); } });