Something went wrong. Try again.
An easy to set up and operate PDS admin panel. forked from brookie.blog/pds-operator
Something went wrong. Try again.
18 kB · 494 lines
TypeScript
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495import 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;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";
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 timers: NodeJS.Timeout[] = []; // latest firehose seq, persisted on the flush tick — a write per frame would hammer SQLite private accountCursor: number | null = null;
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 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(); } 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, updated_at) VALUES (@did, @handle, @email, @indexed_at, @status, @avatar, @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, 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, updated_at: Date.now(), }); } // drop accounts (and their labels/activity) 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 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); setSyncState(this.db, "last_full_sync", new Date().toISOString()); this.log.info( { accounts: repos.length, ms: Date.now() - started }, "full sync complete", ); }
private async fetchAvatars(dids: string[]): Promise<Map<string, string>> { const avatarByDid = new Map<string, string>(); await mapLimit(chunks(dids, 25), FETCH_CONCURRENCY, async (batch) => { const params = new URLSearchParams(); for (const did of batch) params.append("actors", did); try { const res = await fetchWithRetry( `https://public.api.bsky.app/xrpc/app.bsky.actor.getProfiles?${params}`, ); if (!res.ok) return; const { profiles } = (await res.json()) as { profiles: { did: string; avatar?: string }[] }; for (const p of profiles) if (p.avatar) avatarByDid.set(p.did, p.avatar); } catch (err) { this.log.warn({ err }, "avatar batch 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}