ensure-native-search-deps.mjs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. #!/usr/bin/env node
  2. import { createHash, randomUUID } from "node:crypto";
  3. import {
  4. copyFileSync,
  5. existsSync,
  6. mkdirSync,
  7. mkdtempSync,
  8. readFileSync,
  9. renameSync,
  10. rmSync,
  11. statSync,
  12. } from "node:fs";
  13. import { tmpdir } from "node:os";
  14. import { basename, dirname, join, resolve } from "node:path";
  15. import process from "node:process";
  16. import { fileURLToPath } from "node:url";
  17. import { resolveNativeSearchPrebuiltPlan } from "./native-search-tools-config.mjs";
  18. import {
  19. packageNativeSearchTools,
  20. resolveNativeSearchPackagedArtifactPath,
  21. } from "./package-native-search-tools.mjs";
  22. function sha256(filePath) {
  23. return createHash("sha256").update(readFileSync(filePath)).digest("hex");
  24. }
  25. function assertPackagedArchive(filePath) {
  26. if (!existsSync(filePath) || !statSync(filePath).isFile() || statSync(filePath).size === 0) {
  27. throw new Error(`native search producer did not create archive: ${filePath}`);
  28. }
  29. }
  30. function assertArchiveSha256(filePath, expectedSha256) {
  31. const normalizedExpectedSha256 = String(expectedSha256 ?? "")
  32. .trim()
  33. .toLowerCase();
  34. if (!/^[a-f0-9]{64}$/u.test(normalizedExpectedSha256)) {
  35. throw new Error(`missing native search archive SHA-256: ${filePath}`);
  36. }
  37. const actualSha256 = sha256(filePath);
  38. if (actualSha256 !== normalizedExpectedSha256) {
  39. throw new Error(
  40. `native search archive SHA-256 mismatch: ${filePath}; expected ${normalizedExpectedSha256}, received ${actualSha256}`,
  41. );
  42. }
  43. return actualSha256;
  44. }
  45. function artifactPaths(plan, depsRoot) {
  46. return plan.artifacts.map((artifact) => ({
  47. artifact,
  48. path: resolveNativeSearchPackagedArtifactPath({ artifact, artifactsDir: depsRoot }),
  49. }));
  50. }
  51. export function canPublishNativeSearchDeps(env = process.env) {
  52. return (
  53. env.CI_COMMIT_REF_PROTECTED?.trim().toLowerCase() === "true" ||
  54. env.ZCODE_NATIVE_SEARCH_ALLOW_PUBLISH?.trim() === "1"
  55. );
  56. }
  57. export function publishNativeSearchArchive({ sourcePath, destinationPath, expectedSha256 }) {
  58. assertPackagedArchive(sourcePath);
  59. // Bugfix:固定版本一旦发布就不可覆盖,必须在创建目标目录前拒绝摘要漂移的候选归档。
  60. const sourceSha256 = assertArchiveSha256(sourcePath, expectedSha256);
  61. mkdirSync(dirname(destinationPath), { recursive: true });
  62. if (existsSync(destinationPath)) {
  63. if (sourceSha256 === sha256(destinationPath)) return false;
  64. throw new Error(`refusing to overwrite native search archive: ${destinationPath}`);
  65. }
  66. // 同目录临时文件保证最终 rename 不会让 downloader 看到半截归档。
  67. const temporaryPath = join(
  68. dirname(destinationPath),
  69. `.${basename(destinationPath)}.${process.pid}.${randomUUID()}.tmp`,
  70. );
  71. copyFileSync(sourcePath, temporaryPath);
  72. try {
  73. // 另一个 pipeline 可能在本 job 编译期间先完成发布;固定版本只接受相同字节。
  74. if (existsSync(destinationPath)) {
  75. if (sourceSha256 === sha256(destinationPath)) return false;
  76. throw new Error(`refusing to overwrite native search archive: ${destinationPath}`);
  77. }
  78. renameSync(temporaryPath, destinationPath);
  79. return true;
  80. } catch (error) {
  81. if (existsSync(destinationPath) && sourceSha256 === sha256(destinationPath)) return false;
  82. throw error;
  83. } finally {
  84. rmSync(temporaryPath, { force: true });
  85. }
  86. }
  87. export async function ensureNativeSearchDeps({
  88. platform = process.env.ZCODE_TARGET_OS || process.platform,
  89. arch = process.env.ZCODE_TARGET_ARCH || process.arch,
  90. depsRoot = process.env.ZCODE_NATIVE_SEARCH_DEPS_ROOT,
  91. env = process.env,
  92. allowPublish = canPublishNativeSearchDeps(env),
  93. tempBaseDir = env.ZCODE_CI_TMPDIR || tmpdir(),
  94. packageTools = packageNativeSearchTools,
  95. log = console.log,
  96. prebuiltPlan,
  97. } = {}) {
  98. if (!depsRoot?.trim()) {
  99. throw new Error("ZCODE_NATIVE_SEARCH_DEPS_ROOT is required");
  100. }
  101. const resolvedDepsRoot = resolve(depsRoot);
  102. const plan = prebuiltPlan ?? resolveNativeSearchPrebuiltPlan({ platform, arch });
  103. const expectedArtifacts = artifactPaths(plan, resolvedDepsRoot);
  104. const missingOfficial = expectedArtifacts.filter(
  105. ({ artifact, path }) => artifact.source === "official" && !existsSync(path),
  106. );
  107. log("==> Ensure native search deps");
  108. log(` target: ${plan.platformKey}`);
  109. log(` deps: ${resolvedDepsRoot}`);
  110. // Bugfix:只按文件存在跳过会让错误归档永久占用固定版本路径,后续 prepare 只能反复失败。
  111. for (const { artifact, path } of expectedArtifacts) {
  112. if (existsSync(path)) assertArchiveSha256(path, artifact.archiveSha256);
  113. }
  114. if (missingOfficial.length > 0) {
  115. throw new Error(
  116. `Microsoft native search archives are missing and cannot be produced: ${missingOfficial
  117. .map(({ path }) => path)
  118. .join(", ")}`,
  119. );
  120. }
  121. const missingProducer = expectedArtifacts.filter(
  122. ({ artifact, path }) => artifact.source === "producer" && !existsSync(path),
  123. );
  124. if (missingProducer.length === 0) {
  125. log(` [skip] producer archives already exist for ${plan.platformKey}`);
  126. return { plan, published: [] };
  127. }
  128. if (!allowPublish) {
  129. throw new Error(
  130. `native search producer archives are missing for ${plan.platformKey}: ${missingProducer
  131. .map(({ artifact }) => artifact.releaseFileName)
  132. .join(
  133. ", ",
  134. )}. Run a protected pipeline or set ZCODE_NATIVE_SEARCH_ALLOW_PUBLISH=1 in a trusted pipeline`,
  135. );
  136. }
  137. mkdirSync(resolve(tempBaseDir), { recursive: true });
  138. const workDir = mkdtempSync(
  139. join(resolve(tempBaseDir), `zcode-native-search-deps-${plan.platformKey}-`),
  140. );
  141. const stagingDepsRoot = join(workDir, "deps");
  142. const buildOutputDir = join(workDir, "binaries");
  143. const published = [];
  144. try {
  145. log(
  146. ` [build] ${missingProducer.map(({ artifact }) => artifact.toolId).join(", ")} (${plan.platformKey})`,
  147. );
  148. const packagedPlan = await packageTools({
  149. platform: plan.platform,
  150. arch: plan.arch,
  151. artifactsDir: stagingDepsRoot,
  152. buildOutputDir,
  153. });
  154. for (const { artifact, path: destinationPath } of missingProducer) {
  155. const packagedArtifact = packagedPlan.artifacts.find(
  156. (candidate) =>
  157. candidate.toolId === artifact.toolId &&
  158. candidate.releaseFileName === artifact.releaseFileName,
  159. );
  160. if (!packagedArtifact || packagedArtifact.source !== "producer") {
  161. throw new Error(`producer plan did not include ${artifact.releaseFileName}`);
  162. }
  163. const sourcePath = resolveNativeSearchPackagedArtifactPath({
  164. artifact: packagedArtifact,
  165. artifactsDir: stagingDepsRoot,
  166. });
  167. const didPublish = publishNativeSearchArchive({
  168. sourcePath,
  169. destinationPath,
  170. expectedSha256: artifact.archiveSha256,
  171. });
  172. if (didPublish) published.push(destinationPath);
  173. log(
  174. ` [${didPublish ? "publish" : "race-skip"}] ${artifact.releaseFileName} sha256=${sha256(destinationPath)}`,
  175. );
  176. }
  177. } finally {
  178. rmSync(workDir, { force: true, recursive: true });
  179. }
  180. for (const { artifact, path } of expectedArtifacts) {
  181. if (!existsSync(path)) throw new Error(`native search archive is still missing: ${path}`);
  182. assertArchiveSha256(path, artifact.archiveSha256);
  183. }
  184. log(`==> Done! native search deps (${plan.platformKey})`);
  185. return { plan, published };
  186. }
  187. function readOption(name) {
  188. const prefix = `--${name}=`;
  189. const inline = process.argv.find((arg) => arg.startsWith(prefix));
  190. if (inline) return inline.slice(prefix.length);
  191. const index = process.argv.indexOf(`--${name}`);
  192. return index >= 0 ? process.argv[index + 1] : undefined;
  193. }
  194. async function main() {
  195. await ensureNativeSearchDeps({
  196. platform: readOption("platform") ?? process.env.ZCODE_TARGET_OS ?? process.platform,
  197. arch: readOption("arch") ?? process.env.ZCODE_TARGET_ARCH ?? process.arch,
  198. depsRoot: readOption("deps-root") ?? process.env.ZCODE_NATIVE_SEARCH_DEPS_ROOT,
  199. });
  200. }
  201. if (resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) {
  202. try {
  203. await main();
  204. } catch (error) {
  205. console.error(error instanceof Error ? error.stack : error);
  206. process.exitCode = 1;
  207. }
  208. }