- Update semver-compatible workspace npm dependencies (TypeScript 5.9.3, Turbo 2.11.13, ESLint 9.39.5, @typescript-eslint 8.74.0, @types/bun 1.4.5, mongodb 6.22.0, pg 8.23.1, bullmq 5.81.6, etc.) - Update compatible Cargo crates in Cargo.lock while preserving exact financial decimal pins and rustc 1.88 compatibility (uuid 1.18.1) - Update Bun.serve/Server WebSocket generics in web-api for @types/bun 1.4.5
171 lines
5.4 KiB
TypeScript
171 lines
5.4 KiB
TypeScript
import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di';
|
|
import type { IServiceContainer } from '@stock-bot/handlers';
|
|
import { getLogger } from '@stock-bot/logger';
|
|
import { initializeStockConfig } from '@stock-bot/stock-config';
|
|
import { createRoutes, WEB_API_MAX_REQUEST_BODY_SIZE } from './routes/create-routes';
|
|
import { createWebSocketRoute, handleWebSocketConnection } from './routes/websocket.routes';
|
|
import { BacktestDispatcher } from './services/BacktestDispatcher';
|
|
import { getWebSocketHandler, type RunSocketData } from './websocket/run-updates';
|
|
import { createWebApiSecurity } from './http-security';
|
|
|
|
// Initialize configuration with service-specific overrides
|
|
const config = initializeStockConfig('webApi');
|
|
const securityOptions = {
|
|
...httpSecurityOptions(),
|
|
environment: config.environment,
|
|
browserSessions: true,
|
|
};
|
|
// Reject invalid authentication settings before opening stores or running migrations.
|
|
createHttpSecurity(securityOptions);
|
|
|
|
// Override queue settings for web-api (no workers needed)
|
|
if (config.queue) {
|
|
config.queue.workers = 0;
|
|
config.queue.concurrency = 0;
|
|
config.queue.enableScheduledJobs = false;
|
|
}
|
|
|
|
// Log the full configuration
|
|
const logger = getLogger('web-api');
|
|
logger.info('Service configuration:', {
|
|
service: 'web-api',
|
|
port: config.service.port,
|
|
environment: config.environment,
|
|
});
|
|
|
|
// Container factory function
|
|
async function createContainer(config: import('@stock-bot/config').UnifiedAppConfig) {
|
|
const { ServiceContainerBuilder } = await import('@stock-bot/di');
|
|
|
|
const container = await new ServiceContainerBuilder()
|
|
.withConfig(config)
|
|
.withOptions({
|
|
enableQuestDB: false,
|
|
enableMongoDB: true,
|
|
enablePostgres: true,
|
|
enableCache: true,
|
|
enableQueue: true,
|
|
enableBrowser: false,
|
|
enableProxy: false,
|
|
})
|
|
.build();
|
|
|
|
// Run database migrations
|
|
const services = container.resolve('serviceContainer');
|
|
if (services.postgres) {
|
|
const { runMigrations } = await import('./migrations/migration-runner');
|
|
await runMigrations(services);
|
|
}
|
|
|
|
return container;
|
|
}
|
|
|
|
// Custom server start function with WebSocket support
|
|
export async function startServerWithWebSocket() {
|
|
let container: IServiceContainer | null = null;
|
|
|
|
try {
|
|
// Create container
|
|
const diContainer = await createContainer(config);
|
|
container = diContainer.resolve('serviceContainer');
|
|
const security = createWebApiSecurity(container, securityOptions);
|
|
|
|
if (!container.postgres || !container.queueManager) {
|
|
throw new Error('Durable backtest dispatch requires PostgreSQL and Redis queues');
|
|
}
|
|
const dispatcher = new BacktestDispatcher(
|
|
container.postgres,
|
|
container.queueManager.getQueue('{orchestrator_orchestrator}', { workers: 0 }),
|
|
logger
|
|
);
|
|
|
|
// Create HTTP routes
|
|
const routes = createRoutes(container, security);
|
|
|
|
// Create WebSocket route handler
|
|
const wsRoute = createWebSocketRoute(container, security);
|
|
|
|
// Start server with WebSocket support
|
|
const port = config.service.port || 2003;
|
|
|
|
logger.info(`Starting server on port ${port}...`);
|
|
|
|
let server;
|
|
try {
|
|
server = Bun.serve<RunSocketData>({
|
|
port,
|
|
hostname: security.hostname,
|
|
maxRequestBodySize: WEB_API_MAX_REQUEST_BODY_SIZE,
|
|
|
|
// Handle HTTP requests
|
|
async fetch(req, server) {
|
|
const url = new URL(req.url);
|
|
|
|
// Check if this is a WebSocket upgrade request
|
|
if (url.pathname === '/ws' && req.headers.get('upgrade') === 'websocket') {
|
|
return wsRoute(req, server);
|
|
}
|
|
|
|
// Otherwise handle as normal HTTP request
|
|
return routes.fetch(req);
|
|
},
|
|
|
|
// WebSocket handlers
|
|
websocket: {
|
|
open(ws) {
|
|
handleWebSocketConnection(ws);
|
|
},
|
|
|
|
message(ws, message) {
|
|
getWebSocketHandler()?.handleMessage(ws, message);
|
|
},
|
|
|
|
close(ws, code, reason) {
|
|
getWebSocketHandler()?.handleClose(ws);
|
|
logger.info('WebSocket closed', { code, reason });
|
|
},
|
|
},
|
|
|
|
development: config.environment === 'development',
|
|
});
|
|
} catch (error) {
|
|
if (error instanceof Error && error.message.includes('port')) {
|
|
logger.error(
|
|
`Port ${port} is already in use. Please stop any other servers running on this port.`
|
|
);
|
|
throw new Error(`Port ${port} is already in use`);
|
|
}
|
|
throw error;
|
|
}
|
|
|
|
logger.info(`Web API service with WebSocket support started on port ${server.port}`);
|
|
dispatcher.start();
|
|
logger.info(`WebSocket endpoint available at ws://localhost:${server.port}/ws`);
|
|
|
|
// Handle shutdown
|
|
let shuttingDown = false;
|
|
const shutdown = async () => {
|
|
if (shuttingDown) {
|
|
return;
|
|
}
|
|
shuttingDown = true;
|
|
logger.info('Shutting down server...');
|
|
const deadline = setTimeout(() => process.exit(1), 10_000);
|
|
deadline.unref();
|
|
await dispatcher.shutdown();
|
|
getWebSocketHandler()?.cleanup();
|
|
await server.stop(true);
|
|
await container?.queueManager?.shutdown();
|
|
await diContainer.dispose();
|
|
clearTimeout(deadline);
|
|
process.exit(0);
|
|
};
|
|
process.on('SIGINT', () => void shutdown());
|
|
process.on('SIGTERM', () => void shutdown());
|
|
} catch (error) {
|
|
logger.fatal('Failed to start web API service', { error });
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
// Export the function - don't start automatically
|