- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
181 lines
5.8 KiB
TypeScript
181 lines
5.8 KiB
TypeScript
/**
|
|
* Stock Bot Orchestrator Service
|
|
* Coordinates between Rust core, data feeds, and analytics
|
|
*/
|
|
|
|
import { Hono } from 'hono';
|
|
import { cors } from 'hono/cors';
|
|
import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di/http-security';
|
|
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
|
|
const config = initializeStockConfig('orchestrator');
|
|
const security = createHttpSecurity({
|
|
...httpSecurityOptions(),
|
|
environment: config.environment,
|
|
browserSessions: true,
|
|
});
|
|
const logger = getLogger('orchestrator');
|
|
|
|
// Get service-specific config
|
|
const serviceConfig = config.services?.orchestrator || {
|
|
port: 2004,
|
|
defaultMode: 'backtest',
|
|
paperTradingCapital: 100000,
|
|
enableWebSocket: true,
|
|
};
|
|
|
|
const PORT = serviceConfig.port;
|
|
|
|
// Log the configuration
|
|
logger.info('Service configuration:', {
|
|
port: PORT,
|
|
defaultMode: serviceConfig.defaultMode,
|
|
enableWebSocket: serviceConfig.enableWebSocket,
|
|
backtesting: serviceConfig.backtesting,
|
|
strategies: serviceConfig.strategies,
|
|
});
|
|
|
|
async function main() {
|
|
let server: ReturnType<typeof Bun.serve> | undefined;
|
|
let runtime: OrchestratorRuntime | undefined;
|
|
|
|
try {
|
|
const started = await startOrchestratorServer(
|
|
() => createContainer(config),
|
|
services => {
|
|
// 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);
|
|
|
|
// 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);
|
|
|
|
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 });
|
|
},
|
|
});
|
|
}
|
|
);
|
|
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',
|
|
defaultMode: serviceConfig.defaultMode,
|
|
enableWebSocket: serviceConfig.enableWebSocket,
|
|
endpoints: {
|
|
health: '/health',
|
|
orders: '/api/orders',
|
|
positions: '/api/positions',
|
|
analytics: '/api/analytics',
|
|
backtest: '/api/backtest',
|
|
},
|
|
});
|
|
|
|
// Note: Socket.IO with Bun requires a different setup
|
|
// For now, we'll disable Socket.IO to avoid the CORS error
|
|
if (serviceConfig.enableWebSocket) {
|
|
services.logger.info(
|
|
'WebSocket support is enabled but Socket.IO integration with Bun requires additional setup'
|
|
);
|
|
}
|
|
|
|
// Graceful shutdown
|
|
let shuttingDown = false;
|
|
const shutdown = async (signal: string) => {
|
|
if (shuttingDown) {
|
|
return;
|
|
}
|
|
shuttingDown = true;
|
|
services.logger.info('Orchestrator service shutting down...', { signal });
|
|
const deadline = setTimeout(() => process.exit(1), 10_000);
|
|
deadline.unref();
|
|
let exitCode = 0;
|
|
try {
|
|
const failures: unknown[] = [];
|
|
// Finish accepted HTTP requests, drain durable work, then close shared clients.
|
|
for (const close of [() => server?.stop(), () => runtime?.shutdown()]) {
|
|
try {
|
|
await close();
|
|
} catch (error) {
|
|
failures.push(error);
|
|
}
|
|
}
|
|
if (failures.length) {
|
|
throw new AggregateError(failures, 'Orchestrator shutdown failed');
|
|
}
|
|
} catch (error) {
|
|
exitCode = 1;
|
|
services.logger.error('Orchestrator shutdown failed', { error });
|
|
} finally {
|
|
clearTimeout(deadline);
|
|
server?.stop(true);
|
|
process.exit(exitCode);
|
|
}
|
|
};
|
|
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);
|
|
}
|
|
}
|
|
|
|
// Start the service
|
|
main().catch(error => {
|
|
logger.error('Unhandled error:', error);
|
|
process.exit(1);
|
|
});
|