Something went wrong. Try again.
fossabot clone for streamplace superbot.mmatt.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import { EventEmitter } from 'node:events'import { env } from './env.ts'import type { Store } from './db/store.ts'
export interface JetstreamCommit { did: string time_us: number kind: 'commit' commit: { operation: 'create' | 'update' | 'delete' collection: string rkey: string cid?: string record?: Record<string, unknown> }}
/** * A Jetstream subscription with cursor persistence and reconnects. `dids` * can be changed at runtime; the socket reconnects with the new filter. */export class Jetstream extends EventEmitter<{ commit: [JetstreamCommit] }> { private ws: WebSocket | null = null private closed = false private backoff = 1000 private cursor: number | null = null private lastSaved = 0 private name: string private collections: string[] private dids: string[] | null private store: Store
constructor(store: Store, name: string, collections: string[], dids: string[] | null = null) { super() this.store = store this.name = name this.collections = collections this.dids = dids this.cursor = store.kvGet<number>(`jetstream_cursor:${name}`) ?? null }
start() { this.closed = false this.connect() }
stop() { this.closed = true this.ws?.close() }
setDids(dids: string[]) { const next = [...new Set(dids)].sort() if (this.dids && next.join() === this.dids.join()) return this.dids = next this.ws?.close() }
private connect() { if (this.closed) return if (this.dids && this.dids.length === 0) { // Nothing to watch; check again later. setTimeout(() => this.connect(), 30_000) return } const url = new URL(env.jetstreamUrl) for (const c of this.collections) url.searchParams.append('wantedCollections', c) for (const d of this.dids ?? []) url.searchParams.append('wantedDids', d) // Rewind a few seconds so nothing is lost across reconnects. Skip stale cursors. if (this.cursor && Date.now() * 1000 - this.cursor < 60 * 60 * 1e6) url.searchParams.set('cursor', String(this.cursor - 5e6)) const ws = new WebSocket(url) this.ws = ws ws.onopen = () => { this.backoff = 1000 } ws.onmessage = (ev) => { let evt: JetstreamCommit try { evt = JSON.parse(String(ev.data)) } catch { return } if (evt.kind !== 'commit') return this.cursor = evt.time_us if (Date.now() - this.lastSaved > 5000) { this.lastSaved = Date.now() this.store.kvSet(`jetstream_cursor:${this.name}`, this.cursor) } this.emit('commit', evt) } ws.onclose = () => { if (this.closed) return setTimeout(() => this.connect(), this.backoff) this.backoff = Math.min(this.backoff * 2, 60_000) } ws.onerror = () => ws.close() }}