// EVERY LIVE RECORDING OF A CHANNEL, ONE ROW PER RUN — `channels//live-recordings.json` // ({rows: [...]}, beside pending-keep.json). // // A recording's own record (`data//live-recording.json`) is where a run // says what it is doing; it is not where a FAILURE can be relied on to stay. A // run that made data// and recorded nothing removes the dir (every // enumerator reads a dir with metadata as "fetched"), and the record with it. // This file is the durable side: record-live writes its row on every save of // the record, and nothing but the cap below ever removes a row — never a // failed run, never a row that needs a person. A row is cleared from // attention by a person (acknowledge) or by a later run of the same id that // lands (supersededBy). // // Written only through these functions (one atomic write per change, under the // file's lock). // // A FILE THAT DOES NOT READ IS NEVER OVERWRITTEN. Its rows are the failures // nobody has acknowledged yet: a write that finds it unparseable (or // unreadable) renames it aside — `live-recordings.json.corrupt-`, beside // it — starts a new file, and names the kept one in the new file's `setAside`, // which needs a person (the listing counts it) until acknowledged. A rename // that fails is a write that fails: the file stays as it is. import path from "node:path"; import { rename } from "node:fs/promises"; import type { Paths } from "./paths"; import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server"; import type { KeptPart, RemovedPart, LiveFailureClass, LivePart, LiveRecordingRecord, LiveRecordingStatus, LostSpan, LiveBootRestart, LiveInsurance, LiveJoin, LiveRestarts, LiveSpaceHeld, LiveTranscriptRedo, LiveVerification, MissingStream, StartRecovery, StreamCoverage, } from "./liveCapture"; export const LIVE_RECORDINGS_FILENAME = "live-recordings.json"; // Rows kept per channel; past it the oldest rows that need nobody go first. export const LIVE_RECORDINGS_MAX_ROWS = 500; export type LiveRecordingRow = { id: string; url: string; platform: string; // When the run started (the record's startedAt): with `id`, the row's key. startedAt: string; endedAt?: string; status: LiveRecordingStatus; jobId?: string; fromStart: boolean; separate?: boolean; error?: string; attempts: number; fallback?: "live-edge"; lost?: LostSpan; mustKeep: boolean; note?: string; // What record-live was asked (its body's recording keys, no `id`/`dryRun`/ // `preclip`): what "Record again" asks again. request?: Record; streamStartedAt?: string; parts: LivePart[]; landedPart?: number; failureClass?: LiveFailureClass; missingStream?: MissingStream; stoppedBy?: "operator" | "shutdown" | "crash"; keptParts?: KeptPart[]; removedParts?: RemovedPart[]; coverage?: StreamCoverage; startRecovery?: StartRecovery; restarts?: LiveRestarts; // This run was started by the boot pass for the interrupted run of this // startedAt; and, on an interrupted run, what the boot pass did with it. resumeOf?: string; restart?: LiveBootRestart; insurance?: LiveInsurance; joins?: LiveJoin[]; spaceHeld?: LiveSpaceHeld[]; endedBy?: { class: LiveFailureClass; message: string; at: string }; awaitingResume?: string[]; transcriptRedo?: LiveTranscriptRedo; verification?: LiveVerification; skippedFragments?: { count: number; positions: number[] }; landedWhileLive?: { at: string; unrecordedSeconds: number | null; why: string }; offline?: { since: string; reads: number }; // What the landing kept: this run's file stored ("new"), or the store's. kept?: "new" | "existing"; acknowledgedAt?: string; acknowledgedBy?: string; // The run (its jobId, else its startedAt) that later landed this id. supersededBy?: string; }; function fileOf(paths: Pick, slug: string): string { return path.join(paths.channelsDir, slug, LIVE_RECORDINGS_FILENAME); } function coerceRow(raw: unknown): LiveRecordingRow | null { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; const r = raw as LiveRecordingRow; if (typeof r.id !== "string" || typeof r.startedAt !== "string" || typeof r.status !== "string") return null; return { ...r, url: typeof r.url === "string" ? r.url : "", platform: typeof r.platform === "string" ? r.platform : "unknown", fromStart: r.fromStart === true, attempts: typeof r.attempts === "number" ? r.attempts : 0, mustKeep: r.mustKeep === true, parts: Array.isArray(r.parts) ? r.parts : [], }; } // A live-recordings.json that did not read, renamed aside by a write. export type SetAsideFile = { // Its name beside live-recordings.json. file: string; at: string; reason: "unreadable" | "unparseable"; acknowledgedAt?: string; acknowledgedBy?: string; }; export type LiveRecordingsFile = { rows: LiveRecordingRow[]; setAside: SetAsideFile[]; // The file as it is now does not read (the next write sets it aside). problem: "unreadable" | "unparseable" | null; }; function coerceSetAside(raw: unknown): SetAsideFile[] { if (!Array.isArray(raw)) return []; return raw.filter( (x): x is SetAsideFile => !!x && typeof x === "object" && typeof (x as SetAsideFile).file === "string" && typeof (x as SetAsideFile).at === "string", ); } export async function loadLiveRecordingsFile(paths: Pick, slug: string): Promise { const read = await readJsonFile(fileOf(paths, slug)); if (!read.ok) return { rows: [], setAside: [], problem: read.reason === "absent" ? null : read.reason }; const value = read.value as { rows?: unknown; setAside?: unknown } | null; if (!value || typeof value !== "object" || Array.isArray(value)) return { rows: [], setAside: [], problem: "unparseable" }; const rows = Array.isArray(value.rows) ? value.rows.map(coerceRow).filter((r): r is LiveRecordingRow => r !== null) : []; return { rows, setAside: coerceSetAside(value.setAside), problem: null }; } export async function loadLiveRecordingRows(paths: Pick, slug: string): Promise { return (await loadLiveRecordingsFile(paths, slug)).rows; } // Needs a person, as the row stands (the listing adds `interrupted` for a // `recording` no job runs). // failed, interrupted always (the listing lets an // interruption the boot pass restarted // go quiet only while the NEW run's // part grows) // cancelled when the stream was must-keep (a // person's Cancel of any other stream // is quiet) // recorded from the live edge the stream's start is lost — unless // a from-start try beside it was // landed and holds the whole stream // (startRecovery "recovered") // restarts refused the stream was live and its recorder // stalled or died once too often // joined with a gap parts joined into the landed file // with seconds of the stream in none // one stream missing it landed without video or audio // parts kept on disk (keptParts) until acknowledged, whatever lands // later: a later recording does not // decide what happens to them // Cleared by an acknowledgement; all but the kept parts also by a later // recording that holds the whole stream (supersededBy). export function rowNeedsAttention( r: Pick & Partial>, ): boolean { if (r.acknowledgedAt) return false; if (r.keptParts && r.keptParts.length > 0) return true; // DESIGN-4: a landed file with fragments skipped, one not verified whole, // a part that lost its kept fragments — loud after the landing too. if (r.skippedFragments && r.skippedFragments.count > 0) return true; if (r.parts?.some((p) => (p.skippedFragments?.count ?? 0) > 0 || p.fragmentsDropped)) return true; if (r.verification && r.verification.state !== "verified") return true; if (r.supersededBy) return false; // DESIGN-5 4: landed while the stream was still live — until acknowledged. if (r.landedWhileLive) return true; // REVIEW-7 1: the state cannot be read (offline): nothing records meanwhile. if (r.offline) return true; if (r.parts?.some((p) => p.resumeDamaged)) return true; // REVIEW-6 4: landed SHORT of an ended stream's own duration — the rest is // in no file (and the archive line stops any later download): a person, // "download the VOD now". if (r.status === "landed" && r.coverage?.basis === "duration" && r.coverage.covers === false) return true; // Parts left in staging with their state, to be resumed: a resume, or a // person (DESIGN-3; a later run that did not resume them lists them too). if (r.awaitingResume && r.awaitingResume.length) return true; // The transcript is (or may be) the replaced shorter file's and no // transcription was asked (REVIEW-LF-4 2). if (r.transcriptRedo && (r.transcriptRedo.verdict === "unknown" || !r.transcriptRedo.jobId)) return true; if (r.status === "failed" || r.status === "interrupted") return true; if (r.status === "cancelled" && r.mustKeep === true) return true; if (r.fallback === "live-edge" && r.startRecovery?.state !== "recovered") return true; // A span of the stream in no part (REVIEW-3 3.1), until a part holds it. if (r.lost && r.startRecovery?.state !== "recovered") return true; if (r.restarts?.refused) return true; // Waiting out a restart bound: nothing records meanwhile. if (r.restarts?.waiting) return true; // A recorder (or a join) not started for want of disk. if (r.spaceHeld && r.spaceHeld.length) return true; // The stream went private or was removed while it was recorded. if (r.endedBy && r.endedBy.class === "private") return true; // Landed as parts joined with a gap: those seconds are in no part. if (r.joins?.some((j) => j.kind === "gap")) return true; return r.missingStream !== undefined; } function cap(rows: LiveRecordingRow[]): LiveRecordingRow[] { if (rows.length <= LIVE_RECORDINGS_MAX_ROWS) return rows; const out = [...rows]; for (let i = 0; i < out.length && out.length > LIVE_RECORDINGS_MAX_ROWS; ) { const r = out[i]!; if (r.status !== "recording" && !rowNeedsAttention(r)) out.splice(i, 1); else i++; } return out; } async function mutate( paths: Pick, slug: string, // Returns its answer and whether it changed anything (nothing changed: // nothing written). fn: (rows: LiveRecordingRow[], setAside: SetAsideFile[]) => [T, boolean], now: () => Date = () => new Date(), ): Promise { const file = fileOf(paths, slug); return withJsonFileLock(file, async () => { const cur = await loadLiveRecordingsFile(paths, slug); let forced = false; if (cur.problem) { // Never overwritten: renamed aside first (a failed rename throws, and // nothing is written). const at = now().toISOString(); const aside = `${LIVE_RECORDINGS_FILENAME}.corrupt-${at.replace(/[:.]/g, "-")}`; await rename(file, path.join(path.dirname(file), aside)); cur.setAside.push({ file: aside, at, reason: cur.problem }); forced = true; } const [out, changed] = fn(cur.rows, cur.setAside); if (changed || forced) { await writeJsonAtomic(file, { rows: cap(cur.rows), ...(cur.setAside.length ? { setAside: cur.setAside } : {}) }); } return out; }); } // The row a run's record makes. export function rowOfRecord( id: string, rec: LiveRecordingRecord, extra: { note?: string; request?: Record } = {}, ): Omit { return { id, url: rec.url, platform: rec.platform, startedAt: rec.startedAt, ...(rec.endedAt ? { endedAt: rec.endedAt } : {}), status: rec.status, ...(rec.jobId ? { jobId: rec.jobId } : {}), fromStart: rec.fromStart, ...(rec.separate !== undefined ? { separate: rec.separate } : {}), ...(rec.error ? { error: rec.error } : {}), attempts: rec.attempts ?? rec.parts.length, ...(rec.fallback ? { fallback: rec.fallback } : {}), ...(rec.lost ? { lost: rec.lost } : {}), mustKeep: rec.mustKeep === true, ...(extra.note ? { note: extra.note } : {}), ...(extra.request ? { request: extra.request } : {}), ...(rec.streamStartedAt ? { streamStartedAt: rec.streamStartedAt } : {}), parts: rec.parts.map((p) => ({ ...p })), ...(rec.landedPart !== undefined ? { landedPart: rec.landedPart } : {}), ...(rec.kept ? { kept: rec.kept } : {}), ...(rec.endedBy ? { endedBy: { ...rec.endedBy } } : {}), ...(rec.awaitingResume && rec.awaitingResume.length ? { awaitingResume: [...rec.awaitingResume] } : {}), ...(rec.transcriptRedo ? { transcriptRedo: { ...rec.transcriptRedo } } : {}), ...(rec.verification ? { verification: { ...rec.verification } } : {}), ...(rec.skippedFragments ? { skippedFragments: { ...rec.skippedFragments } } : {}), ...(rec.landedWhileLive ? { landedWhileLive: { ...rec.landedWhileLive } } : {}), ...(rec.offline ? { offline: { ...rec.offline } } : {}), ...(rec.spaceHeld && rec.spaceHeld.length ? { spaceHeld: rec.spaceHeld.map((x) => ({ ...x })) } : {}), ...(rec.failureClass ? { failureClass: rec.failureClass } : {}), ...(rec.missingStream ? { missingStream: rec.missingStream } : {}), ...(rec.stoppedBy ? { stoppedBy: rec.stoppedBy } : {}), ...(rec.keptParts && rec.keptParts.length ? { keptParts: rec.keptParts.map((k) => ({ ...k, files: k.files.map((f) => ({ ...f })) })) } : {}), ...(rec.removedParts && rec.removedParts.length ? { removedParts: rec.removedParts.map((r) => ({ ...r })) } : {}), ...(rec.coverage ? { coverage: { ...rec.coverage } } : {}), ...(rec.startRecovery ? { startRecovery: { ...rec.startRecovery } } : {}), ...(rec.restarts ? { restarts: { ...rec.restarts, at: [...rec.restarts.at] } } : {}), ...(rec.resumeOf ? { resumeOf: rec.resumeOf } : {}), ...(rec.insurance ? { insurance: { ...rec.insurance } } : {}), ...(rec.joins && rec.joins.length ? { joins: rec.joins.map((j) => ({ ...j, parts: [...j.parts] })) } : {}), }; } // Whether a row holds the whole stream: landed, from its start, with video and // audio, and as long as the stream within the coverage's tolerance // (controller/recordLive.ts streamCoverage). Only such a run supersedes. A run // that fell back to the live edge qualifies only when a from-start try beside // it was the landed file and covers (startRecovery "recovered"). export function rowCoversStream( r: Pick & Partial>, ): boolean { const startHeld = !r.fallback || r.startRecovery?.state === "recovered"; // (Never a landing made while the stream still read live: DESIGN-5 3.) return r.status === "landed" && r.fromStart && startHeld && !r.missingStream && r.coverage?.covers === true && !(r as { landedWhileLive?: unknown }).landedWhileLive; } // Writes (or rewrites) the run's row. A run that lands the WHOLE stream // (rowCoversStream) marks every earlier row of the same id that still needs a // person as superseded by it. A live-edge landing, a run asked not to start at // the start, or a short partial never does. export async function upsertLiveRecordingRow( paths: Pick, slug: string, row: Omit, ): Promise { await mutate(paths, slug, (rows) => { const i = rows.findIndex((r) => r.id === row.id && r.startedAt === row.startedAt); const prev = i >= 0 ? rows[i]! : null; const next: LiveRecordingRow = { ...row, ...(prev?.acknowledgedAt ? { acknowledgedAt: prev.acknowledgedAt } : {}), ...(prev?.acknowledgedBy ? { acknowledgedBy: prev.acknowledgedBy } : {}), ...(prev?.supersededBy ? { supersededBy: prev.supersededBy } : {}), ...(prev?.restart ? { restart: prev.restart } : {}), }; if (i >= 0) rows[i] = next; else rows.push(next); if (rowCoversStream(row)) { const by = row.jobId ?? row.startedAt; for (const r of rows) { if (r === next || r.id !== row.id || r.supersededBy) continue; if (r.status === "recording" || rowNeedsAttention(r)) r.supersededBy = by; } } return [undefined, true]; }); } // A person has seen it: every row of `id` that needs a person (or the one // run `startedAt` names) is acknowledged. The rows stay. export async function acknowledgeLiveRecordingRows( paths: Pick, slug: string, id: string, opts: { by?: string; startedAt?: string; now?: Date; interrupted?: (r: LiveRecordingRow) => boolean } = {}, ): Promise { const at = (opts.now ?? new Date()).toISOString(); return mutate(paths, slug, (rows) => { let n = 0; for (const r of rows) { if (r.id !== id || r.acknowledgedAt) continue; if (opts.startedAt && r.startedAt !== opts.startedAt) continue; if (!rowNeedsAttention(r) && !opts.interrupted?.(r)) continue; r.acknowledgedAt = at; if (opts.by) r.acknowledgedBy = opts.by; n++; } return [n, n > 0]; }); } // A person has seen a set-aside file (its name, or every one of the channel's // when `file` is not given). The file stays where it is. export async function acknowledgeSetAsideFiles( paths: Pick, slug: string, opts: { file?: string; by?: string; now?: Date } = {}, ): Promise { const at = (opts.now ?? new Date()).toISOString(); return mutate(paths, slug, (_rows, setAside) => { let n = 0; for (const f of setAside) { if (f.acknowledgedAt || (opts.file && f.file !== opts.file)) continue; f.acknowledgedAt = at; if (opts.by) f.acknowledgedBy = opts.by; n++; } return [n, n > 0]; }); } // Changes one row (by id and startedAt) under the file's lock. False: no such // row. `fn` returns false to write nothing. export async function patchLiveRecordingRow( paths: Pick, slug: string, id: string, startedAt: string, fn: (row: LiveRecordingRow) => boolean | void, ): Promise { return mutate(paths, slug, (rows) => { const r = rows.find((x) => x.id === id && x.startedAt === startedAt); if (!r) return [false, false]; const changed = fn(r) !== false; return [true, changed]; }); }