preinstalledEntryShim.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import { execFile, spawn, spawnSync } from "node:child_process";
  2. import { once } from "node:events";
  3. import { existsSync } from "node:fs";
  4. import {
  5. copyFile,
  6. mkdir,
  7. mkdtemp,
  8. readFile,
  9. rename,
  10. rm,
  11. unlink,
  12. writeFile,
  13. } from "node:fs/promises";
  14. import { tmpdir } from "node:os";
  15. import { join, resolve } from "node:path";
  16. import { promisify } from "node:util";
  17. import { afterAll, beforeAll, describe, expect, it } from "vitest";
  18. /**
  19. * Windows 入口 shim 的验收,对应 docs/preinstalled-tools/windows-entry-shim.md 的验收表。
  20. * 目标用 node.exe:它能回显收到的参数和环境,也能派生后代进程。
  21. */
  22. const execFileAsync = promisify(execFile);
  23. const desktopRoot = resolve(import.meta.dirname, "..");
  24. const builtShim = join(
  25. desktopRoot,
  26. "bundled-tools",
  27. `win32-${process.arch}`,
  28. "preinstalled-entry-shim",
  29. "zcode-preinstalled-entry-shim.exe",
  30. );
  31. const echoProgram = [
  32. "process.stdout.write(JSON.stringify({",
  33. "argv:process.argv.slice(1),",
  34. "fixedDefault:process.env.SHIM_DEFAULT,",
  35. "fixedSet:process.env.SHIM_SET,",
  36. "unset:process.env.SHIM_UNSET,",
  37. "}));",
  38. ].join("");
  39. const isAlive = (pid: number) => {
  40. try {
  41. process.kill(pid, 0);
  42. return true;
  43. } catch {
  44. return false;
  45. }
  46. };
  47. const waitFor = async (condition: () => boolean | Promise<boolean>, timeoutMs = 10_000) => {
  48. const deadline = Date.now() + timeoutMs;
  49. while (Date.now() < deadline) {
  50. if (await condition()) return;
  51. await new Promise((done) => setTimeout(done, 50));
  52. }
  53. throw new Error("等待条件超时");
  54. };
  55. describe.skipIf(process.platform !== "win32")("Windows 入口 shim", () => {
  56. let root: string;
  57. let counter = 0;
  58. async function entry(config: {
  59. target?: string;
  60. args?: string[];
  61. env?: unknown[];
  62. raw?: string;
  63. directory?: string;
  64. }) {
  65. counter += 1;
  66. const directory = config.directory ?? join(root, `entry-${counter}`);
  67. await mkdir(directory, { recursive: true });
  68. const exe = join(directory, "tool.exe");
  69. await copyFile(builtShim, exe);
  70. await writeFile(
  71. join(directory, "tool.shim"),
  72. config.raw ??
  73. JSON.stringify({
  74. schemaVersion: 1,
  75. target: config.target ?? process.execPath,
  76. args: config.args ?? ["-e", echoProgram],
  77. env: config.env ?? [],
  78. }),
  79. );
  80. return exe;
  81. }
  82. beforeAll(async () => {
  83. if (!existsSync(builtShim)) {
  84. const result = spawnSync(
  85. process.execPath,
  86. [join(desktopRoot, "scripts/build-windows-preinstalled-entry-shim.mjs")],
  87. { stdio: "inherit" },
  88. );
  89. expect(result.status).toBe(0);
  90. }
  91. root = await mkdtemp(join(tmpdir(), "shim 中文 100%-"));
  92. }, 180_000);
  93. afterAll(async () => {
  94. await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
  95. });
  96. it("参数含空格、中文、特殊字符和空字符串时,目标收到的与调用方传入的一致", async () => {
  97. const exe = await entry({});
  98. const args = [
  99. "带 空格",
  100. "中文参数",
  101. "100%",
  102. "%PATH%",
  103. "a^b",
  104. "a&b",
  105. 'quote"inside',
  106. "",
  107. "trailing\\",
  108. "file:///C:/a%20b",
  109. ];
  110. const { stdout } = await execFileAsync(exe, args);
  111. expect(JSON.parse(stdout).argv).toEqual(args);
  112. });
  113. it("配置中的固定参数排在调用方参数之前,含引号和反斜杠时不变形", async () => {
  114. const fixed = ["--install=C:\\路径 含空格\\", 'a"b', ""];
  115. const exe = await entry({ args: ["-e", echoProgram, "--", ...fixed] });
  116. const { stdout } = await execFileAsync(exe, ["caller"]);
  117. expect(JSON.parse(stdout).argv).toEqual([...fixed, "caller"]);
  118. });
  119. it("按 set、default、unset 处理环境,default 不覆盖已有值", async () => {
  120. const exe = await entry({
  121. env: [
  122. { name: "SHIM_SET", action: "set", value: "配置值 100%" },
  123. { name: "SHIM_DEFAULT", action: "default", value: "默认值" },
  124. { name: "SHIM_UNSET", action: "unset" },
  125. ],
  126. });
  127. const env = { ...process.env, SHIM_SET: "调用方", SHIM_UNSET: "调用方" };
  128. const absent = JSON.parse((await execFileAsync(exe, [], { env })).stdout);
  129. expect(absent).toMatchObject({ fixedSet: "配置值 100%", fixedDefault: "默认值" });
  130. expect(absent.unset).toBeUndefined();
  131. const present = JSON.parse(
  132. (await execFileAsync(exe, [], { env: { ...env, SHIM_DEFAULT: "调用方" } })).stdout,
  133. );
  134. expect(present.fixedDefault).toBe("调用方");
  135. });
  136. it("返回目标的退出码,包含大于 INT_MAX 的值", async () => {
  137. for (const code of [0, 5, 3221225477]) {
  138. const exe = await entry({ args: ["-e", `process.exit(${code})`] });
  139. const result = spawnSync(exe, []);
  140. expect(result.status).toBe(code);
  141. }
  142. });
  143. it.each([
  144. ["配置缺失", async (exe: string) => unlink(exe.replace(/\.exe$/, ".shim"))],
  145. ["JSON 无效", async (exe: string) => writeFile(exe.replace(/\.exe$/, ".shim"), "{")],
  146. [
  147. "未知字段",
  148. async (exe: string) =>
  149. writeFile(
  150. exe.replace(/\.exe$/, ".shim"),
  151. '{"schemaVersion":1,"target":"x","args":[],"env":[],"extra":1}',
  152. ),
  153. ],
  154. [
  155. "版本不支持",
  156. async (exe: string) =>
  157. writeFile(
  158. exe.replace(/\.exe$/, ".shim"),
  159. '{"schemaVersion":2,"target":"x","args":[],"env":[]}',
  160. ),
  161. ],
  162. [
  163. "目标不存在",
  164. async (exe: string) =>
  165. writeFile(
  166. exe.replace(/\.exe$/, ".shim"),
  167. '{"schemaVersion":1,"target":"C:\\\\missing\\\\x.exe","args":[],"env":[]}',
  168. ),
  169. ],
  170. ])("%s时退出码为 127,并写明原因", async (_name, breakConfig) => {
  171. const exe = await entry({});
  172. await breakConfig(exe);
  173. const result = spawnSync(exe, [], { encoding: "utf8" });
  174. expect(result.status).toBe(127);
  175. expect(result.stderr).toContain("zcode-preinstalled-entry-shim:");
  176. });
  177. it("结束 shim 时,目标及其后代一起结束,版本目录可以删除", async () => {
  178. const version = join(root, "版本目录");
  179. await mkdir(version);
  180. const target = join(version, "target.exe");
  181. await copyFile(process.execPath, target);
  182. const pids = join(root, "kill-tree-pids.json");
  183. const program = [
  184. "const {spawn}=require('child_process'),{writeFileSync}=require('fs');",
  185. "const c=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'});",
  186. `writeFileSync(${JSON.stringify(pids)},JSON.stringify([process.pid,c.pid]));`,
  187. "setInterval(()=>{},1000);",
  188. ].join("");
  189. const exe = await entry({ target, args: ["-e", program] });
  190. const shim = spawn(exe, [], { stdio: "ignore" });
  191. await waitFor(() => existsSync(pids));
  192. const [targetPid, childPid] = JSON.parse(await readFile(pids, "utf8")) as [number, number];
  193. expect(isAlive(targetPid)).toBe(true);
  194. expect(isAlive(childPid)).toBe(true);
  195. shim.kill();
  196. await once(shim, "exit");
  197. await waitFor(() => !isAlive(targetPid) && !isAlive(childPid));
  198. await rm(version, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
  199. expect(existsSync(version)).toBe(false);
  200. }, 30_000);
  201. it("shim 刚启动目标就被结束时,目标不残留,版本目录可以删除", async () => {
  202. const version = join(root, "立即结束");
  203. await mkdir(version);
  204. const target = join(version, "target.exe");
  205. await copyFile(process.execPath, target);
  206. const exe = await entry({ target, args: ["-e", "setInterval(()=>{},1000)"] });
  207. // 结束时机落在 shim 创建目标的毫秒级窗口内才会留下挂起的目标;定时器精度不够,用忙等按 0.25 毫秒步进扫过前 40 毫秒。
  208. for (let attempt = 0; attempt < 320; attempt += 1) {
  209. const shim = spawn(exe, [], { stdio: "ignore" });
  210. const killAt = performance.now() + (attempt % 160) * 0.25;
  211. while (performance.now() < killAt) continue;
  212. shim.kill();
  213. await once(shim, "exit");
  214. }
  215. // 残留的目标映射着 target.exe,目录删不掉。
  216. await rm(version, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
  217. expect(existsSync(version)).toBe(false);
  218. }, 120_000);
  219. it("目标正常结束时,保留它有意留在后台的后代进程", async () => {
  220. const pidFile = join(root, "detached-pid.txt");
  221. const program = [
  222. "const {spawn}=require('child_process'),{writeFileSync}=require('fs');",
  223. "const c=spawn(process.execPath,['-e','setTimeout(()=>{},60000)'],{stdio:'ignore',detached:true});",
  224. `writeFileSync(${JSON.stringify(pidFile)},String(c.pid));`,
  225. "c.unref();",
  226. ].join("");
  227. const exe = await entry({ args: ["-e", program] });
  228. await execFileAsync(exe, []);
  229. const pid = Number(await readFile(pidFile, "utf8"));
  230. try {
  231. expect(isAlive(pid)).toBe(true);
  232. } finally {
  233. process.kill(pid);
  234. }
  235. }, 30_000);
  236. it("目标运行中撤下入口:新调用找不到入口,运行中的调用返回目标的退出码", async () => {
  237. const exe = await entry({
  238. args: ["-e", "setTimeout(()=>process.exit(5),1500)"],
  239. });
  240. const running = spawn(exe, [], { stdio: "ignore" });
  241. await new Promise((done) => setTimeout(done, 300));
  242. await mkdir(join(root, "retired"), { recursive: true });
  243. const retired = join(root, "retired", "tool-1.exe");
  244. await rename(exe, retired);
  245. await unlink(exe.replace(/\.exe$/, ".shim"));
  246. expect(existsSync(exe)).toBe(false);
  247. const [code] = (await once(running, "exit")) as [number];
  248. expect(code).toBe(5);
  249. await rm(retired, { force: true, maxRetries: 5, retryDelay: 100 });
  250. expect(existsSync(retired)).toBe(false);
  251. }, 30_000);
  252. it("目标运行中替换配置和 shim:运行中的调用不受影响,新调用用新配置", async () => {
  253. const exe = await entry({
  254. args: ["-e", "setTimeout(()=>process.exit(7),1500)"],
  255. });
  256. const running = spawn(exe, [], { stdio: "ignore" });
  257. await new Promise((done) => setTimeout(done, 300));
  258. const shimConfig = exe.replace(/\.exe$/, ".shim");
  259. const nextConfig = `${shimConfig}.next`;
  260. await writeFile(
  261. nextConfig,
  262. JSON.stringify({
  263. schemaVersion: 1,
  264. target: process.execPath,
  265. args: ["-e", "process.exit(9)"],
  266. env: [],
  267. }),
  268. );
  269. await rename(nextConfig, shimConfig);
  270. const retired = `${exe}.retired`;
  271. await rename(exe, retired);
  272. await copyFile(builtShim, exe);
  273. expect(spawnSync(exe, []).status).toBe(9);
  274. const [code] = (await once(running, "exit")) as [number];
  275. expect(code).toBe(7);
  276. await rm(retired, { force: true, maxRetries: 5, retryDelay: 100 });
  277. }, 30_000);
  278. it("目标是 .cmd 时也能启动(只用于小包夹具)", async () => {
  279. const script = join(root, "fixture.cmd");
  280. await writeFile(script, "@echo hello %1\r\n@exit /b 3\r\n");
  281. const exe = await entry({ target: script, args: [] });
  282. const result = spawnSync(exe, ["world"], { encoding: "utf8" });
  283. expect(result.status).toBe(3);
  284. expect(result.stdout).toContain("hello world");
  285. });
  286. it("重复构建产出相同字节,入口替换判断才可靠", async () => {
  287. const before = await readFile(builtShim);
  288. const result = spawnSync(
  289. process.execPath,
  290. [join(desktopRoot, "scripts/build-windows-preinstalled-entry-shim.mjs")],
  291. { encoding: "utf8" },
  292. );
  293. expect(result.status).toBe(0);
  294. expect((await readFile(builtShim)).equals(before)).toBe(true);
  295. }, 180_000);
  296. });