// 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: `.tmp---`. // // Unique per WRITE, not per process. `..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 (`.`) keeps its temp hidden. // // A sweep test (umtool/lib/atomicFile-sweep.test.mjs) fails on a new `.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; } }