sourceServerTransportAdapter.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. import { PassThrough } from "node:stream";
  2. import { Emitter } from "@zcode/rpc";
  3. import type { RemoteTarget } from "@zcode/shared";
  4. import type { IRemoteBackend, StdioStream } from "../src/remote/backend.js";
  5. import {
  6. createSourceServerTransportAdapter,
  7. type SourceServerTransportAdapter,
  8. } from "../src/source-server/transportAdapter.js";
  9. import { describe, expect, it, vi } from "vitest";
  10. function completedStream(stdoutText: string, stderrText = "", code = 0): StdioStream {
  11. const stdin = new PassThrough();
  12. const stdout = new PassThrough();
  13. const stderr = new PassThrough();
  14. const closed = new Emitter<number>();
  15. setTimeout(() => {
  16. stdout.end(stdoutText);
  17. stderr.end(stderrText);
  18. closed.fire(code);
  19. }, 0);
  20. return { stdin, stdout, stderr, onClose: closed.event };
  21. }
  22. class FakeBackend implements IRemoteBackend {
  23. readonly commands: string[] = [];
  24. readonly uploads: Array<{ localPath: string; remotePath: string }> = [];
  25. readonly readPaths: string[] = [];
  26. constructor(
  27. private readonly versionOutput = "3.8.0\n",
  28. private readonly updateResult?: {
  29. stdout: string;
  30. stderr?: string;
  31. exitCode: number;
  32. },
  33. private readonly serveResult?: {
  34. stdout: string;
  35. stderr?: string;
  36. exitCode: number;
  37. },
  38. private readonly tarAvailable = true,
  39. ) {}
  40. async detect() {
  41. return { platform: "linux", arch: "x64" };
  42. }
  43. async upload(localPath: string, remotePath: string): Promise<void> {
  44. this.uploads.push({ localPath, remotePath });
  45. }
  46. async exec(command: string): Promise<StdioStream> {
  47. this.commands.push(command);
  48. if (command.includes("__ZCODE_PROBE_PLATFORM__")) {
  49. const releaseSection = command.includes("__ZCODE_PROBE_RELEASE__")
  50. ? `__ZCODE_PROBE_RELEASE__\n${JSON.stringify({ version: "3.8.0", archiveSha256: "c".repeat(64) })}\n`
  51. : "";
  52. return completedStream(
  53. `__ZCODE_PROBE_PLATFORM__\nLinux\n` +
  54. `__ZCODE_PROBE_ARCH__\nx86_64\n` +
  55. `__ZCODE_PROBE_KERNEL__\nLinux\n` +
  56. `__ZCODE_PROBE_INSTALLED__\n1\n` +
  57. releaseSection +
  58. `__ZCODE_PROBE_VERSION__\n${this.versionOutput}` +
  59. `__ZCODE_PROBE_STATUS__\n${JSON.stringify({
  60. state: "ready",
  61. port: 43123,
  62. version: "3.8.0",
  63. serviceRegistered: false,
  64. })}\n` +
  65. `__ZCODE_PROBE_END__\n`,
  66. );
  67. }
  68. if (command.includes("command -v tar") && !command.includes("command -v curl")) {
  69. return completedStream(this.tarAvailable ? "tar=tar\n" : "tar=\n");
  70. }
  71. if (command.includes("command -v curl")) {
  72. return completedStream("download=curl\ntar=tar\nsha256=sha256sum\n");
  73. }
  74. if (command.includes("curl -fL"))
  75. return completedStream(
  76. "download progress: [Source Server linux-x64] 50.0% (2.0/4.0 MB, 1.00 MB/s)\n",
  77. );
  78. if (command.includes("proxy-stdio")) {
  79. const stdin = new PassThrough();
  80. const stdout = new PassThrough();
  81. const stderr = new PassThrough();
  82. const closed = new Emitter<number>();
  83. stdin.pipe(stdout);
  84. stdin.once("end", () => closed.fire(0));
  85. return { stdin, stdout, stderr, onClose: closed.event };
  86. }
  87. if (command.includes("--version")) return completedStream(this.versionOutput);
  88. if (command.includes("'status'")) {
  89. return completedStream(
  90. `${JSON.stringify({
  91. state: "ready",
  92. port: 43123,
  93. version: "3.8.0",
  94. serviceRegistered: false,
  95. })}\n`,
  96. );
  97. }
  98. if (command.includes("'serve' '--daemon'")) {
  99. if (this.serveResult) {
  100. return completedStream(
  101. this.serveResult.stdout,
  102. this.serveResult.stderr,
  103. this.serveResult.exitCode,
  104. );
  105. }
  106. return completedStream(
  107. `${JSON.stringify({
  108. state: "ready",
  109. port: 43123,
  110. version: "3.8.0",
  111. serviceRegistered: false,
  112. })}\n`,
  113. );
  114. }
  115. if (command.includes("update --from-archive")) {
  116. if (this.updateResult) {
  117. return completedStream(
  118. this.updateResult.stdout,
  119. this.updateResult.stderr,
  120. this.updateResult.exitCode,
  121. );
  122. }
  123. return completedStream(`${JSON.stringify({ ok: true, applied: true })}\n`);
  124. }
  125. return completedStream(`${JSON.stringify({ ok: true })}\n`);
  126. }
  127. async exists(): Promise<boolean> {
  128. return true;
  129. }
  130. async readFile(remotePath: string): Promise<string> {
  131. this.readPaths.push(remotePath);
  132. if (remotePath.endsWith("ingress-token")) return "ingress-token-value";
  133. if (remotePath.endsWith("current.json")) {
  134. return JSON.stringify({ archiveSha256: "c".repeat(64) });
  135. }
  136. return "";
  137. }
  138. dispose(): void {}
  139. }
  140. const targets: RemoteTarget[] = [
  141. { kind: "ssh", host: "example.com", username: "alice" },
  142. { kind: "wsl", distro: "Ubuntu-24.04", user: "alice" },
  143. { kind: "docker", container: "zcode-dev" },
  144. ];
  145. it("reads the installed release identity only when development probing requests it", async () => {
  146. const backend = new FakeBackend();
  147. const target = targets[0]!;
  148. const adapter = createSourceServerTransportAdapter("ssh", {
  149. createBackend: async () => backend,
  150. });
  151. await expect(adapter.probe(target, {})).resolves.not.toHaveProperty("installedArchiveSha256");
  152. expect(backend.commands.at(-1)).not.toContain("__ZCODE_PROBE_RELEASE__");
  153. await expect(adapter.probe(target, {}, { includeReleaseIdentity: true })).resolves.toMatchObject({
  154. installedArchiveSha256: "c".repeat(64),
  155. });
  156. expect(backend.commands.at(-1)).toContain("__ZCODE_PROBE_RELEASE__");
  157. });
  158. describe("probe failure classification", () => {
  159. const target = targets[0]!;
  160. const probeWith = (exec: () => Promise<StdioStream>) => {
  161. const backend = new FakeBackend();
  162. backend.exec = async (command) => {
  163. backend.commands.push(command);
  164. return exec();
  165. };
  166. return createSourceServerTransportAdapter("ssh", { createBackend: async () => backend }).probe(
  167. target,
  168. {},
  169. );
  170. };
  171. it.each([
  172. "SSH 连接握手超时:未能在 15 秒内建立 SSH 会话,请检查网络、服务器 SSH 服务或终端 SSH 配置差异",
  173. "Connection lost before handshake",
  174. ])("does not report transport failure %s as a preflight failure", async (message) => {
  175. // 传输失败不是远端环境不满足;未识别时只能是未知,不能借探测阶段冒充预检失败。
  176. await expect(probeWith(() => Promise.reject(new Error(message)))).rejects.toMatchObject({
  177. code: "remote-connection-unknown",
  178. message,
  179. });
  180. });
  181. it("keeps the network classification of a reset transport", async () => {
  182. const reset = Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" });
  183. await expect(probeWith(() => Promise.reject(reset))).rejects.toMatchObject({
  184. code: "remote-host-unreachable",
  185. });
  186. });
  187. it("reports a failed environment probe command as a preflight failure", async () => {
  188. await expect(
  189. probeWith(async () => completedStream("", "sh: uname: not found", 127)),
  190. ).rejects.toMatchObject({ code: "remote-preflight-failed", message: "sh: uname: not found" });
  191. });
  192. it("keeps the specific reason a failed environment probe reports", async () => {
  193. await expect(
  194. probeWith(async () => completedStream("", "mkdir: Permission denied", 1)),
  195. ).rejects.toMatchObject({ code: "remote-permission-denied" });
  196. });
  197. it("reports an unsupported remote platform as a preflight failure", async () => {
  198. await expect(
  199. probeWith(async () =>
  200. completedStream(
  201. "__ZCODE_PROBE_PLATFORM__\nMINGW64_NT-10.0\n__ZCODE_PROBE_ARCH__\nx86_64\n" +
  202. "__ZCODE_PROBE_INSTALLED__\n0\n__ZCODE_PROBE_END__\n",
  203. ),
  204. ),
  205. ).rejects.toMatchObject({ code: "remote-preflight-failed" });
  206. });
  207. });
  208. it("probes environment, installation, release identity, version and live status without starting the CLI", async () => {
  209. const backend = new FakeBackend();
  210. const adapter = createSourceServerTransportAdapter("ssh", {
  211. createBackend: async () => backend,
  212. });
  213. await adapter.probe(targets[0]!, {}, { includeReleaseIdentity: true });
  214. const probeCommands = backend.commands.filter((command) =>
  215. command.includes("__ZCODE_PROBE_PLATFORM__"),
  216. );
  217. expect(probeCommands).toHaveLength(1);
  218. expect(probeCommands[0]).toContain("current.json");
  219. expect(probeCommands[0]).toContain("run/status.json");
  220. expect(probeCommands[0]).not.toContain(" status --json");
  221. expect(probeCommands[0]).not.toContain(" --version");
  222. });
  223. it("reuses a just-probed ready daemon status instead of running serve --daemon again", async () => {
  224. const backend = new FakeBackend();
  225. const adapter = createSourceServerTransportAdapter("ssh", {
  226. createBackend: async () => backend,
  227. });
  228. const probe = await adapter.probe(targets[0]!, {});
  229. const commandCountBeforeEnsure = backend.commands.length;
  230. await expect(
  231. adapter.ensureDaemon(targets[0]!, {}, { observedStatus: probe.daemonStatus }),
  232. ).resolves.toEqual({ port: 43123, ingressToken: "ingress-token-value" });
  233. expect(backend.commands.slice(commandCountBeforeEnsure)).not.toEqual(
  234. expect.arrayContaining([expect.stringContaining("'serve' '--daemon'")]),
  235. );
  236. });
  237. function contract(name: string, target: RemoteTarget): void {
  238. describe(`${name} Source Server Transport contract`, () => {
  239. it("implements the common probe/install/daemon/channel/exec behavior", async () => {
  240. const backend = new FakeBackend();
  241. const adapter: SourceServerTransportAdapter = createSourceServerTransportAdapter(
  242. target.kind as "ssh" | "wsl" | "docker",
  243. { createBackend: async () => backend },
  244. );
  245. await expect(adapter.probe(target, {})).resolves.toMatchObject({
  246. platform: "linux",
  247. arch: "x64",
  248. installed: true,
  249. installedVersion: "3.8.0",
  250. daemonStatus: { state: "ready", port: 43123 },
  251. });
  252. await adapter.installOrUpdate(
  253. target,
  254. {
  255. localArchivePath: "/tmp/zcode-server-linux-x64.tar.gz",
  256. target: "linux-x64",
  257. version: "3.8.0",
  258. sha256: "a".repeat(64),
  259. sizeBytes: 1024,
  260. urls: ["https://cdn.example.test/zcode-server-linux-x64.tar.gz"],
  261. },
  262. {},
  263. { force: true },
  264. );
  265. expect(backend.uploads).toHaveLength(1);
  266. expect(backend.uploads[0]?.remotePath).toMatch(
  267. /^~\/\.zcode\/server\/\.bootstrap-[^/]+\/zcode-server\.tar\.gz$/u,
  268. );
  269. expect(backend.uploads[0]?.remotePath).not.toContain("/tmp/");
  270. const prepareCommand = backend.commands.find(
  271. (command) => command.includes("mkdir -p") && command.includes(".bootstrap-"),
  272. );
  273. expect(prepareCommand).toContain('"$HOME/.zcode/server"/.bootstrap-*');
  274. expect(prepareCommand).toContain("1800000");
  275. expect(prepareCommand).toContain("date +%s");
  276. const updateCommand = backend.commands.find((command) =>
  277. command.includes("update --from-archive"),
  278. );
  279. expect(updateCommand).toContain("--force");
  280. if (target.kind === "ssh") {
  281. expect(updateCommand).not.toContain("ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1");
  282. } else {
  283. expect(updateCommand).toContain("ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1");
  284. }
  285. const daemonLogs: string[] = [];
  286. const ingress = await adapter.ensureDaemon(target, {
  287. onLog: (event) => daemonLogs.push(event.message),
  288. });
  289. expect(ingress).toEqual({
  290. port: 43123,
  291. ingressToken: "ingress-token-value",
  292. });
  293. expect(daemonLogs).toContain(
  294. "Source Server started in detached fallback mode for this remote environment",
  295. );
  296. const serveCommand = backend.commands.find((command) =>
  297. command.includes("'serve' '--daemon'"),
  298. );
  299. if (target.kind === "ssh") {
  300. expect(serveCommand).not.toContain("ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1");
  301. } else {
  302. expect(serveCommand).toContain("ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1");
  303. }
  304. const channel = await adapter.openChannel(target, ingress, {});
  305. const echoed = new Promise<Buffer>((resolve) =>
  306. channel.once("data", (data) => resolve(Buffer.from(data))),
  307. );
  308. channel.write(Buffer.from([0, 1, 2, 255]));
  309. expect(await echoed).toEqual(Buffer.from([0, 1, 2, 255]));
  310. channel.end();
  311. await expect(adapter.exec(target, ["status", "--json"], {})).resolves.toMatchObject({
  312. exitCode: 0,
  313. });
  314. expect(backend.commands.some((command) => command.includes("proxy-stdio"))).toBe(true);
  315. });
  316. });
  317. }
  318. for (const target of targets) contract(target.kind, target);
  319. it.each(targets)("forwards $kind install progress before command completion", async (target) => {
  320. const backend = new FakeBackend();
  321. const originalExec = backend.exec.bind(backend);
  322. const stdout = new PassThrough();
  323. const stderr = new PassThrough();
  324. const closed = new Emitter<number>();
  325. const started = Promise.withResolvers<void>();
  326. vi.spyOn(backend, "exec").mockImplementation(async (command) => {
  327. if (!command.includes("update --from-archive")) return await originalExec(command);
  328. backend.commands.push(command);
  329. started.resolve();
  330. return { stdin: new PassThrough(), stdout, stderr, onClose: closed.event };
  331. });
  332. const adapter = createSourceServerTransportAdapter(target.kind as "ssh" | "wsl" | "docker", {
  333. createBackend: async () => backend,
  334. });
  335. const onLog = vi.fn();
  336. let complete = false;
  337. const install = adapter.installOrUpdate(target, {
  338. localArchivePath: "/tmp/release.tar.gz", target: "linux-x64", version: "3.12.1",
  339. sha256: "a".repeat(64), sizeBytes: 1024, urls: [],
  340. }, { onLog }).then(() => { complete = true; });
  341. await started.promise;
  342. expect(backend.commands.at(-1)).toContain("--progress");
  343. expect(onLog).toHaveBeenCalledWith(expect.objectContaining({ phase: "extract" }));
  344. stdout.write('shell banner\n{"type":"source-server-install-progress","phase":"ver');
  345. stdout.write('ify"}\n{"type":"source-server-install-progress","phase":"ready"}\n');
  346. await vi.waitFor(() => expect(onLog).toHaveBeenCalledWith(expect.objectContaining({ phase: "verify" })));
  347. expect(complete).toBe(false);
  348. expect(onLog).not.toHaveBeenCalledWith(expect.objectContaining({ phase: "ready" }));
  349. stdout.write('{"type":"source-server-install-progress","phase":"restart"}\n');
  350. await vi.waitFor(() => expect(onLog).toHaveBeenCalledWith(expect.objectContaining({ phase: "restart" })));
  351. stdout.end('{"applied":true}\n');
  352. stderr.end();
  353. closed.fire(0);
  354. await install;
  355. expect(complete).toBe(true);
  356. });
  357. it("extracts a unique semver from legacy decorated version output", async () => {
  358. const backend = new FakeBackend("legacy zcode server version v3.7.4\n");
  359. const adapter = createSourceServerTransportAdapter("docker", {
  360. createBackend: async () => backend,
  361. });
  362. await expect(adapter.probe({ kind: "docker", container: "legacy" }, {})).resolves.toMatchObject({
  363. installedVersion: "3.7.4",
  364. });
  365. });
  366. it("extracts one pure semver line despite remote shell stdout noise", async () => {
  367. const backend = new FakeBackend("remote shell banner\nv3.8.0\n");
  368. const adapter = createSourceServerTransportAdapter("docker", {
  369. createBackend: async () => backend,
  370. });
  371. await expect(adapter.probe({ kind: "docker", container: "legacy" }, {})).resolves.toMatchObject({
  372. installedVersion: "3.8.0",
  373. });
  374. });
  375. it("does not treat an unrelated IP address as a legacy Source Server version", async () => {
  376. const backend = new FakeBackend("connected to 10.0.0.1\n");
  377. const adapter = createSourceServerTransportAdapter("docker", {
  378. createBackend: async () => backend,
  379. });
  380. await expect(adapter.probe({ kind: "docker", container: "legacy" }, {})).resolves.toEqual(
  381. expect.not.objectContaining({ installedVersion: expect.anything() }),
  382. );
  383. });
  384. it("preserves a public archive update guard from CLI JSON", async () => {
  385. const backend = new FakeBackend("3.8.0\n", {
  386. stdout: `${JSON.stringify({
  387. ok: false,
  388. code: "source-server-update-running-tasks",
  389. retryable: false,
  390. error: "Running tasks require --force for update",
  391. })}\n`,
  392. exitCode: 1,
  393. });
  394. const adapter = createSourceServerTransportAdapter("docker", {
  395. createBackend: async () => backend,
  396. });
  397. await expect(
  398. adapter.installOrUpdate(
  399. { kind: "docker", container: "busy" },
  400. {
  401. localArchivePath: "/tmp/zcode-server-linux-x64.tar.gz",
  402. target: "linux-x64",
  403. version: "3.9.0",
  404. sha256: "b".repeat(64),
  405. sizeBytes: 2048,
  406. urls: ["https://cdn.example.test/zcode-server-linux-x64.tar.gz"],
  407. },
  408. {},
  409. ),
  410. ).rejects.toMatchObject({
  411. code: "source-server-update-running-tasks",
  412. retryable: false,
  413. message: "Running tasks require --force for update",
  414. });
  415. const updateCommand = backend.commands.find((command) =>
  416. command.includes("update --from-archive"),
  417. );
  418. expect(updateCommand).toMatch(/trap .* EXIT/u);
  419. expect(updateCommand).toContain(".bootstrap-");
  420. expect(updateCommand).toContain("zcode-server.tar.gz");
  421. expect(updateCommand).not.toContain("/tmp/zcode-server-bootstrap-");
  422. expect(updateCommand).toContain('"$HOME/.zcode/server"/.bootstrap-');
  423. });
  424. it.each(targets)(
  425. "surfaces the structured $kind archive error before stderr runtime warnings",
  426. async (target) => {
  427. const error = "Server Core pid 6011 did not terminate after SIGKILL";
  428. const backend = new FakeBackend("3.8.0\n", {
  429. stdout: `${JSON.stringify({ type: "source-server-install-progress", phase: "restart" })}\n${JSON.stringify({ ok: false, error })}\n`,
  430. stderr: "(node:6011) ExperimentalWarning: SQLite is an experimental feature\n",
  431. exitCode: 1,
  432. });
  433. const adapter = createSourceServerTransportAdapter(target.kind, {
  434. createBackend: async () => backend,
  435. });
  436. await expect(
  437. adapter.installOrUpdate(
  438. target,
  439. {
  440. localArchivePath: "/tmp/zcode-server-linux-x64.tar.gz",
  441. target: "linux-x64",
  442. version: "3.9.0",
  443. sha256: "b".repeat(64),
  444. sizeBytes: 2048,
  445. urls: [],
  446. },
  447. {},
  448. ),
  449. ).rejects.toThrow(error);
  450. },
  451. );
  452. it("surfaces the structured daemon error before stderr runtime warnings", async () => {
  453. const backend = new FakeBackend("3.8.1\n", undefined, {
  454. stdout: `${JSON.stringify({
  455. ok: false,
  456. error: "Failed to register Source Server service: user service manager unavailable",
  457. })}\n`,
  458. stderr:
  459. "(node:4823) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n",
  460. exitCode: 1,
  461. });
  462. const adapter = createSourceServerTransportAdapter("ssh", {
  463. createBackend: async () => backend,
  464. });
  465. await expect(
  466. adapter.ensureDaemon({ kind: "ssh", host: "example.com", username: "alice" }, {}),
  467. ).rejects.toThrow("Failed to register Source Server service: user service manager unavailable");
  468. });
  469. describe("SSH gateway that merges remote stderr into stdout", () => {
  470. // 部分 SSH 堡垒机把远端 stderr 合并进 stdout,并在 stdout 结束后才投递,warning 排在结果行之后。
  471. const mergedWarning =
  472. "(node:4823) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n" +
  473. "(Use `node --trace-warnings ...` to show where the warning was created)\n";
  474. const target: RemoteTarget = { kind: "ssh", host: "example.com", username: "alice" };
  475. it("reads the daemon status before the merged warning", async () => {
  476. const backend = new FakeBackend("3.8.1\n", undefined, {
  477. stdout: `${JSON.stringify({ state: "ready", port: 43123, serviceRegistered: true })}\n${mergedWarning}`,
  478. exitCode: 0,
  479. });
  480. const adapter = createSourceServerTransportAdapter("ssh", {
  481. createBackend: async () => backend,
  482. });
  483. await expect(adapter.ensureDaemon(target, {})).resolves.toEqual({
  484. port: 43123,
  485. ingressToken: "ingress-token-value",
  486. });
  487. });
  488. it("surfaces the structured daemon error before the merged warning", async () => {
  489. const backend = new FakeBackend("3.8.1\n", undefined, {
  490. stdout: `${JSON.stringify({ ok: false, error: "Source Server daemon crashed" })}\n${mergedWarning}`,
  491. exitCode: 1,
  492. });
  493. const adapter = createSourceServerTransportAdapter("ssh", {
  494. createBackend: async () => backend,
  495. });
  496. await expect(adapter.ensureDaemon(target, {})).rejects.toThrow("Source Server daemon crashed");
  497. });
  498. it("reads the archive update result before the merged warning", async () => {
  499. const backend = new FakeBackend("3.8.0\n", {
  500. stdout:
  501. `${JSON.stringify({ type: "source-server-install-progress", phase: "restart" })}\n` +
  502. `${JSON.stringify({ ok: true, applied: true })}\n${mergedWarning}`,
  503. exitCode: 0,
  504. });
  505. const adapter = createSourceServerTransportAdapter("ssh", {
  506. createBackend: async () => backend,
  507. });
  508. await expect(
  509. adapter.installOrUpdate(
  510. target,
  511. {
  512. localArchivePath: "/tmp/zcode-server-linux-x64.tar.gz",
  513. target: "linux-x64",
  514. version: "3.9.0",
  515. sha256: "b".repeat(64),
  516. sizeBytes: 2048,
  517. urls: [],
  518. },
  519. {},
  520. ),
  521. ).resolves.toBeUndefined();
  522. });
  523. });
  524. it("fails before uploading when the remote host cannot extract the archive", async () => {
  525. const backend = new FakeBackend("3.8.1\n", undefined, undefined, false);
  526. const adapter = createSourceServerTransportAdapter("ssh", {
  527. createBackend: async () => backend,
  528. });
  529. await expect(
  530. adapter.installOrUpdate(
  531. { kind: "ssh", host: "example.com", username: "alice" },
  532. {
  533. localArchivePath: "/tmp/zcode-server-linux-x64.tar.gz",
  534. target: "linux-x64",
  535. version: "3.8.1",
  536. sha256: "d".repeat(64),
  537. sizeBytes: 4096,
  538. urls: ["https://cdn.example.test/zcode-server-linux-x64.tar.gz"],
  539. },
  540. {},
  541. ),
  542. ).rejects.toThrow("远端服务器缺少 tar");
  543. expect(backend.uploads).toEqual([]);
  544. });
  545. it("downloads and verifies the Source Server archive on the SSH target when requested", async () => {
  546. const backend = new FakeBackend();
  547. const adapter = createSourceServerTransportAdapter("ssh", {
  548. createBackend: async () => backend,
  549. });
  550. const onLog = vi.fn();
  551. await adapter.installOrUpdate(
  552. {
  553. kind: "ssh",
  554. host: "example.com",
  555. username: "alice",
  556. assetInstallMode: "remote-download",
  557. },
  558. {
  559. target: "linux-x64",
  560. version: "3.9.0",
  561. sha256: "c".repeat(64),
  562. sizeBytes: 4096,
  563. urls: ["https://cdn.example.test/zcode-server-linux-x64.tar.gz"],
  564. },
  565. { onLog },
  566. );
  567. expect(onLog).toHaveBeenCalledWith(
  568. expect.objectContaining({ phase: "download", message: expect.stringContaining("1.00 MB/s") }),
  569. );
  570. expect(backend.uploads).toEqual([]);
  571. expect(backend.commands).toEqual(
  572. expect.arrayContaining([
  573. expect.stringContaining("curl -fL"),
  574. expect.stringContaining("sha256sum"),
  575. expect.stringContaining("update --from-archive"),
  576. ]),
  577. );
  578. });
  579. it("uploads an explicitly resolved local development archive despite the SSH download preference", async () => {
  580. const backend = new FakeBackend();
  581. const adapter = createSourceServerTransportAdapter("ssh", {
  582. createBackend: async () => backend,
  583. });
  584. await adapter.installOrUpdate(
  585. {
  586. kind: "ssh",
  587. host: "example.com",
  588. username: "alice",
  589. assetInstallMode: "remote-download",
  590. },
  591. {
  592. localArchivePath: "/tmp/current-development-source-server.tar.gz",
  593. target: "linux-x64",
  594. version: "3.8.1",
  595. sha256: "d".repeat(64),
  596. sizeBytes: 4096,
  597. urls: ["https://cdn.example.test/zcode-server-linux-x64.tar.gz"],
  598. },
  599. {},
  600. );
  601. expect(backend.uploads).toEqual([
  602. {
  603. localPath: "/tmp/current-development-source-server.tar.gz",
  604. remotePath: expect.stringMatching(
  605. /^~\/\.zcode\/server\/\.bootstrap-[^/]+\/zcode-server\.tar\.gz$/u,
  606. ),
  607. },
  608. ]);
  609. expect(backend.commands).not.toEqual(
  610. expect.arrayContaining([expect.stringContaining("curl -fL")]),
  611. );
  612. });
  613. it.each(targets)("附件文件传输复用 $kind 已有 backend 且保留取消/进度参数", async (target) => {
  614. const backend = new FakeBackend();
  615. const upload = vi.spyOn(backend, "upload");
  616. const createBackend = vi.fn(async () => backend);
  617. const adapter = createSourceServerTransportAdapter(target.kind as "ssh" | "wsl" | "docker", {
  618. createBackend,
  619. });
  620. await adapter.probe(target, {});
  621. const transfer = adapter.createFileTransfer(target);
  622. const options = { signal: new AbortController().signal, onProgress: vi.fn() };
  623. await transfer.upload("/local/attachment.txt", "/remote/private/attachment.txt", options);
  624. await transfer.exec("printf attachment");
  625. expect(createBackend).toHaveBeenCalledTimes(1);
  626. expect(upload).toHaveBeenCalledWith(
  627. "/local/attachment.txt",
  628. "/remote/private/attachment.txt",
  629. options,
  630. );
  631. expect(backend.commands.at(-1)).toBe("printf attachment");
  632. adapter.dispose?.();
  633. });