// 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 (`..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 `.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 `..tmp` and `.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$/); });