serviceManager.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import * as childProcess from "node:child_process";
  2. import { PassThrough } from "node:stream";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import {
  5. createServiceDescriptor,
  6. isServiceManagerAvailable,
  7. registerService,
  8. unregisterService,
  9. } from "../src/platform/serviceManager.js";
  10. vi.mock("node:child_process", async (importOriginal) => {
  11. const actual = await importOriginal<typeof childProcess>();
  12. return { ...actual, spawn: vi.fn(actual.spawn) };
  13. });
  14. describe("service manager adapters", () => {
  15. afterEach(() => {
  16. vi.mocked(childProcess.spawn).mockReset();
  17. });
  18. it("finishes a timed-out probe while a descendant still holds its pipes", async () => {
  19. const { spawn } = await vi.importActual<typeof childProcess>("node:child_process");
  20. let descendantPid = 0;
  21. let settled = false;
  22. const exited = new Promise<void>((resolve, reject) => {
  23. vi.mocked(childProcess.spawn).mockImplementationOnce((_command, _args, options) => {
  24. // 模拟 D-Bus 辅助进程继承管道:探测父进程被超时杀死后,后代仍存活。
  25. const child = spawn(
  26. process.execPath,
  27. [
  28. "--eval",
  29. `const { spawn } = require("node:child_process");
  30. spawn(process.execPath, ["--eval", 'process.stdout.write(String(process.pid)); setInterval(() => {}, 1000);'], { stdio: ["ignore", "inherit", "inherit"] });
  31. setInterval(() => {}, 1000);`,
  32. ],
  33. options,
  34. );
  35. child.stdout?.on("data", (chunk) => {
  36. descendantPid = Number(String(chunk).trim());
  37. });
  38. child.once("error", reject);
  39. child.once("exit", () => resolve());
  40. return child;
  41. });
  42. });
  43. const probe = isServiceManagerAvailable("linux").then((available) => {
  44. settled = true;
  45. return available;
  46. });
  47. try {
  48. await exited;
  49. expect(descendantPid).toBeGreaterThan(0);
  50. expect(process.kill(descendantPid, 0)).toBe(true);
  51. // 只等待执行器完成收口;后代退出由 finally 控制,不以延长 timeout 掩盖阻塞。
  52. await vi.waitFor(() => expect(settled).toBe(true), { timeout: 500 });
  53. expect(await probe).toBe(false);
  54. } finally {
  55. if (descendantPid > 0) process.kill(descendantPid, "SIGKILL");
  56. await probe;
  57. }
  58. });
  59. it("keeps reading a successful probe until its inherited stdout closes", async () => {
  60. const child = new childProcess.ChildProcess();
  61. const output = new PassThrough();
  62. child.stdout = output;
  63. let settled = false;
  64. const spawned = new Promise<void>((resolve) => {
  65. vi.mocked(childProcess.spawn).mockImplementationOnce(() => {
  66. resolve();
  67. return child;
  68. });
  69. });
  70. const probe = isServiceManagerAvailable("linux").then((available) => {
  71. settled = true;
  72. return available;
  73. });
  74. try {
  75. await spawned;
  76. // 固定 exit 先于剩余输出的事件顺序,不依赖真实后代进程的启动速度。
  77. child.emit("exit", 0, null);
  78. await new Promise<void>((resolve) => setImmediate(resolve));
  79. expect(settled).toBe(false);
  80. output.end("Version=252\n");
  81. child.emit("close", 0, null);
  82. expect(await probe).toBe(true);
  83. } finally {
  84. output.destroy();
  85. child.emit("close", 1, null);
  86. await probe;
  87. }
  88. });
  89. it("probes the Linux user service manager without registering a unit", async () => {
  90. const calls: Array<{
  91. command: string;
  92. args: readonly string[];
  93. timeoutMs: number | undefined;
  94. }> = [];
  95. await expect(
  96. isServiceManagerAvailable("linux", {
  97. run: async () => undefined,
  98. runResult: async (command, args, options) => {
  99. calls.push({ command, args, timeoutMs: options?.timeoutMs });
  100. return { exitCode: 0, stdout: "Version=249.11-0ubuntu3.22\n", stderr: "" };
  101. },
  102. }),
  103. ).resolves.toBe(true);
  104. expect(calls).toEqual([
  105. {
  106. command: "systemctl",
  107. args: ["--user", "show", "--property=Version"],
  108. timeoutMs: 2_000,
  109. },
  110. ]);
  111. });
  112. it("treats an inaccessible user service manager as a fallback capability", async () => {
  113. await expect(
  114. isServiceManagerAvailable("linux", {
  115. run: async () => undefined,
  116. runResult: async () => ({
  117. exitCode: 1,
  118. stdout: "",
  119. stderr: "Failed to connect to bus",
  120. }),
  121. }),
  122. ).resolves.toBe(false);
  123. });
  124. it("does not register against a skipped Linux probe that exits successfully", async () => {
  125. await expect(
  126. isServiceManagerAvailable("linux", {
  127. run: async () => undefined,
  128. runResult: async () => ({
  129. exitCode: 0,
  130. stdout: "",
  131. stderr: "Running in chroot, ignoring command 'show'\n",
  132. }),
  133. }),
  134. ).resolves.toBe(false);
  135. });
  136. it.each(["", "Version=\n", "Welcome to the server\n"])(
  137. "requires a manager response even when stderr is empty (stdout: %j)",
  138. async (stdout) => {
  139. await expect(
  140. isServiceManagerAvailable("linux", {
  141. run: async () => undefined,
  142. runResult: async () => ({ exitCode: 0, stdout, stderr: "" }),
  143. }),
  144. ).resolves.toBe(false);
  145. },
  146. );
  147. it("keeps a responding Linux manager available despite an unrelated warning", async () => {
  148. await expect(
  149. isServiceManagerAvailable("linux", {
  150. run: async () => undefined,
  151. runResult: async () => ({
  152. exitCode: 0,
  153. stdout: "Version=252\n",
  154. stderr: "A diagnostic warning\n",
  155. }),
  156. }),
  157. ).resolves.toBe(true);
  158. });
  159. it("maps all supported platforms to their native registration commands", async () => {
  160. const calls: Array<{ command: string; args: readonly string[] }> = [];
  161. const executor = {
  162. run: async (command: string, args: readonly string[]) => {
  163. calls.push({ command, args });
  164. },
  165. };
  166. for (const platform of ["darwin", "linux", "win32"] as const) {
  167. const descriptor = createServiceDescriptor({
  168. platform,
  169. command: "/opt/zcode/bin/zcode",
  170. args: ["serve", "--daemon"],
  171. });
  172. await registerService(descriptor, `/tmp/${descriptor.kind}.service`, executor);
  173. await unregisterService(descriptor, `/tmp/${descriptor.kind}.service`, executor);
  174. }
  175. expect(calls.map((call) => call.command)).toEqual([
  176. "launchctl",
  177. "launchctl",
  178. "launchctl",
  179. "launchctl",
  180. "systemctl",
  181. "systemctl",
  182. "systemctl",
  183. "schtasks",
  184. "schtasks",
  185. "schtasks",
  186. ]);
  187. expect(calls.at(-2)?.args).toContain("/Run");
  188. });
  189. it("does not restart a launchd service after a normal stop", () => {
  190. const descriptor = createServiceDescriptor({
  191. platform: "darwin",
  192. command: "/opt/zcode/bin/zcode",
  193. });
  194. expect(descriptor.content).toContain(
  195. "<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>",
  196. );
  197. });
  198. it("tolerates launchd unregister when a deferred registration was never loaded", async () => {
  199. const descriptor = createServiceDescriptor({
  200. platform: "darwin",
  201. command: "/opt/zcode/bin/zcode",
  202. });
  203. await expect(
  204. unregisterService(descriptor, "/tmp/zcode.plist", {
  205. run: async () => {
  206. throw new Error("launchctl unload failed (3): Could not find specified service");
  207. },
  208. }),
  209. ).resolves.toBeUndefined();
  210. });
  211. it("tolerates a missing Windows task when schtasks reports a missing file", async () => {
  212. const descriptor = createServiceDescriptor({
  213. platform: "win32",
  214. command: "C:/zcode/bin/zcode.cmd",
  215. });
  216. await expect(
  217. unregisterService(descriptor, "C:/zcode/service/task.json", {
  218. run: async () => {
  219. throw new Error(
  220. "schtasks /Delete failed (1): ERROR: The system cannot find the file specified.",
  221. );
  222. },
  223. }),
  224. ).resolves.toBeUndefined();
  225. });
  226. it("does not swallow Windows task permission failures", async () => {
  227. const descriptor = createServiceDescriptor({
  228. platform: "win32",
  229. command: "C:/zcode/bin/zcode.cmd",
  230. });
  231. await expect(
  232. unregisterService(descriptor, "C:/zcode/service/task.json", {
  233. run: async () => {
  234. throw new Error("schtasks /Delete failed (5): Access is denied.");
  235. },
  236. }),
  237. ).rejects.toThrow(/Access is denied/);
  238. });
  239. it("uses the structured schtasks HRESULT probe before deleting a Windows task", async () => {
  240. const descriptor = createServiceDescriptor({
  241. platform: "win32",
  242. command: "C:/zcode/bin/zcode.cmd",
  243. });
  244. const calls: string[][] = [];
  245. await expect(
  246. unregisterService(descriptor, "C:/zcode/service/task.json", {
  247. run: async (_command, args) => {
  248. calls.push([...args]);
  249. },
  250. runResult: async (_command, args) => {
  251. calls.push([...args]);
  252. return { exitCode: 0x80070002, stdout: "", stderr: "" };
  253. },
  254. }),
  255. ).resolves.toBeUndefined();
  256. expect(calls).toEqual([["/Query", "/TN", descriptor.name, "/HResult"]]);
  257. });
  258. it("does not treat a structured Windows task query permission error as absence", async () => {
  259. const descriptor = createServiceDescriptor({
  260. platform: "win32",
  261. command: "C:/zcode/bin/zcode.cmd",
  262. });
  263. await expect(
  264. unregisterService(descriptor, "C:/zcode/service/task.json", {
  265. run: async () => undefined,
  266. runResult: async () => ({
  267. exitCode: 0x80070005,
  268. stdout: "",
  269. stderr: "Access is denied.",
  270. }),
  271. }),
  272. ).rejects.toThrow(/failed \(2147942405\)/);
  273. });
  274. it("reloads an existing launchd label before starting the new descriptor", async () => {
  275. const descriptor = createServiceDescriptor({
  276. platform: "darwin",
  277. command: "/opt/zcode/bin/zcode",
  278. args: ["serve", "--new"],
  279. });
  280. const calls: string[][] = [];
  281. await registerService(descriptor, "/tmp/new.plist", {
  282. run: async (_command, args) => {
  283. calls.push([...args]);
  284. if (args[0] === "unload") throw new Error("Could not find specified service");
  285. },
  286. });
  287. expect(calls).toEqual([
  288. ["unload", "-w", "/tmp/new.plist"],
  289. ["load", "-w", "/tmp/new.plist"],
  290. ["start", descriptor.name],
  291. ]);
  292. });
  293. it("propagates launchd load failures with the descriptor path", async () => {
  294. const descriptor = createServiceDescriptor({
  295. platform: "darwin",
  296. command: "/opt/zcode/bin/zcode",
  297. });
  298. await expect(
  299. registerService(descriptor, "/tmp/broken.plist", {
  300. run: async (_command, args) => {
  301. if (args[0] === "load") throw new Error("permission denied");
  302. },
  303. }),
  304. ).rejects.toThrow(/broken\.plist/);
  305. });
  306. });