import type { OrchestratorServices } from './types'; export interface OrchestratorRuntime { services: OrchestratorServices; shutdown(): Promise; } const workShutdown = new WeakMap>(); /** Registration rollback and application shutdown share the same work lifetime. */ export function stopOrchestratorWork(services: OrchestratorServices): Promise { let pending = workShutdown.get(services); if (!pending) { pending = (async () => { const failures: unknown[] = []; for (const close of [ () => services.custom?.PaperDeploymentHost?.shutdown(), () => services.custom?.CanonicalPaperRuntime?.shutdown(), () => services.custom?.BacktestRunner?.shutdown(), ]) { try { await close(); } catch (error) { failures.push(error); } } if (failures.length) { throw new AggregateError(failures, 'Orchestrator work shutdown failed'); } })(); workShutdown.set(services, pending); } return pending; } /** Shared clients stay open until work has drained or reported its cleanup failure. */ export function ownOrchestratorRuntime( services: OrchestratorServices, closeSharedServices: () => Promise ): OrchestratorRuntime { let shutdown: Promise | undefined; return { services, shutdown: () => (shutdown ??= (async () => { const failures: unknown[] = []; for (const close of [() => stopOrchestratorWork(services), closeSharedServices]) { try { await close(); } catch (error) { failures.push(error); } } if (failures.length) { throw new AggregateError(failures, 'Orchestrator shutdown failed'); } })()), }; } /** Route setup and HTTP bind failure release the already initialized runtime. */ export async function startOrchestratorServer( create: () => Promise, listen: (services: OrchestratorServices) => Server ): Promise<{ runtime: OrchestratorRuntime; server: Server }> { const runtime = await create(); try { return { runtime, server: listen(runtime.services) }; } catch (error) { try { await runtime.shutdown(); } catch (cleanupError) { runtime.services.logger.error('Orchestrator startup cleanup failed', { cleanupError }); } throw error; } }