import type { ServerWebSocket } from 'bun'; import { getLogger } from '@stock-bot/logger'; import type { IServiceContainer } from '@stock-bot/services'; const logger = getLogger('websocket-run-updates'); export interface RunSocketData { runId: string; } type RunSocket = ServerWebSocket; export interface RunUpdateMessage { type: 'run_update' | 'progress' | 'error' | 'completed'; runId: string; data: unknown; } export function createWebSocketHandler(container: IServiceContainer) { const connections = new Map>(); const completionTimers = new Map>(); const snapshots = new Map(); let pollTimer: ReturnType | undefined; let polling: Promise | undefined; let stopped = false; return { handleConnection(ws: RunSocket, runId: string) { const clients = connections.get(runId) ?? new Set(); 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 { const message: unknown = JSON.parse(payload.toString()); if ( message && typeof message === 'object' && 'type' in message && message.type === 'ping' ) { ws.send(JSON.stringify({ type: 'pong' })); } } catch (error) { logger.warn('Invalid WebSocket message', { error }); } }, handleClose(ws: RunSocket) { const runId = ws.data.runId; const clients = connections.get(runId); 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 { 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) { const message: RunUpdateMessage = { type: 'run_update', runId, data: update.data ?? update, ...update, }; for (const ws of connections.get(runId) ?? []) { try { ws.send(JSON.stringify(message)); } catch { this.handleClose(ws); } } }, sendProgressUpdate(runId: string, progress: number, currentDate?: string) { this.broadcastRunUpdate(runId, { type: 'progress', data: { progress, currentDate, timestamp: new Date().toISOString() }, }); }, sendError(runId: string, error: string) { this.broadcastRunUpdate(runId, { type: 'error', data: { error, timestamp: new Date().toISOString() }, }); }, sendCompletion(runId: string, results?: unknown) { this.broadcastRunUpdate(runId, { type: 'completed', data: { results, timestamp: new Date().toISOString() }, }); clearTimeout(completionTimers.get(runId)); completionTimers.set( runId, setTimeout(() => { for (const ws of connections.get(runId) ?? []) { ws.close(); } connections.delete(runId); completionTimers.delete(runId); }, 5000) ); }, getConnectionsCount(runId: string): number { 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); } completionTimers.clear(); for (const clients of connections.values()) { for (const ws of clients) { ws.close(); } } connections.clear(); }, }; } export type WebSocketHandler = ReturnType; let sharedHandler: WebSocketHandler | null = null; export function setWebSocketHandler(handler: WebSocketHandler): void { sharedHandler = handler; } export function getWebSocketHandler(): WebSocketHandler | null { return sharedHandler; }