Something went wrong. Try again.
An atproto indexer and web app that scrapes domains from collections it sees
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import 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 hitconst 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<string, unknown>; 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<typeof setInterval> | null = null; let reconnectTimer: ReturnType<typeof setTimeout> | null = null; let reconnectDelay = 1_000; let totalFlushed = 0; let totalEvents = 0;
async function flush(): Promise<void> { 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<void> { 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();}