227 lines
7.5 KiB
TypeScript
227 lines
7.5 KiB
TypeScript
import { Hono, type Handler } from 'hono';
|
|
import { z } from 'zod';
|
|
import { defined } from '@stock-bot/invariants';
|
|
import { HistoricalDataRequestError } from '@stock-bot/types';
|
|
import { parseBacktestRequest } from '../../backtest/BacktestRunner';
|
|
import { BacktestCancelledError, LEGACY_EXECUTION_RETIRED } from '../../backtest/execution-engine';
|
|
import { BacktestConflictError } from '../../backtest/run-repository';
|
|
import type { OrchestratorServices as IServiceContainer } from '../../types';
|
|
|
|
const runIdSchema = z
|
|
.string()
|
|
.uuid()
|
|
.transform(value => value.toLowerCase());
|
|
const controlSchema = z.object({ runId: runIdSchema.optional() }).strict();
|
|
|
|
export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|
const app = new Hono();
|
|
const backtestEngine = defined(
|
|
container.custom?.BacktestRunner,
|
|
'Backtest runner is unavailable'
|
|
);
|
|
|
|
// Default POST to / is the same as /run for backward compatibility
|
|
const runBacktest: Handler = async c => {
|
|
try {
|
|
const body = await c.req.json();
|
|
const config = parseBacktestRequest(body);
|
|
|
|
// Run backtest
|
|
const result = await backtestEngine.runBacktest(config);
|
|
|
|
return c.json(result, 201);
|
|
} catch (error) {
|
|
if (error instanceof BacktestCancelledError) {
|
|
return c.json({ status: 'cancelled', error: error.message }, 409);
|
|
}
|
|
if (error instanceof BacktestConflictError) {
|
|
return c.json({ error: error.message }, 409);
|
|
}
|
|
if (error instanceof z.ZodError) {
|
|
return c.json(
|
|
{
|
|
error: 'Invalid backtest configuration',
|
|
details: error.errors,
|
|
},
|
|
400
|
|
);
|
|
}
|
|
if (error instanceof HistoricalDataRequestError) {
|
|
return c.json({ error: error.message }, 400);
|
|
}
|
|
|
|
container.logger.error('Error running backtest:', error);
|
|
return c.json(
|
|
{
|
|
error: error instanceof Error ? error.message : 'Failed to run backtest',
|
|
},
|
|
500
|
|
);
|
|
}
|
|
};
|
|
app.post('/', runBacktest);
|
|
app.post('/run', runBacktest);
|
|
|
|
const controlError = (error: unknown) => ({
|
|
body: { error: error instanceof Error ? error.message : 'Backtest control failed' },
|
|
status:
|
|
error instanceof BacktestConflictError
|
|
? (409 as const)
|
|
: error instanceof z.ZodError || error instanceof SyntaxError
|
|
? (400 as const)
|
|
: (500 as const),
|
|
});
|
|
// Empty legacy bodies still target the sole active run. Invalid JSON never becomes an untargeted control.
|
|
for (const [path, operation, message] of [
|
|
['/stop', 'stopBacktest', 'Backtest stop requested'],
|
|
['/pause', 'pauseBacktest', 'Backtest paused'],
|
|
['/resume', 'resumeBacktest', 'Backtest resumed'],
|
|
] as const) {
|
|
app.post(path, async c => {
|
|
try {
|
|
const text = await c.req.text();
|
|
const { runId } = controlSchema.parse(text.trim() ? JSON.parse(text) : {});
|
|
await backtestEngine[operation](runId);
|
|
return c.json({ message, timestamp: new Date().toISOString() });
|
|
} catch (error) {
|
|
const failure = controlError(error);
|
|
return c.json(failure.body, failure.status);
|
|
}
|
|
});
|
|
}
|
|
app.post('/speed', async c => {
|
|
try {
|
|
const { speed, runId } = z
|
|
.object({
|
|
speed: z.number().finite().positive().nullable().default(1),
|
|
runId: runIdSchema.optional(),
|
|
})
|
|
.strict()
|
|
.parse(await c.req.json());
|
|
await backtestEngine.setSpeedMultiplier(speed, runId);
|
|
return c.json({
|
|
message: 'Backtest speed updated',
|
|
speed: speed === null ? 'unlimited' : speed,
|
|
timestamp: new Date().toISOString(),
|
|
});
|
|
} catch (error) {
|
|
const failure = controlError(error);
|
|
return c.json(failure.body, failure.status);
|
|
}
|
|
});
|
|
app.get('/progress', c => {
|
|
try {
|
|
const runId = runIdSchema.optional().parse(c.req.query('runId'));
|
|
const status = backtestEngine.getStatus(runId);
|
|
if (runId !== undefined && status.runId !== runId) {
|
|
throw new BacktestConflictError('No matching active backtest');
|
|
}
|
|
return c.json({
|
|
status: status.isPaused ? 'paused' : status.isRunning ? 'running' : 'idle',
|
|
progress: status.progress,
|
|
currentTime: new Date(status.currentTime).toISOString(),
|
|
isRunning: status.isRunning,
|
|
isPaused: status.isPaused,
|
|
runId: status.runId,
|
|
});
|
|
} catch (error) {
|
|
const failure = controlError(error);
|
|
return c.json(failure.body, failure.status);
|
|
}
|
|
});
|
|
|
|
// Stream backtest events (Server-Sent Events)
|
|
app.get('/stream', c => {
|
|
let runId: string;
|
|
try {
|
|
const requested = runIdSchema.optional().parse(c.req.query('runId'));
|
|
const target = requested ?? backtestEngine.getStatus().runId;
|
|
if (!target) {
|
|
throw new BacktestConflictError('An exact runId is required when no backtest is active');
|
|
}
|
|
runId = target;
|
|
} catch (error) {
|
|
const failure = controlError(error);
|
|
return c.json(failure.body, failure.status);
|
|
}
|
|
c.header('Content-Type', 'text/event-stream');
|
|
c.header('Cache-Control', 'no-cache');
|
|
c.header('Connection', 'keep-alive');
|
|
|
|
let dispose = () => {};
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
start(controller) {
|
|
const encoder = new TextEncoder();
|
|
let closed = false;
|
|
const finish = () => {
|
|
if (closed) {
|
|
return;
|
|
}
|
|
dispose();
|
|
controller.close();
|
|
};
|
|
const matches = (data: unknown) =>
|
|
data !== null && typeof data === 'object' && 'runId' in data && data.runId === runId;
|
|
const send = (data: unknown) => {
|
|
if (!closed) {
|
|
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
|
|
}
|
|
};
|
|
const onProgress = (data: unknown) => {
|
|
if (matches(data)) {
|
|
send(data);
|
|
}
|
|
};
|
|
const onComplete = (data: unknown) => {
|
|
if (matches(data)) {
|
|
send({ event: 'complete', runId, data });
|
|
finish();
|
|
}
|
|
};
|
|
const onError = (data: unknown) => {
|
|
if (matches(data)) {
|
|
const error = (data as { error: unknown }).error;
|
|
send({
|
|
event: 'error',
|
|
runId,
|
|
error: error instanceof Error ? error.message : String(error),
|
|
});
|
|
finish();
|
|
}
|
|
};
|
|
const onCancelled = (data: unknown) => {
|
|
if (matches(data)) {
|
|
send({ event: 'cancelled', runId, data });
|
|
finish();
|
|
}
|
|
};
|
|
dispose = () => {
|
|
closed = true;
|
|
backtestEngine.off('progress', onProgress);
|
|
backtestEngine.off('complete', onComplete);
|
|
backtestEngine.off('error', onError);
|
|
backtestEngine.off('cancelled', onCancelled);
|
|
c.req.raw.signal.removeEventListener('abort', finish);
|
|
};
|
|
backtestEngine.on('progress', onProgress);
|
|
backtestEngine.on('complete', onComplete);
|
|
backtestEngine.on('error', onError);
|
|
backtestEngine.on('cancelled', onCancelled);
|
|
c.req.raw.signal.addEventListener('abort', finish, { once: true });
|
|
if (c.req.raw.signal.aborted) {
|
|
finish();
|
|
}
|
|
},
|
|
cancel() {
|
|
dispose();
|
|
},
|
|
});
|
|
|
|
return new Response(stream);
|
|
});
|
|
|
|
// The old route cannot approve unversioned strategies or mutable provider inputs.
|
|
app.post('/validate', c => c.json({ valid: false, error: LEGACY_EXECUTION_RETIRED }, 409));
|
|
|
|
return app;
|
|
}
|