Something went wrong. Try again.
An atproto indexer and web app that scrapes domains from collections it sees
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211/** * Non-blocking PDS resolver. * * Hot path (event loop): * - getPdsHost(did) → O(1) in-memory Map lookup, never blocks * - enqueue(did) → adds to a Set, never blocks * * Background worker (runs every RESOLVE_INTERVAL_MS): * - Drains up to BATCH_SIZE DIDs from the queue * - Resolves them in parallel chunks of CONCURRENT * - Writes results to the in-memory cache and persists to DB * - Prunes the DB cache weekly * * Throughput: 100 DIDs / 2 s ≈ 50 DIDs/s ≈ 4.3 M DIDs/day * Fills the active-user cache within a few hours on fresh deploy. */
import { persistDidPds, loadDidPdsCache, pruneDidPdsCache } from "./db.js";
const PLC_DIRECTORY = "https://plc.directory";
const RESOLVE_INTERVAL_MS = 2_000; // run the worker every 2 sconst BATCH_SIZE = 100; // DIDs dequeued per worker runconst CONCURRENT = 10; // parallel requests per chunkconst CHUNK_GAP_MS = 50; // pause between chunks (politeness)const MAX_QUEUE_SIZE = 20_000; // drop oldest when fullconst PRUNE_INTERVAL_MS = 7 * 24 * 60 * 60 * 1_000; // weekly
// ── In-memory state ────────────────────────────────────────────────────────
// did → pdsHost: populated from DB on startup, then updated as resolutions completeconst cache = new Map<string, string>();
// DIDs waiting to be resolved (Set deduplicates; checked before enqueue)const queue = new Set<string>();
// Cumulative counters — surfaced via getResolverStats()let totalResolved = 0;let totalFailed = 0;
// Throttle repetitive error logging: track last-seen error messagelet lastErrorMsg = "";let lastErrorCount = 0;
// ── Public API ─────────────────────────────────────────────────────────────
/** Returns the PDS hostname for a DID, or undefined if not yet resolved. */export function getPdsHost(did: string): string | undefined { return cache.get(did);}
/** Returns current resolver stats for the stats endpoint. */export function getResolverStats(): { queueSize: number; cacheSize: number; totalResolved: number; totalFailed: number;} { return { queueSize: queue.size, cacheSize: cache.size, totalResolved, totalFailed };}
/** Queues a DID for background resolution if not already cached/queued. */export function enqueue(did: string): void { if (cache.has(did) || queue.has(did)) return; if (queue.size >= MAX_QUEUE_SIZE) { // Queue full: evict one entry to make room (FIFO approximation via iterator) const first = queue.values().next().value; if (first !== undefined) queue.delete(first); } queue.add(did);}
// ── Resolution logic ───────────────────────────────────────────────────────
// plc.directory returns the W3C DID document format:// { service: [{ id: "#atproto_pds", type: "...", serviceEndpoint: "https://..." }] }interface PlcDoc { service?: Array<{ id: string; type: string; serviceEndpoint: string; }>;}
interface ResolveResult { host: string | null; error?: string;}
async function resolveOne(did: string): Promise<ResolveResult> { try { if (did.startsWith("did:web:")) { // did:web:example.com → pds host is example.com return { host: did.slice("did:web:".length).split(":")[0] }; }
// did:plc:* → hit plc.directory const res = await fetch(`${PLC_DIRECTORY}/${encodeURIComponent(did)}`, { signal: AbortSignal.timeout(5_000), }); if (!res.ok) { return { host: null, error: `HTTP ${res.status}` }; }
const doc = (await res.json()) as PlcDoc; const service = doc.service?.find((s) => s.id === "#atproto_pds"); if (!service?.serviceEndpoint) { return { host: null, error: "no atproto_pds serviceEndpoint in DID doc" }; }
return { host: new URL(service.serviceEndpoint).hostname }; } catch (err) { const msg = err instanceof Error ? err.message : String(err); return { host: null, error: msg }; }}
function logError(msg: string): void { if (msg === lastErrorMsg) { lastErrorCount++; // Re-log every 50 occurrences so log spam is bounded but still visible if (lastErrorCount % 50 === 0) { console.error(`[pds-resolver] ${msg} (×${lastErrorCount})`); } } else { if (lastErrorCount > 1) { console.error(`[pds-resolver] previous error repeated ×${lastErrorCount}`); } lastErrorMsg = msg; lastErrorCount = 1; console.error(`[pds-resolver] ${msg}`); }}
// ── Background worker ──────────────────────────────────────────────────────
async function runWorker(): Promise<void> { if (queue.size === 0) return;
// Take a batch const batch: string[] = []; for (const did of queue) { if (batch.length >= BATCH_SIZE) break; batch.push(did); queue.delete(did); }
const resolved: Array<{ did: string; pdsHost: string }> = []; let batchFailed = 0;
// Resolve in parallel chunks, with a small gap between chunks for (let i = 0; i < batch.length; i += CONCURRENT) { const chunk = batch.slice(i, i + CONCURRENT); const results = await Promise.all( chunk.map((did) => resolveOne(did).then((r) => ({ did, ...r }))) ); for (const { did, host, error } of results) { if (host) { cache.set(did, host); resolved.push({ did, pdsHost: host }); } else { batchFailed++; if (error) logError(`resolve failed: ${error}`); } } if (i + CONCURRENT < batch.length) { await new Promise((r) => setTimeout(r, CHUNK_GAP_MS)); } }
totalResolved += resolved.length; totalFailed += batchFailed;
// Always log so we know the worker is running, even when all fail console.log( `[pds-resolver] Resolved ${resolved.length}/${batch.length} DIDs` + ` (ok: ${totalResolved}, failed: ${totalFailed}, cache: ${cache.size}, queue: ${queue.size})` );
if (resolved.length > 0) { await persistDidPds(resolved).catch((err: unknown) => console.error("[pds-resolver] Failed to persist DID cache:", err) ); }}
// ── Startup ────────────────────────────────────────────────────────────────
export async function startPdsResolver(): Promise<void> { // Warm the in-memory cache from DB (last 7 days only — keeps startup fast) const warm = await loadDidPdsCache(); for (const [did, pdsHost] of warm) { cache.set(did, pdsHost); } console.log(`[pds-resolver] Warmed cache with ${cache.size} entries from DB`);
// Resolution worker setInterval(() => { runWorker().catch((err: unknown) => console.error("[pds-resolver] Worker error:", err) ); }, RESOLVE_INTERVAL_MS);
// Weekly DB prune setInterval(() => { pruneDidPdsCache(30).catch((err: unknown) => console.error("[pds-resolver] Prune error:", err) ); }, PRUNE_INTERVAL_MS);}