prebuilt-binary-download.mjs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import {
  2. chmodSync,
  3. copyFileSync,
  4. createWriteStream,
  5. mkdirSync,
  6. mkdtempSync,
  7. rmSync,
  8. } from "node:fs";
  9. import http from "node:http";
  10. import https from "node:https";
  11. import { tmpdir } from "node:os";
  12. import { dirname, join } from "node:path";
  13. import process from "node:process";
  14. import {
  15. assertPrebuiltArchiveSha256,
  16. extractPrebuiltArchive,
  17. findPrebuiltBinary,
  18. verifyPrebuiltArchiveSha256,
  19. } from "./prebuilt-binary-extract.mjs";
  20. // 解包、定位与归档验真只保留 prebuilt-binary-extract.mjs 一份实现:内网下载链路与仓库归档链路
  21. // 共用同一套 Windows tar 路径处理和 SHA-256 校验,避免两份实现漂移。继续转出以保持既有调用方接口。
  22. export { extractPrebuiltArchive, findPrebuiltBinary, verifyPrebuiltArchiveSha256 };
  23. const DOWNLOAD_TIMEOUT_MS = 60_000;
  24. const PROXY_DOWNLOAD_HOSTS = new Set(["github.com", "githubusercontent.com"]);
  25. export function shouldUsePrebuiltDownloadProxy(rawUrl) {
  26. const hostname = new URL(rawUrl).hostname.toLowerCase();
  27. return PROXY_DOWNLOAD_HOSTS.has(hostname) || hostname.endsWith(".githubusercontent.com");
  28. }
  29. export async function downloadPrebuiltArchive(url, destinationPath) {
  30. return new Promise((resolvePromise, rejectPromise) => {
  31. const client = url.startsWith("https:") ? https : http;
  32. const file = createWriteStream(destinationPath);
  33. let handled = false;
  34. const cleanupAndReject = (error) => {
  35. if (handled) return;
  36. handled = true;
  37. file.close(() => {
  38. rmSync(destinationPath, { force: true });
  39. rejectPromise(error);
  40. });
  41. };
  42. // Bugfix:默认 deps 是内网镜像,不能因构建机的全局代理被送往外部出口;只有固定的
  43. // GitHub release 主机及其重定向主机读取代理环境,其他下载显式直连。
  44. const requestOptions = shouldUsePrebuiltDownloadProxy(url)
  45. ? { agent: new client.Agent({ proxyEnv: process.env }) }
  46. : { agent: false };
  47. const request = client
  48. .get(url, requestOptions, (response) => {
  49. // Bugfix:响应头成功后连接仍可能在归档写完前中断;此时 request 不再报错,文件也不会
  50. // finish,必须监听响应流本身,才能让 prepare 明确失败并清理半截归档。
  51. response.once("aborted", () => {
  52. cleanupAndReject(new Error(`Download aborted before completion (${url})`));
  53. });
  54. response.once("error", cleanupAndReject);
  55. if (
  56. response.statusCode &&
  57. response.statusCode >= 300 &&
  58. response.statusCode < 400 &&
  59. response.headers.location
  60. ) {
  61. handled = true;
  62. response.resume();
  63. file.close(() => {
  64. rmSync(destinationPath, { force: true });
  65. downloadPrebuiltArchive(response.headers.location, destinationPath).then(
  66. resolvePromise,
  67. rejectPromise,
  68. );
  69. });
  70. return;
  71. }
  72. if (response.statusCode !== 200) {
  73. response.resume();
  74. cleanupAndReject(new Error(`Download failed: HTTP ${response.statusCode} (${url})`));
  75. return;
  76. }
  77. // 保留既有 ripgrep 下载器的原始字节语义,避免 fetch 按 Content-Encoding
  78. // 自动解压后再把已经变化的内容交给 tar/unzip。
  79. response.pipe(file);
  80. file.on("finish", () => {
  81. if (handled) return;
  82. handled = true;
  83. file.close((error) => {
  84. if (error) {
  85. rmSync(destinationPath, { force: true });
  86. rejectPromise(error);
  87. return;
  88. }
  89. resolvePromise();
  90. });
  91. });
  92. })
  93. .on("error", cleanupAndReject);
  94. request.setTimeout(DOWNLOAD_TIMEOUT_MS, () => {
  95. request.destroy(new Error(`Download timed out after ${DOWNLOAD_TIMEOUT_MS}ms (${url})`));
  96. });
  97. file.on("error", cleanupAndReject);
  98. });
  99. }
  100. export async function downloadAndExtractPrebuiltBinary({
  101. archiveExt,
  102. archiveSha256,
  103. binaryName,
  104. binaryPath,
  105. cwd,
  106. downloadUrl,
  107. targetPlatform,
  108. validateBinary,
  109. }) {
  110. const normalizedArchiveSha256 = assertPrebuiltArchiveSha256(archiveSha256);
  111. mkdirSync(dirname(binaryPath), { recursive: true });
  112. mkdirSync(tmpdir(), { recursive: true });
  113. const tempDir = mkdtempSync(join(tmpdir(), "zcode-prebuilt-binary-"));
  114. const archivePath = join(tempDir, `archive.${archiveExt}`);
  115. const extractDir = join(tempDir, "extract");
  116. try {
  117. await downloadPrebuiltArchive(downloadUrl, archivePath);
  118. // Bugfix:release plan 中固定摘要的归档必须先验真,不能只校验下载内容自带的架构。
  119. verifyPrebuiltArchiveSha256(archivePath, normalizedArchiveSha256);
  120. extractPrebuiltArchive({ archivePath, archiveExt, extractDir, cwd });
  121. const extractedBinaryPath = findPrebuiltBinary(extractDir, binaryName);
  122. if (!extractedBinaryPath) {
  123. throw new Error(`Failed to locate ${binaryName} in extracted archive`);
  124. }
  125. // Bugfix: foreign target 不能靠执行下载文件验真,必须在覆盖正式路径前校验临时产物。
  126. await validateBinary?.(extractedBinaryPath);
  127. copyFileSync(extractedBinaryPath, binaryPath);
  128. if (targetPlatform !== "win32") {
  129. chmodSync(binaryPath, 0o755);
  130. }
  131. } finally {
  132. rmSync(tempDir, { force: true, recursive: true });
  133. }
  134. }