"use client"; // One console-wide WebSocket: it only nudges pages to refetch. Rest stays the // source of truth, so a dropped socket costs freshness, not correctness. import { useEffect, useRef, useState } from "react"; import { wsUrl } from "./api"; import type { Frame } from "./types"; export type SocketStatus = "connecting" | "open" | "closed"; const THROTTLE_MS = 400; export function useHubSocket(topics: string[] = ["*.>"]) { const [status, setStatus] = useState("connecting"); const [revision, setRevision] = useState(0); const [lastFrame, setLastFrame] = useState(null); const stamp = useRef(0); const key = topics.join(","); useEffect(() => { let socket: WebSocket | null = null; let timer: ReturnType | null = null; let attempts = 0; let closed = false; const connect = () => { setStatus(attempts === 0 ? "connecting" : "connecting"); socket = new WebSocket(wsUrl(key.split(","))); socket.onopen = () => { attempts = 0; setStatus("open"); }; socket.onmessage = (message) => { let frame: Frame; try { frame = JSON.parse(message.data as string) as Frame; } catch { return; } if ((frame as unknown as { type?: string }).type === "ping") { socket?.send(JSON.stringify({ action: "ping" })); return; } setLastFrame(frame); const now = Date.now(); if (now - stamp.current > THROTTLE_MS) { stamp.current = now; setRevision((value) => value + 1); } }; socket.onclose = () => { if (closed) return; setStatus("closed"); attempts += 1; timer = setTimeout(connect, Math.min(15000, 800 * 2 ** Math.min(attempts, 4))); }; socket.onerror = () => socket?.close(); }; connect(); return () => { closed = true; if (timer) clearTimeout(timer); socket?.close(); }; }, [key]); return { status, revision, lastFrame }; }