"use server"; import path from "node:path"; import { safeRevalidate } from "../lib/safeRevalidate"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { clearCompactionMarker, clearKeptFailedEncode, compactSavedVideos, effectiveCompactionSettings, listCompactionMarkers, listKeptFailedEncodes, listKeptOriginals, listCompactionReview, planCompaction, type CompactItem, type CompactPlan, type CompactionReviewRow, } from "yt-dlp-transcript-common/controller/compactSavedVideos"; import { SavedAlternateRefusal, recordOriginalReview, } from "yt-dlp-transcript-common/lib/savedVideo-server"; import type { SavedVideoAlternate } from "yt-dlp-transcript-common/lib/savedVideo"; import type { SavedVideoCompactionSettings } from "yt-dlp-transcript-common/lib/savedVideoCompaction"; import { runManagedFunction, type StreamActionResult, } from "yt-dlp-transcript-common/jobs/streamCommand"; import { channelTextStall } from "yt-dlp-transcript-common/lib/channelMedia"; // COMPACT SAVED VIDEOS: the `compact-saved-videos` job, as `pnpm ops // compact-saved-videos` posts it (`/api/ops/compact-saved-videos`). The work // and its rules are common/controller/compactSavedVideos.ts. // // ONE QUEUE MACHINE-WIDE: an encode is hours of CPU and a write of gigabytes // on the archive drive; one video at a time across every channel. const COMPACT_QUEUE = "compact"; export type CompactOverrides = Partial>; export type CompactSavedVideosActionResult = | { ok: false; error: string } | { ok: true; dryRun: true; plan: CompactPlan } | { ok: true; dryRun: false; plan: CompactPlan; jobs: { slug: string; jobId: string }[]; jobIds: string[]; skipped: { slug: string; reason: string }[]; }; function settingsFor(overrides: CompactOverrides): SavedVideoCompactionSettings { return effectiveCompactionSettings(getSettings().savedVideoCompaction, overrides); } // One channel's list as one job on the compact queue. The job carries its ids, // its mode and its overrides in its spec, so a replay (the job's Retry, after a // cancel or a restart) re-runs the same list, resuming the chunks already // encoded. The boot pass never re-runs it by itself: it may drop originals. export async function compactChannelVideosAction( slug: string, ids: string[], opts: { mode: "explicit" | "select"; overrides?: CompactOverrides; retryFailed?: boolean; reverify?: boolean; belowThreshold?: boolean }, ): Promise { const wanted = [...new Set(ids)]; if (wanted.length === 0) return { ok: false, error: "No video ids to compact." }; const paths = getPaths(); const config = await readChannelConfig(paths, slug); if (!config) return { ok: false, error: `Channel "${slug}" not found` }; const overrides = opts.overrides ?? {}; return runManagedFunction({ kind: "compact-saved-videos", queueKey: COMPACT_QUEUE, paths, channelSlug: slug, spec: { kind: "compact-saved-videos", slug, params: { ids: wanted, mode: opts.mode, ...overrides, ...(opts.retryFailed ? { retryFailed: true } : {}), ...(opts.reverify ? { reverify: true } : {}), ...(opts.belowThreshold ? { belowThreshold: true } : {}), }, }, fn: async (onLog, signal, _progress, ctx) => { // The settings as they are when the job STARTS (it may have queued). const result = await compactSavedVideos({ paths, jobId: ctx.jobId, settings: settingsFor(overrides), items: wanted.map((id) => ({ slug, id })), mode: opts.mode, ...(opts.retryFailed ? { retryFailed: true } : {}), ...(opts.reverify ? { reverify: true } : {}), ...(opts.belowThreshold ? { belowThreshold: true } : {}), onLog, signal, drainSignal: ctx.drainSignal, }); if (result.compacted.length) safeRevalidate([`/channels/${slug}`, "/saved-videos"]); if (result.stopped && result.stopped !== "drained" && result.stopped !== "cancelled") { throw new Error(`Stopped: ${result.stopped}. A re-run resumes.`); } if (result.failed.length > 0) { throw new Error(`${result.failed.length} video(s) not compacted: ${result.failed.map((f) => `${f.id} — ${f.reason}`).join("; ")}`); } }, }); } // An explicit list, or (`select`) what the settings' selector picks across the // store (or `slugs`). A dry run answers with the plan — every item's line, the // estimate, the disk, why one is skipped — and writes nothing. A real run // starts one job per channel with something to compact. export async function compactSavedVideosAction(input: { items?: CompactItem[]; select?: boolean; slugs?: string[]; dryRun?: boolean; retryFailed?: boolean; reverify?: boolean; belowThreshold?: boolean; overrides?: CompactOverrides; }): Promise { if (!input.select && !input.items?.length) { return { ok: false, error: 'Name the videos ("items": [{slug, id}]) or ask the selector ("select": true).' }; } if (input.select && input.items?.length) { return { ok: false, error: '"items" and "select" are two ways to ask: pass one.' }; } const paths = getPaths(); const settings = settingsFor(input.overrides ?? {}); const plan = await planCompaction({ paths, settings, ...(input.items ? { items: input.items } : {}), ...(input.select ? { select: true } : {}), ...(input.slugs?.length ? { slugs: input.slugs } : {}), ...(input.retryFailed ? { retryFailed: true } : {}), ...(input.reverify ? { reverify: true } : {}), ...(input.belowThreshold ? { belowThreshold: true } : {}), }); if (input.dryRun) return { ok: true, dryRun: true, plan }; const bySlug = new Map(); for (const i of plan.items) { if (!i.compact) continue; bySlug.set(i.slug, [...(bySlug.get(i.slug) ?? []), i.id]); } const jobs: { slug: string; jobId: string }[] = []; const skipped: { slug: string; reason: string }[] = []; for (const [slug, ids] of bySlug) { let result: StreamActionResult; try { result = await compactChannelVideosAction(slug, ids, { mode: input.select ? "select" : "explicit", ...(input.overrides ? { overrides: input.overrides } : {}), ...(input.retryFailed ? { retryFailed: true } : {}), ...(input.reverify ? { reverify: true } : {}), ...(input.belowThreshold ? { belowThreshold: true } : {}), }); } catch (e) { skipped.push({ slug, reason: (e as Error).message }); continue; } if (!result.ok) { skipped.push({ slug, reason: result.error }); continue; } // Nobody reads the stream: the job's log is on disk (see the ops layer). void result.stream.cancel(); jobs.push({ slug, jobId: result.jobId }); } if (bySlug.size === 0) { // Nothing to start: the plan's lines say why each one was skipped. const why = plan.items.map((i) => `${i.slug}/${i.id}: ${i.reason ?? "?"}`).join("; "); return { ok: false, error: `Nothing to compact${why ? ` — ${why}` : ""}.` }; } if (jobs.length === 0) { return { ok: false, error: skipped.map((s) => `${s.slug}: ${s.reason}`).join("; ") }; } return { ok: true, dryRun: false, plan, jobs, jobIds: jobs.map((j) => j.jobId), skipped }; } // The review list: every compacted video and what its original waits for. export async function compactionReviewList(opts: { slug?: string } = {}): Promise<{ rows: CompactionReviewRow[]; notAnswering: string[]; }> { const notAnswering: string[] = []; const rows = await listCompactionReview({ paths: getPaths(), settings: getSettings().savedVideoCompaction, ...(opts.slug ? { channelSlug: opts.slug } : {}), notAnswering, }); return { rows, notAnswering: notAnswering.sort() }; } // A PERSON'S REVIEW of a compacted copy (the video page's "The compacted copy // is good", `pnpm ops review-compacted-original`): recorded on the original's // entry. It deletes nothing — it is what lets drop-saved-alternate, with // `confirmOriginal`, drop the original of a video gone from its platform. export async function reviewCompactedOriginalAction( slug: string, videoId: string, opts: { note?: string; by?: string; formerOriginal?: string } = {}, ): Promise<{ ok: true; original: SavedVideoAlternate; watched: string } | { ok: false; error: string }> { const paths = getPaths(); const config = await readChannelConfig(paths, slug); if (!config) return { ok: false, error: `No such channel: ${slug}` }; if (channelTextStall(config)) { return { ok: false, error: "Not recorded: this channel's drive is not answering." }; } try { const original = await recordOriginalReview(path.join(paths.channelsDir, slug, "data", videoId), { at: new Date().toISOString(), by: opts.by ?? "editor", ...(opts.note?.trim() ? { note: opts.note.trim() } : {}), }, opts.formerOriginal ? { formerOriginal: opts.formerOriginal } : {}); safeRevalidate([`/channels/${slug}/videos/${videoId}`, "/saved-videos"]); return { ok: true, original, watched: original.review?.forSha256 ?? "" }; } catch (e) { if (e instanceof SavedAlternateRefusal) return { ok: false, error: e.message }; throw e; } } // Every pointer that keeps an original or a former one, or has a drop in // flight: what a rollback past this release would mistreat (OPERATING.md). export async function keptOriginalsList(opts: { slug?: string } = {}) { const notAnswering: string[] = []; const rows = await listKeptOriginals({ paths: getPaths(), ...(opts.slug ? { channelSlug: opts.slug } : {}), notAnswering }); return { rows, notAnswering: notAnswering.sort() }; } // The failed encodes kept in the store (never active), and clearing one. export async function keptFailedEncodesAction(opts: { clear?: CompactItem } = {}) { const paths = getPaths(); const cleared = opts.clear ? { ...opts.clear, ...(await clearKeptFailedEncode(paths, opts.clear)) } : null; const rows = await listKeptFailedEncodes(paths); return { rows, bytes: rows.reduce((n, r) => n + (r.kept?.bytes ?? 0), 0), ...(cleared ? { cleared } : {}) }; } // The `.compacting.json` markers, and clearing a stale one. export async function compactionMarkersAction(opts: { clear?: CompactItem } = {}) { const paths = getPaths(); const cleared = opts.clear ? { ...opts.clear, ...(await clearCompactionMarker(paths, opts.clear)) } : null; return { markers: await listCompactionMarkers(paths), ...(cleared ? { cleared } : {}) }; }