Files
Kelx/utils/atomic-file.test.js
2026-11-30 16:32:37 +00:00

126 lines
5.3 KiB
JavaScript

"use strict";
// Tests for the shared atomic file replacement primitive. Contract under test:
// - readers never observe a torn/partial file (rename is atomic);
// - a crash between create and rename leaves the destination untouched;
// - permissions are applied exactly, regardless of umask;
// - temp files never survive a failed write;
// - concurrent writers converge to one complete document (no interleaving).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { atomicWriteFileSync, createAtomicWriteTempPath } = require("./atomic-file");
function tmpDir(t) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "atomic-file-"));
t.after(() => {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch (_) { }
});
return dir;
}
test("creates a new file atomically with exact content", (t) => {
const dir = tmpDir(t);
const file = path.join(dir, "config.json");
atomicWriteFileSync(file, JSON.stringify({ enabled: true, users: ["a"] }), { mode: 0o600 });
assert.strictEqual(fs.readFileSync(file, "utf8"), JSON.stringify({ enabled: true, users: ["a"] }));
// No temp litter left behind.
assert.deepStrictEqual(fs.readdirSync(dir), ["config.json"]);
});
test("replaces an existing file atomically (old content never partially visible)", (t) => {
const dir = tmpDir(t);
const file = path.join(dir, "config.json");
atomicWriteFileSync(file, '{"v":1}', { mode: 0o600 });
atomicWriteFileSync(file, '{"v":2}', { mode: 0o600 });
assert.strictEqual(fs.readFileSync(file, "utf8"), '{"v":2}');
assert.deepStrictEqual(fs.readdirSync(dir), ["config.json"]);
});
test("destination is untouched when the write fails mid-way", (t) => {
const dir = tmpDir(t);
const file = path.join(dir, "config.json");
atomicWriteFileSync(file, "original", { mode: 0o600 });
// Force a failure after temp creation by making the write itself fail:
// pass a payload writeFileSync rejects, so the throw lands after the temp
// file exists but before any rename.
const evil = /** @type {any} */ ({ toString() { return undefined; } });
assert.throws(() => atomicWriteFileSync(file, evil), TypeError);
assert.strictEqual(fs.readFileSync(file, "utf8"), "original");
// No temp file left in the directory.
const leftovers = fs.readdirSync(dir).filter((n) => n.endsWith(".tmp"));
assert.deepStrictEqual(leftovers, []);
});
test("temp file is cleaned up when the rename step fails", (t) => {
const dir = tmpDir(t);
// A directory where the destination file should be: rename(2) onto a
// directory fails (EISDIR/ENOTEMPTY) after the temp file was fully written.
const file = path.join(dir, "occupied.json");
fs.mkdirSync(file);
assert.throws(() => atomicWriteFileSync(file, "x", { mode: 0o600 }));
const leftovers = fs.readdirSync(dir).filter((n) => n.endsWith(".tmp"));
assert.deepStrictEqual(leftovers, []);
assert.ok(fs.statSync(file).isDirectory());
});
test("a reserved atomic temporary cannot overwrite or remove an existing path", (t) => {
const dir = tmpDir(t);
const file = path.join(dir, "config.json");
const temporaryPath = createAtomicWriteTempPath(file);
fs.writeFileSync(temporaryPath, "existing temporary");
assert.throws(() => atomicWriteFileSync(file, "replacement", { temporaryPath }), { code: "EEXIST" });
assert.strictEqual(fs.readFileSync(temporaryPath, "utf8"), "existing temporary");
assert.strictEqual(fs.existsSync(file), false);
fs.unlinkSync(temporaryPath);
atomicWriteFileSync(file, "replacement", { temporaryPath, durable: true });
assert.strictEqual(fs.readFileSync(file, "utf8"), "replacement");
assert.strictEqual(fs.existsSync(temporaryPath), false);
});
test("mode is enforced exactly regardless of umask", (t) => {
const dir = tmpDir(t);
const file = path.join(dir, "secret.json");
const oldUmask = process.umask(0o077);
try {
// With umask 077 a plain openSync(.., mode 0o600) still lands on 0600, so
// use a mode that umask 077 would normally widen away: nothing in 0o600
// is group/world, but assert the fchmod enforcement with 0o640 which a
// 0o077 umask would strip to 0o600.
atomicWriteFileSync(file, "x", { mode: 0o640 });
} finally {
process.umask(oldUmask);
}
assert.strictEqual(fs.statSync(file).mode & 0o777, 0o640);
});
test("buffer content round-trips", (t) => {
const dir = tmpDir(t);
const file = path.join(dir, "blob.bin");
const payload = Buffer.from([0, 1, 2, 255, 128, 7]);
atomicWriteFileSync(file, payload);
assert.deepStrictEqual(fs.readFileSync(file), payload);
});
test("two sequential writers converge; directory never holds both generations", (t) => {
const dir = tmpDir(t);
const file = path.join(dir, "config.json");
for (let i = 0; i < 25; i++) {
atomicWriteFileSync(file, JSON.stringify({ i }), { mode: 0o600 });
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
assert.strictEqual(parsed.i, i);
assert.ok(fs.readdirSync(dir).every((n) => !n.endsWith(".tmp")), `no tmp litter at i=${i}`);
}
});
test("throws when the destination directory does not exist", (t) => {
const dir = tmpDir(t);
const missing = path.join(dir, "nope", "config.json");
assert.throws(() => atomicWriteFileSync(missing, "x"));
});