From d65cc65e2f26ebc29b93b52cd4abb4fe7e442c5f Mon Sep 17 00:00:00 2001 From: Steve Purves Date: Sat, 11 Apr 2026 07:37:59 +0000 Subject: [PATCH] feat: domain card layout, AT URI storage, pdsls.dev links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Relay (schema + data model): - Add last_at_uri TEXT column (idempotent ALTER TABLE ADD COLUMN IF NOT EXISTS) - batchUpsert now accepts CollectionEvent[] {name, atUri} instead of string[] - AT URI constructed per event: at://${did}/${collection}/${rkey} - Upsert updates last_at_uri on every conflict so it always reflects the most recently seen record for that collection Web (loader): - Group collections by two-segment domain prefix via SQL CTE (split_part(name,'.', 1) || '.' || split_part(name,'.', 2)) - avg_count = SUM(count) / COUNT(*) — normalised per collection type - Sort by count now orders by avg_count; date sorts use MAX/MIN across domain - COUNT(*) OVER () + MAX(avg_count) OVER () window functions replace the separate count + maxCount queries - Sub-query fetches all collections for visible domain cards via = ANY($domains) Web (UI): - Domain cards replace flat table rows - Domain header links to https://{reversed-domain} (e.g. social.attic → attic.social) - Bar width relative to max avg_count across all domains (respecting hide_bsky) - Each collection name links to https://pdsls.dev/${last_at_uri} when URI available - Date sorts work on MAX(last_seen) / MIN(first_seen) per domain https://claude.ai/code/session_01C5w4RGRwK9tB9DNmtaUwfc --- relay/src/db.ts | 56 ++++--- relay/src/jetstream.ts | 14 +- web/app/lib/db.server.ts | 2 +- web/app/routes/home.tsx | 313 +++++++++++++++++++++++---------------- 4 files changed, 225 insertions(+), 160 deletions(-) diff --git a/relay/src/db.ts b/relay/src/db.ts index 261c0a6..d5b4695 100644 --- a/relay/src/db.ts +++ b/relay/src/db.ts @@ -25,10 +25,17 @@ export async function migrate(): Promise { 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_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_at_uri TEXT ) `); + // Idempotent: add column if a pre-existing table is missing it + 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) @@ -42,40 +49,45 @@ export async function migrate(): Promise { console.log("Database migration complete"); } +export interface CollectionEvent { + name: string; + atUri: string; +} + /** - * Batch upsert a list of collection/type names. - * Aggregates counts locally first to minimise the number of rows in the - * INSERT statement, then uses ON CONFLICT to atomically increment counters. + * 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(names: string[]): Promise { - if (names.length === 0) return; - - // Aggregate duplicates within the batch - const counts = new Map(); - for (const name of names) { - if (name && name.trim()) { - counts.set(name, (counts.get(name) ?? 0) + 1); - } +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 (counts.size === 0) return; + if (agg.size === 0) return; - const entries = Array.from(counts.entries()); + const entries = Array.from(agg.entries()); - // Build a multi-row INSERT with parameterised placeholders - // ($1,$2), ($3,$4), ... + // ($1, $2::bigint, $3), ($4, $5::bigint, $6), ... const placeholders = entries - .map((_, i) => `($${i * 2 + 1}, $${i * 2 + 2}::bigint)`) + .map((_, i) => `($${i * 3 + 1}, $${i * 3 + 2}::bigint, $${i * 3 + 3})`) .join(", "); - const values = entries.flatMap(([name, count]) => [name, count]); + const values = entries.flatMap(([name, { count, atUri }]) => [name, count, atUri]); await pool.query( - `INSERT INTO collection_stats (name, count) + `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()`, + count = collection_stats.count + EXCLUDED.count, + last_seen = NOW(), + last_at_uri = EXCLUDED.last_at_uri`, values ); } diff --git a/relay/src/jetstream.ts b/relay/src/jetstream.ts index 3a7ad96..cca3d0f 100644 --- a/relay/src/jetstream.ts +++ b/relay/src/jetstream.ts @@ -1,5 +1,5 @@ import WebSocket from "ws"; -import { batchUpsert } from "./db.js"; +import { batchUpsert, type CollectionEvent } from "./db.js"; const JETSTREAM_URL = process.env.JETSTREAM_URL ?? @@ -32,7 +32,7 @@ interface JetstreamEvent { } export function startJetstreamRelay(): void { - let buffer: string[] = []; + let buffer: CollectionEvent[] = []; let flushTimer: ReturnType | null = null; let reconnectTimer: ReturnType | null = null; let reconnectDelay = 1_000; // ms, doubles on each failure up to 30s @@ -51,7 +51,7 @@ export function startJetstreamRelay(): void { ); } catch (err) { console.error("Error flushing buffer:", err); - // Put the names back so they're not lost + // Put the events back so they're not lost buffer = toFlush.concat(buffer); } } @@ -77,16 +77,18 @@ export function startJetstreamRelay(): void { if (event.kind !== "commit" || !event.commit) return; - const { collection, record, operation } = event.commit; + const { collection, record, operation, rkey } = event.commit; // We only care about creates and updates if (operation === "delete") return; totalEvents++; + const atUri = `at://${event.did}/${collection}/${rkey}`; + // Always track the collection namespace if (collection) { - buffer.push(collection); + buffer.push({ name: collection, atUri }); } // Also track the lexicon $type if it differs from the collection @@ -96,7 +98,7 @@ export function startJetstreamRelay(): void { typeof record["$type"] === "string" && record["$type"] !== collection ) { - buffer.push(record["$type"] as string); + buffer.push({ name: record["$type"] as string, atUri }); } if (buffer.length >= FLUSH_BATCH_SIZE) { diff --git a/web/app/lib/db.server.ts b/web/app/lib/db.server.ts index b501665..91512aa 100644 --- a/web/app/lib/db.server.ts +++ b/web/app/lib/db.server.ts @@ -33,7 +33,7 @@ function getPool(): pg.Pool { export async function query( sql: string, - params: (string | number | null | boolean)[] = [] + params: (string | number | null | boolean | string[])[] = [] ): Promise> { return getPool().query(sql, params); } diff --git a/web/app/routes/home.tsx b/web/app/routes/home.tsx index 6c8a106..9994a89 100644 --- a/web/app/routes/home.tsx +++ b/web/app/routes/home.tsx @@ -5,7 +5,7 @@ import { Button } from "~/components/ui/button"; import { Input } from "~/components/ui/input"; import { Badge } from "~/components/ui/badge"; import { Switch } from "~/components/ui/switch"; -import { Search, ChevronLeft, ChevronRight, Activity } from "lucide-react"; +import { Search, ChevronLeft, ChevronRight, Activity, ExternalLink } from "lucide-react"; import { cn } from "~/lib/utils"; export const meta = () => [ @@ -21,15 +21,22 @@ const PAGE_SIZE = 50; type SortKey = "last_seen" | "count" | "first_seen"; type SortDir = "asc" | "desc"; -interface CollectionStat { - name: string; - count: string; - first_seen: string; +interface DomainStatRow { + domain: string; + collection_count: string; + total_count: string; + avg_count: string; last_seen: string; + first_seen: string; + total_domains: string; + max_avg_count: string; } -interface CountRow { +interface CollectionRow { + name: string; count: string; + last_seen: string; + last_at_uri: string | null; } interface TotalRow { @@ -37,10 +44,6 @@ interface TotalRow { total_records: string; } -interface MaxRow { - max_count: string; -} - export async function loader({ request }: LoaderFunctionArgs) { const url = new URL(request.url); const q = url.searchParams.get("q")?.trim() ?? ""; @@ -48,7 +51,6 @@ export async function loader({ request }: LoaderFunctionArgs) { const rawSort = url.searchParams.get("sort") ?? "last_seen"; const sort: SortKey = rawSort === "count" || rawSort === "first_seen" ? rawSort : "last_seen"; - const rawDir = url.searchParams.get("dir") ?? "desc"; const dir: SortDir = rawDir === "asc" ? "asc" : "desc"; @@ -57,80 +59,106 @@ export async function loader({ request }: LoaderFunctionArgs) { const hideBsky = rawHideBsky === null ? true : rawHideBsky !== "0"; const offset = (page - 1) * PAGE_SIZE; - // sort and dir are both validated to a fixed set of values — safe to interpolate - const col = sort === "count" ? "count" : sort === "first_seen" ? "first_seen" : "last_seen"; - const orderSql = `${col} ${dir === "asc" ? "ASC" : "DESC"}`; + // sort and dir are both validated to a fixed set — safe to interpolate + const sortCol = + sort === "count" ? "avg_count" : + sort === "first_seen" ? "first_seen" : + "last_seen"; + const orderSql = `${sortCol} ${dir === "asc" ? "ASC" : "DESC"}`; + const bskyClause = hideBsky ? "AND name NOT LIKE 'app.bsky.%'" : ""; - let statsResult: { rows: CollectionStat[] }; - let countResult: { rows: CountRow[] }; + // Domain grouping CTE. + // Window functions compute total_domains + max_avg_count across all matching + // domains before LIMIT/OFFSET is applied, so no separate count query needed. + const buildDomainCte = (extraWhere: string, paramOffset: number) => ` + WITH domain_stats AS ( + SELECT + split_part(name, '.', 1) || '.' || split_part(name, '.', 2) AS domain, + COUNT(*)::bigint AS collection_count, + SUM(count)::bigint AS total_count, + (SUM(count) / NULLIF(COUNT(*), 0))::bigint AS avg_count, + MAX(last_seen) AS last_seen, + MIN(first_seen) AS first_seen + FROM collection_stats + WHERE 1=1 ${bskyClause} ${extraWhere} + GROUP BY domain + ) + SELECT + domain, + collection_count::text, + total_count::text, + avg_count::text, + last_seen, + first_seen, + COUNT(*) OVER ()::text AS total_domains, + MAX(avg_count) OVER ()::text AS max_avg_count + FROM domain_stats + ORDER BY ${orderSql} + LIMIT $${paramOffset} OFFSET $${paramOffset + 1} + `; + + let domainResult: { rows: DomainStatRow[] }; let summaryResult: { rows: TotalRow[] }; - let maxCountResult: { rows: MaxRow[] }; - - const bskyClause = hideBsky ? "AND name NOT LIKE 'app.bsky.%'" : ""; - // Global max count query — respects hide_bsky but not the search term, - // so bars are always scaled relative to the most-seen collection in the dataset. - const maxCountQuery = query( - `SELECT COALESCE(MAX(count), 1)::text AS max_count - FROM collection_stats - ${hideBsky ? "WHERE name NOT LIKE 'app.bsky.%'" : ""}` + const summaryQuery = query( + `SELECT COUNT(*)::text AS total_count, COALESCE(SUM(count),0)::text AS total_records + FROM collection_stats` ); if (q) { const pattern = `%${q}%`; - [statsResult, countResult, summaryResult, maxCountResult] = await Promise.all([ - query( - `SELECT name, count, first_seen, last_seen - FROM collection_stats - WHERE name ILIKE $1 ${bskyClause} - ORDER BY ${orderSql} - LIMIT $2 OFFSET $3`, - [pattern, PAGE_SIZE, offset] - ), - query( - `SELECT COUNT(*)::text AS count FROM collection_stats WHERE name ILIKE $1 ${bskyClause}`, - [pattern] - ), - query( - `SELECT COUNT(*)::text AS total_count, COALESCE(SUM(count),0)::text AS total_records FROM collection_stats` - ), - maxCountQuery, + [domainResult, summaryResult] = await Promise.all([ + query(buildDomainCte("AND name ILIKE $1", 2), [pattern, PAGE_SIZE, offset]), + summaryQuery, ]); } else { - [statsResult, countResult, summaryResult, maxCountResult] = await Promise.all([ - query( - `SELECT name, count, first_seen, last_seen - FROM collection_stats - ${hideBsky ? "WHERE name NOT LIKE 'app.bsky.%'" : ""} - ORDER BY ${orderSql} - LIMIT $1 OFFSET $2`, - [PAGE_SIZE, offset] - ), - query( - `SELECT COUNT(*)::text AS count FROM collection_stats - ${hideBsky ? "WHERE name NOT LIKE 'app.bsky.%'" : ""}` - ), - query( - `SELECT COUNT(*)::text AS total_count, COALESCE(SUM(count),0)::text AS total_records FROM collection_stats` - ), - maxCountQuery, + [domainResult, summaryResult] = await Promise.all([ + query(buildDomainCte("", 1), [PAGE_SIZE, offset]), + summaryQuery, ]); } - const total = parseInt(countResult.rows[0]?.count ?? "0", 10); - const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE)); + const domains = domainResult.rows; + const totalDomains = parseInt(domains[0]?.total_domains ?? "0", 10); + const maxAvgCount = parseInt(domains[0]?.max_avg_count ?? "1", 10); + const totalPages = Math.max(1, Math.ceil(totalDomains / PAGE_SIZE)); + + // Fetch all collections for the visible domain cards in one query + let collectionsByDomain = new Map(); + if (domains.length > 0) { + const domainNames = domains.map((d) => d.domain); + const searchWhere = q ? "AND name ILIKE $2" : ""; + const colResult = await query( + `SELECT name, count::text AS count, last_seen, last_at_uri + FROM collection_stats + WHERE (split_part(name, '.', 1) || '.' || split_part(name, '.', 2)) = ANY($1) + ${bskyClause} ${searchWhere} + ORDER BY count DESC`, + q ? [domainNames, `%${q}%`] : [domainNames] + ); + for (const col of colResult.rows) { + const dom = col.name.split(".").slice(0, 2).join("."); + const list = collectionsByDomain.get(dom) ?? []; + list.push(col); + collectionsByDomain.set(dom, list); + } + } + const summary = summaryResult.rows[0]; return { - stats: statsResult.rows, - total, + domains: domains.map((d) => ({ + ...d, + collections: collectionsByDomain.get(d.domain) ?? [], + })), + total: totalDomains, totalPages, + maxAvgCount, page: Math.min(page, totalPages), q, sort, dir, hideBsky, - maxCount: parseInt(maxCountResult.rows[0]?.max_count ?? "1", 10), totalCollections: parseInt(summary?.total_count ?? "0", 10), totalRecords: parseInt(summary?.total_records ?? "0", 10), }; @@ -153,6 +181,11 @@ function formatDate(iso: string): string { return `${year}-${month}-${day} ${hour}:${min} UTC`; } +/** Reverse a two-segment reverse-domain prefix to a URL: "social.attic" → "https://attic.social" */ +function domainToUrl(domain: string): string { + return `https://${domain.split(".").reverse().join(".")}`; +} + function buildLink( base: { q: string; sort: SortKey; dir: SortDir; page: number; hideBsky: boolean }, overrides: Partial<{ q: string; sort: SortKey; dir: SortDir; page: number; hideBsky: boolean }> @@ -170,7 +203,7 @@ function buildLink( } export default function Home() { - const { stats, total, totalPages, page, q, sort, dir, hideBsky, maxCount, totalCollections, totalRecords } = + const { domains, total, totalPages, page, q, sort, dir, hideBsky, maxAvgCount, totalCollections, totalRecords } = useLoaderData(); const navigation = useNavigation(); const isLoading = navigation.state === "loading"; @@ -181,7 +214,6 @@ export default function Home() { const SortLink = ({ field, label }: { field: SortKey; label: string }) => { const isActive = sort === field; - // Clicking the active sort toggles direction; clicking an inactive sort starts at desc const nextDir: SortDir = isActive ? (dir === "desc" ? "asc" : "desc") : "desc"; return ( - {/* Search bar */} + {/* Search + filter bar */}
@@ -294,11 +326,11 @@ export default function Home() { of{" "} {total.toLocaleString()} - + {" "} + domains {q && ( <> - {" "} - matching "{q}" + {" "}matching "{q}" )} @@ -307,86 +339,105 @@ export default function Home() {
Sort: - +
- {/* Table */} + {/* Domain cards */}
- {stats.length === 0 ? ( -
+ {domains.length === 0 ? ( +
{q ? ( - <>No collections match "{q}" + <>No domains match "{q}" ) : ( "No data yet — the relay is still warming up." )}
) : ( -
- {/* Header row — hidden on mobile */} -
- Collection / Lexicon type - Count - First seen - Last seen -
- {stats.map((stat, i) => { - const count = parseInt(stat.count, 10); - const barWidth = Math.max(2, Math.round((count / maxCount) * 100)); - - return ( -
- {/* Collection name + bar */} -
- - {stat.name} - -
-
+ domains.map((domain) => { + const avgCount = parseInt(domain.avg_count, 10); + const collectionCount = parseInt(domain.collection_count, 10); + const barWidth = Math.max(2, Math.round((avgCount / maxAvgCount) * 100)); + const domainUrl = domainToUrl(domain.domain); + + return ( +
+ {/* Card header */} +
+
+ + {domain.domain} + + +
+ + {formatCount(avgCount)} + {" "} + avg/type + · + {collectionCount} {collectionCount === 1 ? "type" : "types"} + · + last seen {formatDate(domain.last_seen)}
- - {/* Mobile stats row — shown below the name on small screens */} -
- - Count: - {count.toLocaleString()} - - - Last seen: - {formatDate(stat.last_seen)} - + {/* Bar */} +
+
- - {/* Desktop grid cells */} - - {count.toLocaleString()} - - - {formatDate(stat.first_seen)} - - - {formatDate(stat.last_seen)} -
- ); - })} -
+ + {/* Collection list */} + {domain.collections.length > 0 && ( +
+ {domain.collections.map((col) => { + const count = parseInt(col.count, 10); + return ( +
+ + {col.last_at_uri ? ( + + {col.name} + + ) : ( + col.name + )} + + + {count.toLocaleString()} + +
+ ); + })} +
+ )} +
+ ); + }) )}
-- knotmirror 0.0.1