stock-bot/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts

169 lines
5.8 KiB
TypeScript

import { EventEmitter } from 'node:events';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
import type { StorageService } from '../services/StorageService';
import type { BacktestConfig } from '../types';
import {
BacktestCancelledError,
BacktestTimeoutError,
type BacktestExecutionEngine,
} from './execution-engine';
import { nativeResultSchema, type NativeBacktestResult } from './native-result';
import { resolveNativeStrategies } from './native-strategies';
import type { NativeWorkerRequest } from './native-worker-protocol';
import { NativeBacktestWorker } from './NativeBacktestWorker';
export type BacktestResult = NativeBacktestResult;
/** Storage stays in the parent; all native backtest execution stays in a disposable worker. */
export class RustBacktestAdapter extends EventEmitter implements BacktestExecutionEngine {
private readonly worker: NativeBacktestWorker;
private readonly timeoutMs: number;
private active: { controller: AbortController; finished: Promise<void> } | undefined;
private closing = false;
private progress = 0;
private currentTime = 0;
constructor(
private readonly dependencies: {
logger: Pick<Logger, 'error'>;
storage: Pick<StorageService, 'getHistoricalBars'>;
},
options: { timeoutMs?: number; workerUrl?: URL } = {}
) {
super();
this.timeoutMs = options.timeoutMs ?? 300_000;
if (
!Number.isInteger(this.timeoutMs) ||
this.timeoutMs <= 0 ||
this.timeoutMs > 2_147_483_647
) {
throw new Error('Native backtest timeout must be a positive 32-bit integer');
}
this.worker = new NativeBacktestWorker(options.workerUrl);
}
async runBacktest(
input: BacktestConfig,
dataset?: DatasetResolver
): Promise<NativeBacktestResult> {
if (this.closing || this.active) {
throw new Error(
this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running'
);
}
const config = parseBacktestRequest(input);
const controller = new AbortController();
let finished!: () => void;
this.active = {
controller,
finished: new Promise<void>(resolve => {
finished = resolve;
}),
};
this.progress = 0;
this.currentTime = Date.parse(config.startDate);
const timeout = setTimeout(
() => controller.abort(new BacktestTimeoutError(this.timeoutMs)),
this.timeoutMs
);
const { signal } = controller;
const onAbort = () => rejectAbort(signal.reason);
let rejectAbort!: (reason: unknown) => void;
const aborted = new Promise<never>((_resolve, reject) => {
rejectAbort = reject;
});
signal.addEventListener('abort', onAbort, { once: true });
try {
resolveNativeStrategies(config);
// Race the read too: a slow database must not prevent cancellation. A late read
// cannot spawn a worker after the run has been stopped.
const data = await Promise.race([this.loadData(config, signal, dataset), aborted]);
signal.throwIfAborted();
const raw = await this.worker.execute({ type: 'run', config, data }, signal, progress => {
this.progress = progress.progress;
this.publish('progress', progress);
});
const result = nativeResultSchema.parse(JSON.parse(raw));
this.currentTime = Date.parse(config.endDate);
this.progress = 100;
this.publish('complete', result);
return result;
} catch (error) {
if (!(error instanceof BacktestCancelledError)) {
this.dependencies.logger.error('Native backtest failed', { error });
}
if (this.listenerCount('error') > 0) {
this.publish('error', error);
}
throw error;
} finally {
clearTimeout(timeout);
signal.removeEventListener('abort', onAbort);
this.active = undefined;
finished();
}
}
private async loadData(
config: BacktestConfig,
signal: AbortSignal,
resolver?: DatasetResolver
): Promise<Extract<NativeWorkerRequest, { type: 'run' }>['data']> {
signal.throwIfAborted();
const dataset = await resolveDataset(this.dependencies.storage, config, resolver, signal);
signal.throwIfAborted();
const data: Extract<NativeWorkerRequest, { type: 'run' }>['data'] = [];
for (const bar of dataset.bars) {
data.push({ ...bar, type: 'bar' });
if (data.length % PREPARATION_BATCH_SIZE === 0) {
await preparationCheckpoint(signal);
}
}
signal.throwIfAborted();
return data;
}
private publish(event: string, data: unknown): void {
try {
this.emit(event, data);
} catch (error) {
this.dependencies.logger.error('Native backtest observer failed', { event, error });
}
}
getStatus() {
return {
isRunning: !!this.active,
isPaused: false,
progress: this.progress,
currentTime: this.currentTime,
};
}
async stopBacktest(): Promise<void> {
const active = this.active;
if (!active) {
throw new Error('No native backtest is running');
}
active.controller.abort(new BacktestCancelledError());
// Acknowledgement means the worker has exited, not merely that a signal was sent.
await active.finished;
}
async shutdown(): Promise<void> {
this.closing = true;
if (this.active) {
await this.stopBacktest();
}
}
async pauseBacktest(): Promise<void> {
throw new Error('Native backtests do not support pause');
}
async resumeBacktest(): Promise<void> {
throw new Error('Native backtests do not support resume');
}
setSpeedMultiplier(_speed: number | null): void {
throw new Error('Native backtests run at maximum speed');
}
}