// A CHANNEL'S STREAM CHATS, FETCHED AFTER ITS DOWNLOADS (2026-10-26) — the // `fetch-chat-backlog` job: `pnpm ops fetch-chat-backlog {slug}`, and the // download lane's own for a channel whose `chat` is "later" once it has nothing // left to download (controller/laneChatBacklog.ts). // // WHY. A stream's live chat replay is 7–42 MB and came down with its captions, // which made each YouTube download of a streaming channel 2–4× slower while // the Ethanalyzer backlog was archived (2026-10-23…26). The fix then was a hand // edit of `subLangs` and a hand-written watcher that waited for the downloads // and ran `pnpm ops fetch-chat` per streamed episode — and died on reboot. A // `chat: "later"` channel's downloads leave the chat out (effectiveSubLangs), // and this job fetches the chats afterwards. // // WHICH VIDEOS. Every held video whose metadata says it was a stream // (`live_status` was_live / post_live, or `was_live: true`) and whose chat is // not here — selected by the METADATA, because a download without `live_chat` // in its sub-langs records no chat track to look for. A raw replay already on // disk is only normalized. Newest first. // // PACED AND RESUMABLE. One chat at a time through fetchLiveChat (the one // chat-only pass: the channel's cookies, the platform's live pace), on the // platform's download queue, with the batch downloads' gap between two // (downloadGapMs). It stops on a rate limit (the platform's cooldown recorded), // a held platform, three failures in a row, a drain or `limit` chats; a re-run // skips every chat already here and every stream already known to have none — // `chat-backlog.json` beside the channel's config remembers those, and what the // last run did. Replayable, and resumed after a restart (jobs/jobKinds.ts). import path from "node:path"; import { readdir, readFile } from "node:fs/promises"; import type { ChannelConfig } from "../lib/channelConfig"; import { assertChannelTextReadable } from "../lib/channelMedia"; import type { ResolvedCookiePolicy } from "../lib/cookiePolicy"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import type { Paths } from "../lib/paths"; import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; import { META_FILENAME } from "../lib/videoStatus"; import { heldPlatformRefusal, platformCooldownRemainingMs, recordDownloadBackoff, recordPlatformClean, } from "../jobs/downloadBackoff"; import { downloadGapMs } from "../jobs/platformBackoff"; import { getRegistry } from "../jobs/registry"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { channelPaceSeconds, channelPlatform, platformMinGapSeconds, staticSleepRequestsSeconds, } from "../ytdlp/channelArgs"; import { fetchLiveChat, liveChatPlan, noChatFetcherSentence, type ChatRunner } from "./fetchLiveChat"; import { normalizeLiveChat } from "./normalizeLiveChat"; import { readChannelSnapshotShared } from "./channels"; export const FETCH_CHAT_BACKLOG_KIND = "fetch-chat-backlog"; export const CHAT_BACKLOG_FILENAME = "chat-backlog.json"; // Three failures in a row (not a rate limit) stop a run: the source is saying // something a fourth request will not change. export const CHAT_BACKLOG_MAX_FAILURES_IN_A_ROW = 3; const STREAM_STATUSES = new Set(["was_live", "post_live"]); export type ChatBacklogState = { version: 1; // Streams whose chat the source does not have (replay off, or never live // after all), and those with no chat fetcher: never asked again. settled: Record; lastRun?: { jobId?: string; startedAt: string; endedAt: string; // Every stream's chat is here or settled. complete: boolean; fetched: number; normalized: number; none: number; failed: number; remaining: number; stopped?: string; // The channel report's downloaded count the run started from: the lane // queues the next run when it moves. downloadedAtRun?: number; }; }; function statePath(paths: Paths, slug: string): string { return path.join(paths.channelsDir, slug, CHAT_BACKLOG_FILENAME); } export async function readChatBacklogState(paths: Paths, slug: string): Promise { const read = await readJsonFile(statePath(paths, slug)); const v = read.ok ? (read.value as Partial) : null; return { version: 1, settled: v && v.settled && typeof v.settled === "object" ? v.settled : {}, ...(v?.lastRun && typeof v.lastRun === "object" ? { lastRun: v.lastRun } : {}), }; } async function writeChatBacklogState(paths: Paths, slug: string, state: ChatBacklogState): Promise { await writeJsonAtomic(statePath(paths, slug), state); } async function streamInfo(videoDir: string): Promise<{ live: string | null; date: string }> { try { const meta = JSON.parse(await readFile(path.join(videoDir, META_FILENAME), "utf8")) as { live_status?: unknown; was_live?: unknown; upload_date?: unknown; release_date?: unknown; }; const live = meta.was_live === true ? "was_live" : typeof meta.live_status === "string" ? meta.live_status : null; const date = typeof meta.upload_date === "string" ? meta.upload_date : typeof meta.release_date === "string" ? meta.release_date : ""; return { live, date }; } catch { return { live: null, date: "" }; } } export type ChatBacklogCandidate = { id: string; date: string; action: "fetch" | "normalize"; url?: string; platform?: string }; export type ChatBacklogPlan = { candidates: ChatBacklogCandidate[]; // Streams whose chat is already here (fresh live_chat.cues.json). have: number; // Streams known to have none (chat-backlog.json `settled`). settled: number; // Held videos that were not streams. notStreams: number; }; // What the job would do, from the disk alone (no request): every held stream // whose chat is neither here nor settled, newest first. export async function planChatBacklog( paths: Paths, slug: string, config: ChannelConfig, state?: ChatBacklogState, ): Promise { const known = state ?? (await readChatBacklogState(paths, slug)); const dataDir = path.join(paths.channelsDir, slug, "data"); let ids: string[]; try { ids = (await readdir(dataDir, { withFileTypes: true })) .filter((e) => e.isDirectory() || e.isSymbolicLink()) .map((e) => e.name); } catch { ids = []; } const plan: ChatBacklogPlan = { candidates: [], have: 0, settled: 0, notStreams: 0 }; for (const id of ids) { if (known.settled[id]) { plan.settled++; continue; } const { live, date } = await streamInfo(path.join(dataDir, id)); if (!live || !STREAM_STATUSES.has(live)) { plan.notStreams++; continue; } const p = await liveChatPlan(paths, slug, id, config); if (p.kind === "fresh") plan.have++; else if (p.kind === "normalize") plan.candidates.push({ id, date, action: "normalize" }); else if (p.kind === "fetch") plan.candidates.push({ id, date, action: "fetch", url: p.url, platform: p.platform }); else if (p.kind === "no-fetcher" || p.kind === "not-live") plan.settled++; } plan.candidates.sort((a, b) => b.date.localeCompare(a.date) || a.id.localeCompare(b.id)); return plan; } export type ChatBacklogResult = NonNullable; export type RunChatBacklogOpts = { paths: Paths; slug: string; config: ChannelConfig; cookiePolicy?: ResolvedCookiePolicy; onLog: (line: string) => void; signal: AbortSignal; drainSignal?: AbortSignal; limit?: number; jobId?: string; downloadedAtRun?: number; // A chat landed (fetched or normalized): the job's itemLanded. onChat?: (id: string) => void; // Test seams. run?: ChatRunner; sleep?: (ms: number, signal: AbortSignal) => Promise; gapMs?: () => number; now?: () => Date; }; function sleepFor(ms: number, signal: AbortSignal): Promise { return new Promise((resolve) => { if (signal.aborted || ms <= 0) return resolve(); const t = setTimeout(resolve, ms); signal.addEventListener("abort", () => { clearTimeout(t); resolve(); }, { once: true }); }); } export async function runChatBacklog(opts: RunChatBacklogOpts): Promise { const now = opts.now ?? (() => new Date()); const sleep = opts.sleep ?? sleepFor; const startedAt = now().toISOString(); const state = await readChatBacklogState(opts.paths, opts.slug); const plan = await planChatBacklog(opts.paths, opts.slug, opts.config, state); opts.onLog( `Chat backlog of ${opts.slug}: ${plan.candidates.length} stream chat(s) to get` + ` (${plan.candidates.filter((c) => c.action === "normalize").length} already on disk, only normalized);` + ` ${plan.have} here, ${plan.settled} known to have none, ${plan.notStreams} video(s) not streams.` + (opts.limit ? ` At most ${opts.limit} this run.` : ""), ); const result: ChatBacklogResult = { ...(opts.jobId ? { jobId: opts.jobId } : {}), startedAt, endedAt: startedAt, complete: false, fetched: 0, normalized: 0, none: 0, failed: 0, remaining: plan.candidates.length, ...(opts.downloadedAtRun !== undefined ? { downloadedAtRun: opts.downloadedAtRun } : {}), }; const save = async () => { result.endedAt = now().toISOString(); state.lastRun = { ...result }; await writeChatBacklogState(opts.paths, opts.slug, state); }; // The batch downloads' gap between two videos (runYtdlp's subtitle pass // takes the same): the pause, plus the platform's pace above its base. const sleepSeconds = opts.config.sleepBetweenDownloadsSeconds ?? getSettings().sleepBetweenDownloadsSeconds; const platformOfChannel = channelPlatform(opts.config); const gapMs = opts.gapMs ?? (() => downloadGapMs( sleepSeconds, channelPaceSeconds(opts.config), staticSleepRequestsSeconds(platformOfChannel), { minSeconds: platformMinGapSeconds(platformOfChannel) }, )); let fetchedOnce = false; let failuresInARow = 0; let attempted = 0; for (const c of plan.candidates) { if (opts.signal.aborted) { result.stopped = "cancelled"; break; } if (opts.drainSignal?.aborted) { result.stopped = "drained"; break; } if (opts.limit && attempted >= opts.limit) { result.stopped = `the run's limit (${opts.limit})`; break; } attempted++; const videoDir = path.join(opts.paths.channelsDir, opts.slug, "data", c.id); try { if (c.action === "normalize") { const out = await normalizeLiveChat({ videoDir, channelSlug: opts.slug, ...(opts.config.name ? { configName: opts.config.name } : {}), force: true, log: (m) => opts.onLog(`${m}\n`), }); if (out.status !== "skipped") { result.normalized++; opts.onChat?.(c.id); } result.remaining--; continue; } const platform = c.platform ?? "youtube"; const held = await heldPlatformRefusal(platform, "The chat backlog", opts.paths); if (held) { result.stopped = held; break; } const cooling = await platformCooldownRemainingMs(platform, opts.paths); if (cooling > 0) { result.stopped = `${platform} is in a rate-limit cooldown (${Math.ceil(cooling / 1000)}s remaining)`; break; } if (fetchedOnce) { const ms = gapMs(); if (ms > 0) { opts.onLog(`Sleeping ${Math.round(ms / 1000)}s before the next chat...`); await sleep(ms, AbortSignal.any([opts.signal, ...(opts.drainSignal ? [opts.drainSignal] : [])])); if (opts.signal.aborted || opts.drainSignal?.aborted) { result.stopped = opts.signal.aborted ? "cancelled" : "drained"; break; } } } fetchedOnce = true; const out = await fetchLiveChat({ paths: opts.paths, slug: opts.slug, videoId: c.id, videoUrl: c.url!, channelConfig: opts.config, ...(opts.cookiePolicy ? { cookiePolicy: opts.cookiePolicy } : {}), onLog: opts.onLog, signal: opts.signal, onPlatformBackoff: () => recordDownloadBackoff(platform, opts.paths), onPlatformClean: () => recordPlatformClean(platform, opts.paths), ...(opts.run ? { run: opts.run } : {}), }); failuresInARow = 0; result.remaining--; if (out.status === "fetched") { result.fetched++; opts.onChat?.(c.id); } else { result.none++; state.settled[c.id] = { at: now().toISOString(), why: "no-chat" }; } } catch (err) { const message = (err as Error).message; if (opts.signal.aborted) { result.stopped = "cancelled"; break; } result.failed++; failuresInARow++; opts.onLog(`${c.id}: ${message}`); if (/rate-limited/i.test(message)) { result.stopped = "a rate limit (the platform's cooldown is recorded)"; break; } if (failuresInARow >= CHAT_BACKLOG_MAX_FAILURES_IN_A_ROW) { result.stopped = `${CHAT_BACKLOG_MAX_FAILURES_IN_A_ROW} failures in a row`; break; } } } result.complete = result.remaining === 0; await save(); opts.onLog( `Chat backlog of ${opts.slug}: ${result.fetched} fetched, ${result.normalized} normalized, ${result.none} with no chat, ` + `${result.failed} failed; ${result.remaining} left${result.stopped ? ` — stopped: ${result.stopped}` : ""}.`, ); return result; } // Is a backlog job of this channel queued or running? export function activeChatBacklogJob(slug: string): string | null { const live = getRegistry() .list() .find((j) => j.kind === FETCH_CHAT_BACKLOG_KIND && j.channelSlug === slug && (j.status === "queued" || j.status === "running")); return live?.id ?? null; } export type StartChatBacklogOpts = { paths: Paths; slug: string; config: ChannelConfig; cookiePolicy: ResolvedCookiePolicy; limit?: number; queueKey?: string; // The download lane's: behind any foreground job on the queue. background?: boolean; downloadedAtRun?: number; run?: ChatRunner; }; // THE JOB. Every refusal before any job, in the sentences the rest of the // app uses: a channel whose text cannot be read, one already running a // backlog, a held platform or one cooling down (`info`: the source is resting). export async function startChatBacklogJob(opts: StartChatBacklogOpts): Promise { const { paths, slug, config } = opts; try { await assertChannelTextReadable(paths, slug, config); } catch (err) { return { ok: false, error: (err as Error).message }; } const active = activeChatBacklogJob(slug); if (active) return { ok: false, info: true, error: `a chat backlog of ${slug} is already queued or running (job ${active})` }; const platform = channelPlatform(config) ?? "unknown"; if (platform !== "youtube") return { ok: false, info: true, error: noChatFetcherSentence(platform) }; const held = await heldPlatformRefusal(platform, "The chat backlog", paths); if (held) return { ok: false, info: true, error: held }; const remainingMs = await platformCooldownRemainingMs(platform, paths); if (remainingMs > 0) { return { ok: false, info: true, error: `${platform} is in a rate-limit cooldown (${Math.ceil(remainingMs / 1000)}s remaining). The chat backlog can run once it lapses.`, }; } return runManagedFunction({ kind: FETCH_CHAT_BACKLOG_KIND, queueKey: resolveQueueKey(downloadQueueKey(config), opts.queueKey), paths, channelSlug: slug, ...(opts.background ? { background: true } : {}), spec: { kind: FETCH_CHAT_BACKLOG_KIND, slug, params: { ...(opts.limit ? { limit: opts.limit } : {}), ...(opts.queueKey ? { queueKey: opts.queueKey } : {}), }, }, fn: async (onLog, signal, _progress, ctx) => { const result = await runChatBacklog({ paths, slug, config, cookiePolicy: opts.cookiePolicy, onLog, signal, drainSignal: ctx.drainSignal, jobId: ctx.jobId, ...(opts.limit ? { limit: opts.limit } : {}), // The report's downloaded count this run starts from (the lane's // "has anything been downloaded since?"). downloadedAtRun: opts.downloadedAtRun ?? (await readChannelSnapshotShared(paths, slug))?.totals?.downloaded, onChat: () => ctx.itemLanded(), ...(opts.run ? { run: opts.run } : {}), }); if (result.failed > 0 && result.fetched + result.normalized + result.none === 0 && !result.stopped?.startsWith("the run's limit")) { throw new Error(`${result.failed} chat fetch(es) failed and none landed${result.stopped ? ` — stopped: ${result.stopped}` : ""}`); } }, }); }