atomicFileUtils.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. import {
  2. existsSync,
  3. mkdirSync,
  4. mkdtempSync,
  5. readFileSync,
  6. readdirSync,
  7. rmSync,
  8. utimesSync,
  9. writeFileSync,
  10. } from "node:fs";
  11. import { mkdir, rename } from "node:fs/promises";
  12. import { tmpdir } from "node:os";
  13. import { join } from "node:path";
  14. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  15. const fsMockState = vi.hoisted(() => ({
  16. renameFailures: [] as NodeJS.ErrnoException[],
  17. lockRemoveFailure: null as NodeJS.ErrnoException | null,
  18. renameDelayMs: 0,
  19. activeRenames: 0,
  20. maxActiveRenames: 0,
  21. lockMkdirGate: null as Promise<void> | null,
  22. lockMkdirEntered: null as (() => void) | null,
  23. }));
  24. vi.mock("node:fs/promises", async () => {
  25. const actual =
  26. await vi.importActual<typeof import("node:fs/promises")>(
  27. "node:fs/promises",
  28. );
  29. return {
  30. ...actual,
  31. mkdir: vi.fn(
  32. async (...args: Parameters<typeof actual.mkdir>) => {
  33. const gate = fsMockState.lockMkdirGate;
  34. if (gate && String(args[0]).endsWith(".lock")) {
  35. fsMockState.lockMkdirEntered?.();
  36. fsMockState.lockMkdirEntered = null;
  37. await gate;
  38. }
  39. return actual.mkdir(...args);
  40. },
  41. ),
  42. rename: vi.fn(
  43. async (
  44. oldPath: Parameters<typeof actual.rename>[0],
  45. newPath: Parameters<typeof actual.rename>[1],
  46. ) => {
  47. const failure = fsMockState.renameFailures.shift();
  48. if (failure) {
  49. throw failure;
  50. }
  51. fsMockState.activeRenames += 1;
  52. fsMockState.maxActiveRenames = Math.max(
  53. fsMockState.maxActiveRenames,
  54. fsMockState.activeRenames,
  55. );
  56. try {
  57. if (fsMockState.renameDelayMs > 0) {
  58. await new Promise((resolve) =>
  59. setTimeout(resolve, fsMockState.renameDelayMs),
  60. );
  61. }
  62. await actual.rename(oldPath, newPath);
  63. } finally {
  64. fsMockState.activeRenames -= 1;
  65. }
  66. },
  67. ),
  68. rm: vi.fn(
  69. async (
  70. path: Parameters<typeof actual.rm>[0],
  71. options?: Parameters<typeof actual.rm>[1],
  72. ) => {
  73. if (String(path).includes(".lock") && fsMockState.lockRemoveFailure) {
  74. throw fsMockState.lockRemoveFailure;
  75. }
  76. await actual.rm(path, options);
  77. },
  78. ),
  79. };
  80. });
  81. import { atomicWriteText } from "../src/fs/atomicFileUtils.js";
  82. import {
  83. createFsFaultInjector,
  84. resetProcessFsFaultInjectorForTests,
  85. setFsFaultInjectorForTests,
  86. } from "../src/fs/fsFaultInjection.js";
  87. function createFsError(code: string): NodeJS.ErrnoException {
  88. const error = new Error(code) as NodeJS.ErrnoException;
  89. error.code = code;
  90. return error;
  91. }
  92. function pauseNextLockMkdir(): {
  93. entered: Promise<void>;
  94. release: () => void;
  95. } {
  96. let release!: () => void;
  97. let markEntered!: () => void;
  98. fsMockState.lockMkdirGate = new Promise<void>((resolve) => {
  99. release = resolve;
  100. });
  101. const entered = new Promise<void>((resolve) => {
  102. markEntered = resolve;
  103. });
  104. fsMockState.lockMkdirEntered = markEntered;
  105. return {
  106. entered,
  107. release: () => {
  108. fsMockState.lockMkdirGate = null;
  109. release();
  110. },
  111. };
  112. }
  113. function createDirectoryLock(
  114. filePath: string,
  115. metadata: { createdAt: number; pid: number; token: string },
  116. ) {
  117. const lockDir = `${filePath}.lock`;
  118. mkdirSync(lockDir);
  119. const ownerFile = join(lockDir, `owner-${metadata.token}.json`);
  120. writeFileSync(ownerFile, `${JSON.stringify(metadata)}\n`, "utf-8");
  121. return ownerFile;
  122. }
  123. describe("atomicWriteText", () => {
  124. let tempDir: string;
  125. beforeEach(() => {
  126. tempDir = mkdtempSync(join(tmpdir(), "zcode-atomic-write-"));
  127. fsMockState.renameFailures.length = 0;
  128. fsMockState.lockRemoveFailure = null;
  129. fsMockState.renameDelayMs = 0;
  130. fsMockState.activeRenames = 0;
  131. fsMockState.maxActiveRenames = 0;
  132. fsMockState.lockMkdirGate = null;
  133. fsMockState.lockMkdirEntered = null;
  134. vi.mocked(mkdir).mockClear();
  135. vi.mocked(rename).mockClear();
  136. });
  137. afterEach(() => {
  138. resetProcessFsFaultInjectorForTests();
  139. rmSync(tempDir, { recursive: true, force: true });
  140. });
  141. it("retries transient Windows rename locks and keeps the atomic temp file clean", async () => {
  142. const filePath = join(tempDir, "session.json");
  143. fsMockState.renameFailures.push(
  144. createFsError("EPERM"),
  145. createFsError("EBUSY"),
  146. );
  147. await atomicWriteText(filePath, "saved\n", {
  148. renameRetryDelaysMs: [1, 1],
  149. });
  150. expect(readFileSync(filePath, "utf-8")).toBe("saved\n");
  151. expect(vi.mocked(rename)).toHaveBeenCalledTimes(3);
  152. expect(
  153. readdirSync(tempDir).filter((name) => name.endsWith(".tmp")),
  154. ).toEqual([]);
  155. });
  156. it("does not retry non-transient rename failures and removes the temp file", async () => {
  157. const filePath = join(tempDir, "session.json");
  158. fsMockState.renameFailures.push(createFsError("ENOENT"));
  159. await expect(
  160. atomicWriteText(filePath, "saved\n", {
  161. renameRetryDelaysMs: [1],
  162. }),
  163. ).rejects.toMatchObject({ code: "ENOENT" });
  164. expect(vi.mocked(rename)).toHaveBeenCalledTimes(1);
  165. expect(
  166. readdirSync(tempDir).filter((name) => name.endsWith(".tmp")),
  167. ).toEqual([]);
  168. });
  169. it("fails immediately on injected fs faults before atomic rename", async () => {
  170. const filePath = join(tempDir, "config.json");
  171. const injector = createFsFaultInjector([
  172. {
  173. code: "EACCES",
  174. id: "D03-provider-settings-eacces",
  175. operations: ["rename"],
  176. pathEndsWith: "/config.json",
  177. },
  178. ]);
  179. setFsFaultInjectorForTests(injector);
  180. await expect(
  181. atomicWriteText(filePath, "blocked\n", {
  182. renameRetryDelaysMs: [1, 1],
  183. }),
  184. ).rejects.toMatchObject({
  185. code: "EACCES",
  186. path: filePath,
  187. syscall: "rename",
  188. zcodeFsFaultId: "D03-provider-settings-eacces",
  189. });
  190. expect(vi.mocked(rename)).toHaveBeenCalledTimes(0);
  191. expect(existsSync(filePath)).toBe(false);
  192. expect(
  193. readdirSync(tempDir).filter((name) => name.endsWith(".tmp")),
  194. ).toEqual([]);
  195. expect(injector.getHits()).toMatchObject([
  196. {
  197. code: "EACCES",
  198. id: "D03-provider-settings-eacces",
  199. matchIndex: 1,
  200. operation: "rename",
  201. path: filePath,
  202. },
  203. ]);
  204. });
  205. it("serializes concurrent writes to the same target with a cooperative lock", async () => {
  206. const filePath = join(tempDir, "session.json");
  207. fsMockState.renameDelayMs = 20;
  208. await Promise.all([
  209. atomicWriteText(filePath, "first\n", {
  210. lockRetryDelaysMs: [1, 5, 20, 20],
  211. }),
  212. atomicWriteText(filePath, "second\n", {
  213. lockRetryDelaysMs: [1, 5, 20, 20],
  214. }),
  215. ]);
  216. expect(["first\n", "second\n"]).toContain(readFileSync(filePath, "utf-8"));
  217. expect(fsMockState.maxActiveRenames).toBe(1);
  218. expect(
  219. readdirSync(tempDir).filter((name) => name.endsWith(".tmp")),
  220. ).toEqual([]);
  221. expect(
  222. readdirSync(tempDir).filter((name) => name.endsWith(".lock")),
  223. ).toEqual([]);
  224. });
  225. it("reclaims a fresh lock when its owner process has already exited", async () => {
  226. const filePath = join(tempDir, "config.json");
  227. writeFileSync(
  228. `${filePath}.lock`,
  229. `${JSON.stringify({ pid: 2_147_483_647, createdAt: Date.now() })}\n`,
  230. "utf-8",
  231. );
  232. await atomicWriteText(filePath, "saved\n", {
  233. lockRetryDelaysMs: [1],
  234. lockOwnerlessGraceMs: 60_000,
  235. });
  236. expect(readFileSync(filePath, "utf-8")).toBe("saved\n");
  237. expect(existsSync(`${filePath}.lock`)).toBe(false);
  238. });
  239. it("reclaims a fresh empty lock directory within the current wait budget", async () => {
  240. const filePath = join(tempDir, "config.json");
  241. const lockDir = `${filePath}.lock`;
  242. mkdirSync(lockDir);
  243. await atomicWriteText(filePath, "saved\n", {
  244. lockRetryDelaysMs: [1],
  245. lockOwnerlessGraceMs: 30_000,
  246. lockMaxWaitMs: 100,
  247. });
  248. expect(readFileSync(filePath, "utf-8")).toBe("saved\n");
  249. expect(existsSync(lockDir)).toBe(false);
  250. });
  251. it("bounds a future empty lock directory mtime by the current wait budget", async () => {
  252. const filePath = join(tempDir, "config-future-lock-dir.json");
  253. const lockDir = `${filePath}.lock`;
  254. mkdirSync(lockDir);
  255. const futureTime = new Date(Date.now() + 24 * 60 * 60_000);
  256. utimesSync(lockDir, futureTime, futureTime);
  257. await atomicWriteText(filePath, "saved\n", {
  258. lockRetryDelaysMs: [1],
  259. lockOwnerlessGraceMs: 30_000,
  260. lockMaxWaitMs: 100,
  261. });
  262. expect(readFileSync(filePath, "utf-8")).toBe("saved\n");
  263. expect(existsSync(lockDir)).toBe(false);
  264. });
  265. it("does not apply an old waiter's age to a replacement empty lock directory", async () => {
  266. const filePath = join(tempDir, "config-replacement-empty.json");
  267. const lockDir = `${filePath}.lock`;
  268. createDirectoryLock(filePath, {
  269. pid: process.pid,
  270. createdAt: Date.now(),
  271. token: "old-owner",
  272. });
  273. let settled = false;
  274. const writePromise = atomicWriteText(filePath, "saved\n", {
  275. lockRetryDelaysMs: [1],
  276. lockOwnerlessGraceMs: 1_000,
  277. lockMaxWaitMs: 240,
  278. });
  279. void writePromise.then(
  280. () => {
  281. settled = true;
  282. },
  283. () => {
  284. settled = true;
  285. },
  286. );
  287. await new Promise((resolve) => setTimeout(resolve, 145));
  288. expect(settled).toBe(false);
  289. const mkdirGate = pauseNextLockMkdir();
  290. await mkdirGate.entered;
  291. rmSync(lockDir, { recursive: true, force: true });
  292. mkdirSync(lockDir);
  293. mkdirGate.release();
  294. await expect(writePromise).rejects.toMatchObject({
  295. code: "ZCODE_FILE_LOCK_TIMEOUT",
  296. });
  297. expect(existsSync(lockDir)).toBe(true);
  298. expect(existsSync(filePath)).toBe(false);
  299. });
  300. it("does not apply an old waiter's age to a replacement damaged ownerless lock", async () => {
  301. const filePath = join(tempDir, "config-replacement-ownerless.json");
  302. const lockFile = `${filePath}.lock`;
  303. createDirectoryLock(filePath, {
  304. pid: process.pid,
  305. createdAt: Date.now(),
  306. token: "old-owner",
  307. });
  308. let settled = false;
  309. const writePromise = atomicWriteText(filePath, "saved\n", {
  310. lockRetryDelaysMs: [1],
  311. lockOwnerlessGraceMs: 1_000,
  312. lockMaxWaitMs: 240,
  313. });
  314. void writePromise.then(
  315. () => {
  316. settled = true;
  317. },
  318. () => {
  319. settled = true;
  320. },
  321. );
  322. await new Promise((resolve) => setTimeout(resolve, 145));
  323. expect(settled).toBe(false);
  324. const mkdirGate = pauseNextLockMkdir();
  325. await mkdirGate.entered;
  326. rmSync(lockFile, { recursive: true, force: true });
  327. writeFileSync(lockFile, '{"pid":0,"createdAt":1e999}\n', "utf-8");
  328. const futureTime = new Date(Date.now() + 24 * 60 * 60_000);
  329. utimesSync(lockFile, futureTime, futureTime);
  330. mkdirGate.release();
  331. await expect(writePromise).rejects.toMatchObject({
  332. code: "ZCODE_FILE_LOCK_TIMEOUT",
  333. });
  334. expect(existsSync(lockFile)).toBe(true);
  335. expect(existsSync(filePath)).toBe(false);
  336. });
  337. it.each(["0", "-1", "1.5", "1e999"])(
  338. "reclaims a stale lock with invalid pid %s as ownerless",
  339. async (rawPid) => {
  340. const filePath = join(
  341. tempDir,
  342. `config-${rawPid.replace(/\W/g, "_")}.json`,
  343. );
  344. const createdAt = Date.now();
  345. writeFileSync(
  346. `${filePath}.lock`,
  347. `{"pid":${rawPid},"createdAt":${createdAt}}\n`,
  348. "utf-8",
  349. );
  350. await atomicWriteText(filePath, "saved\n", {
  351. lockRetryDelaysMs: [1],
  352. lockOwnerlessGraceMs: 30_000,
  353. lockMaxWaitMs: 100,
  354. });
  355. expect(readFileSync(filePath, "utf-8")).toBe("saved\n");
  356. expect(existsSync(`${filePath}.lock`)).toBe(false);
  357. },
  358. );
  359. it.each([
  360. ["non-finite", "1e999"],
  361. ["negative", "-1"],
  362. ["far-future", String(Date.now() + 24 * 60 * 60_000)],
  363. ])(
  364. "reclaims an ownerless stale lock with %s createdAt via file mtime",
  365. async (label, rawCreatedAt) => {
  366. const filePath = join(tempDir, `config-created-at-${label}.json`);
  367. const lockFile = `${filePath}.lock`;
  368. writeFileSync(
  369. lockFile,
  370. `{"pid":0,"createdAt":${rawCreatedAt}}\n`,
  371. "utf-8",
  372. );
  373. const oldTime = new Date(Date.now() - 60_000);
  374. utimesSync(lockFile, oldTime, oldTime);
  375. await atomicWriteText(filePath, "saved\n", {
  376. lockRetryDelaysMs: [1],
  377. lockOwnerlessGraceMs: 10,
  378. lockMaxWaitMs: 100,
  379. });
  380. expect(readFileSync(filePath, "utf-8")).toBe("saved\n");
  381. expect(existsSync(lockFile)).toBe(false);
  382. },
  383. );
  384. it("reclaims a lock with invalid metadata and mtime from its first observation", async () => {
  385. const filePath = join(tempDir, "config-invalid-timestamps.json");
  386. const lockFile = `${filePath}.lock`;
  387. writeFileSync(lockFile, '{"pid":0,"createdAt":1e999}\n', "utf-8");
  388. const futureTime = new Date(Date.now() + 24 * 60 * 60_000);
  389. utimesSync(lockFile, futureTime, futureTime);
  390. await atomicWriteText(filePath, "saved\n", {
  391. lockRetryDelaysMs: [1],
  392. lockOwnerlessGraceMs: 20,
  393. lockMaxWaitMs: 100,
  394. });
  395. expect(readFileSync(filePath, "utf-8")).toBe("saved\n");
  396. expect(existsSync(lockFile)).toBe(false);
  397. });
  398. it("does not reclaim a stale-looking lock while its owner is still alive", async () => {
  399. const filePath = join(tempDir, "config.json");
  400. const ownerFile = createDirectoryLock(filePath, {
  401. pid: process.pid,
  402. createdAt: Date.now() - 60_000,
  403. token: "live-owner",
  404. });
  405. await expect(
  406. atomicWriteText(filePath, "saved\n", {
  407. lockRetryDelaysMs: [1],
  408. lockOwnerlessGraceMs: 10,
  409. lockMaxWaitMs: 20,
  410. }),
  411. ).rejects.toMatchObject({ code: "ZCODE_FILE_LOCK_TIMEOUT" });
  412. expect(readFileSync(ownerFile, "utf-8")).toContain('"token":"live-owner"');
  413. expect(existsSync(filePath)).toBe(false);
  414. });
  415. it("does not delete a fresh owner that replaces the lock while a waiter is near timeout", async () => {
  416. const filePath = join(tempDir, "config.json");
  417. createDirectoryLock(filePath, {
  418. pid: process.pid,
  419. createdAt: Date.now(),
  420. token: "old-owner",
  421. });
  422. const writePromise = atomicWriteText(filePath, "saved\n", {
  423. lockRetryDelaysMs: [1],
  424. lockOwnerlessGraceMs: 40,
  425. lockMaxWaitMs: 65,
  426. });
  427. await new Promise((resolve) => setTimeout(resolve, 20));
  428. const mkdirGate = pauseNextLockMkdir();
  429. await mkdirGate.entered;
  430. rmSync(`${filePath}.lock`, { recursive: true, force: true });
  431. const freshOwnerFile = createDirectoryLock(filePath, {
  432. pid: process.pid,
  433. createdAt: Date.now(),
  434. token: "fresh-owner",
  435. });
  436. mkdirGate.release();
  437. await expect(writePromise).rejects.toMatchObject({
  438. code: "ZCODE_FILE_LOCK_TIMEOUT",
  439. });
  440. expect(readFileSync(freshOwnerFile, "utf-8")).toContain(
  441. '"token":"fresh-owner"',
  442. );
  443. expect(existsSync(filePath)).toBe(false);
  444. });
  445. it("stops waiting with an explicit lock timeout", async () => {
  446. const filePath = join(tempDir, "config.json");
  447. writeFileSync(
  448. `${filePath}.lock`,
  449. `${JSON.stringify({ pid: process.pid, createdAt: Date.now() })}\n`,
  450. "utf-8",
  451. );
  452. await expect(
  453. atomicWriteText(filePath, "saved\n", {
  454. lockRetryDelaysMs: [1],
  455. lockOwnerlessGraceMs: 60_000,
  456. lockMaxWaitMs: 10,
  457. }),
  458. ).rejects.toMatchObject({
  459. code: "ZCODE_FILE_LOCK_TIMEOUT",
  460. path: filePath,
  461. syscall: "mkdir",
  462. });
  463. });
  464. it("preserves permission errors when an abandoned lock cannot be removed", async () => {
  465. const filePath = join(tempDir, "config.json");
  466. const oldCreatedAt = Date.now() - 60_000;
  467. writeFileSync(
  468. `${filePath}.lock`,
  469. `${JSON.stringify({ pid: 2_147_483_647, createdAt: oldCreatedAt })}\n`,
  470. "utf-8",
  471. );
  472. fsMockState.lockRemoveFailure = createFsError("EACCES");
  473. await expect(
  474. atomicWriteText(filePath, "saved\n", {
  475. lockRetryDelaysMs: [1],
  476. lockOwnerlessGraceMs: 10,
  477. lockMaxWaitMs: 10,
  478. }),
  479. ).rejects.toMatchObject({ code: "EACCES" });
  480. });
  481. it("removes stale temp files for the same target without deleting fresh temp files", async () => {
  482. const filePath = join(tempDir, "config.json");
  483. const staleTemp = join(tempDir, "config.json.123.1000.stale.tmp");
  484. const freshTemp = join(tempDir, "config.json.123.1000.fresh.tmp");
  485. writeFileSync(staleTemp, "stale\n", "utf-8");
  486. writeFileSync(freshTemp, "fresh\n", "utf-8");
  487. const oldTime = new Date(Date.now() - 120_000);
  488. utimesSync(staleTemp, oldTime, oldTime);
  489. await atomicWriteText(filePath, "saved\n", {
  490. lockOwnerlessGraceMs: 60_000,
  491. tempFileStaleMs: 60_000,
  492. });
  493. const files = readdirSync(tempDir);
  494. expect(files).not.toContain("config.json.123.1000.stale.tmp");
  495. expect(files).toContain("config.json.123.1000.fresh.tmp");
  496. });
  497. });