// Live jetstream subscription for the vuln-notif record graph. // // Filters the firehose to one repo DID and the collections the viewer indexes. // Reconnects forever with exponential backoff and jitter; callers only need to // call start() once and stop() on teardown. No credentials are used. const JETSTREAM_URL = "wss://jetstream1.us-east.bsky.network/subscribe"; const BASE_BACKOFF_MS = 1000; const MAX_BACKOFF_MS = 30000; let socket = null; let stopped = true; let state = "connecting"; let retryTimer = null; let attempt = 0; let handler = null; let options = {}; let wanted = new Set(); let cursor = null; export function status() { return state; } function setState(next) { state = next; if (typeof options.onStatus === "function") { try { options.onStatus(next); } catch (error) { console.error("jetstream status handler failed", error); } } } /** * Parse a raw jetstream frame into a graph event. Returns null for frames that * are not commits for a wanted collection. `fallbackDid` is used when a frame * omits the repo DID (handy for tests and replays). */ export function parseFrame(frame, fallbackDid) { if (!frame || typeof frame !== "object" || frame.kind !== "commit") return null; const commit = frame.commit; if (!commit || typeof commit !== "object") return null; const collection = commit.collection; if (typeof collection !== "string" || !collection) return null; const operation = commit.operation; if (operation !== "create" && operation !== "update" && operation !== "delete") { return null; } const did = typeof frame.did === "string" && frame.did ? frame.did : typeof commit.did === "string" && commit.did ? commit.did : fallbackDid || ""; const rkey = typeof commit.rkey === "string" ? commit.rkey : ""; if (!did || !rkey) return null; return { kind: operation === "delete" ? "delete" : "put", operation, uri: `at://${did}/${collection}/${rkey}`, did, collection, rkey, cid: typeof commit.cid === "string" ? commit.cid : "", record: commit.record && typeof commit.record === "object" ? commit.record : null, timeUs: typeof frame.time_us === "number" ? frame.time_us : null, }; } function clearRetry() { if (retryTimer !== null) { clearTimeout(retryTimer); retryTimer = null; } } function scheduleReconnect() { if (stopped) return; const base = Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * Math.pow(2, attempt)); attempt += 1; const jitter = 0.5 + Math.random() * 0.5; const delay = Math.max(250, Math.min(MAX_BACKOFF_MS, Math.round(base * jitter))); clearRetry(); retryTimer = setTimeout(connect, delay); } function handleMessage(raw) { let frame; try { frame = JSON.parse(raw); } catch (error) { return; } const event = parseFrame(frame, options.repoDid); if (!event || !wanted.has(event.collection)) return; if (event.timeUs !== null) { cursor = event.timeUs; if (typeof options.onCursor === "function") { try { options.onCursor(event.timeUs); } catch (error) { console.error("jetstream cursor handler failed", error); } } } try { handler(event); } catch (error) { console.error("jetstream event handler failed", error); } } function connect() { if (stopped) return; clearRetry(); setState(attempt === 0 ? "connecting" : "reconnecting"); const url = new URL(JETSTREAM_URL); if (options.repoDid) url.searchParams.set("wantedDids", options.repoDid); for (const collection of wanted) { if (collection) url.searchParams.append("wantedCollections", collection); } const resumeAt = cursor === null || cursor === undefined ? options.cursor : cursor; if (resumeAt !== null && resumeAt !== undefined && resumeAt !== "") { url.searchParams.set("cursor", String(resumeAt)); } let ws; try { ws = new WebSocket(url.toString()); } catch (error) { setState("error"); scheduleReconnect(); return; } socket = ws; ws.onopen = () => { attempt = 0; setState("live"); }; ws.onmessage = (event) => { handleMessage(event.data); }; ws.onerror = () => { setState("error"); }; ws.onclose = () => { if (socket === ws) socket = null; if (stopped) return; setState("reconnecting"); scheduleReconnect(); }; } export function start(onEvent, opts = {}) { stop(); handler = onEvent; options = opts || {}; wanted = new Set((options.collections || []).filter(Boolean)); attempt = 0; stopped = false; cursor = options.cursor === null || options.cursor === undefined || options.cursor === "" ? null : Number(options.cursor); if (!Number.isFinite(cursor)) cursor = null; connect(); } export function stop() { stopped = true; clearRetry(); if (socket) { const ws = socket; socket = null; ws.onopen = null; ws.onmessage = null; ws.onerror = null; ws.onclose = null; try { ws.close(1000, "stopped"); } catch (error) { // Socket may already be closing; nothing to do. } } }