stock-bot/apps/stock/web-api/src/routes/backtests-v2.routes.ts

370 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Hono } from 'hono';
import { z } from 'zod';
import {
getCredentialHttpPrincipal,
getResearchHttpPrincipal,
getVerifiedHttpPrincipal,
} from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import {
isBacktestRequestError,
rejectCatalogVersionReferences,
} from '@stock-bot/stock-config/backtest';
import { isResearchAgent } from '@stock-bot/types';
import {
BacktestRetentionError,
BacktestServiceV2,
CatalogExecutionUnavailableError,
RunSubmissionConflictError,
} from '../services/backtest-v2.service';
import { RunReproductionError } from '../services/run-reproduction';
import { StrategyCatalogError } from '../services/strategy-catalog.service';
const logger = getLogger('backtests-v2-routes');
export function createBacktestV2Routes(container: IServiceContainer) {
const app = new Hono();
const backtestService = new BacktestServiceV2(container);
const agentScope = (request: Request) => {
const principal = getResearchHttpPrincipal(request);
return principal && isResearchAgent(principal) ? principal : undefined;
};
// 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 archiveQuery = c.req.query('includeArchived');
if (archiveQuery !== undefined && archiveQuery !== 'true' && archiveQuery !== 'false') {
return c.json({ error: 'includeArchived must be true or false' }, 400);
}
const agentId = agentScope(c.req.raw);
const backtests = await backtestService.listBacktests({
limit,
offset,
includeArchived: archiveQuery === 'true',
...(agentId ? { agentId } : {}),
});
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.get('/api/v2/backtests/:id/canonical-capability', async c =>
c.json(await backtestService.canonicalCapability(c.req.param('id')))
);
app.post('/api/v2/backtests', async c => {
try {
const body = await c.req.json();
if (body.autoStart !== undefined && typeof body.autoStart !== 'boolean') {
return c.json({ error: 'autoStart must be a boolean' }, 400);
}
// Saving requires explicit autoStart:false; run submission is a separate operation.
const { autoStart, ...definition } = body;
const backtest = await backtestService.createBacktest(definition, { autoStart });
return c.json(backtest, 201);
} catch (error) {
logger.error('Failed to create backtest', error);
if (error instanceof StrategyCatalogError) {
return c.json({ error: error.message }, error.status);
}
if (isBacktestRequestError(error)) {
return c.json({ error: error.message }, 400);
}
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);
if (error instanceof StrategyCatalogError) {
return c.json({ error: error.message }, error.status);
}
if (error instanceof BacktestRetentionError) {
return c.json({ error: error.message, code: error.code }, 409);
}
if (isBacktestRequestError(error)) {
return c.json({ error: error.message }, 400);
}
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);
if (error instanceof BacktestRetentionError) {
return c.json({ error: error.message, code: error.code, runCount: error.runCount }, 409);
}
return c.json({ error: 'Failed to delete backtest' }, 500);
}
});
app.post('/api/v2/backtests/:id/archive', async c => {
try {
const body = z
.object({ archived: z.boolean() })
.strict()
.parse(await c.req.json());
const backtest = await backtestService.archiveBacktest(c.req.param('id'), body.archived);
return backtest ? c.json(backtest) : c.json({ error: 'Backtest not found' }, 404);
} catch (error) {
if (error instanceof z.ZodError || error instanceof SyntaxError) {
return c.json({ error: 'Archive request must contain only archived: boolean' }, 400);
}
logger.error('Failed to archive backtest', error);
return c.json({ error: 'Failed to archive backtest' }, 500);
}
});
// Run endpoints
app.get('/api/v2/backtests/:backtestId/runs', async c => {
try {
const runs = await backtestService.listRuns(
c.req.param('backtestId'),
agentScope(c.req.raw)
);
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 key = c.req.header('Idempotency-Key');
const principal = getVerifiedHttpPrincipal(c.req.raw);
if (key !== undefined && !principal) {
return c.json({ error: 'Verified submission principal required' }, 401);
}
if (key !== undefined && !/^[\x21-\x7e]{1,200}$/.test(key)) {
return c.json(
{ error: 'Idempotency-Key must contain 1–200 visible ASCII characters' },
400
);
}
const body = await c.req.json();
rejectCatalogVersionReferences(body);
const run = await backtestService.createRun(
{ backtestId: c.req.param('backtestId'), speedMultiplier: body.speedMultiplier },
key !== undefined && principal ? { principal, key } : undefined
);
c.header('Location', `/api/v2/runs/${run.id}`);
return c.json(run, 202);
} catch (error) {
logger.error('Failed to create run', error);
if (error instanceof CatalogExecutionUnavailableError) {
return c.json({ error: error.message, code: error.code }, 409);
}
if (error instanceof BacktestRetentionError) {
return c.json({ error: error.message, code: error.code }, 409);
}
if (error instanceof RunSubmissionConflictError) {
return c.json({ error: error.message }, 409);
}
if (isBacktestRequestError(error)) {
return c.json({ error: error.message }, 400);
}
return c.json({ error: 'Failed to create run' }, 500);
}
});
app.get('/api/v2/runs/:id/reproduction', async c => {
c.header('Cache-Control', 'no-store');
const id = z.string().uuid().safeParse(c.req.param('id'));
if (!id.success) {
return c.json({ error: 'Invalid original run ID' }, 400);
}
try {
return c.json(await backtestService.getReproductionPreview(id.data));
} catch (error) {
if (error instanceof RunReproductionError) {
return c.json({ error: error.message, code: error.code }, error.status);
}
logger.error('Failed to preview reproduction', error);
return c.json({ error: 'Could not inspect original run reproduction' }, 500);
}
});
app.post('/api/v2/runs/:id/reproduce', async c => {
c.header('Cache-Control', 'no-store');
const principal = getCredentialHttpPrincipal(c.req.raw);
if (!principal) {
return c.json({ error: 'Verified credential principal required' }, 401);
}
let originalRunId: string;
let key: string;
try {
originalRunId = z.string().uuid().parse(c.req.param('id'));
key = z
.string()
.regex(/^[\x21-\x7e]{1,200}$/)
.parse(c.req.header('Idempotency-Key'));
z.object({})
.strict()
.parse(await c.req.json());
} catch {
return c.json(
{ error: 'Use a valid run ID, an empty object and a 1–200 visible ASCII Idempotency-Key' },
400
);
}
try {
const run = await backtestService.reproduceRun(originalRunId, { principal, key });
c.header('Location', `/api/v2/runs/${run.id}`);
return c.json(run, 202);
} catch (error) {
if (error instanceof RunReproductionError) {
return c.json({ error: error.message, code: error.code }, error.status);
}
if (error instanceof BacktestRetentionError || error instanceof RunSubmissionConflictError) {
return c.json({ error: error.message }, 409);
}
logger.error('Failed to reproduce original run', error);
return c.json({ error: 'Could not reproduce original run' }, 500);
}
});
app.get('/api/v2/runs/:id/reproduction-comparison', async c => {
c.header('Cache-Control', 'no-store');
const id = z.string().uuid().safeParse(c.req.param('id'));
if (!id.success) {
return c.json({ error: 'Invalid run ID' }, 400);
}
try {
return c.json(await backtestService.getReproductionComparison(id.data));
} catch (error) {
if (error instanceof RunReproductionError) {
return c.json({ error: error.message, code: error.code }, error.status);
}
logger.error('Failed to compare reproduction', error);
return c.json({ error: 'Could not compare retained reproduction results' }, 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: 'Cancellation requested' }, 202);
} 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, attemptId } = body;
if (typeof attemptId !== 'string') {
return c.json({ error: 'Execution attempt ID required' }, 400);
}
// Update run progress in database
await backtestService.updateRunProgress(runId, {
progress,
currentDate,
attemptId,
});
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;
}