feat(research): run durable backtests in a bounded worker pool
This commit is contained in:
parent
bbf0dd4453
commit
26b97265c6
15 changed files with 1730 additions and 129 deletions
|
|
@ -7,9 +7,11 @@ import { BacktestCancelledError, LEGACY_EXECUTION_RETIRED } from '../../backtest
|
|||
import { BacktestConflictError } from '../../backtest/run-repository';
|
||||
import type { OrchestratorServices as IServiceContainer } from '../../types';
|
||||
|
||||
const _BacktestIdSchema = z.object({
|
||||
backtestId: z.string(),
|
||||
});
|
||||
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();
|
||||
|
|
@ -60,103 +62,60 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
app.post('/', runBacktest);
|
||||
app.post('/run', runBacktest);
|
||||
|
||||
// Stop running backtest
|
||||
app.post('/stop', async c => {
|
||||
try {
|
||||
const { runId } = await c.req.json().catch(() => ({}));
|
||||
await backtestEngine.stopBacktest(runId);
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest stop requested',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error stopping backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to stop backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
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),
|
||||
});
|
||||
|
||||
// Pause running backtest
|
||||
app.post('/pause', async c => {
|
||||
try {
|
||||
const { runId } = await c.req.json().catch(() => ({}));
|
||||
await backtestEngine.pauseBacktest(runId);
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest paused',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error pausing backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to pause backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Resume paused backtest
|
||||
app.post('/resume', async c => {
|
||||
try {
|
||||
const { runId } = await c.req.json().catch(() => ({}));
|
||||
await backtestEngine.resumeBacktest(runId);
|
||||
|
||||
return c.json({
|
||||
message: 'Backtest resumed',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error resuming backtest:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to resume backtest',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Set backtest speed
|
||||
// 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 body = await c.req.json();
|
||||
const { speed, runId } = z
|
||||
.object({
|
||||
speed: z.number().finite().positive().nullable().default(1),
|
||||
runId: z.string().uuid().optional(),
|
||||
runId: runIdSchema.optional(),
|
||||
})
|
||||
.parse(body);
|
||||
|
||||
.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) {
|
||||
container.logger.error('Error setting backtest speed:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to set speed',
|
||||
},
|
||||
500
|
||||
);
|
||||
const failure = controlError(error);
|
||||
return c.json(failure.body, failure.status);
|
||||
}
|
||||
});
|
||||
|
||||
// Get backtest progress
|
||||
app.get('/progress', async c => {
|
||||
app.get('/progress', c => {
|
||||
try {
|
||||
const status = backtestEngine.getStatus();
|
||||
|
||||
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,
|
||||
|
|
@ -166,18 +125,25 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
runId: status.runId,
|
||||
});
|
||||
} catch (error) {
|
||||
container.logger.error('Error getting backtest progress:', error);
|
||||
return c.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : 'Failed to get progress',
|
||||
},
|
||||
500
|
||||
);
|
||||
const failure = controlError(error);
|
||||
return c.json(failure.body, failure.status);
|
||||
}
|
||||
});
|
||||
|
||||
// Stream backtest events (Server-Sent Events)
|
||||
app.get('/stream', async c => {
|
||||
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');
|
||||
|
|
@ -194,25 +160,40 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
|
|||
dispose();
|
||||
controller.close();
|
||||
};
|
||||
const onProgress = (data: unknown) => {
|
||||
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 onComplete = (data: unknown) => {
|
||||
onProgress({ event: 'complete', data });
|
||||
finish();
|
||||
const onProgress = (data: unknown) => {
|
||||
if (matches(data)) {
|
||||
send(data);
|
||||
}
|
||||
};
|
||||
const onError = (error: unknown) => {
|
||||
onProgress({
|
||||
event: 'error',
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
finish();
|
||||
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) => {
|
||||
onProgress({ event: 'cancelled', data });
|
||||
finish();
|
||||
if (matches(data)) {
|
||||
send({ event: 'cancelled', runId, data });
|
||||
finish();
|
||||
}
|
||||
};
|
||||
dispose = () => {
|
||||
closed = true;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue