bash-file-output.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import { constants } from "node:fs";
  2. import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. const { openSpy, statSpy } = vi.hoisted(() => ({ openSpy: vi.fn(), statSpy: vi.fn() }));
  7. vi.mock("node:fs/promises", async (importOriginal) => {
  8. const actual = await importOriginal<typeof import("node:fs/promises")>();
  9. openSpy.mockImplementation(actual.open);
  10. statSpy.mockImplementation(actual.stat);
  11. return { ...actual, open: openSpy, stat: statSpy };
  12. });
  13. import { BashFileOutput, readBashOutput } from "../src/exec/bash-file-output.js";
  14. const roots: string[] = [];
  15. const outputs: BashFileOutput[] = [];
  16. afterEach(async () => {
  17. for (const output of outputs.splice(0)) {
  18. output.stopWatching();
  19. await output.close();
  20. }
  21. vi.useRealTimers();
  22. vi.clearAllMocks();
  23. for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
  24. });
  25. async function fixture(platform: NodeJS.Platform = process.platform) {
  26. const root = await mkdtemp(join(tmpdir(), "zcode-bash-file-"));
  27. roots.push(root);
  28. const path = join(root, "输出 with spaces.log");
  29. const output = new BashFileOutput(path, platform, null);
  30. outputs.push(output);
  31. return { output, path };
  32. }
  33. describe("Bash direct output", () => {
  34. it.each(["darwin", "linux", "win32"] as const)(
  35. "uses host %s flags and existing-file semantics",
  36. async (platform) => {
  37. const { output, path } = await fixture(platform);
  38. await writeFile(path, "existing\n");
  39. await output.prepare();
  40. const flags =
  41. platform === "win32"
  42. ? "w"
  43. : constants.O_WRONLY |
  44. constants.O_CREAT |
  45. constants.O_APPEND |
  46. (constants.O_NOFOLLOW ?? 0);
  47. expect(openSpy).toHaveBeenCalledWith(path, flags, 0o600);
  48. expect(openSpy).toHaveBeenCalledTimes(1);
  49. await output.close();
  50. expect(await readFile(path, "utf8")).toBe(platform === "win32" ? "" : "existing\n");
  51. },
  52. );
  53. it("only deletes a file created by this preparation when cancelled", async () => {
  54. const fresh = await fixture();
  55. await fresh.output.prepare();
  56. await fresh.output.discard();
  57. await expect(readFile(fresh.path)).rejects.toMatchObject({ code: "ENOENT" });
  58. const existing = await fixture();
  59. await writeFile(existing.path, "preserved");
  60. await existing.output.prepare();
  61. await existing.output.discard();
  62. expect(await readFile(existing.path, "utf8")).toBe(
  63. process.platform === "win32" ? "" : "preserved",
  64. );
  65. });
  66. it("does not let descriptor cleanup failure replace cancellation or settlement", async () => {
  67. const { output, path } = await fixture();
  68. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  69. openSpy.mockImplementationOnce(async (...args: Parameters<typeof actual.open>) => {
  70. const handle = await actual.open(...args);
  71. const close = handle.close.bind(handle);
  72. vi.spyOn(handle, "close").mockImplementationOnce(async () => {
  73. await close();
  74. throw new Error("close failed");
  75. });
  76. return handle;
  77. });
  78. await output.prepare();
  79. await expect(output.discard()).resolves.toBeUndefined();
  80. expect(output.fd).toBeUndefined();
  81. await expect(readFile(path)).rejects.toMatchObject({ code: "ENOENT" });
  82. });
  83. it("reads bounded head/tail with full file byte counts and explicit read errors", async () => {
  84. const { output, path } = await fixture();
  85. await output.prepare();
  86. await output.close();
  87. await writeFile(path, "abcdefgh");
  88. expect(await readBashOutput(path, 3, false, null)).toMatchObject({
  89. text: "abc",
  90. bytes: 8,
  91. truncated: true,
  92. });
  93. expect(await readBashOutput(path, 3, true, null)).toMatchObject({
  94. text: "fgh",
  95. bytes: 8,
  96. truncated: true,
  97. });
  98. expect(await output.result(0)).toMatchObject({ text: "", bytes: 8, truncated: true });
  99. await rm(path);
  100. expect((await output.result(3)).text).toContain("bash output unavailable");
  101. });
  102. it("polls after the foreground delay, reads at most 4 KiB and stops at settlement", async () => {
  103. const { output, path } = await fixture();
  104. await output.prepare();
  105. await output.close();
  106. const text = Array.from({ length: 500 }, (_, i) => `line-${i + 1}\r\n`).join("");
  107. await writeFile(path, text);
  108. openSpy.mockClear();
  109. const onRead = vi.fn();
  110. let read!: () => void;
  111. const first = new Promise<void>((resolve) => {
  112. read = resolve;
  113. });
  114. vi.useFakeTimers();
  115. output.watchProgress(8192, 2000, 1000, (sample, preview) => {
  116. onRead(sample, preview);
  117. read();
  118. });
  119. await vi.advanceTimersByTimeAsync(2999);
  120. expect(openSpy).not.toHaveBeenCalled();
  121. await vi.advanceTimersByTimeAsync(1);
  122. await first;
  123. const [sample, preview] = onRead.mock.calls[0]!;
  124. expect(sample.bytesRead).toBe(4096);
  125. expect(preview).toMatchObject({ totalBytes: Buffer.byteLength(text), linesEstimated: true });
  126. expect(preview.text).toContain("line-500");
  127. expect(preview.text).not.toContain("line-450");
  128. expect(preview.fullText).toContain("line-450");
  129. output.stopWatching();
  130. await vi.advanceTimersByTimeAsync(10000);
  131. expect(onRead).toHaveBeenCalledTimes(1);
  132. });
  133. it("shares the progress interval across files and isolates background handoff", async () => {
  134. const first = await fixture();
  135. const second = await fixture();
  136. for (const fixture of [first, second]) {
  137. await fixture.output.prepare();
  138. await fixture.output.close();
  139. }
  140. await writeFile(first.path, "first output");
  141. await writeFile(second.path, "second output");
  142. const firstRead = vi.fn();
  143. const secondRead = vi.fn();
  144. let finishFirst!: () => void;
  145. let finishSecond!: () => void;
  146. const readFirst = new Promise<void>((resolve) => {
  147. finishFirst = resolve;
  148. });
  149. const readSecond = new Promise<void>((resolve) => {
  150. finishSecond = resolve;
  151. });
  152. vi.useFakeTimers();
  153. first.output.watchProgress(4096, 2000, 1000, (sample) => {
  154. firstRead(sample.text);
  155. finishFirst();
  156. });
  157. await vi.advanceTimersByTimeAsync(500);
  158. second.output.watchProgress(4096, 2000, 1000, (sample) => {
  159. secondRead(sample.text);
  160. finishSecond();
  161. });
  162. await vi.advanceTimersByTimeAsync(2000);
  163. expect(vi.getTimerCount()).toBe(1);
  164. await vi.advanceTimersByTimeAsync(500);
  165. await Promise.all([readFirst, readSecond]);
  166. expect(firstRead).toHaveBeenCalledWith("first output");
  167. expect(secondRead).toHaveBeenCalledWith("second output");
  168. // 后台提交重启独立的大小 watchdog,只取消本任务的前台订阅。
  169. first.output.watchLimit(5 * 1024 ** 3, vi.fn());
  170. expect(vi.getTimerCount()).toBe(2);
  171. const nextRead = new Promise<void>((resolve) => {
  172. finishSecond = resolve;
  173. });
  174. await vi.advanceTimersByTimeAsync(1000);
  175. await nextRead;
  176. expect(firstRead).toHaveBeenCalledTimes(1);
  177. expect(secondRead).toHaveBeenCalledTimes(2);
  178. second.output.stopWatching();
  179. expect(vi.getTimerCount()).toBe(1);
  180. first.output.stopWatching();
  181. expect(vi.getTimerCount()).toBe(0);
  182. });
  183. it("cancels a pending subscription before its delay without starting a poller", async () => {
  184. const { output } = await fixture();
  185. const onRead = vi.fn();
  186. openSpy.mockClear();
  187. vi.useFakeTimers();
  188. output.watchProgress(4096, 2000, 1000, onRead);
  189. output.stopWatching();
  190. await vi.advanceTimersByTimeAsync(10000);
  191. expect(vi.getTimerCount()).toBe(0);
  192. expect(openSpy).not.toHaveBeenCalled();
  193. expect(onRead).not.toHaveBeenCalled();
  194. });
  195. it("drops an old file read after progress resubscription", async () => {
  196. const { output, path } = await fixture();
  197. await output.prepare();
  198. await output.close();
  199. await writeFile(path, "current output");
  200. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  201. const gate = Promise.withResolvers<void>();
  202. const closed = Promise.withResolvers<void>();
  203. openSpy.mockImplementationOnce(async (...args: Parameters<typeof actual.open>) => {
  204. const handle = await actual.open(...args);
  205. const close = handle.close.bind(handle);
  206. vi.spyOn(handle, "close").mockImplementation(async () => {
  207. await close();
  208. closed.resolve();
  209. });
  210. await gate.promise;
  211. return handle;
  212. });
  213. const oldRead = vi.fn();
  214. const next = Promise.withResolvers<string>();
  215. vi.useFakeTimers();
  216. output.watchProgress(4096, 0, 1000, oldRead);
  217. await vi.advanceTimersByTimeAsync(1000);
  218. output.watchProgress(4096, 0, 1000, (sample) => next.resolve(sample.text));
  219. gate.resolve();
  220. await closed.promise;
  221. await vi.advanceTimersByTimeAsync(0);
  222. expect(oldRead).not.toHaveBeenCalled();
  223. expect(vi.getTimerCount()).toBe(1);
  224. await vi.advanceTimersByTimeAsync(1000);
  225. expect(await next.promise).toBe("current output");
  226. });
  227. it("checks every five seconds, ignores equality, and restarts at background commit", async () => {
  228. const { output, path } = await fixture();
  229. const actualStat = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  230. let size = 5 * 1024 ** 3;
  231. statSpy.mockImplementation(async (candidate, ...args) =>
  232. candidate === path ? { size } : actualStat.stat(candidate, ...args),
  233. );
  234. const limit = vi.fn();
  235. vi.useFakeTimers();
  236. try {
  237. output.watchLimit(size, limit);
  238. await vi.advanceTimersByTimeAsync(4_999);
  239. expect(statSpy).not.toHaveBeenCalled();
  240. await vi.advanceTimersByTimeAsync(1);
  241. expect(limit).not.toHaveBeenCalled();
  242. await vi.advanceTimersByTimeAsync(1_000);
  243. output.watchLimit(size, limit);
  244. size += 1;
  245. await vi.advanceTimersByTimeAsync(4_999);
  246. expect(limit).not.toHaveBeenCalled();
  247. await vi.advanceTimersByTimeAsync(1);
  248. expect(limit).toHaveBeenCalledTimes(1);
  249. await vi.advanceTimersByTimeAsync(10_000);
  250. expect(limit).toHaveBeenCalledTimes(1);
  251. } finally {
  252. statSpy.mockImplementation(actualStat.stat);
  253. }
  254. });
  255. it("ignores a late stat result after settlement", async () => {
  256. const { output } = await fixture();
  257. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  258. let finish!: (value: { size: number }) => void;
  259. statSpy.mockImplementationOnce(
  260. () =>
  261. new Promise((resolve) => {
  262. finish = resolve;
  263. }),
  264. );
  265. const limit = vi.fn();
  266. vi.useFakeTimers();
  267. try {
  268. output.watchLimit(10, limit);
  269. await vi.advanceTimersByTimeAsync(5_000);
  270. output.stopWatching();
  271. finish({ size: 11 });
  272. await vi.advanceTimersByTimeAsync(0);
  273. expect(limit).not.toHaveBeenCalled();
  274. } finally {
  275. statSpy.mockImplementation(actual.stat);
  276. }
  277. });
  278. });