From 0cbdc283a3d90b55314c0168cadc89c285a19444 Mon Sep 17 00:00:00 2001 From: Cristina Poncela Cubeiro <140309543+cristinaponcela@users.noreply.github.com> Date: Thu, 18 Jun 2026 13:19:42 +0200 Subject: [PATCH] fix: lifecycle --- packages/orchestrator/src/serve.ts | 31 ++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/packages/orchestrator/src/serve.ts b/packages/orchestrator/src/serve.ts index 1651086b..5183ca60 100644 --- a/packages/orchestrator/src/serve.ts +++ b/packages/orchestrator/src/serve.ts @@ -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 { handleIpcRequest } from "./handler.ts"; import { startIpcServer } from "./ipc/server.ts"; export async function serve(): Promise { const socketPath = getSocketPath(); + mkdirSync(dirname(socketPath), { recursive: true }); const server = await startIpcServer(handleIpcRequest); + console.log(`orchestrator listening on ${socketPath}`); + let cleanedUp = false; const cleanup = () => { + if (cleanedUp) { + return; + } + cleanedUp = true; server.close(); if (existsSync(socketPath)) { unlinkSync(socketPath); } }; - process.on("SIGINT", () => { + const shutdown = (exitCode: number) => { 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", () => { - cleanup(); - process.exit(0); + await new Promise(() => { + // Keep the process alive until a signal or fatal error triggers shutdown. }); }