77 lines
2.4 KiB
TypeScript
77 lines
2.4 KiB
TypeScript
import type { OrchestratorServices } from './types';
|
|
|
|
export interface OrchestratorRuntime {
|
|
services: OrchestratorServices;
|
|
shutdown(): Promise<void>;
|
|
}
|
|
|
|
const workShutdown = new WeakMap<OrchestratorServices, Promise<void>>();
|
|
|
|
/** Registration rollback and application shutdown share the same work lifetime. */
|
|
export function stopOrchestratorWork(services: OrchestratorServices): Promise<void> {
|
|
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<void>
|
|
): OrchestratorRuntime {
|
|
let shutdown: Promise<void> | 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<Server>(
|
|
create: () => Promise<OrchestratorRuntime>,
|
|
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;
|
|
}
|
|
}
|