Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243// Reads the standard.site collections from Jetstream, Bluesky's filtered// firehose. A cursor is a `time_us` value; replaying from one returns the// commits after it. Only commits in the four standard.site collections are// returned to the caller.//// Jetstream is a public derived service. It is how a daily run learns what// changed; the full relay walk remains the authoritative reconciliation.
import { COLLECTIONS } from './relay.mjs'
export const DEFAULT_JETSTREAM = 'wss://jetstream2.us-east.bsky.network/subscribe'export const JETSTREAM_COLLECTIONS = Object.values(COLLECTIONS)
const KNOWN = new Set(JETSTREAM_COLLECTIONS)
/** The filtered subscription URL. The cursor is microseconds since epoch. */export function jetstreamUrl({ url = DEFAULT_JETSTREAM, cursor, collections = JETSTREAM_COLLECTIONS,} = {}) { const target = new URL(url) for (const collection of collections) { target.searchParams.append('wantedCollections', collection) } if (Number.isFinite(cursor) && cursor > 0) target.searchParams.set('cursor', String(cursor)) return target.toString()}
/** * One event, reduced to what the indexer needs. Account events matter because * a deleted account means every repository record it held is gone. Identity * and other event kinds are ignored. */export function parseJetstreamEvent(data) { let event try { event = typeof data === 'string' ? JSON.parse(data) : data } catch { return null } if (!event || !Number.isFinite(event.time_us)) return null const did = typeof event.did === 'string' ? event.did : undefined if (event.kind === 'commit') { const commit = event.commit ?? {} const collection = commit.collection const operation = commit.operation if (!KNOWN.has(collection)) return null if (!['create', 'update', 'delete'].includes(operation)) return null return { timeUs: event.time_us, did, kind: 'commit', collection, operation } } if (event.kind === 'account') { const account = event.account ?? {} return { timeUs: event.time_us, did, kind: 'account', active: account.active !== false && account.status !== 'deleted', } } return { timeUs: event.time_us, did, kind: event.kind }}
/** * Follow the filtered stream until the event clock reaches `untilUs`. * * The stream has no "caught up" marker, so an idle stream counts as caught up: * after `idleMs` without an event, the next run can start at `untilUs`. A * maximum wall-clock is still needed because a large backlog must not hold the * task forever; when it trips, the returned cursor is the last event seen and * the next run continues from there. */export async function drainJetstream({ cursor, untilUs = Date.now() * 1_000, idleMs = 10_000, maxMs = 15 * 60_000, url, collections, WebSocketImpl = globalThis.WebSocket, now = () => Date.now(),} = {}) { if (!Number.isFinite(untilUs)) throw new Error('Jetstream needs an untilUs value') if (Number.isFinite(cursor) && cursor >= untilUs) { return { cursor, dirty: new Map(), accounts: new Set(), deletedAccounts: new Set(), identities: new Set(), events: 0, truncated: false, window: false, } } if (typeof WebSocketImpl !== 'function') throw new Error('This runtime has no WebSocket')
let lastError for (let attempt = 0; attempt < 3; attempt++) { try { return await drainOnce({ cursor, untilUs, idleMs, maxMs, url, collections, WebSocketImpl, now, }) } catch (error) { lastError = error if (attempt < 2) await new Promise((resolve) => setTimeout(resolve, 250 * 2 ** attempt)) } } throw lastError}
function drainOnce({ cursor, untilUs, idleMs, maxMs, url, collections, WebSocketImpl, now,}) { const dirty = new Map() const accounts = new Set() const deletedAccounts = new Set() const identities = new Set() let lastTime = Number.isFinite(cursor) ? cursor : 0 let firstTime let events = 0 let finished = false let socket
return new Promise((resolve, reject) => { const started = now() let idleTimer let maxTimer let openTimer
const finish = (error, truncated = false) => { if (finished) return finished = true clearTimeout(idleTimer) clearTimeout(maxTimer) clearTimeout(openTimer) try { socket?.close() } catch { // Closing a socket that already failed is not an error. } if (error) { reject(error) return } resolve({ cursor: truncated ? lastTime : Math.max(lastTime, untilUs), dirty, accounts, deletedAccounts, identities, events, truncated, window: true, gap: Number.isFinite(cursor) && Number.isFinite(firstTime) && untilUs - cursor > 26 * 60 * 60 * 1_000_000 && firstTime > cursor + 60 * 60 * 1_000_000, }) }
const armIdle = () => { clearTimeout(idleTimer) idleTimer = setTimeout(() => { // Idle only means caught up when the event clock has reached the run // time. A silent but backlogged stream must keep its last cursor. const caughtUp = !Number.isFinite(cursor) || lastTime >= untilUs - 5 * 60 * 1_000_000 finish(undefined, !caughtUp) }, idleMs) }
try { socket = new WebSocketImpl( jetstreamUrl({ url, cursor: Number.isFinite(cursor) ? cursor : undefined, collections }), ) } catch (error) { reject(error) return }
maxTimer = setTimeout(() => { finish(undefined, true) }, maxMs) openTimer = setTimeout(() => { finish(new Error('Jetstream connection did not open')) }, 10_000)
socket.addEventListener('open', () => { clearTimeout(openTimer) armIdle() }) socket.addEventListener('message', (message) => { armIdle() const event = parseJetstreamEvent(message.data) if (!event) return events++ if (firstTime === undefined) firstTime = event.timeUs if (event.timeUs > lastTime) lastTime = event.timeUs if (event.kind === 'commit' && event.did) { let kinds = dirty.get(event.did) if (!kinds) dirty.set(event.did, (kinds = new Set())) for (const [kind, collection] of Object.entries(COLLECTIONS)) { if (collection === event.collection) kinds.add(kind) } } else if (event.kind === 'account' && event.did) { // A status change can remove every record or bring them back. The // last status in the drain wins: a migration or reactivation sends an // inactive event and then an active one. accounts.add(event.did) if (event.active) deletedAccounts.delete(event.did) else deletedAccounts.add(event.did) } else if (event.kind === 'identity' && event.did) { // A handle change; publication rows carry the handle for attribution. identities.add(event.did) } if (event.timeUs >= untilUs) finish() if (now() - started > maxMs) finish(undefined, true) }) socket.addEventListener('error', (event) => { finish(new Error(`Jetstream connection failed: ${event?.message ?? 'socket error'}`)) }) socket.addEventListener('close', () => { if (!finished) finish(new Error('Jetstream closed before reaching the run time')) }) })}