fix: lifecycle
This commit is contained in:
@@ -1,26 +1,45 @@
|
|||||||
import { existsSync, unlinkSync } from "node:fs";
|
import { existsSync, mkdirSync, unlinkSync } from "node:fs";
|
||||||
|
import { dirname } from "node:path";
|
||||||
import { getSocketPath } from "./config.ts";
|
import { getSocketPath } from "./config.ts";
|
||||||
import { handleIpcRequest } from "./handler.ts";
|
import { handleIpcRequest } from "./handler.ts";
|
||||||
import { startIpcServer } from "./ipc/server.ts";
|
import { startIpcServer } from "./ipc/server.ts";
|
||||||
|
|
||||||
export async function serve(): Promise<void> {
|
export async function serve(): Promise<void> {
|
||||||
const socketPath = getSocketPath();
|
const socketPath = getSocketPath();
|
||||||
|
mkdirSync(dirname(socketPath), { recursive: true });
|
||||||
const server = await startIpcServer(handleIpcRequest);
|
const server = await startIpcServer(handleIpcRequest);
|
||||||
|
console.log(`orchestrator listening on ${socketPath}`);
|
||||||
|
|
||||||
|
let cleanedUp = false;
|
||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
|
if (cleanedUp) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cleanedUp = true;
|
||||||
server.close();
|
server.close();
|
||||||
if (existsSync(socketPath)) {
|
if (existsSync(socketPath)) {
|
||||||
unlinkSync(socketPath);
|
unlinkSync(socketPath);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
process.on("SIGINT", () => {
|
const shutdown = (exitCode: number) => {
|
||||||
cleanup();
|
cleanup();
|
||||||
process.exit(0);
|
process.exit(exitCode);
|
||||||
|
};
|
||||||
|
|
||||||
|
process.on("SIGINT", () => shutdown(0));
|
||||||
|
process.on("SIGTERM", () => shutdown(0));
|
||||||
|
process.on("exit", cleanup);
|
||||||
|
process.on("uncaughtException", (error) => {
|
||||||
|
console.error(error);
|
||||||
|
shutdown(1);
|
||||||
|
});
|
||||||
|
process.on("unhandledRejection", (reason) => {
|
||||||
|
console.error(reason);
|
||||||
|
shutdown(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on("SIGTERM", () => {
|
await new Promise<void>(() => {
|
||||||
cleanup();
|
// Keep the process alive until a signal or fatal error triggers shutdown.
|
||||||
process.exit(0);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user