windows-job-object.test.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import { spawn, type ChildProcess } from "node:child_process";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. attachProcessToWindowsJobObject,
  5. type WindowsJobObjectApi,
  6. } from "../src/mcp/windows-job-object.js";
  7. describe("Windows MCP Job Object adapter", () => {
  8. it("attaches the transport root and terminates/closes its private job", async () => {
  9. const job = { id: "job-1" };
  10. const api: WindowsJobObjectApi = {
  11. create: vi.fn(() => job),
  12. assign: vi.fn(() => true),
  13. terminate: vi.fn(),
  14. close: vi.fn(),
  15. };
  16. const controller = await attachProcessToWindowsJobObject(4321, {
  17. api,
  18. platform: "win32",
  19. });
  20. expect(api.create).toHaveBeenCalledOnce();
  21. expect(api.assign).toHaveBeenCalledWith(job, 4321);
  22. expect(controller).toBeDefined();
  23. controller?.terminate();
  24. controller?.close();
  25. expect(api.terminate).toHaveBeenCalledWith(job);
  26. expect(api.close).toHaveBeenCalledWith(job);
  27. });
  28. it("returns no controller and closes the job when root assignment fails", async () => {
  29. const job = { id: "job-2" };
  30. const api: WindowsJobObjectApi = {
  31. create: vi.fn(() => job),
  32. assign: vi.fn(() => false),
  33. terminate: vi.fn(),
  34. close: vi.fn(),
  35. };
  36. await expect(
  37. attachProcessToWindowsJobObject(9876, { api, platform: "win32" }),
  38. ).resolves.toBeUndefined();
  39. expect(api.assign).toHaveBeenCalledWith(job, 9876);
  40. expect(api.close).toHaveBeenCalledWith(job);
  41. expect(api.terminate).not.toHaveBeenCalled();
  42. });
  43. it("does not load or create a Windows job on non-Windows platforms", async () => {
  44. const api: WindowsJobObjectApi = {
  45. create: vi.fn(),
  46. assign: vi.fn(),
  47. terminate: vi.fn(),
  48. close: vi.fn(),
  49. };
  50. await expect(
  51. attachProcessToWindowsJobObject(1234, { api, platform: "darwin" }),
  52. ).resolves.toBeUndefined();
  53. expect(api.create).not.toHaveBeenCalled();
  54. });
  55. it.runIf(process.platform === "win32")(
  56. "terminates a root and a descendant created after Job Object attach",
  57. async () => {
  58. const root = spawn(
  59. process.execPath,
  60. [
  61. "-e",
  62. [
  63. "const { spawn } = require('node:child_process');",
  64. "process.stdin.on('data', (chunk) => {",
  65. " if (!chunk.toString().includes('spawn')) return;",
  66. " const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore', windowsHide: true });",
  67. " console.log(child.pid);",
  68. "});",
  69. "setInterval(() => {}, 1000);",
  70. ].join("\n"),
  71. ],
  72. { stdio: ["pipe", "pipe", "ignore"], windowsHide: true },
  73. );
  74. let childPid = 0;
  75. try {
  76. const controller = await attachProcessToWindowsJobObject(root.pid ?? 0, {
  77. platform: "win32",
  78. });
  79. expect(controller).toBeDefined();
  80. const childPidPromise = readFirstLine(root);
  81. root.stdin?.write("spawn\n");
  82. childPid = await childPidPromise;
  83. controller?.terminate();
  84. controller?.close();
  85. await expect(waitForExit(root.pid ?? 0)).resolves.toBeUndefined();
  86. await expect(waitForExit(childPid)).resolves.toBeUndefined();
  87. } finally {
  88. if (root.exitCode == null) root.kill();
  89. if (childPid > 0) {
  90. try {
  91. process.kill(childPid);
  92. } catch {
  93. // 子进程已被 Job 或测试主体回收。
  94. }
  95. }
  96. }
  97. },
  98. 10_000,
  99. );
  100. });
  101. function readFirstLine(child: ChildProcess): Promise<number> {
  102. return new Promise((resolveLine, rejectLine) => {
  103. let output = "";
  104. const onData = (chunk: Buffer) => {
  105. output += chunk.toString();
  106. const line = output.match(/\d+/u)?.[0];
  107. if (!line) return;
  108. child.stdout?.off("data", onData);
  109. resolveLine(Number(line));
  110. };
  111. child.once("error", rejectLine);
  112. child.stdout?.on("data", onData);
  113. });
  114. }
  115. async function waitForExit(pid: number): Promise<void> {
  116. const deadline = Date.now() + 5_000;
  117. while (Date.now() < deadline) {
  118. try {
  119. process.kill(pid, 0);
  120. } catch {
  121. return;
  122. }
  123. await new Promise((resolveWait) => setTimeout(resolveWait, 50));
  124. }
  125. throw new Error(`process ${pid} is still alive`);
  126. }