transportAdapter.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. /* eslint-disable max-lines -- Source Server transport 在同一适配器内汇合安装、daemon、channel 与 target 生命周期,继续拆分会割裂取消边界。 */
  2. import { Duplex } from "node:stream";
  3. import {
  4. isPublicZCodeErrorCode,
  5. normalizeRemoteConnectionError,
  6. normalizeRemoteAssetInstallMode,
  7. sourceServerInstallProgressSchema,
  8. type SourceServerInstallProgress,
  9. type PublicZCodeErrorCode,
  10. type RemoteTarget,
  11. } from "@zcode/shared";
  12. import type { IRemoteBackend } from "@zcode/server/remote/backend.js";
  13. import { createRemoteBackend } from "@zcode/server/remote/create-backend.js";
  14. import { detectRemoteTarTool } from "@zcode/server/remote/remoteAssetPreflight.js";
  15. import {
  16. probeSourceServer,
  17. SourceServerProbeEnvironmentError,
  18. } from "@zcode/server/source-server/sourceServerProbe.js";
  19. import { buildSourceServerReleaseDownloadCommand } from "@zcode/server/source-server/sourceServerReleaseDownload.js";
  20. import {
  21. collectCommand,
  22. duplexFromStdio,
  23. quoteShellArg,
  24. readLastJsonLine,
  25. readStructuredCommandCode,
  26. readStructuredCommandError,
  27. throwIfAborted,
  28. type RemoteExecResult,
  29. } from "@zcode/server/source-server/sourceServerTransportRuntime.js";
  30. export type { RemoteExecResult } from "@zcode/server/source-server/sourceServerTransportRuntime.js";
  31. export interface SourceServerProbeResult {
  32. platform: string;
  33. arch: string;
  34. installed: boolean;
  35. installPath?: string;
  36. installedVersion?: string;
  37. installedArchiveSha256?: string;
  38. /** 当前 release 由显式降级安装时,被替换的版本。 */
  39. downgradedFrom?: string;
  40. daemonStatus?: Record<string, unknown> & { state: string; port?: number };
  41. }
  42. export interface SourceServerProbeOptions {
  43. includeReleaseIdentity?: boolean;
  44. }
  45. export interface SourceServerIngressInfo {
  46. port: number;
  47. ingressToken: string;
  48. /** 端口取自 probe 读到的 status.json 快照,本次没有执行 serve --daemon。 */
  49. reusedProbeStatus?: true;
  50. }
  51. export interface ServerReleaseAsset {
  52. localArchivePath?: string;
  53. target: string;
  54. version: string;
  55. sha256: string;
  56. sizeBytes: number;
  57. urls: string[];
  58. }
  59. export interface TransportContext {
  60. signal?: AbortSignal;
  61. onLog?: (event: {
  62. phase: string;
  63. message: string;
  64. progress?: number;
  65. level?: "info" | "warn" | "error";
  66. }) => void;
  67. }
  68. export interface SourceServerInstallOrUpdateOptions {
  69. force?: boolean;
  70. /** 用户已确认把远端切换到更旧版本;方向由远端 CLI 按真实 current 判定。 */
  71. allowDowngrade?: boolean;
  72. }
  73. export interface SourceServerEnsureDaemonOptions {
  74. observedStatus?: SourceServerProbeResult["daemonStatus"];
  75. }
  76. export class SourceServerTransportOperationError extends Error {
  77. public constructor(
  78. message: string,
  79. public readonly code: PublicZCodeErrorCode,
  80. public readonly retryable?: boolean,
  81. ) {
  82. super(message);
  83. this.name = "SourceServerTransportOperationError";
  84. }
  85. }
  86. /**
  87. * 远端 Server CLI `--json` 失败输出 `{ok:false,error,code?,retryable?}`(写在 stdout)。
  88. * 公开错误码必须原样保留给 Host/UI 分类,不能只取 error 文本。
  89. */
  90. function createServerCommandError(result: RemoteExecResult, fallbackMessage: string): Error {
  91. try {
  92. const response = readLastJsonLine(result.stdout);
  93. if (isPublicZCodeErrorCode(response.code)) {
  94. return new SourceServerTransportOperationError(
  95. typeof response.error === "string" && response.error.trim()
  96. ? response.error
  97. : fallbackMessage,
  98. response.code,
  99. typeof response.retryable === "boolean" ? response.retryable : undefined,
  100. );
  101. }
  102. } catch {
  103. // 输出不是 JSON 时按文本诊断处理。
  104. }
  105. // Bug 原因:CLI 的 --json 错误写在 stdout,stderr 可能只有 SQLite warning;
  106. // 安装路径与 daemon 启动复用同一错误解析,避免 warning 覆盖真正的失败原因。
  107. return new Error(
  108. (readStructuredCommandError(result.stdout) ?? result.stderr.trim()) || fallbackMessage,
  109. );
  110. }
  111. /** 读取远端 Server CLI `--json` 命令的最终 JSON;非零退出按 {@link createServerCommandError} 失败。 */
  112. export function readServerCommandResult(
  113. result: RemoteExecResult,
  114. fallbackMessage: string,
  115. ): Record<string, unknown> {
  116. if (result.exitCode !== 0) throw createServerCommandError(result, fallbackMessage);
  117. return readLastJsonLine(result.stdout);
  118. }
  119. export type SourceServerFileTransfer = Pick<IRemoteBackend, "exec" | "upload">;
  120. export interface SourceServerTransportAdapter {
  121. readonly kind: "ssh" | "wsl" | "docker";
  122. /** Host 附件暂存复用当前 target 的 transport,不创建另一条远程连接。 */
  123. createFileTransfer(target: RemoteTarget): SourceServerFileTransfer;
  124. /** 取消单个连接目标的底层 transport,防止超时 flight 迟到注册为在线 Source。 */
  125. cancel?(target: RemoteTarget): void;
  126. probe(
  127. target: RemoteTarget,
  128. context: TransportContext,
  129. options?: SourceServerProbeOptions,
  130. ): Promise<SourceServerProbeResult>;
  131. installOrUpdate(
  132. target: RemoteTarget,
  133. release: ServerReleaseAsset,
  134. context: TransportContext,
  135. options?: SourceServerInstallOrUpdateOptions,
  136. ): Promise<void>;
  137. ensureDaemon(
  138. target: RemoteTarget,
  139. context: TransportContext,
  140. options?: SourceServerEnsureDaemonOptions,
  141. ): Promise<SourceServerIngressInfo>;
  142. openChannel(
  143. target: RemoteTarget,
  144. ingress: SourceServerIngressInfo,
  145. context: TransportContext,
  146. ): Promise<Duplex>;
  147. exec(target: RemoteTarget, argv: string[], context: TransportContext): Promise<RemoteExecResult>;
  148. dispose?(): void;
  149. }
  150. export interface CreateSourceServerTransportAdapterOptions {
  151. createBackend?: (target: RemoteTarget) => Promise<IRemoteBackend>;
  152. }
  153. const SERVER_ROOT_READ_PATH = "~/.zcode/server";
  154. const SERVER_ROOT_SHELL = '"$HOME/.zcode/server"';
  155. const SERVER_BIN_SHELL = '"$HOME/.zcode/server/bin/zcode"';
  156. const STALE_BOOTSTRAP_AGE_MS = 30 * 60 * 1_000;
  157. const INSTALL_PROGRESS_MESSAGES: Record<SourceServerInstallProgress["phase"], string> = {
  158. "verify-archive": "Verifying Source Server archive",
  159. extract: "Extracting Source Server files",
  160. verify: "Verifying Source Server files",
  161. restart: "Restarting Source Server",
  162. };
  163. type DirectChannelBackend = IRemoteBackend & {
  164. openDirectTcpChannel?: (port: number) => Promise<Duplex>;
  165. };
  166. class BackendSourceServerTransportAdapter implements SourceServerTransportAdapter {
  167. private readonly backends = new WeakMap<object, Promise<IRemoteBackend>>();
  168. private readonly backendPromises = new Set<Promise<IRemoteBackend>>();
  169. public constructor(
  170. public readonly kind: "ssh" | "wsl" | "docker",
  171. private readonly createBackend: (target: RemoteTarget) => Promise<IRemoteBackend>,
  172. ) {}
  173. public createFileTransfer(target: RemoteTarget): SourceServerFileTransfer {
  174. // R3 全转发遗漏了 desktop localPath 的跨机边界;只复用已有 backend 的文件原语。
  175. const backend = this.getBackend(target);
  176. return {
  177. exec: async (command) => (await backend).exec(command),
  178. upload: async (localPath, remotePath, options) =>
  179. (await backend).upload(localPath, remotePath, options),
  180. };
  181. }
  182. public async probe(
  183. target: RemoteTarget,
  184. context: TransportContext,
  185. options: SourceServerProbeOptions = {},
  186. ): Promise<SourceServerProbeResult> {
  187. throwIfAborted(context.signal);
  188. const backend = await this.getBackend(target);
  189. try {
  190. return await probeSourceServer(backend, context, options);
  191. } catch (error) {
  192. // Bug 原因:catch 对所有失败都套 preflight 阶段兜底,握手超时、握手前断开等未识别的
  193. // 传输失败被报成“设备环境不满足安装要求”;断线恢复耗尽预算时横幅也沿用该误报。
  194. // 只有远端环境检查本身失败才是预检失败,传输失败识别不了就归入未知。
  195. const failure = normalizeRemoteConnectionError(
  196. error,
  197. error instanceof SourceServerProbeEnvironmentError ? "preflight" : undefined,
  198. );
  199. throw Object.assign(error instanceof Error ? error : new Error(failure.message), failure);
  200. }
  201. }
  202. public async installOrUpdate(
  203. target: RemoteTarget,
  204. release: ServerReleaseAsset,
  205. context: TransportContext,
  206. options: SourceServerInstallOrUpdateOptions = {},
  207. ): Promise<void> {
  208. let phase = "preflight";
  209. try {
  210. await this.installRelease(
  211. target,
  212. release,
  213. {
  214. ...context,
  215. onLog: (event) => {
  216. phase = event.phase;
  217. context.onLog?.(event);
  218. },
  219. },
  220. options,
  221. );
  222. } catch (error) {
  223. const failure = normalizeRemoteConnectionError(error, phase);
  224. throw Object.assign(error instanceof Error ? error : new Error(failure.message), failure);
  225. }
  226. }
  227. private async installRelease(
  228. target: RemoteTarget,
  229. release: ServerReleaseAsset,
  230. context: TransportContext,
  231. options: SourceServerInstallOrUpdateOptions,
  232. ): Promise<void> {
  233. throwIfAborted(context.signal);
  234. const backend = await this.getBackend(target);
  235. const operationId = `${process.pid}-${Date.now()}`;
  236. const bootstrapRootShell = `${SERVER_ROOT_SHELL}/.bootstrap-${operationId}`;
  237. const bootstrapDirShell = `${bootstrapRootShell}/extract`;
  238. const remoteArchive = `~/.zcode/server/.bootstrap-${operationId}/zcode-server.tar.gz`;
  239. const remoteArchiveShell = `${bootstrapRootShell}/zcode-server.tar.gz`;
  240. const cleanupCommand = `rm -rf ${bootstrapRootShell}`;
  241. const cleanupStaleBootstrapRootsCommand =
  242. "now_ms=$(($(date +%s) * 1000)); " +
  243. `for candidate in ${SERVER_ROOT_SHELL}/.bootstrap-*; do ` +
  244. '[ -d "$candidate" ] || continue; ' +
  245. "name=${candidate##*/}; " +
  246. "created_ms=${name##*-}; " +
  247. 'case "$created_ms" in ""|*[!0-9]*) continue ;; esac; ' +
  248. "age_ms=$((now_ms - created_ms)); " +
  249. `[ "$age_ms" -le ${STALE_BOOTSTRAP_AGE_MS} ] || rm -rf -- "$candidate"; ` +
  250. "done";
  251. const prepareBootstrapRoot = async (): Promise<void> => {
  252. const result = await collectCommand(
  253. await backend.exec(
  254. // Bug 原因:Controller 在 SFTP/upload 中被强制退出时,JS catch 和远端 EXIT trap
  255. // 都没有机会运行,Server root 会永久积累数十 MiB 的半包。下次安装只回收带合法
  256. // epoch 后缀且超过 30 分钟的私有 staging;新鲜并发操作和未知目录一律保留。
  257. `${cleanupStaleBootstrapRootsCommand} && rm -rf ${bootstrapRootShell} && mkdir -p ${bootstrapRootShell}`,
  258. ),
  259. );
  260. if (result.exitCode !== 0) {
  261. throw new Error(result.stderr.trim() || "Source Server bootstrap staging failed");
  262. }
  263. };
  264. // Bug 原因:R3 切换完整 archive 后曾无条件走 Desktop upload,SSH 表单保存的
  265. // remote-download 变成无效选项。这里只分流 archive 获取位置,后续仍汇合到同一 installer。
  266. const remoteDownload =
  267. target.kind === "ssh" &&
  268. normalizeRemoteAssetInstallMode(target.assetInstallMode) === "remote-download" &&
  269. // Bug 原因:开发态 resolver 已固定本轮本地 archive;若仍按 Profile 偏好直下,
  270. // bootstrap 产物会被 CDN 同版本 release 替换。显式本地路径拥有更高的制品来源优先级。
  271. !release.localArchivePath;
  272. if (remoteDownload) {
  273. context.onLog?.({
  274. phase: "download",
  275. message: `Downloading Source Server ${release.version} on remote host`,
  276. });
  277. const downloadCommand = await buildSourceServerReleaseDownloadCommand({
  278. backend,
  279. release,
  280. remoteArchive,
  281. onLog: (message) => context.onLog?.({ phase: "download", message }),
  282. });
  283. await prepareBootstrapRoot();
  284. const downloadResult = await collectCommand(await backend.exec(downloadCommand), (line) => {
  285. if (/^download progress:/iu.test(line.trim()))
  286. context.onLog?.({ phase: "download", message: line.trim() });
  287. });
  288. if (downloadResult.exitCode !== 0) {
  289. await collectCommand(await backend.exec(cleanupCommand)).catch(() => undefined);
  290. throw new Error(
  291. downloadResult.stderr.trim() || "Remote Source Server archive download failed",
  292. );
  293. }
  294. } else {
  295. if (!release.localArchivePath) {
  296. throw new Error("Source Server local archive is unavailable for upload");
  297. }
  298. // Bug 原因:本地下载上传路径过去不做 tar preflight,会先传完整 archive,
  299. // 最后才在远端解压阶段失败;且旧提示错误地建议用户切回同样需要 tar 的本地上传。
  300. context.onLog?.({
  301. phase: "preflight",
  302. message: "Checking remote installation prerequisites",
  303. });
  304. await detectRemoteTarTool(backend, {
  305. log: (message) => context.onLog?.({ phase: "preflight", message: String(message) }),
  306. });
  307. await prepareBootstrapRoot();
  308. context.onLog?.({
  309. phase: "upload",
  310. message: `Uploading Source Server ${release.version}`,
  311. });
  312. const uploadStartedAt = Date.now();
  313. try {
  314. await backend.upload(release.localArchivePath, remoteArchive, {
  315. signal: context.signal,
  316. onProgress: ({ uploadedBytes, totalBytes }) =>
  317. context.onLog?.({
  318. phase: "upload",
  319. message: `upload progress: ${(totalBytes > 0 ? (uploadedBytes / totalBytes) * 100 : 0).toFixed(1)}% (${(uploadedBytes / 1048576).toFixed(1)}/${(totalBytes / 1048576).toFixed(1)} MB, ${(uploadedBytes / 1048576 / Math.max(0.001, (Date.now() - uploadStartedAt) / 1000)).toFixed(2)} MB/s)`,
  320. progress: totalBytes > 0 ? uploadedBytes / totalBytes : 0,
  321. }),
  322. });
  323. } catch (error) {
  324. await collectCommand(await backend.exec(cleanupCommand)).catch(() => undefined);
  325. throw error;
  326. }
  327. }
  328. context.onLog?.({ phase: "extract", message: INSTALL_PROGRESS_MESSAGES.extract });
  329. const command = [
  330. "set -eu",
  331. // Bug 原因:running-task guard 让 update 非零退出后,`&& rm` 永远不会执行,远端
  332. // archive 与 bootstrap staging 会持续残留。EXIT trap 覆盖成功、guard、解压失败和中断。
  333. `trap ${quoteShellArg(cleanupCommand)} EXIT`,
  334. // Bug 原因:安全加固/最小服务器常把 /tmp 设为 noexec 或很小的 tmpfs。过去虽把
  335. // 解压目录移到 Server root,75MB archive 仍先写 /tmp,容量不足时上传到 90% 才
  336. // EPIPE。archive 与可执行 bootstrap 必须一起位于同一私有 Server staging root。
  337. `rm -rf ${bootstrapDirShell}`,
  338. `mkdir -p ${bootstrapDirShell}`,
  339. `tar -xzf ${remoteArchiveShell} -C ${bootstrapDirShell} --strip-components=1`,
  340. // Bug 原因:update 现在会重启完整 daemon;若不把既有 transport 能力边界传给目标
  341. // bootstrap CLI,WSL/Docker 会在 handoff 时误尝试注册不可用的 systemd user service。
  342. `${this.kind === "ssh" ? "" : "ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1 "}${bootstrapDirShell}/bin/zcode update --from-archive ${remoteArchiveShell}${options.force ? " --force" : ""}${options.allowDowngrade ? " --allow-downgrade" : ""} --server-root ${SERVER_ROOT_SHELL} --json --progress --prepare-credentials`,
  343. ].join(" && ");
  344. // 上传完成后命令仍需解压、整树校验和 daemon 换代;必须实时消费阶段,不能等退出才显示。
  345. const result = await collectCommand(await backend.exec(command), (line) => {
  346. let value: unknown;
  347. try {
  348. value = JSON.parse(line);
  349. } catch {
  350. return;
  351. }
  352. const event = sourceServerInstallProgressSchema.safeParse(value);
  353. if (event.success) {
  354. context.onLog?.({
  355. phase: event.data.phase,
  356. message: INSTALL_PROGRESS_MESSAGES[event.data.phase],
  357. });
  358. }
  359. });
  360. if (result.exitCode !== 0) {
  361. throw createServerCommandError(result, "Source Server archive installation failed");
  362. }
  363. const response = readLastJsonLine(result.stdout);
  364. if (response.ok === false || response.applied !== true) {
  365. throw new Error("Source Server archive installation did not apply the release");
  366. }
  367. context.onLog?.({
  368. phase: "install",
  369. message: `Source Server ${release.version} installed`,
  370. });
  371. }
  372. public async ensureDaemon(
  373. target: RemoteTarget,
  374. context: TransportContext,
  375. options: SourceServerEnsureDaemonOptions = {},
  376. ): Promise<SourceServerIngressInfo> {
  377. throwIfAborted(context.signal);
  378. let status = options.observedStatus;
  379. const observedReady =
  380. status?.state === "ready" && Number.isInteger(status.port) && (status.port as number) > 0;
  381. if (!observedReady) {
  382. context.onLog?.({ phase: "daemon", message: "Starting Source Server" });
  383. const result = await this.exec(
  384. target,
  385. ["serve", "--daemon", "--json", "--prepare-credentials"],
  386. context,
  387. );
  388. if (result.exitCode !== 0) {
  389. // Bug 原因:Server CLI 的 --json 错误写在 stdout,Node 运行时 warning 写在 stderr。
  390. // 旧逻辑只取 stderr,最终把 SQLite warning 当成连接根因展示给用户。
  391. const message =
  392. (readStructuredCommandError(result.stdout) ?? result.stderr.trim()) ||
  393. "Source Server daemon failed to start";
  394. // CLI 失败信息会追加 Core 的失败原因;CLI 已按原首句带码时用该码,不让详情文本改判类别。
  395. const code = readStructuredCommandCode(result.stdout);
  396. throw code ? new SourceServerTransportOperationError(message, code) : new Error(message);
  397. }
  398. status = readLastJsonLine(result.stdout) as SourceServerProbeResult["daemonStatus"];
  399. }
  400. // Bug 原因:probe 刚确认 ready 后仍重复执行 serve --daemon,会多占一个远端 round-trip,
  401. // 让冷启动在 10 秒预算边缘失败。ready status 只复用端口;ingress token 仍每次重新读取。
  402. if (!status) throw new Error("Source Server daemon status is unavailable");
  403. const port = status.port;
  404. if (!Number.isInteger(port) || (port as number) <= 0) {
  405. throw new Error("Source Server daemon did not report a valid ingress port");
  406. }
  407. // Bug 原因:复用 probe 已确认就绪的 daemon 时也按 serviceRegistered 打印
  408. // “started in detached fallback mode”,日志读起来像每次连接都另起了一个实例。
  409. // 启动方式只在本次实际执行 serve --daemon 时报告。
  410. if (observedReady) {
  411. context.onLog?.({ phase: "daemon", message: "Reusing running Source Server" });
  412. } else if (status.serviceRegistered === false) {
  413. // Bug 原因:systemd 装载失败后 CLI 改用 fallback,原因只在本次输出的 serviceFallbackReason 里;
  414. // 不写进连接日志,用户和排障都看不出这次为什么没有用 OS 用户服务。脱敏由连接日志统一处理。
  415. const fallbackReason =
  416. typeof status.serviceFallbackReason === "string" ? status.serviceFallbackReason.trim() : "";
  417. context.onLog?.({
  418. phase: "daemon",
  419. message: `Source Server started in detached fallback mode for this remote environment${fallbackReason ? ` (${fallbackReason})` : ""}`,
  420. });
  421. } else if (status.serviceRegistered === true) {
  422. context.onLog?.({
  423. phase: "daemon",
  424. message: "Source Server registered with the remote OS user service manager",
  425. });
  426. }
  427. const backend = await this.getBackend(target);
  428. const ingressToken = (
  429. await backend.readFile(`${SERVER_ROOT_READ_PATH}/run/ingress-token`)
  430. ).trim();
  431. if (!ingressToken) throw new Error("Source Server ingress token is missing");
  432. return {
  433. port: port as number,
  434. ingressToken,
  435. ...(observedReady ? { reusedProbeStatus: true } : {}),
  436. };
  437. }
  438. public async openChannel(
  439. target: RemoteTarget,
  440. ingress: SourceServerIngressInfo,
  441. context: TransportContext,
  442. ): Promise<Duplex> {
  443. throwIfAborted(context.signal);
  444. const backend = (await this.getBackend(target)) as DirectChannelBackend;
  445. if (this.kind === "ssh" && backend.openDirectTcpChannel) {
  446. try {
  447. return await backend.openDirectTcpChannel(ingress.port);
  448. } catch (error) {
  449. context.onLog?.({
  450. phase: "channel",
  451. message: `SSH direct-tcpip unavailable; using proxy-stdio (${error instanceof Error ? error.message : String(error)})`,
  452. });
  453. }
  454. }
  455. return duplexFromStdio(
  456. await backend.exec(
  457. `${SERVER_BIN_SHELL} server proxy-stdio --server-root ${SERVER_ROOT_SHELL}`,
  458. ),
  459. );
  460. }
  461. public async exec(
  462. target: RemoteTarget,
  463. argv: string[],
  464. context: TransportContext,
  465. ): Promise<RemoteExecResult> {
  466. throwIfAborted(context.signal);
  467. const backend = await this.getBackend(target);
  468. const hasServerRoot = argv.includes("--server-root");
  469. // `restart` 会在远端重新执行 serve --daemon,必须与它一样保持 detached fallback(R2 §8.1)。
  470. const startsDaemon =
  471. (argv[0] === "serve" && argv.includes("--daemon")) || argv[0] === "restart";
  472. const daemonEnvironment =
  473. this.kind !== "ssh" && startsDaemon ? "ZCODE_SERVER_SKIP_SERVICE_REGISTRATION=1 " : "";
  474. const command = [
  475. // Bug 原因:WSL/Docker 没有稳定的用户级服务管理器;若沿用 SSH 命令会尝试
  476. // 注册 systemd user service 并在常见环境中失败。两者必须显式进入 detached fallback。
  477. `${daemonEnvironment}${SERVER_BIN_SHELL}`,
  478. ...argv.map(quoteShellArg),
  479. ...(hasServerRoot ? [] : ["--server-root", SERVER_ROOT_SHELL]),
  480. ].join(" ");
  481. return await collectCommand(await backend.exec(command));
  482. }
  483. public dispose(): void {
  484. for (const backend of this.backendPromises) {
  485. void backend.then(
  486. (resolved) => resolved.dispose(),
  487. () => undefined,
  488. );
  489. }
  490. this.backendPromises.clear();
  491. }
  492. public cancel(target: RemoteTarget): void {
  493. if (target.kind !== this.kind) return;
  494. const key = target as object;
  495. const backend = this.backends.get(key);
  496. if (!backend) return;
  497. // Bug 原因:启动 10 秒超时过去只 reject 外层 Promise,SSH 握手仍在后台继续,
  498. // 迟到后会把 Source 注册 online。精确摘除本 target backend,后续手动重试可新建 transport。
  499. this.backends.delete(key);
  500. this.backendPromises.delete(backend);
  501. void backend.then(
  502. (resolved) => resolved.dispose(),
  503. () => undefined,
  504. );
  505. }
  506. private async getBackend(target: RemoteTarget): Promise<IRemoteBackend> {
  507. if (target.kind !== this.kind) {
  508. throw new Error(`Transport ${this.kind} cannot handle target ${target.kind}`);
  509. }
  510. const key = target as object;
  511. let backend = this.backends.get(key);
  512. if (!backend) {
  513. backend = this.createBackend(target);
  514. this.backends.set(key, backend);
  515. this.backendPromises.add(backend);
  516. }
  517. return await backend;
  518. }
  519. }
  520. export function createSourceServerTransportAdapter(
  521. kind: "ssh" | "wsl" | "docker",
  522. options: CreateSourceServerTransportAdapterOptions = {},
  523. ): SourceServerTransportAdapter {
  524. return new BackendSourceServerTransportAdapter(
  525. kind,
  526. options.createBackend ?? createRemoteBackend,
  527. );
  528. }