lock.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import { spawn } from "node:child_process";
  2. import { mkdir, mkdtemp, readFile, readdir, rename, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { describe, expect, it } from "vitest";
  6. import { DataRootLock } from "../src/runtime/lock.js";
  7. // 超出常见平台 pid 上限的值:process.kill(pid, 0) 必然 ESRCH,模拟已死的持锁进程。
  8. const DEAD_PID = 2 ** 30;
  9. describe("DataRootLock", () => {
  10. it("recovers a stale lock left behind by a dead process", async () => {
  11. const root = await mkdtemp(join(tmpdir(), "zcode-r2-lock-stale-"));
  12. const lockFile = join(root, "run", "server.lock");
  13. await mkdir(join(root, "run"), { recursive: true });
  14. await writeFile(lockFile, `${JSON.stringify({ pid: DEAD_PID, acquiredAt: 0 })}\n`, "utf8");
  15. const lock = new DataRootLock(lockFile);
  16. await lock.acquire();
  17. expect(JSON.parse(await readFile(lockFile, "utf8"))).toMatchObject({ pid: process.pid });
  18. await lock.release();
  19. });
  20. it("recovers a corrupted lock file", async () => {
  21. const root = await mkdtemp(join(tmpdir(), "zcode-r2-lock-corrupt-"));
  22. const lockFile = join(root, "run", "server.lock");
  23. await mkdir(join(root, "run"), { recursive: true });
  24. await writeFile(lockFile, "not-json", "utf8");
  25. const lock = new DataRootLock(lockFile);
  26. await lock.acquire();
  27. await lock.release();
  28. });
  29. it("refuses to steal the lock from a live process", async () => {
  30. const root = await mkdtemp(join(tmpdir(), "zcode-r2-lock-live-"));
  31. const lockFile = join(root, "run", "server.lock");
  32. await mkdir(join(root, "run"), { recursive: true });
  33. await writeFile(lockFile, `${JSON.stringify({ pid: process.pid, acquiredAt: Date.now() })}\n`, "utf8");
  34. const lock = new DataRootLock(lockFile);
  35. await expect(lock.acquire()).rejects.toThrow(/already running/);
  36. });
  37. it("reports missing, stale, active and malformed lock owners without mutating the file", async () => {
  38. const root = await mkdtemp(join(tmpdir(), "zcode-r2-lock-inspect-"));
  39. const lockFile = join(root, "run", "server.lock");
  40. const lock = new DataRootLock(lockFile);
  41. await expect(lock.inspect()).resolves.toMatchObject({ state: "missing" });
  42. await mkdir(join(root, "run"), { recursive: true });
  43. await writeFile(lockFile, `${JSON.stringify({ pid: DEAD_PID })}\n`, "utf8");
  44. await expect(lock.inspect()).resolves.toMatchObject({ state: "stale", pid: DEAD_PID });
  45. await writeFile(lockFile, `${JSON.stringify({ pid: process.pid })}\n`, "utf8");
  46. await expect(lock.inspect()).resolves.toMatchObject({ state: "active", pid: process.pid });
  47. await writeFile(lockFile, "not-json", "utf8");
  48. await expect(lock.inspect()).resolves.toMatchObject({ state: "invalid" });
  49. await expect(readFile(lockFile, "utf8")).resolves.toBe("not-json");
  50. });
  51. it("keeps locks under different data roots isolated (R2-CLI-13)", async () => {
  52. const rootA = await mkdtemp(join(tmpdir(), "zcode-r2-lock-a-"));
  53. const rootB = await mkdtemp(join(tmpdir(), "zcode-r2-lock-b-"));
  54. const lockA = new DataRootLock(join(rootA, "run", "server.lock"));
  55. const lockB = new DataRootLock(join(rootB, "run", "server.lock"));
  56. await lockA.acquire();
  57. await lockB.acquire();
  58. await lockA.release();
  59. await lockB.release();
  60. // 释放后可重新获取。
  61. await lockA.acquire();
  62. await lockA.release();
  63. });
  64. it.skipIf(process.platform === "win32")("does not delete a replacement lock owned by another token during release", async () => {
  65. const root = await mkdtemp(join(tmpdir(), "zcode-r2-lock-owner-"));
  66. const lockFile = join(root, "run", "server.lock");
  67. const replacement = join(root, "run", "replacement.lock");
  68. const lock = new DataRootLock(lockFile);
  69. await lock.acquire();
  70. await writeFile(replacement, `${JSON.stringify({
  71. pid: process.pid,
  72. acquiredAt: Date.now(),
  73. ownerToken: "replacement-owner",
  74. })}\n`, "utf8");
  75. await rename(replacement, lockFile);
  76. await lock.release();
  77. expect(JSON.parse(await readFile(lockFile, "utf8"))).toMatchObject({
  78. ownerToken: "replacement-owner",
  79. });
  80. });
  81. it("allows only one real process to claim the same stale lock", async () => {
  82. const root = await mkdtemp(join(tmpdir(), "zcode-lock-race-"));
  83. const lockFile = join(root, "server.lock");
  84. const barrierFile = join(root, "go");
  85. const resultsFile = join(root, "results");
  86. const readyDir = join(root, "ready");
  87. await mkdir(readyDir);
  88. await writeFile(lockFile, `${JSON.stringify({ pid: DEAD_PID, acquiredAt: 0 })}\n`, "utf8");
  89. // 根目录 Vitest 与 package 脚本的 cwd 不同,不能用 cwd 推导源码路径,否则子进程会导入不存在的 root/src/runtime/lock.ts。
  90. const moduleUrl = new URL("../src/runtime/lock.ts", import.meta.url).href;
  91. const childProgram = `
  92. import { access, appendFile, writeFile } from "node:fs/promises";
  93. import { setTimeout as delay } from "node:timers/promises";
  94. const { DataRootLock } = await import(process.env.ZCODE_TEST_LOCK_MODULE);
  95. await writeFile(process.env.ZCODE_TEST_LOCK_READY, "ready\\n");
  96. while (true) { try { await access(process.env.ZCODE_TEST_LOCK_BARRIER); break; } catch { await delay(5); } }
  97. const lock = new DataRootLock(process.env.ZCODE_TEST_LOCK_FILE);
  98. try {
  99. await lock.acquire();
  100. await appendFile(process.env.ZCODE_TEST_LOCK_RESULTS, "success " + process.env.ZCODE_TEST_LOCK_CHILD + "\\n");
  101. await delay(1_000);
  102. await lock.release();
  103. } catch {
  104. await appendFile(process.env.ZCODE_TEST_LOCK_RESULTS, "locked " + process.env.ZCODE_TEST_LOCK_CHILD + "\\n");
  105. }
  106. `;
  107. const children = Array.from({ length: 8 }, (_, index) => new Promise<void>((resolve, reject) => {
  108. const child = spawn(process.execPath, ["--import", "tsx", "--input-type=module", "--eval", childProgram], {
  109. env: {
  110. ...process.env,
  111. ZCODE_TEST_LOCK_MODULE: moduleUrl,
  112. ZCODE_TEST_LOCK_BARRIER: barrierFile,
  113. ZCODE_TEST_LOCK_FILE: lockFile,
  114. ZCODE_TEST_LOCK_READY: join(readyDir, String(index)),
  115. ZCODE_TEST_LOCK_RESULTS: resultsFile,
  116. ZCODE_TEST_LOCK_CHILD: String(index),
  117. },
  118. stdio: ["ignore", "ignore", "pipe"],
  119. });
  120. let childError = "";
  121. child.stderr.on("data", (chunk) => { childError += String(chunk); });
  122. child.once("error", reject);
  123. child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(childError || `lock child exited ${code}`)));
  124. }));
  125. // 先等待所有子进程进入 barrier;只按固定时间放行会让慢启动的子进程在首个 owner
  126. // 释放后再次成功获取锁,导致“一个 success”断言随机出现多个 success。
  127. const readyDeadline = Date.now() + 20_000;
  128. let allChildrenReady = false;
  129. while (Date.now() < readyDeadline) {
  130. if ((await readdir(readyDir)).length === children.length) {
  131. allChildrenReady = true;
  132. break;
  133. }
  134. await new Promise<void>((resolve) => setTimeout(resolve, 10));
  135. }
  136. await writeFile(barrierFile, "go", "utf8");
  137. await Promise.all(children);
  138. const results = (await readFile(resultsFile, "utf8")).trim().split("\n");
  139. expect(allChildrenReady).toBe(true);
  140. expect(results.filter((result) => result.startsWith("success "))).toHaveLength(1);
  141. expect(results.filter((result) => result.startsWith("locked "))).toHaveLength(7);
  142. }, 30_000);
  143. });