fix(orchestrator): own startup and shutdown resources (CL16)

This commit is contained in:
Boki 2026-10-26 19:28:43 -04:00
parent 21666242f4
commit 8546fce4a9
8 changed files with 384 additions and 117 deletions

View file

@ -9,6 +9,7 @@ import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig } from '@stock-bot/stock-config';
import { createRoutes } from './routes/create-routes';
import { startOrchestratorServer, type OrchestratorRuntime } from './runtime';
import { createContainer } from './simple-container';
// Initialize configuration with service-specific overrides
@ -40,85 +41,70 @@ logger.info('Service configuration:', {
});
async function main() {
let server: ReturnType<typeof Bun.serve> | undefined; // Declare server in outer scope for shutdown
let server: ReturnType<typeof Bun.serve> | undefined;
let runtime: OrchestratorRuntime | undefined;
try {
// Initialize container with all services using configuration
const services = await createContainer(config);
const started = await startOrchestratorServer(
() => createContainer(config),
services => {
// Initialize Hono app
const app = new Hono();
// Initialize Hono app
const app = new Hono();
// CORS middleware - use config for origins
app.use(
'*',
cors({
origin: config.services?.webApi?.cors?.origins || [
'http://localhost:4200',
'http://localhost:3000',
'http://localhost:5173',
'http://localhost:5174',
],
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
credentials: config.services?.webApi?.cors?.credentials ?? true,
})
);
security.mount(app);
// CORS middleware - use config for origins
app.use(
'*',
cors({
origin: config.services?.webApi?.cors?.origins || [
'http://localhost:4200',
'http://localhost:3000',
'http://localhost:5173',
'http://localhost:5174',
],
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
credentials: config.services?.webApi?.cors?.credentials ?? true,
})
);
security.mount(app);
// Logging middleware
app.use('*', async (c, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
services.logger.debug(`${c.req.method} ${c.req.url} - ${ms}ms`);
});
// Logging middleware
app.use('*', async (c, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
services.logger.debug(`${c.req.method} ${c.req.url} - ${ms}ms`);
});
// Create and mount routes (without Socket.IO for now)
const routes = createRoutes(services, undefined, security.allowedOrigins);
app.route('/', routes);
// Create and mount routes (without Socket.IO for now)
const routes = createRoutes(services, undefined, security.allowedOrigins);
app.route('/', routes);
// Start Bun server
try {
server = Bun.serve({
port: PORT,
hostname: security.hostname,
maxRequestBodySize: 1_048_576,
fetch: async req => {
services.logger.debug(`Incoming request: ${req.method} ${req.url}`);
try {
const response = await app.fetch(req);
return response;
} catch (error) {
services.logger.error('Request handling error:', error);
return Bun.serve({
port: PORT,
hostname: security.hostname,
maxRequestBodySize: 1_048_576,
fetch: async req => {
services.logger.debug(`Incoming request: ${req.method} ${req.url}`);
try {
const response = await app.fetch(req);
return response;
} catch (error) {
services.logger.error('Request handling error:', error);
return new Response('Internal Server Error', { status: 500 });
}
},
error: error => {
services.logger.error('Server error:', error);
return new Response('Internal Server Error', { status: 500 });
}
},
error: error => {
services.logger.error('Server error:', error);
return new Response('Internal Server Error', { status: 500 });
},
});
services.logger.info(`Orchestrator service started on port ${server?.port ?? PORT}`);
services.logger.info(`Server hostname: ${server.hostname}`);
services.logger.info(`Server URL: http://${server.hostname}:${server.port}`);
// Test that server is actually listening
setTimeout(async () => {
try {
const testResponse = await fetch(`http://localhost:${server?.port ?? PORT}/health`);
services.logger.info(
`Server self-test: ${testResponse.status} ${testResponse.statusText}`
);
} catch (error) {
services.logger.error('Server self-test failed:', error);
}
}, 1000);
} catch (error) {
services.logger.error('Failed to start Bun server:', error);
throw error;
}
},
});
}
);
server = started.server;
runtime = started.runtime;
const services = runtime.services;
services.logger.info(`Orchestrator service started on port ${server.port}`);
services.logger.info('Service metadata:', {
version: '1.0.0',
description: 'Trading System Orchestrator',
@ -151,19 +137,11 @@ async function main() {
services.logger.info('Orchestrator service shutting down...', { signal });
const deadline = setTimeout(() => process.exit(1), 10_000);
deadline.unref();
// Stop accepting connections, but let the active run persist its terminal state.
const stopped = server?.stop();
let exitCode = 0;
try {
const failures: unknown[] = [];
for (const close of [
() => services.custom?.PaperDeploymentHost?.shutdown(),
() => services.custom?.CanonicalPaperRuntime?.shutdown(),
() => services.custom?.BacktestRunner?.shutdown(),
() => services.queueManager?.shutdown(),
() => services.custom?.ModeManager?.shutdown(),
() => stopped,
]) {
// Finish accepted HTTP requests, drain durable work, then close shared clients.
for (const close of [() => server?.stop(), () => runtime?.shutdown()]) {
try {
await close();
} catch (error) {
@ -185,6 +163,12 @@ async function main() {
process.on('SIGINT', () => void shutdown('SIGINT'));
process.on('SIGTERM', () => void shutdown('SIGTERM'));
} catch (error) {
server?.stop(true);
try {
await runtime?.shutdown();
} catch (cleanupError) {
logger.error('Orchestrator startup cleanup failed', { cleanupError });
}
logger.error('Failed to start orchestrator service:', error);
process.exit(1);
}