preinstalled-tools-fixture.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. import { execFile } from "node:child_process";
  2. import { createServer, type ServerResponse } from "node:http";
  3. import { createHash } from "node:crypto";
  4. import { chmod, mkdir, mkdtemp, readFile, stat, writeFile, symlink } from "node:fs/promises";
  5. import { join } from "node:path";
  6. import { promisify } from "node:util";
  7. import { create as createTar } from "tar";
  8. import { preinstalledToolsCatalogSchema } from "@zcode/shared/preinstalled-tools";
  9. const isWindows = process.platform === "win32";
  10. /** 普通 E2E 显式保留工具卡片但移除资源,避免启动时下载正式 CDN 的大包。 */
  11. export async function writeEmptyPreinstalledToolsCatalog(directory: string): Promise<string> {
  12. const catalog = preinstalledToolsCatalogSchema.parse(
  13. JSON.parse(
  14. await readFile(
  15. new URL("../../../src/preinstalled-tools/catalog.json", import.meta.url),
  16. "utf8",
  17. ),
  18. ),
  19. );
  20. await mkdir(directory, { recursive: true });
  21. const path = join(directory, "empty-catalog.json");
  22. await writeFile(
  23. path,
  24. JSON.stringify(
  25. catalog.map(({ toolId, displayName }) => ({ toolId, displayName, resources: [] })),
  26. ),
  27. );
  28. return path;
  29. }
  30. /** 夹具程序本体在资源内的相对路径;Windows 没有 sh,由 Node 脚本承担同样的断言与输出。 */
  31. export const PREINSTALLED_FIXTURE_PROGRAM = isWindows ? "bin/office.mjs" : "bin/office";
  32. /** 入口目标随平台变化:POSIX 是指向程序本体的符号链接,Windows 是一行 .cmd。 */
  33. export function preinstalledFixtureTarget(toolId: string): string {
  34. const command = toolId === "libreoffice" ? "soffice" : toolId;
  35. return isWindows ? `bin/${command}.cmd` : `bin/${command}`;
  36. }
  37. /** Windows 入口目标:用 %~dp0 定位脚本、%~f0 报告自身路径,文件内容不含安装目录。 */
  38. export function preinstalledFixtureWindowsLauncher(): string {
  39. return `@"${process.execPath}" "%~dp0office.mjs" "%~f0" %*\r\n`;
  40. }
  41. /** Windows 夹具程序:与 POSIX sh 脚本相同的断言顺序、退出码和输出流。 */
  42. export function preinstalledFixtureWindowsProgram(
  43. runtimeCheckUrl: string,
  44. options: { assertEntryContract?: boolean; failAfterCheck?: boolean; outputToStderr?: boolean },
  45. ): string {
  46. return `import { stat } from "node:fs/promises";
  47. const [self, ...args] = process.argv.slice(2);
  48. ${
  49. options.assertEntryContract
  50. ? `if (args[0] !== \`--install=\${process.env.FIXTURE_INSTALL_DIR}\`) process.exit(2);
  51. if (args[1]?.startsWith("--temp=")) {
  52. const temporary = await stat(args[1].slice("--temp=".length)).catch(() => null);
  53. if (!temporary?.isDirectory()) process.exit(3);
  54. }
  55. if (process.env.FIXTURE_DEFAULT !== "fixture-default") process.exit(4);
  56. `
  57. : ""
  58. }if (args.includes("--fixture-location")) {
  59. console.log(self);
  60. process.exit(0);
  61. }
  62. const response = await fetch(${JSON.stringify(runtimeCheckUrl)});
  63. if (!response.ok) process.exit(22);
  64. process.${options.outputToStderr ? "stderr" : "stdout"}.write(await response.text());
  65. ${options.failAfterCheck ? "process.exitCode = 1;\n" : ""}`;
  66. }
  67. /** 公开入口的可执行文件:Windows 上是 shim 副本 <name>.exe,其他平台是 sh 脚本。 */
  68. export function preinstalledEntryPath(binDir: string, name: string): string {
  69. return join(binDir, isWindows ? `${name}.exe` : name);
  70. }
  71. /**
  72. * 入口指向的目标、参数和环境值,用于断言入口指向哪个版本。
  73. * Windows 上读 shim 配置并解码 JSON,避免路径中的反斜杠被转义后断言落空。
  74. */
  75. export async function readPreinstalledEntryDefinition(
  76. binDir: string,
  77. name: string,
  78. ): Promise<string> {
  79. if (!isWindows) return readFile(join(binDir, name), "utf8");
  80. const config = JSON.parse(await readFile(join(binDir, `${name}.shim`), "utf8")) as {
  81. target: string;
  82. args: string[];
  83. env: { value?: string }[];
  84. };
  85. return [config.target, ...config.args, ...config.env.map((item) => item.value ?? "")].join("\n");
  86. }
  87. /** 从测试进程调用公开入口;Windows 上 shim 是普通可执行文件,与 POSIX 同样直接运行。 */
  88. export async function executePreinstalledEntry(
  89. binDir: string,
  90. name: string,
  91. args: readonly string[],
  92. ): Promise<{ stdout: string; stderr: string }> {
  93. return promisify(execFile)(preinstalledEntryPath(binDir, name), [...args], {
  94. windowsHide: true,
  95. });
  96. }
  97. const lockedDirectoryModes = new Map<string, number>();
  98. /**
  99. * 让目录可读不可写,制造真实的写入失败。Windows 的 chmod 限制不了目录写入,
  100. * 这里对当前用户加拒绝项(新建、写入、删除子项),解锁时只移除拒绝项。
  101. */
  102. export async function lockPreinstalledDirectory(directory: string): Promise<void> {
  103. if (!isWindows) {
  104. lockedDirectoryModes.set(directory, (await stat(directory)).mode);
  105. await chmod(directory, 0o500);
  106. return;
  107. }
  108. await promisify(execFile)(
  109. "icacls",
  110. [directory, "/deny", `${process.env.USERNAME}:(OI)(CI)(WD,AD,DC,DE)`],
  111. { windowsHide: true },
  112. );
  113. }
  114. export async function unlockPreinstalledDirectory(directory: string): Promise<void> {
  115. if (!isWindows) {
  116. await chmod(directory, lockedDirectoryModes.get(directory)!);
  117. return;
  118. }
  119. await promisify(execFile)("icacls", [directory, "/remove:d", process.env.USERNAME!], {
  120. windowsHide: true,
  121. });
  122. }
  123. /** 固定发布点与资源版本无关;测试不从已发布记录反推当前目标。 */
  124. export async function preinstalledFixtureRecordPath(
  125. releaseRoot: string,
  126. toolId = "libreoffice",
  127. ): Promise<string> {
  128. return join(releaseRoot, "tools", toolId, "installation.json");
  129. }
  130. /** 每个工具有独立 HTTP 屏障,测试显式放行而非用延时猜测串行顺序。 */
  131. export async function startPreinstalledToolsFixture(
  132. artifactDirectory: string,
  133. toolIds = ["libreoffice"],
  134. ) {
  135. await mkdir(artifactDirectory, { recursive: true });
  136. const directory = await mkdtemp(join(artifactDirectory, "session-"));
  137. const tools = new Map(
  138. toolIds.map((toolId) => [
  139. toolId,
  140. {
  141. bytes: Buffer.alloc(0),
  142. pending: new Set<ServerResponse>(),
  143. downloads: new Map<number, ServerResponse>(),
  144. checking: new Set<ServerResponse>(),
  145. requests: 0,
  146. runtimeChecks: 0,
  147. lateWrites: 0,
  148. released: false,
  149. checkReleased: false,
  150. },
  151. ]),
  152. );
  153. const events: Array<{ path: string | undefined; toolId?: string; at: string }> = [];
  154. const snapshot = () => {
  155. const states = [...tools].map(
  156. ([toolId, tool]) =>
  157. [
  158. toolId,
  159. {
  160. requests: tool.requests,
  161. pending: tool.pending.size,
  162. runtimeChecks: tool.runtimeChecks,
  163. lateWrites: tool.lateWrites,
  164. },
  165. ] as const,
  166. );
  167. return {
  168. requests: states.reduce((sum, [, tool]) => sum + tool.requests, 0),
  169. pending: states.reduce((sum, [, tool]) => sum + tool.pending, 0),
  170. runtimeChecks: states.reduce((sum, [, tool]) => sum + tool.runtimeChecks, 0),
  171. lateWrites: states.reduce((sum, [, tool]) => sum + tool.lateWrites, 0),
  172. tools: Object.fromEntries(states),
  173. };
  174. };
  175. const server = createServer((req, res) => {
  176. const segments = (req.url ?? "").split("/").filter(Boolean);
  177. const toolId = tools.has(segments[0] ?? "") ? segments.shift()! : "libreoffice";
  178. const path = `/${segments.join("/")}`;
  179. const tool = tools.get(toolId);
  180. events.push({ path: req.url, toolId, at: new Date().toISOString() });
  181. if (path === "/status") {
  182. res.setHeader("content-type", "application/json");
  183. res.end(JSON.stringify(snapshot()));
  184. return;
  185. }
  186. if (!tool) {
  187. res.writeHead(404).end();
  188. return;
  189. }
  190. const output = toolId === "libreoffice" ? "LibreOffice 26.8.1\n" : `${toolId} fixture\n`;
  191. if (path === "/archive") {
  192. tool.requests += 1;
  193. tool.downloads.set(tool.requests, res);
  194. res.writeHead(200, { "content-length": tool.bytes.length });
  195. if (tool.released) res.end(tool.bytes);
  196. else {
  197. res.write(tool.bytes.subarray(0, Math.floor(tool.bytes.length / 2)));
  198. tool.pending.add(res);
  199. res.once("close", () => tool.pending.delete(res));
  200. }
  201. } else if (path.startsWith("/release-request/") || path.startsWith("/break-request/")) {
  202. const response = tool.downloads.get(Number(segments.at(-1)));
  203. if (!response) {
  204. res.writeHead(404).end();
  205. return;
  206. }
  207. if (path.startsWith("/break-request/")) response.destroy();
  208. else {
  209. if (response.destroyed) tool.lateWrites += 1;
  210. response.end(tool.bytes.subarray(Math.floor(tool.bytes.length / 2)));
  211. }
  212. tool.pending.delete(response);
  213. res.end("settled-one");
  214. } else if (path === "/release") {
  215. tool.released = true;
  216. for (const response of tool.pending)
  217. response.end(tool.bytes.subarray(Math.floor(tool.bytes.length / 2)));
  218. tool.pending.clear();
  219. res.end("released");
  220. } else if (path === "/runtime-check") {
  221. tool.runtimeChecks += 1;
  222. if (tool.checkReleased) res.end(output);
  223. else {
  224. tool.checking.add(res);
  225. res.once("close", () => tool.checking.delete(res));
  226. }
  227. } else if (path === "/finish-check") {
  228. tool.checkReleased = true;
  229. for (const response of tool.checking) response.end(output);
  230. tool.checking.clear();
  231. res.end("checked");
  232. } else if (path === "/hold-check") {
  233. tool.checkReleased = false;
  234. res.end("holding-check");
  235. } else if (path === "/hold") {
  236. tool.released = false;
  237. res.end("holding");
  238. } else res.writeHead(404).end();
  239. });
  240. await new Promise<void>((resolve, reject) => {
  241. server.once("error", reject);
  242. server.listen(0, "127.0.0.1", resolve);
  243. });
  244. const address = server.address();
  245. if (!address || typeof address === "string") throw new Error("fixture address missing");
  246. const url = `http://127.0.0.1:${address.port}`;
  247. const catalog = [];
  248. for (const [toolId, tool] of tools) {
  249. const payload = join(directory, toolId, "payload");
  250. await mkdir(join(payload, "bin"), { recursive: true });
  251. const target = preinstalledFixtureTarget(toolId);
  252. if (isWindows) {
  253. await writeFile(
  254. join(payload, PREINSTALLED_FIXTURE_PROGRAM),
  255. preinstalledFixtureWindowsProgram(`${url}/${toolId}/runtime-check`, {
  256. assertEntryContract: toolId === "qpdf",
  257. outputToStderr: toolId === "qpdf",
  258. }),
  259. );
  260. await writeFile(join(payload, target), preinstalledFixtureWindowsLauncher());
  261. } else {
  262. const assertions =
  263. toolId === "qpdf"
  264. ? 'test "$1" = "--install=$FIXTURE_INSTALL_DIR" || exit 2\ncase "$2" in --temp=*) [ -d "${2#--temp=}" ] || exit 3;; esac\ntest "$FIXTURE_DEFAULT" = "fixture-default" || exit 4\n'
  265. : "";
  266. await writeFile(
  267. join(payload, PREINSTALLED_FIXTURE_PROGRAM),
  268. `#!/bin/sh\n${assertions}for argument in "$@"; do\n if [ "$argument" = "--fixture-location" ]; then printf '%s\\n' "$0"; exit 0; fi\ndone\nexec /usr/bin/curl --silent --show-error --fail --noproxy '*' '${url}/${toolId}/runtime-check'${toolId === "qpdf" ? " >&2" : ""}\n`,
  269. { mode: 0o755 },
  270. );
  271. await symlink("office", join(payload, target));
  272. }
  273. const archive = join(directory, toolId, "fixture.tar.gz");
  274. await createTar({ gzip: true, portable: true, cwd: payload, file: archive }, ["bin"]);
  275. tool.bytes = await readFile(archive);
  276. const entryName = toolId === "libreoffice" ? "zcode-soffice" : toolId;
  277. catalog.push({
  278. toolId,
  279. displayName: toolId === "libreoffice" ? "LibreOffice" : toolId,
  280. resources: [
  281. {
  282. toolId,
  283. resourceId: `fixture-${toolId}-26.8.1-${process.platform}-${process.arch}`,
  284. version: "26.8.1",
  285. platforms: [{ platform: process.platform, arch: process.arch }],
  286. binaryArch: process.arch,
  287. archive: {
  288. format: "tar.gz",
  289. sizeBytes: tool.bytes.length,
  290. sha256: createHash("sha256").update(tool.bytes).digest("hex"),
  291. path: `${toolId}/archive`,
  292. },
  293. installedSizeBytes: 8192,
  294. requiredFiles: [target, PREINSTALLED_FIXTURE_PROGRAM],
  295. entries: [
  296. {
  297. name: entryName,
  298. target,
  299. args: toolId === "qpdf" ? ["--install=${INSTALL_DIR}"] : [],
  300. env:
  301. toolId === "qpdf"
  302. ? [
  303. { name: "FIXTURE_INSTALL_DIR", action: "set", value: "${INSTALL_DIR}" },
  304. { name: "FIXTURE_DEFAULT", action: "default", value: "fixture-default" },
  305. { name: "FIXTURE_UNUSED", action: "unset" },
  306. ]
  307. : [],
  308. },
  309. ],
  310. runtimeChecks: Array.from({ length: toolId === "qpdf" ? 2 : 1 }, () => ({
  311. entry: entryName,
  312. args: toolId === "qpdf" ? ["--temp=${CHECK_TEMP_DIR}"] : ["--version"],
  313. expectedOutput: toolId === "libreoffice" ? "LibreOffice 26.8.1" : `${toolId} fixture`,
  314. timeoutMs: 60000,
  315. })),
  316. },
  317. ],
  318. });
  319. }
  320. const catalogPath = join(directory, "catalog.json");
  321. await writeFile(catalogPath, JSON.stringify(catalog));
  322. return {
  323. url,
  324. // App 只按这个基址拼接 catalog 的 archive.path,与正式 CDN 走同一条装配规则。
  325. cdnBaseUrl: url,
  326. catalogPath,
  327. stop: async () => {
  328. await writeFile(
  329. join(directory, "http-events.json"),
  330. JSON.stringify({ events, ...snapshot() }, null, 2),
  331. );
  332. for (const tool of tools.values())
  333. for (const response of [...tool.pending, ...tool.checking]) response.destroy();
  334. server.closeAllConnections();
  335. await new Promise<void>((resolve, reject) =>
  336. server.close((error) => (error ? reject(error) : resolve())),
  337. );
  338. },
  339. };
  340. }