// A REFRESH'S STAGE 1 — fetch what is new, then build (umtool R4), on its own: // a refresh runs it first (./task.ts), and R5's recurring reports run it on a // tick before a series' edition. No model, nothing written but what the // editor's own actions write. // // per channel a video channel: `sync`, then `refresh-report` (its report, // so the bucket is current) and `transcribe-bucket` for the // recordings that LANDED (the bucket against the one before — // never the channel's whole backlog); a posts channel: // `fetch-posts`. A platform held or cooling down is skipped, // and says so (polite scraping). Channels run side by side; // the editor's platform queues pace them. // the build the site whose build holds the channels, `publish build` // (never forced: a fresh build is not rebuilt; through the // publish lock; never a deploy), waited for. // // Every action's job is waited for (polled; a step still going after // `waitMs` is left running and said). Each step is logged and traced. import type { JobOf } from "../research/state"; import type { ResearchEditor } from "../research/tools"; import type { TraceInput, TraceStepStatus } from "../tasks/trace"; import type { QuoteReaders } from "./delta"; import type { BuildStep, FetchStep } from "./types"; // What a refresh asks of the editor (the controller passes the editor's own, // in process — controller/reportRefresh.ts refreshHooksOf; the tests stub them). export type RefreshHooks = { // One ops action (the research run's door: the same refusals, same words). editor: ResearchEditor; jobOf: JobOf; // A channel of this editor: what it is and on which platform; null: none. // `localLibrary`: a local media library channel (a library, no URL) — // nothing online to sync, so its sync is a routine skip. channelOf: (slug: string) => Promise<{ kind: "video" | "posts"; platform?: string; localLibrary?: true } | null>; // Why a fetch on this platform would be refused now (held, cooling down), or null. platformRefusal?: (platform: string) => Promise; // A channel's "downloaded, not transcribed" recordings (its report's bucket), or null. bucketOf?: (slug: string) => Promise; // R4.1: why transcription would not run now (the pool paused, no worker // enabled), or null. Asked before transcribe-bucket is queued: a held // transcription is skipped and said, never waited on for hours. transcriptionHeld?: () => Promise; // The site to build so a build holds the channels (the parent's corpus // first); null with why when there is none to build. siteOf: (channels: string[], prefer: string | null) => Promise<{ site: string | null; reason?: string }>; // When the build that holds the channels was made (ms), to say whether it moved. builtAt?: (channels: string[], prefer: string | null) => Promise; // Open the corpus the delta and the update read (deps.corpus becomes it). openCorpus: (channels: string[], prefer: string | null) => Promise<{ source: string; origin: string; build?: string }>; // A recording on disk (every track, its platform state), else the build's cues. recordOf?: QuoteReaders["recordOf"]; // Why an update of about `usd` would be refused by a cap now, or null. capRefusal: (usd: number) => Promise; // Polling (default 5 s) and how long one step is waited for (default 6 h). pollMs?: number; waitMs?: number; sleep?: (ms: number, signal?: AbortSignal) => Promise; }; // Stage 1 needs only the editor's side. export type FetchHooks = Pick; export type FetchAndBuild = { fetch: FetchStep[]; build: BuildStep | null; warnings: string[] }; const sleeper = (ms: number, signal?: AbortSignal) => new Promise((resolve, reject) => { if (signal?.aborted) return reject(signal.reason ?? new Error("cancelled")); const t = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms); const onAbort = () => { clearTimeout(t); reject(signal?.reason ?? new Error("cancelled")); }; signal?.addEventListener("abort", onAbort, { once: true }); }); const ENDED = new Set(["done", "failed", "cancelled", "archived"]); /** Stage 1 over `scope.channels`: each channel's fetches, then the build (see the head of this file). */ export async function fetchAndBuild( scope: { channels: readonly string[] }, hooks: FetchHooks, o: { // The corpus the work was read from (its build is preferred). prefer?: string | null; signal?: AbortSignal; log?: (line: string) => void; trace?: (e: TraceInput) => void; // After the fetches, before the build (a refresh keeps them on disk). onFetched?: (steps: FetchStep[]) => void | Promise; // false: fetch, no build. build?: boolean; } = {}, ): Promise { const channels = [...scope.channels]; const prefer = o.prefer ?? null; const log = (l: string) => o.log?.(l); const trace = (e: TraceInput) => o.trace?.(e); const sleep = hooks.sleep ?? sleeper; const poll = hooks.pollMs ?? 5000; const waitMs = hooks.waitMs ?? 6 * 3600_000; const warnings: string[] = []; // Every job ended (or the wait's limit): each job's status, "waiting" for one still going. const waitJobs = async (ids: string[]): Promise> => { const out: Record = {}; const t0 = Date.now(); for (;;) { o.signal?.throwIfAborted(); let pending = 0; for (const id of ids) { if (out[id] && out[id] !== "waiting") continue; const j = await hooks.jobOf(id).catch(() => null); if (!j) out[id] = "unknown"; else if (ENDED.has(j.status)) out[id] = j.status; else { out[id] = "waiting"; pending++; } } if (!pending || Date.now() - t0 >= waitMs) return out; await sleep(poll, o.signal); } }; // One action, then its job waited for. const runAndWait = async (channel: string, action: string, args: Record): Promise => { let answer: Record; try { answer = await hooks.editor.run(action, args); } catch (e) { const step: FetchStep = { channel, action, status: "refused", reason: (e as Error).message }; trace({ t: "fetch", ...step }); log(`${channel}: ${action} refused — ${step.reason}`); return step; } const jobId = typeof answer.jobId === "string" ? answer.jobId : undefined; const ids = Array.isArray(args.ids) ? (args.ids as string[]) : undefined; if (!jobId) { const step: FetchStep = { channel, action, status: "done", reason: "nothing queued" }; trace({ t: "fetch", ...step }); return step; } trace({ t: "fetch", channel, action, status: "queued", jobId, ...(ids ? { ids } : {}) }); log(`${channel}: ${action} queued (job ${jobId})`); const st = (await waitJobs([jobId]))[jobId] ?? "unknown"; const status: TraceStepStatus = st === "done" ? "done" : st === "cancelled" ? "cancelled" : st === "waiting" ? "waiting" : "failed"; const step: FetchStep = { channel, action, status, jobId, ...(ids ? { ids } : {}), ...(status === "done" ? {} : { reason: st === "waiting" ? `still running after ${Math.round(waitMs / 60_000)} min: read what is there` : `the job ended ${st}` }), }; trace({ t: "fetch", ...step }); log(`${channel}: ${action} ${status}${step.reason ? ` (${step.reason})` : ""}`); return step; }; const skip = (channel: string, action: string, reason: string, routine = false): FetchStep => { const step: FetchStep = { channel, action, status: "skipped", reason, ...(routine ? { routine: true } : {}) }; trace({ t: "fetch", ...step }); log(`${channel}: ${action} skipped — ${reason}`); return step; }; const fetchChannel = async (slug: string): Promise => { const ch = await hooks.channelOf(slug).catch(() => null); if (!ch) return [skip(slug, "sync", "not a channel of this editor")]; if (ch.localLibrary) return [skip(slug, "sync", "a local media library: nothing online to sync", true)]; const first = ch.kind === "posts" ? "fetch-posts" : "sync"; if (ch.platform && hooks.platformRefusal) { const no = await hooks.platformRefusal(ch.platform).catch(() => null); if (no) return [skip(slug, first, no)]; } if (ch.kind === "posts") return [await runAndWait(slug, "fetch-posts", { slug })]; const steps: FetchStep[] = []; const before = hooks.bucketOf ? await hooks.bucketOf(slug).catch(() => null) : null; const sync = await runAndWait(slug, "sync", { slug }); steps.push(sync); if (sync.status !== "done" || !hooks.bucketOf) return steps; // What landed: the channel's report again, its bucket against the one before. steps.push(await runAndWait(slug, "refresh-report", { slug })); const after = await hooks.bucketOf(slug).catch(() => null); if (before === null || after === null) { steps.push(skip(slug, "transcribe-bucket", before === null ? "no channel report before the sync: what landed is not known" : "the channel's report does not read")); return steps; } const had = new Set(before); const landed = after.filter((id) => !had.has(id)); if (!landed.length) { steps.push(skip(slug, "transcribe-bucket", "nothing new to transcribe", true)); return steps; } // R4.1: a held transcription is not waited on (the step would sit for hours). const held = hooks.transcriptionHeld ? await hooks.transcriptionHeld().catch(() => null) : null; if (held) { steps.push({ ...skip(slug, "transcribe-bucket", `transcription is paused (${held}) — ${landed.length} recording${landed.length === 1 ? " waits; a later run reads it" : "s wait; a later run reads them"} once transcribed`), ids: landed, }); return steps; } steps.push(await runAndWait(slug, "transcribe-bucket", { slug, ids: landed })); return steps; }; const fetch = (await Promise.all(channels.map((c) => fetchChannel(c)))).flat(); // A step that failed, was cancelled or is still going is a warning (a // refused or skipped one is said by the caller; a routine skip never is). for (const s of fetch) if (s.status === "failed" || s.status === "waiting" || s.status === "cancelled") warnings.push(`${s.channel}: ${s.action} ${s.status}${s.reason ? ` — ${s.reason}` : ""}`); await o.onFetched?.(fetch); if (o.build === false) return { fetch, build: null, warnings }; // The build: the site whose build holds the channels, built if stale. const target = await hooks.siteOf(channels, prefer).catch((e: Error) => ({ site: null, reason: e.message })); let build: BuildStep; if (!target.site) { build = { site: null, status: "skipped", reason: target.reason ?? "no site's build holds these channels" }; } else { const was = hooks.builtAt ? await hooks.builtAt(channels, prefer).catch(() => null) : null; let answer: Record | null = null; build = { site: target.site, status: "refused" }; try { answer = await hooks.editor.run("publish", { verb: "build", siteId: target.site, force: false }); } catch (e) { build = { site: target.site, status: "refused", reason: (e as Error).message }; } if (answer) { const jobs = Array.isArray(answer.jobs) ? (answer.jobs as { jobId?: unknown }[]).map((j) => j.jobId).filter((x): x is string => typeof x === "string") : []; if (!jobs.length) { const skipped = Array.isArray(answer.skipped) ? (answer.skipped as { reason?: unknown }[]).map((s) => String(s.reason ?? "")).filter(Boolean) : []; build = { site: target.site, status: "skipped", reason: skipped[0] ?? "nothing to build" }; } else { trace({ t: "build", site: target.site, status: "queued", jobIds: jobs }); log(`build ${target.site}: queued (${jobs.join(", ")})`); const st = await waitJobs(jobs); const bad = jobs.filter((j) => st[j] !== "done"); const worst = bad.length ? st[bad[0]!]! : "done"; build = bad.length ? { site: target.site, status: worst === "waiting" ? "waiting" : worst === "cancelled" ? "cancelled" : "failed", jobIds: jobs, reason: `job ${bad[0]} ${worst === "waiting" ? "still running" : `ended ${worst}`}: the corpus is read as it stands`, } : { site: target.site, status: "done", jobIds: jobs }; } } const is = hooks.builtAt ? await hooks.builtAt(channels, prefer).catch(() => null) : null; if (is) build.builtAt = new Date(is).toISOString(); if (build.status === "done" && was !== null && is !== null && is <= was) build.reason = "the build was current: nothing to rebuild"; } trace({ t: "build", ...build }); log(`build: ${build.site ?? "none"} ${build.status}${build.reason ? ` — ${build.reason}` : ""}`); if (build.status !== "done" && build.status !== "skipped") warnings.push(`the build ${build.site ?? ""} ${build.status}: ${build.reason ?? ""}`.trim()); return { fetch, build, warnings }; }