import { EventEmitter } from 'node:events'; import type { Logger } from '@stock-bot/services'; import { canonicalRunRequestSchema, type CanonicalRunRequest, type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; import type { HistoricalDatasetV2 } from '@stock-bot/types'; import type { DatasetResolver } from '../data/historical-dataset'; import type { BacktestConfig } from '../types'; import { BacktestCancelledError, BacktestTimeoutError, LEGACY_EXECUTION_RETIRED, type BacktestExecutionEngine, } from './execution-engine'; import type { NativeBacktestResult } from './native-result'; 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 } | undefined; private closing = false; private progress = 0; private currentTime = 0; constructor( private readonly dependencies: { logger: Pick; }, 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 { throw new Error(LEGACY_EXECUTION_RETIRED); } async runCanonical( input: CanonicalRunRequest, resolveDataset: (signal: AbortSignal) => Promise, controls: { executionDeadlineAt?: number } = {} ): Promise> { const request = canonicalRunRequestSchema.parse(input); return this.runOwned( request.policy.matching.risk.ledger.riskSession.startsAt, async (signal, aborted) => { const dataset = await Promise.race([resolveDataset(signal), aborted]); signal.throwIfAborted(); const result = await this.worker.executeRetained( { type: 'runRetainedStrategy', request, dataset, ...(controls.executionDeadlineAt === undefined ? {} : { executionDeadlineAt: controls.executionDeadlineAt }), }, signal, progress => { this.progress = progress.progress; this.publish('progress', progress); } ); this.currentTime = dataset.manifest.bounds.tradeEnd; return { financial: result.financial, analytics: result.analytics }; } ); } /** One ownership/deadline/cancellation lifecycle for canonical work. */ private async runOwned( initialTime: number, work: (signal: AbortSignal, aborted: Promise) => Promise ): Promise { if (this.closing || this.active) { throw new Error( this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running' ); } const controller = new AbortController(); let finished!: () => void; this.active = { controller, finished: new Promise(resolve => { finished = resolve; }), }; this.progress = 0; this.currentTime = initialTime; 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((_resolve, reject) => { rejectAbort = reject; }); signal.addEventListener('abort', onAbort, { once: true }); try { const result = await work(signal, aborted); 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 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 { 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 { this.closing = true; if (this.active) { await this.stopBacktest(); } } async pauseBacktest(): Promise { throw new Error('Native backtests do not support pause'); } async resumeBacktest(): Promise { throw new Error('Native backtests do not support resume'); } setSpeedMultiplier(_speed: number | null): void { throw new Error('Native backtests run at maximum speed'); } }