sourceServerTransportAdapter.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. const linuxProbeOutput = (libc: string) =>
  208. "__ZCODE_PROBE_PLATFORM__\nLinux\n__ZCODE_PROBE_ARCH__\nx86_64\n__ZCODE_PROBE_KERNEL__\nLinux\n" +
  209. `__ZCODE_PROBE_LIBC__\n${libc}\n__ZCODE_PROBE_INSTALLED__\n0\n__ZCODE_PROBE_END__\n`;
  210. it.each(["2.17", "2.27"])(
  211. "rejects Linux glibc %s before install because the bundled Node runtime needs glibc 2.28",
  212. async (version) => {
  213. // ZCT-2112008575366098944:CentOS 7 先上传 87MB archive,解压后执行 bin/zcode 才报 7 行 not found。
  214. await expect(
  215. probeWith(async () => completedStream(linuxProbeOutput(`glibc ${version}`))),
  216. ).rejects.toMatchObject({
  217. code: "remote-preflight-failed",
  218. message: expect.stringMatching(
  219. new RegExp(`glibc ${version.replace(".", "\\.")}\\b.*glibc 2\\.28`, "u"),
  220. ),
  221. });
  222. },
  223. );
  224. it.each(["glibc 2.28", "glibc 2.39", ""])(
  225. "keeps the install chain when the remote libc reports %j",
  226. async (libc) => {
  227. // 空段代表 musl、缺 getconf 或无法识别:读不到版本时不凭猜测拒绝。
  228. await expect(
  229. probeWith(async () => completedStream(linuxProbeOutput(libc))),
  230. ).resolves.toMatchObject({ platform: "linux", installed: false });
  231. },
  232. );
  233. });
  234. it("probes environment, installation, release identity, version and live status without starting the CLI", async () => {
  235. const backend = new FakeBackend();
  236. const adapter = createSourceServerTransportAdapter("ssh", {
  237. createBackend: async () => backend,
  238. });
  239. await adapter.probe(targets[0]!, {}, { includeReleaseIdentity: true });
  240. const probeCommands = backend.commands.filter((command) =>
  241. command.includes("__ZCODE_PROBE_PLATFORM__"),
  242. );
  243. expect(probeCommands).toHaveLength(1);
  244. expect(probeCommands[0]).toContain("current.json");
  245. expect(probeCommands[0]).toContain("run/status.json");
  246. expect(probeCommands[0]).toContain("getconf GNU_LIBC_VERSION 2>/dev/null");
  247. expect(probeCommands[0]).not.toContain(" status --json");
  248. expect(probeCommands[0]).not.toContain(" --version");
  249. });
  250. it("reuses a just-probed ready daemon status instead of running serve --daemon again", async () => {
  251. const backend = new FakeBackend();
  252. const adapter = createSourceServerTransportAdapter("ssh", {
  253. createBackend: async () => backend,
  254. });
  255. const probe = await adapter.probe(targets[0]!, {});
  256. const commandCountBeforeEnsure = backend.commands.length;
  257. await expect(
  258. adapter.ensureDaemon(targets[0]!, {}, { observedStatus: probe.daemonStatus }),
  259. ).resolves.toEqual({ port: 43123, ingressToken: "ingress-token-value" });
  260. expect(backend.commands.slice(commandCountBeforeEnsure)).not.toEqual(
  261. expect.arrayContaining([expect.stringContaining("'serve' '--daemon'")]),
  262. );
  263. });
  264. function contract(name: string, target: RemoteTarget): void {
  265. describe(`${name} Source Server Transport contract`, () => {
  266. it("implements the common probe/install/daemon/channel/exec behavior", async () => {
  267. const backend = new FakeBackend();
  268. const adapter: SourceServerTransportAdapter = createSourceServerTransportAdapter(
  269. target.kind as "ssh" | "wsl" | "docker",
  270. { createBackend: async () => backend },
  271. );
  272. await expect(adapter.probe(target, {})).resolves.toMatchObject({
  273. platform: "linux",
  274. arch: "x64",
  275. installed: true,
  276. installedVersion: "3.8.0",
  277. daemonStatus: { state: "ready", port: 43123 },
  278. });
  279. await adapter.installOrUpdate(
  280. target,
  281. {
  282. localArchivePath: "/tmp/zcode-server-linux-x64.tar.gz",
  283. target: "linux-x64",
  284. version: "3.8.0",
  285. sha256: "a".repeat(64),
  286. sizeBytes: 1024,
  287. urls: ["https://cdn.example.test/zcode-server-linux-x64.tar.gz"],
  288. },
  289. {},
  290. { force: true },
  291. );
  292. expect(backend.uploads).toHaveLength(1);
  293. expect(backend.uploads[0]?.remotePath).toMatch(
  294. /^~\/\.zcode\/server\/\.bootstrap-[^/]+\/zcode-server\.tar\.gz$/u,
  295. );
  296. expect(backend.uploads[0]?.remotePath).not.toContain("/tmp/");
  297. const prepareCommand = backend.commands.find(
  298. (command) => command.includes("mkdir -p") && command.includes(".bootstrap-"),
  299. );
  300. expect(prepareCommand).toContain('"$HOME/.zcode/server"/.bootstrap-*');
  301. expect(prepareCommand).toContain("1800000");
  302. expect(prepareCommand).toContain("date +%s");
  303. const updateCommand = backend.commands.find((command) =>
  304. command.includes("update --from-archive"),
  305. );
  306. expect(updateCommand).toContain("--force");
  307. if (target.kind === "ssh") {
  308. expect(updateCommand).not.toContain("ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1");
  309. } else {
  310. expect(updateCommand).toContain("ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1");
  311. }
  312. const daemonLogs: string[] = [];
  313. const ingress = await adapter.ensureDaemon(target, {
  314. onLog: (event) => daemonLogs.push(event.message),
  315. });
  316. expect(ingress).toEqual({
  317. port: 43123,
  318. ingressToken: "ingress-token-value",
  319. });
  320. expect(daemonLogs).toContain(
  321. "Source Server started in detached fallback mode for this remote environment",
  322. );
  323. const serveCommand = backend.commands.find((command) =>
  324. command.includes("'serve' '--daemon'"),
  325. );
  326. if (target.kind === "ssh") {
  327. expect(serveCommand).not.toContain("ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1");
  328. } else {
  329. expect(serveCommand).toContain("ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1");
  330. }
  331. const channel = await adapter.openChannel(target, ingress, {});
  332. const echoed = new Promise<Buffer>((resolve) =>
  333. channel.once("data", (data) => resolve(Buffer.from(data))),
  334. );
  335. channel.write(Buffer.from([0, 1, 2, 255]));
  336. expect(await echoed).toEqual(Buffer.from([0, 1, 2, 255]));
  337. channel.end();
  338. await expect(adapter.exec(target, ["status", "--json"], {})).resolves.toMatchObject({
  339. exitCode: 0,
  340. });
  341. expect(backend.commands.some((command) => command.includes("proxy-stdio"))).toBe(true);
  342. });
  343. });
  344. }
  345. for (const target of targets) contract(target.kind, target);
  346. it.each(targets)("forwards $kind install progress before command completion", async (target) => {
  347. const backend = new FakeBackend();
  348. const originalExec = backend.exec.bind(backend);
  349. const stdout = new PassThrough();
  350. const stderr = new PassThrough();
  351. const closed = new Emitter<number>();
  352. const started = Promise.withResolvers<void>();
  353. vi.spyOn(backend, "exec").mockImplementation(async (command) => {
  354. if (!command.includes("update --from-archive")) return await originalExec(command);
  355. backend.commands.push(command);
  356. started.resolve();
  357. return { stdin: new PassThrough(), stdout, stderr, onClose: closed.event };
  358. });
  359. const adapter = createSourceServerTransportAdapter(target.kind as "ssh" | "wsl" | "docker", {
  360. createBackend: async () => backend,
  361. });
  362. const onLog = vi.fn();
  363. let complete = false;
  364. const install = adapter.installOrUpdate(target, {
  365. localArchivePath: "/tmp/release.tar.gz", target: "linux-x64", version: "3.12.1",
  366. sha256: "a".repeat(64), sizeBytes: 1024, urls: [],
  367. }, { onLog }).then(() => { complete = true; });
  368. await started.promise;
  369. expect(backend.commands.at(-1)).toContain("--progress");
  370. expect(onLog).toHaveBeenCalledWith(expect.objectContaining({ phase: "extract" }));
  371. stdout.write('shell banner\n{"type":"source-server-install-progress","phase":"ver');
  372. stdout.write('ify"}\n{"type":"source-server-install-progress","phase":"ready"}\n');
  373. await vi.waitFor(() => expect(onLog).toHaveBeenCalledWith(expect.objectContaining({ phase: "verify" })));
  374. expect(complete).toBe(false);
  375. expect(onLog).not.toHaveBeenCalledWith(expect.objectContaining({ phase: "ready" }));
  376. stdout.write('{"type":"source-server-install-progress","phase":"restart"}\n');
  377. await vi.waitFor(() => expect(onLog).toHaveBeenCalledWith(expect.objectContaining({ phase: "restart" })));
  378. stdout.end('{"applied":true}\n');
  379. stderr.end();
  380. closed.fire(0);
  381. await install;
  382. expect(complete).toBe(true);
  383. });
  384. it("extracts a unique semver from legacy decorated version output", async () => {
  385. const backend = new FakeBackend("legacy zcode server version v3.7.4\n");
  386. const adapter = createSourceServerTransportAdapter("docker", {
  387. createBackend: async () => backend,
  388. });
  389. await expect(adapter.probe({ kind: "docker", container: "legacy" }, {})).resolves.toMatchObject({
  390. installedVersion: "3.7.4",
  391. });
  392. });
  393. it("extracts one pure semver line despite remote shell stdout noise", async () => {
  394. const backend = new FakeBackend("remote shell banner\nv3.8.0\n");
  395. const adapter = createSourceServerTransportAdapter("docker", {
  396. createBackend: async () => backend,
  397. });
  398. await expect(adapter.probe({ kind: "docker", container: "legacy" }, {})).resolves.toMatchObject({
  399. installedVersion: "3.8.0",
  400. });
  401. });
  402. it("does not treat an unrelated IP address as a legacy Source Server version", async () => {
  403. const backend = new FakeBackend("connected to 10.0.0.1\n");
  404. const adapter = createSourceServerTransportAdapter("docker", {
  405. createBackend: async () => backend,
  406. });
  407. await expect(adapter.probe({ kind: "docker", container: "legacy" }, {})).resolves.toEqual(
  408. expect.not.objectContaining({ installedVersion: expect.anything() }),
  409. );
  410. });
  411. it("preserves a public archive update guard from CLI JSON", async () => {
  412. const backend = new FakeBackend("3.8.0\n", {
  413. stdout: `${JSON.stringify({
  414. ok: false,
  415. code: "source-server-update-running-tasks",
  416. retryable: false,
  417. error: "Running tasks require --force for update",
  418. })}\n`,
  419. exitCode: 1,
  420. });
  421. const adapter = createSourceServerTransportAdapter("docker", {
  422. createBackend: async () => backend,
  423. });
  424. await expect(
  425. adapter.installOrUpdate(
  426. { kind: "docker", container: "busy" },
  427. {
  428. localArchivePath: "/tmp/zcode-server-linux-x64.tar.gz",
  429. target: "linux-x64",
  430. version: "3.9.0",
  431. sha256: "b".repeat(64),
  432. sizeBytes: 2048,
  433. urls: ["https://cdn.example.test/zcode-server-linux-x64.tar.gz"],
  434. },
  435. {},
  436. ),
  437. ).rejects.toMatchObject({
  438. code: "source-server-update-running-tasks",
  439. retryable: false,
  440. message: "Running tasks require --force for update",
  441. });
  442. const updateCommand = backend.commands.find((command) =>
  443. command.includes("update --from-archive"),
  444. );
  445. expect(updateCommand).toMatch(/trap .* EXIT/u);
  446. expect(updateCommand).toContain(".bootstrap-");
  447. expect(updateCommand).toContain("zcode-server.tar.gz");
  448. expect(updateCommand).not.toContain("/tmp/zcode-server-bootstrap-");
  449. expect(updateCommand).toContain('"$HOME/.zcode/server"/.bootstrap-');
  450. });
  451. it.each(targets)(
  452. "surfaces the structured $kind archive error before stderr runtime warnings",
  453. async (target) => {
  454. const error = "Server Core pid 6011 did not terminate after SIGKILL";
  455. const backend = new FakeBackend("3.8.0\n", {
  456. stdout: `${JSON.stringify({ type: "source-server-install-progress", phase: "restart" })}\n${JSON.stringify({ ok: false, error })}\n`,
  457. stderr: "(node:6011) ExperimentalWarning: SQLite is an experimental feature\n",
  458. exitCode: 1,
  459. });
  460. const adapter = createSourceServerTransportAdapter(target.kind, {
  461. createBackend: async () => backend,
  462. });
  463. await expect(
  464. adapter.installOrUpdate(
  465. target,
  466. {
  467. localArchivePath: "/tmp/zcode-server-linux-x64.tar.gz",
  468. target: "linux-x64",
  469. version: "3.9.0",
  470. sha256: "b".repeat(64),
  471. sizeBytes: 2048,
  472. urls: [],
  473. },
  474. {},
  475. ),
  476. ).rejects.toThrow(error);
  477. },
  478. );
  479. it("surfaces the structured daemon error before stderr runtime warnings", async () => {
  480. const backend = new FakeBackend("3.8.1\n", undefined, {
  481. stdout: `${JSON.stringify({
  482. ok: false,
  483. error: "Failed to register Source Server service: user service manager unavailable",
  484. })}\n`,
  485. stderr:
  486. "(node:4823) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n",
  487. exitCode: 1,
  488. });
  489. const adapter = createSourceServerTransportAdapter("ssh", {
  490. createBackend: async () => backend,
  491. });
  492. await expect(
  493. adapter.ensureDaemon({ kind: "ssh", host: "example.com", username: "alice" }, {}),
  494. ).rejects.toThrow("Failed to register Source Server service: user service manager unavailable");
  495. });
  496. describe("SSH gateway that merges remote stderr into stdout", () => {
  497. // 部分 SSH 堡垒机把远端 stderr 合并进 stdout,并在 stdout 结束后才投递,warning 排在结果行之后。
  498. const mergedWarning =
  499. "(node:4823) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n" +
  500. "(Use `node --trace-warnings ...` to show where the warning was created)\n";
  501. const target: RemoteTarget = { kind: "ssh", host: "example.com", username: "alice" };
  502. it("reads the daemon status before the merged warning", async () => {
  503. const backend = new FakeBackend("3.8.1\n", undefined, {
  504. stdout: `${JSON.stringify({ state: "ready", port: 43123, serviceRegistered: true })}\n${mergedWarning}`,
  505. exitCode: 0,
  506. });
  507. const adapter = createSourceServerTransportAdapter("ssh", {
  508. createBackend: async () => backend,
  509. });
  510. await expect(adapter.ensureDaemon(target, {})).resolves.toEqual({
  511. port: 43123,
  512. ingressToken: "ingress-token-value",
  513. });
  514. });
  515. it("surfaces the structured daemon error before the merged warning", async () => {
  516. const backend = new FakeBackend("3.8.1\n", undefined, {
  517. stdout: `${JSON.stringify({ ok: false, error: "Source Server daemon crashed" })}\n${mergedWarning}`,
  518. exitCode: 1,
  519. });
  520. const adapter = createSourceServerTransportAdapter("ssh", {
  521. createBackend: async () => backend,
  522. });
  523. await expect(adapter.ensureDaemon(target, {})).rejects.toThrow("Source Server daemon crashed");
  524. });
  525. it("reads the archive update result before the merged warning", async () => {
  526. const backend = new FakeBackend("3.8.0\n", {
  527. stdout:
  528. `${JSON.stringify({ type: "source-server-install-progress", phase: "restart" })}\n` +
  529. `${JSON.stringify({ ok: true, applied: true })}\n${mergedWarning}`,
  530. exitCode: 0,
  531. });
  532. const adapter = createSourceServerTransportAdapter("ssh", {
  533. createBackend: async () => backend,
  534. });
  535. await expect(
  536. adapter.installOrUpdate(
  537. target,
  538. {
  539. localArchivePath: "/tmp/zcode-server-linux-x64.tar.gz",
  540. target: "linux-x64",
  541. version: "3.9.0",
  542. sha256: "b".repeat(64),
  543. sizeBytes: 2048,
  544. urls: [],
  545. },
  546. {},
  547. ),
  548. ).resolves.toBeUndefined();
  549. });
  550. });
  551. it("fails before uploading when the remote host cannot extract the archive", async () => {
  552. const backend = new FakeBackend("3.8.1\n", undefined, undefined, false);
  553. const adapter = createSourceServerTransportAdapter("ssh", {
  554. createBackend: async () => backend,
  555. });
  556. await expect(
  557. adapter.installOrUpdate(
  558. { kind: "ssh", host: "example.com", username: "alice" },
  559. {
  560. localArchivePath: "/tmp/zcode-server-linux-x64.tar.gz",
  561. target: "linux-x64",
  562. version: "3.8.1",
  563. sha256: "d".repeat(64),
  564. sizeBytes: 4096,
  565. urls: ["https://cdn.example.test/zcode-server-linux-x64.tar.gz"],
  566. },
  567. {},
  568. ),
  569. ).rejects.toThrow("远端服务器缺少 tar");
  570. expect(backend.uploads).toEqual([]);
  571. });
  572. it("downloads and verifies the Source Server archive on the SSH target when requested", async () => {
  573. const backend = new FakeBackend();
  574. const adapter = createSourceServerTransportAdapter("ssh", {
  575. createBackend: async () => backend,
  576. });
  577. const onLog = vi.fn();
  578. await adapter.installOrUpdate(
  579. {
  580. kind: "ssh",
  581. host: "example.com",
  582. username: "alice",
  583. assetInstallMode: "remote-download",
  584. },
  585. {
  586. target: "linux-x64",
  587. version: "3.9.0",
  588. sha256: "c".repeat(64),
  589. sizeBytes: 4096,
  590. urls: ["https://cdn.example.test/zcode-server-linux-x64.tar.gz"],
  591. },
  592. { onLog },
  593. );
  594. expect(onLog).toHaveBeenCalledWith(
  595. expect.objectContaining({ phase: "download", message: expect.stringContaining("1.00 MB/s") }),
  596. );
  597. expect(backend.uploads).toEqual([]);
  598. expect(backend.commands).toEqual(
  599. expect.arrayContaining([
  600. expect.stringContaining("curl -fL"),
  601. expect.stringContaining("sha256sum"),
  602. expect.stringContaining("update --from-archive"),
  603. ]),
  604. );
  605. });
  606. it("uploads an explicitly resolved local development archive despite the SSH download preference", async () => {
  607. const backend = new FakeBackend();
  608. const adapter = createSourceServerTransportAdapter("ssh", {
  609. createBackend: async () => backend,
  610. });
  611. await adapter.installOrUpdate(
  612. {
  613. kind: "ssh",
  614. host: "example.com",
  615. username: "alice",
  616. assetInstallMode: "remote-download",
  617. },
  618. {
  619. localArchivePath: "/tmp/current-development-source-server.tar.gz",
  620. target: "linux-x64",
  621. version: "3.8.1",
  622. sha256: "d".repeat(64),
  623. sizeBytes: 4096,
  624. urls: ["https://cdn.example.test/zcode-server-linux-x64.tar.gz"],
  625. },
  626. {},
  627. );
  628. expect(backend.uploads).toEqual([
  629. {
  630. localPath: "/tmp/current-development-source-server.tar.gz",
  631. remotePath: expect.stringMatching(
  632. /^~\/\.zcode\/server\/\.bootstrap-[^/]+\/zcode-server\.tar\.gz$/u,
  633. ),
  634. },
  635. ]);
  636. expect(backend.commands).not.toEqual(
  637. expect.arrayContaining([expect.stringContaining("curl -fL")]),
  638. );
  639. });
  640. it.each(targets)("附件文件传输复用 $kind 已有 backend 且保留取消/进度参数", async (target) => {
  641. const backend = new FakeBackend();
  642. const upload = vi.spyOn(backend, "upload");
  643. const createBackend = vi.fn(async () => backend);
  644. const adapter = createSourceServerTransportAdapter(target.kind as "ssh" | "wsl" | "docker", {
  645. createBackend,
  646. });
  647. await adapter.probe(target, {});
  648. const transfer = adapter.createFileTransfer(target);
  649. const options = { signal: new AbortController().signal, onProgress: vi.fn() };
  650. await transfer.upload("/local/attachment.txt", "/remote/private/attachment.txt", options);
  651. await transfer.exec("printf attachment");
  652. expect(createBackend).toHaveBeenCalledTimes(1);
  653. expect(upload).toHaveBeenCalledWith(
  654. "/local/attachment.txt",
  655. "/remote/private/attachment.txt",
  656. options,
  657. );
  658. expect(backend.commands.at(-1)).toBe("printf attachment");
  659. adapter.dispose?.();
  660. });