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