Something went wrong. Try again.
An easy to set up and operate PDS admin panel.
Something went wrong. Try again.
25 kB · 658 lines
TypeScript
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659import WebSocket from "ws";import type { FastifyBaseLogger } from "fastify";import { readFrame, type PdsClient, type RepoEntry } from "./pdsClient.js";import { activeLabels, type Label, type WatchedLabeler } from "./labelerClient.js";import { setSyncState, getSyncState, type Db } from "./db.js";import type { BskyDmNotifier } from "./notifier.js";
const FULL_SYNC_INTERVAL_MS = 15 * 60 * 1000;// a changed repo is re-measured at most this often, so busy accounts don't cost a// CAR download on every syncconst STORAGE_REMEASURE_MS = 6 * 60 * 60 * 1000;const DIRTY_FLUSH_MS = 5_000;const RECONNECT_MS = 10_000;const FETCH_CONCURRENCY = 4;
/** Run `fn` over `items` with bounded concurrency. */async function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> { const results: R[] = new Array(items.length); let next = 0; const workers = Array.from({ length: Math.min(limit, items.length) }, async () => { while (next < items.length) { const i = next++; results[i] = await fn(items[i]); } }); await Promise.all(workers); return results;}
function chunks<T>(items: T[], size: number): T[][] { const out: T[][] = []; for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size)); return out;}
/** fetch with retry/backoff on 429 and 5xx — third-party APIs rate limit under fan-out. */async function fetchWithRetry(url: string, tries = 3): Promise<Response> { let lastErr: unknown; for (let attempt = 0; attempt < tries; attempt++) { try { const res = await fetch(url); if (res.status === 429 || res.status >= 500) { const retryAfter = Number(res.headers.get("retry-after")); const delay = Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : 1000 * 2 ** attempt; await new Promise((r) => setTimeout(r, delay)); continue; } return res; } catch (err) { lastErr = err; await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt)); } } throw lastErr ?? new Error(`fetch failed after ${tries} tries: ${url}`);}
/** * Liveness watchdog: a stream socket can go half-dead (no close event, no data — * e.g. after a NAT timeout), which would silently stop live updates until restart. * Ping every 30s; a missed pong means the connection is gone, so terminate it and * let the close handler's reconnect logic take over. */function attachHeartbeat(ws: WebSocket, intervalMs = 30_000) { let alive = true; ws.on("pong", () => { alive = true; }); const timer = setInterval(() => { if (ws.readyState !== WebSocket.OPEN) return; if (!alive) { ws.terminate(); // fires 'close' → reconnect return; } alive = false; ws.ping(); }, intervalMs); timer.unref(); ws.once("close", () => clearInterval(timer));}
const ACCOUNT_STREAM_CURSOR_KEY = "account_stream_cursor";
/** DM an alert when one account makes this many record creations within the window. */export interface ActivityAlertConfig { creates: number; windowMinutes: number;}
export function accountStreamUrl(hostname: string, cursor: string | null): string { return ( `wss://${hostname}/xrpc/com.atproto.sync.subscribeRepos` + (cursor ? `?cursor=${cursor}` : "") );}
function repoStatusToAccountStatus(repo: RepoEntry): "active" | "takendown" | "deactivated" { if (repo.active !== false) return "active"; return repo.status === "deactivated" ? "deactivated" : "takendown";}
export class Syncer { private dirty = new Set<string>(); // firehose commit counts buffered as "day|did" -> n, flushed on the dirty interval private activity = new Map<string, number>(); private sockets: WebSocket[] = []; private stopped = false; private syncing = false; private sweepingStorage = false; private timers: NodeJS.Timeout[] = []; // latest firehose seq, persisted on the flush tick — a write per frame would hammer SQLite private accountCursor: number | null = null; // record creations per account, bucketed by minute, for burst alerts private createBursts = new Map<string, Map<number, number>>(); private burstAlertedAt = new Map<string, number>();
constructor( private db: Db, private pds: PdsClient, private labelers: WatchedLabeler[], private log: FastifyBaseLogger, private notifier: BskyDmNotifier | null = null, private labelNames: Map<string, Map<string, string>> = new Map(), private activityAlert: ActivityAlertConfig | null = null, ) {}
private isWatched(labeler: WatchedLabeler, val: string): boolean { return labeler.watch.size === 0 || labeler.watch.has(val); }
private notifyNewFlags(did: string, vals: string[], src: string) { if (!this.notifier || vals.length === 0) return; const row = this.db.prepare("SELECT handle FROM accounts WHERE did = ?").get(did) as | { handle: string } | undefined; const names = vals.sort().map((val) => this.labelNames.get(src)?.get(val) ?? val); void this.notifier.notifyFlags({ did, handle: row?.handle ?? did }, names); }
start() { void this.fullSync().catch((err) => this.log.error({ err }, "initial full sync failed")); const syncTimer = setInterval(() => { void this.fullSync().catch((err) => this.log.error({ err }, "full sync failed")); }, FULL_SYNC_INTERVAL_MS); const flushTimer = setInterval(() => { void this.flushDirty().catch((err) => this.log.error({ err }, "dirty flush failed")); try { this.flushActivity(); this.flushCursor(); this.pruneCreateBursts(); } catch (err) { this.log.error({ err }, "activity flush failed"); } }, DIRTY_FLUSH_MS); for (const t of [syncTimer, flushTimer]) t.unref(); this.timers.push(syncTimer, flushTimer);
this.connectAccountStream(); for (const labeler of this.labelers) this.connectLabelStream(labeler); }
/** Shutdown seam: stop reconnects, tear down sockets, cancel timers, flush buffers. */ stop() { this.stopped = true; for (const t of this.timers) clearInterval(t); this.timers = []; for (const ws of this.sockets) ws.terminate(); this.sockets = []; try { this.flushActivity(); this.flushCursor(); } catch (err) { this.log.error({ err }, "final flush failed"); } }
// ---- full reconcile ------------------------------------------------------
async fullSync() { if (this.syncing) return; // a slow sync must not overlap the next tick this.syncing = true; try { await this.fullSyncInner(); } finally { this.syncing = false; } }
private async fullSyncInner() { const started = Date.now(); const repos = await this.pds.listAllRepos(); const dids = repos.map((r) => r.did);
const infoBatches = await mapLimit(chunks(dids, 100), FETCH_CONCURRENCY, (batch) => this.pds.accountInfos(batch), ); const infoByDid = new Map(infoBatches.flat().map((i) => [i.did, i])); const avatarByDid = await this.fetchAvatars(dids);
const upsert = this.db.prepare(` INSERT INTO accounts (did, handle, email, indexed_at, status, avatar, rev, updated_at) VALUES (@did, @handle, @email, @indexed_at, @status, @avatar, @rev, @updated_at) ON CONFLICT(did) DO UPDATE SET handle = excluded.handle, email = excluded.email, indexed_at = excluded.indexed_at, status = excluded.status, avatar = excluded.avatar, rev = excluded.rev, updated_at = excluded.updated_at `); this.db.transaction(() => { for (const repo of repos) { const info = infoByDid.get(repo.did); upsert.run({ did: repo.did, handle: info?.handle ?? "(unknown)", email: info?.email ?? null, indexed_at: info?.indexedAt ?? "", status: repoStatusToAccountStatus(repo), avatar: avatarByDid.get(repo.did) ?? null, rev: repo.rev ?? repo.head ?? "", updated_at: Date.now(), }); } // drop accounts (and their labels/activity/blob sizes) that no longer exist on the PDS const params = dids.map(() => "?").join(","); this.db.prepare(`DELETE FROM labels WHERE did NOT IN (SELECT did FROM accounts)`).run(); this.db.prepare(`DELETE FROM activity WHERE did NOT IN (SELECT did FROM accounts)`).run(); this.db.prepare(`DELETE FROM blob_sizes WHERE did NOT IN (SELECT did FROM accounts)`).run(); this.db.prepare(`DELETE FROM activity WHERE hour < date('now', '-400 days')`).run(); if (dids.length > 0) { this.db.prepare(`DELETE FROM accounts WHERE did NOT IN (${params})`).run(...dids); } })();
await this.backfillLabels(dids); // storage runs detached: a long first sweep must not delay the sync heartbeat void this.syncStorage().catch((err) => this.log.error({ err }, "storage sweep failed")); setSyncState(this.db, "last_full_sync", new Date().toISOString()); this.log.info( { accounts: repos.length, ms: Date.now() - started }, "full sync complete", ); }
/** * Measure storage per account: repo CAR bytes plus blob bytes. Repo revs plus a * time floor gate the work (only repos that changed since their last measurement, * each at most every STORAGE_REMEASURE_MS), and blob sizes are cached per cid * since blobs are immutable. First run walks everything; later runs touch only * changed repos, so the sweep is cheap enough to run detached on every sync. */ private async syncStorage() { if (this.sweepingStorage) return; // a slow sweep must not overlap the next one this.sweepingStorage = true; try { const stale = this.db .prepare( `SELECT did, rev FROM accounts WHERE (storage_rev IS NULL OR storage_rev != rev) AND (storage_at IS NULL OR storage_at < ?)`, ) .all(Date.now() - STORAGE_REMEASURE_MS) as { did: string; rev: string }[]; if (stale.length === 0) return; const started = Date.now(); await mapLimit(stale, FETCH_CONCURRENCY, async ({ did, rev }) => { if (this.stopped) return; try { const repoBytes = await this.pds.repoCarBytes(did); const cids = await this.pds.listBlobCids(did); const known = new Map( ( this.db.prepare("SELECT cid, bytes FROM blob_sizes WHERE did = ?").all(did) as { cid: string; bytes: number; }[] ).map((r) => [r.cid, r.bytes]), ); const insert = this.db.prepare( "INSERT OR REPLACE INTO blob_sizes (did, cid, bytes) VALUES (?, ?, ?)", ); // a listed cid can 404 (blob lost or never imported), so count it as 0 // and cache the 0 so it isn't refetched every sweep const fresh = [...new Set(cids)].filter((cid) => !known.has(cid)); await mapLimit(fresh, FETCH_CONCURRENCY, async (cid) => { const bytes = await this.pds.blobBytes(did, cid).catch(() => 0); insert.run(did, cid, bytes); known.set(cid, bytes); }); const present = new Set(cids); let blobBytes = 0; for (const cid of present) blobBytes += known.get(cid) ?? 0; const remove = this.db.prepare("DELETE FROM blob_sizes WHERE did = ? AND cid = ?"); for (const cid of known.keys()) if (!present.has(cid)) remove.run(did, cid); this.db .prepare( `UPDATE accounts SET repo_bytes = ?, blob_bytes = ?, storage_rev = ?, storage_at = ? WHERE did = ?`, ) .run(repoBytes, blobBytes, rev, Date.now(), did); } catch (err) { this.log.warn({ err, did }, "storage measurement failed"); } }); this.log.info( { accounts: stale.length, ms: Date.now() - started }, "storage sweep complete", ); } finally { this.sweepingStorage = false; } }
/** * Avatar URLs come straight from the PDS: read each account's profile record and * point at the blob endpoint. No appview dependency, so it works for accounts the * relay never crawled, at the cost of raw blobs instead of CDN-resized thumbnails. */ private async fetchAvatars(dids: string[]): Promise<Map<string, string>> { const avatarByDid = new Map<string, string>(); await mapLimit(dids, FETCH_CONCURRENCY, async (did) => { const repo = encodeURIComponent(did); try { const res = await fetchWithRetry( `https://${this.pds.hostname}/xrpc/com.atproto.repo.getRecord?repo=${repo}&collection=app.bsky.actor.profile&rkey=self`, ); if (!res.ok) return; // no profile record, or repo unavailable (e.g. takendown) const { value } = (await res.json()) as { value?: { avatar?: { ref?: { $link?: string }; cid?: string } }; }; // blob refs are {ref: {$link}} in current repos, {cid} in legacy ones const cid = value?.avatar?.ref?.$link ?? value?.avatar?.cid; if (cid) { avatarByDid.set( did, `https://${this.pds.hostname}/xrpc/com.atproto.sync.getBlob?did=${repo}&cid=${cid}`, ); } } catch (err) { this.log.warn({ err, did }, "avatar fetch failed"); } }); return avatarByDid; }
private async backfillLabels(dids: string[]) { for (const labeler of this.labelers) { const src = labeler.did; try { const batches = await mapLimit(chunks(dids, 20), FETCH_CONCURRENCY, (batch) => labeler.client.queryLabels(batch), ); const byUri = activeLabels(batches.flat(), src);
const before = new Set( ( this.db.prepare("SELECT did, val FROM labels WHERE src = ?").all(src) as { did: string; val: string; }[] ).map((r) => `${r.did}