workspace-hook-script-entry-deadline.test.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import { mkdtempSync } from "node:fs";
  2. import type { FileHandle } from "node:fs/promises";
  3. import { rm } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { Readable, addAbortSignal } from "node:stream";
  7. import { afterEach, describe, expect, it, vi } from "vitest";
  8. import {
  9. readWorkspaceHookScriptStates,
  10. workspaceHooksConfigSchema,
  11. type WorkspaceHookSourceInput,
  12. } from "@zcode/shared/workspace-hook-discovery";
  13. /**
  14. * CR-01(!3691):discovery 的读取预算曾只是一个取消信号,stat/open/handle.stat 不响应它,
  15. * 脚本位于无响应的文件系统时,会话初始化与 Settings 加载会无限等待。
  16. * 这里注入挂起的文件操作,断言预算到期后返回 unverifiable,且迟到打开的句柄仍被关闭。
  17. */
  18. const hang = vi.hoisted(() => ({
  19. target: "" as "" | "stat" | "open" | "handleStat" | "stream",
  20. late: undefined as undefined | (() => void),
  21. lateHandleClosed: false,
  22. inFlightStats: 0,
  23. maxInFlightStats: 0,
  24. }));
  25. vi.mock("node:fs/promises", async (importOriginal) => {
  26. const actual = await importOriginal<typeof import("node:fs/promises")>();
  27. const never = () => new Promise<never>(() => undefined);
  28. return {
  29. ...actual,
  30. stat: (async (...args: Parameters<typeof actual.stat>) => {
  31. if (hang.target === "stat") return never();
  32. hang.inFlightStats += 1;
  33. hang.maxInFlightStats = Math.max(hang.maxInFlightStats, hang.inFlightStats);
  34. try {
  35. // 让出若干轮事件循环,使并发读取有机会重叠。
  36. await new Promise((resolve) => setImmediate(resolve));
  37. return await actual.stat(...args);
  38. } finally {
  39. hang.inFlightStats -= 1;
  40. }
  41. }) as typeof actual.stat,
  42. open: (async (...args: Parameters<typeof actual.open>) => {
  43. if (hang.target === "open") {
  44. // 预算到期后才返回句柄,模拟迟到的 open。
  45. await new Promise<void>((resolve) => {
  46. hang.late = resolve;
  47. });
  48. }
  49. const handle = await actual.open(...args);
  50. if (hang.target === "open") {
  51. return Object.assign(Object.create(handle) as FileHandle, {
  52. close: async () => {
  53. hang.lateHandleClosed = true;
  54. await handle.close();
  55. },
  56. });
  57. }
  58. if (hang.target === "stream") {
  59. // 读取流挂起但响应取消信号(与 fs 流一致);句柄关闭被记录。
  60. return Object.assign(Object.create(handle) as FileHandle, {
  61. createReadStream: (options?: { signal?: AbortSignal }) => {
  62. const stream = new Readable({ read() {} });
  63. return options?.signal ? addAbortSignal(options.signal, stream) : stream;
  64. },
  65. close: async () => {
  66. hang.lateHandleClosed = true;
  67. await handle.close();
  68. },
  69. });
  70. }
  71. if (hang.target !== "handleStat") return handle;
  72. return Object.assign(Object.create(handle) as FileHandle, {
  73. stat: never,
  74. close: () => handle.close(),
  75. });
  76. }) as typeof actual.open,
  77. };
  78. });
  79. const roots: string[] = [];
  80. afterEach(async () => {
  81. hang.target = "";
  82. hang.late = undefined;
  83. hang.lateHandleClosed = false;
  84. hang.inFlightStats = 0;
  85. hang.maxInFlightStats = 0;
  86. vi.useRealTimers();
  87. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  88. });
  89. async function fixture(): Promise<{ workspace: string; sources: WorkspaceHookSourceInput[] }> {
  90. const { writeFile, mkdir } = await vi.importActual<typeof import("node:fs/promises")>(
  91. "node:fs/promises",
  92. );
  93. const workspace = mkdtempSync(join(tmpdir(), "zcode-hook-script-deadline-"));
  94. roots.push(workspace);
  95. await mkdir(join(workspace, ".zcode"), { recursive: true });
  96. await writeFile(join(workspace, "x.sh"), "echo hi\n", "utf8");
  97. const hooks = workspaceHooksConfigSchema.parse({
  98. enabled: true,
  99. events: { SessionStart: [{ hooks: [{ type: "process", command: "sh", args: ["x.sh"] }] }] },
  100. });
  101. return {
  102. workspace,
  103. sources: [
  104. {
  105. canonicalPath: join(workspace, ".zcode", "config.json"),
  106. baseDir: workspace,
  107. discoveryOrder: 0,
  108. configFileKind: ".zcode/config.json",
  109. explicitProjectConfig: false,
  110. editable: true,
  111. hooks,
  112. },
  113. ],
  114. };
  115. }
  116. describe("readWorkspaceHookScriptStates 截止时间(CR-01)", () => {
  117. it.each(["stat", "open", "handleStat"] as const)(
  118. "%s 挂起时预算到期返回 unverifiable,不无限等待",
  119. async (target) => {
  120. const { workspace, sources } = await fixture();
  121. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  122. hang.target = target;
  123. const pending = readWorkspaceHookScriptStates({ workspacePath: workspace, sources });
  124. await vi.advanceTimersByTimeAsync(5_000);
  125. const states = await pending;
  126. expect([...states.values()]).toEqual([{ kind: "unverifiable" }]);
  127. },
  128. );
  129. it("预算到期后才返回的句柄仍被关闭,迟到结果不改变已返回的状态", async () => {
  130. const { workspace, sources } = await fixture();
  131. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  132. hang.target = "open";
  133. const pending = readWorkspaceHookScriptStates({ workspacePath: workspace, sources });
  134. // 先等读取真正进入 open 再推进截止时间;否则并行负载下截止时间可能在 open 之前触发,
  135. // 迟到的 open 从未开始,句柄关闭也就无从断言(曾导致本用例在多文件并行运行时失败)。
  136. await vi.waitFor(() => expect(hang.late).toBeDefined());
  137. await vi.advanceTimersByTimeAsync(5_000);
  138. const states = await pending;
  139. expect([...states.values()]).toEqual([{ kind: "unverifiable" }]);
  140. hang.late?.();
  141. await vi.waitFor(() => expect(hang.lateHandleClosed).toBe(true));
  142. expect([...states.values()]).toEqual([{ kind: "unverifiable" }]);
  143. });
  144. it("读取流挂起时预算到期返回 unverifiable,句柄被关闭", async () => {
  145. const { workspace, sources } = await fixture();
  146. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  147. hang.target = "stream";
  148. const pending = readWorkspaceHookScriptStates({ workspacePath: workspace, sources });
  149. await vi.advanceTimersByTimeAsync(5_000);
  150. expect([...(await pending).values()]).toEqual([{ kind: "unverifiable" }]);
  151. await vi.waitFor(() => expect(hang.lateHandleClosed).toBe(true));
  152. });
  153. });
  154. /**
  155. * 第六轮验证项:大量不同脚本时限制同时打开的文件数,避免 EMFILE 波及进程内其他 I/O。
  156. * handle.stat 挂起时句柄无法强制关闭(fstat 不可取消),每个挂起文件最多占用一个句柄,
  157. * 且挂起的读取数受同一并发上限约束;这一点写入 spec,不在这里断言。
  158. */
  159. describe("readWorkspaceHookScriptStates 并发上限", () => {
  160. it("同时进行的读取不超过上限,全部结果正确", async () => {
  161. const { writeFile, mkdir } = await vi.importActual<typeof import("node:fs/promises")>(
  162. "node:fs/promises",
  163. );
  164. const workspace = mkdtempSync(join(tmpdir(), "zcode-hook-script-many-"));
  165. roots.push(workspace);
  166. await mkdir(join(workspace, "s"), { recursive: true });
  167. const hookList = [];
  168. for (let index = 0; index < 40; index += 1) {
  169. await writeFile(join(workspace, "s", `h${index}.sh`), `echo ${index}\n`, "utf8");
  170. hookList.push({ type: "process", command: "sh", args: [`s/h${index}.sh`] });
  171. }
  172. const hooks = workspaceHooksConfigSchema.parse({
  173. enabled: true,
  174. events: { SessionStart: [{ hooks: hookList }] },
  175. });
  176. const states = await readWorkspaceHookScriptStates({
  177. workspacePath: workspace,
  178. sources: [
  179. {
  180. canonicalPath: join(workspace, ".zcode", "config.json"),
  181. baseDir: workspace,
  182. discoveryOrder: 0,
  183. configFileKind: ".zcode/config.json",
  184. explicitProjectConfig: false,
  185. editable: true,
  186. hooks,
  187. },
  188. ],
  189. });
  190. expect(states.size).toBe(40);
  191. expect([...states.values()].every((state) => state.kind === "file")).toBe(true);
  192. expect(hang.maxInFlightStats).toBeGreaterThan(1);
  193. expect(hang.maxInFlightStats).toBeLessThanOrEqual(8);
  194. });
  195. });