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]
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue