prepare-native-search-tools.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { dirname, join } from "node:path";
  5. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  6. const mocks = vi.hoisted(() => ({
  7. intranetConfigured: true,
  8. downloadNativeSearchTools: vi.fn(),
  9. }));
  10. // 用可切换的替身模拟“依赖源已配置 / 未配置时抛错”两种环境;已配置时显式注入中性主机,
  11. // 不依赖仓库默认的内网地址(开源导出里默认地址为空),其余导出保持真实实现。
  12. vi.mock("../../../scripts/intranetDefaults.mjs", async (importOriginal) => {
  13. const actual = await importOriginal<Record<string, unknown>>();
  14. const resolveActual = actual.resolveIntranetDepsBaseUrl as (env?: NodeJS.ProcessEnv) => string;
  15. return {
  16. ...actual,
  17. resolveIntranetDepsBaseUrl: (env?: NodeJS.ProcessEnv) => {
  18. if (!mocks.intranetConfigured) {
  19. throw new Error("Configure ZCODE_DEPS_BASE_URL or INTRANET_MACHINE_HOST");
  20. }
  21. return resolveActual({ INTRANET_MACHINE_HOST: "intranet-deps.example", ...env });
  22. },
  23. };
  24. });
  25. vi.mock("../../../scripts/download-native-search-tools.mjs", () => ({
  26. downloadNativeSearchTools: mocks.downloadNativeSearchTools,
  27. }));
  28. import {
  29. NATIVE_SEARCH_DEPENDENCIES_DIR,
  30. LEGACY_REMOTE_RIPGREP_ARCHIVE_SHA256_BY_TARGET as CONFIG_LEGACY_SHA256,
  31. LEGACY_REMOTE_RIPGREP_VERSION as CONFIG_LEGACY_VERSION,
  32. resolveNativeSearchArtifactSource,
  33. resolveNativeSearchPrebuiltPlan,
  34. } from "../../../scripts/native-search-tools-config.mjs";
  35. import { prepareNativeSearchTools } from "../../../scripts/prepare-native-search-tools.mjs";
  36. import { verifyPrebuiltArchiveSha256 } from "../../../scripts/prebuilt-binary-extract.mjs";
  37. import {
  38. LEGACY_REMOTE_RIPGREP_ARCHIVE_SHA256_BY_TARGET,
  39. LEGACY_REMOTE_RIPGREP_VERSION,
  40. resolveRemoteNativeSearchPrebuiltPlan,
  41. } from "../../../scripts/remote-native-search-tools-config.mjs";
  42. type PrebuiltArtifact = {
  43. toolId: string;
  44. release: string;
  45. archivePath: string;
  46. archiveSha256: string;
  47. binaryPath: string;
  48. downloadUrl?: string;
  49. };
  50. type PrebuiltPlan = { platformKey: string; artifacts: PrebuiltArtifact[] };
  51. const localTargets = [
  52. ["darwin", "arm64"],
  53. ["darwin", "x64"],
  54. ["linux", "arm64"],
  55. ["linux", "x64"],
  56. ["win32", "arm64"],
  57. ["win32", "x64"],
  58. ] as const;
  59. const remoteTargets = localTargets.filter(([platform]) => platform !== "win32");
  60. const temporaryDirectories: string[] = [];
  61. async function createTemporaryDirectory(): Promise<string> {
  62. const directory = await mkdtemp(join(tmpdir(), "zcode-prepare-native-search-"));
  63. temporaryDirectories.push(directory);
  64. return directory;
  65. }
  66. function readSources(artifact: PrebuiltArtifact): {
  67. binary: { origin: string; toolId: string };
  68. } {
  69. return JSON.parse(readFileSync(join(dirname(artifact.binaryPath), "SOURCES.json"), "utf8"));
  70. }
  71. beforeEach(() => {
  72. mocks.intranetConfigured = true;
  73. mocks.downloadNativeSearchTools.mockReset();
  74. });
  75. afterEach(async () => {
  76. await Promise.all(
  77. temporaryDirectories
  78. .splice(0)
  79. .map((directory) => rm(directory, { recursive: true, force: true })),
  80. );
  81. });
  82. describe("native search 归档来源判定", () => {
  83. it("内网依赖源已配置时判定为 intranet,计划同时带下载地址与同名仓库归档", () => {
  84. expect(resolveNativeSearchArtifactSource({})).toBe("intranet");
  85. for (const [platform, arch] of localTargets) {
  86. const plan = resolveNativeSearchPrebuiltPlan({ platform, arch, env: {} }) as PrebuiltPlan;
  87. for (const artifact of plan.artifacts) {
  88. expect(
  89. artifact.downloadUrl?.endsWith(`/${artifact.archivePath.split(/[\\/]/).pop()}`),
  90. ).toBe(true);
  91. }
  92. }
  93. });
  94. it("显式 NATIVE_SEARCH_TOOLS_DOWNLOAD_BASE_URL 在依赖源未配置时仍走 intranet", () => {
  95. mocks.intranetConfigured = false;
  96. expect(
  97. resolveNativeSearchArtifactSource({
  98. NATIVE_SEARCH_TOOLS_DOWNLOAD_BASE_URL: "https://deps.example.test/native-search-tools",
  99. }),
  100. ).toBe("intranet");
  101. });
  102. it("依赖源未配置时判定为 repository,计划不再解析下载地址", () => {
  103. mocks.intranetConfigured = false;
  104. expect(resolveNativeSearchArtifactSource({})).toBe("repository");
  105. const plan = resolveNativeSearchPrebuiltPlan({
  106. platform: "linux",
  107. arch: "x64",
  108. env: {},
  109. }) as PrebuiltPlan;
  110. expect(plan.artifacts.every((artifact) => artifact.downloadUrl === undefined)).toBe(true);
  111. });
  112. it("本地与远端计划引用的仓库归档全部存在且摘要与固定值一致", () => {
  113. const plans = [
  114. ...localTargets.map(([platform, arch]) =>
  115. resolveNativeSearchPrebuiltPlan({ platform, arch }),
  116. ),
  117. ...remoteTargets.map(([platform, arch]) =>
  118. resolveRemoteNativeSearchPrebuiltPlan({ platform, arch }),
  119. ),
  120. ] as PrebuiltPlan[];
  121. for (const plan of plans) {
  122. for (const artifact of plan.artifacts) {
  123. expect(artifact.archivePath.startsWith(NATIVE_SEARCH_DEPENDENCIES_DIR)).toBe(true);
  124. expect(() =>
  125. verifyPrebuiltArchiveSha256(artifact.archivePath, artifact.archiveSha256),
  126. ).not.toThrow();
  127. }
  128. }
  129. // legacy rg13 常量只有一个所有者,远端配置只转出。
  130. expect(LEGACY_REMOTE_RIPGREP_VERSION).toBe(CONFIG_LEGACY_VERSION);
  131. expect(LEGACY_REMOTE_RIPGREP_ARCHIVE_SHA256_BY_TARGET).toBe(CONFIG_LEGACY_SHA256);
  132. const darwinRemote = resolveRemoteNativeSearchPrebuiltPlan({
  133. platform: "darwin",
  134. arch: "arm64",
  135. }) as PrebuiltPlan;
  136. expect(darwinRemote.artifacts.map(({ toolId, release }) => [toolId, release])).toEqual([
  137. ["ripgrep", CONFIG_LEGACY_VERSION],
  138. ]);
  139. });
  140. });
  141. describe("prepareNativeSearchTools", () => {
  142. it("intranet 来源原样委托既有下载链路,并在工具目录写入 intranet-mirror 声明", async () => {
  143. const outputDir = join(await createTemporaryDirectory(), "tools");
  144. const env = { NATIVE_SEARCH_TOOLS_DOWNLOAD_BASE_URL: "https://deps.example.test/native" };
  145. mocks.downloadNativeSearchTools.mockImplementation(async (options) => {
  146. const plan = resolveNativeSearchPrebuiltPlan(options) as PrebuiltPlan;
  147. for (const artifact of plan.artifacts) {
  148. mkdirSync(dirname(artifact.binaryPath), { recursive: true });
  149. writeFileSync(artifact.binaryPath, `${artifact.toolId}-downloaded`);
  150. }
  151. return plan;
  152. });
  153. const plan = (await prepareNativeSearchTools({
  154. platform: "linux",
  155. arch: "x64",
  156. outputDir,
  157. env,
  158. })) as PrebuiltPlan;
  159. expect(mocks.downloadNativeSearchTools).toHaveBeenCalledTimes(1);
  160. expect(mocks.downloadNativeSearchTools).toHaveBeenCalledWith({
  161. platform: "linux",
  162. arch: "x64",
  163. outputDir,
  164. env,
  165. prebuiltPlan: undefined,
  166. });
  167. for (const artifact of plan.artifacts) {
  168. expect(existsSync(join(dirname(artifact.binaryPath), "THIRD-PARTY-NOTICES.txt"))).toBe(true);
  169. expect(readSources(artifact).binary).toMatchObject({
  170. origin: "intranet-mirror",
  171. toolId: artifact.toolId,
  172. });
  173. }
  174. });
  175. it("repository 来源解包仓库归档,不触发下载;缓存命中时跳过解包但刷新声明", async () => {
  176. mocks.intranetConfigured = false;
  177. const outputDir = join(await createTemporaryDirectory(), "tools");
  178. const plan = (await prepareNativeSearchTools({
  179. platform: "linux",
  180. arch: "x64",
  181. outputDir,
  182. env: {},
  183. })) as PrebuiltPlan;
  184. expect(mocks.downloadNativeSearchTools).not.toHaveBeenCalled();
  185. expect(plan.artifacts.map(({ toolId }) => toolId)).toEqual(["bfs", "ugrep", "ripgrep"]);
  186. for (const artifact of plan.artifacts) {
  187. expect(existsSync(artifact.binaryPath)).toBe(true);
  188. expect(readSources(artifact).binary.origin).toBe("repository-archive");
  189. rmSync(join(dirname(artifact.binaryPath), "THIRD-PARTY-NOTICES.txt"));
  190. }
  191. const binaryBeforeCacheHit = readFileSync(plan.artifacts[0].binaryPath);
  192. await prepareNativeSearchTools({ platform: "linux", arch: "x64", outputDir, env: {} });
  193. expect(readFileSync(plan.artifacts[0].binaryPath)).toEqual(binaryBeforeCacheHit);
  194. for (const artifact of plan.artifacts) {
  195. expect(existsSync(join(dirname(artifact.binaryPath), "THIRD-PARTY-NOTICES.txt"))).toBe(true);
  196. }
  197. });
  198. it("仓库归档被改动时在替换任何产物前失败", async () => {
  199. const root = await createTemporaryDirectory();
  200. const dependenciesDir = join(root, "dependencies");
  201. cpSync(NATIVE_SEARCH_DEPENDENCIES_DIR, dependenciesDir, { recursive: true });
  202. const plan = resolveNativeSearchPrebuiltPlan({
  203. platform: "linux",
  204. arch: "x64",
  205. outputDir: join(root, "tools"),
  206. dependenciesDir,
  207. }) as PrebuiltPlan;
  208. writeFileSync(plan.artifacts[1].archivePath, "tampered");
  209. await expect(
  210. prepareNativeSearchTools({ prebuiltPlan: plan, source: "repository" }),
  211. ).rejects.toThrow(/Invalid local native search archive/u);
  212. expect(plan.artifacts.some((artifact) => existsSync(artifact.binaryPath))).toBe(false);
  213. });
  214. });