Skip to main content

uv_python_managed/
downloads.rs

1//! Discover available Python downloads and fetch their distributions.
2
3use std::borrow::Cow;
4use std::collections::HashMap;
5use std::fmt::Display;
6use std::io::Read;
7use std::path::{Path, PathBuf};
8use std::pin::Pin;
9use std::str::FromStr;
10use std::task::{Context, Poll};
11use std::time::{Duration, Instant, SystemTimeError};
12use std::{env, io};
13use uv_python_types::{PythonDownloadRequest, PythonDownloadRequestError};
14
15use futures::TryStreamExt;
16use itertools::Itertools;
17use owo_colors::OwoColorize;
18use reqwest::Response;
19use reqwest_retry::RetryError;
20use reqwest_retry::policies::ExponentialBackoff;
21use serde::{Deserialize, Serialize};
22use tempfile::TempDir;
23use thiserror::Error;
24use tokio::io::{AsyncRead, AsyncWriteExt, BufWriter, ReadBuf};
25use tokio_util::compat::FuturesAsyncReadCompatExt;
26use tokio_util::either::Either;
27use tracing::{debug, instrument};
28use url::Url;
29use zstd::stream::read::Decoder;
30
31use uv_cache::{Cache, CacheBucket};
32use uv_cache_key::cache_digest;
33use uv_client::{
34    BaseClient, BaseClientBuilder, CacheControl, CachedClient, CachedClientError, ClientBuildError,
35    Connectivity, RetriableError, RetryState, WrappedReqwestError, fetch_with_url_fallback,
36    retryable_on_request_failure,
37};
38use uv_distribution_filename::{ExtensionError, SourceDistExtension};
39use uv_extract::hash::Hasher;
40use uv_fs::{Simplified, rename_with_retry};
41use uv_macros::DebugNoInline;
42use uv_platform::{Arch, Libc, Os, Platform};
43use uv_pypi_types::{Digest, HashAlgorithm, HashDigest};
44use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError};
45use uv_static::{
46    EnvVars, TarBackend, astral_mirror_base_url, astral_mirror_url_from_env,
47    custom_astral_mirror_url,
48};
49
50use uv_python_types::{
51    ImplementationName, LenientImplementationName, PythonDownloadMirrors, PythonInstallationKey,
52    PythonVariant, PythonVersion,
53};
54
55#[derive(Error, DebugNoInline)]
56pub enum Error {
57    #[error(transparent)]
58    Io(#[from] io::Error),
59    #[error(transparent)]
60    Request(#[from] PythonDownloadRequestError),
61    #[error("Expected download URL (`{0}`) to end in a supported file extension: {1}")]
62    MissingExtension(String, ExtensionError),
63    #[error("Failed to download `{0}`")]
64    NetworkError(DisplaySafeUrl, #[source] WrappedReqwestError),
65    #[error(
66        "Request failed after {retries} {subject} in {duration:.1}s",
67        subject = if *retries > 1 { "retries" } else { "retry" },
68        duration = duration.as_secs_f32()
69    )]
70    NetworkErrorWithRetries {
71        #[source]
72        err: Box<Self>,
73        retries: u32,
74        duration: Duration,
75    },
76    #[error("Failed to download `{0}`")]
77    NetworkMiddlewareError(DisplaySafeUrl, #[source] anyhow::Error),
78    #[error("Failed to extract archive: {0}")]
79    ExtractError(String, #[source] uv_extract::Error),
80    #[error("Failed to hash installation")]
81    HashExhaustion(#[source] io::Error),
82    #[error("Hash mismatch for `{installation}`\n\nExpected:\n{expected}\n\nComputed:\n{actual}")]
83    HashMismatch {
84        installation: String,
85        expected: String,
86        actual: String,
87    },
88    #[error("Invalid download URL")]
89    InvalidUrl(#[from] DisplaySafeUrlError),
90    #[error("Invalid download URL: {0}")]
91    InvalidUrlFormat(DisplaySafeUrl),
92    #[error("Invalid path in file URL: {0}")]
93    InvalidFileUrl(String),
94    #[error("Failed to create download directory")]
95    DownloadDirError(#[source] io::Error),
96    #[error("Failed to copy to: {0}", to.user_display())]
97    CopyError {
98        to: PathBuf,
99        #[source]
100        err: io::Error,
101    },
102    #[error("Failed to read managed Python installation directory: {0}", dir.user_display())]
103    ReadError {
104        dir: PathBuf,
105        #[source]
106        err: io::Error,
107    },
108    #[error("No download found for request: {}", _0.green())]
109    NoDownloadFound(PythonDownloadRequest),
110    #[error("A mirror was provided via `{0}`, but the URL does not match the expected format: {1}")]
111    Mirror(&'static str, DisplaySafeUrl),
112    #[error("Unable to parse the JSON Python download list at `{0}`")]
113    InvalidPythonDownloadsJSON(String, #[source] serde_json::Error),
114    #[error("This version of uv is too old to support the JSON Python download list at `{0}`")]
115    UnsupportedPythonDownloadsJSON(String),
116    #[error("Error while fetching remote python downloads json from `{0}`")]
117    FetchingPythonDownloadsJSONError(String, #[source] Box<Self>),
118    #[error(transparent)]
119    RemotePythonDownloadsJSONClient(Box<uv_client::Error>),
120    #[error(transparent)]
121    ClientBuild(Box<ClientBuildError>),
122    #[error("An offline Python installation was requested, but `{file}` (from `{url}`) is missing in `{}`", python_builds_dir.user_display())]
123    OfflinePythonMissing {
124        file: Box<PythonInstallationKey>,
125        url: Box<DisplaySafeUrl>,
126        python_builds_dir: PathBuf,
127    },
128    #[error("No download URL found for Python")]
129    NoPythonDownloadUrlFound,
130    #[error(transparent)]
131    SystemTime(#[from] SystemTimeError),
132}
133
134impl RetriableError for Error {
135    // Return the number of retries that were made to complete this request before this error was
136    // returned.
137    //
138    // Note that e.g. 3 retries equates to 4 attempts.
139    fn retries(&self) -> u32 {
140        // Unfortunately different variants of `Error` track retry counts in different ways. We
141        // could consider unifying the variants we handle here in `Error::from_reqwest_middleware`
142        // instead, but both approaches will be fragile as new variants get added over time.
143        if let Self::NetworkErrorWithRetries { retries, .. } = self {
144            return *retries;
145        }
146        if let Self::NetworkMiddlewareError(_, anyhow_error) = self
147            && let Some(RetryError::WithRetries { retries, .. }) =
148                anyhow_error.downcast_ref::<RetryError>()
149        {
150            return *retries;
151        }
152        0
153    }
154
155    /// Returns `true` if trying an alternative URL makes sense after this error.
156    ///
157    /// HTTP-level failures (4xx, 5xx) and connection-level failures return `true`.
158    /// Hash mismatches, extraction failures, and similar post-download errors return `false`
159    /// because switching to a different host would not fix them.
160    fn should_try_next_url(&self) -> bool {
161        match self {
162            // There are two primary reasons to try an alternative URL:
163            // - HTTP/DNS/TCP/etc errors due to a mirror being blocked at various layers
164            // - HTTP 404s from the mirror, which may mean the next URL still works
165            // So we catch all network-level errors here.
166            Self::NetworkError(..)
167            | Self::NetworkMiddlewareError(..)
168            | Self::NetworkErrorWithRetries { .. } => true,
169            // `Io` uses `#[error(transparent)]`, so `source()` delegates to the inner error's
170            // own source rather than returning the `io::Error` itself. We must unwrap it
171            // explicitly so that `retryable_on_request_failure` can inspect the io error kind.
172            Self::Io(err) => retryable_on_request_failure(err).is_some(),
173            _ => false,
174        }
175    }
176
177    fn into_retried(self, retries: u32, duration: Duration) -> Self {
178        Self::NetworkErrorWithRetries {
179            err: Box::new(self),
180            retries,
181            duration,
182        }
183    }
184}
185
186/// The URL prefix used by `python-build-standalone` releases on GitHub.
187const CPYTHON_DOWNLOADS_URL_PREFIX: &str =
188    "https://github.com/astral-sh/python-build-standalone/releases/download/";
189
190/// The suffix appended to the Astral mirror base for `python-build-standalone` releases.
191const CPYTHON_MIRROR_SUFFIX: &str = "/github/python-build-standalone/releases/download/";
192
193/// Return the Astral mirror base URL for CPython downloads.
194fn effective_cpython_mirror(astral_mirror_url: Option<&str>) -> String {
195    format!(
196        "{}{CPYTHON_MIRROR_SUFFIX}",
197        astral_mirror_base_url(astral_mirror_url)
198    )
199}
200
201#[derive(Debug, PartialEq, Eq, Clone, Hash)]
202pub struct ManagedPythonDownload {
203    key: PythonInstallationKey,
204    url: Cow<'static, str>,
205    sha256: Option<Digest<32>>,
206    build: Option<&'static str>,
207}
208
209const BUILTIN_PYTHON_DOWNLOADS_ZSTD: &[u8] =
210    include_bytes!(concat!(env!("OUT_DIR"), "/download-metadata.json.zst"));
211
212pub struct ManagedPythonDownloadList {
213    downloads: Vec<ManagedPythonDownload>,
214}
215
216#[derive(Debug, Deserialize, Serialize, Clone)]
217struct JsonPythonDownload {
218    name: String,
219    arch: JsonArch,
220    os: String,
221    libc: String,
222    major: u8,
223    minor: u8,
224    patch: u8,
225    prerelease: Option<String>,
226    url: String,
227    sha256: Option<Digest<32>>,
228    variant: Option<String>,
229    build: Option<String>,
230}
231
232#[derive(Debug, Deserialize, Serialize, Clone)]
233struct JsonArch {
234    family: String,
235    variant: Option<String>,
236}
237
238#[derive(Debug, Clone)]
239pub enum DownloadResult {
240    AlreadyAvailable(PathBuf),
241    Fetched(PathBuf),
242}
243
244impl ManagedPythonDownloadList {
245    /// Iterate over all [`ManagedPythonDownload`]s.
246    fn iter_all(&self) -> impl Iterator<Item = &ManagedPythonDownload> {
247        self.downloads.iter()
248    }
249
250    /// Iterate over all [`ManagedPythonDownload`]s that match the request.
251    pub fn iter_matching(
252        &self,
253        request: &PythonDownloadRequest,
254    ) -> impl Iterator<Item = &ManagedPythonDownload> {
255        self.iter_all()
256            .filter(move |download| download.matches_request(request))
257    }
258
259    /// Return the first [`ManagedPythonDownload`] matching a request, if any.
260    ///
261    /// If there is no stable version matching the request, a compatible pre-release version will
262    /// be searched for — even if a pre-release was not explicitly requested.
263    pub fn find(&self, request: &PythonDownloadRequest) -> Result<&ManagedPythonDownload, Error> {
264        if let Some(download) = self.iter_matching(request).next() {
265            return Ok(download);
266        }
267
268        if !request.allows_prereleases()
269            && let Some(download) = self
270                .iter_matching(&request.clone().with_prereleases(true))
271                .next()
272        {
273            return Ok(download);
274        }
275
276        Err(Error::NoDownloadFound(request.clone()))
277    }
278
279    /// Load available Python distributions from a provided source or the compiled-in list.
280    ///
281    /// Returns an error if the provided list could not be opened, if the JSON is invalid, or if it
282    /// does not parse into the expected data structure.
283    pub async fn new(
284        client_builder: &BaseClientBuilder<'_>,
285        cache: &Cache,
286        python_downloads_json_url: Option<&str>,
287    ) -> Result<Self, Error> {
288        // file:// URLs are converted to local file reads, and we also support parsing bare
289        // filenames like "/tmp/py.json", not just "file:///tmp/py.json". Note that
290        // "C:\Temp\py.json" should be considered a filename, even though Url::parse would
291        // successfully misparse it as a URL with scheme "C".
292        enum Source<'a> {
293            BuiltIn,
294            Path(Cow<'a, Path>),
295            Http(DisplaySafeUrl),
296        }
297
298        let json_source = if let Some(url_or_path) = python_downloads_json_url {
299            if let Ok(url) = DisplaySafeUrl::parse(url_or_path) {
300                match url.scheme() {
301                    "http" | "https" => Source::Http(url),
302                    "file" => Source::Path(Cow::Owned(
303                        url.to_file_path().or(Err(Error::InvalidUrlFormat(url)))?,
304                    )),
305                    _ => Source::Path(Cow::Borrowed(Path::new(url_or_path))),
306                }
307            } else {
308                Source::Path(Cow::Borrowed(Path::new(url_or_path)))
309            }
310        } else {
311            Source::BuiltIn
312        };
313
314        let json_downloads = match json_source {
315            Source::BuiltIn => parse_builtin_downloads()?,
316            Source::Path(ref path) => parse_downloads_json(
317                &fs_err::read(path.as_ref())?,
318                path.to_string_lossy().to_string(),
319            )?,
320            Source::Http(ref url) => {
321                let client = CachedClient::new(
322                    client_builder
323                        .build()
324                        .map_err(|err| Error::ClientBuild(Box::new(err)))?,
325                );
326                fetch_downloads_from_url(&client, cache, url)
327                    .await
328                    .map_err(|e| match e {
329                        e @ (Error::InvalidPythonDownloadsJSON(..)
330                        | Error::UnsupportedPythonDownloadsJSON(..)) => e,
331                        e => Error::FetchingPythonDownloadsJSONError(url.to_string(), Box::new(e)),
332                    })?
333            }
334        };
335
336        let downloads = parse_json_downloads(json_downloads);
337        Ok(Self { downloads })
338    }
339
340    /// Load available Python distributions from the compiled-in list only.
341    /// for testing purposes.
342    pub fn new_only_embedded() -> Result<Self, Error> {
343        let json_downloads = parse_builtin_downloads()?;
344        let result = parse_json_downloads(json_downloads);
345        Ok(Self { downloads: result })
346    }
347}
348
349/// Decompress and parse the embedded Python download catalog.
350fn parse_builtin_downloads() -> Result<HashMap<String, JsonPythonDownload>, Error> {
351    let mut json = Vec::new();
352    Decoder::with_buffer(BUILTIN_PYTHON_DOWNLOADS_ZSTD)?.read_to_end(&mut json)?;
353    parse_downloads_json(&json, "EMBEDDED IN THE BINARY".to_owned())
354}
355
356/// Parse the downloads JSON.
357///
358/// `source` is where the JSON came from for error reporting.
359fn parse_downloads_json(
360    buf: &[u8],
361    source: String,
362) -> Result<HashMap<String, JsonPythonDownload>, Error> {
363    match serde_json::from_slice(buf) {
364        Ok(data) => Ok(data),
365        Err(e) => {
366            // As an explicit compatibility mechanism, if there's a top-level "version" key, it
367            // means it's a newer format than we know how to deal with. Before reporting a
368            // parse error about the format of JsonPythonDownload, check for that key. We can do
369            // this by parsing into a Map<String, IgnoredAny> which allows any valid JSON on the
370            // value side. (Because it's zero-sized, Clippy suggests Set<String>, but that won't
371            // have the same parsing effect.)
372            #[expect(clippy::zero_sized_map_values)]
373            if let Ok(keys) = serde_json::from_slice::<HashMap<String, serde::de::IgnoredAny>>(buf)
374                && keys.contains_key("version")
375            {
376                Err(Error::UnsupportedPythonDownloadsJSON(source))
377            } else {
378                Err(Error::InvalidPythonDownloadsJSON(source, e))
379            }
380        }
381    }
382}
383
384async fn fetch_downloads_from_url(
385    client: &CachedClient,
386    cache: &Cache,
387    url: &DisplaySafeUrl,
388) -> Result<HashMap<String, JsonPythonDownload>, Error> {
389    let cache_entry = cache.entry(
390        CacheBucket::Python,
391        "downloads-json",
392        format!("{}.msgpack", cache_digest(&url.as_str())),
393    );
394    let cache_control = match client.uncached().connectivity() {
395        Connectivity::Online => CacheControl::from(cache.freshness(&cache_entry, None, None)?),
396        Connectivity::Offline => CacheControl::AllowStale,
397    };
398
399    let request = client
400        .uncached()
401        .for_host(url)
402        .get(Url::from(url.clone()))
403        .build()
404        .map_err(|err| Error::NetworkError(url.clone(), WrappedReqwestError::from(err)))?;
405
406    let response_callback = async |response: Response, _: &mut RetryState| {
407        let bytes = response
408            .bytes()
409            .await
410            .map_err(|err| Error::NetworkError(url.clone(), WrappedReqwestError::from(err)))?;
411        parse_downloads_json(&bytes, url.to_string())
412    };
413
414    client
415        .get_serde_with_retry(request, &cache_entry, cache_control, response_callback)
416        .await
417        .map_err(|err| match err {
418            CachedClientError::Client(err) => Error::RemotePythonDownloadsJSONClient(Box::new(err)),
419            CachedClientError::Callback {
420                err,
421                retries,
422                duration,
423            } => match err {
424                // Avoid double-wrapping errors.
425                err @ (Error::InvalidPythonDownloadsJSON(..)
426                | Error::UnsupportedPythonDownloadsJSON(..)) => err,
427                err if retries > 0 => err.into_retried(retries, duration),
428                err => err,
429            },
430        })
431}
432
433impl ManagedPythonDownload {
434    pub(crate) fn url(&self) -> &Cow<'static, str> {
435        &self.url
436    }
437
438    pub fn key(&self) -> &PythonInstallationKey {
439        &self.key
440    }
441
442    fn os(&self) -> &Os {
443        self.key.os()
444    }
445
446    pub(crate) fn sha256(&self) -> Option<&Digest<32>> {
447        self.sha256.as_ref()
448    }
449
450    pub fn build(&self) -> Option<&'static str> {
451        self.build
452    }
453
454    /// Download and extract a Python distribution, retrying on failure.
455    ///
456    /// For CPython without a user-configured mirror, the default Astral mirror is tried first.
457    /// Each attempt tries all URLs in sequence without backoff between them; backoff is only
458    /// applied after all URLs have been exhausted.
459    #[instrument(skip_all, fields(download = % self.key()))]
460    pub async fn fetch_with_retry(
461        &self,
462        client: &BaseClient,
463        retry_policy: &ExponentialBackoff,
464        installation_dir: &Path,
465        scratch_dir: &Path,
466        reinstall: bool,
467        mirrors: PythonDownloadMirrors<'_>,
468        reporter: Option<&dyn Reporter>,
469    ) -> Result<DownloadResult, Error> {
470        let urls = self.download_urls(mirrors)?;
471        let tar_backend = TarBackend::from_env();
472        if urls.is_empty() {
473            return Err(Error::NoPythonDownloadUrlFound);
474        }
475        fetch_with_url_fallback(&urls, *retry_policy, &format!("`{}`", self.key()), |url| {
476            self.fetch_from_url(
477                url,
478                client,
479                installation_dir,
480                scratch_dir,
481                reinstall,
482                reporter,
483                tar_backend,
484            )
485        })
486        .await
487    }
488
489    /// Download and extract a Python distribution from the given URL.
490    async fn fetch_from_url(
491        &self,
492        url: DisplaySafeUrl,
493        client: &BaseClient,
494        installation_dir: &Path,
495        scratch_dir: &Path,
496        reinstall: bool,
497        reporter: Option<&dyn Reporter>,
498        tar_backend: TarBackend,
499    ) -> Result<DownloadResult, Error> {
500        let path = installation_dir.join(self.key().to_string());
501
502        // If it is not a reinstall and the dir already exists, return it.
503        if !reinstall && path.is_dir() {
504            return Ok(DownloadResult::AlreadyAvailable(path));
505        }
506
507        // We improve filesystem compatibility by using neither the URL-encoded `%2B` nor the `+` it
508        // decodes to.
509        let filename = url
510            .path_segments()
511            .ok_or_else(|| Error::InvalidUrlFormat(url.clone()))?
512            .next_back()
513            .ok_or_else(|| Error::InvalidUrlFormat(url.clone()))?
514            .replace("%2B", "-");
515        debug_assert!(
516            filename
517                .chars()
518                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.'),
519            "Unexpected char in filename: {filename}"
520        );
521        let ext = SourceDistExtension::from_path(&filename)
522            .map_err(|err| Error::MissingExtension(url.to_string(), err))?;
523
524        let temp_dir = tempfile::tempdir_in(scratch_dir).map_err(Error::DownloadDirError)?;
525
526        let temp_dir = if let Some(python_builds_dir) =
527            env::var_os(EnvVars::UV_PYTHON_CACHE_DIR).filter(|s| !s.is_empty())
528        {
529            let python_builds_dir = PathBuf::from(python_builds_dir);
530            fs_err::create_dir_all(&python_builds_dir)?;
531            let hash_prefix = match self.sha256.as_ref() {
532                Some(digest) => {
533                    // Shorten the hash to avoid too-long-filename errors
534                    &digest.as_str()[..9]
535                }
536                None => "none",
537            };
538            let target_cache_file = python_builds_dir.join(format!("{hash_prefix}-{filename}"));
539
540            // Download the archive to the cache, or return a reader if we have it in cache.
541            // TODO(konsti): We should "tee" the write so we can do the download-to-cache and unpacking
542            // in one step.
543            let (reader, size): (Box<dyn AsyncRead + Unpin>, Option<u64>) =
544                match fs_err::tokio::File::open(&target_cache_file).await {
545                    Ok(file) => {
546                        debug!(
547                            "Extracting existing `{}`",
548                            target_cache_file.simplified_display()
549                        );
550                        let size = file.metadata().await?.len();
551                        let reader = Box::new(tokio::io::BufReader::new(file));
552                        (reader, Some(size))
553                    }
554                    Err(err) if err.kind() == io::ErrorKind::NotFound => {
555                        // Point the user to which file is missing where and where to download it
556                        if client.connectivity().is_offline() {
557                            return Err(Error::OfflinePythonMissing {
558                                file: Box::new(self.key().clone()),
559                                url: Box::new(url.clone()),
560                                python_builds_dir,
561                            });
562                        }
563
564                        self.download_archive(
565                            &url,
566                            client,
567                            reporter,
568                            &python_builds_dir,
569                            &target_cache_file,
570                        )
571                        .await?;
572
573                        debug!("Extracting `{}`", target_cache_file.simplified_display());
574                        let file = fs_err::tokio::File::open(&target_cache_file).await?;
575                        let size = file.metadata().await?.len();
576                        let reader = Box::new(tokio::io::BufReader::new(file));
577                        (reader, Some(size))
578                    }
579                    Err(err) => return Err(err.into()),
580                };
581
582            // Extract the downloaded archive into a temporary directory.
583            self.extract_reader(
584                reader,
585                temp_dir,
586                &filename,
587                ext,
588                size,
589                reporter,
590                Direction::Extract,
591                tar_backend,
592            )
593            .await?
594        } else {
595            // Avoid overlong log lines
596            debug!("Downloading `{url}`");
597            debug!(
598                "Extracting `{filename}` to temporary location `{}`",
599                temp_dir.path().simplified_display()
600            );
601
602            let (reader, size) = read_url(&url, client).await?;
603            self.extract_reader(
604                reader,
605                temp_dir,
606                &filename,
607                ext,
608                size,
609                reporter,
610                Direction::Download,
611                tar_backend,
612            )
613            .await?
614        };
615
616        // Extract the top-level directory.
617        let mut extracted = match uv_extract::strip_component(temp_dir.path()) {
618            Ok(top_level) => top_level,
619            Err(uv_extract::Error::NonSingularArchive(_)) => temp_dir.path().to_path_buf(),
620            Err(err) => return Err(Error::ExtractError(filename, err)),
621        };
622
623        // If the distribution is a `full` archive, the Python installation is in the `install` directory.
624        if extracted.join("install").is_dir() {
625            extracted = extracted.join("install");
626        // If the distribution is a Pyodide archive, the Python installation is in the `pyodide-root/dist` directory.
627        } else if self.os().is_emscripten() {
628            extracted = extracted.join("pyodide-root").join("dist");
629        }
630
631        #[cfg(unix)]
632        {
633            // Pyodide distributions require all of the supporting files to be alongside the Python
634            // executable, so they don't have a `bin` directory. We create it and link
635            // `bin/pythonX.Y` to `dist/python`.
636            if self.os().is_emscripten() {
637                fs_err::create_dir_all(extracted.join("bin"))?;
638                fs_err::os::unix::fs::symlink(
639                    "../python",
640                    extracted
641                        .join("bin")
642                        .join(format!("python{}.{}", self.key.major, self.key.minor)),
643                )?;
644            }
645
646            // If the distribution is missing a `python` -> `pythonX.Y` symlink, add it.
647            //
648            // We skip for Windows distributions, allowing cross-installs from Unix.
649            //
650            // Pyodide releases never contain this link by default.
651            //
652            // PEP 394 permits it, and python-build-standalone releases after `20240726` include it,
653            // but releases prior to that date do not.
654            if !self.os().is_windows() {
655                match fs_err::os::unix::fs::symlink(
656                    format!("python{}.{}", self.key.major, self.key.minor),
657                    extracted.join("bin").join("python"),
658                ) {
659                    Ok(()) => {}
660                    Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
661                    Err(err) => return Err(err.into()),
662                }
663            }
664        }
665
666        // Remove the target if it already exists.
667        if path.is_dir() {
668            debug!("Removing existing directory: {}", path.user_display());
669            fs_err::tokio::remove_dir_all(&path).await?;
670        }
671
672        // Persist it to the target.
673        debug!(
674            "Moving `{}` to `{}`",
675            extracted.display(),
676            path.user_display()
677        );
678        rename_with_retry(extracted, &path)
679            .await
680            .map_err(|err| Error::CopyError {
681                to: path.clone(),
682                err,
683            })?;
684
685        Ok(DownloadResult::Fetched(path))
686    }
687
688    /// Download the managed Python archive into the cache directory.
689    async fn download_archive(
690        &self,
691        url: &DisplaySafeUrl,
692        client: &BaseClient,
693        reporter: Option<&dyn Reporter>,
694        python_builds_dir: &Path,
695        target_cache_file: &Path,
696    ) -> Result<(), Error> {
697        debug!(
698            "Downloading `{}` to `{}`",
699            url,
700            target_cache_file.simplified_display()
701        );
702
703        let (mut reader, size) = read_url(url, client).await?;
704        let temp_dir = tempfile::tempdir_in(python_builds_dir)?;
705        let temp_file = temp_dir.path().join("download");
706
707        // Download to a temporary file. We verify the hash when unpacking the file.
708        {
709            let mut archive_writer = BufWriter::new(fs_err::tokio::File::create(&temp_file).await?);
710
711            // Download with or without progress bar.
712            if let Some(reporter) = reporter {
713                let key = reporter.on_request_start(Direction::Download, &self.key, size);
714                tokio::io::copy(
715                    &mut ProgressReader::new(reader, key, reporter),
716                    &mut archive_writer,
717                )
718                .await?;
719                reporter.on_request_complete(Direction::Download, key);
720            } else {
721                tokio::io::copy(&mut reader, &mut archive_writer).await?;
722            }
723
724            archive_writer.flush().await?;
725        }
726        // Move the completed file into place, invalidating the `File` instance.
727        match rename_with_retry(&temp_file, target_cache_file).await {
728            Ok(()) => {}
729            Err(_) if target_cache_file.is_file() => {}
730            Err(err) => return Err(err.into()),
731        }
732        Ok(())
733    }
734
735    /// Extract a Python interpreter archive into a (temporary) directory, either from a file or
736    /// from a download stream.
737    async fn extract_reader(
738        &self,
739        reader: impl AsyncRead + Unpin,
740        target: TempDir,
741        filename: &String,
742        ext: SourceDistExtension,
743        size: Option<u64>,
744        reporter: Option<&dyn Reporter>,
745        direction: Direction,
746        tar_backend: TarBackend,
747    ) -> Result<TempDir, Error> {
748        let mut hashers = self
749            .sha256
750            .as_ref()
751            .map(|_| Hasher::from(HashAlgorithm::Sha256));
752        let mut hasher = uv_extract::hash::HashReader::new(reader, hashers.as_mut_slice());
753
754        let target = if let Some(reporter) = reporter {
755            let progress_key = reporter.on_request_start(direction, &self.key, size);
756            let mut reader = ProgressReader::new(&mut hasher, progress_key, reporter);
757            let (target, _) = uv_extract::stream::archive(&mut reader, ext, target, tar_backend)
758                .await
759                .map_err(|err| Error::ExtractError(filename.to_owned(), err))?;
760            reporter.on_request_complete(direction, progress_key);
761            target
762        } else {
763            let (target, _) = uv_extract::stream::archive(&mut hasher, ext, target, tar_backend)
764                .await
765                .map_err(|err| Error::ExtractError(filename.to_owned(), err))?;
766            target
767        };
768        hasher.finish().await.map_err(Error::HashExhaustion)?;
769
770        // Check the hash
771        if let Some((expected, hasher)) = self.sha256.as_ref().zip(hashers) {
772            let actual = HashDigest::from(hasher);
773            if actual.digest() != expected.as_str() {
774                return Err(Error::HashMismatch {
775                    installation: self.key.to_string(),
776                    expected: expected.as_str().to_string(),
777                    actual: actual.digest().to_string(),
778                });
779            }
780        }
781
782        Ok(target)
783    }
784
785    #[cfg(test)]
786    fn python_version(&self) -> PythonVersion {
787        self.key.version()
788    }
789
790    /// Return the ordered list of [`Url`]s to try when downloading the distribution.
791    ///
792    /// For CPython without a user-configured mirror, the default Astral mirror is listed first,
793    /// followed by the canonical GitHub URL as a fallback.
794    ///
795    /// For all other cases (user mirror explicitly set, PyPy, GraalPy, Pyodide), a single URL
796    /// is returned with no fallback.
797    pub fn download_urls(
798        &self,
799        mirrors: PythonDownloadMirrors<'_>,
800    ) -> Result<Vec<DisplaySafeUrl>, Error> {
801        let custom_astral_mirror = astral_mirror_url_from_env();
802        self.download_urls_with_astral_mirror(mirrors, custom_astral_mirror.as_deref())
803    }
804
805    fn download_urls_with_astral_mirror(
806        &self,
807        mirrors: PythonDownloadMirrors<'_>,
808        astral_mirror_url: Option<&str>,
809    ) -> Result<Vec<DisplaySafeUrl>, Error> {
810        let astral_mirror_url = custom_astral_mirror_url(astral_mirror_url);
811        match self.key.implementation().as_ref() {
812            LenientImplementationName::Known(ImplementationName::CPython) => {
813                if let Some(mirror) = mirrors.cpython {
814                    // User-configured mirror: use it exclusively, no automatic fallback.
815                    let Some(suffix) = self.url.strip_prefix(CPYTHON_DOWNLOADS_URL_PREFIX) else {
816                        return Err(Error::Mirror(
817                            EnvVars::UV_PYTHON_INSTALL_MIRROR,
818                            DisplaySafeUrl::parse(&self.url)?,
819                        ));
820                    };
821                    return Ok(vec![DisplaySafeUrl::parse(
822                        format!("{}/{}", mirror.trim_end_matches('/'), suffix).as_str(),
823                    )?]);
824                }
825                // No user mirror: try the default/custom Astral mirror first.
826                if let Some(suffix) = self.url.strip_prefix(CPYTHON_DOWNLOADS_URL_PREFIX) {
827                    let effective_mirror = effective_cpython_mirror(astral_mirror_url);
828                    let mirror_url = DisplaySafeUrl::parse(
829                        format!("{}/{}", effective_mirror.trim_end_matches('/'), suffix).as_str(),
830                    )?;
831                    // When a custom Astral mirror is set, use it exclusively.
832                    if astral_mirror_url.is_some() {
833                        return Ok(vec![mirror_url]);
834                    }
835                    // Otherwise fall back to the canonical GitHub URL.
836                    let canonical_url = DisplaySafeUrl::parse(&self.url)?;
837                    return Ok(vec![mirror_url, canonical_url]);
838                }
839            }
840
841            LenientImplementationName::Known(ImplementationName::PyPy) => {
842                if let Some(mirror) = mirrors.pypy {
843                    let Some(suffix) = self.url.strip_prefix("https://downloads.python.org/pypy/")
844                    else {
845                        return Err(Error::Mirror(
846                            EnvVars::UV_PYPY_INSTALL_MIRROR,
847                            DisplaySafeUrl::parse(&self.url)?,
848                        ));
849                    };
850                    return Ok(vec![DisplaySafeUrl::parse(
851                        format!("{}/{}", mirror.trim_end_matches('/'), suffix).as_str(),
852                    )?]);
853                }
854            }
855
856            LenientImplementationName::Known(ImplementationName::GraalPy) => {
857                if let Some(mirror) = mirrors.graalpy {
858                    let Some(suffix) = self
859                        .url
860                        .strip_prefix("https://github.com/oracle/graalpython/releases/download/")
861                    else {
862                        return Err(Error::Mirror(
863                            EnvVars::UV_GRAALPY_INSTALL_MIRROR,
864                            DisplaySafeUrl::parse(&self.url)?,
865                        ));
866                    };
867                    return Ok(vec![DisplaySafeUrl::parse(
868                        format!("{}/{}", mirror.trim_end_matches('/'), suffix).as_str(),
869                    )?]);
870                }
871            }
872
873            LenientImplementationName::Known(ImplementationName::Pyodide) => {
874                if let Some(mirror) = mirrors.pyodide {
875                    let Some(suffix) = self
876                        .url
877                        .strip_prefix("https://github.com/pyodide/pyodide/releases/download/")
878                    else {
879                        return Err(Error::Mirror(
880                            EnvVars::UV_PYODIDE_INSTALL_MIRROR,
881                            DisplaySafeUrl::parse(&self.url)?,
882                        ));
883                    };
884                    return Ok(vec![DisplaySafeUrl::parse(
885                        format!("{}/{}", mirror.trim_end_matches('/'), suffix).as_str(),
886                    )?]);
887                }
888            }
889
890            _ => {}
891        }
892
893        Ok(vec![DisplaySafeUrl::parse(&self.url)?])
894    }
895
896    /// Whether this download satisfies the requested Python and build.
897    fn matches_request(&self, request: &PythonDownloadRequest) -> bool {
898        // First check the key
899        if !request.satisfied_by_key(self.key()) {
900            return false;
901        }
902
903        // Then check the build if specified
904        if let Some(ref requested_build) = request.build {
905            let Some(download_build) = self.build() else {
906                debug!(
907                    "Skipping download `{}`: a build version was requested but is not available for this download",
908                    self
909                );
910                return false;
911            };
912
913            if download_build != requested_build {
914                debug!(
915                    "Skipping download `{}`: requested build version `{}` does not match download build version `{}`",
916                    self, requested_build, download_build
917                );
918                return false;
919            }
920        }
921
922        true
923    }
924}
925
926fn parse_json_downloads(
927    json_downloads: HashMap<String, JsonPythonDownload>,
928) -> Vec<ManagedPythonDownload> {
929    json_downloads
930        .into_iter()
931        .filter_map(|(key, entry)| {
932            let implementation = match entry.name.as_str() {
933                "cpython" => LenientImplementationName::Known(ImplementationName::CPython),
934                "pypy" => LenientImplementationName::Known(ImplementationName::PyPy),
935                "graalpy" => LenientImplementationName::Known(ImplementationName::GraalPy),
936                _ => LenientImplementationName::Unknown(entry.name.clone()),
937            };
938
939            let arch_str = match entry.arch.family.as_str() {
940                "armv5tel" => Cow::Borrowed("armv5te"),
941                // The `gc` variant of riscv64 is the common base instruction set and
942                // is the target in `python-build-standalone`
943                // See https://github.com/astral-sh/python-build-standalone/issues/504
944                "riscv64" => Cow::Borrowed("riscv64gc"),
945                value => Cow::Borrowed(value),
946            };
947
948            let arch_str = if let Some(variant) = entry.arch.variant {
949                Cow::Owned(format!("{arch_str}_{variant}"))
950            } else {
951                arch_str
952            };
953
954            let arch = match Arch::from_str(&arch_str) {
955                Ok(arch) => arch,
956                Err(e) => {
957                    debug!("Skipping entry {key}: Invalid arch '{arch_str}' - {e}");
958                    return None;
959                }
960            };
961
962            let os = match Os::from_str(&entry.os) {
963                Ok(os) => os,
964                Err(e) => {
965                    debug!("Skipping entry {}: Invalid OS '{}' - {}", key, entry.os, e);
966                    return None;
967                }
968            };
969
970            let libc = match Libc::from_str(&entry.libc) {
971                Ok(libc) => libc,
972                Err(e) => {
973                    debug!(
974                        "Skipping entry {}: Invalid libc '{}' - {}",
975                        key, entry.libc, e
976                    );
977                    return None;
978                }
979            };
980
981            let variant = match entry
982                .variant
983                .as_deref()
984                .map(PythonVariant::from_str)
985                .transpose()
986            {
987                Ok(Some(variant)) => variant,
988                Ok(None) => PythonVariant::default(),
989                Err(()) => {
990                    debug!(
991                        "Skipping entry {key}: Unknown python variant - {}",
992                        entry.variant.unwrap_or_default()
993                    );
994                    return None;
995                }
996            };
997
998            let version_str = format!(
999                "{}.{}.{}{}",
1000                entry.major,
1001                entry.minor,
1002                entry.patch,
1003                entry.prerelease.as_deref().unwrap_or_default()
1004            );
1005
1006            let version = match PythonVersion::from_str(&version_str) {
1007                Ok(version) => version,
1008                Err(e) => {
1009                    debug!("Skipping entry {key}: Invalid version '{version_str}' - {e}");
1010                    return None;
1011                }
1012            };
1013
1014            let url = Cow::Owned(entry.url);
1015            let sha256 = entry.sha256;
1016            let build = entry
1017                .build
1018                .map(|s| Box::leak(s.into_boxed_str()) as &'static str);
1019
1020            Some(ManagedPythonDownload {
1021                key: PythonInstallationKey::new_from_version(
1022                    implementation,
1023                    &version,
1024                    Platform::new(os, arch, libc),
1025                    variant,
1026                ),
1027                url,
1028                sha256,
1029                build,
1030            })
1031        })
1032        .sorted_by(|a, b| Ord::cmp(&b.key, &a.key))
1033        .collect()
1034}
1035
1036impl Error {
1037    fn from_reqwest(
1038        url: DisplaySafeUrl,
1039        err: reqwest::Error,
1040        retries: Option<u32>,
1041        start: Instant,
1042    ) -> Self {
1043        let err = Self::NetworkError(url, WrappedReqwestError::from(err));
1044        if let Some(retries) = retries {
1045            Self::NetworkErrorWithRetries {
1046                err: Box::new(err),
1047                retries,
1048                duration: start.elapsed(),
1049            }
1050        } else {
1051            err
1052        }
1053    }
1054
1055    fn from_reqwest_middleware(url: DisplaySafeUrl, err: reqwest_middleware::Error) -> Self {
1056        match err {
1057            reqwest_middleware::Error::Middleware(error) => {
1058                Self::NetworkMiddlewareError(url, error)
1059            }
1060            reqwest_middleware::Error::Reqwest(error) => {
1061                Self::NetworkError(url, WrappedReqwestError::from(error))
1062            }
1063        }
1064    }
1065}
1066
1067impl Display for ManagedPythonDownload {
1068    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1069        write!(f, "{}", self.key)
1070    }
1071}
1072
1073#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1074pub enum Direction {
1075    Download,
1076    Extract,
1077}
1078
1079impl Direction {
1080    fn as_str(&self) -> &str {
1081        match self {
1082            Self::Download => "download",
1083            Self::Extract => "extract",
1084        }
1085    }
1086}
1087
1088impl Display for Direction {
1089    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1090        f.write_str(self.as_str())
1091    }
1092}
1093
1094pub trait Reporter: Send + Sync {
1095    fn on_request_start(
1096        &self,
1097        direction: Direction,
1098        name: &PythonInstallationKey,
1099        size: Option<u64>,
1100    ) -> usize;
1101    fn on_request_progress(&self, id: usize, inc: u64);
1102    fn on_request_complete(&self, direction: Direction, id: usize);
1103}
1104
1105/// An asynchronous reader that reports progress as bytes are read.
1106struct ProgressReader<'a, R> {
1107    reader: R,
1108    index: usize,
1109    reporter: &'a dyn Reporter,
1110}
1111
1112impl<'a, R> ProgressReader<'a, R> {
1113    /// Create a new [`ProgressReader`] that wraps another reader.
1114    fn new(reader: R, index: usize, reporter: &'a dyn Reporter) -> Self {
1115        Self {
1116            reader,
1117            index,
1118            reporter,
1119        }
1120    }
1121}
1122
1123impl<R> AsyncRead for ProgressReader<'_, R>
1124where
1125    R: AsyncRead + Unpin,
1126{
1127    fn poll_read(
1128        mut self: Pin<&mut Self>,
1129        cx: &mut Context<'_>,
1130        buf: &mut ReadBuf<'_>,
1131    ) -> Poll<io::Result<()>> {
1132        Pin::new(&mut self.as_mut().reader)
1133            .poll_read(cx, buf)
1134            .map_ok(|()| {
1135                self.reporter
1136                    .on_request_progress(self.index, buf.filled().len() as u64);
1137            })
1138    }
1139}
1140
1141/// Convert a [`Url`] into an [`AsyncRead`] stream.
1142async fn read_url(
1143    url: &DisplaySafeUrl,
1144    client: &BaseClient,
1145) -> Result<(impl AsyncRead + Unpin, Option<u64>), Error> {
1146    if url.scheme() == "file" {
1147        // Loads downloaded distribution from the given `file://` URL.
1148        let path = url
1149            .to_file_path()
1150            .map_err(|()| Error::InvalidFileUrl(url.to_string()))?;
1151
1152        let size = fs_err::tokio::metadata(&path).await?.len();
1153        let reader = fs_err::tokio::File::open(&path).await?;
1154
1155        Ok((Either::Left(reader), Some(size)))
1156    } else {
1157        let start = Instant::now();
1158        let response = client
1159            .for_host(url)
1160            .get(Url::from(url.clone()))
1161            .send()
1162            .await
1163            .map_err(|err| Error::from_reqwest_middleware(url.clone(), err))?;
1164
1165        let retry_count = response
1166            .extensions()
1167            .get::<reqwest_retry::RetryCount>()
1168            .map(|retries| retries.value());
1169
1170        // Check the status code.
1171        let response = response
1172            .error_for_status()
1173            .map_err(|err| Error::from_reqwest(url.clone(), err, retry_count, start))?;
1174
1175        let size = response.content_length();
1176        let stream = response
1177            .bytes_stream()
1178            .map_err(io::Error::other)
1179            .into_async_read();
1180
1181        Ok((Either::Right(stream.compat()), size))
1182    }
1183}
1184
1185#[cfg(test)]
1186mod tests {
1187    #[cfg(target_arch = "aarch64")]
1188    use uv_python_types::ArchRequest;
1189    use uv_python_types::VersionRequest;
1190
1191    use std::collections::HashSet;
1192
1193    use uv_platform::{Arch, Libc, Os, Platform};
1194    use uv_python_types::{LenientImplementationName, PythonInstallationKey};
1195
1196    use super::*;
1197
1198    #[test]
1199    fn test_download_error_debug() {
1200        let errors = [
1201            Error::Request(PythonDownloadRequestError::EmptyRequest),
1202            Error::Mirror(
1203                "UV_PYTHON_INSTALL_MIRROR",
1204                DisplaySafeUrl::parse("file:///mirror").expect("mirror URL should be valid"),
1205            ),
1206            Error::NetworkErrorWithRetries {
1207                err: Box::new(Error::Request(
1208                    PythonDownloadRequestError::InvalidPythonVersion("3.x".to_owned()),
1209                )),
1210                retries: 2,
1211                duration: Duration::from_secs(3),
1212            },
1213            Error::HashMismatch {
1214                installation: "cpython-3.12.0-linux-x86_64-gnu".to_owned(),
1215                expected: "abc".to_owned(),
1216                actual: "def".to_owned(),
1217            },
1218        ];
1219
1220        insta::assert_debug_snapshot!(errors, @r#"
1221        [
1222            Request(
1223                EmptyRequest,
1224            ),
1225            Mirror(
1226                "UV_PYTHON_INSTALL_MIRROR",
1227                DisplaySafeUrl {
1228                    scheme: "file",
1229                    cannot_be_a_base: false,
1230                    username: "",
1231                    password: None,
1232                    host: None,
1233                    port: None,
1234                    path: "/mirror",
1235                    query: None,
1236                    fragment: None,
1237                },
1238            ),
1239            NetworkErrorWithRetries {
1240                err: Request(
1241                    InvalidPythonVersion(
1242                        "3.x",
1243                    ),
1244                ),
1245                retries: 2,
1246                duration: 3s,
1247            },
1248            HashMismatch {
1249                installation: "cpython-3.12.0-linux-x86_64-gnu",
1250                expected: "abc",
1251                actual: "def",
1252            },
1253        ]
1254        "#);
1255    }
1256
1257    /// Test that build filtering works correctly
1258    #[tokio::test]
1259    async fn test_python_download_request_build_filtering() {
1260        let mut request = PythonDownloadRequest::default()
1261            .with_version(VersionRequest::from_str("3.12").unwrap())
1262            .with_implementation(ImplementationName::CPython);
1263        request.build = Some("20240814".to_string());
1264
1265        let client_builder = uv_client::BaseClientBuilder::default();
1266        let cache = uv_cache::Cache::temp().expect("failed to create temp cache");
1267        let download_list = ManagedPythonDownloadList::new(&client_builder, &cache, None)
1268            .await
1269            .unwrap();
1270
1271        let downloads: Vec<_> = download_list
1272            .iter_all()
1273            .filter(|d| d.matches_request(&request))
1274            .collect();
1275
1276        assert!(
1277            !downloads.is_empty(),
1278            "Should find at least one matching download"
1279        );
1280        for download in downloads {
1281            assert_eq!(download.build(), Some("20240814"));
1282        }
1283    }
1284
1285    /// Test that an invalid build results in no matches
1286    #[tokio::test]
1287    async fn test_python_download_request_invalid_build() {
1288        // Create a request with a non-existent build
1289        let mut request = PythonDownloadRequest::default()
1290            .with_version(VersionRequest::from_str("3.12").unwrap())
1291            .with_implementation(ImplementationName::CPython);
1292        request.build = Some("99999999".to_string());
1293
1294        let client_builder = uv_client::BaseClientBuilder::default();
1295        let cache = uv_cache::Cache::temp().expect("failed to create temp cache");
1296        let download_list = ManagedPythonDownloadList::new(&client_builder, &cache, None)
1297            .await
1298            .unwrap();
1299
1300        // Should find no matching downloads
1301        let downloads: Vec<_> = download_list
1302            .iter_all()
1303            .filter(|d| d.matches_request(&request))
1304            .collect();
1305
1306        assert_eq!(downloads.len(), 0);
1307    }
1308
1309    #[test]
1310    #[cfg(target_arch = "aarch64")]
1311    fn windows_aarch64_download_selection() {
1312        let downloads =
1313            ManagedPythonDownloadList::new_only_embedded().expect("valid embedded downloads");
1314        let native_arch = Arch::from_str("aarch64").expect("valid architecture");
1315        let x86_64_arch = Arch::from_str("x86_64").expect("valid architecture");
1316        let mut request =
1317            PythonDownloadRequest::from_str("cpython-windows").expect("valid download request");
1318        request.libc = Some(Libc::None);
1319        request.arch = Some(ArchRequest::Environment(native_arch));
1320
1321        // The native preference also applies to versions released before Python 3.15.
1322        for version in ["3.11", "3.12", "3.13", "3.14", "3.15"] {
1323            let request = request
1324                .clone()
1325                .with_version(VersionRequest::from_str(version).expect("valid version"));
1326            let download = downloads.find(&request).expect("native download available");
1327            assert_eq!(*download.key.arch(), native_arch);
1328
1329            let request = request.with_arch(x86_64_arch);
1330            let download = downloads.find(&request).expect("x86_64 download available");
1331            assert_eq!(*download.key.arch(), x86_64_arch);
1332        }
1333
1334        // Python 3.10 has no managed Windows ARM64 build.
1335        let request =
1336            request.with_version(VersionRequest::from_str("3.10").expect("valid version"));
1337        let download = downloads.find(&request).expect("x86_64 fallback available");
1338        assert_eq!(*download.key.arch(), x86_64_arch);
1339    }
1340
1341    fn cpython_download_for_url(url: &'static str) -> ManagedPythonDownload {
1342        let key = PythonInstallationKey::new(
1343            LenientImplementationName::Known(uv_python_types::ImplementationName::CPython),
1344            3,
1345            12,
1346            4,
1347            None,
1348            Platform::new(
1349                Os::from_str("linux").unwrap(),
1350                Arch::from_str("x86_64").unwrap(),
1351                Libc::from_str("gnu").unwrap(),
1352            ),
1353            uv_python_types::PythonVariant::default(),
1354        );
1355
1356        ManagedPythonDownload {
1357            key,
1358            url: Cow::Borrowed(url),
1359            sha256: Some(Digest::from_bytes([0xab; 32])),
1360            build: Some("20240713"),
1361        }
1362    }
1363
1364    #[test]
1365    fn test_cpython_mirror_unexpected_download_url_redacts_credentials() {
1366        let download = cpython_download_for_url(
1367            "https://user:password@example.com/cpython.tar.gz?X-Amz-Signature=signature&safe=value",
1368        );
1369
1370        let error = download
1371            .download_urls_with_astral_mirror(
1372                PythonDownloadMirrors {
1373                    cpython: Some("https://python-mirror.example.com/releases/"),
1374                    ..PythonDownloadMirrors::default()
1375                },
1376                None,
1377            )
1378            .expect_err("the download URL should not match the CPython mirror format");
1379
1380        insta::assert_snapshot!(error, @"A mirror was provided via `UV_PYTHON_INSTALL_MIRROR`, but the URL does not match the expected format: https://user:****@example.com/cpython.tar.gz?X-Amz-Signature=****&safe=value");
1381    }
1382
1383    #[test]
1384    fn test_cpython_mirror_invalid_download_url() {
1385        let download = cpython_download_for_url("not a URL");
1386
1387        let error = download
1388            .download_urls_with_astral_mirror(
1389                PythonDownloadMirrors {
1390                    cpython: Some("https://python-mirror.example.com/releases/"),
1391                    ..PythonDownloadMirrors::default()
1392                },
1393                None,
1394            )
1395            .expect_err("the download URL should be invalid");
1396
1397        insta::assert_snapshot!(error, @"Invalid download URL");
1398    }
1399
1400    #[test]
1401    fn test_cpython_download_urls_custom_astral_mirror() {
1402        let download = cpython_download_for_url(
1403            "https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-x86_64-unknown-linux-gnu-install_only.tar.gz",
1404        );
1405
1406        let urls = download
1407            .download_urls_with_astral_mirror(
1408                PythonDownloadMirrors::default(),
1409                Some("https://nexus.example.com/repository/releases.astral.sh/"),
1410            )
1411            .expect("download URLs should be valid");
1412        let urls = urls
1413            .into_iter()
1414            .map(|url| url.to_string())
1415            .collect::<Vec<_>>();
1416        assert_eq!(
1417            urls,
1418            vec![
1419                "https://nexus.example.com/repository/releases.astral.sh/github/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-x86_64-unknown-linux-gnu-install_only.tar.gz"
1420                    .to_string(),
1421            ]
1422        );
1423    }
1424
1425    #[test]
1426    fn test_cpython_specific_mirror_takes_precedence_over_astral_mirror() {
1427        let download = cpython_download_for_url(
1428            "https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-x86_64-unknown-linux-gnu-install_only.tar.gz",
1429        );
1430
1431        let urls = download
1432            .download_urls_with_astral_mirror(
1433                PythonDownloadMirrors {
1434                    cpython: Some("https://python-mirror.example.com/releases/"),
1435                    ..PythonDownloadMirrors::default()
1436                },
1437                Some("https://nexus.example.com/repository/releases.astral.sh/"),
1438            )
1439            .expect("download URLs should be valid");
1440        let urls = urls
1441            .into_iter()
1442            .map(|url| url.to_string())
1443            .collect::<Vec<_>>();
1444        assert_eq!(
1445            urls,
1446            vec![
1447                "https://python-mirror.example.com/releases/20240713/cpython-3.12.4%2B20240713-x86_64-unknown-linux-gnu-install_only.tar.gz"
1448                    .to_string(),
1449            ]
1450        );
1451    }
1452
1453    #[test]
1454    fn test_cpython_download_urls_empty_astral_mirror_uses_default() {
1455        let download = cpython_download_for_url(
1456            "https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-x86_64-unknown-linux-gnu-install_only.tar.gz",
1457        );
1458
1459        let default_urls = download
1460            .download_urls_with_astral_mirror(PythonDownloadMirrors::default(), None)
1461            .expect("download URLs should be valid");
1462        let empty_urls = download
1463            .download_urls_with_astral_mirror(PythonDownloadMirrors::default(), Some(""))
1464            .expect("download URLs should be valid");
1465
1466        assert_eq!(default_urls, empty_urls);
1467    }
1468
1469    /// A hash mismatch is a post-download integrity failure — retrying a different URL cannot fix
1470    /// it, so it should not trigger a fallback.
1471    #[test]
1472    fn test_should_try_next_url_hash_mismatch() {
1473        let err = Error::HashMismatch {
1474            installation: "cpython-3.12.0".to_string(),
1475            expected: "abc".to_string(),
1476            actual: "def".to_string(),
1477        };
1478        assert!(!err.should_try_next_url());
1479    }
1480
1481    /// A local filesystem error during extraction (e.g. permission denied writing to disk) is not
1482    /// a network failure — a different URL would produce the same outcome.
1483    #[test]
1484    fn test_should_try_next_url_extract_error_filesystem() {
1485        let err = Error::ExtractError(
1486            "archive.tar.gz".to_string(),
1487            uv_extract::Error::Io(io::Error::new(io::ErrorKind::PermissionDenied, "")),
1488        );
1489        assert!(!err.should_try_next_url());
1490    }
1491
1492    /// A generic IO error from a local filesystem operation (e.g. permission denied on cache
1493    /// directory) should not trigger a fallback to a different URL.
1494    #[test]
1495    fn test_should_try_next_url_io_error_filesystem() {
1496        let err = Error::Io(io::Error::new(io::ErrorKind::PermissionDenied, ""));
1497        assert!(!err.should_try_next_url());
1498    }
1499
1500    /// A network IO error (e.g. connection reset mid-download) surfaces as `Error::Io` from
1501    /// `download_archive`. It should trigger a fallback because a different mirror may succeed.
1502    #[test]
1503    fn test_should_try_next_url_io_error_network() {
1504        let err = Error::Io(io::Error::new(io::ErrorKind::ConnectionReset, ""));
1505        assert!(err.should_try_next_url());
1506    }
1507
1508    /// A 404 HTTP response from the mirror becomes `Error::NetworkError` — it should trigger a
1509    /// URL fallback, because a 404 on the mirror does not mean the file is absent from GitHub.
1510    #[test]
1511    fn test_should_try_next_url_network_error_404() {
1512        let url =
1513            DisplaySafeUrl::from_str("https://releases.astral.sh/python/cpython-3.12.0.tar.gz")
1514                .unwrap();
1515        // `NetworkError` wraps a `WrappedReqwestError`; we use a middleware error as a
1516        // stand-in because `should_try_next_url` only inspects the variant, not the contents.
1517        let wrapped = WrappedReqwestError::with_problem_details(
1518            reqwest_middleware::Error::Middleware(anyhow::anyhow!("404 Not Found")),
1519            None,
1520        );
1521        let err = Error::NetworkError(url, wrapped);
1522        assert!(err.should_try_next_url());
1523    }
1524
1525    /// Every [`PythonVersion`] in the embedded download metadata must be convertible
1526    /// to a [`VersionRequest`] to avoid runtime panics.
1527    #[test]
1528    fn embedded_download_versions_convert_to_version_requests() {
1529        let downloads = ManagedPythonDownloadList::new_only_embedded()
1530            .expect("embedded download metadata should load");
1531
1532        let unique_versions: HashSet<PythonVersion> = downloads
1533            .iter_all()
1534            .map(ManagedPythonDownload::python_version)
1535            .collect();
1536
1537        for version in &unique_versions {
1538            let _ = VersionRequest::from(version);
1539        }
1540    }
1541}