From 0438a5fd5fb31cd58ab759ab7a67772f4f76771b Mon Sep 17 00:00:00 2001 From: Clay Date: Thu, 3 Dec 2026 15:39:35 -0500 Subject: [PATCH] Harden shutdown: graceful HTTP/sweep/DB close; add process error handlers --- src/server.js | 61 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 51 insertions(+), 10 deletions(-) diff --git a/src/server.js b/src/server.js index fe40df3..285197f 100644 --- a/src/server.js +++ b/src/server.js @@ -15,7 +15,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { PORT, LISTEN_HOST, SESSION_SECRET, TRUST_PROXY, COOKIE_SECURE, SESSION_MAX_AGE_MS, logStartupConfig } from './config.js'; -import { getDb } from './db.js'; +import { closeDb, getDb } from './db.js'; import { SqliteSessionStore } from './sqlite-session-store.js'; import * as oscar from './oscar.js'; import { authRouter, cleanupSessionById } from './routes/auth.js'; @@ -124,12 +124,40 @@ app.use((err, _req, res, _next) => { res.status(500).json({ error: 'Internal server error' }); }); +let httpServer = null; +let sweepTimer = null; let shuttingDown = false; -async function shutdown(signal) { +async function shutdown(signal, { exitCode = 0, err } = {}) { if (shuttingDown) return; shuttingDown = true; - console.log(`[shutdown] received ${signal}, ending OSCAR sessions...`); + if (err) console.error(`[shutdown] ${signal}:`, err); + else console.log(`[shutdown] received ${signal}, shutting down...`); + + const forceTimer = setTimeout(() => { + console.error('[shutdown] forced exit after timeout'); + process.exit(exitCode || 1); + }, 10_000); + forceTimer.unref?.(); + + if (sweepTimer) { + clearInterval(sweepTimer); + sweepTimer = null; + } + try { app.locals.sessionStore?.stop?.(); } catch (e) { console.warn('[shutdown] session store stop failed:', e.message); } + + if (httpServer) { + await new Promise((resolve) => { + try { + httpServer.closeIdleConnections?.(); + httpServer.close(() => resolve()); + } catch { + resolve(); + } + }); + httpServer = null; + } + const tasks = []; for (const rec of sessionsStore.allSessions()) { rec.polling = false; @@ -141,20 +169,33 @@ async function shutdown(signal) { if (rec.aimsid) { tasks.push( oscar.endSession(rec.aimsid, { base: rec.webapiBase }) - .catch((err) => console.warn(`[shutdown] endSession failed for ${rec.screenName}:`, err.message)) + .catch((e) => console.warn(`[shutdown] endSession failed for ${rec.screenName}:`, e.message)) ); } } await Promise.allSettled(tasks); + + try { closeDb(); } catch (e) { console.warn('[shutdown] db close failed:', e.message); } console.log('[shutdown] done'); - process.exit(0); + process.exit(exitCode); } -process.on('SIGINT', () => { void shutdown('SIGINT'); }); -process.on('SIGTERM', () => { void shutdown('SIGTERM'); }); +process.on('SIGINT', () => { void shutdown('SIGINT', { exitCode: 0 }); }); +process.on('SIGTERM', () => { void shutdown('SIGTERM', { exitCode: 0 }); }); + +process.on('unhandledRejection', (reason) => { + console.error('[process] unhandledRejection:', reason); + void shutdown('unhandledRejection', { exitCode: 1 }); +}); + +process.on('uncaughtException', (err) => { + console.error('[process] uncaughtException:', err); + void shutdown('uncaughtException', { exitCode: 1 }); +}); function startSessionSweep() { - const timer = setInterval(async () => { + if (sweepTimer) clearInterval(sweepTimer); + sweepTimer = setInterval(async () => { try { const now = Date.now(); for (const rec of Array.from(sessionsStore.allSessions())) { @@ -175,7 +216,7 @@ function startSessionSweep() { console.error('[sweep] failed:', err.message); } }, 5 * 60 * 1000); - timer.unref?.(); + sweepTimer.unref?.(); } async function main() { @@ -183,7 +224,7 @@ async function main() { await oscar.healthCheck(); startSessionSweep(); - app.listen(PORT, LISTEN_HOST, () => { + httpServer = app.listen(PORT, LISTEN_HOST, () => { console.log(`[server] listening on http://${LISTEN_HOST}:${PORT}`); }); }