Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 21cfb2746af992c5c1350e1ca38af6c221ca9998
parent f5e2981b81344783a468c921cbe85202a78cc42c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 22 Nov 2026 05:50:58 -0500

record-live: REVIEW-7 4-9: the check can be run again, a failed merge is set aside, the lock before the repair, room for a raw copy

- 4: the landing's check is given the fragment length (the tracks'
  tolerance is max(2 s, 2 fragments) as documented). A part whose
  fragments were dropped for want of disk skips the byte check (said). A
  join with a gap is never "verified whole".
  - reverifyLiveLanding, `pnpm ops live-recording-verify` (route, client,
    help) and the row's "Verify again" button check a failed or pending
    landing again. Verified and the stream done, the stream files, state and
    fragments go; the row and the record say so.
- 5: a strict merge that fails renames its output to a scratch name and
  says the next step; it is never left at a finished name.
- 6: the stem lock is taken before the repair at all three resume sites
  and handed to the resume. The lock file is created by link() of a fully
  written temp file and updated by rename.
- 8: a raw source's copy needs its size plus the floor free; when that is
  short it is not landed, said plainly, everything kept.
- 9: the record-live help (COMMANDS.md regenerated) says resume or reuse,
  then a fresh part, then the live edge; the offline rule; and the
  behind-insurance.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 3++-
