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 zstd::stream::read::Decoder;
29
30use uv_cache::{Cache, CacheBucket};
31use uv_cache_key::cache_digest;
32use uv_client::{
33    BaseClient, BaseClientBuilder, CacheControl, CachedClient, CachedClientError, ClientBuildError,
34    Connectivity, RetriableError, RetryState, WrappedReqwestError, fetch_with_url_fallback,
35    retryable_on_request_failure,
36};
37use uv_distribution_filename::{ExtensionError, SourceDistExtension};
38use uv_extract::hash::Hasher;
39use uv_fs::{Simplified, rename_with_retry};
40use uv_macros::DebugNoInline;
41use uv_platform::{Arch, Libc, Os, Platform};
42use uv_pypi_types::{Digest, HashAlgorithm, HashDigest};
43use uv_redacted::{SafeUrl, SafeUrlError};
44use uv_static::{
45    EnvVars, TarBackend, astral_mirror_base_url, astral_mirror_url_from_env,
46    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(SafeUrl, #[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(SafeUrl, #[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] SafeUrlError),
89    #[error("Invalid download URL: {0}")]
90    InvalidUrlFormat(SafeUrl),
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, SafeUrl),
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<SafeUrl>,
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(SafeUrl),
295        }
296
297        let json_source = if let Some(url_or_path) = python_downloads_json_url {
298            if let Ok(url) = SafeUrl::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: &SafeUrl,
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.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        let tar_backend = TarBackend::from_env();
471        if urls.is_empty() {
472            return Err(Error::NoPythonDownloadUrlFound);
473        }
474        fetch_with_url_fallback(&urls, *retry_policy, &format!("`{}`", self.key()), |url| {
475            self.fetch_from_url(
476                url,
477                client,
478                installation_dir,
479                scratch_dir,
480                reinstall,
481                reporter,
482                tar_backend,
483            )
484        })
485        .await
486    }
487
488    /// Download and extract a Python distribution from the given URL.
489    async fn fetch_from_url(
490        &self,
491        url: SafeUrl,
492        client: &BaseClient,
493        installation_dir: &Path,
494        scratch_dir: &Path,
495        reinstall: bool,
496        reporter: Option<&dyn Reporter>,
497        tar_backend: TarBackend,
498    ) -> Result<DownloadResult, Error> {
499        let path = installation_dir.join(self.key().to_string());
500
501        // If it is not a reinstall and the dir already exists, return it.
502        if !reinstall && path.is_dir() {
503            return Ok(DownloadResult::AlreadyAvailable(path));
504        }
505
506        // We improve filesystem compatibility by using neither the URL-encoded `%2B` nor the `+` it
507        // decodes to.
508        let filename = url
509            .path_segments()
510            .ok_or_else(|| Error::InvalidUrlFormat(url.clone()))?
511            .next_back()
512            .ok_or_else(|| Error::InvalidUrlFormat(url.clone()))?
513            .replace("%2B", "-");
514        debug_assert!(
515            filename
516                .chars()
517                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.'),
518            "Unexpected char in filename: {filename}"
519        );
520        let ext = SourceDistExtension::from_path(&filename)
521            .map_err(|err| Error::MissingExtension(url.to_string(), err))?;
522
523        let temp_dir = tempfile::tempdir_in(scratch_dir).map_err(Error::DownloadDirError)?;
524
525        let temp_dir = if let Some(python_builds_dir) =
526            env::var_os(EnvVars::UV_PYTHON_CACHE_DIR).filter(|s| !s.is_empty())
527        {
528            let python_builds_dir = PathBuf::from(python_builds_dir);
529            fs_err::create_dir_all(&python_builds_dir)?;
530            let hash_prefix = match self.sha256.as_ref() {
531                Some(digest) => {
532                    // Shorten the hash to avoid too-long-filename errors
533                    &digest.as_str()[..9]
534                }
535                None => "none",
536            };
537            let target_cache_file = python_builds_dir.join(format!("{hash_prefix}-{filename}"));
538
539            // Download the archive to the cache, or return a reader if we have it in cache.
540            // TODO(konsti): We should "tee" the write so we can do the download-to-cache and unpacking
541            // in one step.
542            let (reader, size): (Box<dyn AsyncRead + Unpin>, Option<u64>) =
543                match fs_err::tokio::File::open(&target_cache_file).await {
544                    Ok(file) => {
545                        debug!(
546                            "Extracting existing `{}`",
547                            target_cache_file.simplified_display()
548                        );
549                        let size = file.metadata().await?.len();
550                        let reader = Box::new(tokio::io::BufReader::new(file));
551                        (reader, Some(size))
552                    }
553                    Err(err) if err.kind() == io::ErrorKind::NotFound => {
554                        // Point the user to which file is missing where and where to download it
555                        if client.connectivity().is_offline() {
556                            return Err(Error::OfflinePythonMissing {
557                                file: Box::new(self.key().clone()),
558                                url: Box::new(url.clone()),
559                                python_builds_dir,
560                            });
561                        }
562
563                        self.download_archive(
564                            &url,
565                            client,
566                            reporter,
567                            &python_builds_dir,
568                            &target_cache_file,
569                        )
570                        .await?;
571
572                        debug!("Extracting `{}`", target_cache_file.simplified_display());
573                        let file = fs_err::tokio::File::open(&target_cache_file).await?;
574                        let size = file.metadata().await?.len();
575                        let reader = Box::new(tokio::io::BufReader::new(file));
576                        (reader, Some(size))
577                    }
578                    Err(err) => return Err(err.into()),
579                };
580
581            // Extract the downloaded archive into a temporary directory.
582            self.extract_reader(
583                reader,
584                temp_dir,
585                &filename,
586                ext,
587                size,
588                reporter,
589                Direction::Extract,
590                tar_backend,
591            )
592            .await?
593        } else {
594            // Avoid overlong log lines
595            debug!("Downloading `{url}`");
596            debug!(
597                "Extracting `{filename}` to temporary location `{}`",
598                temp_dir.path().simplified_display()
599            );
600
601            let (reader, size) = read_url(&url, client).await?;
602            self.extract_reader(
603                reader,
604                temp_dir,
605                &filename,
606                ext,
607                size,
608                reporter,
609                Direction::Download,
610                tar_backend,
611            )
612            .await?
613        };
614
615        // Extract the top-level directory.
616        let mut extracted = match uv_extract::strip_component(temp_dir.path()) {
617            Ok(top_level) => top_level,
618            Err(uv_extract::Error::NonSingularArchive(_)) => temp_dir.path().to_path_buf(),
619            Err(err) => return Err(Error::ExtractError(filename, err)),
620        };
621
622        // If the distribution is a `full` archive, the Python installation is in the `install` directory.
623        if extracted.join("install").is_dir() {
624            extracted = extracted.join("install");
625        // If the distribution is a Pyodide archive, the Python installation is in the `pyodide-root/dist` directory.
626        } else if self.os().is_emscripten() {
627            extracted = extracted.join("pyodide-root").join("dist");
628        }
629
630        #[cfg(unix)]
631        {
632            // Pyodide distributions require all of the supporting files to be alongside the Python
633            // executable, so they don't have a `bin` directory. We create it and link
634            // `bin/pythonX.Y` to `dist/python`.
635            if self.os().is_emscripten() {
636                fs_err::create_dir_all(extracted.join("bin"))?;
637                fs_err::os::unix::fs::symlink(
638                    "../python",
639                    extracted
640                        .join("bin")
641                        .join(format!("python{}.{}", self.key.major, self.key.minor)),
642                )?;
643            }
644
645            // If the distribution is missing a `python` -> `pythonX.Y` symlink, add it.
646            //
647            // We skip for Windows distributions, allowing cross-installs from Unix.
648            //
649            // Pyodide releases never contain this link by default.
650            //
651            // PEP 394 permits it, and python-build-standalone releases after `20240726` include it,
652            // but releases prior to that date do not.
653            if !self.os().is_windows() {
654                match fs_err::os::unix::fs::symlink(
655                    format!("python{}.{}", self.key.major, self.key.minor),
656                    extracted.join("bin").join("python"),
657                ) {
658                    Ok(()) => {}
659                    Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
660                    Err(err) => return Err(err.into()),
661                }
662            }
663        }
664
665        // Remove the target if it already exists.
666        if path.is_dir() {
667            debug!("Removing existing directory: {}", path.user_display());
668            fs_err::tokio::remove_dir_all(&path).await?;
669        }
670
671        // Persist it to the target.
672        debug!(
673            "Moving `{}` to `{}`",
674            extracted.display(),
675            path.user_display()
676        );
677        rename_with_retry(extracted, &path)
678            .await
679            .map_err(|err| Error::CopyError {
680                to: path.clone(),
681                err,
682            })?;
683
684        Ok(DownloadResult::Fetched(path))
685    }
686
687    /// Download the managed Python archive into the cache directory.
688    async fn download_archive(
689        &self,
690        url: &SafeUrl,
691        client: &BaseClient,
692        reporter: Option<&dyn Reporter>,
693        python_builds_dir: &Path,
694        target_cache_file: &Path,
695    ) -> Result<(), Error> {
696        debug!(
697            "Downloading `{}` to `{}`",
698            url,
699            target_cache_file.simplified_display()
700        );
701
702        let (mut reader, size) = read_url(url, client).await?;
703        let temp_dir = tempfile::tempdir_in(python_builds_dir)?;
704        let temp_file = temp_dir.path().join("download");
705
706        // Download to a temporary file. We verify the hash when unpacking the file.
707        {
708            let mut archive_writer = BufWriter::new(fs_err::tokio::File::create(&temp_file).await?);
709
710            // Download with or without progress bar.
711            if let Some(reporter) = reporter {
712                let key = reporter.on_request_start(Direction::Download, &self.key, size);
713                tokio::io::copy(
714                    &mut ProgressReader::new(reader, key, reporter),
715                    &mut archive_writer,
716                )
717                .await?;
718                reporter.on_request_complete(Direction::Download, key);
719            } else {
720                tokio::io::copy(&mut reader, &mut archive_writer).await?;
721            }
722
723            archive_writer.flush().await?;
724        }
725        // Move the completed file into place, invalidating the `File` instance.
726        match rename_with_retry(&temp_file, target_cache_file).await {
727            Ok(()) => {}
728            Err(_) if target_cache_file.is_file() => {}
729            Err(err) => return Err(err.into()),
730        }
731        Ok(())
732    }
733
734    /// Extract a Python interpreter archive into a (temporary) directory, either from a file or
735    /// from a download stream.
736    async fn extract_reader(
737        &self,
738        reader: impl AsyncRead + Unpin,
739        target: TempDir,
740        filename: &String,
741        ext: SourceDistExtension,
742        size: Option<u64>,
743        reporter: Option<&dyn Reporter>,
744        direction: Direction,
745        tar_backend: TarBackend,
746    ) -> Result<TempDir, Error> {
747        let mut hashers = self
748            .sha256
749            .as_ref()
750            .map(|_| Hasher::from(HashAlgorithm::Sha256));
751        let mut hasher = uv_extract::hash::HashReader::new(reader, hashers.as_mut_slice());
752
753        let target = if let Some(reporter) = reporter {
754            let progress_key = reporter.on_request_start(direction, &self.key, size);
755            let mut reader = ProgressReader::new(&mut hasher, progress_key, reporter);
756            let (target, _) = uv_extract::stream::archive(&mut reader, ext, target, tar_backend)
757                .await
758                .map_err(|err| Error::ExtractError(filename.to_owned(), err))?;
759            reporter.on_request_complete(direction, progress_key);
760            target
761        } else {
762            let (target, _) = uv_extract::stream::archive(&mut hasher, ext, target, tar_backend)
763                .await
764                .map_err(|err| Error::ExtractError(filename.to_owned(), err))?;
765            target
766        };
767        hasher.finish().await.map_err(Error::HashExhaustion)?;
768
769        // Check the hash
770        if let Some((expected, hasher)) = self.sha256.as_ref().zip(hashers) {
771            let actual = HashDigest::from(hasher);
772            if actual.digest() != expected.as_str() {
773                return Err(Error::HashMismatch {
774                    installation: self.key.to_string(),
775                    expected: expected.as_str().to_string(),
776                    actual: actual.digest().to_string(),
777                });
778            }
779        }
780
781        Ok(target)
782    }
783
784    #[cfg(test)]
785    fn python_version(&self) -> PythonVersion {
786        self.key.version()
787    }
788
789    /// Return the ordered list of [`SafeUrl`]s to try when downloading the distribution.
790    ///
791    /// For CPython without a user-configured mirror, the default Astral mirror is listed first,
792    /// followed by the canonical GitHub URL as a fallback.
793    ///
794    /// For all other cases (user mirror explicitly set, PyPy, GraalPy, Pyodide), a single URL
795    /// is returned with no fallback.
796    pub fn download_urls(&self, mirrors: PythonDownloadMirrors<'_>) -> Result<Vec<SafeUrl>, Error> {
797        let custom_astral_mirror = astral_mirror_url_from_env();
798        self.download_urls_with_astral_mirror(mirrors, custom_astral_mirror.as_deref())
799    }
800
801    fn download_urls_with_astral_mirror(
802        &self,
803        mirrors: PythonDownloadMirrors<'_>,
804        astral_mirror_url: Option<&str>,
805    ) -> Result<Vec<SafeUrl>, Error> {
806        let astral_mirror_url = custom_astral_mirror_url(astral_mirror_url);
807        match self.key.implementation().as_ref() {
808            LenientImplementationName::Known(ImplementationName::CPython) => {
809                if let Some(mirror) = mirrors.cpython {
810                    // User-configured mirror: use it exclusively, no automatic fallback.
811                    let Some(suffix) = self.url.strip_prefix(CPYTHON_DOWNLOADS_URL_PREFIX) else {
812                        return Err(Error::Mirror(
813                            EnvVars::UV_PYTHON_INSTALL_MIRROR,
814                            SafeUrl::parse(&self.url)?,
815                        ));
816                    };
817                    return Ok(vec![SafeUrl::parse(
818                        format!("{}/{}", mirror.trim_end_matches('/'), suffix).as_str(),
819                    )?]);
820                }
821                // No user mirror: try the default/custom Astral mirror first.
822                if let Some(suffix) = self.url.strip_prefix(CPYTHON_DOWNLOADS_URL_PREFIX) {
823                    let effective_mirror = effective_cpython_mirror(astral_mirror_url);
824                    let mirror_url = SafeUrl::parse(
825                        format!("{}/{}", effective_mirror.trim_end_matches('/'), suffix).as_str(),
826                    )?;
827                    // When a custom Astral mirror is set, use it exclusively.
828                    if astral_mirror_url.is_some() {
829                        return Ok(vec![mirror_url]);
830                    }
831                    // Otherwise fall back to the canonical GitHub URL.
832                    let canonical_url = SafeUrl::parse(&self.url)?;
833                    return Ok(vec![mirror_url, canonical_url]);
834                }
835            }
836
837            LenientImplementationName::Known(ImplementationName::PyPy) => {
838                if let Some(mirror) = mirrors.pypy {
839                    let Some(suffix) = self.url.strip_prefix("https://downloads.python.org/pypy/")
840                    else {
841                        return Err(Error::Mirror(
842                            EnvVars::UV_PYPY_INSTALL_MIRROR,
843                            SafeUrl::parse(&self.url)?,
844                        ));
845                    };
846                    return Ok(vec![SafeUrl::parse(
847                        format!("{}/{}", mirror.trim_end_matches('/'), suffix).as_str(),
848                    )?]);
849                }
850            }
851
852            LenientImplementationName::Known(ImplementationName::GraalPy) => {
853                if let Some(mirror) = mirrors.graalpy {
854                    let Some(suffix) = self
855                        .url
856                        .strip_prefix("https://github.com/oracle/graalpython/releases/download/")
857                    else {
858                        return Err(Error::Mirror(
859                            EnvVars::UV_GRAALPY_INSTALL_MIRROR,
860                            SafeUrl::parse(&self.url)?,
861                        ));
862                    };
863                    return Ok(vec![SafeUrl::parse(
864                        format!("{}/{}", mirror.trim_end_matches('/'), suffix).as_str(),
865                    )?]);
866                }
867            }
868
869            LenientImplementationName::Known(ImplementationName::Pyodide) => {
870                if let Some(mirror) = mirrors.pyodide {
871                    let Some(suffix) = self
872                        .url
873                        .strip_prefix("https://github.com/pyodide/pyodide/releases/download/")
874                    else {
875                        return Err(Error::Mirror(
876                            EnvVars::UV_PYODIDE_INSTALL_MIRROR,
877                            SafeUrl::parse(&self.url)?,
878                        ));
879                    };
880                    return Ok(vec![SafeUrl::parse(
881                        format!("{}/{}", mirror.trim_end_matches('/'), suffix).as_str(),
882                    )?]);
883                }
884            }
885
886            _ => {}
887        }
888
889        Ok(vec![SafeUrl::parse(&self.url)?])
890    }
891
892    /// Whether this download satisfies the requested Python and build.
893    fn matches_request(&self, request: &PythonDownloadRequest) -> bool {
894        // First check the key
895        if !request.satisfied_by_key(self.key()) {
896            return false;
897        }
898
899        // Then check the build if specified
900        if let Some(ref requested_build) = request.build {
901            let Some(download_build) = self.build() else {
902                debug!(
903                    "Skipping download `{}`: a build version was requested but is not available for this download",
904                    self
905                );
906                return false;
907            };
908
909            if download_build != requested_build {
910                debug!(
911                    "Skipping download `{}`: requested build version `{}` does not match download build version `{}`",
912                    self, requested_build, download_build
913                );
914                return false;
915            }
916        }
917
918        true
919    }
920}
921
922fn parse_json_downloads(
923    json_downloads: HashMap<String, JsonPythonDownload>,
924) -> Vec<ManagedPythonDownload> {
925    json_downloads
926        .into_iter()
927        .filter_map(|(key, entry)| {
928            let implementation = match entry.name.as_str() {
929                "cpython" => LenientImplementationName::Known(ImplementationName::CPython),
930                "pypy" => LenientImplementationName::Known(ImplementationName::PyPy),
931                "graalpy" => LenientImplementationName::Known(ImplementationName::GraalPy),
932                _ => LenientImplementationName::Unknown(entry.name.clone()),
933            };
934
935            let arch_str = match entry.arch.family.as_str() {
936                "armv5tel" => Cow::Borrowed("armv5te"),
937                // The `gc` variant of riscv64 is the common base instruction set and
938                // is the target in `python-build-standalone`
939                // See https://github.com/astral-sh/python-build-standalone/issues/504
940                "riscv64" => Cow::Borrowed("riscv64gc"),
941                value => Cow::Borrowed(value),
942            };
943
944            let arch_str = if let Some(variant) = entry.arch.variant {
945                Cow::Owned(format!("{arch_str}_{variant}"))
946            } else {
947                arch_str
948            };
949
950            let arch = match Arch::from_str(&arch_str) {
951                Ok(arch) => arch,
952                Err(e) => {
953                    debug!("Skipping entry {key}: Invalid arch '{arch_str}' - {e}");
954                    return None;
955                }
956            };
957
958            let os = match Os::from_str(&entry.os) {
959                Ok(os) => os,
960                Err(e) => {
961                    debug!("Skipping entry {}: Invalid OS '{}' - {}", key, entry.os, e);
962                    return None;
963                }
964            };
965
966            let libc = match Libc::from_str(&entry.libc) {
967                Ok(libc) => libc,
968                Err(e) => {
969                    debug!(
970                        "Skipping entry {}: Invalid libc '{}' - {}",
971                        key, entry.libc, e
972                    );
973                    return None;
974                }
975            };
976
977            let variant = match entry
978                .variant
979                .as_deref()
980                .map(PythonVariant::from_str)
981                .transpose()
982            {
983                Ok(Some(variant)) => variant,
984                Ok(None) => PythonVariant::default(),
985                Err(()) => {
986                    debug!(
987                        "Skipping entry {key}: Unknown python variant - {}",
988                        entry.variant.unwrap_or_default()
989                    );
990                    return None;
991                }
992            };
993
994            let version_str = format!(
995                "{}.{}.{}{}",
996                entry.major,
997                entry.minor,
998                entry.patch,
999                entry.prerelease.as_deref().unwrap_or_default()
1000            );
1001
1002            let version = match PythonVersion::from_str(&version_str) {
1003                Ok(version) => version,
1004                Err(e) => {
1005                    debug!("Skipping entry {key}: Invalid version '{version_str}' - {e}");
1006                    return None;
1007                }
1008            };
1009
1010            let url = Cow::Owned(entry.url);
1011            let sha256 = entry.sha256;
1012            let build = entry
1013                .build
1014                .map(|s| Box::leak(s.into_boxed_str()) as &'static str);
1015
1016            Some(ManagedPythonDownload {
1017                key: PythonInstallationKey::new_from_version(
1018                    implementation,
1019                    &version,
1020                    Platform::new(os, arch, libc),
1021                    variant,
1022                ),
1023                url,
1024                sha256,
1025                build,
1026            })
1027        })
1028        .sorted_by(|a, b| Ord::cmp(&b.key, &a.key))
1029        .collect()
1030}
1031
1032impl Error {
1033    fn from_reqwest(
1034        url: SafeUrl,
1035        err: reqwest::Error,
1036        retries: Option<u32>,
1037        start: Instant,
1038    ) -> Self {
1039        let err = Self::NetworkError(url, WrappedReqwestError::from(err));
1040        if let Some(retries) = retries {
1041            Self::NetworkErrorWithRetries {
1042                err: Box::new(err),
1043                retries,
1044                duration: start.elapsed(),
1045            }
1046        } else {
1047            err
1048        }
1049    }
1050
1051    fn from_reqwest_middleware(url: SafeUrl, err: reqwest_middleware::Error) -> Self {
1052        match err {
1053            reqwest_middleware::Error::Middleware(error) => {
1054                Self::NetworkMiddlewareError(url, error)
1055            }
1056            reqwest_middleware::Error::Reqwest(error) => {
1057                Self::NetworkError(url, WrappedReqwestError::from(error))
1058            }
1059        }
1060    }
1061}
1062
1063impl Display for ManagedPythonDownload {
1064    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1065        write!(f, "{}", self.key)
1066    }
1067}
1068
1069#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1070pub enum Direction {
1071    Download,
1072    Extract,
1073}
1074
1075impl Direction {
1076    fn as_str(&self) -> &str {
1077        match self {
1078            Self::Download => "download",
1079            Self::Extract => "extract",
1080        }
1081    }
1082}
1083
1084impl Display for Direction {
1085    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1086        f.write_str(self.as_str())
1087    }
1088}
1089
1090pub trait Reporter: Send + Sync {
1091    fn on_request_start(
1092        &self,
1093        direction: Direction,
1094        name: &PythonInstallationKey,
1095        size: Option<u64>,
1096    ) -> usize;
1097    fn on_request_progress(&self, id: usize, inc: u64);
1098    fn on_request_complete(&self, direction: Direction, id: usize);
1099}
1100
1101/// An asynchronous reader that reports progress as bytes are read.
1102struct ProgressReader<'a, R> {
1103    reader: R,
1104    index: usize,
1105    reporter: &'a dyn Reporter,
1106}
1107
1108impl<'a, R> ProgressReader<'a, R> {
1109    /// Create a new [`ProgressReader`] that wraps another reader.
1110    fn new(reader: R, index: usize, reporter: &'a dyn Reporter) -> Self {
1111        Self {
1112            reader,
1113            index,
1114            reporter,
1115        }
1116    }
1117}
1118
1119impl<R> AsyncRead for ProgressReader<'_, R>
1120where
1121    R: AsyncRead + Unpin,
1122{
1123    fn poll_read(
1124        mut self: Pin<&mut Self>,
1125        cx: &mut Context<'_>,
1126        buf: &mut ReadBuf<'_>,
1127    ) -> Poll<io::Result<()>> {
1128        Pin::new(&mut self.as_mut().reader)
1129            .poll_read(cx, buf)
1130            .map_ok(|()| {
1131                self.reporter
1132                    .on_request_progress(self.index, buf.filled().len() as u64);
1133            })
1134    }
1135}
1136
1137/// Convert a [`SafeUrl`] into an [`AsyncRead`] stream.
1138async fn read_url(
1139    url: &SafeUrl,
1140    client: &BaseClient,
1141) -> Result<(impl AsyncRead + Unpin, Option<u64>), Error> {
1142    if url.scheme() == "file" {
1143        // Loads downloaded distribution from the given `file://` URL.
1144        let path = url
1145            .to_file_path()
1146            .map_err(|()| Error::InvalidFileUrl(url.to_string()))?;
1147
1148        let size = fs_err::tokio::metadata(&path).await?.len();
1149        let reader = fs_err::tokio::File::open(&path).await?;
1150
1151        Ok((Either::Left(reader), Some(size)))
1152    } else {
1153        let start = Instant::now();
1154        let response = client
1155            .for_host(url)
1156            .get(url.clone())
1157            .send()
1158            .await
1159            .map_err(|err| Error::from_reqwest_middleware(url.clone(), err))?;
1160
1161        let retry_count = response
1162            .extensions()
1163            .get::<reqwest_retry::RetryCount>()
1164            .map(|retries| retries.value());
1165
1166        // Check the status code.
1167        let response = response
1168            .error_for_status()
1169            .map_err(|err| Error::from_reqwest(url.clone(), err, retry_count, start))?;
1170
1171        let size = response.content_length();
1172        let stream = response
1173            .bytes_stream()
1174            .map_err(io::Error::other)
1175            .into_async_read();
1176
1177        Ok((Either::Right(stream.compat()), size))
1178    }
1179}
1180
1181#[cfg(test)]
1182mod tests {
1183    #[cfg(unix)]
1184    use crate::ManagedPythonInstallation;
1185    #[cfg(target_arch = "aarch64")]
1186    use uv_python_types::ArchRequest;
1187    use uv_python_types::VersionRequest;
1188
1189    use std::collections::HashSet;
1190
1191    use uv_platform::{Arch, Libc, Os, Platform};
1192    use uv_python_types::{LenientImplementationName, PythonInstallationKey};
1193
1194    use super::*;
1195
1196    #[test]
1197    fn test_download_error_debug() {
1198        let errors = [
1199            Error::Request(PythonDownloadRequestError::EmptyRequest),
1200            Error::Mirror(
1201                "UV_PYTHON_INSTALL_MIRROR",
1202                SafeUrl::parse("file:///mirror").expect("mirror URL should be valid"),
1203            ),
1204            Error::NetworkErrorWithRetries {
1205                err: Box::new(Error::Request(
1206                    PythonDownloadRequestError::InvalidPythonVersion("3.x".to_owned()),
1207                )),
1208                retries: 2,
1209                duration: Duration::from_secs(3),
1210            },
1211            Error::HashMismatch {
1212                installation: "cpython-3.12.0-linux-x86_64-gnu".to_owned(),
1213                expected: "abc".to_owned(),
1214                actual: "def".to_owned(),
1215            },
1216        ];
1217
1218        insta::assert_debug_snapshot!(errors, @r#"
1219        [
1220            Request(
1221                EmptyRequest,
1222            ),
1223            Mirror(
1224                "UV_PYTHON_INSTALL_MIRROR",
1225                SafeUrl {
1226                    scheme: "file",
1227                    cannot_be_a_base: false,
1228                    username: "",
1229                    password: None,
1230                    host: None,
1231                    port: None,
1232                    path: "/mirror",
1233                    query: None,
1234                    fragment: None,
1235                },
1236            ),
1237            NetworkErrorWithRetries {
1238                err: Request(
1239                    InvalidPythonVersion(
1240                        "3.x",
1241                    ),
1242                ),
1243                retries: 2,
1244                duration: 3s,
1245            },
1246            HashMismatch {
1247                installation: "cpython-3.12.0-linux-x86_64-gnu",
1248                expected: "abc",
1249                actual: "def",
1250            },
1251        ]
1252        "#);
1253    }
1254
1255    /// Test that build filtering works correctly
1256    #[tokio::test]
1257    async fn test_python_download_request_build_filtering() {
1258        let mut request = PythonDownloadRequest::default()
1259            .with_version(VersionRequest::from_str("3.12").unwrap())
1260            .with_implementation(ImplementationName::CPython);
1261        request.build = Some("20240814".to_string());
1262
1263        let client_builder = uv_client::BaseClientBuilder::default();
1264        let cache = uv_cache::Cache::temp().expect("failed to create temp cache");
1265        let download_list = ManagedPythonDownloadList::new(&client_builder, &cache, None)
1266            .await
1267            .unwrap();
1268
1269        let downloads: Vec<_> = download_list
1270            .iter_all()
1271            .filter(|d| d.matches_request(&request))
1272            .collect();
1273
1274        assert!(
1275            !downloads.is_empty(),
1276            "Should find at least one matching download"
1277        );
1278        for download in downloads {
1279            assert_eq!(download.build(), Some("20240814"));
1280        }
1281    }
1282
1283    /// Test that an invalid build results in no matches
1284    #[tokio::test]
1285    async fn test_python_download_request_invalid_build() {
1286        // Create a request with a non-existent build
1287        let mut request = PythonDownloadRequest::default()
1288            .with_version(VersionRequest::from_str("3.12").unwrap())
1289            .with_implementation(ImplementationName::CPython);
1290        request.build = Some("99999999".to_string());
1291
1292        let client_builder = uv_client::BaseClientBuilder::default();
1293        let cache = uv_cache::Cache::temp().expect("failed to create temp cache");
1294        let download_list = ManagedPythonDownloadList::new(&client_builder, &cache, None)
1295            .await
1296            .unwrap();
1297
1298        // Should find no matching downloads
1299        let downloads: Vec<_> = download_list
1300            .iter_all()
1301            .filter(|d| d.matches_request(&request))
1302            .collect();
1303
1304        assert_eq!(downloads.len(), 0);
1305    }
1306
1307    #[test]
1308    #[cfg(target_arch = "aarch64")]
1309    fn windows_aarch64_download_selection() {
1310        let downloads =
1311            ManagedPythonDownloadList::new_only_embedded().expect("valid embedded downloads");
1312        let native_arch = Arch::from_str("aarch64").expect("valid architecture");
1313        let x86_64_arch = Arch::from_str("x86_64").expect("valid architecture");
1314        let mut request =
1315            PythonDownloadRequest::from_str("cpython-windows").expect("valid download request");
1316        request.libc = Some(Libc::None);
1317        request.arch = Some(ArchRequest::Environment(native_arch));
1318
1319        // The native preference also applies to versions released before Python 3.15.
1320        for version in ["3.11", "3.12", "3.13", "3.14", "3.15"] {
1321            let request = request
1322                .clone()
1323                .with_version(VersionRequest::from_str(version).expect("valid version"));
1324            let download = downloads.find(&request).expect("native download available");
1325            assert_eq!(*download.key.arch(), native_arch);
1326
1327            let request = request.with_arch(x86_64_arch);
1328            let download = downloads.find(&request).expect("x86_64 download available");
1329            assert_eq!(*download.key.arch(), x86_64_arch);
1330        }
1331
1332        // Python 3.10 has no managed Windows ARM64 build.
1333        let request =
1334            request.with_version(VersionRequest::from_str("3.10").expect("valid version"));
1335        let download = downloads.find(&request).expect("x86_64 fallback available");
1336        assert_eq!(*download.key.arch(), x86_64_arch);
1337    }
1338
1339    fn cpython_download_for_url(url: &'static str) -> ManagedPythonDownload {
1340        let key = PythonInstallationKey::new(
1341            LenientImplementationName::Known(uv_python_types::ImplementationName::CPython),
1342            3,
1343            12,
1344            4,
1345            None,
1346            Platform::new(
1347                Os::from_str("linux").unwrap(),
1348                Arch::from_str("x86_64").unwrap(),
1349                Libc::from_str("gnu").unwrap(),
1350            ),
1351            uv_python_types::PythonVariant::default(),
1352        );
1353
1354        ManagedPythonDownload {
1355            key,
1356            url: Cow::Borrowed(url),
1357            sha256: Some(Digest::from_bytes([0xab; 32])),
1358            build: Some("20240713"),
1359        }
1360    }
1361
1362    #[cfg(unix)]
1363    #[tokio::test]
1364    async fn relative_installation_minor_link_resolves() -> anyhow::Result<()> {
1365        let root = tempfile::tempdir_in(std::env::current_dir()?)?;
1366        let download = cpython_download_for_url("https://example.com/python.tar.gz");
1367        let installed = root.path().join(download.key().to_string());
1368        fs_err::create_dir_all(installed.join("bin"))?;
1369        fs_err::write(installed.join("bin/python3.12"), b"interpreter")?;
1370        let relative = uv_fs::relative_to(&installed, std::env::current_dir()?)?;
1371        let installation = ManagedPythonInstallation::new(relative, &download)?;
1372
1373        installation.ensure_minor_version_link().await?;
1374
1375        let minor = root
1376            .path()
1377            .join(installation.minor_version_key().to_string());
1378        assert_eq!(fs_err::read(minor.join("bin/python3.12"))?, b"interpreter");
1379        assert_eq!(
1380            fs_err::canonicalize(minor)?,
1381            fs_err::canonicalize(installed)?
1382        );
1383        Ok(())
1384    }
1385
1386    #[test]
1387    fn test_cpython_mirror_unexpected_download_url_redacts_credentials() {
1388        let download = cpython_download_for_url(
1389            "https://user:password@example.com/cpython.tar.gz?X-Amz-Signature=signature&safe=value",
1390        );
1391
1392        let error = download
1393            .download_urls_with_astral_mirror(
1394                PythonDownloadMirrors {
1395                    cpython: Some("https://python-mirror.example.com/releases/"),
1396                    ..PythonDownloadMirrors::default()
1397                },
1398                None,
1399            )
1400            .expect_err("the download URL should not match the CPython mirror format");
1401
1402        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");
1403    }
1404
1405    #[test]
1406    fn test_cpython_mirror_invalid_download_url() {
1407        let download = cpython_download_for_url("not a URL");
1408
1409        let error = download
1410            .download_urls_with_astral_mirror(
1411                PythonDownloadMirrors {
1412                    cpython: Some("https://python-mirror.example.com/releases/"),
1413                    ..PythonDownloadMirrors::default()
1414                },
1415                None,
1416            )
1417            .expect_err("the download URL should be invalid");
1418
1419        insta::assert_snapshot!(error, @"Invalid download URL");
1420    }
1421
1422    #[test]
1423    fn test_cpython_download_urls_custom_astral_mirror() {
1424        let download = cpython_download_for_url(
1425            "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",
1426        );
1427
1428        let urls = download
1429            .download_urls_with_astral_mirror(
1430                PythonDownloadMirrors::default(),
1431                Some("https://nexus.example.com/repository/releases.astral.sh/"),
1432            )
1433            .expect("download URLs should be valid");
1434        let urls = urls
1435            .into_iter()
1436            .map(|url| url.to_string())
1437            .collect::<Vec<_>>();
1438        assert_eq!(
1439            urls,
1440            vec![
1441                "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"
1442                    .to_string(),
1443            ]
1444        );
1445    }
1446
1447    #[test]
1448    fn test_cpython_specific_mirror_takes_precedence_over_astral_mirror() {
1449        let download = cpython_download_for_url(
1450            "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",
1451        );
1452
1453        let urls = download
1454            .download_urls_with_astral_mirror(
1455                PythonDownloadMirrors {
1456                    cpython: Some("https://python-mirror.example.com/releases/"),
1457                    ..PythonDownloadMirrors::default()
1458                },
1459                Some("https://nexus.example.com/repository/releases.astral.sh/"),
1460            )
1461            .expect("download URLs should be valid");
1462        let urls = urls
1463            .into_iter()
1464            .map(|url| url.to_string())
1465            .collect::<Vec<_>>();
1466        assert_eq!(
1467            urls,
1468            vec![
1469                "https://python-mirror.example.com/releases/20240713/cpython-3.12.4%2B20240713-x86_64-unknown-linux-gnu-install_only.tar.gz"
1470                    .to_string(),
1471            ]
1472        );
1473    }
1474
1475    #[test]
1476    fn test_cpython_download_urls_empty_astral_mirror_uses_default() {
1477        let download = cpython_download_for_url(
1478            "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",
1479        );
1480
1481        let default_urls = download
1482            .download_urls_with_astral_mirror(PythonDownloadMirrors::default(), None)
1483            .expect("download URLs should be valid");
1484        let empty_urls = download
1485            .download_urls_with_astral_mirror(PythonDownloadMirrors::default(), Some(""))
1486            .expect("download URLs should be valid");
1487
1488        assert_eq!(default_urls, empty_urls);
1489    }
1490
1491    /// A hash mismatch is a post-download integrity failure — retrying a different URL cannot fix
1492    /// it, so it should not trigger a fallback.
1493    #[test]
1494    fn test_should_try_next_url_hash_mismatch() {
1495        let err = Error::HashMismatch {
1496            installation: "cpython-3.12.0".to_string(),
1497            expected: "abc".to_string(),
1498            actual: "def".to_string(),
1499        };
1500        assert!(!err.should_try_next_url());
1501    }
1502
1503    /// A local filesystem error during extraction (e.g. permission denied writing to disk) is not
1504    /// a network failure — a different URL would produce the same outcome.
1505    #[test]
1506    fn test_should_try_next_url_extract_error_filesystem() {
1507        let err = Error::ExtractError(
1508            "archive.tar.gz".to_string(),
1509            uv_extract::Error::Io(io::Error::new(io::ErrorKind::PermissionDenied, "")),
1510        );
1511        assert!(!err.should_try_next_url());
1512    }
1513
1514    /// A generic IO error from a local filesystem operation (e.g. permission denied on cache
1515    /// directory) should not trigger a fallback to a different URL.
1516    #[test]
1517    fn test_should_try_next_url_io_error_filesystem() {
1518        let err = Error::Io(io::Error::new(io::ErrorKind::PermissionDenied, ""));
1519        assert!(!err.should_try_next_url());
1520    }
1521
1522    /// A network IO error (e.g. connection reset mid-download) surfaces as `Error::Io` from
1523    /// `download_archive`. It should trigger a fallback because a different mirror may succeed.
1524    #[test]
1525    fn test_should_try_next_url_io_error_network() {
1526        let err = Error::Io(io::Error::new(io::ErrorKind::ConnectionReset, ""));
1527        assert!(err.should_try_next_url());
1528    }
1529
1530    /// A 404 HTTP response from the mirror becomes `Error::NetworkError` — it should trigger a
1531    /// URL fallback, because a 404 on the mirror does not mean the file is absent from GitHub.
1532    #[test]
1533    fn test_should_try_next_url_network_error_404() {
1534        let url =
1535            SafeUrl::from_str("https://releases.astral.sh/python/cpython-3.12.0.tar.gz").unwrap();
1536        // `NetworkError` wraps a `WrappedReqwestError`; we use a middleware error as a
1537        // stand-in because `should_try_next_url` only inspects the variant, not the contents.
1538        let wrapped = WrappedReqwestError::with_problem_details(
1539            reqwest_middleware::Error::Middleware(anyhow::anyhow!("404 Not Found")),
1540            None,
1541        );
1542        let err = Error::NetworkError(url, wrapped);
1543        assert!(err.should_try_next_url());
1544    }
1545
1546    /// Every [`PythonVersion`] in the embedded download metadata must be convertible
1547    /// to a [`VersionRequest`].
1548    #[test]
1549    fn embedded_download_versions_convert_to_version_requests() {
1550        let downloads = ManagedPythonDownloadList::new_only_embedded()
1551            .expect("embedded download metadata should load");
1552
1553        let unique_versions: HashSet<PythonVersion> = downloads
1554            .iter_all()
1555            .map(ManagedPythonDownload::python_version)
1556            .collect();
1557
1558        for version in &unique_versions {
1559            assert!(
1560                VersionRequest::try_from(version).is_ok(),
1561                "invalid embedded download version: {version}"
1562            );
1563        }
1564    }
1565}