import { channelCoverage, type ChannelCoverage } from "yt-dlp-transcript-common/controller/channelCoverage"; import { mapConcurrent } from "yt-dlp-transcript-common/lib/concurrency"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { describeFetchError, editorFromEnv, resolveSelectedChannels, type ChannelRef } from "yt-dlp-transcript-mcp/research"; import { CHANNELS_DIR } from "../paths.mjs"; import { yearOf } from "./facets.mjs"; import { isLocalOnly } from "./rules.mjs"; import { openSource } from "./sources"; import type { CoverageResponse, CoverageRow, Scope } from "./types"; // --------------------------------------------------------------------------- // THE ARCHIVE INVENTORY's numbers (plans/umtool-redesign.md, "Research, // first-class" 6): what the archive can and cannot answer, channels × years. // // published the source's own summaries index, by upload year and state: // what a search over this source can reach // held what the editor holds on disk (channel_coverage: every held // video by its coverage date, and the spans with nothing held), // asked of the editor's GET /api/ops/coverage exactly as the MCP's // channel_coverage asks it. When umtool has no WORKER_TOKEN, or the // editor does not answer, the answer says which -- and for the // local corpus reads the same controller on disk instead // (common/controller/channelCoverage.ts, read only) // tracks transcripts vs captions per year, for a channel a search has // read whole (lib/research/corpus.ts's census) // --------------------------------------------------------------------------- /** The inventory marks a gap longer than this (the canvas: "gap over 60 days that year"). */ export const GAP_DAYS = 60; const TIMEOUT_MS = 15_000; type Held = NonNullable; function heldOf(c: Pick): Held { const gapYears = new Set(); for (const g of c.gaps) { for (let y = Number(g.after.slice(0, 4)); y <= Number(g.before.slice(0, 4)); y++) gapYears.add(String(y)); } return { total: c.held, byYear: c.byYear, gaps: c.gaps, gapYears: [...gapYears].sort(), first: c.first, last: c.last, }; } type EditorAsk = { ok: true; body: ChannelCoverage } | { ok: false; status?: number; why: string; stop: boolean }; /** One channel from the editor, as the MCP's channel_coverage asks it. */ async function askEditor(slug: string): Promise { const editor = editorFromEnv(process.env); if (!editor) return { ok: false, why: "WORKER_TOKEN is not set for umtool, so the editor was not asked", stop: true }; const q = new URLSearchParams({ slug, gapDays: String(GAP_DAYS) }); let res: Response; try { res = await fetch(`${editor.url}/api/ops/coverage?${q}`, { headers: { authorization: `Bearer ${editor.token}` }, signal: AbortSignal.timeout(TIMEOUT_MS), }); } catch (e) { return { ok: false, why: `the editor at ${editor.url} is unreachable: ${describeFetchError(e, TIMEOUT_MS)}`, stop: true }; } const body = (await res.json().catch(() => null)) as (ChannelCoverage & { error?: string }) | null; if (res.ok && body && typeof body.held === "number") return { ok: true, body }; if (res.status === 503) return { ok: false, status: 503, why: "the editor's ops surface is off (it has no WORKER_TOKEN)", stop: true }; if (res.status === 401) return { ok: false, status: 401, why: "the editor refused umtool's WORKER_TOKEN", stop: true }; const err = body?.error ?? `HTTP ${res.status}`; // A channel the editor does not hold is an answer about that channel; a // route the editor does not have is an answer about the editor. if (res.status === 404 && /^Channel ".*" not found$/.test(err)) return { ok: false, status: 404, why: err, stop: false }; return { ok: false, status: res.status, why: `the editor answered ${res.status}: ${err}`, stop: true }; } async function fromDisk(slug: string): Promise { try { return heldOf(await channelCoverage({ ...getPaths(), channelsDir: CHANNELS_DIR }, slug, { gapDays: GAP_DAYS })); } catch { return null; } } // ── the held counts, memoised ── // // Each channel's held count is a walk of the editor's disk (every held // video's metadata), and the editor has stalled on the external drive before: // a page load must not cost a walk per channel. So a channel's answer -- // the editor's, the disk's, or "not known" with the reason -- is kept // HELD_TTL_MS per source and channel, on globalThis (one copy for every route // bundle). `fresh` (the page's Refresh) asks again. The editor is still asked // four at a time. export const HELD_TTL_MS = 5 * 60_000; type HeldMemo = { at: number; held: Held | null; via: CoverageResponse["held"]["via"]; note?: string }; const g = globalThis as { __umtoolResearchHeld?: Map }; const heldMemo = (g.__umtoolResearchHeld ??= new Map()); export async function coverageOf(scope: Scope, opts: { fresh?: boolean; now?: () => number } = {}): Promise { const now = opts.now ?? Date.now; const opened = await openSource(scope.source); const { source } = opened; const sel = await resolveSelectedChannels(source, { channels: scope.channels }); const channels: ChannelRef[] = sel.channels; // Published, from the summaries index (one read for every channel). const published = new Map(); const index = source.videoIndex ? await source.videoIndex().catch(() => null) : null; for (const ch of channels) published.set(ch.slug, { total: 0, byYear: {}, byState: {}, missingByYear: {} }); if (index) { for (const v of index.values()) { const p = published.get(v.channelSlug); if (!p) continue; p.total++; const y = yearOf(v.uploadDate); if (y) p.byYear[y] = (p.byYear[y] ?? 0) + 1; p.byState[v.state] = (p.byState[v.state] ?? 0) + 1; if (y && v.state !== "available") { const m = (p.missingByYear[y] ??= {}); m[v.state] = (m[v.state] ?? 0) + 1; } } } for (const ch of channels) { const p = published.get(ch.slug)!; if (p.total === 0 && ch.videoCount) p.total = ch.videoCount; } // Held: the memo, else the editor, else (local corpus) the disk. const memoKey = (ch: ChannelRef) => `${opened.option.handle}\u0000${ch.key}`; const t = now(); const todo = channels.filter((ch) => { const m = heldMemo.get(memoKey(ch)); return opts.fresh || !m || t - m.at >= HELD_TTL_MS; }); if (todo.length > 0) { let note: string | undefined; let stopped = false; const fromEditor = new Map(); await mapConcurrent(todo, 4, async (ch) => { if (stopped) return; const a = await askEditor(ch.slug); if (a.ok) fromEditor.set(ch.key, heldOf(a.body)); else if (a.stop) { stopped = true; note ??= a.why; } else fromEditor.set(ch.key, null); }); const at = now(); if (!stopped) { for (const ch of todo) heldMemo.set(memoKey(ch), { at, held: fromEditor.get(ch.key) ?? null, via: "editor" }); } else if (opened.option.kind === "local") { const why = `${note}; read on disk instead`; await mapConcurrent(todo, 8, async (ch) => heldMemo.set(memoKey(ch), { at, held: await fromDisk(ch.slug), via: "disk", note: why })); } else { const why = `${note}; held counts need the editor for a published source`; for (const ch of todo) heldMemo.set(memoKey(ch), { at, held: null, via: "none", note: why }); } } const memos = channels.map((ch) => heldMemo.get(memoKey(ch))!).filter(Boolean); const held = new Map(channels.map((ch) => [ch.key, heldMemo.get(memoKey(ch))?.held ?? null])); // The page says where the counts came from, and how old the oldest is. const odd = memos.find((m) => m.via === "disk") ?? memos.find((m) => m.via === "none"); const via: CoverageResponse["held"]["via"] = odd?.via ?? "editor"; const note = odd?.note; const at = memos.length ? Math.min(...memos.map((m) => m.at)) : t; const years = new Set(); const rows: CoverageRow[] = channels.map((ch) => { const p = published.get(ch.slug)!; const h = held.get(ch.key) ?? null; const census = opened.census.get(ch.key); for (const y of Object.keys(p.byYear)) years.add(y); for (const y of Object.keys(h?.byYear ?? {})) years.add(y); return { key: ch.key, slug: ch.slug, name: ch.name, ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}), published: p, held: h, tracks: census ? census.byYear : null, }; }); const ys = [...years].filter((y) => /^\d{4}$/.test(y)).map(Number).sort((a, b) => a - b); const span: string[] = []; for (let y = ys[0]; ys.length && y <= ys[ys.length - 1]; y++) span.push(String(y)); rows.sort((a, b) => (b.held?.total ?? b.published.total) - (a.held?.total ?? a.published.total) || a.name.localeCompare(b.name)); return { source: opened.option, years: span, rows, held: { via, ...(note ? { note } : {}), at, cached: todo.length === 0, asked: todo.length }, gapDays: GAP_DAYS, }; }