"use server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { listChannelSlugs } from "yt-dlp-transcript-common/controller/channels"; import { COMPRESS_RATE_BYTES, COMPRESS_RATE_RECORDING_BYTES, compressText, type CompressTextKind, type CompressTextResult, } from "yt-dlp-transcript-common/controller/compressText"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { runManagedFunction, type StreamActionResult, } from "yt-dlp-transcript-common/jobs/streamCommand"; import { waitWhileRenderHeld } from "yt-dlp-transcript-common/lib/renderHold"; // COMPRESS TEXT: the `compress-text` job, as `pnpm ops compress-text` posts it // (`/api/ops/compress-text`). The work and its rules are // common/controller/compressText.ts and lib/storedText-write-server.ts. // // ONE QUEUE MACHINE-WIDE, ONE JOB PER CHANNEL: one file at a time across every // channel. Per channel because the job is a media writer of THAT channel — // the media guard asks it before the job starts, and a move of the channel's // media refuses while it runs (`channelMediaWriters` finds it by its slug). // So `limit` is per job, and is taken only with one channel named. STARTED BY // A PERSON ONLY (jobKinds.ts `startedByPerson`): a restart closes a queued one // and resumes no interrupted one — it removes originals (a restore: stored // copies); the job's Retry (a person) re-runs it, and a re-run continues. const COMPRESS_QUEUE = "compress-text"; export type CompressTextActionResult = | { ok: false; error: string } | { ok: true; dryRun: true; result: CompressTextResult } | { ok: true; dryRun: false; verify: boolean; restore: boolean; jobs: { slug: string; jobId: string }[]; jobIds: string[]; skipped: { slug: string; reason: string }[]; }; // A job running for this video: one of its own, or a batch with a task on it. // The compress job itself is not counted. function videoBusy(slug: string, id: string, self: string): boolean { return getRegistry() .list() .some( (j) => j.id !== self && j.status === "running" && j.channelSlug === slug && (j.videoId === id || (j.tasks ?? []).some((t) => t.id === id)), ); } // A live recording in progress anywhere: the reads go slower. function recordingRunning(): boolean { return getRegistry() .list() .some((j) => j.kind === "record-live" && j.status === "running"); } const sleep = (ms: number, signal?: AbortSignal) => new Promise((resolve) => { const t = setTimeout(resolve, ms); signal?.addEventListener( "abort", () => { clearTimeout(t); resolve(); }, { once: true }, ); }); export async function compressTextJobAction( slug: string, opts: { limit?: number; verify?: boolean; restore?: boolean; kinds?: CompressTextKind[] } = {}, ): Promise { const paths = getPaths(); return runManagedFunction({ kind: "compress-text", queueKey: COMPRESS_QUEUE, paths, channelSlug: slug, spec: { kind: "compress-text", slug, params: { ...(opts.limit !== undefined ? { limit: opts.limit } : {}), ...(opts.verify ? { verify: true } : {}), ...(opts.restore ? { restore: true } : {}), ...(opts.kinds?.length ? { kinds: opts.kinds } : {}), }, }, fn: async (onLog, signal, _progress, ctx) => { const result = await compressText({ paths, slugs: [slug], ...(opts.limit !== undefined ? { limit: opts.limit } : {}), ...(opts.verify ? { verify: true } : {}), ...(opts.restore ? { restore: true } : {}), ...(opts.kinds?.length ? { kinds: opts.kinds } : {}), onLog, signal, drainSignal: ctx.drainSignal, isBusy: (s, id) => videoBusy(s, id, ctx.jobId), rate: () => (recordingRunning() ? COMPRESS_RATE_RECORDING_BYTES : COMPRESS_RATE_BYTES), waitForRender: () => waitWhileRenderHeld({ sleep, onLog: (l) => onLog(`${l}\n`), what: "compress-text", signal }), sleep, }); const failed = result.channels.reduce((a, c) => a + (c.failed?.length ?? 0) + (c.problems?.length ?? 0), 0); if (result.stopped === "cancelled") throw new Error("Stopped: cancelled. A re-run continues."); if (failed > 0) throw new Error(`${failed} file(s) failed or did not verify — see the lines above.`); }, }); } // `slugs` (default: every channel). A dry run answers with the plan and // writes nothing; a real run (a check, a restore) starts one job per channel // that has a raw chat to compress or a stopped run to finish (a stored one to // check, or to restore). export async function compressTextAction(input: { slugs?: string[]; // Default: the live chat alone (controller/compressText.ts). kinds?: CompressTextKind[]; dryRun?: boolean; verify?: boolean; restore?: boolean; limit?: number; }): Promise { const paths = getPaths(); const all = (await listChannelSlugs(paths)).sort(); const missing = (input.slugs ?? []).filter((s) => !all.includes(s)); if (missing.length) return { ok: false, error: `Channel(s) not found: ${missing.join(", ")}` }; if (input.limit !== undefined && input.slugs?.length !== 1) { return { ok: false, error: '"limit" is per channel: name exactly one in "slugs"' }; } const slugs = input.slugs ?? all; const plan = await compressText({ paths, slugs, dryRun: true, ...(input.restore ? { restore: true } : {}), ...(input.kinds?.length ? { kinds: input.kinds } : {}), onLog: () => {}, }); if (input.dryRun) return { ok: true, dryRun: true, result: plan }; const jobs: { slug: string; jobId: string }[] = []; const skipped: { slug: string; reason: string }[] = []; for (const line of plan.channels) { if (line.refused) { skipped.push({ slug: line.slug, reason: line.refused }); continue; } const work = input.verify ? line.storedFiles : (line.pending ?? 0); if (work === 0) continue; const r = await compressTextJobAction(line.slug, { ...(input.limit !== undefined ? { limit: input.limit } : {}), ...(input.verify ? { verify: true } : {}), ...(input.restore ? { restore: true } : {}), ...(input.kinds?.length ? { kinds: input.kinds } : {}), }); if (r.ok) jobs.push({ slug: line.slug, jobId: r.jobId }); else skipped.push({ slug: line.slug, reason: r.error }); } return { ok: true, dryRun: false, verify: input.verify === true, restore: input.restore === true, jobs, jobIds: jobs.map((j) => j.jobId), skipped, }; }