116 lines
4.9 KiB
TypeScript
116 lines
4.9 KiB
TypeScript
import type { Logger, PostgresClient, Queue } from '@stock-bot/services';
|
|
|
|
/**
|
|
* Bridges committed backtest_dispatch rows to BullMQ and recovers expired leases.
|
|
* PostgreSQL is the source of truth; Redis jobs are repeatable notifications.
|
|
* Duplicate delivery is safe because BacktestRunner must claim the SQL run before
|
|
* executing it. Queue retries and durable attempt limits are separate mechanisms.
|
|
*/
|
|
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 })
|
|
);
|
|
}
|
|
|
|
/** Timer/manual ticks share one in-flight pass; a slow publish cannot overlap itself. */
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* Recover SQL ownership first, reserve due notifications second, publish last.
|
|
* next_publish_at is a retry delay, not a delivery acknowledgement: a crash
|
|
* after reservation leaves a durable intent that becomes due again.
|
|
*/
|
|
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 AS r SET
|
|
status = CASE WHEN cancel_requested THEN 'cancelled'::run_status
|
|
WHEN (attempt_number >= LEAST($1,COALESCE((to_jsonb(r)#>>'{research_limits,maxAttempts}')::integer,$1)) OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp())) THEN 'failed'::run_status ELSE 'pending'::run_status END,
|
|
error = CASE WHEN cancel_requested THEN NULL
|
|
WHEN (attempt_number >= LEAST($1,COALESCE((to_jsonb(r)#>>'{research_limits,maxAttempts}')::integer,$1)) OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp())) THEN CASE WHEN ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp()) THEN 'Research attempt wall time exceeded' ELSE 'Execution lease expired; retry limit reached' END ELSE NULL END,
|
|
completed_at = CASE WHEN cancel_requested OR (attempt_number >= LEAST($1,COALESCE((to_jsonb(r)#>>'{research_limits,maxAttempts}')::integer,$1)) OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp())) 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() OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= 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]
|
|
);
|
|
});
|
|
}
|
|
}
|
|
}
|