Something went wrong. Try again.
fossabot clone for streamplace superbot.mmatt.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358import type { Store, WriteEvent } from '../db/store.ts'import { CHANNEL_COLLECTIONS, RECORD_COLLECTIONS, type RecordTarget } from './collections.ts'import { applyRecord, localKeys, localRecord, targetsFor } from './mapping.ts'
/** Writes to someone's repo through their OAuth session. */export interface RepoWriter { /** Collections the stored session can't write, or null when there's no usable session. */ missingScopes(did: string, collections: readonly string[]): Promise<string[] | null> put(did: string, collection: string, rkey: string, record: Record<string, unknown>): Promise<string> delete(did: string, collection: string, rkey: string): Promise<void>}
/** Reads a repo's records. Must throw (not return []) when the repo can't be reached. */export interface RepoReader { list(did: string, collection: string): Promise<{ rkey: string; cid: string; value: unknown }[]>}
export interface RepoCommit { did: string collection: string rkey: string operation: 'create' | 'update' | 'delete' cid?: string record?: Record<string, unknown>}
interface OutboxRow { repo: string collection: string rkey: string seq: number attempts: number next_at: number error: string | null}
/** Marks an outbox row that is waiting for its owner to sign in again. */const NEEDS_SIGN_IN = 'needs-sign-in'const validRkey = (k: string) => /^[a-zA-Z0-9._:~-]{1,512}$/.test(k) && k !== '.' && k !== '..'
/** * Keeps public config in its owner's atproto repo. The repo is the source of * truth: local edits are applied right away and queued in an outbox until * they're written, and anything else that changes in the repo (seen on * Jetstream, or when reconciling) overwrites the local copy. A queued local * edit wins over a remote one, since it's newer. */export class RecordSync { private store: Store private writer: RepoWriter private reader: RepoReader private flushing: Promise<void> | null = null private again = false private timer: NodeJS.Timeout | null = null private log: (msg: string) => void /** Per-repo queue, so a reconcile never reads a repo while we're writing to it. */ private locks = new Map<string, Promise<unknown>>() /** CIDs we wrote lately, so a late Jetstream echo of an older write doesn't roll a record back. */ private written = new Map<string, string[]>() /** The last CID Jetstream showed for each record, to spot an echo that beat our write's response. */ private lastSeen = new Map<string, string>() /** Records Jetstream changed while a reconcile was reading the repo; its snapshot is stale for them. */ private touched = new Map<string, Set<string>>()
constructor(store: Store, writer: RepoWriter, reader: RepoReader, log: (msg: string) => void = (m) => console.warn(`[records] ${m}`)) { this.store = store this.writer = writer this.reader = reader this.log = log store.on('write', (e) => this.onWrite(e)) }
private onWrite(e: WriteEvent) { if (e.remote) return const targets = targetsFor(this.store, e) for (const t of targets) this.enqueue(t) if (targets.length) this.schedule() }
// --- outbox ------------------------------------------------------------------------------------
enqueue(t: RecordTarget) { if (!validRkey(t.rkey)) return this.store.db.run( 'INSERT INTO record_outbox (repo, collection, rkey) VALUES (?, ?, ?) ON CONFLICT DO UPDATE SET seq = seq + 1, attempts = 0, next_at = 0, error = NULL', t.repo, t.collection, t.rkey, ) }
private pending(t: RecordTarget): boolean { return !!this.store.db.get('SELECT 1 FROM record_outbox WHERE repo = ? AND collection = ? AND rkey = ?', t.repo, t.collection, t.rkey) }
private withRepo<T>(repo: string, fn: () => Promise<T>): Promise<T> { const run = (this.locks.get(repo) ?? Promise.resolve()).then(fn, fn) const tail = run.catch(() => {}) this.locks.set(repo, tail) void tail.then(() => { if (this.locks.get(repo) === tail) this.locks.delete(repo) }) return run }
private noteWritten(t: RecordTarget, cid: string) { const key = `${t.repo} ${t.collection} ${t.rkey}` // Our write already echoed back, so every older echo has too. if (this.lastSeen.get(key) === cid) return void this.written.delete(key) const list = [cid, ...(this.written.get(key) ?? [])].slice(0, 5) this.written.delete(key) this.written.set(key, list) if (this.written.size > 5000) this.written.delete(this.written.keys().next().value!) }
private wroteRecently(t: RecordTarget, cid: string | null) { return !!cid && !!this.written.get(`${t.repo} ${t.collection} ${t.rkey}`)?.includes(cid) }
private stateCid(t: RecordTarget): string | undefined { return this.store.db.get<{ cid: string }>('SELECT cid FROM record_state WHERE repo = ? AND collection = ? AND rkey = ?', t.repo, t.collection, t.rkey)?.cid }
private setState(t: RecordTarget, cid: string | null) { if (cid === null) this.store.db.run('DELETE FROM record_state WHERE repo = ? AND collection = ? AND rkey = ?', t.repo, t.collection, t.rkey) else this.store.db.run( 'INSERT INTO record_state (repo, collection, rkey, cid) VALUES (?, ?, ?, ?) ON CONFLICT DO UPDATE SET cid = excluded.cid', t.repo, t.collection, t.rkey, cid, ) }
/** Flush soon, coalescing bursts of edits. */ schedule(delayMs = 200) { if (this.timer) return this.timer = setTimeout(() => { this.timer = null void this.flush() }, delayMs) }
/** Write every due record. Resolves once the outbox has been worked through. */ flush(): Promise<void> { if (this.flushing) { this.again = true return this.flushing } this.flushing = (async () => { do { this.again = false await this.flushOnce() } while (this.again) })().finally(() => { this.flushing = null }) return this.flushing }
private async flushOnce() { const rows = this.store.db.all<OutboxRow>('SELECT * FROM record_outbox WHERE next_at <= ? ORDER BY repo, collection, rkey', Date.now()) const byRepo = Map.groupBy(rows, (r) => r.repo) for (const [repo, list] of byRepo) { await this.withRepo(repo, async () => { const isChannel = this.store.getChannel(repo)?.kind === 'channel' const live: OutboxRow[] = [] for (const row of list) { // The channel was removed from Superbot. Its records stay in the owner's repo; we just stop managing them. if (!isChannel && (CHANNEL_COLLECTIONS as readonly string[]).includes(row.collection)) this.drop(row) else live.push(row) } if (!live.length) return const collections = [...new Set(live.map((r) => r.collection))] const missing = await this.writer.missingScopes(repo, collections).catch(() => null) const blocked = new Set(missing === null ? collections : missing) for (const row of live) { if (blocked.has(row.collection)) this.waitForSignIn(row) else await this.push(row) } }) } }
private drop(row: OutboxRow) { this.store.db.run('DELETE FROM record_outbox WHERE repo = ? AND collection = ? AND rkey = ? AND seq = ?', row.repo, row.collection, row.rkey, row.seq) }
private waitForSignIn(row: OutboxRow) { // Retried when the owner signs in again (see reconnected), or a few times a day. this.store.db.run( 'UPDATE record_outbox SET error = ?, next_at = ? WHERE repo = ? AND collection = ? AND rkey = ?', NEEDS_SIGN_IN, Date.now() + 6 * 3600_000, row.repo, row.collection, row.rkey, ) }
private async push(row: OutboxRow) { const t = { repo: row.repo, collection: row.collection, rkey: row.rkey } // The channel may have been removed while we waited; its records stay in the repo. if ((CHANNEL_COLLECTIONS as readonly string[]).includes(t.collection) && this.store.getChannel(t.repo)?.kind !== 'channel') return this.drop(row) let value: Record<string, unknown> | null = null try { value = localRecord(this.store, t) if (value) { const cid = await this.writer.put(t.repo, t.collection, t.rkey, value) this.noteWritten(t, cid) this.setState(t, cid) } else if (this.stateCid(t) !== undefined) { await this.writer.delete(t.repo, t.collection, t.rkey) this.setState(t, null) } // Only clear the entry if nothing changed while we were writing. this.drop(row) } catch (err) { const status = (err as { status?: number }).status if (status === 401 || status === 403 || (err as Error).name === 'NotConnectedError') return this.waitForSignIn(row) // The write may have landed even though we got no answer. Remember that, so a later delete still runs. if (value && this.stateCid(t) === undefined) this.setState(t, '') const attempts = row.attempts + 1 const message = err instanceof Error ? err.message : String(err) this.log(`couldn’t write ${t.collection}/${t.rkey} for ${t.repo}: ${message}`) this.store.db.run( 'UPDATE record_outbox SET attempts = ?, next_at = ?, error = ? WHERE repo = ? AND collection = ? AND rkey = ? AND seq = ?', attempts, Date.now() + Math.min(2 ** attempts * 30_000, 3600_000), message.slice(0, 500), t.repo, t.collection, t.rkey, row.seq, ) } }
/** The owner signed in again: retry their queued writes now and catch up with their repo. */ async reconnected(did: string) { this.store.db.run('UPDATE record_outbox SET next_at = 0 WHERE repo = ?', did) await this.reconcile(did) await this.flush() }
/** How publishing is going for one repo. */ status(did: string): { pending: number; needsSignIn: boolean; error: string | null } { const rows = this.store.db.all<{ error: string | null }>('SELECT error FROM record_outbox WHERE repo = ?', did) return { pending: rows.length, needsSignIn: rows.some((r) => r.error === NEEDS_SIGN_IN), error: rows.find((r) => r.error && r.error !== NEEDS_SIGN_IN)?.error ?? null, } }
/** Whether a record is published, queued, or not published at all. */ publication(t: RecordTarget): 'published' | 'pending' | 'none' { if (this.pending(t)) return 'pending' return this.stateCid(t) !== undefined ? 'published' : 'none' }
// --- reading from repos ------------------------------------------------------------------------
/** Apply one record from a repo (value null = deleted). */ ingest(t: RecordTarget, cid: string | null, value: unknown | null, fromFeed = false) { if (!RECORD_COLLECTIONS.includes(t.collection) || !validRkey(t.rkey)) return // A local edit is still on its way to the repo; it's newer, so it wins. if (this.pending(t)) return const known = this.stateCid(t) if (value !== null && (known === cid || (fromFeed && this.wroteRecently(t, cid))) && localRecord(this.store, t)) return try { this.store.asRemote(() => applyRecord(this.store, t, value)) } catch (err) { this.log(`ignoring ${t.collection}/${t.rkey} from ${t.repo}: ${err instanceof Error ? err.message : err}`) return } this.setState(t, value === null ? null : cid) }
onCommit(c: RepoCommit) { const t = { repo: c.did, collection: c.collection, rkey: c.rkey } const key = `${t.repo} ${t.collection} ${t.rkey}` this.touched.get(t.repo)?.add(`${t.collection} ${t.rkey}`) this.lastSeen.delete(key) if (c.cid) this.lastSeen.set(key, c.cid) if (this.lastSeen.size > 5000) this.lastSeen.delete(this.lastSeen.keys().next().value!) if (c.operation === 'delete') this.ingest(t, null, null) else if (c.record && c.cid) { // Jetstream delivers a repo's commits in order, so once our latest write echoes back, older echoes are done. const latest = c.cid === this.stateCid(t) this.ingest(t, c.cid, c.record, true) if (latest) this.written.delete(key) } }
/** * Bring the local copy in line with a repo: apply what's there, drop what was * deleted while we weren't watching, and queue anything that was never published. */ reconcile(repo: string): Promise<void> { return this.withRepo(repo, () => this.reconcileNow(repo)) }
private async reconcileNow(repo: string) { const touched = new Set<string>() this.touched.set(repo, touched) try { await this.reconcileCollections(repo, touched) } finally { this.touched.delete(repo) } }
private async reconcileCollections(repo: string, touched: Set<string>) { const isChannel = this.store.getChannel(repo)?.kind === 'channel' for (const collection of RECORD_COLLECTIONS) { if (!isChannel && (CHANNEL_COLLECTIONS as readonly string[]).includes(collection)) continue let remote: Awaited<ReturnType<RepoReader['list']>> try { remote = await this.reader.list(repo, collection) } catch (err) { this.log(`couldn’t read ${collection} from ${repo}: ${err instanceof Error ? err.message : err}`) continue } const seen = new Set<string>() for (const r of remote) { seen.add(r.rkey) if (touched.has(`${collection} ${r.rkey}`)) continue this.ingest({ repo, collection, rkey: r.rkey }, r.cid, r.value) } for (const rkey of localKeys(this.store, repo, collection)) { if (seen.has(rkey) || touched.has(`${collection} ${rkey}`)) continue const t = { repo, collection, rkey } if (this.pending(t)) continue // Published before but gone now: it was deleted from the repo. if (this.stateCid(t) !== undefined) this.ingest(t, null, null) else this.enqueue(t) } for (const { rkey } of this.store.db.all<{ rkey: string }>('SELECT rkey FROM record_state WHERE repo = ? AND collection = ?', repo, collection)) { if (!seen.has(rkey) && !touched.has(`${collection} ${rkey}`)) this.setState({ repo, collection, rkey }, null) } } }
/** Reconcile every repo Superbot knows about, a few at a time. */ async reconcileAll(concurrency = 4) { const repos = this.store.listRecordOwners() let i = 0 await Promise.all( Array.from({ length: Math.min(concurrency, repos.length) }, async () => { while (i < repos.length) await this.reconcile(repos[i++]!) }), ) await this.flush() }}