Files
Checkmate/server/src/shutdown.ts
T

49 lines
1.3 KiB
TypeScript
Raw Normal View History

2026-06-24 10:30:21 -07:00
import { IDb } from "@/db/db.interface.js";
2026-06-24 10:53:03 -07:00
import type { ILogger } from "@/utils/logger.js";
2026-01-22 21:02:34 +00:00
import type { Server } from "http";
2026-06-24 10:30:21 -07:00
import { Mongoose } from "mongoose";
import { IJobScheduler } from "@/worker/worker.interface.js";
import { IHealthServer } from "@/worker/worker.health-server.js";
2025-07-25 15:15:14 -07:00
2026-06-24 10:30:21 -07:00
type ShutdownTargets = {
worker: IJobScheduler;
db: IDb<Mongoose>;
2026-06-24 10:53:03 -07:00
logger: ILogger;
healthServer?: IHealthServer;
2026-06-24 10:30:21 -07:00
};
export const initShutdownListener = (server: Server | null, shutdownTargets: ShutdownTargets) => {
2025-07-25 15:15:14 -07:00
const SERVICE_NAME = "Server";
const logger = shutdownTargets.logger;
2025-07-25 15:15:14 -07:00
let isShuttingDown = false;
const shutdown = async () => {
if (isShuttingDown) {
return;
}
isShuttingDown = true;
logger.info({ message: "Attempting graceful shutdown" });
try {
2026-06-01 10:45:09 -07:00
server?.close();
await shutdownTargets.worker.drain();
await shutdownTargets.worker.shutdown();
await shutdownTargets.healthServer?.close();
await shutdownTargets.db.disconnect();
2025-07-25 15:15:14 -07:00
logger.info({ message: "Graceful shutdown complete" });
process.exit(0);
} catch (error) {
2026-01-22 21:01:45 +00:00
const err = error as Error;
2025-07-25 15:15:14 -07:00
logger.error({
2026-01-22 21:01:45 +00:00
message: err.message,
2025-07-25 15:15:14 -07:00
service: SERVICE_NAME,
method: "shutdown",
2026-01-22 21:01:45 +00:00
stack: err.stack,
2025-07-25 15:15:14 -07:00
});
process.exit(1);
}
};
process.on("SIGUSR2", shutdown);
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
};