Files
Checkmate/server/src/shutdown.ts
T

43 lines
1.1 KiB
TypeScript
Raw Normal View History

2026-06-24 10:30:21 -07:00
import { IDb } from "@/db/db.interface.js";
2025-07-29 10:01:20 -07:00
import { logger } 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";
2025-07-25 15:15:14 -07:00
2026-06-24 10:30:21 -07:00
type ShutdownTargets = {
worker: IJobScheduler;
db: IDb<Mongoose>;
};
export const initShutdownListener = (server: Server | null, services: ShutdownTargets) => {
2025-07-25 15:15:14 -07:00
const SERVICE_NAME = "Server";
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();
2026-06-10 09:30:14 -07:00
await services.worker.shutdown();
2025-07-25 15:15:14 -07:00
await services.db.disconnect();
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);
};