more stuff

This commit is contained in:
Boki 2026-10-20 20:11:40 -04:00
parent c3cb36c8d6
commit 7dec0be3b4
26 changed files with 1394 additions and 275 deletions

View file

@ -13,15 +13,29 @@ export interface RunUpdateMessage {
data: unknown;
}
export function createWebSocketHandler(_container: IServiceContainer) {
export function createWebSocketHandler(container: IServiceContainer) {
const connections = new Map<string, Set<RunSocket>>();
const completionTimers = new Map<string, ReturnType<typeof setTimeout>>();
const snapshots = new Map<string, string>();
let pollTimer: ReturnType<typeof setInterval> | undefined;
let polling: Promise<void> | undefined;
let stopped = false;
return {
handleConnection(ws: RunSocket, runId: string) {
const clients = connections.get(runId) ?? new Set<RunSocket>();
clients.add(ws);
connections.set(runId, clients);
ws.send(JSON.stringify({ type: 'connected', runId, timestamp: new Date().toISOString() }));
if (container.postgres && !pollTimer) {
pollTimer = setInterval(
() =>
void this.refreshRunUpdates().catch(error => {
logger.warn('Could not refresh persisted run updates', { error });
}),
1000
);
pollTimer.unref();
}
},
handleMessage(ws: RunSocket, payload: string | Buffer) {
try {
@ -44,8 +58,61 @@ export function createWebSocketHandler(_container: IServiceContainer) {
clients?.delete(ws);
if (clients?.size === 0) {
connections.delete(runId);
snapshots.delete(runId);
if (!connections.size && pollTimer) {
clearInterval(pollTimer);
pollTimer = undefined;
}
}
},
/** Notifications are a projection of committed SQL state, independent of the executor process. */
refreshRunUpdates(): Promise<void> {
if (stopped || !container.postgres || !connections.size) {
return Promise.resolve();
}
const postgres = container.postgres;
return (polling ??= (async () => {
const result = await postgres.query(
`SELECT id, status, progress, current_simulation_date,
error, cancel_requested, attempt_number, updated_at FROM runs WHERE id::text = ANY($1::text[])`,
[[...connections.keys()]]
);
if (stopped) {
return;
}
for (const row of result.rows) {
const fingerprint = JSON.stringify(row);
if (snapshots.get(row.id) === fingerprint) {
continue;
}
snapshots.set(row.id, fingerprint);
this.broadcastRunUpdate(row.id, {
data: {
status: row.status,
progress: Number(row.progress),
currentDate: row.current_simulation_date,
cancelRequested: row.cancel_requested,
attemptNumber: row.attempt_number,
timestamp: new Date().toISOString(),
},
});
// Terminal rows do not change after commit, so these events are emitted once per subscription.
if (row.status === 'completed') {
this.sendCompletion(row.id);
} else if (row.status === 'failed') {
this.sendError(row.id, String(row.error ?? 'Backtest failed'));
} else if (row.status === 'running' || row.status === 'paused') {
this.sendProgressUpdate(
row.id,
Number(row.progress),
row.current_simulation_date?.toISOString()
);
}
}
})().finally(() => {
polling = undefined;
}));
},
broadcastRunUpdate(runId: string, update: Partial<RunUpdateMessage>) {
const message: RunUpdateMessage = {
type: 'run_update',
@ -94,6 +161,12 @@ export function createWebSocketHandler(_container: IServiceContainer) {
return connections.get(runId)?.size ?? 0;
},
cleanup() {
stopped = true;
if (pollTimer) {
clearInterval(pollTimer);
}
pollTimer = undefined;
snapshots.clear();
for (const timer of completionTimers.values()) {
clearTimeout(timer);
}