This commit is contained in:
Boki 2026-10-20 18:36:19 -04:00
parent 879e9b4228
commit c3cb36c8d6
51 changed files with 2290 additions and 1467 deletions

View file

@ -18,7 +18,11 @@ if (config.queue) {
// Log the full configuration
const logger = getLogger('web-api');
logger.info('Service configuration:', config);
logger.info('Service configuration:', {
service: 'web-api',
port: config.service.port,
environment: config.environment,
});
// Import and start WebSocket-enabled server
import('./server-with-websocket').then(({ startServerWithWebSocket }) => {

View file

@ -5,24 +5,32 @@
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { createHttpSecurity, httpSecurityOptions, type HttpSecurity } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/handlers';
import { createBacktestRoutes } from './backtest.routes';
import { createBacktestV2Routes } from './backtests-v2.routes';
import { createExchangeRoutes } from './exchange.routes';
import { createHealthRoutes } from './health.routes';
import { createMonitoringRoutes } from './monitoring.routes';
import { createPipelineRoutes } from './pipeline.routes';
import { createBacktestRoutes } from './backtest.routes';
import { createBacktestV2Routes } from './backtests-v2.routes';
export function createRoutes(container: IServiceContainer): Hono {
export function createRoutes(
container: IServiceContainer,
security: HttpSecurity = createHttpSecurity({ ...httpSecurityOptions(), browserSessions: true })
): Hono {
const app = new Hono();
// Add CORS middleware
app.use('*', cors({
origin: ['http://localhost:4200', 'http://localhost:3000', 'http://localhost:3002', 'http://localhost:5173', 'http://localhost:5174'],
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
credentials: true,
}));
app.use(
'*',
cors({
origin: security.allowedOrigins,
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
credentials: true,
})
);
security.mount(app);
// Create routes with container
const healthRoutes = createHealthRoutes(container);

View file

@ -6,6 +6,7 @@
import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { parseReferenceDataResetRequest } from '@stock-bot/types';
import { PipelineService } from '../services/pipeline.service';
const logger = getLogger('pipeline-routes');
@ -48,6 +49,9 @@ export function createPipelineRoutes(container: IServiceContainer) {
});
pipeline.post('/exchanges/all', async c => {
if (c.req.query('clear') && c.req.query('clear') !== 'false') {
return c.json({ error: 'Sync is non-destructive; use the explicit maintenance reset' }, 400);
}
try {
const clearFirst = c.req.query('clear') === 'true';
const result = await pipelineService.syncAllExchanges(clearFirst);
@ -92,9 +96,15 @@ export function createPipelineRoutes(container: IServiceContainer) {
// Clear data endpoint
pipeline.post('/clear/postgresql', async c => {
const input: unknown = await c.req.json().catch(() => null);
let reset;
try {
const dataType = c.req.query('type') as 'exchanges' | 'provider_mappings' | 'all';
const result = await pipelineService.clearPostgreSQLData(dataType || 'all');
reset = parseReferenceDataResetRequest(input);
} catch (error) {
return c.json({ error: error instanceof Error ? error.message : 'Invalid reset' }, 400);
}
try {
const result = await pipelineService.clearPostgreSQLData(reset.type, reset.confirmation);
return c.json(result, result.success ? 200 : 503);
} catch (error) {
logger.error('Error in POST /clear/postgresql', { error });

View file

@ -1,4 +1,5 @@
import type { Server, ServerWebSocket } from 'bun';
import { createHttpSecurity, httpSecurityOptions, type HttpSecurity } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import {
@ -10,13 +11,20 @@ import {
const logger = getLogger('websocket-routes');
export function createWebSocketRoute(container: IServiceContainer) {
export function createWebSocketRoute(
container: IServiceContainer,
security: HttpSecurity = createHttpSecurity({ ...httpSecurityOptions(), browserSessions: true })
) {
const wsHandler = createWebSocketHandler(container);
// Make the handler available globally for other services
setWebSocketHandler(wsHandler);
return (request: Request, server: Pick<Server, 'upgrade'>) => {
const rejection = security.authorize(request);
if (rejection) {
return rejection;
}
const url = new URL(request.url);
const runId = url.searchParams.get('runId');

View file

@ -1,3 +1,4 @@
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';
@ -7,6 +8,11 @@ import { getWebSocketHandler, type RunSocketData } from './websocket/run-updates
// Initialize configuration with service-specific overrides
const config = initializeStockConfig('webApi');
const security = createHttpSecurity({
...httpSecurityOptions(),
environment: config.environment,
browserSessions: true,
});
// Override queue settings for web-api (no workers needed)
if (config.queue) {
@ -17,7 +23,11 @@ if (config.queue) {
// Log the full configuration
const logger = getLogger('web-api');
logger.info('Service configuration:', config);
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) {
@ -56,10 +66,10 @@ export async function startServerWithWebSocket() {
container = diContainer.resolve('serviceContainer');
// Create HTTP routes
const routes = createRoutes(container);
const routes = createRoutes(container, security);
// Create WebSocket route handler
const wsRoute = createWebSocketRoute(container);
const wsRoute = createWebSocketRoute(container, security);
// Start server with WebSocket support
const port = config.service.port || 2003;
@ -70,6 +80,8 @@ export async function startServerWithWebSocket() {
try {
server = Bun.serve<RunSocketData, {}>({
port,
hostname: security.hostname,
maxRequestBodySize: 1_048_576,
// Handle HTTP requests
async fetch(req, server) {

View file

@ -1,5 +1,6 @@
import { randomUUID as uuidv4 } from 'node:crypto';
import type { QueryResultRow } from 'pg';
import { authenticatedServiceFetch } from '@stock-bot/di';
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
@ -64,7 +65,7 @@ export class BacktestServiceV2 {
constructor(
container: IServiceContainer,
private readonly request: BacktestTransport = fetch
private readonly request: BacktestTransport = authenticatedServiceFetch
) {
this.container = requireServices(container, 'postgres');
logger.info('BacktestServiceV2 initialized');

View file

@ -6,6 +6,7 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { getFullQueueName } from '@stock-bot/queue';
import { parseReferenceDataResetRequest, type ReferenceDataResetScope } from '@stock-bot/types';
const logger = getLogger('pipeline-service');
@ -119,6 +120,9 @@ export class PipelineService {
*/
async syncAllExchanges(clearFirst: boolean = false): Promise<PipelineJobResult> {
try {
if (clearFirst) {
throw new Error('Sync is non-destructive; use the explicit maintenance reset');
}
const queueManager = this.container.queueManager;
if (!queueManager) {
return { success: false, error: 'Queue manager not available' };
@ -246,9 +250,11 @@ export class PipelineService {
* Clear PostgreSQL data
*/
async clearPostgreSQLData(
dataType: 'exchanges' | 'provider_mappings' | 'all' = 'all'
dataType: ReferenceDataResetScope,
confirmation: string
): Promise<PipelineJobResult> {
try {
const payload = parseReferenceDataResetRequest({ type: dataType, confirmation });
const queueManager = this.container.queueManager;
if (!queueManager) {
return { success: false, error: 'Queue manager not available' };
@ -258,7 +264,7 @@ export class PipelineService {
const job = await exchangesQueue.add('clear-postgresql-data', {
handler: 'exchanges',
operation: 'clear-postgresql-data',
payload: { dataType },
payload,
});
logger.info('PostgreSQL data clear job queued', { jobId: job.id, dataType });