288 lines
11 KiB
TypeScript
288 lines
11 KiB
TypeScript
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
import { OrderRequestSchema, type OrderRequest } from '../types';
|
|
import { accountMetrics, identity, type Account, type ExecutionChange } from './model';
|
|
import { ExecutionConflictError, type ExecutionTransaction } from './repository';
|
|
import {
|
|
canonicalJson,
|
|
strategyConfigHash,
|
|
type RecoverableStrategy,
|
|
type StrategyCheckpoint,
|
|
type StrategyOrderIntent,
|
|
} from './strategy-recovery';
|
|
|
|
/** Explicit ports keep recovery independent of the service container and storage adapters. */
|
|
export interface StrategyRecoveryRuntime {
|
|
accountId(): string;
|
|
isBacktest(): boolean;
|
|
serialized<T>(work: () => Promise<T>): Promise<T>;
|
|
transact<T>(work: (tx: ExecutionTransaction) => Promise<T>): Promise<T>;
|
|
dispatch(tx: ExecutionTransaction, intent: StrategyOrderIntent): Promise<ExecutionChange>;
|
|
publish(change: ExecutionChange): Promise<void>;
|
|
consumeMarketInput(): Promise<boolean>;
|
|
observationFailed(error: unknown): void;
|
|
}
|
|
|
|
/** Owns checkpoints, decision scopes and outbox replay; never opens a nested transaction. */
|
|
export class StrategyRecovery {
|
|
private readonly decision = new AsyncLocalStorage<{
|
|
account: Account;
|
|
strategyId: string;
|
|
intents: StrategyOrderIntent[];
|
|
sequence: number;
|
|
open: boolean;
|
|
observations: (() => void)[];
|
|
}>();
|
|
constructor(private readonly runtime: StrategyRecoveryRuntime) {}
|
|
|
|
assertExternalIO(): void {
|
|
if (this.decision.getStore()) {
|
|
throw new Error(
|
|
'Strategy callbacks cannot perform repository I/O; use the decision account view and order intents'
|
|
);
|
|
}
|
|
}
|
|
|
|
decisionAccount() {
|
|
const context = this.decision.getStore();
|
|
if (!context) {
|
|
return undefined;
|
|
}
|
|
if (!context.open) {
|
|
throw new Error('Strategy evaluation has finished');
|
|
}
|
|
return { ...structuredClone(context.account), ...accountMetrics(context.account) };
|
|
}
|
|
|
|
captureStrategyOrder(request: OrderRequest, strategyId: string): void {
|
|
const context = this.decision.getStore();
|
|
if (!context?.open || context.strategyId !== strategyId) {
|
|
throw new Error('Strategy orders require an active checkpoint transaction');
|
|
}
|
|
const order = OrderRequestSchema.parse(request);
|
|
if (!order.clientOrderId) {
|
|
throw new Error('Strategy intent requires a stable client order ID');
|
|
}
|
|
if (context.intents.some(intent => intent.clientOrderId === order.clientOrderId)) {
|
|
throw new ExecutionConflictError('Duplicate intent in one decision');
|
|
}
|
|
context.intents.push({
|
|
strategyId,
|
|
clientOrderId: order.clientOrderId,
|
|
sequence: context.sequence,
|
|
request: order,
|
|
status: 'pending',
|
|
});
|
|
}
|
|
afterStrategyCommit(observation: () => void): void {
|
|
const context = this.decision.getStore();
|
|
if (!context?.open) {
|
|
throw new Error('No active strategy decision');
|
|
}
|
|
context.observations.push(observation);
|
|
}
|
|
async getRecoveryStatus() {
|
|
return this.runtime.transact(async tx => ({
|
|
accountId: this.runtime.accountId(),
|
|
pendingInputs: !!(await tx.nextInput()),
|
|
pendingIntents: !!(await tx.nextIntent()),
|
|
strategies: (await tx.strategies()).map(s => ({
|
|
strategyId: s.strategyId,
|
|
enabled: s.enabled,
|
|
version: s.version,
|
|
cursor: s.cursor,
|
|
journalTail: tx.account.strategySequence ?? 0,
|
|
lag: (tx.account.strategySequence ?? 0) - s.cursor,
|
|
})),
|
|
}));
|
|
}
|
|
|
|
async registerStrategy(strategy: RecoverableStrategy): Promise<void> {
|
|
const config = structuredClone(strategy.getConfig());
|
|
const version =
|
|
strategy.getCheckpointVersion() ??
|
|
(this.runtime.isBacktest() ? 'run-local-unversioned' : undefined);
|
|
if (!version) {
|
|
throw new Error('Paper strategies require a versioned checkpoint contract');
|
|
}
|
|
const hash = strategyConfigHash(config, version);
|
|
const initialState = JSON.parse(canonicalJson(strategy.captureCheckpoint()));
|
|
strategy.restoreCheckpoint(initialState);
|
|
const saved = await this.runtime.serialized(() =>
|
|
this.runtime.transact(async tx => {
|
|
const existing = (await tx.strategies()).find(s => s.strategyId === config.id);
|
|
if (existing && (existing.version !== version || existing.configHash !== hash)) {
|
|
throw new ExecutionConflictError(
|
|
'Strategy configuration/checkpoint version changed; use an explicit new strategy ID'
|
|
);
|
|
}
|
|
const checkpoint: StrategyCheckpoint = existing ?? {
|
|
strategyId: config.id,
|
|
config,
|
|
configHash: hash,
|
|
version,
|
|
enabled: true,
|
|
cursor: tx.account.strategySequence ?? 0,
|
|
state: initialState,
|
|
};
|
|
strategy.restoreCheckpoint(checkpoint.state);
|
|
await tx.putStrategy({ ...checkpoint, enabled: true });
|
|
return checkpoint;
|
|
})
|
|
);
|
|
strategy.restoreCheckpoint(saved.state);
|
|
}
|
|
|
|
async registeredStrategies() {
|
|
return this.runtime.transact(async tx =>
|
|
(await tx.strategies()).map(s => ({ ...s.config, enabled: s.enabled }))
|
|
);
|
|
}
|
|
async pauseStrategy(strategyId: string) {
|
|
await this.runtime.serialized(() =>
|
|
this.runtime.transact(async tx => {
|
|
const checkpoint = (await tx.strategies()).find(s => s.strategyId === strategyId);
|
|
if (checkpoint) {
|
|
await tx.putStrategy({ ...checkpoint, enabled: false });
|
|
}
|
|
})
|
|
);
|
|
}
|
|
|
|
/** Account row locks serialize owners. Restore before EVERY step, not just startup. */
|
|
async recoverStrategies(strategies: RecoverableStrategy[]): Promise<void> {
|
|
await this.runtime.serialized(async () => {
|
|
const byId = new Map(strategies.map(strategy => [strategy.getConfig().id, strategy]));
|
|
const enabled = await this.runtime.transact(async tx =>
|
|
(await tx.strategies()).filter(s => s.enabled)
|
|
);
|
|
for (const checkpoint of enabled) {
|
|
const strategy = byId.get(checkpoint.strategyId);
|
|
if (!strategy) {
|
|
throw new ExecutionConflictError(
|
|
'An enabled strategy must be restored before processing its account'
|
|
);
|
|
}
|
|
const version = strategy.getCheckpointVersion() ?? 'run-local-unversioned';
|
|
if (
|
|
checkpoint.version !== version ||
|
|
checkpoint.configHash !== strategyConfigHash(strategy.getConfig(), version)
|
|
) {
|
|
throw new ExecutionConflictError('Strategy checkpoint definition mismatch');
|
|
}
|
|
}
|
|
while (true) {
|
|
const dispatched = await this.runtime.transact(async tx => {
|
|
const intent = await tx.nextIntent();
|
|
if (!intent) {
|
|
return undefined;
|
|
}
|
|
const change = await this.runtime.dispatch(tx, intent);
|
|
await tx.putIntent({ ...intent, status: 'dispatched', orderId: change.report.orderId });
|
|
return change;
|
|
});
|
|
if (dispatched) {
|
|
await this.runtime.publish(dispatched);
|
|
continue;
|
|
}
|
|
let progressed = false;
|
|
const registrations = await this.runtime.transact(tx => tx.strategies());
|
|
for (const registration of registrations.filter(s => s.enabled)) {
|
|
const strategy = byId.get(registration.strategyId);
|
|
if (!strategy) {
|
|
throw new ExecutionConflictError(
|
|
'An enabled strategy must be restored before processing its account'
|
|
);
|
|
}
|
|
let before = strategy.captureCheckpoint();
|
|
let observations: (() => void)[] = [];
|
|
try {
|
|
const advanced = await this.runtime.transact(async tx => {
|
|
const checkpoint = (await tx.strategies()).find(
|
|
s => s.strategyId === registration.strategyId
|
|
);
|
|
if (!checkpoint?.enabled) {
|
|
return false;
|
|
}
|
|
const version = strategy.getCheckpointVersion() ?? 'run-local-unversioned';
|
|
if (
|
|
strategyConfigHash(strategy.getConfig(), version) !== checkpoint.configHash ||
|
|
checkpoint.version !== version
|
|
) {
|
|
throw new ExecutionConflictError('Strategy checkpoint definition mismatch');
|
|
}
|
|
strategy.restoreCheckpoint(checkpoint.state);
|
|
before = checkpoint.state;
|
|
const event = await tx.nextJournal(checkpoint.cursor);
|
|
if (!event) {
|
|
return false;
|
|
}
|
|
const context = {
|
|
account: event.payload.account,
|
|
strategyId: checkpoint.strategyId,
|
|
intents: [] as StrategyOrderIntent[],
|
|
sequence: event.sequence,
|
|
open: true,
|
|
observations: [] as (() => void)[],
|
|
};
|
|
try {
|
|
await this.decision.run(context, async () => {
|
|
const payload = event.payload;
|
|
if (
|
|
payload.kind === 'market' &&
|
|
payload.recipients.includes(checkpoint.strategyId) &&
|
|
strategy.getConfig().symbols.includes(payload.market.data.symbol)
|
|
) {
|
|
await strategy.onMarketData({
|
|
...payload.market,
|
|
eventId: identity(payload.market),
|
|
});
|
|
} else if (
|
|
payload.kind === 'execution' &&
|
|
payload.report.strategyId === checkpoint.strategyId
|
|
) {
|
|
for (const fill of payload.fills) {
|
|
await strategy.onFill({
|
|
...fill,
|
|
orderId: payload.report.orderId,
|
|
symbol: payload.report.symbol,
|
|
side: payload.report.side,
|
|
strategyId: checkpoint.strategyId,
|
|
});
|
|
}
|
|
await strategy.onOrderUpdate(payload.report);
|
|
}
|
|
});
|
|
} finally {
|
|
context.open = false;
|
|
}
|
|
const state = JSON.parse(canonicalJson(strategy.captureCheckpoint()));
|
|
await tx.putStrategy({ ...checkpoint, cursor: event.sequence, state });
|
|
for (const intent of context.intents) {
|
|
await tx.putIntent(intent);
|
|
}
|
|
observations = context.observations;
|
|
return true;
|
|
});
|
|
progressed ||= advanced;
|
|
for (const observe of observations) {
|
|
try {
|
|
observe();
|
|
} catch (error) {
|
|
this.runtime.observationFailed(error);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
strategy.restoreCheckpoint(before);
|
|
throw error;
|
|
}
|
|
}
|
|
if (progressed) {
|
|
continue;
|
|
}
|
|
if (!(await this.runtime.consumeMarketInput())) {
|
|
break;
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|