// A POSTS CHANNEL'S TIMES, CHEAPLY (lane x-console): what the account // activity panel needs of every archived post — id, createdAt, author, // permalink and a short first line — without materialising whole posts. // // readAllPosts parses, validates and sorts every post on every call: ~1 s for // the largest posts channel (kf-quartering-thread, 66 MB, 37,802 posts) on // every render of its page. This keeps each SHARD's light rows in memory, // keyed by the shard's path and re-read only when its mtime or size changes // (a fetch appends to the newest shard; the rest never change), so a render // re-reads at most the shard a fetch just wrote. // // Dedupe by id across shards, as readAllPosts does (an interrupted archive // write can leave one post in two shards). Unordered: accountActivity sorts. import { readFile, stat } from "node:fs/promises"; import path from "node:path"; import { channelPostsDir, listPostShards } from "./posts-server"; import { parsePost } from "./posts"; import { accountActivity, type AccountActivity, type ActivityPost } from "./accountActivity"; type ShardRows = { mtimeMs: number; size: number; rows: ActivityPost[] }; // Shards kept, process-wide; the oldest entry goes first past this. const MAX_SHARDS = 4000; declare global { // eslint-disable-next-line no-var var __yttPostTimes__: Map | undefined; } function cache(): Map { return (globalThis.__yttPostTimes__ ??= new Map()); } export function clearPostTimesCache(): void { globalThis.__yttPostTimes__?.clear(); globalThis.__yttActivityMemo__?.clear(); } function snippet(text: unknown): string | undefined { if (typeof text !== "string") return undefined; const first = text.split("\n", 8).find((l) => l.trim()); if (!first) return undefined; const t = first.trim(); return t.length > 90 ? `${t.slice(0, 89)}…` : t; } function rowsOf(text: string, channelSlug: string): ActivityPost[] { const rows: ActivityPost[] = []; for (const line of text.split("\n")) { if (!line.trim()) continue; let raw: Record; try { raw = JSON.parse(line) as Record; } catch { continue; } if (!raw || typeof raw !== "object") continue; const { id, createdAt } = raw; if (typeof id !== "string" || !id || typeof createdAt !== "string" || !createdAt) continue; let url = typeof raw.url === "string" ? raw.url : ""; // A record stored without its permalink: the full parse derives it (a // forum post's needs its forum's origin). if (!url) url = parsePost({ ...raw, channelSlug })?.url ?? ""; rows.push({ id, createdAt, url, ...(typeof raw.author === "string" ? { author: raw.author } : {}), ...(snippet(raw.text) ? { text: snippet(raw.text) } : {}), }); } return rows; } // The shards' identity: when no shard changed, nothing derived from them did. async function shardSignature(channelRoot: string): Promise { const dir = channelPostsDir(channelRoot); const parts: string[] = []; for (const shard of await listPostShards(channelRoot)) { try { const st = await stat(path.join(dir, `${shard}.jsonl`)); parts.push(`${shard}:${st.mtimeMs}:${st.size}`); } catch { // gone between the listing and the stat } } return parts.join("|"); } type ActivityMemo = { key: string; activity: AccountActivity | null }; declare global { // eslint-disable-next-line no-var var __yttActivityMemo__: Map | undefined; } // THE PANEL'S DATA: accountActivity over readPostTimes, memoised per channel // by the shards' signature and the options — an unchanged channel costs one // stat per shard (sorting 37,802 posts' dates is ~100 ms; a render should not // pay it twice). A day's turn is part of the key too, so a bogus date's // "a day from now" bound moves. export async function readChannelActivity( channelRoot: string, opts: { asOf?: string; author?: string } = {}, ): Promise { const memo = (globalThis.__yttActivityMemo__ ??= new Map()); const key = `${await shardSignature(channelRoot)}#${opts.asOf ?? ""}#${opts.author ?? ""}#${new Date().toISOString().slice(0, 10)}`; const hit = memo.get(channelRoot); if (hit && hit.key === key) return hit.activity; const activity = accountActivity(await readPostTimes(channelRoot), opts); memo.delete(channelRoot); memo.set(channelRoot, { key, activity }); while (memo.size > 500) memo.delete(memo.keys().next().value!); return activity; } export async function readPostTimes(channelRoot: string): Promise { const shards = await listPostShards(channelRoot); const dir = channelPostsDir(channelRoot); const channelSlug = path.basename(channelRoot); const c = cache(); const byId = new Map(); for (const shard of shards) { const file = path.join(dir, `${shard}.jsonl`); let st; try { st = await stat(file); } catch { continue; } let hit = c.get(file); if (!hit || hit.mtimeMs !== st.mtimeMs || hit.size !== st.size) { let text: string; try { text = await readFile(file, "utf8"); } catch { continue; } hit = { mtimeMs: st.mtimeMs, size: st.size, rows: rowsOf(text, channelSlug) }; c.delete(file); c.set(file, hit); while (c.size > MAX_SHARDS) c.delete(c.keys().next().value!); } for (const row of hit.rows) byId.set(row.id, row); } return [...byId.values()]; }