commit 2 refactor
This commit is contained in:
parent
588f666943
commit
32e43c9243
310 changed files with 33318 additions and 31189 deletions
|
|
@ -3,7 +3,7 @@
|
|||
* Configures dependency injection for the web API service
|
||||
*/
|
||||
|
||||
import type { AppConfig } from '@stock-bot/config';
|
||||
import type { UnifiedAppConfig } from '@stock-bot/config';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
|
|
@ -13,7 +13,7 @@ const logger = getLogger('web-api-container');
|
|||
* Configure the service container for web API workloads
|
||||
*/
|
||||
export function setupServiceContainer(
|
||||
config: AppConfig,
|
||||
config: UnifiedAppConfig,
|
||||
container: IServiceContainer
|
||||
): IServiceContainer {
|
||||
logger.info('Configuring web API service container...');
|
||||
|
|
|
|||
|
|
@ -1,70 +1,67 @@
|
|||
import { readFileSync, readdirSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
const logger = getLogger('migration-runner');
|
||||
|
||||
export async function runMigrations(container: IServiceContainer): Promise<void> {
|
||||
logger.info('Migration runner called');
|
||||
logger.info('Container type:', typeof container);
|
||||
logger.info('Container postgres available:', !!container.postgres);
|
||||
|
||||
if (!container.postgres) {
|
||||
logger.warn('PostgreSQL not available, skipping migrations');
|
||||
logger.info('Container keys:', Object.keys(container));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Create migrations table if it doesn't exist
|
||||
await container.postgres.query(`
|
||||
CREATE TABLE IF NOT EXISTS migrations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
filename VARCHAR(255) NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
)
|
||||
`);
|
||||
|
||||
// Get list of migration files from database/postgres/init
|
||||
const migrationsDir = join(process.cwd(), 'database', 'postgres', 'init');
|
||||
logger.info('Looking for migrations in:', migrationsDir);
|
||||
|
||||
const files = readdirSync(migrationsDir)
|
||||
.filter(f => f.endsWith('.sql') && f.startsWith('001_')) // Only run our backtest migration for now
|
||||
.sort();
|
||||
|
||||
logger.info('Found migration files:', files);
|
||||
|
||||
for (const file of files) {
|
||||
// Check if migration has already been run
|
||||
const result = await container.postgres.query(
|
||||
'SELECT 1 FROM migrations WHERE filename = $1',
|
||||
[file]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
logger.info(`Running migration: ${file}`);
|
||||
|
||||
// Read and execute migration
|
||||
const sql = readFileSync(join(migrationsDir, file), 'utf8');
|
||||
await container.postgres.query(sql);
|
||||
|
||||
// Record migration as executed
|
||||
await container.postgres.query(
|
||||
'INSERT INTO migrations (filename) VALUES ($1)',
|
||||
[file]
|
||||
);
|
||||
|
||||
logger.info(`Migration completed: ${file}`);
|
||||
} else {
|
||||
logger.debug(`Migration already executed: ${file}`);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info('All migrations completed successfully');
|
||||
} catch (error) {
|
||||
logger.error('Migration failed', { error });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
import { readdirSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
const logger = getLogger('migration-runner');
|
||||
|
||||
export async function runMigrations(container: IServiceContainer): Promise<void> {
|
||||
logger.info('Migration runner called');
|
||||
logger.info('Container type', { type: typeof container });
|
||||
logger.info('Container postgres available', { available: !!container.postgres });
|
||||
|
||||
if (!container.postgres) {
|
||||
logger.warn('PostgreSQL not available, skipping migrations');
|
||||
logger.info('Container keys:', Object.keys(container));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Create migrations table if it doesn't exist
|
||||
await container.postgres.query(`
|
||||
CREATE TABLE IF NOT EXISTS migrations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
filename VARCHAR(255) NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
)
|
||||
`);
|
||||
|
||||
// Get list of migration files from database/postgres/init
|
||||
const migrationsDir = join(process.cwd(), 'database', 'postgres', 'init');
|
||||
logger.info('Looking for migrations', { directory: migrationsDir });
|
||||
|
||||
const files = readdirSync(migrationsDir)
|
||||
.filter(f => f.endsWith('.sql') && f.startsWith('001_')) // Only run our backtest migration for now
|
||||
.sort();
|
||||
|
||||
logger.info('Found migration files:', files);
|
||||
|
||||
for (const file of files) {
|
||||
// Check if migration has already been run
|
||||
const result = await container.postgres.query(
|
||||
'SELECT 1 FROM migrations WHERE filename = $1',
|
||||
[file]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
logger.info(`Running migration: ${file}`);
|
||||
|
||||
// Read and execute migration
|
||||
const sql = readFileSync(join(migrationsDir, file), 'utf8');
|
||||
await container.postgres.query(sql);
|
||||
|
||||
// Record migration as executed
|
||||
await container.postgres.query('INSERT INTO migrations (filename) VALUES ($1)', [file]);
|
||||
|
||||
logger.info(`Migration completed: ${file}`);
|
||||
} else {
|
||||
logger.debug(`Migration already executed: ${file}`);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info('All migrations completed successfully');
|
||||
} catch (error) {
|
||||
logger.error('Migration failed', { error });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,178 +0,0 @@
|
|||
import { Router } from 'express';
|
||||
import { BacktestServiceV2 } from '../services/backtest-v2.service';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
const logger = getLogger('backtests-v2-router');
|
||||
|
||||
export function createBacktestsV2Router(container: IServiceContainer): Router {
|
||||
const router = Router();
|
||||
const backtestService = new BacktestServiceV2(container);
|
||||
|
||||
// Backtest endpoints
|
||||
router.get('/backtests', async (req, res) => {
|
||||
try {
|
||||
const limit = parseInt(req.query.limit as string) || 50;
|
||||
const offset = parseInt(req.query.offset as string) || 0;
|
||||
|
||||
const backtests = await backtestService.listBacktests({ limit, offset });
|
||||
res.json(backtests);
|
||||
} catch (error) {
|
||||
logger.error('Failed to list backtests', error);
|
||||
res.status(500).json({ error: 'Failed to list backtests' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/backtests/:id', async (req, res) => {
|
||||
try {
|
||||
const backtest = await backtestService.getBacktest(req.params.id);
|
||||
if (!backtest) {
|
||||
return res.status(404).json({ error: 'Backtest not found' });
|
||||
}
|
||||
res.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get backtest', error);
|
||||
res.status(500).json({ error: 'Failed to get backtest' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/backtests', async (req, res) => {
|
||||
try {
|
||||
const backtest = await backtestService.createBacktest(req.body);
|
||||
res.status(201).json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', error);
|
||||
res.status(500).json({ error: 'Failed to create backtest' });
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/backtests/:id', async (req, res) => {
|
||||
try {
|
||||
const backtest = await backtestService.updateBacktest(req.params.id, req.body);
|
||||
if (!backtest) {
|
||||
return res.status(404).json({ error: 'Backtest not found' });
|
||||
}
|
||||
res.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to update backtest', error);
|
||||
res.status(500).json({ error: 'Failed to update backtest' });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/backtests/:id', async (req, res) => {
|
||||
try {
|
||||
await backtestService.deleteBacktest(req.params.id);
|
||||
res.status(204).send();
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete backtest', error);
|
||||
res.status(500).json({ error: 'Failed to delete backtest' });
|
||||
}
|
||||
});
|
||||
|
||||
// Run endpoints
|
||||
router.get('/backtests/:backtestId/runs', async (req, res) => {
|
||||
try {
|
||||
const runs = await backtestService.listRuns(req.params.backtestId);
|
||||
res.json(runs);
|
||||
} catch (error) {
|
||||
logger.error('Failed to list runs', error);
|
||||
res.status(500).json({ error: 'Failed to list runs' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/backtests/:backtestId/runs', async (req, res) => {
|
||||
try {
|
||||
const run = await backtestService.createRun({
|
||||
backtestId: req.params.backtestId,
|
||||
speedMultiplier: req.body.speedMultiplier
|
||||
});
|
||||
res.status(201).json(run);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create run', error);
|
||||
res.status(500).json({ error: 'Failed to create run' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/runs/:id', async (req, res) => {
|
||||
try {
|
||||
const run = await backtestService.getRun(req.params.id);
|
||||
if (!run) {
|
||||
return res.status(404).json({ error: 'Run not found' });
|
||||
}
|
||||
res.json(run);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get run', error);
|
||||
res.status(500).json({ error: 'Failed to get run' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/runs/:id/results', async (req, res) => {
|
||||
try {
|
||||
const results = await backtestService.getRunResults(req.params.id);
|
||||
if (!results) {
|
||||
return res.status(404).json({ error: 'Results not found' });
|
||||
}
|
||||
res.json(results);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get run results', error);
|
||||
res.status(500).json({ error: 'Failed to get run results' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/runs/:id/pause', async (req, res) => {
|
||||
try {
|
||||
await backtestService.pauseRun(req.params.id);
|
||||
res.json({ message: 'Run paused' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to pause run', error);
|
||||
res.status(500).json({ error: 'Failed to pause run' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/runs/:id/resume', async (req, res) => {
|
||||
try {
|
||||
await backtestService.resumeRun(req.params.id);
|
||||
res.json({ message: 'Run resumed' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to resume run', error);
|
||||
res.status(500).json({ error: 'Failed to resume run' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/runs/:id/cancel', async (req, res) => {
|
||||
try {
|
||||
await backtestService.cancelRun(req.params.id);
|
||||
res.json({ message: 'Run cancelled' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to cancel run', error);
|
||||
res.status(500).json({ error: 'Failed to cancel run' });
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/runs/:id/speed', async (req, res) => {
|
||||
try {
|
||||
await backtestService.updateRunSpeed(req.params.id, req.body.speedMultiplier);
|
||||
res.json({ message: 'Speed updated' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to update run speed', error);
|
||||
res.status(500).json({ error: 'Failed to update run speed' });
|
||||
}
|
||||
});
|
||||
|
||||
// WebSocket endpoint for real-time run updates
|
||||
router.ws('/runs/:id/stream', (ws, req) => {
|
||||
const runId = req.params.id;
|
||||
logger.info('WebSocket connection established for run', { runId });
|
||||
|
||||
// TODO: Implement real-time updates
|
||||
ws.on('message', (msg) => {
|
||||
logger.debug('Received WebSocket message', { runId, msg });
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
logger.info('WebSocket connection closed', { runId });
|
||||
});
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
|
@ -1,196 +1,197 @@
|
|||
import { Hono } from 'hono';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { BacktestServiceV2 } from '../services/backtest-v2.service';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
||||
export function createBacktestV2Routes(container: IServiceContainer) {
|
||||
const app = new Hono();
|
||||
const backtestService = new BacktestServiceV2(container);
|
||||
|
||||
// Backtest endpoints
|
||||
app.get('/api/v2/backtests', async (c) => {
|
||||
try {
|
||||
const limit = parseInt(c.req.query('limit') || '50');
|
||||
const offset = parseInt(c.req.query('offset') || '0');
|
||||
|
||||
const backtests = await backtestService.listBacktests({ limit, offset });
|
||||
return c.json(backtests);
|
||||
} catch (error) {
|
||||
logger.error('Failed to list backtests', error);
|
||||
return c.json({ error: 'Failed to list backtests' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/backtests/:id', async (c) => {
|
||||
try {
|
||||
const backtest = await backtestService.getBacktest(c.req.param('id'));
|
||||
if (!backtest) {
|
||||
return c.json({ error: 'Backtest not found' }, 404);
|
||||
}
|
||||
return c.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get backtest', error);
|
||||
return c.json({ error: 'Failed to get backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/backtests', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const backtest = await backtestService.createBacktest(body);
|
||||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', error);
|
||||
return c.json({ error: 'Failed to create backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/v2/backtests/:id', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const backtest = await backtestService.updateBacktest(c.req.param('id'), body);
|
||||
if (!backtest) {
|
||||
return c.json({ error: 'Backtest not found' }, 404);
|
||||
}
|
||||
return c.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to update backtest', error);
|
||||
return c.json({ error: 'Failed to update backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/v2/backtests/:id', async (c) => {
|
||||
try {
|
||||
await backtestService.deleteBacktest(c.req.param('id'));
|
||||
return c.text('', 204);
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete backtest', error);
|
||||
return c.json({ error: 'Failed to delete backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Run endpoints
|
||||
app.get('/api/v2/backtests/:backtestId/runs', async (c) => {
|
||||
try {
|
||||
const runs = await backtestService.listRuns(c.req.param('backtestId'));
|
||||
return c.json(runs);
|
||||
} catch (error) {
|
||||
logger.error('Failed to list runs', error);
|
||||
return c.json({ error: 'Failed to list runs' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/backtests/:backtestId/runs', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const run = await backtestService.createRun({
|
||||
backtestId: c.req.param('backtestId'),
|
||||
speedMultiplier: body.speedMultiplier
|
||||
});
|
||||
return c.json(run, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create run', error);
|
||||
return c.json({ error: 'Failed to create run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/runs/:id', async (c) => {
|
||||
try {
|
||||
const run = await backtestService.getRun(c.req.param('id'));
|
||||
if (!run) {
|
||||
return c.json({ error: 'Run not found' }, 404);
|
||||
}
|
||||
return c.json(run);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get run', error);
|
||||
return c.json({ error: 'Failed to get run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/runs/:id/results', async (c) => {
|
||||
try {
|
||||
const results = await backtestService.getRunResults(c.req.param('id'));
|
||||
if (!results) {
|
||||
return c.json({ error: 'Results not found' }, 404);
|
||||
}
|
||||
return c.json(results);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get run results', error);
|
||||
return c.json({ error: 'Failed to get run results' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/runs/:id/pause', async (c) => {
|
||||
try {
|
||||
await backtestService.pauseRun(c.req.param('id'));
|
||||
return c.json({ message: 'Run paused' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to pause run', error);
|
||||
return c.json({ error: 'Failed to pause run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/runs/:id/resume', async (c) => {
|
||||
try {
|
||||
await backtestService.resumeRun(c.req.param('id'));
|
||||
return c.json({ message: 'Run resumed' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to resume run', error);
|
||||
return c.json({ error: 'Failed to resume run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/runs/:id/cancel', async (c) => {
|
||||
try {
|
||||
await backtestService.cancelRun(c.req.param('id'));
|
||||
return c.json({ message: 'Run cancelled' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to cancel run', error);
|
||||
return c.json({ error: 'Failed to cancel run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/v2/runs/:id/speed', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
await backtestService.updateRunSpeed(c.req.param('id'), body.speedMultiplier);
|
||||
return c.json({ message: 'Speed updated' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to update run speed', error);
|
||||
return c.json({ error: 'Failed to update run speed' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Progress update endpoint (called by orchestrator)
|
||||
app.post('/api/runs/:id/progress', async (c) => {
|
||||
try {
|
||||
const runId = c.req.param('id');
|
||||
const body = await c.req.json();
|
||||
const { progress, currentDate } = body;
|
||||
|
||||
// Update run progress in database
|
||||
await backtestService.updateRunStatus(runId, 'running', {
|
||||
progress,
|
||||
currentDate
|
||||
});
|
||||
|
||||
// Broadcast via WebSocket if handler is available
|
||||
const wsHandler = (global as any).wsHandler;
|
||||
if (wsHandler) {
|
||||
wsHandler.sendProgressUpdate(runId, progress, currentDate);
|
||||
}
|
||||
|
||||
return c.json({ message: 'Progress updated' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to update run progress', error);
|
||||
return c.json({ error: 'Failed to update run progress' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// TODO: WebSocket endpoint for real-time run updates
|
||||
// This needs additional setup with Hono WebSocket support
|
||||
|
||||
return app;
|
||||
}
|
||||
import { Hono } from 'hono';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { BacktestServiceV2 } from '../services/backtest-v2.service';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
||||
export function createBacktestV2Routes(container: IServiceContainer) {
|
||||
const app = new Hono();
|
||||
const backtestService = new BacktestServiceV2(container);
|
||||
|
||||
// Backtest endpoints
|
||||
app.get('/api/v2/backtests', async c => {
|
||||
try {
|
||||
const limit = parseInt(c.req.query('limit') || '50');
|
||||
const offset = parseInt(c.req.query('offset') || '0');
|
||||
|
||||
const backtests = await backtestService.listBacktests({ limit, offset });
|
||||
return c.json(backtests);
|
||||
} catch (error) {
|
||||
logger.error('Failed to list backtests', error);
|
||||
return c.json({ error: 'Failed to list backtests' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/backtests/:id', async c => {
|
||||
try {
|
||||
const backtest = await backtestService.getBacktest(c.req.param('id'));
|
||||
if (!backtest) {
|
||||
return c.json({ error: 'Backtest not found' }, 404);
|
||||
}
|
||||
return c.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get backtest', error);
|
||||
return c.json({ error: 'Failed to get backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/backtests', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const backtest = await backtestService.createBacktest(body);
|
||||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', error);
|
||||
return c.json({ error: 'Failed to create backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/v2/backtests/:id', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const backtest = await backtestService.updateBacktest(c.req.param('id'), body);
|
||||
if (!backtest) {
|
||||
return c.json({ error: 'Backtest not found' }, 404);
|
||||
}
|
||||
return c.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to update backtest', error);
|
||||
return c.json({ error: 'Failed to update backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/v2/backtests/:id', async c => {
|
||||
try {
|
||||
await backtestService.deleteBacktest(c.req.param('id'));
|
||||
return c.body(null, 204);
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete backtest', error);
|
||||
return c.json({ error: 'Failed to delete backtest' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Run endpoints
|
||||
app.get('/api/v2/backtests/:backtestId/runs', async c => {
|
||||
try {
|
||||
const runs = await backtestService.listRuns(c.req.param('backtestId'));
|
||||
return c.json(runs);
|
||||
} catch (error) {
|
||||
logger.error('Failed to list runs', error);
|
||||
return c.json({ error: 'Failed to list runs' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/backtests/:backtestId/runs', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const run = await backtestService.createRun({
|
||||
backtestId: c.req.param('backtestId'),
|
||||
speedMultiplier: body.speedMultiplier,
|
||||
});
|
||||
return c.json(run, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create run', error);
|
||||
return c.json({ error: 'Failed to create run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/runs/:id', async c => {
|
||||
try {
|
||||
const run = await backtestService.getRun(c.req.param('id'));
|
||||
if (!run) {
|
||||
return c.json({ error: 'Run not found' }, 404);
|
||||
}
|
||||
return c.json(run);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get run', error);
|
||||
return c.json({ error: 'Failed to get run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/runs/:id/results', async c => {
|
||||
try {
|
||||
const results = await backtestService.getRunResults(c.req.param('id'));
|
||||
if (!results) {
|
||||
return c.json({ error: 'Results not found' }, 404);
|
||||
}
|
||||
return c.json(results);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get run results', error);
|
||||
return c.json({ error: 'Failed to get run results' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/runs/:id/pause', async c => {
|
||||
try {
|
||||
await backtestService.pauseRun(c.req.param('id'));
|
||||
return c.json({ message: 'Run paused' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to pause run', error);
|
||||
return c.json({ error: 'Failed to pause run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/runs/:id/resume', async c => {
|
||||
try {
|
||||
await backtestService.resumeRun(c.req.param('id'));
|
||||
return c.json({ message: 'Run resumed' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to resume run', error);
|
||||
return c.json({ error: 'Failed to resume run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/runs/:id/cancel', async c => {
|
||||
try {
|
||||
await backtestService.cancelRun(c.req.param('id'));
|
||||
return c.json({ message: 'Run cancelled' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to cancel run', error);
|
||||
return c.json({ error: 'Failed to cancel run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/v2/runs/:id/speed', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
await backtestService.updateRunSpeed(c.req.param('id'), body.speedMultiplier);
|
||||
return c.json({ message: 'Speed updated' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to update run speed', error);
|
||||
return c.json({ error: 'Failed to update run speed' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Progress update endpoint (called by orchestrator)
|
||||
app.post('/api/runs/:id/progress', async c => {
|
||||
try {
|
||||
const runId = c.req.param('id');
|
||||
const body = await c.req.json();
|
||||
const { progress, currentDate } = body;
|
||||
|
||||
// Update run progress in database
|
||||
await backtestService.updateRunStatus(runId, 'running', {
|
||||
progress,
|
||||
currentDate,
|
||||
});
|
||||
|
||||
// Broadcast via WebSocket if handler is available
|
||||
const wsHandler = getWebSocketHandler();
|
||||
if (wsHandler) {
|
||||
wsHandler.sendProgressUpdate(runId, progress, currentDate);
|
||||
}
|
||||
|
||||
return c.json({ message: 'Progress updated' });
|
||||
} catch (error) {
|
||||
logger.error('Failed to update run progress', error);
|
||||
return c.json({ error: 'Failed to update run progress' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// TODO: WebSocket endpoint for real-time run updates
|
||||
// This needs additional setup with Hono WebSocket support
|
||||
|
||||
return app;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -183,12 +183,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
|
|||
);
|
||||
}
|
||||
|
||||
const info = await container.cache.info();
|
||||
const stats = await monitoringService.getCacheStats();
|
||||
|
||||
return c.json({
|
||||
parsed: stats,
|
||||
raw: info,
|
||||
raw: null, // Raw Redis commands are not part of the cache capability.
|
||||
});
|
||||
} catch (error) {
|
||||
return c.json(
|
||||
|
|
@ -288,12 +287,12 @@ export function createMonitoringRoutes(container: IServiceContainer) {
|
|||
queueName,
|
||||
counts,
|
||||
});
|
||||
} catch (error: any) {
|
||||
} catch (error) {
|
||||
await queue.close();
|
||||
return c.json(
|
||||
{
|
||||
queueName,
|
||||
error: error.message,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
500
|
||||
);
|
||||
|
|
|
|||
|
|
@ -106,7 +106,7 @@ export function createPipelineRoutes(container: IServiceContainer) {
|
|||
pipeline.get('/stats/exchanges', async c => {
|
||||
try {
|
||||
const result = await pipelineService.getExchangeStats();
|
||||
if (result.success) {
|
||||
if (result.success && result.data) {
|
||||
return c.json(result.data);
|
||||
} else {
|
||||
return c.json({ error: result.error }, 503);
|
||||
|
|
@ -120,7 +120,7 @@ export function createPipelineRoutes(container: IServiceContainer) {
|
|||
pipeline.get('/stats/provider-mappings', async c => {
|
||||
try {
|
||||
const result = await pipelineService.getProviderMappingStats();
|
||||
if (result.success) {
|
||||
if (result.success && result.data) {
|
||||
return c.json(result.data);
|
||||
} else {
|
||||
return c.json({ error: result.error }, 503);
|
||||
|
|
|
|||
|
|
@ -1,47 +1,53 @@
|
|||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { createWebSocketHandler } from '../websocket/run-updates';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
const logger = getLogger('websocket-routes');
|
||||
|
||||
export function createWebSocketRoute(container: IServiceContainer) {
|
||||
const wsHandler = createWebSocketHandler(container);
|
||||
|
||||
// Make the handler available globally for other services
|
||||
(global as any).wsHandler = wsHandler;
|
||||
|
||||
return (request: Request, server: any) => {
|
||||
const url = new URL(request.url);
|
||||
const runId = url.searchParams.get('runId');
|
||||
|
||||
if (!runId) {
|
||||
return new Response('Missing runId parameter', { status: 400 });
|
||||
}
|
||||
|
||||
logger.info(`WebSocket upgrade request for run: ${runId}`);
|
||||
|
||||
// Upgrade the connection to WebSocket
|
||||
const success = server.upgrade(request, {
|
||||
data: { runId }
|
||||
});
|
||||
|
||||
if (success) {
|
||||
logger.info(`WebSocket upgrade successful for run: ${runId}`);
|
||||
// Return undefined to indicate successful upgrade
|
||||
return;
|
||||
} else {
|
||||
logger.error(`WebSocket upgrade failed for run: ${runId}`);
|
||||
return new Response('WebSocket upgrade failed', { status: 500 });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// WebSocket connection handler for Bun
|
||||
export function handleWebSocketConnection(ws: any) {
|
||||
const { runId } = ws.data;
|
||||
const wsHandler = (global as any).wsHandler;
|
||||
|
||||
if (wsHandler && runId) {
|
||||
wsHandler.handleConnection(ws, runId);
|
||||
}
|
||||
}
|
||||
import type { Server, ServerWebSocket } from 'bun';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import {
|
||||
createWebSocketHandler,
|
||||
getWebSocketHandler,
|
||||
setWebSocketHandler,
|
||||
type RunSocketData,
|
||||
} from '../websocket/run-updates';
|
||||
|
||||
const logger = getLogger('websocket-routes');
|
||||
|
||||
export function createWebSocketRoute(container: IServiceContainer) {
|
||||
const wsHandler = createWebSocketHandler(container);
|
||||
|
||||
// Make the handler available globally for other services
|
||||
setWebSocketHandler(wsHandler);
|
||||
|
||||
return (request: Request, server: Pick<Server, 'upgrade'>) => {
|
||||
const url = new URL(request.url);
|
||||
const runId = url.searchParams.get('runId');
|
||||
|
||||
if (!runId) {
|
||||
return new Response('Missing runId parameter', { status: 400 });
|
||||
}
|
||||
|
||||
logger.info(`WebSocket upgrade request for run: ${runId}`);
|
||||
|
||||
// Upgrade the connection to WebSocket
|
||||
const success = server.upgrade(request, {
|
||||
data: { runId },
|
||||
});
|
||||
|
||||
if (success) {
|
||||
logger.info(`WebSocket upgrade successful for run: ${runId}`);
|
||||
// Return undefined to indicate successful upgrade
|
||||
return;
|
||||
} else {
|
||||
logger.error(`WebSocket upgrade failed for run: ${runId}`);
|
||||
return new Response('WebSocket upgrade failed', { status: 500 });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// WebSocket connection handler for Bun
|
||||
export function handleWebSocketConnection(ws: ServerWebSocket<RunSocketData>) {
|
||||
const { runId } = ws.data;
|
||||
const wsHandler = getWebSocketHandler();
|
||||
|
||||
if (wsHandler && runId) {
|
||||
wsHandler.handleConnection(ws, runId);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,131 +1,131 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import { initializeStockConfig } from '@stock-bot/stock-config';
|
||||
import { createRoutes } from './routes/create-routes';
|
||||
import { createWebSocketRoute, handleWebSocketConnection } from './routes/websocket.routes';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
|
||||
// Initialize configuration with service-specific overrides
|
||||
const config = initializeStockConfig('webApi');
|
||||
|
||||
// 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:', config);
|
||||
|
||||
// Container factory function
|
||||
async function createContainer(config: any) {
|
||||
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
|
||||
if (container.postgres) {
|
||||
const { runMigrations } = await import('./migrations/migration-runner');
|
||||
await runMigrations(container);
|
||||
}
|
||||
|
||||
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');
|
||||
|
||||
// Create HTTP routes
|
||||
const routes = createRoutes(container);
|
||||
|
||||
// Create WebSocket route handler
|
||||
const wsRoute = createWebSocketRoute(container);
|
||||
|
||||
// Start server with WebSocket support
|
||||
const port = config.service.port || 2003;
|
||||
|
||||
logger.info(`Starting server on port ${port}...`);
|
||||
|
||||
let server;
|
||||
try {
|
||||
server = Bun.serve({
|
||||
port,
|
||||
|
||||
// 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) {
|
||||
// Message handling is done in the WebSocket handler
|
||||
// No need to echo messages back
|
||||
},
|
||||
|
||||
close(ws, code, reason) {
|
||||
logger.info('WebSocket closed', { code, reason });
|
||||
},
|
||||
|
||||
error(ws, error) {
|
||||
logger.error('WebSocket error', error);
|
||||
}
|
||||
},
|
||||
|
||||
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}`);
|
||||
logger.info(`WebSocket endpoint available at ws://localhost:${server.port}/ws`);
|
||||
|
||||
// Handle shutdown
|
||||
process.on('SIGINT', async () => {
|
||||
logger.info('Shutting down server...');
|
||||
server.stop();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.fatal('Failed to start web API service', { error });
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Export the function - don't start automatically
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { initializeStockConfig } from '@stock-bot/stock-config';
|
||||
import { createRoutes } from './routes/create-routes';
|
||||
import { createWebSocketRoute, handleWebSocketConnection } from './routes/websocket.routes';
|
||||
import { getWebSocketHandler, type RunSocketData } from './websocket/run-updates';
|
||||
|
||||
// Initialize configuration with service-specific overrides
|
||||
const config = initializeStockConfig('webApi');
|
||||
|
||||
// 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:', config);
|
||||
|
||||
// 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');
|
||||
|
||||
// Create HTTP routes
|
||||
const routes = createRoutes(container);
|
||||
|
||||
// Create WebSocket route handler
|
||||
const wsRoute = createWebSocketRoute(container);
|
||||
|
||||
// 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,
|
||||
|
||||
// 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}`);
|
||||
logger.info(`WebSocket endpoint available at ws://localhost:${server.port}/ws`);
|
||||
|
||||
// Handle shutdown
|
||||
process.on('SIGINT', async () => {
|
||||
logger.info('Shutting down server...');
|
||||
getWebSocketHandler()?.cleanup();
|
||||
await server.stop(true);
|
||||
process.exit(0);
|
||||
});
|
||||
} catch (error) {
|
||||
logger.fatal('Failed to start web API service', { error });
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Export the function - don't start automatically
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,294 +1,301 @@
|
|||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
|
||||
const logger = getLogger('backtest-service');
|
||||
|
||||
// Use environment variable or default
|
||||
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
|
||||
|
||||
export interface BacktestRequest {
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
config?: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface BacktestJob {
|
||||
id: string;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
initialCapital: number;
|
||||
config: Record<string, any>;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export class BacktestService {
|
||||
private container: IServiceContainer;
|
||||
|
||||
constructor(container: IServiceContainer) {
|
||||
this.container = container;
|
||||
logger.info('BacktestService initialized', {
|
||||
hasPostgres: !!container.postgres,
|
||||
containerKeys: Object.keys(container)
|
||||
});
|
||||
}
|
||||
async createBacktest(request: BacktestRequest): Promise<BacktestJob> {
|
||||
const backtestId = uuidv4();
|
||||
|
||||
// Insert into PostgreSQL
|
||||
const result = await this.container.postgres.query(
|
||||
`INSERT INTO backtests
|
||||
(id, name, strategy, symbols, start_date, end_date, initial_capital, config, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending')
|
||||
RETURNING *`,
|
||||
[
|
||||
backtestId,
|
||||
request.config?.name || `Backtest ${new Date().toISOString()}`,
|
||||
request.strategy,
|
||||
JSON.stringify(request.symbols),
|
||||
request.startDate,
|
||||
request.endDate,
|
||||
request.initialCapital,
|
||||
JSON.stringify(request.config || {})
|
||||
]
|
||||
);
|
||||
|
||||
const backtest: BacktestJob = {
|
||||
id: result.rows[0].id,
|
||||
status: result.rows[0].status,
|
||||
strategy: result.rows[0].strategy,
|
||||
symbols: result.rows[0].symbols,
|
||||
startDate: result.rows[0].start_date,
|
||||
endDate: result.rows[0].end_date,
|
||||
initialCapital: parseFloat(result.rows[0].initial_capital),
|
||||
config: result.rows[0].config,
|
||||
createdAt: result.rows[0].created_at,
|
||||
updatedAt: result.rows[0].updated_at,
|
||||
};
|
||||
|
||||
// Call orchestrator to run backtest
|
||||
try {
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
mode: 'backtest',
|
||||
startDate: new Date(request.startDate).toISOString(),
|
||||
endDate: new Date(request.endDate).toISOString(),
|
||||
symbols: request.symbols,
|
||||
strategy: request.strategy,
|
||||
initialCapital: request.initialCapital,
|
||||
dataFrequency: '1d', // Default to daily
|
||||
commission: request.config?.commission,
|
||||
slippage: request.config?.slippage,
|
||||
speed: 'max', // Default speed
|
||||
fillModel: {
|
||||
slippage: 'realistic',
|
||||
marketImpact: true,
|
||||
partialFills: true
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Orchestrator returned ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
// Store result directly without transformation
|
||||
if (result.status === 'completed') {
|
||||
// Update backtest status
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
['completed', backtestId]
|
||||
);
|
||||
|
||||
// Store results in backtest_results table
|
||||
await this.saveBacktestResults(backtestId, result);
|
||||
|
||||
logger.info('Backtest completed', {
|
||||
backtestId,
|
||||
trades: result.metrics?.totalTrades,
|
||||
return: result.metrics?.totalReturn
|
||||
});
|
||||
} else {
|
||||
// Update status to running if not completed
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
['running', backtestId]
|
||||
);
|
||||
}
|
||||
|
||||
logger.info('Backtest started in orchestrator', { backtestId, result });
|
||||
} catch (error) {
|
||||
logger.error('Failed to start backtest in orchestrator', { backtestId, error });
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
|
||||
['failed', error.message, backtestId]
|
||||
);
|
||||
backtest.status = 'failed';
|
||||
backtest.error = error.message;
|
||||
}
|
||||
|
||||
return backtest;
|
||||
}
|
||||
|
||||
async getBacktest(id: string): Promise<BacktestJob | null> {
|
||||
const result = await this.container.postgres.query(
|
||||
'SELECT * FROM backtests WHERE id = $1',
|
||||
[id]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = result.rows[0];
|
||||
return {
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date,
|
||||
endDate: row.end_date,
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
config: row.config,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
error: row.error,
|
||||
};
|
||||
}
|
||||
|
||||
async getBacktestResults(id: string): Promise<any> {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT
|
||||
br.*,
|
||||
b.strategy,
|
||||
b.symbols,
|
||||
b.start_date,
|
||||
b.end_date,
|
||||
b.initial_capital,
|
||||
b.config as backtest_config
|
||||
FROM backtest_results br
|
||||
JOIN backtests b ON b.id = br.backtest_id
|
||||
WHERE br.backtest_id = $1`,
|
||||
[id]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = result.rows[0];
|
||||
|
||||
// Reconstruct the result format expected by frontend
|
||||
return {
|
||||
backtestId: row.backtest_id,
|
||||
status: 'completed',
|
||||
completedAt: row.completed_at.toISOString(),
|
||||
config: {
|
||||
name: row.backtest_config?.name || 'Backtest',
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date.toISOString(),
|
||||
endDate: row.end_date.toISOString(),
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
commission: row.backtest_config?.commission ?? 0.001,
|
||||
slippage: row.backtest_config?.slippage ?? 0.0001,
|
||||
dataFrequency: row.backtest_config?.dataFrequency || '1d',
|
||||
},
|
||||
metrics: row.metrics,
|
||||
equity: row.equity_curve,
|
||||
ohlcData: row.ohlc_data,
|
||||
trades: row.trades,
|
||||
positions: row.positions,
|
||||
analytics: row.analytics,
|
||||
executionTime: row.execution_time,
|
||||
};
|
||||
}
|
||||
|
||||
async listBacktests(params: { limit: number; offset: number }): Promise<BacktestJob[]> {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT * FROM backtests
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1 OFFSET $2`,
|
||||
[params.limit, params.offset]
|
||||
);
|
||||
|
||||
return result.rows.map(row => ({
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date,
|
||||
endDate: row.end_date,
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
config: row.config,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
error: row.error,
|
||||
}));
|
||||
}
|
||||
|
||||
async updateBacktestStatus(id: string, status: BacktestJob['status'], error?: string): Promise<void> {
|
||||
if (error) {
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
|
||||
[status, error, id]
|
||||
);
|
||||
} else {
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
[status, id]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async cancelBacktest(id: string): Promise<void> {
|
||||
await this.updateBacktestStatus(id, 'cancelled');
|
||||
|
||||
// Call orchestrator to stop backtest
|
||||
try {
|
||||
await fetch(`${ORCHESTRATOR_URL}/api/backtest/stop`, {
|
||||
method: 'POST',
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to stop backtest in orchestrator', { backtestId: id, error });
|
||||
}
|
||||
}
|
||||
|
||||
private async saveBacktestResults(backtestId: string, result: any): Promise<void> {
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`INSERT INTO backtest_results
|
||||
(backtest_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
||||
[
|
||||
backtestId,
|
||||
result.completedAt || new Date(),
|
||||
JSON.stringify(result.metrics || {}),
|
||||
JSON.stringify(result.equity || result.equityCurve || []),
|
||||
JSON.stringify(result.ohlcData || {}),
|
||||
JSON.stringify(result.trades || []),
|
||||
JSON.stringify(result.positions || result.finalPositions || {}),
|
||||
JSON.stringify(result.analytics || {}),
|
||||
result.executionTime || 0
|
||||
]
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('Failed to save backtest results', { backtestId, error });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
import { randomUUID as uuidv4 } from 'node:crypto';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
|
||||
const logger = getLogger('backtest-service');
|
||||
|
||||
// Use environment variable or default
|
||||
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
|
||||
|
||||
export interface BacktestRequest {
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BacktestJob {
|
||||
id: string;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
initialCapital: number;
|
||||
config: Record<string, unknown>;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export class BacktestService {
|
||||
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
|
||||
|
||||
constructor(container: IServiceContainer) {
|
||||
this.container = requireServices(container, 'postgres');
|
||||
logger.info('BacktestService initialized', {
|
||||
hasPostgres: !!container.postgres,
|
||||
containerKeys: Object.keys(container),
|
||||
});
|
||||
}
|
||||
async createBacktest(request: BacktestRequest): Promise<BacktestJob> {
|
||||
const backtestId = uuidv4();
|
||||
|
||||
// Insert into PostgreSQL
|
||||
const result = await this.container.postgres.query(
|
||||
`INSERT INTO backtests
|
||||
(id, name, strategy, symbols, start_date, end_date, initial_capital, config, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending')
|
||||
RETURNING *`,
|
||||
[
|
||||
backtestId,
|
||||
request.config?.name || `Backtest ${new Date().toISOString()}`,
|
||||
request.strategy,
|
||||
JSON.stringify(request.symbols),
|
||||
request.startDate,
|
||||
request.endDate,
|
||||
request.initialCapital,
|
||||
JSON.stringify(request.config || {}),
|
||||
]
|
||||
);
|
||||
|
||||
const backtest: BacktestJob = {
|
||||
id: at(result.rows, 0).id,
|
||||
status: at(result.rows, 0).status,
|
||||
strategy: at(result.rows, 0).strategy,
|
||||
symbols: at(result.rows, 0).symbols,
|
||||
startDate: at(result.rows, 0).start_date,
|
||||
endDate: at(result.rows, 0).end_date,
|
||||
initialCapital: parseFloat(at(result.rows, 0).initial_capital),
|
||||
config: at(result.rows, 0).config,
|
||||
createdAt: at(result.rows, 0).created_at,
|
||||
updatedAt: at(result.rows, 0).updated_at,
|
||||
};
|
||||
|
||||
// Call orchestrator to run backtest
|
||||
try {
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
mode: 'backtest',
|
||||
startDate: new Date(request.startDate).toISOString(),
|
||||
endDate: new Date(request.endDate).toISOString(),
|
||||
symbols: request.symbols,
|
||||
strategy: request.strategy,
|
||||
initialCapital: request.initialCapital,
|
||||
dataFrequency: '1d', // Default to daily
|
||||
commission: request.config?.commission,
|
||||
slippage: request.config?.slippage,
|
||||
speed: 'max', // Default speed
|
||||
fillModel: {
|
||||
slippage: 'realistic',
|
||||
marketImpact: true,
|
||||
partialFills: true,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Orchestrator returned ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
// Store result directly without transformation
|
||||
if (result.status === 'completed') {
|
||||
// Update backtest status
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
['completed', backtestId]
|
||||
);
|
||||
|
||||
// Store results in backtest_results table
|
||||
await this.saveBacktestResults(backtestId, result);
|
||||
|
||||
logger.info('Backtest completed', {
|
||||
backtestId,
|
||||
trades: result.metrics?.totalTrades,
|
||||
return: result.metrics?.totalReturn,
|
||||
});
|
||||
} else {
|
||||
// Update status to running if not completed
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
['running', backtestId]
|
||||
);
|
||||
}
|
||||
|
||||
logger.info('Backtest started in orchestrator', { backtestId, result });
|
||||
} catch (error) {
|
||||
logger.error('Failed to start backtest in orchestrator', { backtestId, error });
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
|
||||
['failed', error instanceof Error ? error.message : String(error), backtestId]
|
||||
);
|
||||
backtest.status = 'failed';
|
||||
backtest.error = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
return backtest;
|
||||
}
|
||||
|
||||
async getBacktest(id: string): Promise<BacktestJob | null> {
|
||||
const result = await this.container.postgres.query('SELECT * FROM backtests WHERE id = $1', [
|
||||
id,
|
||||
]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = at(result.rows, 0);
|
||||
return {
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date,
|
||||
endDate: row.end_date,
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
config: row.config,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
error: row.error,
|
||||
};
|
||||
}
|
||||
|
||||
async getBacktestResults(id: string) {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT
|
||||
br.*,
|
||||
b.strategy,
|
||||
b.symbols,
|
||||
b.start_date,
|
||||
b.end_date,
|
||||
b.initial_capital,
|
||||
b.config as backtest_config
|
||||
FROM backtest_results br
|
||||
JOIN backtests b ON b.id = br.backtest_id
|
||||
WHERE br.backtest_id = $1`,
|
||||
[id]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = at(result.rows, 0);
|
||||
|
||||
// Reconstruct the result format expected by frontend
|
||||
return {
|
||||
backtestId: row.backtest_id,
|
||||
status: 'completed',
|
||||
completedAt: row.completed_at.toISOString(),
|
||||
config: {
|
||||
name: row.backtest_config?.name || 'Backtest',
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date.toISOString(),
|
||||
endDate: row.end_date.toISOString(),
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
commission: row.backtest_config?.commission ?? 0.001,
|
||||
slippage: row.backtest_config?.slippage ?? 0.0001,
|
||||
dataFrequency: row.backtest_config?.dataFrequency || '1d',
|
||||
},
|
||||
metrics: row.metrics,
|
||||
equity: row.equity_curve,
|
||||
ohlcData: row.ohlc_data,
|
||||
trades: row.trades,
|
||||
positions: row.positions,
|
||||
analytics: row.analytics,
|
||||
executionTime: row.execution_time,
|
||||
};
|
||||
}
|
||||
|
||||
async listBacktests(params: { limit: number; offset: number }): Promise<BacktestJob[]> {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT * FROM backtests
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1 OFFSET $2`,
|
||||
[params.limit, params.offset]
|
||||
);
|
||||
|
||||
return result.rows.map(row => ({
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date,
|
||||
endDate: row.end_date,
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
config: row.config,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
error: row.error,
|
||||
}));
|
||||
}
|
||||
|
||||
async updateBacktestStatus(
|
||||
id: string,
|
||||
status: BacktestJob['status'],
|
||||
error?: string
|
||||
): Promise<void> {
|
||||
if (error) {
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
|
||||
[status, error, id]
|
||||
);
|
||||
} else {
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
[status, id]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async cancelBacktest(id: string): Promise<void> {
|
||||
await this.updateBacktestStatus(id, 'cancelled');
|
||||
|
||||
// Call orchestrator to stop backtest
|
||||
try {
|
||||
await fetch(`${ORCHESTRATOR_URL}/api/backtest/stop`, {
|
||||
method: 'POST',
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to stop backtest in orchestrator', { backtestId: id, error });
|
||||
}
|
||||
}
|
||||
|
||||
private async saveBacktestResults(
|
||||
backtestId: string,
|
||||
result: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`INSERT INTO backtest_results
|
||||
(backtest_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
||||
[
|
||||
backtestId,
|
||||
result.completedAt || new Date(),
|
||||
JSON.stringify(result.metrics || {}),
|
||||
JSON.stringify(result.equity || result.equityCurve || []),
|
||||
JSON.stringify(result.ohlcData || {}),
|
||||
JSON.stringify(result.trades || []),
|
||||
JSON.stringify(result.positions || result.finalPositions || {}),
|
||||
JSON.stringify(result.analytics || {}),
|
||||
result.executionTime || 0,
|
||||
]
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('Failed to save backtest results', { backtestId, error });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,16 @@
|
|||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
CreateExchangeRequest,
|
||||
CreateProviderMappingRequest,
|
||||
Exchange,
|
||||
ExchangeStats,
|
||||
ExchangeWithMappings,
|
||||
ProviderExchange,
|
||||
ProviderMapping,
|
||||
UpdateExchangeRequest,
|
||||
UpdateProviderMappingRequest,
|
||||
type CreateExchangeRequest,
|
||||
type CreateProviderMappingRequest,
|
||||
type Exchange,
|
||||
type ExchangeStats,
|
||||
type ExchangeWithMappings,
|
||||
type ProviderExchange,
|
||||
type ProviderMapping,
|
||||
type UpdateExchangeRequest,
|
||||
type UpdateProviderMappingRequest,
|
||||
} from '../types/exchange.types';
|
||||
|
||||
const logger = getLogger('exchange-service');
|
||||
|
|
@ -18,11 +19,11 @@ export class ExchangeService {
|
|||
constructor(private container: IServiceContainer) {}
|
||||
|
||||
private get postgresClient() {
|
||||
return this.container.postgres;
|
||||
return requireServices(this.container, 'postgres').postgres;
|
||||
}
|
||||
|
||||
private get mongoClient() {
|
||||
return this.container.mongodb;
|
||||
return requireServices(this.container, 'mongodb').mongodb;
|
||||
}
|
||||
|
||||
// Exchanges
|
||||
|
|
@ -49,7 +50,7 @@ export class ExchangeService {
|
|||
ORDER BY e.code
|
||||
`;
|
||||
|
||||
const exchangesResult = await this.postgresClient.query(exchangesQuery);
|
||||
const exchangesResult = await this.postgresClient.query<ExchangeWithMappings>(exchangesQuery);
|
||||
|
||||
// Get all provider mappings
|
||||
const mappingsQuery = `
|
||||
|
|
@ -62,7 +63,7 @@ export class ExchangeService {
|
|||
WHERE e.visible = true
|
||||
ORDER BY pem.master_exchange_id, pem.provider, pem.provider_exchange_code
|
||||
`;
|
||||
const mappingsResult = await this.postgresClient.query(mappingsQuery);
|
||||
const mappingsResult = await this.postgresClient.query<ProviderMapping>(mappingsQuery);
|
||||
|
||||
// Group mappings by exchange ID
|
||||
const mappingsByExchange = mappingsResult.rows.reduce(
|
||||
|
|
@ -88,7 +89,7 @@ export class ExchangeService {
|
|||
id: string
|
||||
): Promise<{ exchange: Exchange; provider_mappings: ProviderMapping[] } | null> {
|
||||
const exchangeQuery = 'SELECT * FROM exchanges WHERE id = $1 AND visible = true';
|
||||
const exchangeResult = await this.postgresClient.query(exchangeQuery, [id]);
|
||||
const exchangeResult = await this.postgresClient.query<Exchange>(exchangeQuery, [id]);
|
||||
|
||||
if (exchangeResult.rows.length === 0) {
|
||||
return null;
|
||||
|
|
@ -104,10 +105,10 @@ export class ExchangeService {
|
|||
WHERE pem.master_exchange_id = $1
|
||||
ORDER BY pem.provider, pem.provider_exchange_code
|
||||
`;
|
||||
const mappingsResult = await this.postgresClient.query(mappingsQuery, [id]);
|
||||
const mappingsResult = await this.postgresClient.query<ProviderMapping>(mappingsQuery, [id]);
|
||||
|
||||
return {
|
||||
exchange: exchangeResult.rows[0],
|
||||
exchange: at(exchangeResult.rows, 0),
|
||||
provider_mappings: mappingsResult.rows,
|
||||
};
|
||||
}
|
||||
|
|
@ -119,7 +120,7 @@ export class ExchangeService {
|
|||
RETURNING *
|
||||
`;
|
||||
|
||||
const result = await this.postgresClient.query(query, [
|
||||
const result = await this.postgresClient.query<Exchange>(query, [
|
||||
data.code,
|
||||
data.name,
|
||||
data.country,
|
||||
|
|
@ -128,12 +129,12 @@ export class ExchangeService {
|
|||
]);
|
||||
|
||||
logger.info('Exchange created', {
|
||||
exchangeId: result.rows[0].id,
|
||||
exchangeId: at(result.rows, 0).id,
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
});
|
||||
|
||||
return result.rows[0];
|
||||
return at(result.rows, 0);
|
||||
}
|
||||
|
||||
async updateExchange(id: string, updates: UpdateExchangeRequest): Promise<Exchange | null> {
|
||||
|
|
@ -156,7 +157,7 @@ export class ExchangeService {
|
|||
RETURNING *
|
||||
`;
|
||||
|
||||
const result = await this.postgresClient.query(query, values);
|
||||
const result = await this.postgresClient.query<Exchange>(query, values);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
|
|
@ -169,7 +170,7 @@ export class ExchangeService {
|
|||
|
||||
logger.info('Exchange updated', { exchangeId: id, updates });
|
||||
|
||||
return result.rows[0];
|
||||
return result.rows[0] ?? null;
|
||||
}
|
||||
|
||||
// Provider Mappings
|
||||
|
|
@ -186,7 +187,7 @@ export class ExchangeService {
|
|||
ORDER BY pem.provider, pem.provider_exchange_code
|
||||
`;
|
||||
|
||||
const result = await this.postgresClient.query(query);
|
||||
const result = await this.postgresClient.query<ProviderMapping>(query);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
|
|
@ -203,7 +204,7 @@ export class ExchangeService {
|
|||
ORDER BY pem.provider_exchange_code
|
||||
`;
|
||||
|
||||
const result = await this.postgresClient.query(query, [provider]);
|
||||
const result = await this.postgresClient.query<ProviderMapping>(query, [provider]);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
|
|
@ -216,7 +217,7 @@ export class ExchangeService {
|
|||
RETURNING *
|
||||
`;
|
||||
|
||||
const result = await this.postgresClient.query(query, [
|
||||
const result = await this.postgresClient.query<ProviderMapping>(query, [
|
||||
data.provider,
|
||||
data.provider_exchange_code,
|
||||
data.provider_exchange_name,
|
||||
|
|
@ -234,7 +235,7 @@ export class ExchangeService {
|
|||
master_exchange_id: data.master_exchange_id,
|
||||
});
|
||||
|
||||
return result.rows[0];
|
||||
return at(result.rows, 0);
|
||||
}
|
||||
|
||||
async updateProviderMapping(
|
||||
|
|
@ -261,7 +262,7 @@ export class ExchangeService {
|
|||
RETURNING *
|
||||
`;
|
||||
|
||||
const result = await this.postgresClient.query(query, values);
|
||||
const result = await this.postgresClient.query<ProviderMapping>(query, values);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
|
|
@ -269,7 +270,7 @@ export class ExchangeService {
|
|||
|
||||
logger.info('Provider mapping updated', { mappingId: id, updates });
|
||||
|
||||
return result.rows[0];
|
||||
return result.rows[0] ?? null;
|
||||
}
|
||||
|
||||
async deleteProviderMappingsByExchangeId(exchangeId: string): Promise<number> {
|
||||
|
|
@ -309,8 +310,8 @@ export class ExchangeService {
|
|||
(SELECT COUNT(DISTINCT provider) FROM provider_exchange_mappings pem JOIN exchanges e ON pem.master_exchange_id = e.id WHERE e.visible = true) as providers
|
||||
`;
|
||||
|
||||
const result = await this.postgresClient.query(query);
|
||||
return result.rows[0];
|
||||
const result = await this.postgresClient.query<ExchangeStats>(query);
|
||||
return at(result.rows, 0);
|
||||
}
|
||||
|
||||
async getUnmappedProviderExchanges(provider: string): Promise<ProviderExchange[]> {
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
import * as os from 'os';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { getFullQueueName } from '@stock-bot/queue';
|
||||
import type {
|
||||
CacheStats,
|
||||
DatabaseStats,
|
||||
|
|
@ -73,269 +74,53 @@ export class MonitoringService {
|
|||
* Get queue statistics
|
||||
*/
|
||||
async getQueueStats(): Promise<QueueStats[]> {
|
||||
const stats: QueueStats[] = [];
|
||||
|
||||
try {
|
||||
if (!this.container.queueManager) {
|
||||
this.logger.warn('No queue manager available');
|
||||
return stats;
|
||||
}
|
||||
|
||||
// Get all queue names from the QueueManager
|
||||
const queueManager = this.container.queueManager as any;
|
||||
this.logger.debug('Queue manager type:', {
|
||||
type: queueManager.constructor.name,
|
||||
hasGetAllQueues: typeof queueManager.getAllQueues === 'function',
|
||||
hasQueues: !!queueManager.queues,
|
||||
hasGetQueue: typeof queueManager.getQueue === 'function',
|
||||
});
|
||||
|
||||
// Always use the known queue names since web-api doesn't create worker queues
|
||||
const handlerMapping = {
|
||||
qm: 'data-ingestion',
|
||||
ib: 'data-ingestion',
|
||||
ceo: 'data-ingestion',
|
||||
webshare: 'data-ingestion',
|
||||
exchanges: 'data-pipeline',
|
||||
symbols: 'data-pipeline',
|
||||
};
|
||||
|
||||
// Worker configuration per queue (from service configs)
|
||||
const workerConfig: Record<string, { count: number; concurrency: number }> = {
|
||||
qm: { count: 1, concurrency: 2 },
|
||||
ib: { count: 1, concurrency: 1 },
|
||||
ceo: { count: 1, concurrency: 2 },
|
||||
webshare: { count: 1, concurrency: 1 },
|
||||
exchanges: { count: 1, concurrency: 1 },
|
||||
symbols: { count: 1, concurrency: 2 },
|
||||
};
|
||||
|
||||
const queueNames = Object.keys(handlerMapping);
|
||||
this.logger.debug('Using known queue names', { count: queueNames.length, names: queueNames });
|
||||
|
||||
// Create BullMQ queues directly with the correct format
|
||||
for (const handlerName of queueNames) {
|
||||
try {
|
||||
// Import BullMQ directly to create queue instances
|
||||
const { Queue: BullMQQueue } = await import('bullmq');
|
||||
const connection = {
|
||||
host: 'localhost',
|
||||
port: 6379,
|
||||
db: 0, // All queues now in DB 0
|
||||
};
|
||||
|
||||
// Get the service that owns this handler
|
||||
const serviceName = handlerMapping[handlerName as keyof typeof handlerMapping];
|
||||
|
||||
// Create BullMQ queue with the new naming format {service_handler}
|
||||
const fullQueueName = `{${serviceName}_${handlerName}}`;
|
||||
const bullQueue = new BullMQQueue(fullQueueName, { connection });
|
||||
|
||||
// Get stats directly from BullMQ
|
||||
const queueStats = await this.getQueueStatsForBullQueue(bullQueue, handlerName);
|
||||
|
||||
// Get actual worker count from BullMQ
|
||||
const actualWorkerCount = await this.getActiveWorkerCountFromBullMQ(bullQueue);
|
||||
const configuredWorkers = workerConfig[handlerName] || { count: 0, concurrency: 1 };
|
||||
|
||||
stats.push({
|
||||
name: handlerName,
|
||||
service: serviceName,
|
||||
queue: handlerName,
|
||||
connected: true,
|
||||
jobs: queueStats,
|
||||
workers: {
|
||||
count: actualWorkerCount,
|
||||
concurrency: configuredWorkers.concurrency,
|
||||
},
|
||||
});
|
||||
|
||||
// Close the queue connection after getting stats
|
||||
await bullQueue.close();
|
||||
} catch (error) {
|
||||
this.logger.warn(`Failed to get stats for queue ${handlerName}`, { error });
|
||||
stats.push({
|
||||
name: handlerName,
|
||||
service: serviceName,
|
||||
queue: handlerName,
|
||||
connected: false,
|
||||
jobs: {
|
||||
waiting: 0,
|
||||
active: 0,
|
||||
completed: 0,
|
||||
failed: 0,
|
||||
delayed: 0,
|
||||
paused: 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error('Failed to get queue stats', { error });
|
||||
const manager = this.container.queueManager;
|
||||
if (!manager) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get stats for a BullMQ queue directly
|
||||
*/
|
||||
private async getQueueStatsForBullQueue(bullQueue: any, queueName: string) {
|
||||
try {
|
||||
// BullMQ provides getJobCounts which returns all counts at once
|
||||
const counts = await bullQueue.getJobCounts();
|
||||
|
||||
return {
|
||||
waiting: counts.waiting || 0,
|
||||
active: counts.active || 0,
|
||||
completed: counts.completed || 0,
|
||||
failed: counts.failed || 0,
|
||||
delayed: counts.delayed || 0,
|
||||
paused: counts.paused || 0,
|
||||
prioritized: counts.prioritized || 0,
|
||||
'waiting-children': counts['waiting-children'] || 0,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to get stats for BullMQ queue ${queueName}`, { error });
|
||||
// Fallback to individual methods
|
||||
try {
|
||||
const [waiting, active, completed, failed, delayed, paused] = await Promise.all([
|
||||
bullQueue.getWaitingCount(),
|
||||
bullQueue.getActiveCount(),
|
||||
bullQueue.getCompletedCount(),
|
||||
bullQueue.getFailedCount(),
|
||||
bullQueue.getDelayedCount(),
|
||||
bullQueue.getPausedCount ? bullQueue.getPausedCount() : 0,
|
||||
]);
|
||||
|
||||
return {
|
||||
waiting,
|
||||
active,
|
||||
completed,
|
||||
failed,
|
||||
delayed,
|
||||
paused,
|
||||
};
|
||||
} catch (fallbackError) {
|
||||
this.logger.error(`Fallback also failed for queue ${queueName}`, { fallbackError });
|
||||
return this.getQueueStatsForQueue(bullQueue, queueName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get stats for a specific queue
|
||||
*/
|
||||
private async getQueueStatsForQueue(queue: any, _queueName: string) {
|
||||
// Check if it has the getStats method
|
||||
if (queue.getStats && typeof queue.getStats === 'function') {
|
||||
const stats = await queue.getStats();
|
||||
return {
|
||||
waiting: stats.waiting || 0,
|
||||
active: stats.active || 0,
|
||||
completed: stats.completed || 0,
|
||||
failed: stats.failed || 0,
|
||||
delayed: stats.delayed || 0,
|
||||
paused: stats.paused || 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Try individual count methods
|
||||
const [waiting, active, completed, failed, delayed] = await Promise.all([
|
||||
this.safeGetCount(queue, 'getWaitingCount', 'getWaiting'),
|
||||
this.safeGetCount(queue, 'getActiveCount', 'getActive'),
|
||||
this.safeGetCount(queue, 'getCompletedCount', 'getCompleted'),
|
||||
this.safeGetCount(queue, 'getFailedCount', 'getFailed'),
|
||||
this.safeGetCount(queue, 'getDelayedCount', 'getDelayed'),
|
||||
]);
|
||||
|
||||
const paused = await this.safeGetPausedStatus(queue);
|
||||
|
||||
return {
|
||||
waiting,
|
||||
active,
|
||||
completed,
|
||||
failed,
|
||||
delayed,
|
||||
paused,
|
||||
const owners = {
|
||||
qm: 'data-ingestion',
|
||||
ib: 'data-ingestion',
|
||||
ceo: 'data-ingestion',
|
||||
webshare: 'data-ingestion',
|
||||
exchanges: 'data-pipeline',
|
||||
symbols: 'data-pipeline',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely get count from queue
|
||||
*/
|
||||
private async safeGetCount(queue: any, ...methodNames: string[]): Promise<number> {
|
||||
for (const methodName of methodNames) {
|
||||
if (queue[methodName] && typeof queue[methodName] === 'function') {
|
||||
return Promise.all(
|
||||
Object.entries(owners).map(async ([name, service]) => {
|
||||
try {
|
||||
const result = await queue[methodName]();
|
||||
return Array.isArray(result) ? result.length : result || 0;
|
||||
} catch (_e) {
|
||||
// Continue to next method
|
||||
const queue = manager.getQueue(getFullQueueName(service, name));
|
||||
const snapshot = await queue.getStats();
|
||||
return {
|
||||
name,
|
||||
service,
|
||||
queue: name,
|
||||
connected: true,
|
||||
jobs: {
|
||||
waiting: snapshot.waiting,
|
||||
active: snapshot.active,
|
||||
completed: snapshot.completed,
|
||||
failed: snapshot.failed,
|
||||
delayed: snapshot.delayed,
|
||||
paused: snapshot.paused ? 1 : 0,
|
||||
},
|
||||
workers: { count: snapshot.workers ?? queue.getWorkerCount(), concurrency: 1 },
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.warn('Unable to inspect queue', { name, service, error });
|
||||
return {
|
||||
name,
|
||||
service,
|
||||
queue: name,
|
||||
connected: false,
|
||||
jobs: { waiting: 0, active: 0, completed: 0, failed: 0, delayed: 0, paused: 0 },
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get paused status
|
||||
*/
|
||||
private async safeGetPausedStatus(queue: any): Promise<number> {
|
||||
try {
|
||||
if (queue.isPaused && typeof queue.isPaused === 'function') {
|
||||
const isPaused = await queue.isPaused();
|
||||
return isPaused ? 1 : 0;
|
||||
}
|
||||
if (queue.getPausedCount && typeof queue.getPausedCount === 'function') {
|
||||
return await queue.getPausedCount();
|
||||
}
|
||||
} catch (_e) {
|
||||
// Ignore
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get worker info for a queue
|
||||
*/
|
||||
private getWorkerInfo(queue: any, queueManager: any, _queueName: string) {
|
||||
try {
|
||||
// Check queue itself for worker info
|
||||
if (queue.workers && Array.isArray(queue.workers)) {
|
||||
return {
|
||||
count: queue.workers.length,
|
||||
concurrency: queue.workers[0]?.concurrency || 1,
|
||||
};
|
||||
}
|
||||
|
||||
// Check queue manager for worker config
|
||||
if (queueManager.config?.defaultQueueOptions) {
|
||||
const options = queueManager.config.defaultQueueOptions;
|
||||
return {
|
||||
count: options.workers || 1,
|
||||
concurrency: options.concurrency || 1,
|
||||
};
|
||||
}
|
||||
|
||||
// Check for getWorkerCount method
|
||||
if (queue.getWorkerCount && typeof queue.getWorkerCount === 'function') {
|
||||
const count = queue.getWorkerCount();
|
||||
return {
|
||||
count,
|
||||
concurrency: 1,
|
||||
};
|
||||
}
|
||||
} catch (_e) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get database statistics
|
||||
*/
|
||||
/** Database health uses the public adapter capabilities. */
|
||||
async getDatabaseStats(): Promise<DatabaseStats[]> {
|
||||
const stats: DatabaseStats[] = [];
|
||||
|
||||
|
|
@ -347,12 +132,13 @@ export class MonitoringService {
|
|||
const latency = Date.now() - startTime;
|
||||
|
||||
// Get pool stats
|
||||
const pool = (this.container.postgres as any).pool;
|
||||
const pool = this.container.postgres.connectionPool;
|
||||
const poolStats = pool
|
||||
? {
|
||||
size: pool.totalCount || 0,
|
||||
active: pool.idleCount || 0,
|
||||
idle: pool.waitingCount || 0,
|
||||
active: pool.totalCount - pool.idleCount,
|
||||
idle: pool.idleCount,
|
||||
waiting: pool.waitingCount,
|
||||
max: pool.options?.max || 0,
|
||||
}
|
||||
: undefined;
|
||||
|
|
@ -378,7 +164,7 @@ export class MonitoringService {
|
|||
if (this.container.mongodb) {
|
||||
try {
|
||||
const startTime = Date.now();
|
||||
const mongoClient = this.container.mongodb as any; // This is MongoDBClient
|
||||
const mongoClient = this.container.mongodb; // This is MongoDBClient
|
||||
const db = mongoClient.getDatabase();
|
||||
await db.admin().ping();
|
||||
const latency = Date.now() - startTime;
|
||||
|
|
@ -528,14 +314,14 @@ export class MonitoringService {
|
|||
*/
|
||||
private parseInfoValue(info: string, key: string): number {
|
||||
const match = info.match(new RegExp(`${key}:(\\d+)`));
|
||||
return match ? parseInt(match[1], 10) : 0;
|
||||
return match?.[1] ? parseInt(match[1], 10) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Redis INFO into structured object
|
||||
*/
|
||||
private parseRedisInfo(info: string): Record<string, any> {
|
||||
const result: Record<string, any> = {};
|
||||
private parseRedisInfo(info: string): Record<string, Record<string, string>> {
|
||||
const result: Record<string, Record<string, string>> = {};
|
||||
const sections = info.split('\r\n\r\n');
|
||||
|
||||
for (const section of sections) {
|
||||
|
|
@ -544,7 +330,7 @@ export class MonitoringService {
|
|||
result[sectionName] = {};
|
||||
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const [key, value] = lines[i].split(':');
|
||||
const [key, value] = (lines[i] ?? '').split(':');
|
||||
if (key && value) {
|
||||
result[sectionName][key] = value;
|
||||
}
|
||||
|
|
@ -656,7 +442,7 @@ export class MonitoringService {
|
|||
this.logger.debug('Attempting to fetch proxy data from cache');
|
||||
|
||||
const [cachedProxies, lastUpdateStr] = await Promise.all([
|
||||
cacheProvider.getRaw<any[]>('cache:proxy:active'),
|
||||
cacheProvider.getRaw<{ isWorking?: boolean }[]>('cache:proxy:active'),
|
||||
cacheProvider.getRaw<string>('cache:proxy:last-update'),
|
||||
]);
|
||||
|
||||
|
|
@ -668,8 +454,8 @@ export class MonitoringService {
|
|||
});
|
||||
|
||||
if (cachedProxies && Array.isArray(cachedProxies)) {
|
||||
const workingCount = cachedProxies.filter((p: any) => p.isWorking !== false).length;
|
||||
const failedCount = cachedProxies.filter((p: any) => p.isWorking === false).length;
|
||||
const workingCount = cachedProxies.filter(p => p.isWorking !== false).length;
|
||||
const failedCount = cachedProxies.filter(p => p.isWorking === false).length;
|
||||
|
||||
return {
|
||||
enabled: true,
|
||||
|
|
@ -811,23 +597,4 @@ export class MonitoringService {
|
|||
/**
|
||||
* Get active worker count using BullMQ's built-in tracking
|
||||
*/
|
||||
private async getActiveWorkerCountFromBullMQ(bullQueue: any): Promise<number> {
|
||||
try {
|
||||
// Use BullMQ's built-in getWorkers method
|
||||
if (bullQueue.getWorkers && typeof bullQueue.getWorkers === 'function') {
|
||||
const workers = await bullQueue.getWorkers();
|
||||
return workers.length;
|
||||
}
|
||||
|
||||
// Fallback to getWorkersCount if available
|
||||
if (bullQueue.getWorkersCount && typeof bullQueue.getWorkersCount === 'function') {
|
||||
return await bullQueue.getWorkersCount();
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
this.logger.debug('Failed to get active worker count from BullMQ', { error });
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,12 +14,12 @@ export interface PipelineJobResult {
|
|||
jobId?: string;
|
||||
message?: string;
|
||||
error?: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
}
|
||||
|
||||
export interface PipelineStatsResult {
|
||||
success: boolean;
|
||||
data?: any;
|
||||
data?: Record<string, unknown>;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
|
|
@ -294,7 +294,7 @@ export class PipelineService {
|
|||
});
|
||||
|
||||
// Wait for job to complete and return result
|
||||
const result = await exchangesQueue.waitForJob(job);
|
||||
const result = await exchangesQueue.waitForJob<Record<string, unknown>>(job);
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
logger.error('Failed to get exchange stats', { error });
|
||||
|
|
@ -323,7 +323,7 @@ export class PipelineService {
|
|||
});
|
||||
|
||||
// Wait for job to complete and return result
|
||||
const result = await exchangesQueue.waitForJob(job);
|
||||
const result = await exchangesQueue.waitForJob<Record<string, unknown>>(job);
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
logger.error('Failed to get provider mapping stats', { error });
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ export interface CacheStats {
|
|||
evictedKeys?: number;
|
||||
expiredKeys?: number;
|
||||
};
|
||||
info?: Record<string, any>;
|
||||
info?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface QueueStats {
|
||||
|
|
@ -59,7 +59,7 @@ export interface DatabaseStats {
|
|||
waiting?: number;
|
||||
max: number;
|
||||
};
|
||||
stats?: Record<string, any>;
|
||||
stats?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface SystemHealth {
|
||||
|
|
@ -70,6 +70,7 @@ export interface SystemHealth {
|
|||
used: number;
|
||||
total: number;
|
||||
percentage: number;
|
||||
heap?: { used: number; total: number };
|
||||
};
|
||||
cpu?: {
|
||||
usage: number;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Context } from 'hono';
|
||||
import type { Context } from 'hono';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { ApiResponse } from '../types/exchange.types';
|
||||
import type { ApiResponse } from '../types/exchange.types';
|
||||
import { ValidationError } from './validation';
|
||||
|
||||
const logger = getLogger('error-handler');
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { CreateExchangeRequest, CreateProviderMappingRequest } from '../types/exchange.types';
|
||||
import type { CreateExchangeRequest, CreateProviderMappingRequest } from '../types/exchange.types';
|
||||
|
||||
export class ValidationError extends Error {
|
||||
constructor(
|
||||
|
|
@ -85,14 +85,15 @@ export function validateCreateProviderMapping(data: unknown): CreateProviderMapp
|
|||
}
|
||||
|
||||
// Validate currency is 3 characters or null
|
||||
const cleanCurrency = currency && currency.length <= 3 ? currency : null;
|
||||
const cleanCurrency = typeof currency === 'string' && currency.length <= 3 ? currency : undefined;
|
||||
|
||||
return {
|
||||
provider: provider.trim(),
|
||||
provider_exchange_code: provider_exchange_code.trim(),
|
||||
provider_exchange_name: provider_exchange_name?.trim(),
|
||||
provider_exchange_name:
|
||||
typeof provider_exchange_name === 'string' ? provider_exchange_name.trim() : undefined,
|
||||
master_exchange_id: master_exchange_id.trim(),
|
||||
country_code: country_code?.trim() || null,
|
||||
country_code: typeof country_code === 'string' ? country_code.trim() || undefined : undefined,
|
||||
currency: cleanCurrency,
|
||||
confidence: Number(confidence),
|
||||
active: Boolean(active),
|
||||
|
|
|
|||
|
|
@ -1,160 +1,118 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
|
||||
const logger = getLogger('websocket-run-updates');
|
||||
|
||||
// Store active WebSocket connections per run
|
||||
// Using 'any' type for Bun WebSocket compatibility
|
||||
const runConnections = new Map<string, Set<any>>();
|
||||
|
||||
export interface RunUpdateMessage {
|
||||
type: 'run_update' | 'progress' | 'error' | 'completed';
|
||||
runId: string;
|
||||
data: any;
|
||||
}
|
||||
|
||||
export function createWebSocketHandler(container: IServiceContainer) {
|
||||
return {
|
||||
// Handle new WebSocket connection (ws is Bun's WebSocket type)
|
||||
handleConnection(ws: any, runId: string) {
|
||||
logger.info(`WebSocket connected for run: ${runId}`);
|
||||
|
||||
// Add connection to the run's connection set
|
||||
if (!runConnections.has(runId)) {
|
||||
runConnections.set(runId, new Set());
|
||||
}
|
||||
runConnections.get(runId)!.add(ws);
|
||||
|
||||
// Send initial connection confirmation
|
||||
ws.send(JSON.stringify({
|
||||
type: 'connected',
|
||||
runId,
|
||||
timestamp: new Date().toISOString()
|
||||
}));
|
||||
|
||||
// In Bun, WebSocket handlers are set directly as properties
|
||||
ws.onmessage = (event: MessageEvent) => {
|
||||
try {
|
||||
const message = JSON.parse(event.data.toString());
|
||||
logger.debug('Received WebSocket message:', message);
|
||||
|
||||
// Handle different message types
|
||||
switch (message.type) {
|
||||
case 'ping':
|
||||
ws.send(JSON.stringify({ type: 'pong' }));
|
||||
break;
|
||||
case 'subscribe':
|
||||
// Already subscribed to this run
|
||||
break;
|
||||
default:
|
||||
logger.warn('Unknown message type:', message.type);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error handling WebSocket message:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle connection close
|
||||
ws.onclose = (event: any) => {
|
||||
logger.info(`WebSocket disconnected for run: ${runId}`, { code: event.code, reason: event.reason });
|
||||
const connections = runConnections.get(runId);
|
||||
if (connections) {
|
||||
connections.delete(ws);
|
||||
if (connections.size === 0) {
|
||||
runConnections.delete(runId);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Handle errors
|
||||
ws.onerror = (error: Event) => {
|
||||
logger.error(`WebSocket error for run ${runId}:`, error);
|
||||
};
|
||||
},
|
||||
|
||||
// Broadcast update to all connected clients for a run
|
||||
broadcastRunUpdate(runId: string, update: Partial<RunUpdateMessage>) {
|
||||
const connections = runConnections.get(runId);
|
||||
if (!connections || connections.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message: RunUpdateMessage = {
|
||||
type: 'run_update',
|
||||
runId,
|
||||
data: update.data || update,
|
||||
...update
|
||||
};
|
||||
|
||||
const messageStr = JSON.stringify(message);
|
||||
|
||||
connections.forEach(ws => {
|
||||
try {
|
||||
// Bun WebSocket - just try to send, it will throw if not open
|
||||
ws.send(messageStr);
|
||||
} catch (error) {
|
||||
// Connection is closed, ignore
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
// Send progress update
|
||||
sendProgressUpdate(runId: string, progress: number, currentDate?: string) {
|
||||
this.broadcastRunUpdate(runId, {
|
||||
type: 'progress',
|
||||
data: {
|
||||
progress,
|
||||
currentDate,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
// Send error
|
||||
sendError(runId: string, error: string) {
|
||||
this.broadcastRunUpdate(runId, {
|
||||
type: 'error',
|
||||
data: {
|
||||
error,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
// Send completion
|
||||
sendCompletion(runId: string, results?: any) {
|
||||
this.broadcastRunUpdate(runId, {
|
||||
type: 'completed',
|
||||
data: {
|
||||
results,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
// Clean up connections after completion
|
||||
setTimeout(() => {
|
||||
const connections = runConnections.get(runId);
|
||||
if (connections) {
|
||||
connections.forEach(ws => ws.close());
|
||||
runConnections.delete(runId);
|
||||
}
|
||||
}, 5000);
|
||||
},
|
||||
|
||||
// Get active connections count
|
||||
getConnectionsCount(runId: string): number {
|
||||
return runConnections.get(runId)?.size || 0;
|
||||
},
|
||||
|
||||
// Clean up all connections
|
||||
cleanup() {
|
||||
runConnections.forEach((connections, runId) => {
|
||||
connections.forEach(ws => ws.close());
|
||||
});
|
||||
runConnections.clear();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Export the WebSocket handler type
|
||||
export type WebSocketHandler = ReturnType<typeof createWebSocketHandler>;
|
||||
import type { ServerWebSocket } from 'bun';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
|
||||
const logger = getLogger('websocket-run-updates');
|
||||
export interface RunSocketData {
|
||||
runId: string;
|
||||
}
|
||||
type RunSocket = ServerWebSocket<RunSocketData>;
|
||||
export interface RunUpdateMessage {
|
||||
type: 'run_update' | 'progress' | 'error' | 'completed';
|
||||
runId: string;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
export function createWebSocketHandler(_container: IServiceContainer) {
|
||||
const connections = new Map<string, Set<RunSocket>>();
|
||||
const completionTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
return {
|
||||
handleConnection(ws: RunSocket, runId: string) {
|
||||
const clients = connections.get(runId) ?? new Set<RunSocket>();
|
||||
clients.add(ws);
|
||||
connections.set(runId, clients);
|
||||
ws.send(JSON.stringify({ type: 'connected', runId, timestamp: new Date().toISOString() }));
|
||||
},
|
||||
handleMessage(ws: RunSocket, payload: string | Buffer) {
|
||||
try {
|
||||
const message: unknown = JSON.parse(payload.toString());
|
||||
if (
|
||||
message &&
|
||||
typeof message === 'object' &&
|
||||
'type' in message &&
|
||||
message.type === 'ping'
|
||||
) {
|
||||
ws.send(JSON.stringify({ type: 'pong' }));
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Invalid WebSocket message', { error });
|
||||
}
|
||||
},
|
||||
handleClose(ws: RunSocket) {
|
||||
const runId = ws.data.runId;
|
||||
const clients = connections.get(runId);
|
||||
clients?.delete(ws);
|
||||
if (clients?.size === 0) {
|
||||
connections.delete(runId);
|
||||
}
|
||||
},
|
||||
broadcastRunUpdate(runId: string, update: Partial<RunUpdateMessage>) {
|
||||
const message: RunUpdateMessage = {
|
||||
type: 'run_update',
|
||||
runId,
|
||||
data: update.data ?? update,
|
||||
...update,
|
||||
};
|
||||
for (const ws of connections.get(runId) ?? []) {
|
||||
try {
|
||||
ws.send(JSON.stringify(message));
|
||||
} catch {
|
||||
this.handleClose(ws);
|
||||
}
|
||||
}
|
||||
},
|
||||
sendProgressUpdate(runId: string, progress: number, currentDate?: string) {
|
||||
this.broadcastRunUpdate(runId, {
|
||||
type: 'progress',
|
||||
data: { progress, currentDate, timestamp: new Date().toISOString() },
|
||||
});
|
||||
},
|
||||
sendError(runId: string, error: string) {
|
||||
this.broadcastRunUpdate(runId, {
|
||||
type: 'error',
|
||||
data: { error, timestamp: new Date().toISOString() },
|
||||
});
|
||||
},
|
||||
sendCompletion(runId: string, results?: unknown) {
|
||||
this.broadcastRunUpdate(runId, {
|
||||
type: 'completed',
|
||||
data: { results, timestamp: new Date().toISOString() },
|
||||
});
|
||||
clearTimeout(completionTimers.get(runId));
|
||||
completionTimers.set(
|
||||
runId,
|
||||
setTimeout(() => {
|
||||
for (const ws of connections.get(runId) ?? []) {
|
||||
ws.close();
|
||||
}
|
||||
connections.delete(runId);
|
||||
completionTimers.delete(runId);
|
||||
}, 5000)
|
||||
);
|
||||
},
|
||||
getConnectionsCount(runId: string): number {
|
||||
return connections.get(runId)?.size ?? 0;
|
||||
},
|
||||
cleanup() {
|
||||
for (const timer of completionTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
completionTimers.clear();
|
||||
for (const clients of connections.values()) {
|
||||
for (const ws of clients) {
|
||||
ws.close();
|
||||
}
|
||||
}
|
||||
connections.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type WebSocketHandler = ReturnType<typeof createWebSocketHandler>;
|
||||
let sharedHandler: WebSocketHandler | null = null;
|
||||
export function setWebSocketHandler(handler: WebSocketHandler): void {
|
||||
sharedHandler = handler;
|
||||
}
|
||||
export function getWebSocketHandler(): WebSocketHandler | null {
|
||||
return sharedHandler;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue