import pg from "pg"; const { Pool } = pg; // Singleton pool - reused across the process lifetime const pool = new Pool({ connectionString: process.env.DATABASE_URL, // Fly internal Postgres doesn't need SSL; external connections do ssl: process.env.DATABASE_SSL === "true" ? { rejectUnauthorized: false } : false, max: 10, idleTimeoutMillis: 30_000, connectionTimeoutMillis: 5_000, }); pool.on("error", (err) => { console.error("Postgres pool error:", err.message); }); export async function migrate(): Promise { await pool.query(` CREATE TABLE IF NOT EXISTS collection_stats ( name TEXT PRIMARY KEY, count BIGINT NOT NULL DEFAULT 0, first_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), last_at_uri TEXT ) `); await pool.query(` ALTER TABLE collection_stats ADD COLUMN IF NOT EXISTS last_at_uri TEXT `); await pool.query(` CREATE INDEX IF NOT EXISTS collection_stats_last_seen_idx ON collection_stats (last_seen DESC) `); await pool.query(` CREATE INDEX IF NOT EXISTS collection_stats_count_idx ON collection_stats (count DESC) `); // DID → PDS persistent cache (warm-up after restarts; pruned periodically) await pool.query(` CREATE TABLE IF NOT EXISTS did_pds_cache ( did TEXT PRIMARY KEY, pds_host TEXT NOT NULL, last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW() ) `); await pool.query(` CREATE INDEX IF NOT EXISTS did_pds_cache_last_seen_idx ON did_pds_cache (last_seen DESC) `); // Per-collection PDS attribution await pool.query(` CREATE TABLE IF NOT EXISTS collection_pds ( collection TEXT NOT NULL, pds_host TEXT NOT NULL, count BIGINT NOT NULL DEFAULT 0, PRIMARY KEY (collection, pds_host) ) `); console.log("Database migration complete"); } export interface CollectionEvent { name: string; atUri: string; } /** * Batch upsert a list of collection events. * Aggregates counts locally first, keeping the last AT URI seen per name, * then uses ON CONFLICT to atomically increment counters. */ export async function batchUpsert(events: CollectionEvent[]): Promise { if (events.length === 0) return; // Aggregate: count occurrences, keep last atUri per name const agg = new Map(); for (const { name, atUri } of events) { if (!name?.trim()) continue; const existing = agg.get(name); agg.set(name, { count: (existing?.count ?? 0) + 1, atUri }); } if (agg.size === 0) return; const entries = Array.from(agg.entries()); // ($1, $2::bigint, $3), ($4, $5::bigint, $6), ... const placeholders = entries .map((_, i) => `($${i * 3 + 1}, $${i * 3 + 2}::bigint, $${i * 3 + 3})`) .join(", "); const values = entries.flatMap(([name, { count, atUri }]) => [name, count, atUri]); await pool.query( `INSERT INTO collection_stats (name, count, last_at_uri) VALUES ${placeholders} ON CONFLICT (name) DO UPDATE SET count = collection_stats.count + EXCLUDED.count, last_seen = NOW(), last_at_uri = EXCLUDED.last_at_uri`, values ); } export interface PdsEvent { collection: string; pdsHost: string; } /** * Batch upsert collection × PDS attribution counts. */ export async function batchUpsertPds(events: PdsEvent[]): Promise { if (events.length === 0) return; // Aggregate locally const agg = new Map>(); for (const { collection, pdsHost } of events) { if (!collection || !pdsHost) continue; const inner = agg.get(collection) ?? new Map(); inner.set(pdsHost, (inner.get(pdsHost) ?? 0) + 1); agg.set(collection, inner); } const entries: Array<[string, string, number]> = []; for (const [collection, pdsCounts] of agg) { for (const [pdsHost, count] of pdsCounts) { entries.push([collection, pdsHost, count]); } } if (entries.length === 0) return; const placeholders = entries .map((_, i) => `($${i * 3 + 1}, $${i * 3 + 2}, $${i * 3 + 3}::bigint)`) .join(", "); const values = entries.flatMap(([c, p, n]) => [c, p, n]); await pool.query( `INSERT INTO collection_pds (collection, pds_host, count) VALUES ${placeholders} ON CONFLICT (collection, pds_host) DO UPDATE SET count = collection_pds.count + EXCLUDED.count`, values ); } /** * Persist resolved DID → PDS mappings. * Uses ON CONFLICT DO UPDATE to refresh last_seen on re-resolution. */ export async function persistDidPds( entries: Array<{ did: string; pdsHost: string }> ): Promise { if (entries.length === 0) return; const placeholders = entries .map((_, i) => `($${i * 2 + 1}, $${i * 2 + 2})`) .join(", "); const values = entries.flatMap(({ did, pdsHost }) => [did, pdsHost]); await pool.query( `INSERT INTO did_pds_cache (did, pds_host) VALUES ${placeholders} ON CONFLICT (did) DO UPDATE SET pds_host = EXCLUDED.pds_host, last_seen = NOW()`, values ); } /** * Load recently-seen DID → PDS entries into the in-memory cache on startup. * Only fetches entries seen within the last 7 days to keep the warm-up fast. */ export async function loadDidPdsCache(): Promise> { const result = await pool.query<{ did: string; pds_host: string }>( `SELECT did, pds_host FROM did_pds_cache WHERE last_seen > NOW() - INTERVAL '7 days'` ); const map = new Map(); for (const row of result.rows) { map.set(row.did, row.pds_host); } return map; } /** * Prune DID cache entries older than the given number of days. * Call periodically to prevent unbounded growth. */ export async function pruneDidPdsCache(olderThanDays = 30): Promise { await pool.query( `DELETE FROM did_pds_cache WHERE last_seen < NOW() - ($1 || ' days')::interval`, [olderThanDays] ); }