commit dedb8bb5071cfaf2ef72ba6d9dafda62548c729c parent 2655fdb45e3840bbf6361f548741c9253083faf5 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Tue, 10 Nov 2026 18:01:20 -0500 umtool, common: every temp name from one helper -- common/lib/atomicFile.mjs tmpPathFor (`<file>.tmp-<pid>-<seq>-<random>`, an extension kept for ffmpeg, a hidden target kept hidden) and writeFileAtomic(Sync), the plain-node twin of jsonFile-server.ts; about 100 writers in umtool and common/lib that built `<file>.<pid>.tmp`, `<file>.tmp-<pid>` or a bare `<file>.tmp` by hand (one name for every write a process made to that file, so two writes in flight shared it: writePlayManifest's E1 race) now take it, posts-server.ts through jsonFile-server's writeFileAtomic. umtool/lib/atomicFile-sweep.test.mjs fails on a temp name made by hand anywhere in umtool's or common's source (E5 A2) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Diffstat:
93 files changed, 336 insertions(+), 134 deletions(-)
diff --git a/common/lib/atomicFile.mjs b/common/lib/atomicFile.mjs @@ -0,0 +1,65 @@ +// THE ONE TEMP NAME for a file written beside its target and renamed over it, for plain-node modules (umtool's +// report-to-video and lib, common's .mjs stores) -- jsonFile-server.ts's writers are the TypeScript twin, in the +// same form: `<file>.tmp-<pid>-<seq>-<random>`. +// +// Unique per WRITE, not per process. `<file>.<pid>.tmp` was one name for every write a process made to a file, so +// two writes in flight at once (two requests in one server, two windows cut at once) shared it: the first rename +// took the other's half-written file, the second threw ENOENT (lib/report/takeManifest.mjs, writePlayManifest). +// The `.tmp-` infix is what a lister skips (lib/report/snapshots.mjs). `ext` keeps an extension a tool reads +// the format from (ffmpeg's `.mp4`); a hidden target (`.<name>`) keeps its temp hidden. +// +// A sweep test (umtool/lib/atomicFile-sweep.test.mjs) fails on a new `<pid>.tmp` name anywhere else. +import { randomBytes } from "node:crypto"; +import { renameSync, rmSync, writeFileSync } from "node:fs"; +import { rename, rm, writeFile } from "node:fs/promises"; + +/** @type {{ seq: number }} one counter however many copies of this module a process loads */ +const state = /** @type {any} */ (globalThis).__yttAtomicFile__ ?? (/** @type {any} */ (globalThis).__yttAtomicFile__ = { seq: 0 }); + +/** + * A temp path beside `file`, unique to this write. + * + * @param {string} file + * @param {{ ext?: string }} [opts] + * @returns {string} + */ +export function tmpPathFor(file, { ext = "" } = {}) { + state.seq += 1; + return `${file}.tmp-${process.pid}-${state.seq}-${randomBytes(4).toString("hex")}${ext}`; +} + +/** + * Write `data` to a unique temp beside `file`, then rename it over `file`; the temp is removed on any failure. + * + * @param {string} file + * @param {string | Uint8Array} data + * @param {import("node:fs").WriteFileOptions} [opts] + */ +export async function writeFileAtomic(file, data, opts) { + const tmp = tmpPathFor(file); + try { + await writeFile(tmp, data, opts); + await rename(tmp, file); + } catch (e) { + await rm(tmp, { force: true }).catch(() => {}); + throw e; + } +} + +/** + * writeFileAtomic's synchronous twin. + * + * @param {string} file + * @param {string | Uint8Array} data + * @param {import("node:fs").WriteFileOptions} [opts] + */ +export function writeFileAtomicSync(file, data, opts) { + const tmp = tmpPathFor(file); + try { + writeFileSync(tmp, data, opts); + renameSync(tmp, file); + } catch (e) { + rmSync(tmp, { force: true }); + throw e; + } +} diff --git a/common/lib/clips/reactions.mjs b/common/lib/clips/reactions.mjs @@ -12,6 +12,7 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { REACTIONS_VERSION, ROLES } from "./clips.mjs"; +import { tmpPathFor } from "../atomicFile.mjs"; export const REACTIONS_FILE = "reactions.json"; export { REACTIONS_VERSION }; @@ -33,7 +34,7 @@ export async function readReactions(dir) { /** Written whole: tmp + rename, so a reader never sees half a file. */ export async function writeReactions(dir, doc) { const file = reactionsFileOf(dir); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`); await rename(tmp, file); return file; diff --git a/common/lib/clips/suggest.mjs b/common/lib/clips/suggest.mjs @@ -27,6 +27,7 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { cleanTurns, cleanWords, roleMap, wordsFromCues, wordsIn } from "./clips.mjs"; +import { tmpPathFor } from "../atomicFile.mjs"; export const SUGGESTIONS_FILE = "clip-suggestions.json"; export const SUGGEST_PROMPT_VERSION = "clips-suggest-1"; @@ -117,7 +118,7 @@ export async function writeSuggestions(dir, doc) { const r = parseSuggestionsDoc(doc); if ("error" in r) throw new Error(`not a suggestions doc: ${r.error}`); const file = suggestionsFileOf(dir); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(r.doc, null, 1)}\n`); await rename(tmp, file); return file; diff --git a/common/lib/montage/cueTextCache.mjs b/common/lib/montage/cueTextCache.mjs @@ -25,6 +25,7 @@ import { createReadStream, createWriteStream } from "node:fs"; import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { createInterface } from "node:readline"; +import { tmpPathFor } from "../atomicFile.mjs"; export const CACHE_VERSION = 3; @@ -149,7 +150,7 @@ export async function openChannelCache(cacheDir, channelsDir, slug, ids) { const nextIndex = {}; if (changed) { await mkdir(root, { recursive: true }); - tmp = `${dataFile}.${process.pid}.${Date.now()}.tmp`; + tmp = tmpPathFor(dataFile); out = createWriteStream(tmp, { encoding: "utf8" }); } @@ -191,7 +192,7 @@ export async function openChannelCache(cacheDir, channelsDir, slug, ids) { } await new Promise((resolve, reject) => out.end((e) => (e ? reject(e) : resolve()))); await rename(tmp, dataFile); - const itmp = `${indexFile}.${process.pid}.tmp`; + const itmp = tmpPathFor(indexFile); await writeFile(itmp, JSON.stringify({ version: CACHE_VERSION, slug, videos: nextIndex }), "utf8"); await rename(itmp, indexFile); return true; diff --git a/common/lib/montage/speakerCheck.mjs b/common/lib/montage/speakerCheck.mjs @@ -29,6 +29,7 @@ import { scoreAgainst, voicedSamples, } from "./voiceMatch.mjs"; +import { tmpPathFor } from "../atomicFile.mjs"; export const SPEAKER_CHECK_FILE = "speaker-check.json"; export const SPEAKER_CHECK_VERSION = 1; @@ -199,7 +200,7 @@ export async function writeSpeakerCheck(dir, doc) { const prev = await readSpeakerCheck(dir); const sig = (d) => JSON.stringify((d?.speakers ?? []).map((s) => [s.name, s.clips, s.recordings])); const merged = prev && sig(prev) === sig(doc) ? { ...doc, clips: { ...prev.clips, ...doc.clips } } : doc; - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(merged, null, 1)}\n`); await rename(tmp, file); return { file, doc: merged }; diff --git a/common/lib/montage/voiceMatch.mjs b/common/lib/montage/voiceMatch.mjs @@ -36,6 +36,7 @@ import { spawn } from "node:child_process"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "../atomicFile.mjs"; export const VOICE_MATCH_FILE = "voice-match.json"; export const VOICE_MATCH_VERSION = 1; @@ -625,7 +626,7 @@ export function voiceMatchSummary(doc) { /** Written whole: tmp + rename. */ export async function writeVoiceMatch(dir, doc) { const file = path.join(dir, VOICE_MATCH_FILE); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`); await rename(tmp, file); return file; diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts @@ -11,7 +11,7 @@ // fetchers stop the same way), and uses the same "<extractor> <id>" line format // so common/lib/archive.ts parses it unchanged. -import { writeJsonAtomic } from "./jsonFile-server"; +import { writeFileAtomic, writeJsonAtomic } from "./jsonFile-server"; import path from "node:path"; import type { ForumWalkState } from "./forumWalk"; import type { TimelineBackfillState, TimelineSyncState } from "./timelineWalk"; @@ -256,20 +256,17 @@ export async function replaceChannelPosts( if (bucket) bucket.push(p); else byShard.set(shard, [p]); } - const tmpSuffix = `.tmp-${process.pid}-${Date.now()}`; for (const [shard, list] of byShard) { list.sort((a, b) => -comparePostsNewestFirst(a, b)); const file = shardPath(channelRoot, shard); - await writeFile(file + tmpSuffix, list.map((p) => JSON.stringify(p)).join("\n") + "\n", "utf8"); - await rename(file + tmpSuffix, file); + await writeFileAtomic(file, list.map((p) => JSON.stringify(p)).join("\n") + "\n"); } for (const shard of await listPostShards(channelRoot)) { if (!byShard.has(shard)) await rm(shardPath(channelRoot, shard), { force: true }); } const archive = channelPostsArchivePath(channelRoot); const lines = [...byId.values()].map((p) => `${p.platform} ${p.id}\n`).join(""); - await writeFile(archive + tmpSuffix, lines, "utf8"); - await rename(archive + tmpSuffix, archive); + await writeFileAtomic(archive, lines); return { shards: [...byShard.keys()].sort(), written: byId.size }; } diff --git a/common/lib/renderPriority.mjs b/common/lib/renderPriority.mjs @@ -46,6 +46,7 @@ import { randomBytes } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { tmpPathFor } from "./atomicFile.mjs"; /** The memory floor a render in render mode is admitted on, absent HEAVY_MIN_FREE_MB. */ export const RENDER_PRIORITY_FLOOR_MB = 4000; @@ -128,7 +129,7 @@ export function readRenderPriorityState(file) { /** tmp + rename, so a reader never sees half a file. */ function writeState(file, state) { fs.mkdirSync(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`; + const tmp = tmpPathFor(file); fs.writeFileSync(/* turbopackIgnore: true */ tmp, `${JSON.stringify(state, null, 2)}\n`); fs.renameSync(tmp, file); } @@ -140,7 +141,7 @@ function writeState(file, state) { */ function createState(file, state) { fs.mkdirSync(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`; + const tmp = tmpPathFor(file); fs.writeFileSync(/* turbopackIgnore: true */ tmp, `${JSON.stringify(state, null, 2)}\n`); try { fs.linkSync(tmp, file); diff --git a/common/lib/report/draft/tasks/media.ts b/common/lib/report/draft/tasks/media.ts @@ -63,6 +63,7 @@ import type { VideoManifest } from "../videoOps"; import { projectDirOf, readManifest, readProjectReport, snapshotManifest, writeManifest } from "./project"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; import type { TaskDeps, TaskResult } from "./types"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export type { DraftTarget, Provenance } from "../../drafted.mjs"; @@ -248,7 +249,7 @@ export function mergeAlternatives(earlier: readonly DraftAlternative[], now: rea } async function writeJsonAtomic(file: string, value: unknown) { - const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); await rename(tmp, file); } diff --git a/common/lib/report/draft/tasks/project.ts b/common/lib/report/draft/tasks/project.ts @@ -10,6 +10,7 @@ import { copyFile, link, mkdir, readdir, readFile, rename, stat, writeFile } fro import path from "node:path"; import { projectOf, type Iteration } from "../../iterations"; import type { VideoManifest } from "../videoOps"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MANIFEST_NAME = "video.manifest.json"; // umtool's snapshots (umtool/lib/report/snapshots.mjs): `revisions/<stamp>-<label>.manifest.json`. @@ -41,7 +42,7 @@ export async function readProjectReport(dir: string): Promise<Record<string, unk export async function writeManifest(dir: string, m: VideoManifest): Promise<void> { await mkdir(dir, { recursive: true }); const file = path.join(dir, MANIFEST_NAME); - const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(m, null, 2)}\n`); await rename(tmp, file); } diff --git a/common/lib/report/groupProposals.mjs b/common/lib/report/groupProposals.mjs @@ -23,6 +23,7 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const GROUP_PROPOSALS_NAME = "group-proposals.json"; export const GROUPS_PROMPT_VERSION = "propose-groups-1"; @@ -209,7 +210,7 @@ export async function writeGroupProposals(dir, doc) { const errors = groupProposalsErrors(doc); if (errors.length) throw new Error(`not group proposals: ${errors.join("; ")}`); const file = fileOf(dir); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`, "utf8"); await rename(tmp, file); return file; diff --git a/common/lib/report/videoAssistProposals.mjs b/common/lib/report/videoAssistProposals.mjs @@ -19,6 +19,7 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const ASSIST_PROPOSALS_NAME = "assist-proposals.json"; export const ASSIST_PROMPT_VERSION = "video-assist-1"; @@ -91,7 +92,7 @@ export async function writeAssistProposals(dir, doc) { const errors = proposalsErrors(doc); if (errors.length) throw new Error(`not proposals: ${errors.join("; ")}`); const file = fileOf(dir); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`, "utf8"); await rename(tmp, file); return file; diff --git a/common/lib/research/caseStore-server.ts b/common/lib/research/caseStore-server.ts @@ -27,6 +27,7 @@ import { } from "./caseTypes"; import { CasePipelineError, checkFindingRow, normalizeDefinition, planBatches, rowGateText, wrapText } from "./casePipeline"; import { assertNoPrivateNames, withholdPrivateNames } from "./casePrivacy-server"; +import { tmpPathFor } from "../atomicFile.mjs"; const file = (dir: string, name: string) => path.join(/* turbopackIgnore: true */ dir, name); @@ -52,7 +53,7 @@ async function readJsonFile<T>(p: string): Promise<T | null> { /** A whole file, to a temp name and a rename. */ export async function writeAtomic(p: string, body: string): Promise<void> { await mkdir(/* turbopackIgnore: true */ path.dirname(p), { recursive: true }); - const tmp = `${p}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(p); try { await writeFile(/* turbopackIgnore: true */ tmp, body); await rename(/* turbopackIgnore: true */ tmp, p); diff --git a/common/lib/waybackPages/store-server.ts b/common/lib/waybackPages/store-server.ts @@ -19,6 +19,7 @@ import { mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises"; import { gunzipSync, gzipSync } from "node:zlib"; import { writeJsonAtomic } from "../jsonFile-server"; import { pageRecordId } from "./types"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const PAGES_DIRNAME = "pages"; export const PAGE_RAW_FILENAME = "raw.html.gz"; @@ -131,7 +132,7 @@ export async function writeStoredCapture( const dir = pageCaptureDir(channelRoot, capture.captureTs, capture.originalUrl); await mkdir(dir, { recursive: true }); const raw = path.join(dir, PAGE_RAW_FILENAME); - const tmp = `${raw}.tmp-${process.pid}-${Date.now()}`; + const tmp = tmpPathFor(raw); await writeFile(tmp, gzipSync(body)); await rename(tmp, raw); await writeJsonAtomic(path.join(dir, PAGE_CAPTURE_FILENAME), capture); diff --git a/common/package.json b/common/package.json @@ -39,6 +39,7 @@ "./lib/clips/scan.mjs": "./lib/clips/scan.mjs", "./lib/clips/segments.mjs": "./lib/clips/segments.mjs", "./lib/clips/suggest.mjs": "./lib/clips/suggest.mjs", + "./lib/atomicFile.mjs": "./lib/atomicFile.mjs", "./lib/cueWiden.mjs": "./lib/cueWiden.mjs", "./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs", "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", diff --git a/umtool/app/api/clip/[key]/audio/route.ts b/umtool/app/api/clip/[key]/audio/route.ts @@ -6,6 +6,7 @@ import { promisify } from "node:util"; import { CACHE_DIR, cacheFile } from "@/lib/paths"; import { sourceWav } from "@/lib/clips"; import { readWavWindow, encodeWav, peakOver } from "@/lib/wav"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const run = promisify(execFile); @@ -89,7 +90,7 @@ export async function GET(request: Request, ctx: { params: Promise<{ key: string body = await readFile(tmpMp3); await rename(tmpMp3, cached).catch(() => {}); } else { - const tmp = cacheFile(`${stamp}.wav.tmp`); + const tmp = tmpPathFor(cached); await writeFile(tmp, wav); await rename(tmp, cached).catch(() => {}); } diff --git a/umtool/lib/analyse.mjs b/umtool/lib/analyse.mjs @@ -21,6 +21,7 @@ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { MIX_CACHE, labelFor } from "./paths.mjs"; import { brightnessCurve, brightnessSteps } from "../song/flatness.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Analysis sample rate. 16 kHz resolves the whole band the ratio looks at. */ const ANALYSIS_SR = 16000; @@ -153,7 +154,7 @@ export async function analyseFile(abs, { st = undefined, cacheDir = MIX_CACHE } }; await mkdir(cacheDir, { recursive: true }); - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(out)); await rename(tmp, file).catch(() => {}); return out; diff --git a/umtool/lib/annotations/store.mjs b/umtool/lib/annotations/store.mjs @@ -23,6 +23,7 @@ import { open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; import { NoteError, applyOp, emptyDoc, parseNotesDoc } from "./shape.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { NoteError }; export const LOCK_STALE_MS = 30_000; @@ -149,7 +150,7 @@ export async function writeOp(file, init, op, { by, token = null }) { }); return { doc: null, token: "absent", note }; } - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(/* turbopackIgnore: true */ tmp, file); return { doc, token: await notesToken(file), note }; diff --git a/umtool/lib/atomicFile-sweep.test.mjs b/umtool/lib/atomicFile-sweep.test.mjs @@ -0,0 +1,59 @@ +// THE TEMP-NAME SWEEP (umtool redesign E5 A2): a file written beside its target and renamed over it takes its temp +// name from ONE helper -- common/lib/atomicFile.mjs `tmpPathFor` (or its writers), and jsonFile-server.ts, its +// TypeScript twin. A name built by hand from the pid (`<file>.<pid>.tmp`) is one name for every write a process +// makes to that file, so two writes in flight at once share it and one rename takes the other's half-written file; +// a bare `<file>.tmp` is one name for every process. This fails on either, anywhere in umtool's or common's source. +// +// Run with: node --test umtool/lib/atomicFile-sweep.test.mjs +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; + +const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); +const ROOTS = ["umtool", "common/lib"]; +const SKIP_DIRS = new Set(["node_modules", ".next", "e2e", "out", "test-results", ".e2e-song"]); +/** The helpers themselves: the only places a temp name is made. */ +const HELPERS = new Set(["common/lib/atomicFile.mjs", "common/lib/jsonFile-server.ts"]); +const SOURCE = /\.(mjs|js|ts|tsx)$/; +const TEST = /\.test\.(mjs|js|ts|tsx)$/; + +/** A temp name made by hand: the pid on the same line as `.tmp`, or a template literal ending `.tmp`. */ +const BY_HAND = [/process\.pid[^\n]*\.tmp/, /\.tmp[^\n]*process\.pid/, /\}\.tmp`/]; + +function* sources(dir) { + for (const d of readdirSync(dir, { withFileTypes: true })) { + if (d.isDirectory()) { + if (!SKIP_DIRS.has(d.name) && !d.name.startsWith(".")) yield* sources(path.join(dir, d.name)); + } else if (d.isFile() && SOURCE.test(d.name) && !TEST.test(d.name)) yield path.join(dir, d.name); + } +} + +test("no temp name is made by hand: every `<file>.<pid>.tmp` and `<file>.tmp` goes through atomicFile.mjs", () => { + const found = []; + let seen = 0; + for (const root of ROOTS) { + for (const file of sources(path.join(REPO, root))) { + const rel = path.relative(REPO, file); + if (HELPERS.has(rel)) continue; + seen += 1; + readFileSync(file, "utf8") + .split("\n") + .forEach((line, i) => { + if (BY_HAND.some((re) => re.test(line))) found.push(`${rel}:${i + 1}: ${line.trim()}`); + }); + } + } + assert.ok(seen > 500, `the sweep read ${seen} source files: a root moved?`); + assert.deepEqual(found, [], `a temp name made by hand -- use tmpPathFor / writeFileAtomic (common/lib/atomicFile.mjs):\n${found.join("\n")}`); +}); + +test("tmpPathFor: a name of its own per call, beside the file, keeping an extension", () => { + const a = tmpPathFor("/d/x.json"); + const b = tmpPathFor("/d/x.json"); + assert.notEqual(a, b); + assert.match(a, new RegExp(`^/d/x\\.json\\.tmp-${process.pid}-\\d+-[0-9a-f]{8}$`)); + assert.match(tmpPathFor("/d/.c01", { ext: ".mp4" }), /^\/d\/\.c01\.tmp-\d+-\d+-[0-9a-f]{8}\.mp4$/); +}); diff --git a/umtool/lib/bench-marks.mjs b/umtool/lib/bench-marks.mjs @@ -20,6 +20,7 @@ // Plain ESM: the unit test reads it the way the app does. import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const BENCH_MARKS_FORMAT = "archilyzer-bench-marks"; export const BENCH_MARKS_VERSION = 1; @@ -110,7 +111,7 @@ export function setBenchMark(root, run, m) { doc.updatedAt = at; const file = benchMarksFile(root, run); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/digestContextReview.mjs b/umtool/lib/digestContextReview.mjs @@ -29,6 +29,7 @@ import { createHash } from "node:crypto"; import { link, lstat, readFile, readdir, realpath, rename, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SUGGESTED = "digest-context.suggested.md"; export const ACTIVE = "digest-context.md"; @@ -235,7 +236,7 @@ export async function decideDigestContextNote({ channelsDir, slug, decision, sha await unlink(/* turbopackIgnore: true */ sugPath); } else { const rec = { by: "operator", at: now().toISOString(), sha256: want }; - const tmp = path.join(/* turbopackIgnore: true */ at.dir, `.${REFUSED}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(/* turbopackIgnore: true */ at.dir, `.${REFUSED}`)); await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(rec, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, /* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ at.dir, REFUSED)); } diff --git a/umtool/lib/inbox/refresh.ts b/umtool/lib/inbox/refresh.ts @@ -14,6 +14,7 @@ import { isMuted, type MutesRead } from "@/lib/mutes"; import { REPORTS_ROOT } from "@/lib/paths"; import type { Piece, PieceGraph } from "@/lib/pieces"; import { localDir, openSource } from "@/lib/research/sources"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // --------------------------------------------------------------------------- // A REFRESH, SUGGESTED (plans/umtool-redesign.md, R4) -- two Inbox kinds: @@ -98,7 +99,7 @@ function saveCheck(entry: CheckEntry): Promise<void> { f.articles[entry.article] = entry; const file = CHECK_FILE(); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(f, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); }); diff --git a/umtool/lib/ingredients/usedIn.mjs b/umtool/lib/ingredients/usedIn.mjs @@ -40,6 +40,7 @@ import path from "node:path"; import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; import { walkProjects } from "../projects/walk.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const USAGE_INDEX_FORMAT = "umtool-usage-index"; export const USAGE_INDEX_VERSION = 1; @@ -224,7 +225,7 @@ export async function readUsageIndex(file) { async function writeUsageIndex(file, index) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(index) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/lifecycle.mjs b/umtool/lib/lifecycle.mjs @@ -23,6 +23,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { isPieceId } from "./pieces/ids.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LIFECYCLE_STATES = ["active", "parked", "done"]; export const LIFECYCLE_FORMAT = "umtool-lifecycle"; @@ -110,7 +111,7 @@ async function write(reportsRoot, id, state, by, now) { pieces: Object.fromEntries(Object.entries({ ...read.pieces, [id]: entry }).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), }; await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/loudness.ts b/umtool/lib/loudness.ts @@ -5,6 +5,7 @@ import path from "node:path"; import { CACHE_DIR, labelFor } from "./paths"; import type { Loudness } from "./loudness-types"; import { pathCache } from "./pathCache.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export * from "./loudness-types"; @@ -163,7 +164,7 @@ export async function measureLoudness(abs: string): Promise<Loudness> { const c = await cacheFileFor(abs); if (c) { await mkdir(LOUD_CACHE, { recursive: true }); - const tmp = `${c.file}.tmp-${process.pid}`; + const tmp = tmpPathFor(c.file); await writeFile(tmp, JSON.stringify(out)); await rename(tmp, c.file).catch(() => {}); memo.set(abs, c.key, out); diff --git a/umtool/lib/mutes.mjs b/umtool/lib/mutes.mjs @@ -18,6 +18,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { isPieceId } from "./pieces/ids.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MUTES_FORMAT = "umtool-mutes"; export const MUTES_VERSION = 1; @@ -122,7 +123,7 @@ async function write(reportsRoot, piece, kind, muted, now) { mutes: sorted(Object.fromEntries(Object.entries(mutes).map(([p, kinds]) => [p, sorted(kinds)]))), }; await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/phrase-finder/cli.mjs b/umtool/lib/phrase-finder/cli.mjs @@ -16,6 +16,7 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { runPhraseScan } from "./scan.mjs"; import { summarisePhrase } from "./summary.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; function parse(args) { const o = { phrases: [], channels: [], prefer: null, exclude: null, mode: "auto", samples: 10, cache: true, json: false, full: false, spec: null, out: null, progress: false }; @@ -70,7 +71,7 @@ export async function phrasesCommand(args) { const answer = await runPhraseScan(spec, { ...(o.cache ? {} : { cacheDir: null }), onProgress }); if (o.out) { await mkdir(path.dirname(o.out), { recursive: true }); - const tmp = `${o.out}.${process.pid}.tmp`; + const tmp = tmpPathFor(o.out); await writeFile(tmp, JSON.stringify(answer), "utf8"); await rename(tmp, o.out); if (o.progress) console.log(JSON.stringify({ done: true, out: o.out, seconds: answer.seconds })); diff --git a/umtool/lib/phrase-finder/server.ts b/umtool/lib/phrase-finder/server.ts @@ -8,6 +8,7 @@ import { CHANNEL_RE, checkSpec } from "./scan.mjs"; import { summarisePhrase } from "./summary.mjs"; import { MONTAGE_KIND } from "../projects/create.mjs"; import type { PhraseChannel, PhraseFinderState, PhraseScanRowView, PhraseScanSpec, PhraseScanView, PhraseSuggestion } from "./types"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // --------------------------------------------------------------------------- // THE PHRASE FINDER's server half (release 34; the page is /tools/phrases). @@ -62,7 +63,7 @@ const runningScan = () => [...reg.jobs.values()].find((j) => j.state === "runnin async function writeAtomic(file: string, text: string) { await mkdir(path.dirname(/* turbopackIgnore: true */ file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, text, "utf8"); await rename(/* turbopackIgnore: true */ tmp, file); } diff --git a/umtool/lib/poster.ts b/umtool/lib/poster.ts @@ -6,6 +6,7 @@ import { existsSync } from "node:fs"; import path from "node:path"; import { CACHE_DIR } from "./paths"; import { probeCached } from "./browse"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const run = promisify(execFile); @@ -60,7 +61,7 @@ export async function posterFrame(abs: string, width = DEFAULT_WIDTH): Promise<P const at = info.duration > 0 ? +(info.duration * POSTER_AT).toFixed(3) : 0; await mkdir(POSTER_CACHE, { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}.jpg`; + const tmp = tmpPathFor(file, { ext: ".jpg" }); try { // -ss BEFORE -i is the fast seek: it jumps in the container rather than // decoding up to the mark, which on a 66 MB render is the difference diff --git a/umtool/lib/queue/store.mjs b/umtool/lib/queue/store.mjs @@ -56,6 +56,7 @@ import { mkdir, open, readdir, readFile, rename, rm, stat, unlink, writeFile } f import os from "node:os"; import path from "node:path"; import { firstErrorLine, procStartTime, processAlive, queueDirFor } from "../report/renderRecord.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const STEP_STATES = Object.freeze(["queued", "running", "done", "failed", "blocked", "cancelled"]); export const TERMINAL = new Set(["done", "failed", "cancelled"]); @@ -82,10 +83,8 @@ export const stepFile = (dir, qid) => path.join(stepsDir(dir), `${qid}.json`); export const logFileOf = (dir, qid, attempt = null) => path.join(dir, "logs", attempt ? `${qid}.${attempt}.log` : `${qid}.log`); const leaseFile = (dir) => path.join(dir, "runner.json"); -let tmpSeq = 0; async function writeJson(file, doc) { - tmpSeq += 1; - const tmp = `${file}.${process.pid}.${tmpSeq}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/benchPrep.mjs b/umtool/lib/report/benchPrep.mjs @@ -56,6 +56,7 @@ import { clipsOf, readManifest } from "../projects/report.mjs"; import { UMTOOL_DIR } from "./driver.mjs"; import { isTakeId } from "./takes.mjs"; import { absOf, ensureWindowFile, projectCache, windowFileFresh, windowsFor } from "./serve.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** An excerpt cut's resident set (234 MB, measured: a 2-minute 720p excerpt of a 1080p stream) plus the runner. */ export const PREP_ESTIMATE_MB = 400; @@ -233,7 +234,7 @@ export async function readPrepStatus(dir, take = null) { /** @param {string} dir @param {PrepStatus} st @param {string | null} [take] */ async function writePrepStatus(dir, st, take = null) { await mkdir(prepStateDirOf(dir, take), { recursive: true }); - const tmp = `${statusFile(dir, take)}.tmp-${process.pid}`; + const tmp = tmpPathFor(statusFile(dir, take)); await writeFile(tmp, `${JSON.stringify(st, null, 1)}\n`); await rename(tmp, statusFile(dir, take)); } diff --git a/umtool/lib/report/candidates.mjs b/umtool/lib/report/candidates.mjs @@ -40,6 +40,7 @@ import { readManifest } from "../projects/report.mjs"; import { groupModel } from "./claimGroups.mjs"; import { sectionModel, sectionWords } from "./sectionEdit.mjs"; import { sentenceBoundaries } from "./sentenceEdges.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CANDIDATES_FILE = "candidates.json"; export const CANDIDATES_FORMAT = "umtool-candidates"; @@ -361,7 +362,7 @@ function writeCandidates(dir, mutate) { candidates: doc.candidates.map(({ key: _k, ...r }) => ({ id: r.id, key: candidateKey(r), ...r })), }; await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(out, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/report/castAudition.mjs b/umtool/lib/report/castAudition.mjs @@ -24,6 +24,7 @@ import { cardText } from "umtool-report-to-video/post-item"; import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; import { ENGINE_WEIGHT, speakerFor } from "umtool-report-to-video/cast"; import { REPORTS_ROOT } from "../paths.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -187,7 +188,7 @@ export async function auditionPlan(dir, candidates, text, { relBase = AUDITION_D /** A sound brought to AUDITION_LUFS, 48 kHz mono (one loudnorm pass), `from` -> `to`; `from` removed when asked. */ export async function levelTo(from, to, { start = null, seconds = null } = {}) { - const tmp = `${to}.tmp-${process.pid}.wav`; + const tmp = tmpPathFor(to, { ext: ".wav" }); await execFileP(FFMPEG(), [ "-nostdin", "-v", "error", "-y", ...(start !== null ? ["-ss", String(start)] : []), "-i", from, ...(seconds !== null ? ["-t", String(seconds)] : []), "-vn", "-af", `loudnorm=I=${AUDITION_LUFS}:TP=-2:LRA=11`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", tmp, @@ -354,7 +355,7 @@ export async function scoreAuditions(project, character, plan, { engineOpts = {} } const file = path.join(project.dir, ...AUDITION_SCORES.split("/")); await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify({ version: 1, rows: scores.rows }, null, 1)}\n`); await rename(tmp, file); return { speaker: speaker.name, rows, reference, pieces: doc.speakers?.[0]?.kept ?? null }; diff --git a/umtool/lib/report/castStore.mjs b/umtool/lib/report/castStore.mjs @@ -17,6 +17,7 @@ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { CAST_FORMAT, CAST_VERSION, emptyCast, validateCast } from "umtool-report-to-video/cast"; import { REPORTS_ROOT } from "../paths.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CAST_UNDO_KEEP = 50; @@ -96,7 +97,7 @@ export async function readCastUndo(file) { async function writeAtomic(file, text) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -55,6 +55,7 @@ import { ChromeRefused, addDeckChrome } from "./manifest.mjs"; import { socialTexts } from "umtool-report-to-video/social"; import { PIPELINE_DIR } from "./driver.mjs"; import { dedupeMedia, seedFromParent } from "./iterations.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const OPS = path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs"); const SCREENSHOT_MISSING = /no captured screenshot/; @@ -429,7 +430,7 @@ STEPS["draft-social"] = async (ctx) => { }; async function writeJson(file, value) { - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/clipSuggest.mjs b/umtool/lib/report/clipSuggest.mjs @@ -17,6 +17,7 @@ import { readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; import { readSuggestions, suggestionsState } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SUGGEST_TASK = "clips-suggest"; export const SUGGEST_JOB_FILE = ".clip-suggest-job.json"; @@ -82,7 +83,7 @@ export async function readSuggestJob(dir) { /** Remember the job a Suggest or an Ask started (tmp + rename). */ export async function writeSuggestJob(dir, rec) { const file = jobFileOf(dir); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(rec)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/clipsLive.mjs b/umtool/lib/report/clipsLive.mjs @@ -51,6 +51,7 @@ import { SHADOW_CHANNELS } from "umtool-report-to-video/sources"; import { ClipsNewError } from "./clipsNew.mjs"; import { WORDS_FILE, proposeProject } from "./reactions.mjs"; import { LIVE_PROJECT_FILE, readLiveProject } from "./liveProject.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LIVE_TRANSCRIPT_FILENAME = "live-transcript.json"; export { LIVE_PROJECT_FILE, readLiveProject }; @@ -65,7 +66,7 @@ const readJson = (f) => readFile(f, "utf8").then(JSON.parse, () => null); async function writeWhole(file, doc) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs @@ -41,6 +41,7 @@ import { renderCut, snapKnobs } from "umtool-report-to-video/snap"; import { transitionStyleOf } from "umtool-report-to-video/transition"; import { CACHE_DIR } from "../paths.mjs"; import { channelsDirFor, cuesForSource, hasShadowChannels, readManifest } from "../projects/report.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Bump when what is cached changes shape. */ const CACHE_VERSION = 1; @@ -77,7 +78,7 @@ async function cached(kind, key, make) { const value = await make(); try { await mkdir(/* turbopackIgnore: true */ cacheDir(), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify({ key, value })); await rename(/* turbopackIgnore: true */ tmp, file); } catch { diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs @@ -40,6 +40,7 @@ import path from "node:path"; import { LEFT_OUT_VERDICTS, clipMomentKey, readMontageRulings } from "umtool-report-to-video/montage-rulings"; import { fetchPieces, renderGaps } from "umtool-report-to-video/gaps"; import { agentToken } from "../annotations/agentAuth.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const FETCH_RUNS_FILE = "fetch-runs.json"; export const MANIFEST_FILE = "video.manifest.json"; @@ -382,7 +383,7 @@ export async function readFetchRuns(projectDir) { async function writeRuns(projectDir, doc) { const file = path.join(projectDir, FETCH_RUNS_FILE); await mkdir(projectDir, { recursive: true }); - const tmp = `${file}.${process.pid}.${Date.now()}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 1) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/groupProposals.mjs b/umtool/lib/report/groupProposals.mjs @@ -20,6 +20,7 @@ import { checkGroupProposals, markGroupProposals, readGroupProposals, writeGroup import { readManifest } from "../projects/report.mjs"; import { StaleToken, manifestToken, setGroup } from "./manifest.mjs"; import { assistJobView } from "./videoAssist.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const GROUPS_TASK = "propose-groups"; export const GROUPS_JOB_FILE = ".propose-groups-job.json"; @@ -60,7 +61,7 @@ export async function readGroupsJob(dir) { export async function writeGroupsJob(dir, rec) { const file = jobFileOf(dir); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(rec)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/iterations.mjs b/umtool/lib/report/iterations.mjs @@ -27,6 +27,7 @@ import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { link, lstat, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MANIFEST_NAME = "video.manifest.json"; // Below this a segment is not worth a hash (a voice always is: it is small @@ -42,7 +43,7 @@ async function readJson(file) { // Replace `file` whole: a temp beside it, then a rename. async function writeJsonAtomic(file, value) { - const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs @@ -31,6 +31,7 @@ import path from "node:path"; import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom } from "umtool-report-to-video/cues"; import { qrsOf } from "umtool-report-to-video/lint"; import { jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LINKS_FILE = "links.json"; export const linksFile = (dir) => path.join(dir, "out", LINKS_FILE); @@ -298,7 +299,7 @@ export async function runLinkCheck(dir, manifest, opts = {}) { const doc = await checkLinks(linksOf(manifest), { siteIdOf: await projectSiteIdOf(dir, manifest), ...opts }); const file = linksFile(dir); await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(tmp, file); return doc; diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -100,6 +100,7 @@ import { import { DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, publishWarnings, pruneDrafted, validateDrafted, validatePublish, } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // Its own write queue, not lib/state.ts's. // @@ -191,7 +192,7 @@ async function writeManifestAtomic(dir, manifest) { if (before) clearEditedDrafts(before, manifest); else pruneDrafted(manifest); await backupOnce(file); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, serialise(manifest), "utf8"); await rename(tmp, file); return manifestToken(dir); @@ -2559,7 +2560,7 @@ export async function readRemoved(dir) { async function recordRemoved(dir, row) { const rows = [...(await readRemoved(dir)), row]; const file = path.join(dir, REMOVED_FILE); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ removed: rows }, null, 2) + "\n"); await rename(tmp, file); } @@ -4890,7 +4891,7 @@ export async function undoStructural(dir, { token = null } = {}) { // within the same second as another snapshot: the state is already kept } const file = manifestFile(dir); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); const undone = target.rel.replace(`-${target.label}.manifest.json`, `-undone-${op}.manifest.json`); @@ -4908,7 +4909,7 @@ export async function undoStructural(dir, { token = null } = {}) { await writeFile(path.join(dir, saved.replace(/\.manifest\.json$/, ".draft.json")), JSON.stringify(now, null, 2) + "\n", "utf8").catch(() => {}); } if (side && typeof side === "object" && typeof side.from === "string" && side.from) { - const tmpD = `${draftFile}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmpD = tmpPathFor(draftFile); await writeFile(tmpD, JSON.stringify(side, null, 2) + "\n", "utf8"); await rename(tmpD, draftFile); draft = side; @@ -4983,7 +4984,7 @@ export async function redoStructural(dir, { token = null } = {}) { const text = await readFile(path.join(dir, head.rel), "utf8"); JSON.parse(text); const file = manifestFile(dir); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); const side = (rel) => path.join(dir, rel.replace(/\.manifest\.json$/, ".draft.json")); @@ -4999,7 +5000,7 @@ export async function redoStructural(dir, { token = null } = {}) { if (pointer !== undefined) { const draftFile = path.join(dir, "takes", "draft.json"); if (pointer && typeof pointer === "object" && typeof pointer.from === "string" && pointer.from) { - const tmpD = `${draftFile}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmpD = tmpPathFor(draftFile); await writeFile(tmpD, JSON.stringify(pointer, null, 2) + "\n", "utf8"); await rename(tmpD, draftFile); draft = pointer; diff --git a/umtool/lib/report/montageRulings.mjs b/umtool/lib/report/montageRulings.mjs @@ -35,6 +35,7 @@ import { parseMontageRulings, rulingsLines, } from "umtool-report-to-video/montage-rulings"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const EDITS_FILE = "edits.json"; export const INSTANCES_FILE = "instances.json"; @@ -97,7 +98,7 @@ async function writeDoc(file, doc) { await mkdir(path.dirname(file), { recursive: true }); // Keys in order, so the file diffs as the deck walks. const rulings = Object.fromEntries(Object.entries(doc.rulings).sort(([a], [b]) => a.localeCompare(b))); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ version: RULINGS_VERSION, rulings }, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/patchMarkers.mjs b/umtool/lib/report/patchMarkers.mjs @@ -23,6 +23,7 @@ // Plain ESM: the CLI runs it under bare node. import { readdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const PATCH_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.patch\.json$/; @@ -125,7 +126,7 @@ export async function syncPatchMarkers(dir, before, after) { const notes = reanchorPatch(patch, anchors); if (!notes.length) continue; try { - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(patch, null, 2)}\n`); await rename(tmp, file); out.push({ file: name, notes }); @@ -201,7 +202,7 @@ export async function fixStalePatchMarkers(dir, manifest, file) { } else left.push({ index, label, after }); }); if (notes.length) { - const tmp = `${full}.tmp-${process.pid}`; + const tmp = tmpPathFor(full); await writeFile(tmp, `${JSON.stringify(patch, null, 2)}\n`); await rename(tmp, full); } @@ -257,7 +258,7 @@ export async function syncSectionMarkers(dir, before, after) { const deck = doc.render.chrome.deck; if (Array.isArray(after) && after.length) deck.markers = JSON.parse(now); else delete deck.markers; - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, indentOf(text)) + "\n", "utf8"); await rename(tmp, file); synced.push(name); diff --git a/umtool/lib/report/postSay.mjs b/umtool/lib/report/postSay.mjs @@ -22,6 +22,7 @@ import { } from "umtool-report-to-video/post-say"; import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { readManifest } from "../projects/report.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export class SayError extends Error { constructor(message) { @@ -76,7 +77,7 @@ async function readJson(file) { async function writeJsonAtomic(file, value) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Date.now()}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 1)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/quoteCheck.mjs b/umtool/lib/report/quoteCheck.mjs @@ -31,6 +31,7 @@ import { resolveLocalSource } from "umtool-report-to-video/sources"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; import { channelsLayersFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const QUOTE_CHECK_FILE = "quote-check.json"; /** Seconds either side of the cut that are transcribed: the 6 Nov offsets reached 13.6 s. */ @@ -78,7 +79,7 @@ export async function readQuoteCheck(dir) { async function writeQuoteCheck(dir, doc) { const file = path.join(dir, QUOTE_CHECK_FILE); - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`); await rename(tmp, file); return file; diff --git a/umtool/lib/report/reactions.mjs b/umtool/lib/report/reactions.mjs @@ -58,6 +58,7 @@ import { SITES_DIR } from "../paths.mjs"; import { replaceManifest, manifestToken, StaleToken } from "./manifest.mjs"; import { REPO_ROOT } from "../paths.mjs"; import { UMTOOL_DIR } from "./driver.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { REACTIONS_FILE }; export const WORDS_FILE = "words.json"; @@ -149,7 +150,7 @@ const scanFile = (projectDir, channel, video, what) => path.join(/* turbopackIgn async function writeWhole(file, doc) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/recordSession.mjs b/umtool/lib/report/recordSession.mjs @@ -16,6 +16,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { postIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; import { RECORD_LABEL_RE, keepRecording } from "./postRecord.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** A part is at most this large (a minute of opus is well under 1 MB). */ export const SESSION_PART_MAX = 100 * 1024 * 1024; @@ -65,7 +66,7 @@ export async function savePart(projectDir, entry, { n, count, text, para, bytes, // A different split of the script (it was edited): the parts kept so far no longer line up. if (doc.count !== null && doc.count !== count) doc.parts = {}; const name = `p${String(n).padStart(2, "0")}.${extOf(type)}`; - const tmp = path.join(dir, `.${name}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(dir, `.${name}`)); await writeFile(tmp, bytes); const old = doc.parts[String(n)]; await rename(tmp, path.join(dir, name)); diff --git a/umtool/lib/report/reelHistory.mjs b/umtool/lib/report/reelHistory.mjs @@ -9,6 +9,7 @@ // diffReel is pure; the writer (trailerBeats.mjs beatsWrite, undo) appends. import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const REEL_HISTORY_CAP = 200; const FIELDS = ["id", "start", "end", "gaps", "at", "dur", "label", "verdict"]; @@ -85,7 +86,7 @@ export async function appendReelHistory(dir, rel, { what, take = null, before, a const file = historyFileOf(dir, rel); const entries = [...(await readReelHistory(dir, rel)), entry].slice(-REEL_HISTORY_CAP); await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ file: rel, entries }, null, 1) + "\n", "utf8"); await rename(tmp, file); return entry; diff --git a/umtool/lib/report/renderRecord.mjs b/umtool/lib/report/renderRecord.mjs @@ -50,6 +50,7 @@ import { createWriteStream, readFileSync } from "node:fs"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const RENDER_FILE = "render.json"; export const RENDER_LOG = "render.log"; @@ -206,10 +207,8 @@ export const WAITING_LINE = /^(queue-lock|heavy):.*\b(waiting|held for a render) /** A line that says it was let in. */ const ADMITTED_LINE = /^(queue-lock|heavy):.*\b(admitted|acquired|going on)\b/i; -let tmpSeq = 0; async function writeAtomic(file, doc) { - tmpSeq += 1; - const tmp = `${file}.${process.pid}.${tmpSeq}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/reviewPass.mjs b/umtool/lib/report/reviewPass.mjs @@ -29,6 +29,7 @@ export { blockAnswer, reviewBlocks, reviewProgress }; export const REVIEW_PASS_FILE = "review-pass.json"; export { REVIEW_MARKS } from "./reviewPassModel.mjs"; import { REVIEW_MARKS } from "./reviewPassModel.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** A Fix's note, at most (a correction is the bench's sixth field; this is its post-and-card twin). */ export const REVIEW_NOTE_LIMIT = 2000; @@ -137,7 +138,7 @@ export async function setReviewMark(dir, manifest, block, mark, { note, now = ne if (mark === null) delete doc.marks[block]; else doc.marks[block] = { mark, ...(text ? { note: text } : {}), sig: entrySignature(e), at: now.toISOString() }; await mkdir(dir, { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); return { doc, mark: doc.marks[block] ?? null }; diff --git a/umtool/lib/report/sourceBacklog.mjs b/umtool/lib/report/sourceBacklog.mjs @@ -29,6 +29,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { channelFor, clipsOf } from "../projects/report.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SOURCE_WATCH_FILE = "source-watch.json"; export const SOURCE_WATCH_FORMAT = "umtool-source-watch"; @@ -172,7 +173,7 @@ function writeSourceWatch(dir, mutate) { const result = mutate(doc); const out = { format: SOURCE_WATCH_FORMAT, version: 1, watch: doc.watch, ...(doc.last ? { last: doc.last } : {}) }; await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(out, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/report/speakerCheck.mjs b/umtool/lib/report/speakerCheck.mjs @@ -32,6 +32,7 @@ import { channelsDirFor, hasShadowChannels, readManifest } from "../projects/rep import { REPO_ROOT } from "../paths.mjs"; import { UMTOOL_DIR } from "./driver.mjs"; import { planClips, referenceRecordings } from "./voiceMatch.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SPEAKERS_FILE = "speakers.json"; const NAME_RE = /^[^\s/=,][^/=,]{0,47}$/; @@ -80,7 +81,7 @@ export async function readSpeakers(dir) { export async function writeSpeakers(dir, speakers) { const list = normalizeSpeakers({ speakers }); const file = path.join(dir, SPEAKERS_FILE); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); const doc = { speakers: list.map((s) => ({ name: s.name, ...(s.clips.length ? { clips: s.clips } : {}), ...(s.videos.length ? { videos: s.videos } : {}), ...(s.channels.length ? { channels: s.channels } : {}) })) }; await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(tmp, file); diff --git a/umtool/lib/report/takeCancel.mjs b/umtool/lib/report/takeCancel.mjs @@ -31,6 +31,7 @@ import os from "node:os"; import path from "node:path"; import { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs"; import { isTakeId, takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CANCEL_FILE = ".cancel.json"; export const CANCELLED_FILE = "cancelled.json"; @@ -48,7 +49,7 @@ export class TakeCancelled extends Error { const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); async function writeJson(file, doc) { - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -52,6 +52,7 @@ import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; import { resolveTakeManifest } from "./takeManifest.mjs"; import { isTakeId, listTakes, setTakePicked, takesDirOf, TAKE_FILE } from "./takes.mjs"; import { stampOf } from "./snapshots.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const TAKE_REVISIONS_DIR = "revisions"; const AUTO = "auto-before-"; @@ -126,7 +127,7 @@ async function keepRevision(projectDir, id, text, label, now) { async function writeTakeAtomic(projectDir, id, doc) { const file = takeFileOf(projectDir, id); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, serialise(doc), "utf8"); await rename(tmp, file); return takeToken(projectDir, id); @@ -461,7 +462,7 @@ export async function undoTakeEdit(projectDir, id, { token = null, now = new Dat JSON.parse(restored); // a revision that does not parse is not restored over a take.json that does const saved = await keepRevision(projectDir, id, text, "undo-saved", now); const file = takeFileOf(projectDir, id); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, restored, "utf8"); await rename(tmp, file); const undone = target.name.replace(`-${target.label}.take.json`, `-undone-${op}.take.json`); diff --git a/umtool/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs @@ -69,6 +69,7 @@ import { makeLinker } from "umtool-report-to-video/link-or-copy"; import { KEEP_FRAMES_DIR, keptFramesDir } from "umtool-report-to-video/prune-frames"; import { seedLadderFit } from "umtool-report-to-video/variants"; import { takesDirOf } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Where a take keeps a layer aside: its `out/.keep-frames/<layer>-frames` (prune-frames.mjs). */ export { KEEP_FRAMES_DIR }; @@ -273,7 +274,7 @@ async function linkVariant({ src, dst, kept, from, chunks: withChunks = true }) const [theirMemo, ownMemo] = await Promise.all([memoOf(src), memoOf(dst)]); if (theirMemo?.v === 1 && theirMemo.h) { const merged = { v: 1, h: { ...theirMemo.h, ...(ownMemo?.v === 1 ? ownMemo.h : {}) } }; - const tmp = path.join(dst, `${HASH_MEMO_FILE}.${process.pid}.tmp`); + const tmp = path.join(dst, tmpPathFor(HASH_MEMO_FILE)); await writeFile(tmp, JSON.stringify(merged), "utf8"); await rename(tmp, path.join(dst, HASH_MEMO_FILE)); } @@ -282,7 +283,7 @@ async function linkVariant({ src, dst, kept, from, chunks: withChunks = true }) // named files) is found through this: build-video adopts it when this // take's segments are those very files (xfadeBatchKeyV1). if (await isDir(batchOut)) { - const tmp = path.join(batchOut, `${XFADE_FROM_FILE}.${process.pid}.tmp`); + const tmp = path.join(batchOut, tmpPathFor(XFADE_FROM_FILE)); await writeFile(tmp, JSON.stringify({ take: from, segments: path.resolve(segs) }) + "\n", "utf8"); await rename(tmp, path.join(batchOut, XFADE_FROM_FILE)); } diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -59,6 +59,7 @@ import { replaceManifest } from "./manifest.mjs"; import { incorrectClips, incorrectWhy } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { autoPickTake, frozenBaseText, isTakeId, isWorkingTake, listTakes, parseWindow, setTakePicked, takesDirOf, BASE_FILE, DRAFT_FILE, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MANIFEST = "video.manifest.json"; export const PREVIEW = "preview.mp4"; @@ -840,7 +841,7 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { } : {}), }; - const tmp = `${takeFile}.tmp-${process.pid}`; + const tmp = tmpPathFor(takeFile); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, takeFile); // A whole-cut take of the DRAFT as it is (not a frozen version re-rendered) is the draft's parent now (versions.mjs). @@ -933,7 +934,7 @@ export async function draftTake(projectDir, rawSpec, opts = {}) { baseHash: hashText(baseText), }; await mkdir(takeDir, { recursive: true }); - const tmp = `${takeFile}.tmp-${process.pid}`; + const tmp = tmpPathFor(takeFile); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, takeFile); const clips = manifest.timeline.filter((e) => isObj(e) && e.type === "clip").length; @@ -966,7 +967,7 @@ async function moveFile(from, to) { } catch (err) { if (/** @type {any} */ (err)?.code !== "EXDEV") throw err; const { copyFile, unlink } = await import("node:fs/promises"); - const tmp = `${to}.tmp-${process.pid}`; + const tmp = tmpPathFor(to); await copyFile(from, tmp); await rename(tmp, to); await unlink(from).catch(() => {}); diff --git a/umtool/lib/report/takeManifest.mjs b/umtool/lib/report/takeManifest.mjs @@ -26,6 +26,7 @@ import { readFile, stat, writeFile, rename } from "node:fs/promises"; import path from "node:path"; import { ALL_STYLES_RECIPE, MANIFEST, RECIPE_FILE, loadMontageStyles, mergePatch, parseRecipe } from "./takeMaker.mjs"; import { BASE_FILE, frozenBaseText, isTakeId, listTakes, parseTake, takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { frozenBaseText }; @@ -211,12 +212,11 @@ export async function cachedTakeManifest(projectDir, id) { // server process -- and with `<file>.<pid>.tmp` the two shared the tmp: the first rename took it, the second // failed ENOENT, and Play said "the intro did not compose" (the intro-play flake, L8a/L4, 9 Nov). The last // rename wins; both write the same take as it is. -let playManifestSeq = 0; /** Write a take's play manifest (tmp + rename); returns its path. Safe to call concurrently. */ export async function writePlayManifest(projectDir, id, manifest) { const file = playManifestPath(projectDir, id); - const tmp = `${file}.${process.pid}.${++playManifestSeq}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(manifest, null, 2)}\n`, "utf8"); await rename(tmp, file); return file; diff --git a/umtool/lib/report/takePreview.mjs b/umtool/lib/report/takePreview.mjs @@ -39,6 +39,7 @@ import { promisify } from "node:util"; import { applyMontageRulings, readMontageRulings } from "umtool-report-to-video/montage-rulings"; import { composeTake, checkSpec, estimatedSeconds, getPath, linkSharedOut, MANIFEST, mergePatch, QUICK_RENDER, sourcedEntries, windowManifest } from "./takeMaker.mjs"; import { takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -742,7 +743,7 @@ export async function changesTake(projectDir, id, opts = {}) { } const list = path.join(work, "pieces.txt"); await writeFile(list, files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n", "utf8"); - const tmp = p.changesMp4.replace(/\.mp4$/, `.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(p.changesMp4.replace(/\.mp4$/, ""), { ext: ".mp4" }); await execFileP(FFMPEG, ["-nostdin", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", list, "-c", "copy", "-movflags", "+faststart", tmp], { maxBuffer: 1 << 26 }); await rename(tmp, p.changesMp4); await rm(work, { recursive: true, force: true }); @@ -777,7 +778,7 @@ export async function changesTake(projectDir, id, opts = {}) { async function writeAtomic(file, doc) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/takePrune.mjs b/umtool/lib/report/takePrune.mjs @@ -91,6 +91,7 @@ import path from "node:path"; import { MEDIA_ROOT, REPORTS_ROOT, inside, mediaMirror } from "../paths.mjs"; import { namesProject, pipelineProcesses } from "./busy.mjs"; import { TAKES_DIR, isTakeId, parseTake, readVerdictsStrict, takesDirOf } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** The project's prune settings: `takes/prune.json`. */ export const POLICY_FILE = "prune.json"; @@ -280,7 +281,7 @@ export function lockIsLive(lock, { host = os.hostname(), alive = pidAlive } = {} export async function writeBuildLock(dir, info = {}, { now = () => new Date() } = {}) { const file = path.join(/* turbopackIgnore: true */ dir, BUILD_LOCK); const doc = { pid: process.pid, host: os.hostname(), startedAt: now().toISOString(), ...info }; - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc) + "\n", "utf8"); await rename(tmp, file); return file; @@ -969,7 +970,7 @@ async function appendPruneRecord(takeDir, entry) { const prev = await readJson(file); const prunes = Array.isArray(prev?.prunes) ? prev.prunes : []; const doc = { format: "umtool-pruned-work", version: 1, prunes: [...prunes, entry].slice(-PRUNE_RECORD_KEEP) }; - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs @@ -19,6 +19,7 @@ import { mkdir, readdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { inside } from "../paths.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const TAKES_DIR = "takes"; export const TAKE_FILE = "take.json"; @@ -359,7 +360,7 @@ async function readVerdictsForWrite(file) { async function writeVerdicts(file, map) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/trailerBeats.mjs b/umtool/lib/report/trailerBeats.mjs @@ -44,6 +44,7 @@ import { indentOf } from "./patchMarkers.mjs"; import { appendReelHistory } from "./reelHistory.mjs"; import { sectionModel, sectionWords } from "./sectionEdit.mjs"; import { trailerCandidates } from "./trailerCandidates.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const TRAILER_BEATS_FILE = path.join("promo", "trailer-beats.json"); /** The reel a caller that names none reads and writes: promo/trailer-beats.json. */ @@ -185,7 +186,7 @@ export async function readReelUndo(dir, { reel = DEFAULT_REEL } = {}) { async function writeUndo(dir, reel, points) { const file = undoFileOf(dir, reel); await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ reel, file: reelFileOf(reel), points: points.slice(-REEL_UNDO_KEEP) }, null, 1) + "\n", "utf8"); await rename(tmp, file); } @@ -226,7 +227,7 @@ async function beatsWrite(dir, token, mutate, { reel = DEFAULT_REEL, what = "an if (read.exists) await copyFile(file, `${file}.bak`).catch(() => {}); // The undo point: the file as it was, before this write. await writeUndo(dir, reel, [...(await readReelUndo(dir, { reel })), { at: new Date().toISOString(), what, text: read.exists ? read.text : null }]); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(out, null, read.indent) + "\n", "utf8"); await rename(tmp, file); // The history (reelHistory.mjs): what moved, old and new, by beat. @@ -253,7 +254,7 @@ export async function undoTrailerBeats(dir, { token = null, reel = DEFAULT_REEL const before = await readTrailerBeats(dir, { reel }).catch(() => null); if (last.text === null) await rm(file, { force: true }); else { - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, last.text, "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/variantFork.mjs b/umtool/lib/report/variantFork.mjs @@ -44,6 +44,7 @@ import { isSegment, walkProjects } from "../projects/walk.mjs"; import { renderHolds } from "./takeHousekeeping.mjs"; import { MANIFEST, PREVIEW, SHARED_OUT, hashText } from "./takeMaker.mjs"; import { isTakeId, listTakes, takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const VARIANT_FILE = "variant.json"; /** Copied, never linked: what a variant may change of its own. */ @@ -55,7 +56,7 @@ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); const exists = (p) => lstat(p).then(() => true, () => false); async function writeAtomic(file, text) { - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/versions.mjs b/umtool/lib/report/versions.mjs @@ -37,6 +37,7 @@ import { applyStructural, manifestToken, replaceManifestLocked, StaleToken, with import { withEditNotes } from "./edit-guard.mjs"; import { BASE_FILE, DRAFT_FILE, frozenBaseText, isTakeId, listTakes, readDraftFile, takesDirOf, TAKE_FILE } from "./takes.mjs"; import { readWorkingCut } from "./workingCut.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const MANIFEST = "video.manifest.json"; export const VERSION_RE = /^v(\d{1,6})$/; @@ -70,7 +71,7 @@ export async function writeDraft(projectDir, { from, hash = null, at = null, bas if (!isTakeId(from)) throw new Error(`"${from}" is not a take id`); await mkdir(path.dirname(file), { recursive: true }); const doc = { from, hash, at: at ?? new Date().toISOString(), ...(base ? { base } : {}) }; - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); return doc; @@ -126,7 +127,7 @@ export async function claimVersionId(projectDir) { } async function writeAtomic(file, text) { - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/videoAssist.mjs b/umtool/lib/report/videoAssist.mjs @@ -28,6 +28,7 @@ import { markProposals, readAssistProposals, writeAssistProposals } from "yt-dlp import { readManifest } from "../projects/report.mjs"; import { StaleToken, manifestToken, updateChrome, updateRender } from "./manifest.mjs"; import { runClipEditorOp } from "./clipEditor.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const ASSIST_TASK = "video-assist"; export const ASSIST_JOB_FILE = ".video-assist-job.json"; @@ -86,7 +87,7 @@ export async function readAssistJob(dir) { /** Remember the job an Ask started (tmp + rename). */ export async function writeAssistJob(dir, rec) { const file = jobFileOf(dir); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(rec)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/research/cases.mjs b/umtool/lib/research/cases.mjs @@ -30,6 +30,7 @@ import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { PIECE_SEGMENT_RE, casePieceId } from "../pieces/ids.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CASE_FORMAT = "umtool-research-case"; export const CASE_VERSION = 1; @@ -331,7 +332,7 @@ function serialised(fn) { async function writeCase(reportsRoot, doc) { const file = caseFile(reportsRoot, doc.id); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/research/census.mjs b/umtool/lib/research/census.mjs @@ -19,6 +19,7 @@ import { createHash } from "node:crypto"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CENSUS_FORMAT = "umtool-research-census"; export const CENSUS_VERSION = 1; @@ -90,7 +91,7 @@ export function writeCensus(reportsRoot, handle, identity, channels, { now } = { channels: Object.fromEntries(Object.entries(channels).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), }; await mkdir(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/research/log.mjs b/umtool/lib/research/log.mjs @@ -16,6 +16,7 @@ // somebody fixes it; a read treats it as empty and says so in `error`). import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LOG_FORMAT = "umtool-research-log"; export const LOG_VERSION = 1; @@ -135,7 +136,7 @@ async function write(reportsRoot, session, key, state, meta) { marks: Object.fromEntries(Object.entries(marks).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), }; await mkdir(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/research/triage-marks.mjs b/umtool/lib/research/triage-marks.mjs @@ -15,6 +15,7 @@ // Plain ESM: the unit test reads it the way the app does. import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MARKS_FORMAT = "umtool-triage-marks"; export const MARKS_VERSION = 1; @@ -99,7 +100,7 @@ export function setMark(reportsRoot, schedule, m) { doc.updatedAt = at; const file = marksFile(reportsRoot, schedule); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/state.ts b/umtool/lib/state.ts @@ -2,6 +2,7 @@ import { readFile, writeFile, rename, mkdir } from "node:fs/promises"; import { existsSync } from "node:fs"; import path from "node:path"; import { stateFile, dataFile } from "./paths"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // The JSON state has TWO writers: this app and the CLI scripts (decode-um.mjs // applies paste-backs from the static page, which stays usable). A lost update @@ -24,7 +25,7 @@ export async function readJson<T>(file: string, fallback: T): Promise<T> { export async function writeJsonAtomic(file: string, value: unknown): Promise<void> { const dir = path.dirname(file); if (!existsSync(dir)) await mkdir(dir, { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(value, null, 1)); await rename(tmp, file); } diff --git a/umtool/report-to-video/basic.mjs b/umtool/report-to-video/basic.mjs @@ -40,6 +40,7 @@ import { basicFadeOf, basicOn } from "yt-dlp-transcript-common/lib/report/look.m import { clipBlurOf } from "./clip-blur.mjs"; import { keptSpans, renderGaps } from "./gaps.mjs"; import { hasLocalMedia } from "./local-media.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const fin = (v) => typeof v === "number" && Number.isFinite(v); @@ -294,7 +295,7 @@ export async function renderBasic({ manifest, dirs, only = null, deps }) { emit("concat", { mode: "hardcut", n: files.length }); await mkdir(path.dirname(dirs.final), { recursive: true }); // Through a temporary name: a concat that fails never leaves a half file at the deliverable's path. - const finalTmp = `${dirs.final}.tmp-${process.pid}.mp4`; + const finalTmp = tmpPathFor(dirs.final, { ext: ".mp4" }); try { await exec(ffmpeg, concatArgs(list, finalTmp)); await rename(finalTmp, dirs.final); diff --git a/umtool/report-to-video/build-podcast.mjs b/umtool/report-to-video/build-podcast.mjs @@ -42,6 +42,7 @@ import { promisify } from "node:util"; import { deckOn, deckQrUrl, segmentSoundEdits, soundEdges, teaserTitle } from "./deck.mjs"; import { hasNarration, narrationsOf } from "./narration.mjs"; import { narrationDir, readCutDisclosure } from "./narration-store.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -372,7 +373,7 @@ export async function buildPodcast({ manifestPath, variant = "sourced", out = nu await writeFile(metaPath, podcastFfmeta(chapters, { title: manifest.title ?? null, disclosure: disclosure?.replace(/\n/g, " ") ?? null }), "utf8"); emit("podcast", { phase: "encode", m4a: path.basename(m4a), mp3: mp3 ? path.basename(mp3) : null }); const encode = async (file, codec) => { - const tmp = file.replace(/(\.[a-z0-9]+)$/, `.${process.pid}.tmp$1`); + const tmp = tmpPathFor(file.replace(/\.[a-z0-9]+$/, ""), { ext: /\.[a-z0-9]+$/.exec(file)?.[0] ?? "" }); try { await execFileP(FFMPEG(), [ "-nostdin", "-v", "error", "-y", "-i", work, "-i", metaPath, diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -863,6 +863,7 @@ export { WIN_EPS, cachedWindowsFor, findContainingWindow, listRawNames, rawWindowName, tightestContaining, windowContains, windowsFromNames, } from "./sources.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // The yt-dlp argv for one clip window. The platform's fixed args come from // common's table (`platformArgsForUrl`) -- the same copy every editor spawn @@ -2239,7 +2240,7 @@ async function placeShort(seg, manifestDir, entry, render) { const dir = path.join(manifestDir, "shorts"); await mkdir(dir, { recursive: true }); const dest = path.join(dir, `${entry.id}.mp4`); - const tmp = `${dest}.tmp-${process.pid}`; + const tmp = tmpPathFor(dest); await writeFile(tmp, await readFile(seg)); await rename(tmp, dest); const rec = await readCutRecord(seg).catch(() => null); @@ -2699,7 +2700,7 @@ export async function detachSegmentFiles(segDir, id) { /** Write `text` to `file` through a rename: a link at `file` is replaced, never written through. */ async function replaceFile(file, text) { - const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(path.dirname(file), `.${path.basename(file)}`)); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } @@ -2856,7 +2857,7 @@ async function buildNarratedCardSegment(card, render, outDir, nodes, framing, re return seg; } const png = await renderCard(resolved, render, outDir, nodes); - const tmp = path.join(path.dirname(seg), `.${card.id}.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(path.join(path.dirname(seg), `.${card.id}`), { ext: ".mp4" }); try { await execFileP(FFMPEG, narratedCardEncodeArgs({ png, wav: narrationWavPath(dir, rec.key), seconds, vf, audio, render, outPath: tmp, @@ -2970,7 +2971,7 @@ export async function buildTeaserSegment(entry, { manifestPath, render, outDir, // on disk may be a hard link to another take's (linked in to re-lay chrome // over it), and a rename replaces this take's name without writing a byte of // the other take's file. - const tmp = path.join(path.dirname(seg), `.${entry.id}.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(path.join(path.dirname(seg), `.${entry.id}`), { ext: ".mp4" }); try { await execFileP(FFMPEG, teaserEncodeArgs({ framesDir: r.frames, seconds, render, audio, outPath: tmp }), { maxBuffer: 1 << 26 }); await rename(tmp, seg); @@ -3049,7 +3050,7 @@ async function buildVideoEntrySegment(entry, render, outDir, baseDir, D, timelin level = { measured, gain: loudnessGain(measured, target), target, basis }; } const graph = videoSegmentGraph({ entry, render, seconds, lead, hasAudio, gainDb: level?.gain ?? null, span }); - const tmp = `${seg}.tmp-${process.pid}.mp4`; + const tmp = tmpPathFor(seg, { ext: ".mp4" }); await execFileP(FFMPEG, [ "-nostdin", "-v", "error", "-y", "-i", src.file, "-filter_complex", graph, "-map", "[v]", "-map", "[a]", diff --git a/umtool/report-to-video/chunked-encode.mjs b/umtool/report-to-video/chunked-encode.mjs @@ -45,6 +45,7 @@ import { createHash } from "node:crypto"; import { readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Bumped when what a chunk key covers changes: every chunk is encoded once more. */ export const CHUNK_KEY_VERSION = 1; @@ -239,8 +240,7 @@ export class HashMemo { async save() { if (!this.file || !this.dirty) return; // A tmp of its own per save: a build may save while another save of the same memo is in flight. - HashMemo.saves = (HashMemo.saves ?? 0) + 1; - const tmp = `${this.file}.${process.pid}.${HashMemo.saves}.tmp`; + const tmp = tmpPathFor(this.file); await writeFile(tmp, JSON.stringify({ v: 1, h: Object.fromEntries(this.map) }), "utf8"); await rename(tmp, this.file); this.dirty = false; diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -48,6 +48,7 @@ import { FRAME_KEYS_FILE, SPARSE_FILE } from "./chunked-encode.mjs"; import { poolFor, poolFrame, poolFrameEvents, poolPutFrames } from "./render-pool.mjs"; import { regionCaching, regionModule } from "./modules/index.mjs"; import { stackedDeckWanted, verticalRender } from "./vertical.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const run = promisify(execFile); @@ -1076,7 +1077,7 @@ export { FRAME_KEYS_FILE }; const frameName = (n) => `frame_${String(n).padStart(6, "0")}.png`; async function writeFrameKeys(dir, fk) { - const tmp = path.join(dir, `${FRAME_KEYS_FILE}.${process.pid}.tmp`); + const tmp = path.join(dir, tmpPathFor(FRAME_KEYS_FILE)); await writeFile(tmp, fk.join("\n") + "\n", "utf8"); await rename(tmp, path.join(dir, FRAME_KEYS_FILE)); } diff --git a/umtool/report-to-video/drafts-review.mjs b/umtool/report-to-video/drafts-review.mjs @@ -45,6 +45,7 @@ import path from "node:path"; import { draftedFields, fieldKey, isCodeDraft, parseReviewAddress, reviewAddress } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; import { narrationsOf } from "./narration.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const DRAFTS_REVIEW_FILE = "drafts.review.json"; /** Release 25's file, read unchanged; never written any more. */ @@ -369,7 +370,7 @@ export async function setDraftReview(manifestDir, address, patch) { } if (row.verdict === null && !row.note && !legacyHas) delete map[address]; else map[address] = row; - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8"); await rename(tmp, file); const stored = row.verdict === null && !row.note ? null : row; diff --git a/umtool/report-to-video/intro.mjs b/umtool/report-to-video/intro.mjs @@ -70,6 +70,7 @@ import { INTRO_URL_PLACES, INTRO_URLS, introErrors, introOf, introSitePrefix, introUrlText, validateIntro, } from "yt-dlp-transcript-common/lib/report/intro.mjs"; import { SITES_DIR } from "../lib/paths.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { INTRO_BEATS, INTRO_BRAND_DEFAULT, INTRO_GROUNDS, INTRO_ID, INTRO_MARKS, INTRO_PROJECT_URL, INTRO_SECONDS, INTRO_SECONDS_MAX, @@ -426,7 +427,7 @@ export async function writeIntroPage(dir, entry, render, { file = "index.html", const at = html.lastIndexOf("</body>"); const page = !extraScript ? html : at < 0 ? html + extraScript : `${html.slice(0, at)}${extraScript}\n ${html.slice(at)}`; const out = path.join(/* turbopackIgnore: true */ dir, file); - const tmp = `${out}.${process.pid}.tmp`; + const tmp = tmpPathFor(out); await writeFile(/* turbopackIgnore: true */ tmp, page, "utf8"); await rename(tmp, out); return { file: out, html }; @@ -501,7 +502,7 @@ export async function renderIntro({ entry, render, encode, manifestDir = process seconds: entry.seconds, render, hasSound: !!sound, soundSeconds: sound ? await probeSeconds(sound) : null, }); await mkdir(cacheDir, { recursive: true }); - const tmp = path.join(/* turbopackIgnore: true */ cacheDir, `.${key}.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(path.join(/* turbopackIgnore: true */ cacheDir, `.${key}`), { ext: ".mp4" }); try { await execFileP(FFMPEG, introEncodeArgs({ framesDir, sound, seconds: entry.seconds, render, encode, audio, outPath: tmp }), { maxBuffer: 1 << 26 }); await rename(tmp, cached); @@ -529,14 +530,14 @@ export async function buildIntroSegment(entry, { render, encode, outDir, manifes return seg; } await mkdir(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ seg), { recursive: true }); - const tmp = path.join(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ seg), `.${entry.id}.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(path.join(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ seg), `.${entry.id}`), { ext: ".mp4" }); try { await copyFile(r.path, tmp); await rename(tmp, seg); } finally { await rm(tmp, { force: true }); } - const recTmp = `${recPath}.${process.pid}.tmp`; + const recTmp = tmpPathFor(recPath); await writeFile(/* turbopackIgnore: true */ recTmp, JSON.stringify({ key: r.key, style: entry.style, ground: entry.ground, mark: entry.mark, seconds: entry.seconds, ...(entry.site ? { site: entry.site.name, swap: entry.swap } : {}), cached: r.cached, diff --git a/umtool/report-to-video/narration-store.mjs b/umtool/report-to-video/narration-store.mjs @@ -20,6 +20,7 @@ import { promisify } from "node:util"; import { disclosureLine, disclosureLines, narrationsOf } from "./narration.mjs"; import { postNarrationDisclosure } from "./post-narration.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -90,7 +91,7 @@ export async function keepNarration(dir, n, result, { jobId = null } = {}) { } await mkdir(dir, { recursive: true }); const wav = narrationWavPath(dir, n.key); - const tmp = path.join(dir, `.${n.key}.${process.pid}.tmp.wav`); + const tmp = tmpPathFor(path.join(dir, `.${n.key}`), { ext: ".wav" }); try { await copyFile(result.wav, tmp); await rename(tmp, wav); @@ -129,7 +130,7 @@ export async function keepNarration(dir, n, result, { jobId = null } = {}) { : disclosureLine(engine, voice), createdAt: new Date().toISOString(), }; - const recTmp = path.join(dir, `.${n.key}.${process.pid}.tmp.json`); + const recTmp = tmpPathFor(path.join(dir, `.${n.key}`), { ext: ".json" }); await writeFile(recTmp, JSON.stringify(record, null, 2) + "\n", "utf8"); await rename(recTmp, narrationRecordPath(dir, n.key)); return record; diff --git a/umtool/report-to-video/post-combo-prints.mjs b/umtool/report-to-video/post-combo-prints.mjs @@ -19,6 +19,7 @@ import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import { COMBO_DEFAULTS, comboCounts, comboItems, comboKnobs, repeatGroups, tiersOf, xMediaIdOf } from "./post-combo.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); @@ -46,7 +47,7 @@ async function cached(file, sig, cacheDir, field, make) { rec[field] = await make(); if (cacheDir) { await mkdir(cacheDir, { recursive: true }).catch(() => {}); - const tmp = path.join(cacheDir, `.${key}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(cacheDir, `.${key}`)); await writeFile(tmp, JSON.stringify(rec), "utf8").then(() => rename(tmp, path.join(cacheDir, `${key}.json`)), () => {}); } } diff --git a/umtool/report-to-video/post-combo-render.mjs b/umtool/report-to-video/post-combo-render.mjs @@ -23,6 +23,7 @@ import { fileURLToPath, pathToFileURL } from "node:url"; import { COMBO_TIMING, comboBadgeHtml, comboFrame, comboPlace, comboStart, comboTransform } from "./post-combo.mjs"; import { panelEntry, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; import { LIMITED_RANGE } from "./color-range.mjs"; +import { writeFileAtomic } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); const r3 = (v) => Math.round(v * 1000) / 1000; @@ -204,8 +205,7 @@ export async function applyPostCombo(seg, entry, { combo, render, outDir, box, e await rename(tmp, seg); const out = sigOf(await stat(seg)); // Through a rename: a record `--from` linked in (another take's) is replaced, never written through. - await writeFile(/* turbopackIgnore: true */ `${record}.tmp`, JSON.stringify({ version: 1, id: entry.id, key, out, count: combo.count, at: cp.at, media: combo.media, region: cp.place.region, sfx: sfx ? combo.knobs.sfx : "off" }, null, 2) + "\n", "utf8"); - await rename(`${record}.tmp`, record); + await writeFileAtomic(record, JSON.stringify({ version: 1, id: entry.id, key, out, count: combo.count, at: cp.at, media: combo.media, region: cp.place.region, sfx: sfx ? combo.knobs.sfx : "off" }, null, 2) + "\n", "utf8"); emit("note", { message: `${entry.id}: combo ×${combo.count} at ${cp.at.toFixed(2)} s${sfx ? ` (sfx ${combo.knobs.sfx})` : ""}` }); return seg; } diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -37,6 +37,7 @@ import { applyVisitState } from "./post-link-visit.mjs"; import { applyMapState, mapPageHtml, mapPlace, mapSize, mapStateAt } from "./post-branch-map.mjs"; import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs"; import { poolFetch, poolFor, poolPut } from "./render-pool.mjs"; +import { writeFileAtomic } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const r3 = (v) => Math.round(v * 1000) / 1000; const num = (v) => String(r3(v)); @@ -1574,8 +1575,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box // The follow frames are in the segment now: a rebuild shoots them again (they are many, and the key decides). if (cards.follow) await rm(path.dirname(cards.follow.list), { recursive: true, force: true }); // Through a rename: a record `--from` linked in (another take's) is replaced, never written through. - await writeFile(`${record}.tmp`, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(cards.slams?.length ? { slams: cards.slams.map((sl) => ({ i: sl.i, text: sl.fx.text, at: sl.t, end: sl.end, source: sl.source, landings: sl.landings, span: { t0: sl.span.t0, t2: sl.span.t2, t3: sl.span.t3 }, where: sl.layout.where, box: { x: sl.layout.x, y: sl.layout.y, width: sl.layout.width, height: sl.layout.height }, ...(sl.layout.bar ? { bar: { text: sl.fx.bar, style: sl.fx.barStyle, x: sl.layout.bar.x, y: sl.layout.bar.y, width: sl.layout.bar.width, height: sl.layout.bar.height } } : {}), size: sl.size, covers: sl.layout.covers, sfx: sl.fx.sfx, shots: sl.shots })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}), ...(Number.isFinite(cards.joinAnchor) ? { joinAnchor: cards.joinAnchor } : {}) }, null, 2) + "\n", "utf8"); - await rename(`${record}.tmp`, record); + await writeFileAtomic(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(cards.slams?.length ? { slams: cards.slams.map((sl) => ({ i: sl.i, text: sl.fx.text, at: sl.t, end: sl.end, source: sl.source, landings: sl.landings, span: { t0: sl.span.t0, t2: sl.span.t2, t3: sl.span.t3 }, where: sl.layout.where, box: { x: sl.layout.x, y: sl.layout.y, width: sl.layout.width, height: sl.layout.height }, ...(sl.layout.bar ? { bar: { text: sl.fx.bar, style: sl.fx.barStyle, x: sl.layout.bar.x, y: sl.layout.bar.y, width: sl.layout.bar.width, height: sl.layout.bar.height } } : {}), size: sl.size, covers: sl.layout.covers, sfx: sl.fx.sfx, shots: sl.shots })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}), ...(Number.isFinite(cards.joinAnchor) ? { joinAnchor: cards.joinAnchor } : {}) }, null, 2) + "\n", "utf8"); if (pool) await poolPut(pool, "post", key, { "seg.mp4": seg, "post.json": record }); emit("note", { message: narration diff --git a/umtool/report-to-video/prune-frames.mjs b/umtool/report-to-video/prune-frames.mjs @@ -33,6 +33,7 @@ import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const PRUNED_RECORD = "pruned.json"; /** Where an out/ keeps its set-aside chrome sequences: `<out>/.keep-frames/`. */ @@ -50,7 +51,7 @@ export function keptFramesDir(outRoot, variant = "sourced") { export async function markKeepFrames(outRoot, { now = () => new Date(), by = "take --keep-frames" } = {}) { const dir = path.join(outRoot, KEEP_FRAMES_DIR); await mkdir(dir, { recursive: true }); - const tmp = path.join(dir, `.${KEEP_FRAMES_ASKED}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(dir, `.${KEEP_FRAMES_ASKED}`)); await writeFile(tmp, `${JSON.stringify({ at: now().toISOString(), by }, null, 2)}\n`, "utf8"); await rename(tmp, path.join(dir, KEEP_FRAMES_ASKED)); } @@ -112,7 +113,7 @@ export async function pruneChromeFrames(variantDir, { now = () => new Date(), se } for (const name of [...sequences, ...work]) bytes += await dirBytes(path.join(chromeDir, name)); const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs }; - const tmp = path.join(chromeDir, `.${PRUNED_RECORD}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(chromeDir, `.${PRUNED_RECORD}`)); await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8"); await rename(tmp, path.join(chromeDir, PRUNED_RECORD)); if (setAside && sequences.length) { @@ -154,7 +155,7 @@ export async function recordPrunedSequences(chromeDir, names, { now = () => new } if (!recorded.length) return recorded; const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs }; - const tmp = path.join(chromeDir, `.${PRUNED_RECORD}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(chromeDir, `.${PRUNED_RECORD}`)); await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8"); await rename(tmp, path.join(chromeDir, PRUNED_RECORD)); return recorded; diff --git a/umtool/report-to-video/reframe.mjs b/umtool/report-to-video/reframe.mjs @@ -20,6 +20,7 @@ import { promisify } from "node:util"; import { postLayout } from "./post-item.mjs"; import { VERTICAL_HEIGHT, VERTICAL_WIDTH, safeArea, verticalKnobs } from "./vertical.mjs"; import { assColour, assTime, captionText } from "./look.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = process.env.FFMPEG ?? "ffmpeg"; @@ -52,7 +53,7 @@ export async function normalizeLoudness(input, output, target, { log = () => {} const spec = `I=${target}:TP=-1.5:LRA=11`; const { stderr } = await execFileP(FFMPEG, ["-nostdin", "-hide_banner", "-i", input, "-af", `loudnorm=${spec}:print_format=json`, "-f", "null", "-"], { maxBuffer: 1 << 26 }); const m = JSON.parse(stderr.slice(stderr.lastIndexOf("{"), stderr.lastIndexOf("}") + 1)); - const tmp = `${output}.tmp-${process.pid}.mp4`; + const tmp = tmpPathFor(output, { ext: ".mp4" }); await execFileP(FFMPEG, [ "-nostdin", "-v", "error", "-y", "-i", input, "-c:v", "copy", "-af", `loudnorm=${spec}:measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:measured_thresh=${m.input_thresh}:offset=${m.target_offset}:linear=true`, diff --git a/umtool/report-to-video/render-pool.mjs b/umtool/report-to-video/render-pool.mjs @@ -51,6 +51,7 @@ import { appendFile, link, lstat, mkdir, readdir, readFile, realpath, rename, rm import path from "node:path"; import { MEDIA_ROOT } from "../lib/paths.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** * The kinds, each with its renderer SALT: bumped when code changes what a @@ -167,7 +168,8 @@ export async function poolPut(pool, kind, key, files, extra = {}) { if ((await stat(path.join(dir, META)).catch(() => null))?.isFile()) return true; const shard = path.dirname(dir); await mkdir(shard, { recursive: true }); - const tmp = path.join(path.dirname(shard), `.tmp-${process.pid}-${randomBytes(4).toString("hex")}`); + // A hidden work dir of its own beside the shards (`<kind dir>/.tmp-<pid>-<seq>-<random>`). + const tmp = tmpPathFor(path.dirname(shard) + path.sep); await mkdir(tmp); try { const meta = { kind, key: String(key), salt: POOL_KINDS[kind].salt, at: new Date().toISOString(), files: {}, ...extra }; diff --git a/umtool/report-to-video/segment-cache.mjs b/umtool/report-to-video/segment-cache.mjs @@ -32,6 +32,7 @@ import { readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promise import path from "node:path"; import { poolFetch, poolFor, poolPut } from "./render-pool.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Bumped when what the key covers changes: every segment is rebuilt once. */ export const SEGMENT_KEY_VERSION = 1; @@ -142,7 +143,7 @@ export async function segmentKey({ argv, record, outDir, ffmpeg }) { const cutRecordOf = (seg) => seg.replace(/\.mp4$/, ".cut.json"); async function replaceText(file, text) { - const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(path.dirname(file), `.${path.basename(file)}`)); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } diff --git a/umtool/report-to-video/side-card.mjs b/umtool/report-to-video/side-card.mjs @@ -17,6 +17,7 @@ import { loadChromium } from "./post-render.mjs"; // The post as a side card shows it (vertical.mjs, pure: Play's route reads it too). import { sideCardEntry } from "./vertical.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { sideCardEntry }; /** The key of a side card: what it draws, at what size, under which redaction. */ @@ -54,7 +55,7 @@ export async function renderSideCard(post, { width, height, render = {}, avatars await writeFile(htmlFile, html, "utf8"); await page.goto(pathToFileURL(htmlFile).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); - const tmp = `${file}.tmp-${process.pid}.png`; + const tmp = tmpPathFor(file, { ext: ".png" }); await page.locator("[data-post-card]").first().screenshot({ path: tmp, omitBackground: true }); await rename(tmp, file); } finally { diff --git a/umtool/report-to-video/trailer.mjs b/umtool/report-to-video/trailer.mjs @@ -78,6 +78,7 @@ import { beatGapsOf, gapFilterParts, offsetIn, recordGaps, sourceAtOffset } from import { OUTRO_FADE, outroAdds, outroFilterParts, renderOutroCard } from "./outro.mjs"; import { outroBrand, reelIntroOf, renderReelIntro } from "./reel-intro.mjs"; import { SNAP_HARD_ROOM, SNAP_MAX_SHIFT, pauseSpans, snapEdge } from "./pauses.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -858,7 +859,7 @@ export async function makeTrailer({ }; let argv = null; // Written beside, then renamed: a half-made file never sits at the name. - const tmp = path.join(path.dirname(outPath), `.${path.basename(outPath, ".mp4")}.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(path.join(path.dirname(outPath), `.${path.basename(outPath, ".mp4")}`), { ext: ".mp4" }); let encodeSeconds = null; // Cancelled (the Trailer page's Cancel signals the job's process group): the // half-made file goes with it. Exits as the signal would when nothing else diff --git a/umtool/report-to-video/variants.mjs b/umtool/report-to-video/variants.mjs @@ -53,6 +53,7 @@ import { ladderJobs, masterFromChunks, rungAudioArgs, rungAudioFile, rungAudioKey, rungChunkArgs, rungChunkFile, rungChunkKey, rungJoinArgs, runPool, } from "./ladder-chunks.mjs"; import { ffmpegIdentity } from "./segment-cache.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -297,7 +298,7 @@ async function openLadder({ outDir, src, work, slug, onLog }) { for (const f of await readdir(cdir).catch(() => [])) { if ((isLadderChunkFile(f) && !keep.has(f)) || /\.partial\.(mp4|m4a)$/.test(f)) await rm(path.join(cdir, f), { force: true }); } - const tmp = path.join(dir, `.${LADDER_RECORD}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(dir, `.${LADDER_RECORD}`)); await writeFile(tmp, JSON.stringify(rec, null, 2) + "\n", "utf8"); await rename(tmp, recFile); }; diff --git a/umtool/song/asr-via-ops.mjs b/umtool/song/asr-via-ops.mjs @@ -36,6 +36,7 @@ import { execFileSync } from "node:child_process"; import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync, writeSync } from "node:fs"; import path from "node:path"; import { SONG_DATA } from "./paths.mjs"; +import { writeFileAtomicSync } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const plans = process.argv.slice(2).filter((a) => a.endsWith(".json")); if (!plans.length || !process.env.WORKER_TOKEN) { @@ -134,8 +135,7 @@ for (const w of words) { for (const id of ready) { const file = path.join(ASR, `${id}.json`); const list = perId.get(id).sort((a, b) => a.start - b.start); - writeFileSync(`${file}.tmp`, JSON.stringify({ windows: windowsOf(spans.get(id)), words: list })); - renameSync(`${file}.tmp`, file); + writeFileAtomicSync(file, JSON.stringify({ windows: windowsOf(spans.get(id)), words: list })); } const counts = ready.map((id) => perId.get(id).length); console.log(`asr: ${ready.length} written (${counts.filter((n) => n === 0).length} with no words), ` + diff --git a/umtool/song/link-sources.mjs b/umtool/song/link-sources.mjs @@ -31,6 +31,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, renameSyn import { execFileSync } from "node:child_process"; import path from "node:path"; import { SONG_DATA } from "./paths.mjs"; +import { writeFileAtomicSync } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const argv = process.argv.slice(2); const ci = argv.indexOf("--channel"); @@ -105,8 +106,7 @@ for (const id of ids) { "-of", "csv=p=0", wav]).toString().trim()); ledger[id] = { channel: CHANNEL, saved: file, bytes: statSync(file).size, seconds: +secs.toFixed(2), linkedAt: new Date().toISOString() }; - writeFileSync(`${LEDGER}.tmp`, JSON.stringify(ledger, null, 1) + "\n"); - renameSync(`${LEDGER}.tmp`, LEDGER); + writeFileAtomicSync(LEDGER, JSON.stringify(ledger, null, 1) + "\n"); console.log(`${id}: ${(secs / 60).toFixed(1)} min`); } console.log(`${ids.length} sources: ${linked} linked, ${wavs} wav48 written, ${already} already done, ${waiting} not saved yet`); diff --git a/umtool/song/spec.mjs b/umtool/song/spec.mjs @@ -29,6 +29,7 @@ import { readFileSync, writeFileSync, existsSync, readdirSync, statSync, renameSync, mkdirSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const ROOT = process.env.VIDEO_ROOT ?? path.join(os.homedir(), "reports", "quartering-uh-song", "videos"); const argv = process.argv.slice(2); @@ -48,7 +49,7 @@ function read(song) { function write(song, spec) { const f = file(song); if (!existsSync(path.dirname(f))) throw new Error(`no such song directory: ${path.dirname(f)}`); - const tmp = `${f}.tmp-${process.pid}`; + const tmp = tmpPathFor(f); writeFileSync(tmp, JSON.stringify(spec, null, 1)); renameSync(tmp, f); } diff --git a/umtool/song/video-dir.mjs b/umtool/song/video-dir.mjs @@ -51,6 +51,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync, readdirSy import { execFileSync } from "node:child_process"; import os from "node:os"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const ROOT = process.env.VIDEO_ROOT ?? path.join(os.homedir(), "reports", "quartering-uh-song", "videos"); const argv = process.argv.slice(2); @@ -79,7 +80,7 @@ function readBuild(song) { function writeBuild(song, value) { const file = buildFile(song); mkdirSync(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); writeFileSync(tmp, JSON.stringify(value, null, 1)); renameSync(tmp, file); }