preinstalledEntryShimBuild.test.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import { execFile } from "node:child_process";
  2. import { chmod, copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  3. import { join, resolve } from "node:path";
  4. import { promisify } from "node:util";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. const exec = promisify(execFile);
  7. const repoRoot = resolve(import.meta.dirname, "../../..");
  8. const directories: string[] = [];
  9. const shimName = "zcode-preinstalled-entry-shim.exe";
  10. afterEach(async () => {
  11. await Promise.all(
  12. directories.splice(0).map((path) => rm(path, { recursive: true, force: true })),
  13. );
  14. });
  15. async function fixture() {
  16. await mkdir(join(repoRoot, "packages/desktop/.e2e-artifacts"), { recursive: true });
  17. const root = await mkdtemp(join(repoRoot, "packages/desktop/.e2e-artifacts/shim-build-"));
  18. directories.push(root);
  19. const source = join(root, "packages/desktop/native/windows-preinstalled-entry-shim");
  20. const script = join(root, "packages/desktop/scripts/build-windows-preinstalled-entry-shim.mjs");
  21. for (const path of [
  22. "packages/desktop/scripts/build-windows-preinstalled-entry-shim.mjs",
  23. "packages/desktop/scripts/ensure-e2e-desktop-build.mjs",
  24. "packages/desktop/scripts/e2e-step-process.mjs",
  25. "scripts/spawn-command.mjs",
  26. ]) {
  27. const target = join(root, path);
  28. await mkdir(resolve(target, ".."), { recursive: true });
  29. await copyFile(join(repoRoot, path), target);
  30. }
  31. await mkdir(source, { recursive: true });
  32. await writeFile(join(source, "shim.c"), "fixture-v1");
  33. await writeFile(join(source, "CMakeLists.txt"), "fixture-cmake");
  34. const preload = join(root, "platform.cjs");
  35. // 只替换平台检测;构建脚本、跨进程锁、文件发布和编译子进程都走真实实现。
  36. await writeFile(
  37. preload,
  38. `require("node:os").platform = () => "win32"; require("node:module").syncBuiltinESMExports();`,
  39. );
  40. const compiler = join(root, "fake-cmake.mjs");
  41. await writeFile(
  42. compiler,
  43. `#!/usr/bin/env node
  44. import { mkdir, readFile, writeFile, appendFile } from "node:fs/promises";
  45. import { join } from "node:path";
  46. import { spawn } from "node:child_process";
  47. import { createHash } from "node:crypto";
  48. const args = process.argv.slice(2);
  49. const value = (name) => args[args.indexOf(name) + 1];
  50. const building = args.includes("--build");
  51. await appendFile(process.env.SHIM_BUILD_EVENTS, building ? "build\\n" : "configure\\n");
  52. if (!building) {
  53. await mkdir(value("-B"), { recursive: true });
  54. await writeFile(join(value("-B"), "fixture.json"), JSON.stringify({
  55. source: value("-S"), arch: value("-A"),
  56. output: args.find((arg) => arg.startsWith("-DZCODE_SHIM_OUTPUT_DIR=")).split("=").slice(1).join("=")
  57. }));
  58. } else {
  59. if (process.env.SHIM_BUILD_HANG === "1") {
  60. const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "inherit" });
  61. await writeFile(process.env.SHIM_BUILD_CHILD_PID, String(child.pid));
  62. setInterval(() => {}, 1000);
  63. await new Promise(() => {});
  64. }
  65. if (process.env.SHIM_BUILD_FAIL === "1") process.exit(7);
  66. const config = JSON.parse(await readFile(join(value("--build"), "fixture.json"), "utf8"));
  67. const bytes = Buffer.alloc(4096);
  68. bytes.write("MZ"); bytes.writeUInt32LE(64, 60); bytes.write("PE\\0\\0", 64);
  69. bytes.writeUInt16LE(config.arch === "ARM64" ? 0xaa64 : 0x8664, 68);
  70. createHash("sha256").update(await readFile(join(config.source, "shim.c"))).digest().copy(bytes, 128);
  71. await mkdir(config.output, { recursive: true });
  72. await writeFile(join(config.output, "${shimName}"), bytes);
  73. }
  74. `,
  75. );
  76. await chmod(compiler, 0o755);
  77. let command = compiler;
  78. if (process.platform === "win32") {
  79. command = join(root, "fake-cmake.cmd");
  80. await writeFile(command, `@"${process.execPath}" "${compiler}" %*\r\n`);
  81. }
  82. const events = join(root, "events.log");
  83. const childPid = join(root, "child.pid");
  84. const output = join(root, "packages/desktop/bundled-tools/win32-x64/preinstalled-entry-shim");
  85. const run = (args: string[] = [], env: Record<string, string> = {}) =>
  86. exec(process.execPath, ["--require", preload, script, ...args], {
  87. timeout: 10000,
  88. env: {
  89. ...process.env,
  90. CMAKE: command,
  91. ZCODE_TARGET_ARCH: "x64",
  92. SHIM_BUILD_EVENTS: events,
  93. SHIM_BUILD_CHILD_PID: childPid,
  94. ...env,
  95. },
  96. });
  97. const counts = async () =>
  98. (await readFile(events, "utf8").catch(() => "")).trim().split("\n").filter(Boolean);
  99. return { root, source, output, run, counts, childPid };
  100. }
  101. describe("preinstalled entry shim build lifecycle", () => {
  102. it("reuses matching source, architecture and binary without invoking CMake", async () => {
  103. const f = await fixture();
  104. await f.run(["--ensure"]);
  105. const before = await readFile(join(f.output, shimName));
  106. await f.run(["--ensure"]);
  107. expect(await f.counts()).toEqual(["configure", "build"]);
  108. expect(await readFile(join(f.output, shimName))).toEqual(before);
  109. await writeFile(join(f.output, shimName), "broken");
  110. await expect(f.run(["--check"])).rejects.toThrow();
  111. await f.run(["--ensure"]);
  112. expect(await f.counts()).toHaveLength(4);
  113. });
  114. it("serializes concurrent prepares and leaves each staged copy unchanged after a rebuild", async () => {
  115. const f = await fixture();
  116. const first = join(f.root, "run-a");
  117. const second = join(f.root, "run-b");
  118. await Promise.all([
  119. f.run(["--ensure", "--stage-dir", first]),
  120. f.run(["--ensure", "--stage-dir", second]),
  121. ]);
  122. expect(await f.counts()).toEqual(["configure", "build"]);
  123. const original = await readFile(join(first, shimName));
  124. expect(await readFile(join(second, shimName))).toEqual(original);
  125. await writeFile(join(f.source, "shim.c"), "fixture-v2");
  126. await expect(f.run(["--check"])).rejects.toThrow();
  127. await f.run(["--ensure"]);
  128. expect(await readFile(join(f.output, shimName))).not.toEqual(original);
  129. expect(await readFile(join(first, shimName))).toEqual(original);
  130. expect(await readFile(join(second, shimName))).toEqual(original);
  131. });
  132. it("check-only refuses a missing cache instead of compiling", async () => {
  133. const f = await fixture();
  134. await expect(f.run(["--check"])).rejects.toThrow();
  135. expect(await f.counts()).toEqual([]);
  136. });
  137. it("prepares once in the parent and lets concurrent check-only children stage private files", async () => {
  138. const f = await fixture();
  139. const parent = await f.run(["--ensure"]);
  140. expect(parent.stdout).toContain("[preinstalled-entry-shim] built");
  141. const children = await Promise.all(
  142. ["shard-a", "shard-b"].map((name) => f.run(["--check", "--stage-dir", join(f.root, name)])),
  143. );
  144. expect(
  145. children.every((child) => !child.stdout.includes("[preinstalled-entry-shim] built")),
  146. ).toBe(true);
  147. expect(await f.counts()).toEqual(["configure", "build"]);
  148. expect(await readFile(join(f.root, "shard-a", shimName))).toEqual(
  149. await readFile(join(f.root, "shard-b", shimName)),
  150. );
  151. await writeFile(join(f.source, "shim.c"), "source-changed-after-parent");
  152. await expect(f.run(["--check"])).rejects.toThrow();
  153. expect(await f.counts()).toEqual(["configure", "build"]);
  154. });
  155. it("rejects a manifest for another architecture without changing the cache", async () => {
  156. const f = await fixture();
  157. await f.run(["--ensure"]);
  158. const path = join(f.output, "build.json");
  159. const manifest = JSON.parse(await readFile(path, "utf8"));
  160. await writeFile(path, JSON.stringify({ ...manifest, arch: "arm64" }));
  161. await expect(f.run(["--check"])).rejects.toThrow();
  162. expect(await f.counts()).toEqual(["configure", "build"]);
  163. await f.run(["--ensure"]);
  164. expect(JSON.parse(await readFile(path, "utf8")).arch).toBe("x64");
  165. });
  166. it("kills a timed-out compiler tree, keeps the previous cache and releases the lock", async () => {
  167. const f = await fixture();
  168. await f.run(["--ensure"]);
  169. const previous = await readFile(join(f.output, shimName));
  170. const manifest = await readFile(join(f.output, "build.json"));
  171. await expect(f.run(["--timeout-ms", "800"], { SHIM_BUILD_HANG: "1" })).rejects.toThrow(
  172. /timed out/,
  173. );
  174. const pid = Number(await readFile(f.childPid, "utf8"));
  175. await expect
  176. .poll(() => {
  177. try {
  178. process.kill(pid, 0);
  179. return true;
  180. } catch {
  181. return false;
  182. }
  183. })
  184. .toBe(false);
  185. expect(await readFile(join(f.output, shimName))).toEqual(previous);
  186. expect(await readFile(join(f.output, "build.json"))).toEqual(manifest);
  187. await f.run(["--check"]);
  188. }, 15000);
  189. it("does not publish or change the previous manifest after a compiler failure", async () => {
  190. const f = await fixture();
  191. await f.run(["--ensure"]);
  192. const previous = await readFile(join(f.output, shimName));
  193. const manifest = await readFile(join(f.output, "build.json"));
  194. await expect(f.run([], { SHIM_BUILD_FAIL: "1" })).rejects.toThrow();
  195. expect(await readFile(join(f.output, shimName))).toEqual(previous);
  196. expect(await readFile(join(f.output, "build.json"))).toEqual(manifest);
  197. });
  198. });