Mcommon/controller/recordLive.test.ts | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/recordLive.ts | 193++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/lib/liveVerify-server.test.ts | 8++++++++
Aeditor/app/api/ops/live-recording-verify/route.ts | 24++++++++++++++++++++++++
Meditor/app/channels/[slug]/liveMediaActions.ts | 19++++++++++++++++++-
Meditor/app/components/LiveRecordingActions.tsx | 20++++++++++++++++++++
Meditor/app/components/LiveRecordingsAttention.tsx | 8+++++++-
Mscripts/archilyzer-ops.mjs | 34+++++++++++++++++++++++-----------
9 files changed, 386 insertions(+), 39 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -147,7 +147,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `remote-listing` | remote-listing lists an Odysee or BitChute channel upstream and diffs it against what it holds: {"slug"}. One flat-playlist read on the platform's queue (refused while it is held or cooling down; a 429 backs it off), nothing written. `get remote-listing <slug>` waits for the job and prints {listed, held, notHeld: \[{id, url}\], heldNotListed: \[id\], ...} on stdout. | | | `attach-media` | attach-media copies each held video's file out of a LOCAL archive into the saved-video store, as its source container (nothing fetched): {"slug", "source"} — an absolute path to a directory, a .zip (read in place) or a .7z. The id is the folder's trailing "(&lt;id&gt;)", else the file's yt-dlp suffix; "items": \[{"id", "path"}\] names exact files (path inside the source), "match" narrows the folders by regex. "createRecords": true writes a record for a video the channel does not hold; "replace": true re-attaches over a saved container. "fillDates": true gives a held record attach-media made (saved-video.json origin "local-archive") that has no upload\_date the date from its folder's description.txt, through the metadata history ("dated" in the log and summary); a record with a date, or one attach-media did not make, is never touched. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous, and dated) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | `pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa\|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait` | | `import-media` | import-media makes ONE file from outside the archive a normal transcribed item: {"slug", "path"} (absolute) and which record — "url" (the source page: one metadata-only pass makes or refreshes the record, under the id the archive keys it by — Rumble's URL id), "id" (a record already here) or "meta": {"title", "date"?, "duration"?, "description"?} (by hand). ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to mp4 (+faststart), never re-encoded. It lands in the saved-video store only when longer than a container already there ("replace": true lands it anyway), then audio.&lt;fmt&gt;, the archive line and media-import.json. "move": true removes the original once the copy verifies; "audio": false lands the container only; "transcribe": true queues a transcribe-one job (held by any pause; without it the transcription lane takes it by its rules); "doNotClean": true marks it, with "note". "dryRun": true says what it would do and writes nothing. A directory, a .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only). | `pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait`<br>`pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait` | -| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/&lt;channel&gt;" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". A from-start attempt that records nothing (yt-dlp: "The downloaded file is empty"), or only one of its two streams, is tried again at +60 and +180 s, then from the live edge at 0, +60 and +180 s (each wait jittered). The failure's class decides: ended, private/removed, members-only/login and a full or unwritable disk are not retried; a 429 or the bot check gets ONE more try after 15 min, then stops; empty, network and unknown failures keep the schedule; a Cancel ends it. The row records the class (failureClass). A live-edge fallback says what it lost (the first N min of the stream) and needs a person. The landing never removes a part it is not known to contain (an earlier run's, one from another point of the stream, one it cannot land): those are kept in staging and listed (keptParts) until acknowledged. The reply is {jobId, kind, "check"}: the `get live-recordings` command that answers for it. --wait-started returns once a FROM-START part's bytes grow (the recording's row on stdout, exit 0; a run asked fromStart: false, any part's), exit 3 when it records only from the live edge (the start is lost), exit 1 with the reason it failed; 15 minutes by default, --wait-timeout overrides. After a live-edge fallback, from its start is tried again BESIDE the live-edge recording (never touching it): every 15 min (jittered), one try at a time, at most 8; a try that holds the whole stream when landed recovers the start (startRecovery). Each recorder has a stall watchdog: no growth for liveRecording.stallMinutes (10) stops that recorder, its part kept; a from-start recorder (dead, stalled, or stopped by a shutdown) is RESUMED in place from yt-dlp's .ytdl state — the same part — and only when that is impossible does a live-edge recorder follow: while the stream still reads live (one metadata read; an exit is read twice, a minute apart) a new part records from the live edge — at most 6 restarts an hour and 24 a run (restarts); past them the row says the stream is live and NOT recorded. "insurance"?: true \| "whole" \| false — a live-edge recorder beside a from-start recording of a stream already live, until the start has caught up (+5 min), or for the whole stream; absent, on exactly when the stream is marked keep ("doNotClean", the record's Do-not-clean marker, a pending keep) when the recording starts. Its part goes at landing only when the landed file holds the whole stream; otherwise it is kept and listed. After an editor restart, a run the shutdown or a crash interrupted restarts by itself (once per run, 3 an hour per stream, never after a Cancel; liveRecording. autoRestartOnBoot): the new run reads the stream's state first — live, it records; ended, it lands what is in staging; unreadable, it starts nothing and the row needs a person. When no single part holds the stream but two or more together hold more, they are joined (-c copy): an overlap at the point their sound shares, a gap stated by the clock; the joined file lands only when PROVEN (its length, its sound around every join), its parts removed only after; the joins are on the row (joins) and in data/&lt;id&gt;/live-joins.json (each segment's place in the stream and in the file). Unproven, or codecs that differ: the longest lands and the rest are kept. A gap needs a person. | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","doNotClean":true}' --wait-started` | +| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/&lt;channel&gt;" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". A from-start attempt that records nothing (yt-dlp: "The downloaded file is empty"), or only one of its two streams, is tried again at +60 and +180 s, then from the live edge at 0, +60 and +180 s (each wait jittered). The failure's class decides: ended, private/removed, members-only/login and a full or unwritable disk are not retried; a 429 or the bot check gets ONE more try after 15 min, then stops; empty, network and unknown failures keep the schedule; a Cancel ends it. The row records the class (failureClass). A live-edge fallback says what it lost (the first N min of the stream) and needs a person. The landing never removes a part it is not known to contain (an earlier run's, one from another point of the stream, one it cannot land): those are kept in staging and listed (keptParts) until acknowledged. The reply is {jobId, kind, "check"}: the `get live-recordings` command that answers for it. --wait-started returns once a FROM-START part's bytes grow (the recording's row on stdout, exit 0; a run asked fromStart: false, any part's), exit 3 when it records only from the live edge (the start is lost), exit 1 with the reason it failed; 15 minutes by default, --wait-timeout overrides. After a live-edge fallback, from its start is tried again BESIDE the live-edge recording (never touching it): every 15 min (jittered), one try at a time, at most 8; a try that holds the whole stream when landed recovers the start (startRecovery). Each recorder has a stall watchdog: no growth for liveRecording.stallMinutes (10) stops that recorder, its part kept; while the stream still reads live (one metadata read; an exit is read twice, a minute apart) a from-start recorder (dead, stalled, stopped by a shutdown, or ended by itself) is RESUMED in place — the same files, every kept fragment reused — and only when that cannot be proven does a FRESH part record from the stream's start, then the live edge (6 restarts an hour, waited out, never an end); while the state cannot be read for the network nothing is started and no restart spent. "insurance"?: true \| "whole" \| false — a live-edge recorder beside a from-start recording of a stream already live, until the start has caught up (+5 min), or for the whole stream; absent, on when the stream is marked keep ("doNotClean", the record's Do-not-clean marker, a pending keep), and also when a from-start part shows itself more than 10 min behind the live edge (liveRecording.insuranceWhenBehind). Its part goes at landing only when the landed file holds the whole stream; otherwise it is kept and listed. After an editor restart, a run the shutdown or a crash interrupted restarts by itself (once per run, 3 an hour per stream, never after a Cancel; liveRecording. autoRestartOnBoot): the new run reads the stream's state first — live, it records; ended, it lands what is in staging; unreadable, it starts nothing and the row needs a person. When no single part holds the stream but two or more together hold more, they are joined (-c copy): an overlap at the point their sound shares, a gap stated by the clock; the joined file lands only when PROVEN (its length, its sound around every join), its parts removed only after; the joins are on the row (joins) and in data/&lt;id&gt;/live-joins.json (each segment's place in the stream and in the file). Unproven, or codecs that differ: the longest lands and the rest are kept. A gap needs a person. | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","doNotClean":true}' --wait-started` | | `local-media-configure` | local-media-configure gives a video channel a LOCAL MEDIA LIBRARY: {"slug", "sourceId", "directory"} — a stable lowercase id and an absolute directory on the editor server whose recordings stay where they are (never copied, moved or deleted). Written through the channel config; a channel that already has one is refused, and so is queued or running channel work. Playback is not set. Synchronous. | `pnpm ops local-media-configure --json '{"slug":"demo-local","sourceId":"library-1","directory":"/mnt/recordings"}'` | | `local-media-preview` | local-media-preview scans the library and writes nothing: {"slug"} -&gt; {preview: {sourceToken, counts, candidates}}. Each .mp4 directly in the directory (not its subdirectories) with its same-named .info.json and .vtt (or .srt) is "new", "existing" (its record is held) or "issue" (with issues). The sourceToken and a candidate's fingerprint (or preparationFingerprint, when it has no .info.json) are what the other local-media actions take. An unreachable library is an error, never an empty preview. | `pnpm ops local-media-preview --json '{"slug":"demo-local"}'` | | `local-media-prepare` | local-media-prepare reviews details for a recording with no .info.json and writes nothing: {"slug", "sourceToken", "media", "sourceFingerprint" (the candidate's preparationFingerprint), "details": {"mode": "inspect" \| "manual", "title", "recordedDate"? (YYYY-MM-DD), "durationSeconds"? (manual)}} -&gt; {review: {metadata, fingerprint}}. "inspect" measures the duration with ffprobe. Import it with local-media-import, the review's fingerprint and "preparation": {"sourceFingerprint", "details"}. | `pnpm ops local-media-prepare --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","sourceFingerprint":"<fp>","details":{"mode":"inspect","title":"A talk"}}'` | @@ -156,6 +156,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `live-preclip` | live-preclip transcribes and mines a recording WHILE it records: {"slug", "id", "action"?: "start" (default) \| "stop" \| "status" \| "finalize"}, and for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"? (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the umtool project, &lt;id&gt;-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/&lt;id&gt;/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` | | `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (&lt;id&gt;-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` | | `live-recording-ack` | live-recording-ack {"slug", "id", "startedAt"?, "by"?} acknowledges every run of the record that needs a person (or the one run startedAt names): listed still, counted no more. {"slug", "file"} acknowledges a set-aside live-recordings.json (it stays where it is). /review's Acknowledge. | `pnpm ops live-recording-ack --json '{"slug":"demo-yt","id":"<videoId>"}'` | +| `live-recording-verify` | live-recording-verify {"slug", "id", "startedAt"?} checks a landed file whose verification failed or never ran against the stream files it was made from (packets per track, the tracks' spans, a hole scan, each stream file byte for byte its kept fragments); verified and the stream confirmed done, those stream files, their state and fragments are removed; else the row says why and nothing is. The row's Verify button. | | | `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | | | `compact-saved-videos` | compact-saved-videos re-encodes saved videos to AV1 (SVT-AV1, settings savedVideoCompaction: crf 36, preset 8, a keyframe every 5 s, the source's height, Kick and Twitch above 30 fps to 30, every other stream and the chapters copied), verifies the copy and makes it the active one; the original stays beside it ("keptAs": "original"): {"items": \[{"slug", "id"}, ...\]} names videos (deliberately stored only: a pin, an explicit persist, a requested or landed container -- never keep-latest, never persist-kept's override); {"select": true, "slugs"?} asks the selector (and platform, height and video bitrate) and is a DRY RUN unless "dryRun": false. A named video the selector would not pick is refused unless "belowThreshold": true (the refusal says how little it saves). "dryRun": true answers each video's line -- size, bitrate, height, fps, the estimate (size, hours), the disk it needs, or why it is skipped. "crf", "preset", "maxFps", "chunkMinutes" override the settings for the run; "retryFailed": true encodes again one whose last checks failed; "reverify": true checks its KEPT encode again without encoding (a chunk whose own content failed is encoded again). One job per channel on the compact queue, one video at a time, each chunk through the heavy slot; a Retry resumes. The checks include a whole-file comparison and excerpts across every chunk join. dropOriginal is "keep" by default; under "after-verify" the original is dropped in a later step once the copy re-checks from disk -- never for a video not freshly checked on its platform (get compaction-review). There is no backup of the store: after a drop the compacted copy is the only copy. | | | `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. "formerOriginal": "&lt;file&gt;" reviews the active copy that replaced a former original instead. | | diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -4977,3 +4977,119 @@ test("REVIEW-7 (the re-arm removal): a keep-marked recording's insurance, stoppe await run.catch(() => {}); assert.equal(insurers, 1, `not started again on the restart: ${insurers}`); }); + +// --- REVIEW-7 4-8 -------------------------------------------------------------------------- + +test("REVIEW-7 4: a verification that failed is checked AGAIN by reverifyLiveLanding — verified and the stream done, the stream files go and the row says verified", { timeout: 60_000 }, async () => { + const id = "exmplr7ver1"; + let live = true; + const r = await incidentRun( + id, + resumableYtdlp(async ({ write }) => { + await write(7200); + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, verifyMerged: async () => ({ ok: false, why: "a transient read error" }) }, refresh: { stillLive: () => live } }, + ); + await r.run; + assert.equal((await rowOf(id))[0]!.verification?.state, "failed"); + assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`))); + const { reverifyLiveLanding } = await import("./recordLive"); + const out = await reverifyLiveLanding({ paths, slug: YT_SLUG, id, channelConfig: YT_CONFIG, deps: { verifyMerged: async () => ({ ok: true }) } }); + assert.equal(out.ok && out.verified, true, JSON.stringify(out)); + assert.deepEqual(await left(id), [], "the stream files, state and fragments went"); + assert.equal((await rowOf(id))[0]!.verification?.state, "verified"); +}); + +test("REVIEW-7 4: a part whose fragments were dropped for want of disk skips the byte check (said), and can be verified", { timeout: 60_000 }, async () => { + const id = "exmplr7drp1"; + let live = true; + let free = 1e15; + const { run, log } = await incidentRun( + id, + resumableYtdlp(async ({ write }) => { + await write(3000); + free = 1e9; + await new Promise((r) => setTimeout(r, 150)); + free = 1e15; + await write(7200); + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, freeBytes: async () => free }, refresh: { stillLive: () => live } }, + ); + await run; + assert.ok(log.some((l) => /byte check .* is skipped: they were dropped/.test(l))); + assert.equal((await rowOf(id))[0]!.verification?.state, "verified"); +}); + +test("REVIEW-7 5: a merge that fails leaves its output set aside (never at the finished name the next run would land)", async () => { + const { resolvePart } = await import("./recordLive"); + const dir = path.join(ROOT, "merge5"); + await mkdir(dir, { recursive: true }); + const stem = ".exmplr7mrg1.live-x.ytdlp"; + await writeFile(path.join(dir, `${stem}.f136.mp4`), "format=mp4;seconds=60;a=none;"); + await writeFile(path.join(dir, `${stem}.f140.m4a`), "format=mp4;seconds=60;v=none;"); + const { livePartFiles: livePartFilesOf } = await import("../lib/liveCapture"); + const g = livePartFilesOf("exmplr7mrg1", await readdir(dir)).find((x) => x.stem === stem)!; + await assert.rejects( + resolvePart(g, dir, { + probe: fakeProbe, + merge: async (args) => { + await writeFile(args[args.length - 1]!, "format=mov,mp4;seconds=60;"); + throw new Error("ffmpeg's merge reported: Packet corrupt"); + }, + say: () => {}, + }), + /set aside as .*merge-failed-/, + ); + const names = await readdir(dir); + assert.ok(!names.some((n) => /\.merged\.(mp4|mkv)$/.test(n)), `no finished merge left: ${names.join(", ")}`); + assert.ok(names.some((n) => /\.merge-failed-\d+\./.test(n))); +}); + +test("REVIEW-7 6: with a live recorder holding the stem's lock, the boot's resume is refused BEFORE any repair — the torn tail and its fragments untouched", { timeout: 60_000 }, async () => { + const id = "exmplr7lck1"; + const { stem, startedAt } = await waitingAtShutdown(id, 3000); + const v = `${stem}.${FAKE_V}`; + await writeFile(`${v}-Frag52`, "seconds=60;#52;xx"); + await appendFile(v, "seconds=60;"); + const sizeBefore = (await stat(v)).size; + // An orphan recorder of the last process still holds it (this pid is alive). + await writeFile(`${stem}.rec.lock`, JSON.stringify({ pid: 2 ** 22 + 777, recorderPid: process.pid, at: new Date().toISOString() })); + await askBoot(id, startedAt); + let live = true; + const r = await incidentRun( + id, + resumableYtdlp(async ({ write }) => { + await write(7200); + live = false; + return "end"; + }), + { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + await r.run.catch(() => {}); + void sizeBefore; + assert.ok(r.log.some((l) => /another recorder holds/.test(l)), "refused by the lock"); + assert.ok(!r.log.some((l) => /truncated from/.test(l)), "no repair under a live writer"); + assert.ok(!r.log.some((l) => /past its state .* removed before the resume/.test(l)), "no fragment removed under it"); + assert.notEqual(outOf(r.calls[0]!), stem, "a fresh part instead"); + await rm(`${stem}.rec.lock`, { force: true }); +}); + +test("REVIEW-7 8: a raw source that must be copied with too little room — not landed, said plainly, everything kept", { timeout: 60_000 }, async () => { + const id = "exmplr7rom1"; + const { run } = await incidentRun( + id, + async (args) => { + await writeFile(`${outOf(args)}.${FAKE_A}`, `format=mp4;seconds=7200;v=none;${"x".repeat(5000)}`); + return okExit; + }, + { meta: { ...YT_META(id), duration: 7200 }, deps: { join: null, merge: fakeMerge, minFreeBytes: 1000, freeBytes: async () => 2000 } }, + ); + await run.catch(() => {}); + const row = (await rowOf(id))[0]!; + assert.match(row.error ?? "", /landed by a copy .* needs .* free/); + assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_A}`)), "kept"); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -53,7 +53,7 @@ import path from "node:path"; import { spawn } from "node:child_process"; import { createWriteStream } from "node:fs"; -import { mkdir, open, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises"; +import { link, mkdir, open, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises"; import { uptime } from "node:os"; import { StringDecoder } from "node:string_decoder"; import { execa } from "execa"; @@ -97,6 +97,7 @@ import { spanWords, ytdlpLiveArgs, type KeptPart, + type LiveVerification, type LiveBootRestartState, type LiveInsurance, type LiveJoinsRecord, @@ -421,6 +422,19 @@ export function isProgressLine(line: string): boolean { return PROGRESS_RE.test(line) && !NEVER_THINNED_RE.test(line); } +// REVIEW-7 4: one fragment's length, from a stream file's kept fragments and +// the landed length (undefined when nothing tells it). +export async function fragmentSecondsOf(dir: string, streams: readonly string[], seconds: number | null): Promise<number | undefined> { + if (!seconds || !streams.length) return undefined; + const names = await readdir(dir).catch(() => [] as string[]); + let n = fragNumbers(streams[0]!, names).length; + if (n < 2) { + const idx = await readYtdlIndex(path.join(dir, streams[0]!)); + n = typeof idx === "number" ? idx : 0; + } + return n > 1 ? seconds / (n - 1) : undefined; +} + // A `.ytdl` state's fragment index, or null when it does not parse. function readYtdlRaw(raw: string): number | null { try { @@ -437,26 +451,33 @@ function readYtdlRaw(raw: string): number | null { // signal) or it was made before the machine last booted (a pid may be // reused): a stale lock is taken over, said. Held by a live process (this // editor's or another's), the recorder is not started on that stem. -export async function takeStemLock( - dir: string, - stem: string, -): Promise<{ ok: true; release: () => Promise<void>; setRecorder: (pid: number) => Promise<void> } | { ok: false; why: string }> { +export type StemLock = { ok: true; release: () => Promise<void>; setRecorder: (pid: number) => Promise<void> }; +export async function takeStemLock(dir: string, stem: string): Promise<StemLock | { ok: false; why: string }> { const file = path.join(dir, `${stem}.rec.lock`); const at = new Date().toISOString(); const body = (recorderPid?: number) => JSON.stringify({ pid: process.pid, ...(recorderPid ? { recorderPid } : {}), at }); for (let tries = 0; tries < 2; tries++) { + // REVIEW-7 6: never a lock a reader can catch empty — written whole to a + // temp file, then linked into place (fails if one is there) or renamed + // over (its update). + const tmp = `${file}.${process.pid}.${Date.now()}.tmp`; try { - const fh = await open(file, "wx"); - await fh.writeFile(body()); - await fh.close(); + await writeFile(tmp, body()); + await link(tmp, file); + await rm(tmp, { force: true }); return { ok: true, release: () => rm(file, { force: true }), // REVIEW-6 9: the RECORDER's pid too — it runs in its own process // group and outlives an editor killed outside the unit. - setRecorder: (pid: number) => writeFile(file, body(pid)).catch(() => {}), + setRecorder: async (pid: number) => { + const t2 = `${file}.${pid}.tmp`; + await writeFile(t2, body(pid)).catch(() => {}); + await rename(t2, file).catch(() => {}); + }, }; } catch (err) { + await rm(tmp, { force: true }); if ((err as NodeJS.ErrnoException).code !== "EEXIST") return { ok: false, why: `its lock could not be made (${(err as Error).message})` }; } const held = await readFile(file, "utf8").then((t) => JSON.parse(t) as { pid?: number; recorderPid?: number; at?: string }, () => null); @@ -847,6 +868,7 @@ export type RecordLiveDeps = { freshFromStart?: boolean; // DESIGN-4 4: the merged file against its stream files, and a file alone. verifyMerged?: (merged: string, streams: readonly string[], signal: AbortSignal) => Promise<{ ok: true } | { ok: false; why: string }>; + // (The landing's fragmentSeconds is in the default; a test's own ignores it.) verifyScan?: (file: string, signal: AbortSignal) => Promise<{ ok: true } | { ok: false; why: string }>; insuranceMarginMs?: number; insuranceGraceMs?: number; @@ -1004,7 +1026,16 @@ export async function resolvePart( `merging them (stream copy) into ${path.basename(output)}.`, ); await rm(output, { force: true }); - await io.merge(mergeStreamsArgs({ video: video.file, audio: audio.file, output, mp4 })); + try { + await io.merge(mergeStreamsArgs({ video: video.file, audio: audio.file, output, mp4 })); + } catch (err) { + // REVIEW-7 5: never left at a name the next run lands as finished. + const aside = path.join(dir, `${g.stem}.merge-failed-${Date.now()}.${mp4 ? "mp4" : "mkv"}`); + await rename(output, aside).catch(() => {}); + throw new Error( + `${(err as Error).message} — the merge's output is set aside as ${path.basename(aside)}; the streams are kept as they are: merge them again by hand, or land the longest stream`, + ); + } const p = await io.probe(output); if (!p?.audioCodec) return { error: `the merge of its streams (${path.basename(output)}) cannot be read` }; return { file: output, seconds: p.seconds, merged: true }; @@ -1610,7 +1641,7 @@ async function recordLiveRunInner( // DESIGN-3: RESUME IN PLACE — this stem's files and state again (same // `-o`), the format pinned to the ids on disk; this run's part of that // stem, or a new entry for it (a boot restart of an earlier run's part). - resume?: { stem: string; formats: string; provenStart?: boolean }; + resume?: { stem: string; formats: string; provenStart?: boolean; lock?: StemLock }; // The run's first attempt, made with no wait before it (main's proof). firstAttempt?: boolean; // DESIGN-4 3: the last resort — this run of the part may skip a @@ -1794,7 +1825,7 @@ async function recordLiveRunInner( } // NOTE 5 (REVIEW-5) — ONE RECORDER PER STEM: a lock file held while the // recorder runs. yt-dlp would let a second writer append to the same file. - const lock = await takeStemLock(slugStore, stem); + const lock = opts.resume?.lock ?? (await takeStemLock(slugStore, stem)); if (!lock.ok) { if (timer) clearInterval(timer); signal.removeEventListener("abort", onJobAbort); @@ -2067,18 +2098,26 @@ async function recordLiveRunInner( // The one repair (DESIGN-4 1), made just before a resume: a torn last // append truncated back, logged with both lengths. Anything it cannot // prove: no resume in place. - const reconcileForResume = async (stem: string): Promise<{ ok: true } | { ok: false; why: string }> => { + // REVIEW-7 6: the stem's lock is taken FIRST — never a repair under a + // recorder that still writes those files — and handed to the resume. + const reconcileForResume = async (stem: string): Promise<{ ok: true; lock: StemLock } | { ok: false; why: string }> => { + const lock = await takeStemLock(slugStore, stem); + if (!lock.ok) return { ok: false, why: lock.why }; + const fail = async (why: string) => { + await lock.release(); + return { ok: false as const, why }; + }; const g = await filesOf(stem); for (const f of g?.streams ?? []) { const r = await reconcileStream(slugStore, f, true, say); - if (!r.ok) return { ok: false, why: r.why }; + if (!r.ok) return fail(r.why); // REVIEW-6 2: no kept fragment past the index may meet the resume. const idx = await readYtdlIndex(path.join(slugStore, f)); - if (typeof idx !== "number") return { ok: false, why: `${f}.ytdl does not read` }; + if (typeof idx !== "number") return fail(`${f}.ytdl does not read`); const gone = await dropFragmentsAbove(slugStore, f, idx); if (gone.length) say(`${f}: fragment(s) ${gone.join(", ")} past its state (${idx}) removed before the resume (a complete one would be refused, 416, and the resume would record nothing).`); } - return { ok: true }; + return { ok: true, lock }; }; // The longest a part's files play (its streams' probes), 0 when unread. // The stream-level length a part holds: a finished file's, else the @@ -2640,7 +2679,8 @@ async function recordLiveRunInner( if (mode === "now" && fromStart && record.fallback === "live-edge" && recovery === null) recovery = recoverStart(index0); // DESIGN-3: a restart after the editor's resumes the interrupted run's // from-start part in place when its state is there. - let bootResume: { stem: string; formats: string; provenStart?: boolean } | null = null; + let bootResume: { stem: string; formats: string; provenStart?: boolean; lock?: StemLock } | null = null; + let bestLock: StemLock | null = null; let reusedFragments: number | null = null; // DESIGN-5 7: ANY run's first from-start attempt (a Record again too) // reuses a part an earlier run left in staging when it can be proven. @@ -2680,12 +2720,12 @@ async function recordLiveRunInner( if (!rc.ok) { say(`${best.stem} is not resumed in place (${rc.why}); a fresh part from the stream's start records instead.`); best = null; - } + } else bestLock = rc.lock; } if (best) { const p = partOfStem.get(best.stem); // The mark the interrupted run earned travels with its file. - bootResume = { stem: best.stem, formats: best.formats, ...(p?.provenStart ? { provenStart: true } : {}) }; + bootResume = { stem: best.stem, formats: best.formats, ...(p?.provenStart ? { provenStart: true } : {}), ...(bestLock ? { lock: bestLock } : {}) }; say(`${resumeOf ? "Restart after the editor restart: " : ""}${best.stem}, an earlier part, is resumed in place from fragment ${best.fragment}${reusedFragments !== null ? " (its state rebuilt from its kept fragments: they are reused, not fetched again)" : ""}.`); // This run holds it now: no row lists it as waiting. const resumed = best.stem; @@ -2950,7 +2990,7 @@ async function recordLiveRunInner( if (st.ok && rc?.ok) { say(`The stream has ended: ${cur.o.part.stem} is resumed once from fragment ${st.fragment} to the stream's end (an ended stream is still served from its start).`); const o = await ytdlpPart(plan.url, "resume", "from-start", "resume to the end; ", { - resume: { stem: cur.o.stem, formats: st.formats }, + resume: { stem: cur.o.stem, formats: st.formats, ...(rc?.ok ? { lock: rc.lock } : {}) }, noWait: true, onStart: onMainStart("from-start", true), onLine: onMainLine, @@ -3054,9 +3094,11 @@ async function recordLiveRunInner( st = { ok: false, why: `fragment ${st.fragment + 1} could not be fetched after ${FRAGMENT_ABORT_WAITS_MS.length} resumes` }; } } + let heldLock: StemLock | null = null; if (st.ok) { const rc = await reconcileForResume(cur.o.stem); if (!rc.ok) st = { ok: false, why: rc.why }; + else heldLock = rc.lock; } if (st.ok) { restarts.count += 1; @@ -3065,7 +3107,7 @@ async function recordLiveRunInner( const before = await streamBytesOf(cur.o.stem); say(`Resume ${(cur.o.part.resumes ?? 0) + 1} of ${cur.o.part.stem} (${why}): the same files from fragment ${st.fragment}, format ${st.formats}.`); const o = await ytdlpPart(plan.url, "resume", "from-start", `resume (${why}); `, { - resume: { stem: cur.o.stem, formats: st.formats }, + resume: { stem: cur.o.stem, formats: st.formats, ...(heldLock ? { lock: heldLock } : {}) }, noWait: true, onStart: onMainStart("from-start", true), onLine: onMainLine, @@ -3820,6 +3862,17 @@ async function recordLiveRunInner( // landing remuxes) is copied, not moved: it stays until the stored file is // verified against it. A merged file is moved (its streams are the source). const rawSource = best.group.streams.includes(path.basename(best.file)) || /\.ts$/i.test(best.file); + // REVIEW-7 8: a copy needs its size plus the floor free where a rename + // needed nothing — checked first, said plainly; everything is kept. + if (rawSource) { + const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => 0); + const need = bestBytes + minFree; + if (free < need) { + return notLanded( + `${path.basename(best.file)} is landed by a copy (it is kept until the stored file is checked against it), which needs ${formatBytes(need)} free on the store's disk; it has ${formatBytes(free)} — everything is kept, free some space and Record again or land it by hand`, + ); + } + } let landed: Awaited<ReturnType<typeof landMediaFile>>; try { landed = await landMediaFile({ @@ -3960,17 +4013,24 @@ async function recordLiveRunInner( const ffprobe = paths.ffprobeBin || "ffprobe"; let verdict: { ok: true } | { ok: false; why: string }; try { + // REVIEW-7 4: the tracks' tolerance is max(2 s, 2 fragments) — the + // fragment's length from the stream file's kept fragments. + const fragmentSeconds = await fragmentSecondsOf(slugStore, mergedFrom, best.seconds); verdict = !landed.container ? { ok: false, why: "there is no stored file to check" } : verifyAgainst.length - ? await (deps.verifyMerged ?? ((m, st, sg) => verifyMerged(ffprobe, m, st, sg)))(landed.container, verifyAgainst, landSignal) - : await (deps.verifyScan ?? ((f, sg) => verifyScan(ffprobe, f, sg)))(landed.container, landSignal); + ? await (deps.verifyMerged ?? ((m, st, sg) => verifyMerged(ffprobe, m, st, sg, { fragmentSeconds })))(landed.container, verifyAgainst, landSignal) + : await (deps.verifyScan ?? ((f, sg) => verifyScan(ffprobe, f, sg, { fragmentSeconds })))(landed.container, landSignal); } catch (err) { verdict = { ok: false, why: (err as Error).message }; } // REVIEW-6 3: before any fragment goes, each stream file is exactly its // kept fragments 1..N, byte for byte (they may be the only whole copy). - if (verdict.ok) { + // (REVIEW-7 4: a part whose fragments were dropped for want of disk has + // none to compare with — the byte check is skipped, said.) + const droppedHere = best.part?.fragmentsDropped ?? (await readStemMarks(slugStore, best.group.stem)).dropped; + if (verdict.ok && droppedHere && mergedFrom.length) say(`The byte check against the kept fragments is skipped: they were dropped for want of disk (${droppedHere}).`); + if (verdict.ok && !droppedHere) { for (const f of mergedFrom) { const eq = await streamEqualsFragments(slugStore, f).catch((e: Error) => ({ ok: false as const, why: e.message })); if (eq && !eq.ok) { @@ -3982,8 +4042,11 @@ async function recordLiveRunInner( const keptBefore = kept.length; if (verdict.ok) { record.verification = { ...record.verification!, state: "verified", at: now().toISOString() }; + const gaps = record.joins?.filter((j) => j.kind === "gap").length ?? 0; say( - stillLive + gaps + ? `The landed file reads clean, but it was joined with ${gaps} gap(s) by the clock: it is NOT whole.` + : stillLive ? `The landed file matches its stream files (${verifyAgainst.length ? verifyAgainst.map((f) => path.basename(f)).join(", ") : "its scan"}) — the stream SO FAR, not the whole: it is still live.` : `The landed file is verified whole (${verifyAgainst.length ? `against ${verifyAgainst.map((f) => path.basename(f)).join(", ")}` : "its scan"}).`, ); @@ -4075,6 +4138,86 @@ export async function transcriptOfReplaced( }; } +// REVIEW-7 4 — THE CHECK, AGAIN: a landing whose verification is `failed` or +// `pending` is checked once more against the stream files it was made from +// (`pnpm ops live-recording-verify`, the row's Verify button). Verified, and +// the stream confirmed done (not landed while live, not gone private), the +// stream files, their state and fragments go and the row says so; otherwise +// the row says why, and nothing is removed. +export async function reverifyLiveLanding(o: { + paths: Paths; + slug: string; + id: string; + startedAt?: string; + channelConfig: ChannelConfig | null; + deps?: { verifyMerged?: RecordLiveDeps["verifyMerged"]; say?: (s: string) => void }; +}): Promise<{ ok: true; verified: boolean; why?: string; removed: string[] } | { ok: false; error: string }> { + const say = o.deps?.say ?? (() => {}); + const rows = (await loadLiveRecordingRows(o.paths, o.slug).catch(() => [])).filter((r) => r.id === o.id); + const row = o.startedAt + ? rows.find((r) => r.startedAt === o.startedAt) + : rows.filter((r) => r.verification && r.verification.state !== "verified").sort((a, b) => b.startedAt.localeCompare(a.startedAt))[0]; + if (!row) return { ok: false, error: `${o.slug}/${o.id}: no landing waiting for its check` }; + const against = row.verification?.against ?? []; + if (!row.verification || row.verification.state === "verified") return { ok: false, error: `${o.slug}/${o.id} (${row.startedAt}): already verified` }; + if (!against.length) return { ok: false, error: `${o.slug}/${o.id} (${row.startedAt}): no stream files are named to check against` }; + const videoDir = path.join(o.paths.channelsDir, o.slug, "data", o.id); + const pointer = await loadSavedVideo(videoDir).catch(() => null); + if (!pointer) return { ok: false, error: `${o.slug}/${o.id}: the store holds no container to check` }; + const stored = savedVideoPath(pointer); + const slugStore = path.join(savedVideoRoot(o.paths, o.channelConfig), o.slug); + const files = against.map((n) => path.join(slugStore, n)); + for (const f of files) if (!(await stat(f).catch(() => null))) return { ok: false, error: `${path.basename(f)} is no longer in staging` }; + const ffprobe = o.paths.ffprobeBin || "ffprobe"; + const fragmentSeconds = await fragmentSecondsOf(slugStore, against, row.coverage?.capturedSeconds ?? null); + let verdict: { ok: true } | { ok: false; why: string } = await (o.deps?.verifyMerged ?? ((m, st, sg) => verifyMerged(ffprobe, m, st, sg, { fragmentSeconds })))( + stored, + files, + new AbortController().signal, + ).catch((e: Error) => ({ ok: false as const, why: e.message })); + const stems = [...new Set(livePartFiles(o.id, against).map((g) => g.stem))]; + const dropped = (await Promise.all(stems.map((st) => readStemMarks(slugStore, st)))).some((m) => m.dropped); + if (verdict.ok && !dropped) { + for (const n of against) { + const eq = await streamEqualsFragments(slugStore, n).catch((e: Error) => ({ ok: false as const, why: e.message })); + if (eq && !eq.ok) { + verdict = { ok: false, why: eq.why }; + break; + } + } + } + const at = new Date().toISOString(); + const confirmedDone = !row.landedWhileLive && row.endedBy?.class !== "private"; + const removed: string[] = []; + if (verdict.ok && confirmedDone) { + const names = await readdir(slugStore).catch(() => [] as string[]); + for (const g of livePartFiles(o.id, names).filter((x) => stems.includes(x.stem))) { + for (const f of [...g.finished, ...g.streams, ...g.scratch]) { + await rm(path.join(slugStore, f), { force: true }); + removed.push(f); + } + } + } + const apply = <T extends { verification?: LiveVerification; keptParts?: KeptPart[] }>(r: T): T => { + r.verification = verdict.ok ? { ...r.verification!, state: "verified", at } : { ...r.verification!, state: "failed", at, why: (verdict as { why: string }).why }; + if (removed.length && r.keptParts) r.keptParts = r.keptParts.filter((k) => !stems.includes(k.stem)); + if (r.keptParts && !r.keptParts.length) delete r.keptParts; + return r; + }; + await patchLiveRecordingRow(o.paths, o.slug, o.id, row.startedAt, (r) => { + apply(r); + }); + // The record beside the video says the same, when it is this run's. + const rec = await liveRecordingSidecar.load(videoDir).catch(() => null); + if (rec && rec.startedAt === row.startedAt) await liveRecordingSidecar.write(videoDir, apply(rec)).catch(() => {}); + say( + verdict.ok + ? `${o.slug}/${o.id}: the landed file is verified${confirmedDone ? `; ${removed.length} file(s) of its stream files removed` : " (the stream is not confirmed done: its stream files are kept)"}.` + : `${o.slug}/${o.id}: NOT verified (${(verdict as { why: string }).why}); nothing is removed.`, + ); + return { ok: true, verified: verdict.ok, ...(verdict.ok ? {} : { why: (verdict as { why: string }).why }), removed }; +} + // Every refusal before any job; then the job. export async function runRecordLiveJob( opts: Omit<RecordLiveJobOpts, "plan">, diff --git a/common/lib/liveVerify-server.test.ts b/common/lib/liveVerify-server.test.ts @@ -125,3 +125,11 @@ test("a video track that STOPPED EARLY (its thread ended, the sound went on): no assert.equal(r.ok, false, JSON.stringify(r)); assert.match((r as { why: string }).why, /stopped short/); }); + +test("REVIEW-7 4: the tracks' tolerance is max(2 s, 2 fragments) — 4 s apart fails with no fragment length, passes with 5 s fragments", async () => { + const v = await streamFile(0, path.join(ROOT, "vf.mp4"), [17, 18, 19, 20]); + const a = await streamFile(1, path.join(ROOT, "af.m4a")); + const m = await merge(v, a, path.join(ROOT, "mf.mp4")); + assert.equal((await verifyMerged(FFPROBE, m, [v, a])).ok, false, "2 s by default"); + assert.equal((await verifyMerged(FFPROBE, m, [v, a], undefined, { fragmentSeconds: 5 })).ok, true, "2 fragments of 5 s"); +}); diff --git a/editor/app/api/ops/live-recording-verify/route.ts b/editor/app/api/ops/live-recording-verify/route.ts @@ -0,0 +1,24 @@ +import { NextResponse } from "next/server"; +import { reverifyLiveRecordingAction } from "../../../channels/[slug]/liveMediaActions"; +import { forgetAttention } from "../_attention"; +import { ops, opsFail, reqSlug, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, id, startedAt? } -> { ok: true, verified, why?, removed } +// +// THE LANDING'S CHECK, AGAIN (controller/recordLive.ts reverifyLiveLanding): +// a recording whose landed file is `failed` or `pending` against the stream +// files it was made from is checked once more. Verified, and the stream +// confirmed done, those stream files, their state and fragments go; else the +// row says why and nothing is removed. The row's Verify button. +export async function POST(request: Request) { + return ops(request, ["slug", "id", "startedAt"], async (body) => { + const slug = reqSlug(body, "slug"); + const id = reqString(body, "id"); + const r = await reverifyLiveRecordingAction({ slug, id, ...(typeof body.startedAt === "string" ? { startedAt: body.startedAt } : {}) }); + if (!r.ok) return opsFail(r.error); + forgetAttention(); + return NextResponse.json(r); + }); +} diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts @@ -31,7 +31,7 @@ import { resolveCookiePolicy } from "yt-dlp-transcript-common/lib/cookiePolicy"; import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { parseImportRequest } from "yt-dlp-transcript-common/lib/mediaImport"; import { isArchivePath, runImportMediaJob } from "yt-dlp-transcript-common/controller/importMedia"; -import { parseRecordLiveRequest, runRecordLiveJob } from "yt-dlp-transcript-common/controller/recordLive"; +import { parseRecordLiveRequest, reverifyLiveLanding, runRecordLiveJob } from "yt-dlp-transcript-common/controller/recordLive"; import { acknowledgeLiveRecording } from "yt-dlp-transcript-common/controller/liveRecordings"; import { loadLiveRecordingRows } from "yt-dlp-transcript-common/lib/liveRecordings-server"; import { @@ -132,6 +132,23 @@ export async function recordLiveAction(body: Record<string, unknown>, internal: // needing anyone. // recordLiveAgainAction the Record again button: record-live with // the run's own url and recording keys. +// REVIEW-7 4: a landing whose check failed or never ran, checked again — +// verified (and the stream confirmed done), its stream files go. +// `pnpm ops live-recording-verify`, the row's Verify button. +export async function reverifyLiveRecordingAction(body: { + slug: string; + id: string; + startedAt?: string; +}): Promise<{ ok: true; verified: boolean; why?: string; removed: string[] } | { ok: false; error: string }> { + if (!isValidChannelSlug(body.slug)) return { ok: false, error: `"${body.slug}" is not a channel slug` }; + const paths = getPaths(); + const config = await readChannelConfig(paths, body.slug); + if (!config) return { ok: false, error: `Channel "${body.slug}" not found` }; + const r = await reverifyLiveLanding({ paths, slug: body.slug, id: body.id, ...(body.startedAt ? { startedAt: body.startedAt } : {}), channelConfig: config }); + if (r.ok) safeRevalidate(["/review", `/channels/${body.slug}`]); + return r; +} + export async function acknowledgeLiveRecordingAction(body: { slug: string; id?: string; diff --git a/editor/app/components/LiveRecordingActions.tsx b/editor/app/components/LiveRecordingActions.tsx @@ -9,6 +9,7 @@ import { useState, useTransition } from "react"; import { acknowledgeLiveRecordingAction, recordLiveAgainAction, + reverifyLiveRecordingAction, } from "../channels/[slug]/liveMediaActions"; export function LiveRecordingActions({ @@ -17,6 +18,7 @@ export function LiveRecordingActions({ startedAt, file, canRecordAgain, + canVerify = false, }: { slug: string; // A recording's run (id + startedAt), or a set-aside live-recordings.json. @@ -24,6 +26,8 @@ export function LiveRecordingActions({ startedAt?: string; file?: string; canRecordAgain: boolean; + // Its landed file's check failed or never ran (REVIEW-7 4): Verify again. + canVerify?: boolean; }): React.ReactNode { const what = file ?? `${slug}/${id ?? ""}`; const [pending, startTransition] = useTransition(); @@ -51,6 +55,22 @@ export function LiveRecordingActions({ Record again </button> )} + {canVerify && id && ( + <button + type="button" + aria-label={`verify ${what} again`} + disabled={pending} + className={btn} + onClick={() => + press( + () => reverifyLiveRecordingAction({ slug, id, ...(startedAt ? { startedAt } : {}) }), + (r) => (r.verified ? `Verified${Array.isArray(r.removed) && r.removed.length ? `; ${r.removed.length} file(s) removed` : ""}` : `Not verified: ${String(r.why ?? "")}`), + ) + } + > + Verify again + </button> + )} <button type="button" aria-label={`acknowledge ${what}`} diff --git a/editor/app/components/LiveRecordingsAttention.tsx b/editor/app/components/LiveRecordingsAttention.tsx @@ -58,7 +58,13 @@ function Row({ r }: { r: LiveRecordingView }) { </ul> ) : null} {r.needsAttention ? ( - <LiveRecordingActions slug={r.slug} id={r.id} startedAt={r.startedAt} canRecordAgain={r.status !== "recording" && Boolean(r.url)} /> + <LiveRecordingActions + slug={r.slug} + id={r.id} + startedAt={r.startedAt} + canRecordAgain={r.status !== "recording" && Boolean(r.url)} + canVerify={Boolean(r.verification && r.verification.state !== "verified" && r.verification.against?.length)} + /> ) : null} </li> ); diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -592,6 +592,9 @@ const ACTIONS = [ // a person ({slug, id, startedAt?, by?}): it stays in `get live-recordings` // and no longer counts as needing anyone. /review's Acknowledge. "live-recording-ack", + // A landing whose check failed or never ran, checked again against its + // stream files ({slug, id, startedAt?}); verified and the stream done, they go. + "live-recording-verify", // A channel's saved containers remuxed losslessly into browser-playable // copies, one torrent each ({slug, ids?, trackers?, root?, dryRun?}). "prepare-playable", @@ -2823,17 +2826,19 @@ export function usage() { " try at a time, at most 8; a try that holds the whole stream when landed", " recovers the start (startRecovery). Each recorder has a stall watchdog:", " no growth for liveRecording.stallMinutes (10) stops that recorder, its", - " part kept; a from-start recorder (dead, stalled, or stopped by a", - " shutdown) is RESUMED in place from yt-dlp's .ytdl state — the same part —", - " and only when that is impossible does a live-edge recorder follow:", - " while the stream still reads live (one metadata read; an exit", - " is read twice, a minute apart) a new part records from the live edge —", - " at most 6 restarts an hour and 24 a run (restarts); past them the row", - " says the stream is live and NOT recorded. \"insurance\"?: true | \"whole\" | false —", - " a live-edge recorder beside a from-start recording of a stream already", - " live, until the start has caught up (+5 min), or for the whole stream;", - " absent, on exactly when the stream is marked keep (\"doNotClean\", the", - " record's Do-not-clean marker, a pending keep) when the recording starts.", + " part kept; while the stream still reads live (one metadata read; an", + " exit is read twice, a minute apart) a from-start recorder (dead, stalled,", + " stopped by a shutdown, or ended by itself) is RESUMED in place — the same", + " files, every kept fragment reused — and only when that cannot be proven", + " does a FRESH part record from the stream's start, then the live edge", + " (6 restarts an hour, waited out, never an end); while the state cannot", + " be read for the network nothing is started and no restart spent.", + " \"insurance\"?: true | \"whole\" | false — a live-edge recorder beside a", + " from-start recording of a stream already live, until the start has", + " caught up (+5 min), or for the whole stream; absent, on when the stream", + " is marked keep (\"doNotClean\", the record's Do-not-clean marker, a", + " pending keep), and also when a from-start part shows itself more than", + " 10 min behind the live edge (liveRecording.insuranceWhenBehind).", " Its part goes at landing only when the landed file holds the whole", " stream; otherwise it is kept and listed. After an editor restart, a run", " the shutdown or a crash interrupted restarts by itself (once per run, 3", @@ -2870,6 +2875,13 @@ export function usage() { " pages show the same rows and the stalled ones, and every ops reply then", " prints \"! N live recordings need you; M ... NOT growing\" on stderr.", "", + 'live-recording-verify {"slug", "id", "startedAt"?} checks a landed file whose', + " verification failed or never ran against the stream files it was made", + " from (packets per track, the tracks' spans, a hole scan, each stream file", + " byte for byte its kept fragments); verified and the stream confirmed", + " done, those stream files, their state and fragments are removed; else", + " the row says why and nothing is. The row's Verify button.", + "", 'live-recording-ack {"slug", "id", "startedAt"?, "by"?} acknowledges every', " run of the record that needs a person (or the one run startedAt names):", ' listed still, counted no more. {"slug", "file"} acknowledges a set-aside',