remoteAssetInstaller.test.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. import { execFile, spawn } from "node:child_process";
  2. import { promisify } from "node:util";
  3. import { existsSync } from "node:fs";
  4. import { access, mkdtemp, mkdir, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises";
  5. import { createHash } from "node:crypto";
  6. import { tmpdir } from "node:os";
  7. import { join } from "node:path";
  8. import { pathToFileURL } from "node:url";
  9. import { PassThrough } from "node:stream";
  10. import type { IDisposable, Event } from "@zcode/rpc";
  11. import type {
  12. IRemoteBackend,
  13. RemoteUploadOptions,
  14. StdioStream,
  15. } from "@zcode/server/remote/backend.js";
  16. import { ZCODE_VERSION } from "@zcode/shared";
  17. import { describe, expect, it, vi } from "vitest";
  18. import {
  19. LocalUploadAssetInstaller,
  20. RemoteDownloadAssetInstaller,
  21. buildRemoteArtifactDownloadCommand,
  22. buildRemoteChecksumCommand,
  23. } from "@zcode/server/remote/remoteAssetInstaller.js";
  24. import type { RemoteSha256Tool } from "@zcode/server/remote/remoteAssetPreflight.js";
  25. import { createTarGzArchive, extractTarGzArchive } from "@zcode/server/remote/localTarGz.js";
  26. import { quotePosixShellArg } from "@zcode/server/remote/posixShell.js";
  27. const execFileAsync = promisify(execFile);
  28. const localShellCommand = resolveLocalShellCommand();
  29. const shellBackedIt = localShellCommand ? it : it.skip;
  30. class InstallerBackend implements IRemoteBackend {
  31. readonly commands: string[] = [];
  32. readonly uploads: Array<{
  33. content: Buffer;
  34. remotePath: string;
  35. signal?: AbortSignal;
  36. }> = [];
  37. constructor(
  38. private readonly stdoutLines: string[] = [],
  39. private readonly existingPaths = new Set<string>(),
  40. ) {}
  41. dispose(): void {}
  42. async detect() {
  43. return { platform: "linux", arch: "x64" };
  44. }
  45. async upload(
  46. localPath: string,
  47. remotePath: string,
  48. options?: RemoteUploadOptions,
  49. ): Promise<void> {
  50. this.uploads.push({
  51. content: await readFile(localPath),
  52. remotePath,
  53. ...(options?.signal ? { signal: options.signal } : {}),
  54. });
  55. }
  56. async exists(remotePath: string): Promise<boolean> {
  57. return this.existingPaths.has(remotePath);
  58. }
  59. async readFile(): Promise<string> {
  60. throw new Error("readFile should not be called in installer tests");
  61. }
  62. async exec(command: string): Promise<StdioStream> {
  63. this.commands.push(command);
  64. return createClosedStream(this.stdoutLines);
  65. }
  66. }
  67. class FailingReplaceBackend extends InstallerBackend {
  68. override async exec(command: string): Promise<StdioStream> {
  69. this.commands.push(command);
  70. return createClosedStream(
  71. [],
  72. command.includes("command chmod +x") ? 1 : 0,
  73. command.includes("command chmod +x") ? "chmod denied" : "",
  74. );
  75. }
  76. }
  77. class ShellInstallerBackend extends InstallerBackend {
  78. constructor(
  79. private readonly rootDir: string,
  80. public prelude: string,
  81. ) {
  82. super();
  83. }
  84. override async exists(remotePath: string): Promise<boolean> {
  85. return access(join(this.rootDir, remotePath.replace(/^~\//u, ""))).then(
  86. () => true,
  87. () => false,
  88. );
  89. }
  90. override async exec(command: string): Promise<StdioStream> {
  91. this.commands.push(command);
  92. // 仅把远端 HOME 路径映射到夹具目录,不改宿主环境;执行完整真实脚本以捕获 shell 退出码。
  93. const isolatedCommand = command.replaceAll(
  94. '"$HOME"',
  95. quotePosixShellArg(toLocalShellPath(this.rootDir)),
  96. );
  97. const child = spawn(localShellCommand!, ["-c", `${this.prelude}\n${isolatedCommand}`], {
  98. detached: process.platform !== "win32",
  99. });
  100. let stdout = "";
  101. let stderr = "";
  102. child.stdout.on("data", (chunk: Buffer) => {
  103. stdout += chunk.toString();
  104. });
  105. child.stderr.on("data", (chunk: Buffer) => {
  106. stderr += chunk.toString();
  107. });
  108. // macOS sh 的后台子进程可能在主命令退出后仍持有管道;退出码已确定后回收测试进程组。
  109. child.once("exit", () => {
  110. if (process.platform === "win32" || !child.pid) return;
  111. try {
  112. process.kill(-child.pid, "SIGKILL");
  113. } catch (error) {
  114. if (!(error instanceof Error) || !("code" in error) || error.code !== "ESRCH") throw error;
  115. }
  116. });
  117. const code = await new Promise<number>((resolve, reject) => {
  118. child.once("error", reject);
  119. child.once("close", (exitCode) => resolve(exitCode ?? 1));
  120. });
  121. return createClosedStream([stdout], code, stderr);
  122. }
  123. }
  124. function createClosedStream(
  125. stdoutLines: string[] = [],
  126. exitCode = 0,
  127. stderrText = "",
  128. ): StdioStream {
  129. const stdin = new PassThrough();
  130. const stdout = new PassThrough();
  131. const stderr = new PassThrough();
  132. const closeListeners: Array<(code: number) => void> = [];
  133. let closeScheduled = false;
  134. const onClose: Event<number> = (listener: (code: number) => void): IDisposable => {
  135. closeListeners.push(listener);
  136. if (!closeScheduled) {
  137. closeScheduled = true;
  138. queueMicrotask(() => {
  139. for (const line of stdoutLines) {
  140. stdout.write(`${line}\n`);
  141. }
  142. if (stderrText) {
  143. stderr.write(`${stderrText}\n`);
  144. }
  145. stdout.end();
  146. stderr.end();
  147. for (const closeListener of closeListeners) {
  148. closeListener(exitCode);
  149. }
  150. });
  151. }
  152. return { dispose() {} };
  153. };
  154. return { stdin, stdout, stderr, onClose };
  155. }
  156. function stubManifestFetch(manifest: unknown): void {
  157. vi.stubGlobal(
  158. "fetch",
  159. vi.fn(async () => new Response(JSON.stringify(manifest), { status: 200 })),
  160. );
  161. }
  162. function stubManifestAndHeadFetch(manifest: unknown, contentLength: number): void {
  163. vi.stubGlobal(
  164. "fetch",
  165. vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
  166. if (init?.method === "HEAD") {
  167. return new Response(null, {
  168. status: 200,
  169. headers: { "content-length": String(contentLength) },
  170. });
  171. }
  172. return new Response(JSON.stringify(manifest), { status: 200 });
  173. }),
  174. );
  175. }
  176. const validManifest = {
  177. schemaVersion: 1,
  178. appVersion: ZCODE_VERSION,
  179. platformArch: "linux-x64",
  180. components: [
  181. {
  182. id: "server-bundle",
  183. version: "1.0.0-server-bundle",
  184. sha256: "a".repeat(64),
  185. artifactPath: "components/linux-x64/server-bundle.tar.gz",
  186. mount: "server",
  187. },
  188. ],
  189. };
  190. function hashRemoteCacheSegment(value: string): string {
  191. return createHash("sha256").update(value).digest("hex").slice(0, 16);
  192. }
  193. function resolveLocalShellCommand(): string | null {
  194. if (process.platform !== "win32") {
  195. return "sh";
  196. }
  197. const gitShellCandidates = [
  198. join(process.env.ProgramFiles ?? "C:\\Program Files", "Git", "bin", "sh.exe"),
  199. join(process.env.ProgramFiles ?? "C:\\Program Files", "Git", "usr", "bin", "sh.exe"),
  200. ];
  201. return gitShellCandidates.find((candidate) => existsSync(candidate)) ?? null;
  202. }
  203. function toLocalShellPath(filePath: string): string {
  204. if (process.platform !== "win32") {
  205. return filePath;
  206. }
  207. // Bugfix: Git Bash 的 sha256sum 读取 C:\... 这类反斜杠路径时,会为了转义文件名在校验值前输出反斜杠,
  208. // 导致测试误判为 sha mismatch。远端真实路径是 POSIX 风格,这里把 Windows 临时路径转成 /c/... 来贴近远端形态。
  209. const normalized = filePath.replaceAll("\\", "/");
  210. return normalized.replace(
  211. /^([A-Za-z]):\//u,
  212. (_match, drive: string) => `/${drive.toLowerCase()}/`,
  213. );
  214. }
  215. async function detectLocalShellSha256Tool(shellCommand: string): Promise<RemoteSha256Tool> {
  216. // Bugfix: Windows Git Bash 环境常有 sha256sum/openssl 但没有 shasum;测试硬编码 shasum
  217. // 会让“备用 URL 校验失败后重试”的用例在真正执行到重试逻辑前就失败。
  218. const { stdout } = await execFileAsync(shellCommand, [
  219. "-c",
  220. "if command -v sha256sum >/dev/null 2>&1; then printf sha256sum; elif command -v shasum >/dev/null 2>&1; then printf shasum; elif command -v openssl >/dev/null 2>&1; then printf openssl; else exit 1; fi",
  221. ]);
  222. const tool = stdout.trim();
  223. if (tool === "sha256sum" || tool === "shasum" || tool === "openssl") {
  224. return tool;
  225. }
  226. throw new Error(`unsupported local sha256 tool: ${tool}`);
  227. }
  228. describe("remote asset installer command builders", () => {
  229. it("quotes remote paths and URLs in download commands", () => {
  230. const command = buildRemoteArtifactDownloadCommand({
  231. tool: "curl",
  232. urls: ["https://cdn.example.test/a b/component.tar.gz"],
  233. outputPath: "~/.zcode/server/asset-cache/staging/a b/component.tar.gz",
  234. progressLabel: "server-bundle@1.0.0-server-bundle",
  235. });
  236. expect(command).toContain("curl");
  237. expect(command).toContain("'https://cdn.example.test/a b/component.tar.gz'");
  238. expect(command).toContain("\"$HOME\"'/.zcode/server/asset-cache/staging/a b/component.tar.gz'");
  239. });
  240. it("emits remote download progress lines while downloading artifacts", () => {
  241. const command = buildRemoteArtifactDownloadCommand({
  242. tool: "wget",
  243. urls: ["https://cdn.example.test/component.tar.gz"],
  244. outputPath: "~/.zcode/server/asset-cache/staging/component.tar.gz",
  245. progressLabel: "server-bundle@1.0.0-server-bundle",
  246. });
  247. expect(command).toContain("download progress: [%s]");
  248. expect(command).toContain("label='server-bundle@1.0.0-server-bundle'");
  249. expect(command).toContain("total unknown");
  250. expect(command).toContain("progress_pid=");
  251. expect(command).toContain('kill "$progress_pid"');
  252. });
  253. it("emits remote download percent when artifact size is known", () => {
  254. const command = buildRemoteArtifactDownloadCommand({
  255. tool: "wget",
  256. urls: ["https://cdn.example.test/component.tar.gz"],
  257. outputPath: "~/.zcode/server/asset-cache/staging/component.tar.gz",
  258. progressLabel: "server-bundle@1.0.0-server-bundle",
  259. totalBytes: 2 * 1024 * 1024,
  260. });
  261. expect(command).toContain("total=2097152");
  262. expect(command).toContain("download progress: [%s] %.1f%%");
  263. expect(command).toContain("%.1f/%.1f MB");
  264. expect(command).not.toContain("total unknown");
  265. });
  266. it("downloads without optional progress tools on minimal remote hosts", () => {
  267. const command = buildRemoteArtifactDownloadCommand({
  268. tool: "curl",
  269. urls: ["https://cdn.example.test/component.tar.gz"],
  270. outputPath: "~/.zcode/server/component.tar.gz",
  271. progressLabel: "source-server-linux-x64",
  272. supportsProgress: false,
  273. });
  274. expect(command).toContain("curl -fL");
  275. expect(command).not.toContain("progress_pid=");
  276. expect(command).not.toContain("awk ");
  277. expect(command).not.toContain("wc -c");
  278. expect(command).not.toContain("date +%s");
  279. });
  280. shellBackedIt(
  281. "tries the next artifact URL when a downloaded candidate fails sha256 validation",
  282. async () => {
  283. const shellCommand = localShellCommand ?? "sh";
  284. const dir = await mkdtemp(join(tmpdir(), "zcode-installer-download-"));
  285. const badArchive = join(dir, "bad.tar.gz");
  286. const goodArchive = join(dir, "good.tar.gz");
  287. const outputPath = join(dir, "component.tar.gz");
  288. const shellOutputPath = toLocalShellPath(outputPath);
  289. await writeFile(badArchive, "stale artifact");
  290. await writeFile(goodArchive, "current artifact");
  291. const expectedSha256 = createHash("sha256").update("current artifact").digest("hex");
  292. const command = buildRemoteArtifactDownloadCommand({
  293. tool: "curl",
  294. urls: [pathToFileURL(badArchive).href, pathToFileURL(goodArchive).href],
  295. outputPath: shellOutputPath,
  296. progressLabel: "node-runtime@v22.16.0",
  297. expectedSha256,
  298. sha256Tool: await detectLocalShellSha256Tool(shellCommand),
  299. supportsProgress: false,
  300. });
  301. await execFileAsync(shellCommand, ["-c", command]);
  302. await expect(readFile(outputPath, "utf8")).resolves.toBe("current artifact");
  303. },
  304. );
  305. it("builds sha256 commands for openssl", () => {
  306. const command = buildRemoteChecksumCommand({
  307. tool: "openssl",
  308. filePath: "~/.zcode/server/component.tar.gz",
  309. });
  310. expect(command).toContain("openssl dgst -sha256");
  311. expect(command).not.toContain("awk");
  312. });
  313. });
  314. describe("LocalUploadAssetInstaller", () => {
  315. it("已取消连接不得开始写入远端 staging", async () => {
  316. const releaseDir = await mkdtemp(join(tmpdir(), "zcode-installer-pre-cancel-test-"));
  317. await mkdir(join(releaseDir, "server"), { recursive: true });
  318. await writeFile(join(releaseDir, "server", "zcode-server.cjs"), "server", "utf8");
  319. const controller = new AbortController();
  320. controller.abort();
  321. const backend = new InstallerBackend();
  322. const upload = vi
  323. .spyOn(backend, "upload")
  324. .mockImplementation(async (_localPath, _remotePath, options) => {
  325. if (options?.signal?.aborted) {
  326. const error = new Error("Remote upload canceled");
  327. error.name = "AbortError";
  328. throw error;
  329. }
  330. });
  331. const installer = new LocalUploadAssetInstaller(
  332. backend,
  333. {
  334. releaseDir,
  335. platformArch: "linux-x64",
  336. signal: controller.signal,
  337. },
  338. { log: () => undefined, logWarn: () => undefined },
  339. );
  340. await expect(
  341. installer.installFile({
  342. componentId: "server-bundle",
  343. sourceRelativePath: "server/zcode-server.cjs",
  344. remotePath: "~/.zcode/server/zcode-server.cjs",
  345. }),
  346. ).rejects.toMatchObject({ name: "AbortError" });
  347. expect(backend.commands).toEqual([]);
  348. expect(upload).not.toHaveBeenCalled();
  349. });
  350. shellBackedIt("SSH staging janitor 只删除超过 24 小时的 owner 文件", async () => {
  351. const rootDir = await mkdtemp(join(tmpdir(), "zcode-installer-stale-shell-test-"));
  352. try {
  353. const releaseDir = join(rootDir, "release");
  354. const remoteDir = join(rootDir, "remote");
  355. await mkdir(join(releaseDir, "server"), { recursive: true });
  356. await mkdir(remoteDir, { recursive: true });
  357. await writeFile(join(releaseDir, "server", "zcode-server.cjs"), "server", "utf8");
  358. const targetPath = join(remoteDir, "zcode-server.cjs");
  359. const stalePath = `${targetPath}.new-stale`;
  360. const freshPath = `${targetPath}.new-fresh`;
  361. await writeFile(targetPath, "final", "utf8");
  362. await writeFile(stalePath, "stale", "utf8");
  363. await writeFile(freshPath, "fresh", "utf8");
  364. const staleTime = new Date(Date.now() - 48 * 60 * 60 * 1_000);
  365. await utimes(stalePath, staleTime, staleTime);
  366. const controller = new AbortController();
  367. const backend = new InstallerBackend();
  368. const installer = new LocalUploadAssetInstaller(
  369. backend,
  370. {
  371. releaseDir,
  372. platformArch: "linux-x64",
  373. signal: controller.signal,
  374. },
  375. { log: () => undefined, logWarn: () => undefined },
  376. );
  377. await installer.installFile({
  378. componentId: "server-bundle",
  379. sourceRelativePath: "server/zcode-server.cjs",
  380. remotePath: toLocalShellPath(targetPath),
  381. });
  382. await execFileAsync(localShellCommand!, ["-c", backend.commands[0]!]);
  383. await expect(access(stalePath)).rejects.toThrow();
  384. await expect(access(freshPath)).resolves.toBeUndefined();
  385. await expect(readFile(targetPath, "utf8")).resolves.toBe("final");
  386. } finally {
  387. await rm(rootDir, { recursive: true, force: true });
  388. }
  389. });
  390. it("文件上传取消后不再执行正式文件替换", async () => {
  391. const releaseDir = await mkdtemp(join(tmpdir(), "zcode-installer-cancel-test-"));
  392. await mkdir(join(releaseDir, "server"), { recursive: true });
  393. await writeFile(join(releaseDir, "server", "zcode-server.cjs"), "server", "utf8");
  394. const controller = new AbortController();
  395. const backend = new InstallerBackend();
  396. let markUploadStarted!: () => void;
  397. const uploadStarted = new Promise<void>((resolve) => {
  398. markUploadStarted = resolve;
  399. });
  400. vi.spyOn(backend, "upload").mockImplementation(async (_localPath, _remotePath, options) => {
  401. markUploadStarted();
  402. await new Promise<never>((_resolve, reject) => {
  403. const rejectAbort = () => {
  404. const error = new Error("Remote upload canceled");
  405. error.name = "AbortError";
  406. reject(error);
  407. };
  408. if (options?.signal?.aborted) {
  409. rejectAbort();
  410. return;
  411. }
  412. options?.signal?.addEventListener("abort", rejectAbort, {
  413. once: true,
  414. });
  415. });
  416. });
  417. const installer = new LocalUploadAssetInstaller(
  418. backend,
  419. {
  420. releaseDir,
  421. platformArch: "linux-x64",
  422. signal: controller.signal,
  423. },
  424. { log: () => undefined, logWarn: () => undefined },
  425. );
  426. const installing = installer.installFile({
  427. componentId: "server-bundle",
  428. sourceRelativePath: "server/zcode-server.cjs",
  429. remotePath: "~/.zcode/server/zcode-server.cjs",
  430. });
  431. await uploadStarted;
  432. controller.abort();
  433. await expect(installing).rejects.toMatchObject({ name: "AbortError" });
  434. expect(backend.commands).toHaveLength(1);
  435. expect(backend.commands[0]).toContain("mkdir -p");
  436. });
  437. it("目录上传取消后不再通过已释放连接执行远端清理", async () => {
  438. const releaseDir = await mkdtemp(join(tmpdir(), "zcode-installer-dir-cancel-test-"));
  439. const sourceDir = join(releaseDir, "tools", "linux-x64", "ripgrep");
  440. await mkdir(sourceDir, { recursive: true });
  441. await writeFile(join(sourceDir, "rg"), "ripgrep", "utf8");
  442. const controller = new AbortController();
  443. const backend = new InstallerBackend();
  444. let markUploadStarted!: () => void;
  445. const uploadStarted = new Promise<void>((resolve) => {
  446. markUploadStarted = resolve;
  447. });
  448. vi.spyOn(backend, "upload").mockImplementation(async (_localPath, _remotePath, options) => {
  449. markUploadStarted();
  450. await new Promise<never>((_resolve, reject) => {
  451. const rejectAbort = () => {
  452. const error = new Error("Remote upload canceled");
  453. error.name = "AbortError";
  454. reject(error);
  455. };
  456. if (options?.signal?.aborted) {
  457. rejectAbort();
  458. return;
  459. }
  460. options?.signal?.addEventListener("abort", rejectAbort, {
  461. once: true,
  462. });
  463. });
  464. });
  465. const installer = new LocalUploadAssetInstaller(
  466. backend,
  467. {
  468. releaseDir,
  469. platformArch: "linux-x64",
  470. signal: controller.signal,
  471. },
  472. { log: () => undefined, logWarn: () => undefined },
  473. );
  474. const installing = installer.installDirectory({
  475. componentId: "ripgrep",
  476. sourceRelativePath: "tools/linux-x64/ripgrep",
  477. remoteDir: "~/.zcode/server/tools/ripgrep",
  478. });
  479. await uploadStarted;
  480. controller.abort();
  481. await expect(installing).rejects.toMatchObject({ name: "AbortError" });
  482. expect(backend.commands).toHaveLength(1);
  483. expect(backend.commands[0]).toContain("mkdir -p");
  484. });
  485. it("新的 SSH 目录上传会先清理超过 24 小时的归档和解压 staging", async () => {
  486. const releaseDir = await mkdtemp(join(tmpdir(), "zcode-installer-stale-dir-test-"));
  487. const sourceDir = join(releaseDir, "tools", "linux-x64", "ripgrep");
  488. await mkdir(sourceDir, { recursive: true });
  489. await writeFile(join(sourceDir, "rg"), "ripgrep", "utf8");
  490. const controller = new AbortController();
  491. const backend = new InstallerBackend();
  492. const installer = new LocalUploadAssetInstaller(
  493. backend,
  494. {
  495. releaseDir,
  496. platformArch: "linux-x64",
  497. signal: controller.signal,
  498. },
  499. { log: () => undefined, logWarn: () => undefined },
  500. );
  501. await installer.installDirectory({
  502. componentId: "ripgrep",
  503. sourceRelativePath: "tools/linux-x64/ripgrep",
  504. remoteDir: "~/.zcode/server/tools/ripgrep",
  505. });
  506. expect(backend.commands[0]).toContain("find");
  507. expect(backend.commands[0]).toContain("ripgrep.tar.gz-");
  508. expect(backend.commands[0]).toContain("ripgrep.extract-");
  509. expect(backend.commands[0]).toContain("-mtime +0");
  510. });
  511. it("uses a unique staging path for each uploaded file replacement", async () => {
  512. const releaseDir = await mkdtemp(join(tmpdir(), "zcode-installer-test-"));
  513. await mkdir(join(releaseDir, "server"), { recursive: true });
  514. await writeFile(join(releaseDir, "server", "zcode-server.cjs"), "server", "utf8");
  515. const backend = new InstallerBackend();
  516. const installer = new LocalUploadAssetInstaller(
  517. backend,
  518. { releaseDir, platformArch: "linux-x64" },
  519. { log: () => undefined, logWarn: () => undefined },
  520. );
  521. await installer.installFile({
  522. componentId: "server-bundle",
  523. sourceRelativePath: "server/zcode-server.cjs",
  524. remotePath: "~/.zcode/server/zcode-server.cjs",
  525. });
  526. expect(backend.uploads[0]?.remotePath).toMatch(
  527. /^~\/\.zcode\/server\/zcode-server\.cjs\.new-[\w-]+$/u,
  528. );
  529. expect(backend.commands.join("\n")).toContain(backend.uploads[0]!.remotePath.split("/").at(-1));
  530. expect(backend.commands[0]).not.toContain("find");
  531. });
  532. it("非取消文件替换失败时清理当前 owner staging", async () => {
  533. const releaseDir = await mkdtemp(join(tmpdir(), "zcode-installer-cleanup-test-"));
  534. await mkdir(join(releaseDir, "node"), { recursive: true });
  535. await writeFile(join(releaseDir, "node", "node"), "node", "utf8");
  536. const backend = new FailingReplaceBackend();
  537. const installer = new LocalUploadAssetInstaller(
  538. backend,
  539. { releaseDir, platformArch: "linux-x64" },
  540. { log: () => undefined, logWarn: () => undefined },
  541. );
  542. await expect(
  543. installer.installFile({
  544. componentId: "node-runtime",
  545. sourceRelativePath: "node/node",
  546. remotePath: "~/.zcode/server/node",
  547. executable: true,
  548. }),
  549. ).rejects.toThrow("chmod denied");
  550. const stagingPath = backend.uploads[0]?.remotePath;
  551. expect(stagingPath).toBeDefined();
  552. expect(backend.commands.at(-1)).toContain("rm -f");
  553. expect(backend.commands.at(-1)).toContain(stagingPath!.split("/").at(-1)!);
  554. });
  555. it("resolves component versions from per-component release dirs", async () => {
  556. const releaseDir = await mkdtemp(join(tmpdir(), "zcode-installer-test-"));
  557. await writeFile(
  558. join(releaseDir, "manifest-linux-x64.json"),
  559. JSON.stringify({
  560. schemaVersion: 1,
  561. appVersion: ZCODE_VERSION,
  562. platformArch: "linux-x64",
  563. components: [
  564. {
  565. id: "node-runtime",
  566. version: "24.10.0-node-runtime",
  567. sha256: "a".repeat(64),
  568. artifactPath: "components/linux-x64/node-runtime.tar.gz",
  569. mount: "node/linux-x64",
  570. },
  571. ],
  572. }),
  573. "utf8",
  574. );
  575. const requestedComponents: Array<string[] | undefined> = [];
  576. const installer = new LocalUploadAssetInstaller(
  577. new InstallerBackend(),
  578. {
  579. platformArch: "linux-x64",
  580. resolveReleaseDir: async (componentIds) => {
  581. requestedComponents.push(componentIds);
  582. return releaseDir;
  583. },
  584. },
  585. { log: () => undefined, logWarn: () => undefined },
  586. );
  587. await expect(installer.resolveComponentVersion("node-runtime")).resolves.toBe(
  588. "24.10.0-node-runtime",
  589. );
  590. expect(requestedComponents).toEqual([["node-runtime"]]);
  591. });
  592. it("allows callers to probe optional local assets without throwing", async () => {
  593. const releaseDir = await mkdtemp(join(tmpdir(), "zcode-installer-test-"));
  594. const installer = new LocalUploadAssetInstaller(
  595. new InstallerBackend(),
  596. { releaseDir, platformArch: "linux-x64" },
  597. { log: () => undefined, logWarn: () => undefined },
  598. );
  599. await expect(
  600. installer.tryResolveLocalPath(["node-pty"], "node-pty/linux-x64/missing.node"),
  601. ).resolves.toBeNull();
  602. await mkdir(join(releaseDir, "server"), { recursive: true });
  603. await writeFile(join(releaseDir, "server", "zcode-server.cjs"), "server");
  604. await expect(
  605. installer.tryResolveLocalPath(["server-bundle"], "server/zcode-server.cjs"),
  606. ).resolves.toBe(join(releaseDir, "server", "zcode-server.cjs"));
  607. });
  608. it("creates directory upload archives without relying on local system tar", async () => {
  609. const rootDir = await mkdtemp(join(tmpdir(), "zcode-installer-test-"));
  610. const releaseDir = join(rootDir, "release");
  611. const sourceDir = join(releaseDir, "tools", "linux-x64", "ripgrep");
  612. const backend = new InstallerBackend();
  613. const installer = new LocalUploadAssetInstaller(
  614. backend,
  615. { releaseDir, platformArch: "linux-x64" },
  616. { log: () => undefined, logWarn: () => undefined },
  617. );
  618. await mkdir(sourceDir, { recursive: true });
  619. await writeFile(join(sourceDir, "rg"), "ripgrep binary", "utf8");
  620. const installParams = {
  621. componentId: "ripgrep",
  622. sourceRelativePath: "tools/linux-x64/ripgrep",
  623. remoteDir: "~/.zcode/server/tools/ripgrep",
  624. };
  625. await Promise.all([
  626. installer.installDirectory(installParams),
  627. installer.installDirectory(installParams),
  628. ]);
  629. expect(backend.uploads).toHaveLength(2);
  630. const remoteTarPaths = backend.uploads.map((upload) => upload.remotePath);
  631. expect(new Set(remoteTarPaths)).toHaveLength(2);
  632. for (const remoteTarPath of remoteTarPaths) {
  633. expect(remoteTarPath).toMatch(/^~\/.zcode\/server\/tools\/ripgrep\.tar\.gz-[\w-]+$/u);
  634. }
  635. expect(backend.commands.join("\n")).toContain("ripgrep.extract-");
  636. expect(backend.commands.join("\n")).toContain("trap cleanup_staging EXIT");
  637. expect(backend.commands[0]).not.toContain("find");
  638. const uploadedArchive = join(rootDir, "uploaded.tar.gz");
  639. const extractDir = join(rootDir, "extract");
  640. await writeFile(uploadedArchive, backend.uploads[0]!.content);
  641. await extractTarGzArchive(uploadedArchive, extractDir);
  642. await expect(readFile(join(extractDir, "ripgrep", "rg"), "utf8")).resolves.toBe(
  643. "ripgrep binary",
  644. );
  645. });
  646. it("falls back to CDN cache when local directory exists but required child paths are missing", async () => {
  647. const rootDir = await mkdtemp(join(tmpdir(), "zcode-installer-test-"));
  648. const staleReleaseDir = join(rootDir, "stale-release");
  649. const cdnReleaseDir = join(rootDir, "cdn-release");
  650. const sourceRelativePath = "glm/linux-x64/packages";
  651. await mkdir(join(staleReleaseDir, sourceRelativePath), { recursive: true });
  652. await mkdir(join(cdnReleaseDir, sourceRelativePath, "skill-creator-plugin", ".zcode-plugin"), {
  653. recursive: true,
  654. });
  655. await writeFile(
  656. join(
  657. cdnReleaseDir,
  658. sourceRelativePath,
  659. "skill-creator-plugin",
  660. ".zcode-plugin",
  661. "plugin.json",
  662. ),
  663. '{"name":"skill-creator-plugin"}',
  664. "utf8",
  665. );
  666. const installer = new LocalUploadAssetInstaller(
  667. new InstallerBackend(),
  668. {
  669. releaseDir: staleReleaseDir,
  670. platformArch: "linux-x64",
  671. version: ZCODE_VERSION,
  672. remoteCacheDir: rootDir,
  673. remoteCdnBaseUrl: "https://cdn.example.test/releases",
  674. },
  675. { log: () => undefined, logWarn: () => undefined },
  676. );
  677. vi.spyOn(
  678. installer as unknown as {
  679. tryResolveCdnReleaseDir(
  680. componentIds: string[],
  681. requiredReleasePaths?: string[],
  682. ): Promise<string | null>;
  683. },
  684. "tryResolveCdnReleaseDir",
  685. ).mockResolvedValue(cdnReleaseDir);
  686. await expect(
  687. installer.tryResolveLocalPath(["glm"], sourceRelativePath, [
  688. `${sourceRelativePath}/skill-creator-plugin/.zcode-plugin/plugin.json`,
  689. ]),
  690. ).resolves.toBe(join(cdnReleaseDir, sourceRelativePath));
  691. });
  692. it("bounds the internal CDN fallback with the configured manifest deadline", async () => {
  693. const releaseDir = await mkdtemp(join(tmpdir(), "zcode-installer-test-"));
  694. const fetchMock = vi.fn(
  695. async (_input: RequestInfo | URL, init?: RequestInit) =>
  696. await new Promise<Response>((_resolve, reject) => {
  697. init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
  698. once: true,
  699. });
  700. }),
  701. );
  702. vi.stubGlobal("fetch", fetchMock);
  703. const installer = new LocalUploadAssetInstaller(
  704. new InstallerBackend(),
  705. {
  706. releaseDir,
  707. platformArch: "linux-x64",
  708. version: ZCODE_VERSION,
  709. remoteCacheDir: join(releaseDir, "cache"),
  710. remoteCdnBaseUrl: "https://cdn.example.test/releases",
  711. manifestRequestTimeoutMs: 25,
  712. },
  713. { log: () => undefined, logWarn: () => undefined },
  714. );
  715. const startedAt = Date.now();
  716. await expect(
  717. installer.tryResolveLocalPath(["glm"], "glm/linux-x64/missing-zcode.cjs"),
  718. ).resolves.toBeNull();
  719. expect(Date.now() - startedAt).toBeLessThan(1_000);
  720. expect(fetchMock).toHaveBeenCalled();
  721. vi.unstubAllGlobals();
  722. });
  723. });
  724. describe("RemoteDownloadAssetInstaller", () => {
  725. shellBackedIt.each(
  726. [
  727. { stage: "download", diagnostic: "fixture download failed" },
  728. { stage: "checksum", diagnostic: "sha256 mismatch" },
  729. { stage: "extract", diagnostic: "fixture extraction failed" },
  730. ].flatMap((scenario) =>
  731. [true, false].map((supportsProgress) => ({ ...scenario, supportsProgress })),
  732. ),
  733. )(
  734. "远端 $stage 失败保留原始错误并清理,恢复后可重试(progress=$supportsProgress)",
  735. async ({ stage, diagnostic, supportsProgress }) => {
  736. const rootDir = await mkdtemp(join(tmpdir(), "zcode-installer-download-failure-"));
  737. const sourcePath = join(rootDir, "zcode-server.cjs");
  738. const archivePath = join(rootDir, "component.tar.gz");
  739. await writeFile(sourcePath, "current server");
  740. await createTarGzArchive(archivePath, [{ sourcePath, archivePath: "zcode-server.cjs" }]);
  741. const sha256 = createHash("sha256")
  742. .update(await readFile(archivePath))
  743. .digest("hex");
  744. stubManifestFetch({
  745. ...validManifest,
  746. components: [{ ...validManifest.components[0], sha256 }],
  747. });
  748. const download = `wget() { while [ "$1" != -O ]; do shift; done; shift; command cp ${quotePosixShellArg(toLocalShellPath(archivePath))} "$1"; }`;
  749. const failure =
  750. stage === "download"
  751. ? 'wget() { echo "fixture download failed" >&2; return 4; }'
  752. : stage === "checksum"
  753. ? 'wget() { while [ "$1" != -O ]; do shift; done; shift; printf corrupt > "$1"; }'
  754. : 'tar() { echo "fixture extraction failed" >&2; return 2; }';
  755. const backend = new ShellInstallerBackend(rootDir, `${download}\n${failure}`);
  756. const installedPath = join(rootDir, ".zcode/server/zcode-server.cjs");
  757. await mkdir(join(rootDir, ".zcode/server"), { recursive: true });
  758. await writeFile(installedPath, "previous server");
  759. const installer = new RemoteDownloadAssetInstaller(
  760. backend,
  761. {
  762. version: ZCODE_VERSION,
  763. platformArch: "linux-x64",
  764. remoteCdnBaseUrl: "https://cdn.example.test/releases",
  765. },
  766. {
  767. download: "wget",
  768. tar: "tar",
  769. sha256: await detectLocalShellSha256Tool(localShellCommand!),
  770. supportsProgress,
  771. },
  772. { log: () => undefined, logWarn: () => undefined },
  773. );
  774. try {
  775. await expect(
  776. installer.installFile({
  777. componentId: "server-bundle",
  778. sourceRelativePath: "server/zcode-server.cjs",
  779. remotePath: "~/.zcode/server/zcode-server.cjs",
  780. }),
  781. ).rejects.toThrow(diagnostic);
  782. expect(backend.commands).toHaveLength(1);
  783. await expect(readdir(join(rootDir, ".zcode/server/asset-cache/staging"))).resolves.toEqual(
  784. [],
  785. );
  786. await expect(
  787. readdir(join(rootDir, ".zcode/server/asset-cache/components/linux-x64/server-bundle")),
  788. ).resolves.toEqual([]);
  789. await expect(readFile(installedPath, "utf8")).resolves.toBe("previous server");
  790. backend.prelude = download;
  791. await installer.installFile({
  792. componentId: "server-bundle",
  793. sourceRelativePath: "server/zcode-server.cjs",
  794. remotePath: "~/.zcode/server/zcode-server.cjs",
  795. });
  796. await expect(readFile(installedPath, "utf8")).resolves.toBe("current server");
  797. await expect(readdir(join(rootDir, ".zcode/server/asset-cache/staging"))).resolves.toEqual(
  798. [],
  799. );
  800. await expect(
  801. readdir(join(rootDir, ".zcode/server/asset-cache/components/linux-x64/server-bundle")),
  802. ).resolves.toEqual([sha256]);
  803. } finally {
  804. vi.unstubAllGlobals();
  805. await rm(rootDir, { recursive: true, force: true });
  806. }
  807. },
  808. );
  809. it("已取消连接不得启动远端下载或 staging 命令", async () => {
  810. stubManifestFetch(validManifest);
  811. const controller = new AbortController();
  812. controller.abort();
  813. const backend = new InstallerBackend();
  814. const installer = new RemoteDownloadAssetInstaller(
  815. backend,
  816. {
  817. version: ZCODE_VERSION,
  818. platformArch: "linux-x64",
  819. remoteCdnBaseUrls: ["https://cdn.example.test/releases"],
  820. signal: controller.signal,
  821. },
  822. { download: "curl", tar: "tar", sha256: "sha256sum" },
  823. { log: () => undefined, logWarn: () => undefined },
  824. );
  825. await expect(
  826. installer.installFile({
  827. componentId: "server-bundle",
  828. sourceRelativePath: "server/zcode-server.cjs",
  829. remotePath: "~/.zcode/server/zcode-server.cjs",
  830. }),
  831. ).rejects.toMatchObject({ name: "AbortError" });
  832. expect(backend.commands).toEqual([]);
  833. vi.unstubAllGlobals();
  834. });
  835. it("远端下载模式的本地 manifest 和 HEAD 使用注入网络出口", async () => {
  836. const remoteAssetFetch = vi.fn<typeof fetch>(async (_input, init) =>
  837. init?.method === "HEAD"
  838. ? new Response(null, {
  839. status: 200,
  840. headers: { "content-length": "1024" },
  841. })
  842. : new Response(JSON.stringify(validManifest), { status: 200 }),
  843. );
  844. const directFetch = vi
  845. .spyOn(globalThis, "fetch")
  846. .mockRejectedValue(new Error("remote asset direct fetch is forbidden"));
  847. const backend = new InstallerBackend();
  848. const installer = new RemoteDownloadAssetInstaller(
  849. backend,
  850. {
  851. version: ZCODE_VERSION,
  852. platformArch: "linux-x64",
  853. remoteCdnBaseUrls: ["https://cdn.example.test/releases"],
  854. remoteAssetNetwork: { fetch: remoteAssetFetch },
  855. },
  856. { download: "curl", tar: "tar", sha256: "sha256sum" },
  857. { log: () => undefined, logWarn: () => undefined },
  858. );
  859. try {
  860. await installer.installFile({
  861. componentId: "server-bundle",
  862. sourceRelativePath: "server/zcode-server.cjs",
  863. remotePath: "~/.zcode/server/zcode-server.cjs",
  864. });
  865. expect(directFetch).not.toHaveBeenCalled();
  866. expect(remoteAssetFetch.mock.calls.some(([, init]) => init?.method === "HEAD")).toBe(true);
  867. expect(remoteAssetFetch.mock.calls.some(([, init]) => init?.method !== "HEAD")).toBe(true);
  868. } finally {
  869. directFetch.mockRestore();
  870. }
  871. });
  872. it("本地 HEAD 请求迟到完成后不得启动已取消的远端下载", async () => {
  873. let markHeadStarted!: () => void;
  874. const headStarted = new Promise<void>((resolve) => {
  875. markHeadStarted = resolve;
  876. });
  877. let resolveHead!: (response: Response) => void;
  878. vi.stubGlobal(
  879. "fetch",
  880. vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
  881. if (init?.method === "HEAD") {
  882. markHeadStarted();
  883. return await new Promise<Response>((resolve) => {
  884. resolveHead = resolve;
  885. });
  886. }
  887. return new Response(JSON.stringify(validManifest), { status: 200 });
  888. }),
  889. );
  890. const controller = new AbortController();
  891. const backend = new InstallerBackend();
  892. const installer = new RemoteDownloadAssetInstaller(
  893. backend,
  894. {
  895. version: ZCODE_VERSION,
  896. platformArch: "linux-x64",
  897. remoteCdnBaseUrls: ["https://cdn.example.test/releases"],
  898. signal: controller.signal,
  899. },
  900. { download: "curl", tar: "tar", sha256: "sha256sum" },
  901. { log: () => undefined, logWarn: () => undefined },
  902. );
  903. const installing = installer.installFile({
  904. componentId: "server-bundle",
  905. sourceRelativePath: "server/zcode-server.cjs",
  906. remotePath: "~/.zcode/server/zcode-server.cjs",
  907. });
  908. await headStarted;
  909. controller.abort();
  910. resolveHead(
  911. new Response(null, {
  912. status: 200,
  913. headers: { "content-length": "1024" },
  914. }),
  915. );
  916. await expect(installing).rejects.toMatchObject({ name: "AbortError" });
  917. expect(backend.commands).toEqual([]);
  918. vi.unstubAllGlobals();
  919. });
  920. it("uses a remote lock and unique staging path when populating component cache", async () => {
  921. stubManifestFetch(validManifest);
  922. const backend = new InstallerBackend();
  923. const installer = new RemoteDownloadAssetInstaller(
  924. backend,
  925. {
  926. version: ZCODE_VERSION,
  927. platformArch: "linux-x64",
  928. remoteCdnBaseUrls: ["https://cdn.example.test/releases"],
  929. },
  930. { download: "curl", tar: "tar", sha256: "sha256sum" },
  931. { log: () => undefined, logWarn: () => undefined },
  932. );
  933. await installer.installFile({
  934. componentId: "server-bundle",
  935. sourceRelativePath: "server/zcode-server.cjs",
  936. remotePath: "~/.zcode/server/zcode-server.cjs",
  937. });
  938. const command = backend.commands.join("\n");
  939. expect(command).toContain(".lock");
  940. expect(command).toContain("while ! mkdir");
  941. expect(command).toContain("stat -c %Y");
  942. expect(command).toContain("stat -f %m");
  943. expect(command).toContain("stale lock for server-bundle@1.0.0-server-bundle");
  944. expect(command).toContain(
  945. 'touch "$HOME"\'/.zcode/server/asset-cache/components/linux-x64/server-bundle/',
  946. );
  947. expect(command).toContain('kill "$lock_heartbeat_pid"');
  948. expect(command).toMatch(/\.new-[^\s']+/u);
  949. expect(command).toMatch(/zcode-server\.cjs\.new-[\w-]+/u);
  950. expect(command).toContain("curl -fL");
  951. expect(command).toContain("sha256sum");
  952. vi.unstubAllGlobals();
  953. });
  954. it("forwards remote stdout download progress into deploy logs", async () => {
  955. stubManifestFetch(validManifest);
  956. const backend = new InstallerBackend([
  957. "download progress: [server-bundle@1.0.0-server-bundle] 1.0 MB (total unknown, 0.50 MB/s)",
  958. "wget diagnostic noise",
  959. ]);
  960. const logs: string[] = [];
  961. const installer = new RemoteDownloadAssetInstaller(
  962. backend,
  963. {
  964. version: ZCODE_VERSION,
  965. platformArch: "linux-x64",
  966. remoteCdnBaseUrls: ["https://cdn.example.test/releases"],
  967. },
  968. { download: "curl", tar: "tar", sha256: "sha256sum" },
  969. {
  970. log: (message) => logs.push(String(message)),
  971. logWarn: () => undefined,
  972. },
  973. );
  974. await installer.installFile({
  975. componentId: "server-bundle",
  976. sourceRelativePath: "server/zcode-server.cjs",
  977. remotePath: "~/.zcode/server/zcode-server.cjs",
  978. });
  979. expect(logs).toContain(
  980. "download progress: [server-bundle@1.0.0-server-bundle] 1.0 MB (total unknown, 0.50 MB/s)",
  981. );
  982. expect(logs).not.toContain("wget diagnostic noise");
  983. vi.unstubAllGlobals();
  984. });
  985. it("uses artifact content length for remote download progress totals", async () => {
  986. stubManifestAndHeadFetch(validManifest, 2 * 1024 * 1024);
  987. const backend = new InstallerBackend();
  988. const installer = new RemoteDownloadAssetInstaller(
  989. backend,
  990. {
  991. version: ZCODE_VERSION,
  992. platformArch: "linux-x64",
  993. remoteCdnBaseUrls: ["https://cdn.example.test/releases"],
  994. },
  995. { download: "curl", tar: "tar", sha256: "sha256sum" },
  996. { log: () => undefined, logWarn: () => undefined },
  997. );
  998. await installer.installFile({
  999. componentId: "server-bundle",
  1000. sourceRelativePath: "server/zcode-server.cjs",
  1001. remotePath: "~/.zcode/server/zcode-server.cjs",
  1002. });
  1003. expect(backend.commands.join("\n")).toContain("total=2097152");
  1004. vi.unstubAllGlobals();
  1005. });
  1006. it("uses manifest SHA for server-bundle remote cache hits", async () => {
  1007. const semanticVersion = "1.0.0-server-bundle";
  1008. const hashedVersion = `${semanticVersion}+aaaaaaaaaaaa`;
  1009. stubManifestFetch({
  1010. ...validManifest,
  1011. components: [
  1012. {
  1013. ...validManifest.components[0],
  1014. version: hashedVersion,
  1015. },
  1016. ],
  1017. });
  1018. const expectedCacheSegment = validManifest.components[0].sha256;
  1019. const backend = new InstallerBackend(
  1020. [],
  1021. new Set([
  1022. `~/.zcode/server/asset-cache/components/linux-x64/server-bundle/${expectedCacheSegment}/.ready`,
  1023. ]),
  1024. );
  1025. const logs: string[] = [];
  1026. const installer = new RemoteDownloadAssetInstaller(
  1027. backend,
  1028. {
  1029. version: ZCODE_VERSION,
  1030. platformArch: "linux-x64",
  1031. remoteCdnBaseUrls: ["https://cdn.example.test/releases"],
  1032. },
  1033. { download: "curl", tar: "tar", sha256: "sha256sum" },
  1034. {
  1035. log: (message) => logs.push(String(message)),
  1036. logWarn: () => undefined,
  1037. },
  1038. );
  1039. await installer.installFile({
  1040. componentId: "server-bundle",
  1041. sourceRelativePath: "server/zcode-server.cjs",
  1042. remotePath: "~/.zcode/server/zcode-server.cjs",
  1043. });
  1044. const commands = backend.commands.join("\n");
  1045. expect(commands).not.toContain("curl -fL");
  1046. expect(commands).toContain(
  1047. `asset-cache/components/linux-x64/server-bundle/${expectedCacheSegment}`,
  1048. );
  1049. expect(logs).toContain(
  1050. `[remote-assets] remote component cache hit: server-bundle@${hashedVersion}`,
  1051. );
  1052. vi.unstubAllGlobals();
  1053. });
  1054. it("uses manifest SHA for the glm cache while leaving the old semantic cache untouched", async () => {
  1055. const semanticVersion = "v0.13.3";
  1056. const hashedVersion = `${semanticVersion}+bbbbbbbbbbbb`;
  1057. stubManifestFetch({
  1058. ...validManifest,
  1059. components: [
  1060. {
  1061. id: "glm",
  1062. version: hashedVersion,
  1063. sha256: "b".repeat(64),
  1064. artifactPath: "components/linux-x64/glm/v0.13.3+bbbbbbbbbbbb.tar.gz",
  1065. mount: "glm/linux-x64",
  1066. },
  1067. ],
  1068. });
  1069. const oldCacheSegment = hashRemoteCacheSegment(semanticVersion);
  1070. const expectedCacheSegment = "b".repeat(64);
  1071. const backend = new InstallerBackend(
  1072. [],
  1073. new Set([`~/.zcode/server/asset-cache/components/linux-x64/glm/${oldCacheSegment}/.ready`]),
  1074. );
  1075. const logs: string[] = [];
  1076. const warnings: string[] = [];
  1077. const installer = new RemoteDownloadAssetInstaller(
  1078. backend,
  1079. {
  1080. version: ZCODE_VERSION,
  1081. platformArch: "linux-x64",
  1082. remoteCdnBaseUrls: ["https://cdn.example.test/releases"],
  1083. },
  1084. { download: "curl", tar: "tar", sha256: "sha256sum" },
  1085. {
  1086. log: (message) => logs.push(String(message)),
  1087. logWarn: (message) => warnings.push(String(message)),
  1088. },
  1089. );
  1090. await installer.installFile({
  1091. componentId: "glm",
  1092. sourceRelativePath: "glm/linux-x64/zcode.cjs",
  1093. remotePath: "~/.zcode/server/agents/glm/zcode.cjs",
  1094. });
  1095. const commands = backend.commands.join("\n");
  1096. expect(commands).toContain("curl -fL");
  1097. expect(commands).toContain(`asset-cache/components/linux-x64/glm/${expectedCacheSegment}`);
  1098. expect(commands).not.toContain(
  1099. `rm -rf "$HOME"'/.zcode/server/asset-cache/components/linux-x64/glm/${oldCacheSegment}'`,
  1100. );
  1101. expect(logs).not.toContain(`[remote-assets] remote component cache hit: glm@${hashedVersion}`);
  1102. expect(warnings).toContain(
  1103. `[remote-assets] download required: component=glm reason=remote component cache missing path=~/.zcode/server/asset-cache/components/linux-x64/glm/${expectedCacheSegment}/.ready`,
  1104. );
  1105. vi.unstubAllGlobals();
  1106. });
  1107. it("rejects manifests that local cache validation would reject", async () => {
  1108. stubManifestFetch({
  1109. ...validManifest,
  1110. components: [{ ...validManifest.components[0], sha256: "not-a-sha" }],
  1111. });
  1112. const installer = new RemoteDownloadAssetInstaller(
  1113. new InstallerBackend(),
  1114. {
  1115. version: ZCODE_VERSION,
  1116. platformArch: "linux-x64",
  1117. remoteCdnBaseUrls: ["https://cdn.example.test/releases"],
  1118. },
  1119. { download: "curl", tar: "tar", sha256: "sha256sum" },
  1120. { log: () => undefined, logWarn: () => undefined },
  1121. );
  1122. await expect(
  1123. installer.installFile({
  1124. componentId: "server-bundle",
  1125. sourceRelativePath: "server/zcode-server.cjs",
  1126. remotePath: "~/.zcode/server/zcode-server.cjs",
  1127. }),
  1128. ).rejects.toThrow("sha256 is invalid");
  1129. vi.unstubAllGlobals();
  1130. });
  1131. });