continuation

This commit is contained in:
Boki 2026-10-20 16:57:59 -04:00
parent 32e43c9243
commit 879e9b4228
42 changed files with 2607 additions and 1306 deletions

View file

@ -0,0 +1,236 @@
import { EventEmitter } from 'node:events';
import { z } from 'zod';
import type { Logger } from '@stock-bot/services';
import type { BacktestRunResult } from '@stock-bot/types';
import { BacktestConfigSchema, type BacktestConfig } from '../types';
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
import { normalizeBacktestResult } from './result';
import {
BacktestConflictError,
type BacktestRunRepository,
type RunIdentity,
} from './run-repository';
export function parseBacktestRequest(input: unknown): BacktestConfig {
const config = BacktestConfigSchema.parse(input);
if (new Date(config.endDate) <= new Date(config.startDate)) {
throw new z.ZodError([
{ code: 'custom', path: ['endDate'], message: 'Backtest endDate must be after startDate' },
]);
}
return config;
}
/** One application workflow for HTTP, jobs, and both execution backends. */
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: RunIdentity | undefined;
private cancelled = false;
private progressWrites: Promise<void> = Promise.resolve();
private closing = false;
private phase: 'preparing' | 'executing' | 'persisting' = 'preparing';
private execution: Promise<BacktestRunResult> | undefined;
constructor(
private readonly dependencies: {
engine: BacktestExecutionEngine;
engineName: Exclude<BacktestRunResult['engine'], 'legacy'>;
repository: BacktestRunRepository;
logger: Pick<Logger, 'error'>;
prepare?: (config: BacktestConfig) => Promise<void>;
}
) {
super();
}
async runBacktest(input: unknown): Promise<BacktestRunResult> {
const config = parseBacktestRequest(input);
if (this.closing) {
throw new BacktestConflictError('Backtest runner is shutting down');
}
if (this.busy) {
throw new BacktestConflictError('A backtest is already running');
}
this.busy = true;
this.cancelled = false;
this.phase = 'preparing';
this.execution = this.execute(config);
return this.execution;
}
private async execute(config: BacktestConfig): Promise<BacktestRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
const onProgress = (data: unknown) => {
const active = this.active;
if (
!active ||
typeof data !== 'object' ||
data === null ||
!('progress' in data) ||
typeof data.progress !== 'number' ||
!Number.isFinite(data.progress)
) {
return;
}
const progress = Math.max(0, Math.min(100, data.progress));
const date =
'currentDate' in data &&
typeof data.currentDate === 'string' &&
Number.isFinite(Date.parse(data.currentDate))
? data.currentDate
: undefined;
this.progressWrites = this.progressWrites
.then(() => this.dependencies.repository.updateProgress(active.runId, progress, date))
.catch(error => {
this.dependencies.logger.error('Could not persist backtest progress', { error });
});
this.publish('progress', { ...data, progress, runId: active.runId });
};
this.dependencies.engine.on('progress', onProgress);
try {
this.active = await this.dependencies.repository.start(config);
const executionConfig = { ...config, ...this.active };
await this.dependencies.prepare?.(executionConfig);
if (this.cancelled) {
throw new BacktestCancelledError();
}
this.phase = 'executing';
const raw = await this.dependencies.engine.runBacktest(executionConfig);
this.phase = 'persisting';
let result: BacktestRunResult;
try {
result = normalizeBacktestResult(
raw,
this.dependencies.engineName,
executionConfig,
this.active,
performance.now() - started,
this.cancelled
);
} catch (error) {
throw new Error('Backtest engine returned an invalid result', { cause: error });
}
await this.progressWrites;
await this.dependencies.repository.complete(result);
// Observers cannot turn a committed success into a failed run.
this.publish('complete', result);
return result;
} catch (error) {
await this.progressWrites;
let failure = error;
if (this.active) {
try {
if (error instanceof BacktestCancelledError) {
await this.dependencies.repository.cancel(this.active.runId);
} else {
await this.dependencies.repository.fail(
this.active.runId,
error instanceof Error ? error.message : String(error)
);
}
} catch (persistenceError) {
this.dependencies.logger.error('Could not record backtest failure', { persistenceError });
// A cancellation acknowledgement must never conceal a failed status write.
if (error instanceof BacktestCancelledError) {
failure = persistenceError;
}
}
}
if (failure instanceof BacktestCancelledError) {
this.publish('cancelled', { ...this.active, status: 'cancelled' });
} else if (this.listenerCount('error')) {
this.publish('error', failure);
}
throw failure;
} finally {
this.dependencies.engine.off('progress', onProgress);
this.active = undefined;
this.busy = false;
}
}
private publish(event: string, value: unknown) {
try {
this.emit(event, value);
} catch (error) {
this.dependencies.logger.error('Backtest observer failed', { event, error });
}
}
private requireActive(runId?: string) {
if (!this.active || (runId && this.active.runId !== runId)) {
throw new BacktestConflictError('No matching active backtest');
}
return this.active;
}
async stopBacktest(runId?: string) {
this.requireActive(runId);
if (this.phase === 'persisting') {
throw new BacktestConflictError('Backtest execution has already finished');
}
const execution = this.execution;
this.cancelled = true;
if (this.phase === 'executing') {
try {
await this.dependencies.engine.stopBacktest();
} catch (error) {
this.cancelled = false;
throw error;
}
}
try {
await execution;
} catch (error) {
if (!(error instanceof BacktestCancelledError)) {
throw error;
}
}
}
async shutdown(): Promise<void> {
this.closing = true;
const execution = this.busy ? this.execution : undefined;
if (this.busy && this.phase !== 'persisting') {
this.cancelled = true;
if (this.phase === 'executing') {
await this.dependencies.engine.stopBacktest();
}
}
// Allow the owner to commit cancellation/failure before database shutdown.
try {
await execution?.catch(error => {
if (!(error instanceof BacktestCancelledError)) {
throw error;
}
});
} finally {
await this.dependencies.engine.shutdown();
}
}
async pauseBacktest(runId?: string) {
const active = this.requireActive(runId);
await this.dependencies.engine.pauseBacktest();
await this.dependencies.repository.updateControl(active.runId, { status: 'paused' });
}
async resumeBacktest(runId?: string) {
const active = this.requireActive(runId);
await this.dependencies.engine.resumeBacktest();
await this.dependencies.repository.updateControl(active.runId, { status: 'running' });
}
async setSpeedMultiplier(speed: number | null, runId?: string) {
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
throw new Error('Backtest speed must be positive or null');
}
const active = this.requireActive(runId);
this.dependencies.engine.setSpeedMultiplier(speed);
await this.dependencies.repository.updateControl(active.runId, { speedMultiplier: speed });
}
getStatus() {
return {
...this.dependencies.engine.getStatus(),
isRunning: this.busy,
runId: this.active?.runId,
};
}
}