import WebSocket from "ws"; import { batchUpsert, batchUpsertPds, type CollectionEvent, type PdsEvent } from "./db.js"; import { getPdsHost, enqueue } from "./pds-resolver.js"; const JETSTREAM_URL = process.env.JETSTREAM_URL ?? "wss://jetstream2.us-east.bsky.network/subscribe"; // Flush when either threshold is hit const FLUSH_INTERVAL_MS = parseInt( process.env.FLUSH_INTERVAL_MS ?? "5000", 10 ); const FLUSH_BATCH_SIZE = parseInt( process.env.FLUSH_BATCH_SIZE ?? "2000", 10 ); interface JetstreamCommit { rev: string; operation: "create" | "update" | "delete"; collection: string; rkey: string; record?: Record; cid?: string; } interface JetstreamEvent { did: string; time_us: number; kind: "commit" | "identity" | "account"; commit?: JetstreamCommit; } export function startJetstreamRelay(): void { let buffer: CollectionEvent[] = []; let pdsBuffer: PdsEvent[] = []; let flushTimer: ReturnType | null = null; let reconnectTimer: ReturnType | null = null; let reconnectDelay = 1_000; let totalFlushed = 0; let totalEvents = 0; async function flush(): Promise { const toFlush = buffer; const toFlushPds = pdsBuffer; buffer = []; pdsBuffer = []; if (toFlush.length === 0 && toFlushPds.length === 0) return; try { await Promise.all([ toFlush.length > 0 ? batchUpsert(toFlush) : Promise.resolve(), toFlushPds.length > 0 ? batchUpsertPds(toFlushPds) : Promise.resolve(), ]); totalFlushed += toFlush.length; console.log( `[${new Date().toISOString()}] Flushed ${toFlush.length} events, ` + `${toFlushPds.length} PDS attributions ` + `(total: ${totalEvents})` ); } catch (err) { console.error("Error flushing buffer:", err); // Put events back so they're not lost buffer = toFlush.concat(buffer); pdsBuffer = toFlushPds.concat(pdsBuffer); } } function connect(): void { console.log(`[${new Date().toISOString()}] Connecting to ${JETSTREAM_URL}`); const ws = new WebSocket(JETSTREAM_URL); ws.on("open", () => { console.log(`[${new Date().toISOString()}] Connected to Jetstream`); reconnectDelay = 1_000; flushTimer = setInterval(() => { flush().catch(console.error); }, FLUSH_INTERVAL_MS); }); ws.on("message", (data: WebSocket.RawData) => { try { const event = JSON.parse(data.toString()) as JetstreamEvent; if (event.kind !== "commit" || !event.commit) return; const { collection, record, operation, rkey } = event.commit; if (operation === "delete") return; totalEvents++; const atUri = `at://${event.did}/${collection}/${rkey}`; if (collection) { buffer.push({ name: collection, atUri }); // PDS attribution — non-blocking cache lookup const pdsHost = getPdsHost(event.did); if (pdsHost) { pdsBuffer.push({ collection, pdsHost }); } else { // Queue DID for background resolution; next event from this DID // will hit the cache enqueue(event.did); } } // Also track lexicon $type if it differs from the collection if ( record && typeof record["$type"] === "string" && record["$type"] !== collection ) { const altType = record["$type"] as string; buffer.push({ name: altType, atUri }); const pdsHost = getPdsHost(event.did); if (pdsHost) { pdsBuffer.push({ collection: altType, pdsHost }); } } if (buffer.length >= FLUSH_BATCH_SIZE) { flush().catch(console.error); } } catch { // Ignore malformed frames } }); ws.on("error", (err: Error) => { console.error(`[${new Date().toISOString()}] WebSocket error: ${err.message}`); }); ws.on("close", (code: number, reason: Buffer) => { const reasonStr = reason.length ? ` (${reason.toString()})` : ""; console.log( `[${new Date().toISOString()}] Disconnected (code: ${code}${reasonStr}). Reconnecting in ${reconnectDelay}ms…` ); if (flushTimer) { clearInterval(flushTimer); flushTimer = null; } flush().catch(console.error); reconnectTimer = setTimeout(() => { reconnectDelay = Math.min(reconnectDelay * 2, 30_000); connect(); }, reconnectDelay); }); } async function shutdown(): Promise { console.log(`[${new Date().toISOString()}] Shutting down relay gracefully…`); if (flushTimer) clearInterval(flushTimer); if (reconnectTimer) clearTimeout(reconnectTimer); await flush(); process.exit(0); } process.on("SIGTERM", () => { shutdown().catch(console.error); }); process.on("SIGINT", () => { shutdown().catch(console.error); }); connect(); }