e2eSshRemoteReleaseAssets.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import { readFile } from "node:fs/promises";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. ensureSshRemoteReleaseAssets,
  5. resolveSshRemoteReleaseScope,
  6. type SshRemoteReleasePrepareRequest,
  7. } from "./e2e/helpers/e2e-ssh-remote-release-assets.js";
  8. const RELEASE_DIR = "/repo/packages/desktop/mock-cdn/releases/3.12.0";
  9. const DESCRIPTOR_PATH = `${RELEASE_DIR}/source-server-release.json`;
  10. // 与 stage:remote-assets(remoteAssetRelease.ts collectSourceServerRemoteReleaseArchives)
  11. // 的实际产物一致:descriptor 最后原子写入,四个 archive 按 target 命名。
  12. const RELEASE_FILES = [
  13. "source-server-release.json",
  14. "zcode-server-linux-x64.tar.gz",
  15. "zcode-server-linux-arm64.tar.gz",
  16. "zcode-server-darwin-x64.tar.gz",
  17. "zcode-server-darwin-arm64.tar.gz",
  18. ];
  19. function normalize(path: string) {
  20. // join 的分隔符随平台变化,fake IO 统一归一化成 posix 形式保证跨 OS 稳定。
  21. return path.split("\\").join("/");
  22. }
  23. function descriptor(targets: string[]) {
  24. return JSON.stringify({
  25. schemaVersion: 1,
  26. version: "3.12.0",
  27. archives: targets.map((target) => ({
  28. target,
  29. version: "3.12.0",
  30. fileName: `zcode-server-${target}.tar.gz`,
  31. sha256: "a".repeat(64),
  32. sizeBytes: 1024,
  33. urls: [`zcode-server-${target}.tar.gz`],
  34. })),
  35. });
  36. }
  37. /** 发布目录的假实现:exists/readText 读同一份内存文件表,prepare 可以改写它。 */
  38. function createFakeRelease(files: Record<string, string>) {
  39. const table = new Map(
  40. Object.entries(files).map(([name, text]) => [`${RELEASE_DIR}/${name}`, text]),
  41. );
  42. return {
  43. table,
  44. exists: vi.fn(async (path: string) => table.has(normalize(path))),
  45. writeText: vi.fn(async (path: string, text: string) => {
  46. table.set(normalize(path), text);
  47. }),
  48. readText: vi.fn(async (path: string) => {
  49. const text = table.get(normalize(path));
  50. if (text === undefined) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
  51. return text;
  52. }),
  53. };
  54. }
  55. const ALL_TARGETS = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64"];
  56. /** 全平台完整发布:descriptor 登记四个 target,四个 archive 都在。 */
  57. function completeAllRelease(): Record<string, string> {
  58. return {
  59. ...Object.fromEntries(RELEASE_FILES.map((name) => [name, "archive"])),
  60. "source-server-release.json": descriptor(ALL_TARGETS),
  61. };
  62. }
  63. describe("ensureSshRemoteReleaseAssets(默认全平台判断)", () => {
  64. it.each([undefined, "previous-commit", "current-commit"])(
  65. "only reuses complete CI archives built for the current revision (receipt=%s)",
  66. async (receipt) => {
  67. const files = completeAllRelease();
  68. if (receipt) files[".e2e-build-revision"] = receipt;
  69. const fixture = createFakeRelease(files);
  70. const prepareReleaseAssets = vi.fn();
  71. const prepared = await ensureSshRemoteReleaseAssets({
  72. ...fixture,
  73. releaseDir: RELEASE_DIR,
  74. buildRevision: "current-commit",
  75. prepareReleaseAssets,
  76. });
  77. expect(prepared).toBe(receipt !== "current-commit");
  78. expect(prepareReleaseAssets).toHaveBeenCalledTimes(receipt === "current-commit" ? 0 : 1);
  79. expect(fixture.table.get(`${RELEASE_DIR}/.e2e-build-revision`)).toBe("current-commit");
  80. },
  81. );
  82. it("invalidates the old receipt before prepare so a failed build cannot be reused", async () => {
  83. const files = completeAllRelease();
  84. delete files[RELEASE_FILES.at(-1)!];
  85. const fixture = createFakeRelease({ ...files, ".e2e-build-revision": "current-commit" });
  86. const options = { ...fixture, releaseDir: RELEASE_DIR, buildRevision: "current-commit" };
  87. await expect(
  88. ensureSshRemoteReleaseAssets({
  89. ...options,
  90. prepareReleaseAssets: async () => {
  91. fixture.table.set(`${RELEASE_DIR}/${RELEASE_FILES.at(-1)}`, "partial");
  92. throw new Error("build interrupted");
  93. },
  94. }),
  95. ).rejects.toThrow("build interrupted");
  96. expect(fixture.table.get(`${RELEASE_DIR}/.e2e-build-revision`)).toBe("");
  97. const prepareReleaseAssets = vi.fn();
  98. expect(await ensureSshRemoteReleaseAssets({ ...options, prepareReleaseAssets })).toBe(true);
  99. expect(prepareReleaseAssets).toHaveBeenCalledOnce();
  100. expect(fixture.table.get(`${RELEASE_DIR}/.e2e-build-revision`)).toBe("current-commit");
  101. });
  102. it("skips prepare when the descriptor lists all four targets and their archives exist", async () => {
  103. const prepareReleaseAssets = vi.fn();
  104. const prepared = await ensureSshRemoteReleaseAssets({
  105. ...createFakeRelease(completeAllRelease()),
  106. prepareReleaseAssets,
  107. releaseDir: RELEASE_DIR,
  108. });
  109. expect(prepared).toBe(false);
  110. expect(prepareReleaseAssets).not.toHaveBeenCalled();
  111. });
  112. it("does not treat legacy manifest-<platform>.json files as a complete release", async () => {
  113. // Bug 根因:分支把 remote release 切换成 descriptor+archive 布局并删掉了
  114. // scripts/prepare-prebuilds.mjs,但 staging 合入的 helper 仍以四份 manifest 为完成态哨兵,
  115. // 新布局永远判“不完整”;旧布局残留目录也不能再被当成可用 release。
  116. const release = createFakeRelease(
  117. Object.fromEntries(
  118. ["linux-arm64", "linux-x64", "darwin-arm64", "darwin-x64"].map((platform) => [
  119. `manifest-${platform}.json`,
  120. "{}",
  121. ]),
  122. ),
  123. );
  124. const prepareReleaseAssets = vi.fn(() => {
  125. for (const [name, text] of Object.entries(completeAllRelease()))
  126. release.table.set(`${RELEASE_DIR}/${name}`, text);
  127. });
  128. const prepared = await ensureSshRemoteReleaseAssets({
  129. ...release,
  130. prepareReleaseAssets,
  131. releaseDir: RELEASE_DIR,
  132. });
  133. expect(prepared).toBe(true);
  134. expect(prepareReleaseAssets).toHaveBeenCalledOnce();
  135. });
  136. it("re-prepares when the release dir exists but the descriptor is missing", async () => {
  137. // 复查回归(issueId Q-a2867155a0ed0492e7f5):目录存在性判幂等时,prepare 中途取消
  138. // 残留的半成品目录会永久跳过自愈。beginSourceServerRemoteReleaseGeneration 在开始时
  139. // 删除 descriptor、collect 全部完成后才重新写入,因此 descriptor 缺失即为不完整。
  140. const files = completeAllRelease();
  141. delete files["source-server-release.json"];
  142. const release = createFakeRelease(files);
  143. const prepareReleaseAssets = vi.fn(() => {
  144. release.table.set(DESCRIPTOR_PATH, descriptor(ALL_TARGETS));
  145. });
  146. const prepared = await ensureSshRemoteReleaseAssets({
  147. ...release,
  148. prepareReleaseAssets,
  149. releaseDir: RELEASE_DIR,
  150. });
  151. expect(prepared).toBe(true);
  152. expect(prepareReleaseAssets).toHaveBeenCalledOnce();
  153. });
  154. it("runs the full-platform entry without env overrides when nothing is declared", async () => {
  155. // 未声明「只需 Linux」时(服务器队列、CI)保持原行为:调用全平台入口,不改 ZCODE_ENV。
  156. const release = createFakeRelease({});
  157. const prepareReleaseAssets = vi.fn((_request: SshRemoteReleasePrepareRequest) => {
  158. for (const [name, text] of Object.entries(completeAllRelease()))
  159. release.table.set(`${RELEASE_DIR}/${name}`, text);
  160. });
  161. const prepared = await ensureSshRemoteReleaseAssets({
  162. ...release,
  163. prepareReleaseAssets,
  164. releaseDir: RELEASE_DIR,
  165. });
  166. expect(prepared).toBe(true);
  167. expect(prepareReleaseAssets).toHaveBeenCalledExactlyOnceWith({
  168. script: "prepare:remote-assets",
  169. env: {},
  170. args: [],
  171. });
  172. });
  173. it("stays fail-closed and names the missing archives when prepare does not complete", async () => {
  174. const prepareReleaseAssets = vi.fn();
  175. const release = createFakeRelease({
  176. "source-server-release.json": descriptor(ALL_TARGETS),
  177. "zcode-server-linux-x64.tar.gz": "x64",
  178. });
  179. await expect(
  180. ensureSshRemoteReleaseAssets({
  181. ...release,
  182. prepareReleaseAssets,
  183. releaseDir: RELEASE_DIR,
  184. }),
  185. ).rejects.toThrow(
  186. /prepare:remote-assets.*\/releases\/3\.12\.0.*zcode-server-linux-arm64\.tar\.gz, zcode-server-darwin-x64\.tar\.gz, zcode-server-darwin-arm64\.tar\.gz/u,
  187. );
  188. expect(prepareReleaseAssets).toHaveBeenCalledOnce();
  189. });
  190. });
  191. // Bug 根因(!3777 评审 CR-02):Linux 范围重建只替换两个 Linux 目标、descriptor 只登记它们,
  192. // 旧 darwin archive 仍留在同一目录。全平台判断原来只看文件存在,切回 all 时会复用,
  193. // 远端 darwin 安装按 descriptor 查不到目标而在连接阶段失败。两种范围必须按 descriptor 判断。
  194. describe("ensureSshRemoteReleaseAssets(all → linux → all 切换)", () => {
  195. it.each([undefined, "commit-2"])(
  196. "rebuilds the full release after a Linux-only rebuild left stale darwin archives (revision=%s)",
  197. async (buildRevision) => {
  198. const release = createFakeRelease({
  199. ...completeAllRelease(),
  200. ".e2e-build-revision": "commit-1",
  201. });
  202. const publish = (targets: readonly string[]) => () => {
  203. // 与发布器一致:只覆盖本轮目标的 archive,descriptor 只登记本轮目标。
  204. for (const target of targets)
  205. release.table.set(`${RELEASE_DIR}/zcode-server-${target}.tar.gz`, "fresh");
  206. release.table.set(DESCRIPTOR_PATH, descriptor([...targets]));
  207. };
  208. // 1. Linux 范围重建:darwin archive 留在目录里,但 descriptor 不再登记它们。
  209. await ensureSshRemoteReleaseAssets({
  210. ...release,
  211. releaseDir: RELEASE_DIR,
  212. buildRevision: "commit-2",
  213. scope: "linux",
  214. prepareReleaseAssets: publish(["linux-x64", "linux-arm64"]),
  215. });
  216. expect(release.table.has(`${RELEASE_DIR}/zcode-server-darwin-x64.tar.gz`)).toBe(true);
  217. // 2. 切回全平台:即使回执匹配(或本机不传提交),也必须重建。
  218. const prepareAll = vi.fn(publish(ALL_TARGETS));
  219. const prepared = await ensureSshRemoteReleaseAssets({
  220. ...release,
  221. releaseDir: RELEASE_DIR,
  222. buildRevision,
  223. prepareReleaseAssets: prepareAll,
  224. });
  225. expect(prepared).toBe(true);
  226. expect(prepareAll).toHaveBeenCalledOnce();
  227. const finalDescriptor = JSON.parse(release.table.get(DESCRIPTOR_PATH)!) as {
  228. archives: Array<{ target: string }>;
  229. };
  230. expect(finalDescriptor.archives.map((archive) => archive.target).sort()).toEqual(
  231. [...ALL_TARGETS].sort(),
  232. );
  233. },
  234. );
  235. });
  236. // Bug 根因(!3777 评审 CR-01 第二轮):ZCODE_E2E_SKIP_AGENT_BUILD=1 时 onPrepare 不构建 agent,只检查入口
  237. // 存在;打包器若仍跳过首个 target 的 agent 重建,会把工作区里的旧 bundle 打进 archive,再写入当前
  238. // 提交回执,之后同提交运行一直复用这个错版本的包。只有本轮 onPrepare 真实构建过 agent 才能跳过。
  239. describe("ensureSshRemoteReleaseAssets(打包器是否复用本轮 agent)", () => {
  240. it.each([
  241. [true, ["--skip-agent-build"]],
  242. [false, []],
  243. [undefined, []],
  244. ])("agentBundleBuiltThisRun=%s → prepare args %j", async (agentBundleBuiltThisRun, args) => {
  245. const release = createFakeRelease({ ".e2e-build-revision": "commit-0" });
  246. const prepareReleaseAssets = vi.fn((_request: SshRemoteReleasePrepareRequest) => {
  247. for (const [name, text] of Object.entries(completeAllRelease()))
  248. release.table.set(`${RELEASE_DIR}/${name}`, text);
  249. });
  250. await ensureSshRemoteReleaseAssets({
  251. ...release,
  252. releaseDir: RELEASE_DIR,
  253. buildRevision: "commit-1",
  254. agentBundleBuiltThisRun,
  255. prepareReleaseAssets,
  256. });
  257. expect(prepareReleaseAssets).toHaveBeenCalledExactlyOnceWith({
  258. script: "prepare:remote-assets",
  259. env: {},
  260. args,
  261. });
  262. expect(release.table.get(`${RELEASE_DIR}/.e2e-build-revision`)).toBe("commit-1");
  263. });
  264. });
  265. describe("ensureSshRemoteReleaseAssets(声明只需 Linux)", () => {
  266. it("accepts a descriptor that lists only the two Linux targets", async () => {
  267. const release = createFakeRelease({
  268. "source-server-release.json": descriptor(["linux-x64", "linux-arm64"]),
  269. "zcode-server-linux-x64.tar.gz": "x64",
  270. "zcode-server-linux-arm64.tar.gz": "arm64",
  271. });
  272. const prepareReleaseAssets = vi.fn();
  273. const prepared = await ensureSshRemoteReleaseAssets({
  274. ...release,
  275. prepareReleaseAssets,
  276. releaseDir: RELEASE_DIR,
  277. scope: "linux",
  278. });
  279. expect(prepared).toBe(false);
  280. expect(prepareReleaseAssets).not.toHaveBeenCalled();
  281. });
  282. it("rebuilds through the Linux entry with ZCODE_ENV=test, never the full-platform entry", async () => {
  283. // 磁盘上有 Linux 包但 descriptor 只列了 linux-x64:不能凭文件存在就复用。
  284. const release = createFakeRelease({
  285. "source-server-release.json": descriptor(["linux-x64"]),
  286. "zcode-server-linux-x64.tar.gz": "x64",
  287. "zcode-server-linux-arm64.tar.gz": "stale",
  288. });
  289. const prepareReleaseAssets = vi.fn((_request: SshRemoteReleasePrepareRequest) => {
  290. release.table.set(DESCRIPTOR_PATH, descriptor(["linux-x64", "linux-arm64"]));
  291. });
  292. const prepared = await ensureSshRemoteReleaseAssets({
  293. ...release,
  294. prepareReleaseAssets,
  295. releaseDir: RELEASE_DIR,
  296. scope: "linux",
  297. });
  298. expect(prepared).toBe(true);
  299. expect(prepareReleaseAssets).toHaveBeenCalledExactlyOnceWith({
  300. script: "prepare:remote-assets:linux",
  301. env: { ZCODE_ENV: "test" },
  302. args: [],
  303. });
  304. });
  305. it("does not require darwin archives and fails closed when a Linux archive is still missing", async () => {
  306. const release = createFakeRelease({
  307. "source-server-release.json": descriptor(["linux-x64", "linux-arm64"]),
  308. "zcode-server-linux-x64.tar.gz": "x64",
  309. });
  310. const prepareReleaseAssets = vi.fn();
  311. await expect(
  312. ensureSshRemoteReleaseAssets({
  313. ...release,
  314. prepareReleaseAssets,
  315. releaseDir: RELEASE_DIR,
  316. scope: "linux",
  317. }),
  318. ).rejects.toThrow(/prepare:remote-assets:linux.*zcode-server-linux-arm64\.tar\.gz/u);
  319. expect(prepareReleaseAssets).toHaveBeenCalledOnce();
  320. expect(prepareReleaseAssets.mock.calls[0]?.[0]?.script).toBe("prepare:remote-assets:linux");
  321. });
  322. it("treats an unreadable descriptor as incomplete", async () => {
  323. const release = createFakeRelease({
  324. "source-server-release.json": "{not json",
  325. "zcode-server-linux-x64.tar.gz": "x64",
  326. "zcode-server-linux-arm64.tar.gz": "arm64",
  327. });
  328. const prepareReleaseAssets = vi.fn(() => {
  329. release.table.set(DESCRIPTOR_PATH, descriptor(["linux-x64", "linux-arm64"]));
  330. });
  331. expect(
  332. await ensureSshRemoteReleaseAssets({
  333. ...release,
  334. prepareReleaseAssets,
  335. releaseDir: RELEASE_DIR,
  336. scope: "linux",
  337. }),
  338. ).toBe(true);
  339. });
  340. });
  341. describe("resolveSshRemoteReleaseScope", () => {
  342. it("defaults to all and only switches to linux on the explicit declaration", () => {
  343. expect(resolveSshRemoteReleaseScope({})).toBe("all");
  344. expect(resolveSshRemoteReleaseScope({ ZCODE_E2E_REMOTE_RELEASE_SCOPE: " " })).toBe("all");
  345. expect(resolveSshRemoteReleaseScope({ ZCODE_E2E_REMOTE_RELEASE_SCOPE: "linux" })).toBe("linux");
  346. expect(() =>
  347. resolveSshRemoteReleaseScope({ ZCODE_E2E_REMOTE_RELEASE_SCOPE: "darwin" }),
  348. ).toThrow(/ZCODE_E2E_REMOTE_RELEASE_SCOPE/u);
  349. });
  350. });
  351. describe("wdio.conf.ts SSH remote assets wiring", () => {
  352. it("auto-prepares missing remote release assets via the root workspace scripts", async () => {
  353. const source = await readFile(new URL("../wdio.conf.ts", import.meta.url), "utf8");
  354. const stageDesktopE2EAppOutput = source.slice(
  355. source.indexOf("async function prepareSshRemoteReleaseForRun("),
  356. source.indexOf("function isRendererE2EStoreBridgeCompiled"),
  357. );
  358. // Bug 根因:版本 bump 后专用 e2e runner 的工作区 mock-cdn 必然缺新版本 release,
  359. // 直接 fatal 会把每次版本升级都变成 CI-only 失败;必须先自动 prepare 再 fail-closed。
  360. expect(stageDesktopE2EAppOutput).toContain("await ensureSshRemoteReleaseAssets(");
  361. expect(stageDesktopE2EAppOutput).not.toContain("SSH remote assets missing");
  362. // 「只需 Linux」声明来自本机 Docker runner 的环境变量;未声明时 helper 返回全平台入口。
  363. expect(stageDesktopE2EAppOutput).toContain("resolveSshRemoteReleaseScope(process.env)");
  364. expect(stageDesktopE2EAppOutput).toContain("buildRevision: process.env.CI_COMMIT_SHA");
  365. // Bug 根因:packages/desktop 的 prepare:remote-assets 脚本已随 legacy asset pipeline 删除,
  366. // `pnpm --filter @zcode/desktop prepare:remote-assets` 会以 ERR_PNPM_RECURSIVE_RUN_NO_SCRIPT
  367. // 失败并让 onPrepare fatal;唯一有效入口是根 package.json 的脚本(helper 给出脚本名)。
  368. // 是否跳过打包器的 agent 构建由 helper 按“本轮 onPrepare 是否真实构建”决定,调用点只透传参数。
  369. expect(stageDesktopE2EAppOutput).toMatch(
  370. /runPnpmWorkspaceCommand\(\[request\.script, \.\.\.request\.args\]/u,
  371. );
  372. expect(stageDesktopE2EAppOutput).not.toContain('"--skip-agent-build"');
  373. expect(stageDesktopE2EAppOutput).toContain("agentBundleBuiltThisRun");
  374. expect(stageDesktopE2EAppOutput).not.toMatch(/@zcode\/desktop",\s*"prepare:remote-assets/u);
  375. // prepare 调用点必须带 timeoutMs:CI 上下载/构建挂死时让 onPrepare 可失败退出,
  376. // 而不是占住专用 runner 直到 job 全局超时。(本片段内仅 prepare 一处 pnpm 调用。)
  377. expect(stageDesktopE2EAppOutput).toContain("timeoutMs: ");
  378. expect(stageDesktopE2EAppOutput).toContain("env: request.env");
  379. });
  380. it("prepares the remote release only for scheduled specs that need it, after the single agent build", async () => {
  381. const source = await readFile(new URL("../wdio.conf.ts", import.meta.url), "utf8");
  382. const prepareRemote = source.slice(
  383. source.indexOf("async function prepareSshRemoteReleaseForRun("),
  384. source.indexOf("function isRendererE2EStoreBridgeCompiled"),
  385. );
  386. const appStage = source.slice(
  387. source.indexOf("async function stageDesktopE2EAppOutput()"),
  388. source.indexOf("async function prepareSshRemoteReleaseForRun("),
  389. );
  390. const onPrepare = source.slice(
  391. source.indexOf(" async onPrepare() {"),
  392. source.indexOf(" onWorkerStart(cid"),
  393. );
  394. // 判据是本轮调度 spec 的 import 关系,而不是 runner 是否配置了 SSH 环境变量。
  395. expect(prepareRemote).toContain("listSpecsRequiringRemoteRelease(");
  396. expect(prepareRemote).toContain("resolveE2EScheduledSpecFiles(");
  397. // worker 兜底读取的目录只能由 onPrepare 在 stage 后经 runnerEnv 下发。
  398. expect(prepareRemote).toContain("[REMOTE_RELEASE_DIR_ENV]: E2E_REMOTE_RELEASE_OUTPUT_DIR");
  399. expect(prepareRemote).toContain("withE2EDesktopBuildLock(");
  400. expect(appStage).not.toContain("ensureSshRemoteReleaseAssets(");
  401. // 子步骤计时,agent 先于 remote release 构建且只构建一次。
  402. for (const phase of [
  403. '"prepare:desktop-build"',
  404. '"prepare:agent-build"',
  405. '"prepare:remote-release"',
  406. '"prepare:plugin-cache"',
  407. ])
  408. expect(source).toContain(phase);
  409. expect(onPrepare.indexOf("prepareZCodeAgentServer()")).toBeGreaterThan(-1);
  410. expect(onPrepare.indexOf("prepareZCodeAgentServer()")).toBeLessThan(
  411. onPrepare.indexOf("prepareSshRemoteReleaseForRun("),
  412. );
  413. });
  414. });