more stuff
This commit is contained in:
parent
c3cb36c8d6
commit
7dec0be3b4
26 changed files with 1394 additions and 275 deletions
105
apps/stock/web-api/src/services/BacktestDispatcher.ts
Normal file
105
apps/stock/web-api/src/services/BacktestDispatcher.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
import type { Logger, PostgresClient, Queue } from '@stock-bot/services';
|
||||
|
||||
/** PostgreSQL is the source of truth; Redis jobs are repeatable delivery notifications. */
|
||||
export class BacktestDispatcher {
|
||||
private timer?: ReturnType<typeof setInterval>;
|
||||
private inFlight?: Promise<void>;
|
||||
private closing = false;
|
||||
|
||||
constructor(
|
||||
private readonly postgres: Pick<PostgresClient, 'transaction'>,
|
||||
private readonly queue: Pick<Queue, 'add'>,
|
||||
private readonly logger: Pick<Logger, 'error'>,
|
||||
private readonly options = { intervalMs: 5_000, republishMs: 30_000, maxAttempts: 3 }
|
||||
) {}
|
||||
|
||||
start() {
|
||||
this.timer ??= setInterval(
|
||||
() =>
|
||||
void this.tick().catch(error => {
|
||||
this.logger.error('Backtest dispatch/recovery failed; will retry', { error });
|
||||
}),
|
||||
this.options.intervalMs
|
||||
);
|
||||
this.timer.unref();
|
||||
void this.tick().catch(error =>
|
||||
this.logger.error('Initial backtest dispatch failed; will retry', { error })
|
||||
);
|
||||
}
|
||||
|
||||
tick(): Promise<void> {
|
||||
if (this.closing) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return (this.inFlight ??= this.dispatch().finally(() => {
|
||||
this.inFlight = undefined;
|
||||
}));
|
||||
}
|
||||
|
||||
async shutdown() {
|
||||
this.closing = true;
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer);
|
||||
}
|
||||
await this.inFlight;
|
||||
}
|
||||
|
||||
private async dispatch() {
|
||||
// Recovery is independent of Redis availability. Every terminal write fences the old owner.
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
`UPDATE runs SET
|
||||
status = CASE WHEN cancel_requested THEN 'cancelled'::run_status
|
||||
WHEN attempt_number >= $1 THEN 'failed'::run_status ELSE 'pending'::run_status END,
|
||||
error = CASE WHEN cancel_requested THEN NULL
|
||||
WHEN attempt_number >= $1 THEN 'Execution lease expired; retry limit reached' ELSE NULL END,
|
||||
completed_at = CASE WHEN cancel_requested OR attempt_number >= $1 THEN NOW() ELSE NULL END,
|
||||
attempt_id = NULL, lease_expires_at = NULL, updated_at = NOW()
|
||||
WHERE status IN ('running', 'paused') AND lease_expires_at <= clock_timestamp()`,
|
||||
[this.options.maxAttempts]
|
||||
);
|
||||
});
|
||||
|
||||
// Reserve a small batch in SQL, then publish outside the transaction. A crash between these
|
||||
// steps only delays redelivery; it cannot lose the intent or hold DB locks during a Redis outage.
|
||||
const rows = await this.postgres.transaction(async client => {
|
||||
const due = await client.query<{ run_id: string }>(`SELECT d.run_id
|
||||
FROM backtest_dispatch d JOIN runs r ON r.id = d.run_id
|
||||
WHERE r.status = 'pending' AND NOT r.cancel_requested AND d.next_publish_at <= NOW()
|
||||
ORDER BY d.next_publish_at LIMIT 20 FOR UPDATE OF d SKIP LOCKED`);
|
||||
for (const row of due.rows) {
|
||||
await client.query(
|
||||
`UPDATE backtest_dispatch
|
||||
SET next_publish_at = NOW() + $2::interval
|
||||
WHERE run_id = $1`,
|
||||
[row.run_id, `${this.options.republishMs} milliseconds`]
|
||||
);
|
||||
}
|
||||
return due.rows;
|
||||
});
|
||||
for (const row of rows) {
|
||||
await this.queue.add(
|
||||
'run-backtest',
|
||||
{
|
||||
handler: 'orchestrator',
|
||||
operation: 'run-backtest',
|
||||
payload: { runId: row.run_id },
|
||||
},
|
||||
{
|
||||
jobId: `backtest-${row.run_id}`,
|
||||
attempts: 3,
|
||||
backoff: { type: 'fixed', delay: 1_000 },
|
||||
removeOnComplete: true,
|
||||
removeOnFail: true,
|
||||
}
|
||||
);
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
`UPDATE backtest_dispatch
|
||||
SET last_published_at = NOW(), publish_count = publish_count + 1 WHERE run_id = $1`,
|
||||
[row.run_id]
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -49,6 +49,8 @@ export interface Run {
|
|||
completedAt?: Date;
|
||||
pausedAt?: Date;
|
||||
progress: number;
|
||||
cancelRequested: boolean;
|
||||
attemptNumber: number;
|
||||
currentDate?: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
|
|
@ -200,29 +202,69 @@ export class BacktestServiceV2 {
|
|||
async createRun(request: RunRequest): Promise<Run> {
|
||||
const runId = uuidv4();
|
||||
const row = await this.container.postgres.transaction(async client => {
|
||||
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
const parent = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
request.backtestId,
|
||||
]);
|
||||
if (!parent.rows.length) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
const definition = this.mapBacktest(at(parent.rows, 0));
|
||||
const multiplier = request.speedMultiplier ?? null;
|
||||
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
||||
throw new Error('Speed multiplier must be positive or null');
|
||||
}
|
||||
const snapshot = {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
name: definition.name,
|
||||
mode: 'backtest',
|
||||
strategy: definition.strategy,
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate.toISOString(),
|
||||
endDate: definition.endDate.toISOString(),
|
||||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
dataFrequency: definition.config.dataFrequency ?? '1d',
|
||||
commission: definition.config.commission ?? 0.001,
|
||||
slippage: definition.config.slippage ?? 0.0001,
|
||||
speed:
|
||||
multiplier === null
|
||||
? 'max'
|
||||
: multiplier >= 10
|
||||
? '10x'
|
||||
: multiplier >= 5
|
||||
? '5x'
|
||||
: multiplier >= 2
|
||||
? '2x'
|
||||
: 'realtime',
|
||||
};
|
||||
if (
|
||||
!snapshot.strategy ||
|
||||
!Array.isArray(snapshot.symbols) ||
|
||||
!snapshot.symbols.length ||
|
||||
snapshot.symbols.some(symbol => typeof symbol !== 'string' || !symbol.length) ||
|
||||
!Number.isFinite(snapshot.initialCapital) ||
|
||||
snapshot.initialCapital <= 0 ||
|
||||
Date.parse(snapshot.endDate) <= Date.parse(snapshot.startDate) ||
|
||||
!['1m', '5m', '15m', '1h', '1d'].includes(String(snapshot.dataFrequency)) ||
|
||||
typeof snapshot.commission !== 'number' ||
|
||||
!Number.isFinite(snapshot.commission) ||
|
||||
typeof snapshot.slippage !== 'number' ||
|
||||
!Number.isFinite(snapshot.slippage)
|
||||
) {
|
||||
throw new Error('Invalid backtest execution configuration');
|
||||
}
|
||||
const result = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb
|
||||
FROM runs WHERE backtest_id = $2 RETURNING *`,
|
||||
[
|
||||
runId,
|
||||
request.backtestId,
|
||||
request.speedMultiplier === undefined ? null : request.speedMultiplier,
|
||||
]
|
||||
[runId, request.backtestId, multiplier, JSON.stringify(snapshot)]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
return at(result.rows, 0);
|
||||
});
|
||||
const run = this.mapRun(row);
|
||||
// startRun handles dispatch failures; the runner owns execution and terminal persistence.
|
||||
void this.startRun(run);
|
||||
return run;
|
||||
return this.mapRun(row);
|
||||
}
|
||||
|
||||
async getRun(id: string): Promise<Run | null> {
|
||||
|
|
@ -248,14 +290,17 @@ export class BacktestServiceV2 {
|
|||
|
||||
async updateRunProgress(
|
||||
id: string,
|
||||
updates: { progress?: number; currentDate?: Date }
|
||||
updates: { progress?: number; currentDate?: Date; attemptId: string }
|
||||
): Promise<void> {
|
||||
const result = await this.container.postgres.query(
|
||||
`UPDATE runs
|
||||
SET progress = COALESCE($2, progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') RETURNING status`,
|
||||
[id, updates.progress ?? null, updates.currentDate ?? null]
|
||||
);
|
||||
const result = await this.container.postgres.transaction(async client => {
|
||||
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [id]);
|
||||
return client.query(
|
||||
`UPDATE runs
|
||||
SET progress = GREATEST(COALESCE($2::numeric, progress), progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') AND attempt_id = $4 AND lease_expires_at > clock_timestamp() RETURNING status`,
|
||||
[id, updates.progress ?? null, updates.currentDate ?? null, updates.attemptId]
|
||||
);
|
||||
});
|
||||
const row = result.rows[0];
|
||||
if (row) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
|
||||
|
|
@ -273,7 +318,21 @@ export class BacktestServiceV2 {
|
|||
await this.sendControl(id, 'resume');
|
||||
}
|
||||
async cancelRun(id: string): Promise<void> {
|
||||
await this.sendControl(id, 'stop');
|
||||
const result = await this.container.postgres.query(
|
||||
`UPDATE runs SET cancel_requested = TRUE,
|
||||
status = CASE WHEN status = 'pending' THEN 'cancelled'::run_status ELSE status END,
|
||||
completed_at = CASE WHEN status = 'pending' THEN NOW() ELSE completed_at END, updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('pending', 'running', 'paused', 'cancelled') RETURNING status`,
|
||||
[id]
|
||||
);
|
||||
const row = result.rows[0];
|
||||
if (!row) {
|
||||
throw new Error('No cancellable run found');
|
||||
}
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
|
||||
type: 'run_update',
|
||||
data: { status: row.status, cancelRequested: true, timestamp: new Date().toISOString() },
|
||||
});
|
||||
}
|
||||
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
|
||||
await this.sendControl(id, 'speed', { speed: speedMultiplier });
|
||||
|
|
@ -394,94 +453,6 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
// Private methods
|
||||
private async startRun(run: Run): Promise<void> {
|
||||
try {
|
||||
const backtest = await this.getBacktest(run.backtestId);
|
||||
if (!backtest) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
this.getWebSocketHandler()?.sendProgressUpdate(run.id, 0);
|
||||
const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
runId: run.id,
|
||||
backtestId: backtest.id,
|
||||
name: backtest.name,
|
||||
mode: 'backtest',
|
||||
startDate: backtest.startDate.toISOString(),
|
||||
endDate: backtest.endDate.toISOString(),
|
||||
symbols: backtest.symbols,
|
||||
strategy: backtest.strategy,
|
||||
initialCapital: backtest.initialCapital,
|
||||
config: backtest.config,
|
||||
dataFrequency: backtest.config.dataFrequency ?? '1d',
|
||||
commission: backtest.config.commission ?? 0.001,
|
||||
slippage: backtest.config.slippage ?? 0.0001,
|
||||
speed:
|
||||
run.speedMultiplier === null
|
||||
? 'max'
|
||||
: run.speedMultiplier >= 10
|
||||
? '10x'
|
||||
: run.speedMultiplier >= 5
|
||||
? '5x'
|
||||
: run.speedMultiplier >= 2
|
||||
? '2x'
|
||||
: 'realtime',
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
if (response.status === 409) {
|
||||
const outcome: unknown = await response
|
||||
.clone()
|
||||
.json()
|
||||
.catch(() => null);
|
||||
if (
|
||||
outcome &&
|
||||
typeof outcome === 'object' &&
|
||||
'status' in outcome &&
|
||||
outcome.status === 'cancelled' &&
|
||||
(await this.getRun(run.id))?.status === 'cancelled'
|
||||
) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(run.id, {
|
||||
type: 'run_update',
|
||||
data: { status: 'cancelled', timestamp: new Date().toISOString() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error(`Orchestrator returned ${response.status}: ${await response.text()}`);
|
||||
}
|
||||
const result: BacktestRunResult = await response.json();
|
||||
if (
|
||||
result.runId !== run.id ||
|
||||
result.backtestId !== backtest.id ||
|
||||
!['completed', 'cancelled'].includes(result.status)
|
||||
) {
|
||||
throw new Error('Invalid orchestrator run response');
|
||||
}
|
||||
// Results and terminal state are already committed by the orchestrator.
|
||||
this.getWebSocketHandler()?.sendCompletion(run.id, result);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logger.error('Backtest dispatch failed', { runId: run.id, error });
|
||||
// A broken HTTP connection must not overwrite a claimed or completed execution.
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`UPDATE runs SET status = 'failed', error = $2,
|
||||
completed_at = NOW(), updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
|
||||
[run.id, message]
|
||||
);
|
||||
} catch (persistenceError) {
|
||||
logger.error('Could not record backtest dispatch failure', {
|
||||
runId: run.id,
|
||||
persistenceError,
|
||||
});
|
||||
}
|
||||
this.getWebSocketHandler()?.sendError(run.id, message);
|
||||
}
|
||||
}
|
||||
|
||||
private mapBacktest(row: QueryResultRow): Backtest {
|
||||
return {
|
||||
id: row.id,
|
||||
|
|
@ -515,6 +486,8 @@ export class BacktestServiceV2 {
|
|||
completedAt: row.completed_at,
|
||||
pausedAt: row.paused_at,
|
||||
progress: parseFloat(row.progress),
|
||||
cancelRequested: row.cancel_requested === true,
|
||||
attemptNumber: Number(row.attempt_number ?? 0),
|
||||
currentDate: row.current_simulation_date,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue