stock-bot/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts
2026-10-20 16:57:59 -04:00

121 lines
4.1 KiB
TypeScript

import { fork, type ChildProcess } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { nativeWorkerMessageSchema, type NativeWorkerRequest } from './native-worker-protocol';
import { BacktestConflictError } from './run-repository';
/** Hard cancellation requires a process boundary: a thread cannot interrupt native Rust. */
export class NativeBacktestWorker {
private active: ChildProcess | undefined;
constructor(
private readonly workerUrl = new URL(
import.meta.url.endsWith('.ts') ? './native-worker.ts' : './native-worker.js',
import.meta.url
)
) {}
async execute(
request: NativeWorkerRequest,
signal: AbortSignal,
onProgress: (progress: { progress: number; message: string }) => void
): Promise<string> {
signal.throwIfAborted();
if (this.active) {
throw new BacktestConflictError('A native backtest worker is already running');
}
const child = fork(fileURLToPath(this.workerUrl), [], {
execPath: process.execPath,
execArgv: [],
serialization: 'json',
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
});
this.active = child;
return new Promise<string>((resolve, reject) => {
let result: string | undefined;
let failure: Error | undefined;
let stderr = '';
let settled = false;
const terminate = (error: Error) => {
failure ??= error;
// SIGKILL also interrupts an uncooperative synchronous native call.
child.kill('SIGKILL');
};
const onAbort = () =>
terminate(
signal.reason instanceof Error ? signal.reason : new Error('Native execution aborted')
);
const onStderr = (chunk: Buffer) => {
// Drain native diagnostics without unbounded buffering or blocking on a full pipe.
stderr = (stderr + chunk.toString()).slice(-4096);
};
const onMessage = (input: unknown) => {
if (failure) {
return;
}
const parsed = nativeWorkerMessageSchema.safeParse(input);
if (!parsed.success || result !== undefined) {
terminate(new Error('Invalid native backtest worker response'));
return;
}
const message = parsed.data;
if (message.type === 'error') {
terminate(new Error(message.message));
} else if (message.type === 'result') {
result = message.result;
} else {
try {
onProgress({ progress: message.progress, message: message.message });
} catch (error) {
terminate(error instanceof Error ? error : new Error(String(error)));
}
}
};
const finish = (code: number | null, exitSignal: NodeJS.Signals | null) => {
if (settled) {
return;
}
settled = true;
signal.removeEventListener('abort', onAbort);
child.off('message', onMessage);
child.stderr?.off('data', onStderr);
this.active = undefined;
if (failure) {
reject(failure);
} else if (code !== 0 || result === undefined) {
reject(
new Error(
`Native backtest worker exited without a result (code ${code}, signal ${exitSignal})${stderr ? `: ${stderr}` : ''}`
)
);
} else {
resolve(result);
}
};
child.on('message', onMessage);
child.stderr?.on('data', onStderr);
child.once('error', error => {
terminate(error);
// Spawn failures have no process to reap; normal errors wait for exit.
if (child.pid === undefined) {
finish(null, null);
}
});
// Wait for IPC/stdio to drain too; exit alone can precede the last message.
child.once('close', finish);
signal.addEventListener('abort', onAbort, { once: true });
if (signal.aborted) {
onAbort();
return;
}
try {
child.send(request, error => {
if (error) {
terminate(error);
}
});
} catch (error) {
terminate(error instanceof Error ? error : new Error(String(error)));
}
});
}
}