ssh-version-policy-fixture.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import { execFile } from "node:child_process";
  2. import { createReadStream } from "node:fs";
  3. import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
  4. import { join, resolve } from "node:path";
  5. import { pipeline } from "node:stream/promises";
  6. import { promisify } from "node:util";
  7. import { Client } from "ssh2";
  8. import { sourceServerReleaseDescriptorSchema } from "@zcode/shared";
  9. import type { SSHConnectionConfig } from "#e2e/helpers/ssh-remote-p0";
  10. const run = promisify(execFile);
  11. /** 完整真实 runtime 的版本元数据变体;只测试兼容策略,不冒充旧版本业务实现。 */
  12. export async function prepareVersionPolicyArchive(options: {
  13. installedSha: string;
  14. version: string;
  15. minimum: string;
  16. }) {
  17. const runId = process.env.ZCODE_E2E_RUN_ID;
  18. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  19. if (!runId || !artifactDir) throw new Error("版本 fixture 缺少隔离 run 身份");
  20. const desktopRoot = resolve(import.meta.dirname, "../../..");
  21. const { version } = JSON.parse(
  22. await readFile(resolve(desktopRoot, "../../package.json"), "utf8"),
  23. );
  24. const releaseRoot = join(desktopRoot, ".e2e-cache", runId, "mock-cdn/releases", version);
  25. const descriptor = sourceServerReleaseDescriptorSchema.parse(
  26. JSON.parse(await readFile(join(releaseRoot, "source-server-release.json"), "utf8")),
  27. );
  28. const entry = descriptor.archives.find((entry) => entry.sha256 === options.installedSha);
  29. if (!entry) throw new Error("实际安装的 archive 不属于本轮构建");
  30. await mkdir(artifactDir, { recursive: true });
  31. const work = await mkdtemp(join(artifactDir, "version-policy-"));
  32. const original = join(releaseRoot, entry.fileName);
  33. const list = await run("tar", ["-tzf", original], { maxBuffer: 1 << 24 });
  34. const top = list.stdout.split("\n")[0]?.split("/")[0];
  35. if (!top || top === "." || top === "..") throw new Error("版本 archive 顶层路径非法");
  36. await run("tar", ["-xzf", original, "-C", work], { timeout: 300_000 });
  37. const manifestPath = join(work, top, "manifest.json");
  38. const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
  39. manifest.appVersion = options.version;
  40. // 元数据变体必须重新走完整包安装,不能复用原 server-runtime 组件摘要。
  41. delete manifest.components;
  42. await writeFile(manifestPath, JSON.stringify(manifest, null, 2));
  43. for (const file of ["server-core.js", "server-cli.js"]) {
  44. const path = join(work, top, "runtime", file);
  45. let source = await readFile(path, "utf8");
  46. let versionCount = 0;
  47. // 编译入口可能先声明变量、再在模块初始化器中赋值;不能只匹配内联 var 声明。
  48. source = source.replace(/(ZCODE_VERSION\d* = true \? )"[^"]+"/gu, (_match, prefix) => {
  49. versionCount += 1;
  50. return prefix + JSON.stringify(options.version);
  51. });
  52. if (!versionCount) throw new Error(`版本 fixture 未找到 ${file} 的编译版本常量`);
  53. source = source.replace(
  54. /(ZCODE_MIN_COMPATIBLE_VERSION\d* = true \? )"[^"]+"/gu,
  55. (_match, prefix) => prefix + JSON.stringify(options.minimum),
  56. );
  57. await writeFile(path, source);
  58. }
  59. const archive = join(work, `version-${options.version}.tar.gz`);
  60. await run("tar", ["-czf", archive, "-C", work, top], { timeout: 300_000 });
  61. return archive;
  62. }
  63. export async function uploadSSHFixtureFile(
  64. config: SSHConnectionConfig,
  65. localPath: string,
  66. remotePath: string,
  67. ) {
  68. const client = new Client();
  69. try {
  70. await new Promise<void>((resolve, reject) => {
  71. client.once("error", reject);
  72. client.once("ready", resolve);
  73. client.connect({
  74. host: config.host,
  75. port: config.port,
  76. username: config.username,
  77. password: config.password,
  78. readyTimeout: 30_000,
  79. });
  80. });
  81. const sftp = await new Promise<import("ssh2").SFTPWrapper>((resolve, reject) =>
  82. client.sftp((error, sftp) => (error ? reject(error) : resolve(sftp))),
  83. );
  84. await pipeline(createReadStream(localPath), sftp.createWriteStream(remotePath));
  85. } finally {
  86. client.end();
  87. }
  88. }
  89. /** 旧主链没有 Server runtime;SQLite 故障 fixture 使用已验真构建内的 Node,独立于业务进程。 */
  90. export async function prepareSSHHistoryFixtureNode(
  91. config: SSHConnectionConfig,
  92. remoteRoot: string,
  93. ): Promise<string> {
  94. const desktopRoot = resolve(import.meta.dirname, "../../..");
  95. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  96. if (!artifactDir) throw new Error("历史 Node fixture 缺少隔离 artifact 目录");
  97. const { version } = JSON.parse(
  98. await readFile(resolve(desktopRoot, "../../package.json"), "utf8"),
  99. );
  100. const releases = join(desktopRoot, "mock-cdn/releases", version);
  101. const descriptor = sourceServerReleaseDescriptorSchema.parse(
  102. JSON.parse(await readFile(join(releases, "source-server-release.json"), "utf8")),
  103. );
  104. const { runSSHCommand } = await import("#e2e/helpers/ssh-remote-p0");
  105. const architecture = await runSSHCommand(config, "uname -m");
  106. const target =
  107. architecture.stdout.trim() === "x86_64"
  108. ? "linux-x64"
  109. : architecture.stdout.trim() === "aarch64"
  110. ? "linux-arm64"
  111. : null;
  112. const entry = descriptor.archives.find((item) => item.target === target);
  113. if (architecture.code !== 0 || !entry) throw new Error("历史 Node fixture 不支持该 SSH 架构");
  114. const work = await mkdtemp(join(artifactDir, "history-node-"));
  115. const archive = join(releases, entry.fileName);
  116. const listing = await run("tar", ["-tzf", archive], { maxBuffer: 1 << 24 });
  117. const nodeEntry = listing.stdout.split("\n").find((item) => /^[^/]+\/runtime\/node$/u.test(item));
  118. if (!nodeEntry) throw new Error("历史 Node fixture 构建包缺少 Node");
  119. await run("tar", ["-xzf", archive, "-C", work, nodeEntry], { timeout: 120_000 });
  120. const remoteNode = `${remoteRoot}/fixture-node`;
  121. await uploadSSHFixtureFile(config, join(work, nodeEntry), remoteNode);
  122. if ((await runSSHCommand(config, `chmod 700 '${remoteNode}'`)).code !== 0)
  123. throw new Error("历史 Node fixture 无法设执行权限");
  124. return remoteNode;
  125. }