Skip to main content

uv_distribution/
distribution_database.rs

1use std::future::Future;
2use std::io;
3use std::path::Path;
4use std::pin::Pin;
5use std::sync::Arc;
6use std::task::{Context, Poll};
7
8use futures::{FutureExt, TryStreamExt};
9use tokio::io::{AsyncRead, AsyncSeekExt, ReadBuf};
10use tokio::sync::Semaphore;
11use tokio_util::compat::FuturesAsyncReadCompatExt;
12use tracing::{Instrument, info_span, instrument, warn};
13use url::Url;
14
15use uv_cache::{ArchiveId, CacheBucket, CacheEntry, WheelCache};
16use uv_cache_info::{CacheInfo, Timestamp};
17use uv_client::{
18    CacheControl, CachedClientError, Connectivity, DataWithCachePolicy, RegistryClient,
19};
20use uv_distribution_filename::{SourceDistExtension, WheelFilename};
21use uv_distribution_types::{
22    BuildInfo, BuildableSource, BuiltDist, Dist, DistRef, File, HashPolicy, Hashed, IndexUrl,
23    InstalledDist, Name, SourceDist, ToUrlError,
24};
25use uv_extract::hash::Hasher;
26use uv_fs::write_atomic;
27use uv_git::{GIT_LFS, GitError};
28use uv_install_wheel::validate_and_heal_record;
29use uv_platform_tags::Tags;
30use uv_pypi_types::{HashDigest, HashDigests, PyProjectToml};
31use uv_python::PythonVariant;
32use uv_redacted::DisplaySafeUrl;
33use uv_types::{BuildContext, BuildStack};
34use uv_warnings::warn_user_once;
35
36use crate::archive::Archive;
37use crate::error::PythonVersion;
38use crate::hash::http_hash_algorithms;
39use crate::metadata::{ArchiveMetadata, Metadata};
40use crate::source::SourceDistributionBuilder;
41use crate::{Error, LocalWheel, Reporter, RequiresDist};
42
43/// A cached high-level interface to convert distributions (a requirement resolved to a location)
44/// to a wheel or wheel metadata.
45///
46/// For wheel metadata, this happens by either fetching the metadata from the remote wheel or by
47/// building the source distribution. For wheel files, either the wheel is downloaded or a source
48/// distribution is downloaded, built and the new wheel gets returned.
49///
50/// All kinds of wheel sources (index, URL, path) and source distribution source (index, URL, path,
51/// Git) are supported.
52///
53/// This struct also has the task of acquiring locks around source dist builds in general and git
54/// operation especially, as well as respecting concurrency limits.
55pub struct DistributionDatabase<'a, Context: BuildContext> {
56    build_context: &'a Context,
57    builder: SourceDistributionBuilder<'a, Context>,
58    client: ManagedClient<'a>,
59    reporter: Option<Arc<dyn Reporter>>,
60}
61
62impl<'a, Context: BuildContext> DistributionDatabase<'a, Context> {
63    pub fn new(
64        client: &'a RegistryClient,
65        build_context: &'a Context,
66        downloads_semaphore: Arc<Semaphore>,
67    ) -> Self {
68        Self {
69            build_context,
70            builder: SourceDistributionBuilder::new(build_context),
71            client: ManagedClient::new(client, downloads_semaphore),
72            reporter: None,
73        }
74    }
75
76    /// Set the build stack to use for the [`DistributionDatabase`].
77    #[must_use]
78    pub fn with_build_stack(self, build_stack: &'a BuildStack) -> Self {
79        Self {
80            builder: self.builder.with_build_stack(build_stack),
81            ..self
82        }
83    }
84
85    /// Set the [`Reporter`] to use for the [`DistributionDatabase`].
86    #[must_use]
87    pub fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
88        Self {
89            builder: self.builder.with_reporter(reporter.clone()),
90            reporter: Some(reporter),
91            ..self
92        }
93    }
94
95    /// Handle a specific `reqwest` error, and convert it to [`io::Error`].
96    fn handle_response_errors(&self, err: reqwest::Error) -> io::Error {
97        if err.is_timeout() {
98            // Assumption: The connect timeout with the 10s default is not the culprit.
99            io::Error::new(
100                io::ErrorKind::TimedOut,
101                format!(
102                    "Failed to download distribution due to network timeout. Try increasing UV_HTTP_TIMEOUT (current value: {}s).",
103                    self.client.unmanaged.read_timeout().as_secs()
104                ),
105            )
106        } else {
107            io::Error::other(err)
108        }
109    }
110
111    /// Either fetch the wheel or fetch and build the source distribution
112    ///
113    /// Returns a wheel that's compliant with the given platform tags.
114    ///
115    /// While hashes will be generated in some cases, hash-checking is only enforced for source
116    /// distributions, and should be enforced by the caller for wheels.
117    #[instrument(skip_all, fields(%dist))]
118    pub async fn get_or_build_wheel(
119        &self,
120        dist: &Dist,
121        tags: &Tags,
122        hashes: HashPolicy<'_>,
123    ) -> Result<LocalWheel, Error> {
124        match dist {
125            Dist::Built(built) => self.get_wheel(built, hashes).await,
126            Dist::Source(source) => self.build_wheel(source, tags, hashes).await,
127        }
128    }
129
130    /// Either fetch the only wheel metadata (directly from the index or with range requests) or
131    /// fetch and build the source distribution.
132    ///
133    /// While hashes will be generated in some cases, hash-checking is only enforced for source
134    /// distributions, and should be enforced by the caller for wheels.
135    #[instrument(skip_all, fields(%dist))]
136    pub async fn get_installed_metadata(
137        &self,
138        dist: &InstalledDist,
139    ) -> Result<ArchiveMetadata, Error> {
140        // If the metadata was provided by the user directly, prefer it.
141        if let Some(metadata) = self
142            .build_context
143            .dependency_metadata()
144            .get(dist.name(), Some(dist.version()))
145        {
146            return Ok(ArchiveMetadata::from_metadata23(metadata.clone()));
147        }
148
149        let metadata = dist
150            .read_metadata()
151            .map_err(|err| Error::ReadInstalled(Box::new(dist.clone()), err))?;
152
153        Ok(ArchiveMetadata::from_metadata23(metadata.clone()))
154    }
155
156    /// Either fetch the only wheel metadata (directly from the index or with range requests) or
157    /// fetch and build the source distribution.
158    ///
159    /// While hashes will be generated in some cases, hash-checking is only enforced for source
160    /// distributions, and should be enforced by the caller for wheels.
161    #[instrument(skip_all, fields(%dist))]
162    pub async fn get_or_build_wheel_metadata(
163        &self,
164        dist: &Dist,
165        hashes: HashPolicy<'_>,
166    ) -> Result<ArchiveMetadata, Error> {
167        match dist {
168            Dist::Built(built) => self.get_wheel_metadata(built, hashes).await,
169            Dist::Source(source) => {
170                self.build_wheel_metadata(&BuildableSource::Dist(source), hashes)
171                    .await
172            }
173        }
174    }
175
176    /// Fetch a wheel from the cache or download it from the index.
177    ///
178    /// While hashes will be generated in all cases, hash-checking is _not_ enforced and should
179    /// instead be enforced by the caller.
180    async fn get_wheel(
181        &self,
182        dist: &BuiltDist,
183        hashes: HashPolicy<'_>,
184    ) -> Result<LocalWheel, Error> {
185        match dist {
186            BuiltDist::Registry(wheels) => {
187                let wheel = wheels.best_wheel();
188                let WheelTarget {
189                    url,
190                    extension,
191                    size,
192                } = WheelTarget::try_from(&*wheel.file)?;
193
194                // Create a cache entry for the wheel.
195                let wheel_entry = self.build_context.cache().entry(
196                    CacheBucket::Wheels,
197                    WheelCache::Index(&wheel.index).wheel_dir(wheel.name().as_ref()),
198                    wheel.filename.cache_key(),
199                );
200
201                // If the URL is a file URL, load the wheel directly.
202                if url.scheme() == "file" {
203                    let path = url
204                        .to_file_path()
205                        .map_err(|()| Error::NonFileUrl(url.clone()))?;
206                    return self
207                        .load_wheel(
208                            &path,
209                            &wheel.filename,
210                            WheelExtension::Whl,
211                            wheel_entry,
212                            dist,
213                            hashes,
214                        )
215                        .await;
216                }
217
218                // Download and unzip.
219                match self
220                    .stream_wheel(
221                        url.clone(),
222                        dist.index(),
223                        &wheel.filename,
224                        extension,
225                        size,
226                        &wheel_entry,
227                        dist,
228                        hashes,
229                    )
230                    .await
231                {
232                    Ok(archive) => Ok(LocalWheel {
233                        dist: Dist::Built(dist.clone()),
234                        archive: self
235                            .build_context
236                            .cache()
237                            .archive(&archive.id)
238                            .into_boxed_path(),
239                        hashes: archive.hashes,
240                        filename: wheel.filename.clone(),
241                        cache: CacheInfo::default(),
242                        build: None,
243                    }),
244                    Err(Error::Extract(name, err)) => {
245                        if err.is_http_streaming_unsupported() {
246                            warn!(
247                                "Streaming unsupported for {dist}; downloading wheel to disk ({err})"
248                            );
249                        } else if err.is_http_streaming_failed() {
250                            warn!("Streaming failed for {dist}; downloading wheel to disk ({err})");
251                        } else {
252                            return Err(Error::Extract(name, err));
253                        }
254
255                        // If the request failed because streaming was unsupported or failed,
256                        // download the wheel directly.
257                        let archive = self
258                            .download_wheel(
259                                url,
260                                dist.index(),
261                                &wheel.filename,
262                                extension,
263                                size,
264                                &wheel_entry,
265                                dist,
266                                hashes,
267                            )
268                            .await?;
269
270                        Ok(LocalWheel {
271                            dist: Dist::Built(dist.clone()),
272                            archive: self
273                                .build_context
274                                .cache()
275                                .archive(&archive.id)
276                                .into_boxed_path(),
277                            hashes: archive.hashes,
278                            filename: wheel.filename.clone(),
279                            cache: CacheInfo::default(),
280                            build: None,
281                        })
282                    }
283                    Err(err) => Err(err),
284                }
285            }
286
287            BuiltDist::DirectUrl(wheel) => {
288                // Create a cache entry for the wheel.
289                let wheel_entry = self.build_context.cache().entry(
290                    CacheBucket::Wheels,
291                    WheelCache::Url(&wheel.url).wheel_dir(wheel.name().as_ref()),
292                    wheel.filename.cache_key(),
293                );
294
295                // Download and unzip.
296                match self
297                    .stream_wheel(
298                        wheel.url.raw().clone(),
299                        None,
300                        &wheel.filename,
301                        WheelExtension::Whl,
302                        None,
303                        &wheel_entry,
304                        dist,
305                        hashes,
306                    )
307                    .await
308                {
309                    Ok(archive) => Ok(LocalWheel {
310                        dist: Dist::Built(dist.clone()),
311                        archive: self
312                            .build_context
313                            .cache()
314                            .archive(&archive.id)
315                            .into_boxed_path(),
316                        hashes: archive.hashes,
317                        filename: wheel.filename.clone(),
318                        cache: CacheInfo::default(),
319                        build: None,
320                    }),
321                    Err(Error::Extract(name, err)) => {
322                        if err.is_http_streaming_unsupported() {
323                            warn!(
324                                "Streaming unsupported for {dist}; downloading wheel to disk ({err})"
325                            );
326                        } else if err.is_http_streaming_failed() {
327                            warn!("Streaming failed for {dist}; downloading wheel to disk ({err})");
328                        } else {
329                            return Err(Error::Extract(name, err));
330                        }
331
332                        // If the request failed because streaming was unsupported or failed,
333                        // download the wheel directly.
334                        let archive = self
335                            .download_wheel(
336                                wheel.url.raw().clone(),
337                                None,
338                                &wheel.filename,
339                                WheelExtension::Whl,
340                                None,
341                                &wheel_entry,
342                                dist,
343                                hashes,
344                            )
345                            .await?;
346                        Ok(LocalWheel {
347                            dist: Dist::Built(dist.clone()),
348                            archive: self
349                                .build_context
350                                .cache()
351                                .archive(&archive.id)
352                                .into_boxed_path(),
353                            hashes: archive.hashes,
354                            filename: wheel.filename.clone(),
355                            cache: CacheInfo::default(),
356                            build: None,
357                        })
358                    }
359                    Err(err) => Err(err),
360                }
361            }
362
363            BuiltDist::GitPath(wheel) => {
364                // Fetch the Git repository.
365                let fetch = self
366                    .build_context
367                    .git()
368                    .fetch(
369                        &wheel.git,
370                        self.client.unmanaged.git_http_settings(wheel.git.url()),
371                        self.build_context.cache().bucket(CacheBucket::Git),
372                        self.reporter.clone().map(<dyn Reporter>::into_git_reporter),
373                    )
374                    .await?;
375
376                if wheel.git.lfs().enabled() && !fetch.lfs_ready() {
377                    if GIT_LFS.is_err() {
378                        return Err(Error::MissingWheelGitLfsArtifacts(
379                            wheel.url.to_url(),
380                            GitError::GitLfsNotFound,
381                        ));
382                    }
383                    return Err(Error::MissingWheelGitLfsArtifacts(
384                        wheel.url.to_url(),
385                        GitError::GitLfsNotConfigured,
386                    ));
387                }
388
389                let git_sha = fetch.git().precise().expect("Exact commit after checkout");
390                let cache_entry = self.build_context.cache().entry(
391                    CacheBucket::Wheels,
392                    WheelCache::Git(&wheel.url, git_sha.as_short_str()).root(),
393                    wheel.filename.stem(),
394                );
395
396                let install_path = fetch.path().join(&wheel.install_path);
397
398                self.load_wheel(
399                    &install_path,
400                    &wheel.filename,
401                    WheelExtension::Whl,
402                    cache_entry,
403                    dist,
404                    hashes,
405                )
406                .await
407            }
408
409            BuiltDist::Path(wheel) => {
410                let cache_entry = self.build_context.cache().entry(
411                    CacheBucket::Wheels,
412                    WheelCache::Url(&wheel.url).wheel_dir(wheel.name().as_ref()),
413                    wheel.filename.cache_key(),
414                );
415
416                self.load_wheel(
417                    &wheel.install_path,
418                    &wheel.filename,
419                    WheelExtension::Whl,
420                    cache_entry,
421                    dist,
422                    hashes,
423                )
424                .await
425            }
426        }
427    }
428
429    /// Convert a source distribution into a wheel, fetching it from the cache or building it if
430    /// necessary.
431    ///
432    /// The returned wheel is guaranteed to come from a distribution with a matching hash, and
433    /// no build processes will be executed for distributions with mismatched hashes.
434    async fn build_wheel(
435        &self,
436        dist: &SourceDist,
437        tags: &Tags,
438        hashes: HashPolicy<'_>,
439    ) -> Result<LocalWheel, Error> {
440        // Warn if the source distribution isn't PEP 625 compliant.
441        // We do this here instead of in `SourceDistExtension::from_path` to minimize log volume:
442        // a non-compliant distribution isn't a huge problem if it's not actually being
443        // materialized into a wheel. Observe that we also allow no extension, since we expect that
444        // for directory and Git installs.
445        // NOTE: Observe that we also allow `.zip` sdists here, which are not PEP 625 compliant.
446        // This is because they were allowed on PyPI until relatively recently (2020).
447        if let Some(extension) = dist.extension()
448            && !matches!(
449                extension,
450                SourceDistExtension::TarGz | SourceDistExtension::Zip
451            )
452        {
453            if matches!(dist, SourceDist::Registry(_)) {
454                // Observe that we display a slightly different warning when the sdist comes
455                // from a registry, since that suggests that the user has inadvertently
456                // (rather than explicitly) depended on a non-compliant sdist.
457                warn_user_once!(
458                    "{dist} uses a legacy source distribution format ('.{extension}') that is not compliant with PEP 625. A future version of uv will reject this source distribution. Consider upgrading to a newer version of {package}",
459                    package = dist.name(),
460                );
461            } else {
462                warn_user_once!(
463                    "{dist} is not a standards-compliant source distribution: expected '.tar.gz' but found '.{extension}'. A future version of uv will reject source distributions that do not meet the requirements specified in PEP 625",
464                );
465            }
466        }
467
468        let built_wheel = self
469            .builder
470            .download_and_build(&BuildableSource::Dist(dist), tags, hashes, &self.client)
471            .boxed_local()
472            .await?;
473
474        // Check that the wheel is compatible with its install target.
475        //
476        // When building a build dependency for a cross-install, the build dependency needs
477        // to install and run on the host instead of the target. In this case the `tags` are already
478        // for the host instead of the target, so this check passes.
479        if !built_wheel.filename.is_compatible(tags) {
480            return if tags.is_cross() {
481                Err(Error::BuiltWheelIncompatibleTargetPlatform {
482                    filename: built_wheel.filename,
483                    python_platform: tags.python_platform().clone(),
484                    python_version: PythonVersion {
485                        version: tags.python_version(),
486                        variant: if tags.is_freethreaded() {
487                            PythonVariant::Freethreaded
488                        } else {
489                            PythonVariant::Default
490                        },
491                    },
492                })
493            } else {
494                Err(Error::BuiltWheelIncompatibleHostPlatform {
495                    filename: built_wheel.filename,
496                    python_platform: tags.python_platform().clone(),
497                    python_version: PythonVersion {
498                        version: tags.python_version(),
499                        variant: if tags.is_freethreaded() {
500                            PythonVariant::Freethreaded
501                        } else {
502                            PythonVariant::Default
503                        },
504                    },
505                })
506            };
507        }
508
509        // Acquire the advisory lock.
510        #[cfg(windows)]
511        let _lock = {
512            let lock_entry = CacheEntry::new(
513                built_wheel.target.parent().unwrap(),
514                format!(
515                    "{}.lock",
516                    built_wheel.target.file_name().unwrap().to_str().unwrap()
517                ),
518            );
519            lock_entry.lock().await.map_err(Error::CacheLock)?
520        };
521
522        // If the wheel was unzipped previously, respect it. Source distributions are
523        // cached under a unique revision ID, so unzipped directories are never stale.
524        match self.build_context.cache().resolve_link(&built_wheel.target) {
525            Ok(archive) => {
526                return Ok(LocalWheel {
527                    dist: Dist::Source(dist.clone()),
528                    archive: archive.into_boxed_path(),
529                    filename: built_wheel.filename,
530                    hashes: built_wheel.hashes,
531                    cache: built_wheel.cache_info,
532                    build: Some(built_wheel.build_info),
533                });
534            }
535            Err(err) if err.kind() == io::ErrorKind::NotFound => {}
536            Err(err) => return Err(Error::CacheRead(err)),
537        }
538
539        // Otherwise, unzip the wheel.
540        let id = self
541            .unzip_wheel(
542                &built_wheel.path,
543                &built_wheel.target,
544                DistRef::Source(dist),
545            )
546            .await?;
547
548        Ok(LocalWheel {
549            dist: Dist::Source(dist.clone()),
550            archive: self.build_context.cache().archive(&id).into_boxed_path(),
551            hashes: built_wheel.hashes,
552            filename: built_wheel.filename,
553            cache: built_wheel.cache_info,
554            build: Some(built_wheel.build_info),
555        })
556    }
557
558    /// Fetch the wheel metadata from the index, or from the cache if possible.
559    ///
560    /// While hashes will be generated in some cases, hash-checking is _not_ enforced and should
561    /// instead be enforced by the caller.
562    async fn get_wheel_metadata(
563        &self,
564        dist: &BuiltDist,
565        hashes: HashPolicy<'_>,
566    ) -> Result<ArchiveMetadata, Error> {
567        // If hash generation is enabled, and the distribution isn't hosted on a registry, get the
568        // entire wheel to ensure that the hashes are included in the response. If the distribution
569        // is hosted on an index, the hashes will be included in the simple metadata response.
570        // For hash _validation_, callers are expected to enforce the policy when retrieving the
571        // wheel.
572        //
573        // Historically, for `uv pip compile --universal`, we also generate hashes for
574        // registry-based distributions when the relevant registry doesn't provide them. This was
575        // motivated by `--find-links`. We continue that behavior (under `HashGeneration::All`) for
576        // backwards compatibility, but it's a little dubious, since we're only hashing _one_
577        // distribution here (as opposed to hashing all distributions for the version), and it may
578        // not even be a compatible distribution!
579        //
580        // TODO(charlie): Request the hashes via a separate method, to reduce the coupling in this API.
581        if hashes.is_generate(dist) {
582            let wheel = self.get_wheel(dist, hashes).await?;
583            // If the metadata was provided by the user directly, prefer it.
584            let metadata = if let Some(metadata) = self
585                .build_context
586                .dependency_metadata()
587                .get(dist.name(), Some(dist.version()))
588            {
589                metadata.clone()
590            } else {
591                wheel.metadata()?
592            };
593            let hashes = wheel.hashes;
594            return Ok(ArchiveMetadata {
595                metadata: Metadata::from_metadata23(metadata),
596                hashes,
597            });
598        }
599
600        // If the metadata was provided by the user directly, prefer it.
601        if let Some(metadata) = self
602            .build_context
603            .dependency_metadata()
604            .get(dist.name(), Some(dist.version()))
605        {
606            return Ok(ArchiveMetadata::from_metadata23(metadata.clone()));
607        }
608
609        let result = self
610            .client
611            .managed(|client| {
612                client
613                    .wheel_metadata(
614                        dist,
615                        self.build_context.git(),
616                        self.build_context.capabilities(),
617                        self.reporter.clone().map(<dyn Reporter>::into_git_reporter),
618                    )
619                    .boxed_local()
620            })
621            .await;
622
623        match result {
624            Ok(metadata) => {
625                // Validate that the metadata is consistent with the distribution.
626                Ok(ArchiveMetadata::from_metadata23(metadata))
627            }
628            Err(err) if err.is_http_streaming_unsupported() => {
629                warn!(
630                    "Streaming unsupported when fetching metadata for {dist}; downloading wheel directly ({err})"
631                );
632
633                // If the request failed due to an error that could be resolved by
634                // downloading the wheel directly, try that.
635                let wheel = self.get_wheel(dist, hashes).await?;
636                let metadata = wheel.metadata()?;
637                let hashes = wheel.hashes;
638                Ok(ArchiveMetadata {
639                    metadata: Metadata::from_metadata23(metadata),
640                    hashes,
641                })
642            }
643            Err(err) => Err(err.into()),
644        }
645    }
646
647    /// Build the wheel metadata for a source distribution, or fetch it from the cache if possible.
648    ///
649    /// The returned metadata is guaranteed to come from a distribution with a matching hash, and
650    /// no build processes will be executed for distributions with mismatched hashes.
651    pub async fn build_wheel_metadata(
652        &self,
653        source: &BuildableSource<'_>,
654        hashes: HashPolicy<'_>,
655    ) -> Result<ArchiveMetadata, Error> {
656        // If the metadata was provided by the user directly, prefer it.
657        if let Some(dist) = source.as_dist() {
658            if let Some(metadata) = self
659                .build_context
660                .dependency_metadata()
661                .get(dist.name(), dist.version())
662            {
663                // If we skipped the build, we should still resolve any Git dependencies to precise
664                // commits.
665                self.builder.resolve_revision(source, &self.client).await?;
666
667                return Ok(ArchiveMetadata::from_metadata23(metadata.clone()));
668            }
669        }
670
671        let metadata = self
672            .builder
673            .download_and_build_metadata(source, hashes, &self.client)
674            .boxed_local()
675            .await?;
676
677        Ok(metadata)
678    }
679
680    /// Return the [`RequiresDist`] from a `pyproject.toml`, if it can be statically extracted.
681    pub async fn requires_dist(
682        &self,
683        path: &Path,
684        pyproject_toml: &PyProjectToml,
685    ) -> Result<Option<RequiresDist>, Error> {
686        self.builder
687            .source_tree_requires_dist(
688                path,
689                pyproject_toml,
690                self.client.unmanaged.credentials_cache(),
691            )
692            .await
693    }
694
695    /// Stream a wheel from a URL, unzipping it into the cache as it's downloaded.
696    async fn stream_wheel(
697        &self,
698        url: DisplaySafeUrl,
699        index: Option<&IndexUrl>,
700        filename: &WheelFilename,
701        extension: WheelExtension,
702        size: Option<u64>,
703        wheel_entry: &CacheEntry,
704        dist: &BuiltDist,
705        hashes: HashPolicy<'_>,
706    ) -> Result<Archive, Error> {
707        // Acquire an advisory lock, to guard against concurrent writes.
708        #[cfg(windows)]
709        let _lock = {
710            let lock_entry = wheel_entry.with_file(format!("{}.lock", filename.stem()));
711            lock_entry.lock().await.map_err(Error::CacheLock)?
712        };
713
714        // Create an entry for the HTTP cache.
715        let http_entry = wheel_entry.with_file(format!("{}.http", filename.cache_key()));
716
717        let query_url = &url.clone();
718
719        let download = |response: reqwest::Response| {
720            async {
721                let size = size.or_else(|| content_length(&response));
722
723                let progress = self
724                    .reporter
725                    .as_ref()
726                    .map(|reporter| (reporter, reporter.on_download_start(dist.name(), size)));
727
728                let reader = response
729                    .bytes_stream()
730                    .map_err(|err| self.handle_response_errors(err))
731                    .into_async_read();
732
733                // Create a hasher for each hash algorithm.
734                let algorithms = http_hash_algorithms(hashes);
735                let mut hashers = algorithms.into_iter().map(Hasher::from).collect::<Vec<_>>();
736                let mut hasher = uv_extract::hash::HashReader::new(reader.compat(), &mut hashers);
737
738                // Download and unzip the wheel to a temporary directory.
739                let temp_dir = tempfile::tempdir_in(self.build_context.cache().root())
740                    .map_err(Error::CacheWrite)?;
741
742                let files = match progress {
743                    Some((reporter, progress)) => {
744                        let mut reader = ProgressReader::new(&mut hasher, progress, &**reporter);
745                        match extension {
746                            WheelExtension::Whl => {
747                                uv_extract::stream::unzip(query_url, &mut reader, temp_dir.path())
748                                    .await
749                                    .map_err(|err| Error::Extract(filename.to_string(), err))?
750                            }
751                            WheelExtension::WhlZst => {
752                                uv_extract::stream::untar_zst(&mut reader, temp_dir.path())
753                                    .await
754                                    .map_err(|err| Error::Extract(filename.to_string(), err))?
755                            }
756                        }
757                    }
758                    None => match extension {
759                        WheelExtension::Whl => {
760                            uv_extract::stream::unzip(query_url, &mut hasher, temp_dir.path())
761                                .await
762                                .map_err(|err| Error::Extract(filename.to_string(), err))?
763                        }
764                        WheelExtension::WhlZst => {
765                            uv_extract::stream::untar_zst(&mut hasher, temp_dir.path())
766                                .await
767                                .map_err(|err| Error::Extract(filename.to_string(), err))?
768                        }
769                    },
770                };
771                // Exhaust the reader to compute the hashes.
772                hasher.finish().await.map_err(Error::HashExhaustion)?;
773
774                // Before we make the wheel accessible by persisting it, ensure that the RECORD is
775                // valid.
776                validate_and_heal_record(temp_dir.path(), files.iter(), dist)
777                    .map_err(Error::InstallWheelError)?;
778
779                // Persist the temporary directory to the directory store.
780                let id = self
781                    .build_context
782                    .cache()
783                    .persist(temp_dir.keep(), wheel_entry.path())
784                    .await
785                    .map_err(Error::CacheRead)?;
786
787                if let Some((reporter, progress)) = progress {
788                    reporter.on_download_complete(dist.name(), progress);
789                }
790
791                Ok(Archive::new(
792                    id,
793                    hashers.into_iter().map(HashDigest::from).collect(),
794                    filename.clone(),
795                ))
796            }
797            .instrument(info_span!("wheel", wheel = %dist))
798        };
799
800        // Fetch the archive from the cache, or download it if necessary.
801        let req = self.request(url.clone())?;
802
803        // Determine the cache control policy for the URL.
804        let cache_control = match self.client.unmanaged.connectivity() {
805            Connectivity::Online => {
806                if let Some(header) = index.and_then(|index| {
807                    self.build_context
808                        .locations()
809                        .artifact_cache_control_for(index)
810                }) {
811                    CacheControl::Override(header)
812                } else {
813                    CacheControl::from(
814                        self.build_context
815                            .cache()
816                            .freshness(&http_entry, Some(&filename.name), None)
817                            .map_err(Error::CacheRead)?,
818                    )
819                }
820            }
821            Connectivity::Offline => CacheControl::AllowStale,
822        };
823
824        let archive = self
825            .client
826            .managed(|client| {
827                client.cached_client().get_serde_with_retry(
828                    req,
829                    &http_entry,
830                    cache_control.clone(),
831                    download,
832                )
833            })
834            .await
835            .map_err(|err| match err {
836                CachedClientError::Callback { err, .. } => err,
837                CachedClientError::Client(err) => Error::Client(err),
838            })?;
839
840        // If the archive is missing the required hashes, or has since been removed, force a refresh.
841        let archive = Some(archive)
842            .filter(|archive| archive.has_digests(hashes))
843            .filter(|archive| archive.exists(self.build_context.cache()));
844
845        let archive = if let Some(archive) = archive {
846            archive
847        } else {
848            self.client
849                .managed(async |client| {
850                    client
851                        .cached_client()
852                        .skip_cache_with_retry(
853                            self.request(url)?,
854                            &http_entry,
855                            cache_control,
856                            download,
857                        )
858                        .await
859                        .map_err(|err| match err {
860                            CachedClientError::Callback { err, .. } => err,
861                            CachedClientError::Client(err) => Error::Client(err),
862                        })
863                })
864                .await?
865        };
866
867        Ok(archive)
868    }
869
870    /// Download a wheel from a URL, then unzip it into the cache.
871    async fn download_wheel(
872        &self,
873        url: DisplaySafeUrl,
874        index: Option<&IndexUrl>,
875        filename: &WheelFilename,
876        extension: WheelExtension,
877        size: Option<u64>,
878        wheel_entry: &CacheEntry,
879        dist: &BuiltDist,
880        hashes: HashPolicy<'_>,
881    ) -> Result<Archive, Error> {
882        // Acquire an advisory lock, to guard against concurrent writes.
883        #[cfg(windows)]
884        let _lock = {
885            let lock_entry = wheel_entry.with_file(format!("{}.lock", filename.stem()));
886            lock_entry.lock().await.map_err(Error::CacheLock)?
887        };
888
889        // Create an entry for the HTTP cache.
890        let http_entry = wheel_entry.with_file(format!("{}.http", filename.cache_key()));
891
892        let download = |response: reqwest::Response| {
893            async {
894                let size = size.or_else(|| content_length(&response));
895
896                let progress = self
897                    .reporter
898                    .as_ref()
899                    .map(|reporter| (reporter, reporter.on_download_start(dist.name(), size)));
900
901                let reader = response
902                    .bytes_stream()
903                    .map_err(|err| self.handle_response_errors(err))
904                    .into_async_read();
905                let algorithms = http_hash_algorithms(hashes);
906                let mut hashers = algorithms.into_iter().map(Hasher::from).collect::<Vec<_>>();
907                let mut hasher = uv_extract::hash::HashReader::new(reader.compat(), &mut hashers);
908
909                // Download the wheel to a temporary file.
910                let temp_file = tempfile::tempfile_in(self.build_context.cache().root())
911                    .map_err(Error::CacheWrite)?;
912                let mut writer = tokio::io::BufWriter::new(fs_err::tokio::File::from_std(
913                    // It's an unnamed file on Linux so that's the best approximation.
914                    fs_err::File::from_parts(temp_file, self.build_context.cache().root()),
915                ));
916
917                match progress {
918                    Some((reporter, progress)) => {
919                        // Wrap the reader in a progress reporter. This will report 100% progress once
920                        // the download is complete, before the wheel is unzipped.
921                        let mut reader = ProgressReader::new(&mut hasher, progress, &**reporter);
922
923                        tokio::io::copy(&mut reader, &mut writer)
924                            .await
925                            .map_err(Error::CacheWrite)?;
926                    }
927                    None => {
928                        tokio::io::copy(&mut hasher, &mut writer)
929                            .await
930                            .map_err(Error::CacheWrite)?;
931                    }
932                }
933
934                // Unzip the wheel to a temporary directory.
935                let temp_dir = tempfile::tempdir_in(self.build_context.cache().root())
936                    .map_err(Error::CacheWrite)?;
937                let mut file = writer.into_inner();
938                file.seek(io::SeekFrom::Start(0))
939                    .await
940                    .map_err(Error::CacheWrite)?;
941
942                let target = temp_dir.path().to_owned();
943                let files = match extension {
944                    WheelExtension::Whl => {
945                        let file = file.into_std().await;
946                        tokio::task::spawn_blocking(move || uv_extract::unzip(file, &target))
947                            .await?
948                    }
949                    WheelExtension::WhlZst => uv_extract::stream::untar_zst(file, &target).await,
950                }
951                .map_err(|err| Error::Extract(filename.to_string(), err))?;
952                let hashes = hashers.into_iter().map(HashDigest::from).collect();
953
954                // Before we make the wheel accessible by persisting it, ensure that the RECORD is
955                // valid.
956                validate_and_heal_record(temp_dir.path(), files.iter(), dist)
957                    .map_err(Error::InstallWheelError)?;
958
959                // Persist the temporary directory to the directory store.
960                let id = self
961                    .build_context
962                    .cache()
963                    .persist(temp_dir.keep(), wheel_entry.path())
964                    .await
965                    .map_err(Error::CacheRead)?;
966
967                if let Some((reporter, progress)) = progress {
968                    reporter.on_download_complete(dist.name(), progress);
969                }
970
971                Ok(Archive::new(id, hashes, filename.clone()))
972            }
973            .instrument(info_span!("wheel", wheel = %dist))
974        };
975
976        // Fetch the archive from the cache, or download it if necessary.
977        let req = self.request(url.clone())?;
978
979        // Determine the cache control policy for the URL.
980        let cache_control = match self.client.unmanaged.connectivity() {
981            Connectivity::Online => {
982                if let Some(header) = index.and_then(|index| {
983                    self.build_context
984                        .locations()
985                        .artifact_cache_control_for(index)
986                }) {
987                    CacheControl::Override(header)
988                } else {
989                    CacheControl::from(
990                        self.build_context
991                            .cache()
992                            .freshness(&http_entry, Some(&filename.name), None)
993                            .map_err(Error::CacheRead)?,
994                    )
995                }
996            }
997            Connectivity::Offline => CacheControl::AllowStale,
998        };
999
1000        let archive = self
1001            .client
1002            .managed(|client| {
1003                client.cached_client().get_serde_with_retry(
1004                    req,
1005                    &http_entry,
1006                    cache_control.clone(),
1007                    download,
1008                )
1009            })
1010            .await
1011            .map_err(|err| match err {
1012                CachedClientError::Callback { err, .. } => err,
1013                CachedClientError::Client(err) => Error::Client(err),
1014            })?;
1015
1016        // If the archive is missing the required hashes, or has since been removed, force a refresh.
1017        let archive = Some(archive)
1018            .filter(|archive| archive.has_digests(hashes))
1019            .filter(|archive| archive.exists(self.build_context.cache()));
1020
1021        let archive = if let Some(archive) = archive {
1022            archive
1023        } else {
1024            self.client
1025                .managed(async |client| {
1026                    client
1027                        .cached_client()
1028                        .skip_cache_with_retry(
1029                            self.request(url)?,
1030                            &http_entry,
1031                            cache_control,
1032                            download,
1033                        )
1034                        .await
1035                        .map_err(|err| match err {
1036                            CachedClientError::Callback { err, .. } => err,
1037                            CachedClientError::Client(err) => Error::Client(err),
1038                        })
1039                })
1040                .await?
1041        };
1042
1043        Ok(archive)
1044    }
1045
1046    /// Load a wheel from a local path.
1047    async fn load_wheel(
1048        &self,
1049        path: &Path,
1050        filename: &WheelFilename,
1051        extension: WheelExtension,
1052        wheel_entry: CacheEntry,
1053        dist: &BuiltDist,
1054        hashes: HashPolicy<'_>,
1055    ) -> Result<LocalWheel, Error> {
1056        #[cfg(windows)]
1057        let _lock = {
1058            let lock_entry = wheel_entry.with_file(format!("{}.lock", filename.stem()));
1059            lock_entry.lock().await.map_err(Error::CacheLock)?
1060        };
1061
1062        // Determine the last-modified time of the wheel.
1063        let modified = Timestamp::from_path(path).map_err(Error::CacheRead)?;
1064
1065        // Attempt to read the archive pointer from the cache.
1066        let pointer_entry = wheel_entry.with_file(format!("{}.rev", filename.cache_key()));
1067        let pointer = PathArchivePointer::read_from(&pointer_entry)?;
1068
1069        // Extract the archive from the pointer.
1070        let archive = pointer
1071            .filter(|pointer| pointer.is_up_to_date(modified))
1072            .map(PathArchivePointer::into_archive)
1073            .filter(|archive| archive.has_digests(hashes));
1074
1075        // If the file is already unzipped, and the cache is up-to-date, return it.
1076        if let Some(archive) = archive {
1077            Ok(LocalWheel {
1078                dist: Dist::Built(dist.clone()),
1079                archive: self
1080                    .build_context
1081                    .cache()
1082                    .archive(&archive.id)
1083                    .into_boxed_path(),
1084                hashes: archive.hashes,
1085                filename: filename.clone(),
1086                cache: CacheInfo::from_timestamp(modified),
1087                build: None,
1088            })
1089        } else if hashes.is_none() {
1090            // Otherwise, unzip the wheel.
1091            let archive = Archive::new(
1092                self.unzip_wheel(path, wheel_entry.path(), DistRef::Built(dist))
1093                    .await?,
1094                HashDigests::empty(),
1095                filename.clone(),
1096            );
1097
1098            // Write the archive pointer to the cache.
1099            let pointer = PathArchivePointer {
1100                timestamp: modified,
1101                archive: archive.clone(),
1102            };
1103            pointer.write_to(&pointer_entry).await?;
1104
1105            Ok(LocalWheel {
1106                dist: Dist::Built(dist.clone()),
1107                archive: self
1108                    .build_context
1109                    .cache()
1110                    .archive(&archive.id)
1111                    .into_boxed_path(),
1112                hashes: archive.hashes,
1113                filename: filename.clone(),
1114                cache: CacheInfo::from_timestamp(modified),
1115                build: None,
1116            })
1117        } else {
1118            // If necessary, compute the hashes of the wheel.
1119            let file = fs_err::tokio::File::open(path)
1120                .await
1121                .map_err(Error::CacheRead)?;
1122            let temp_dir = tempfile::tempdir_in(self.build_context.cache().root())
1123                .map_err(Error::CacheWrite)?;
1124
1125            // Create a hasher for each hash algorithm.
1126            let algorithms = hashes.algorithms();
1127            let mut hashers = algorithms.into_iter().map(Hasher::from).collect::<Vec<_>>();
1128            let mut hasher = uv_extract::hash::HashReader::new(file, &mut hashers);
1129
1130            // Unzip the wheel to a temporary directory.
1131            let files = match extension {
1132                WheelExtension::Whl => {
1133                    uv_extract::stream::unzip(path.display(), &mut hasher, temp_dir.path())
1134                        .await
1135                        .map_err(|err| Error::Extract(filename.to_string(), err))?
1136                }
1137                WheelExtension::WhlZst => {
1138                    uv_extract::stream::untar_zst(&mut hasher, temp_dir.path())
1139                        .await
1140                        .map_err(|err| Error::Extract(filename.to_string(), err))?
1141                }
1142            };
1143
1144            // Exhaust the reader to compute the hash.
1145            hasher.finish().await.map_err(Error::HashExhaustion)?;
1146
1147            let hashes = hashers.into_iter().map(HashDigest::from).collect();
1148
1149            // Before we make the wheel accessible by persisting it, ensure that the RECORD is
1150            // valid.
1151            validate_and_heal_record(temp_dir.path(), files.iter(), dist)
1152                .map_err(Error::InstallWheelError)?;
1153
1154            // Persist the temporary directory to the directory store.
1155            let id = self
1156                .build_context
1157                .cache()
1158                .persist(temp_dir.keep(), wheel_entry.path())
1159                .await
1160                .map_err(Error::CacheWrite)?;
1161
1162            // Create an archive.
1163            let archive = Archive::new(id, hashes, filename.clone());
1164
1165            // Write the archive pointer to the cache.
1166            let pointer = PathArchivePointer {
1167                timestamp: modified,
1168                archive: archive.clone(),
1169            };
1170            pointer.write_to(&pointer_entry).await?;
1171
1172            Ok(LocalWheel {
1173                dist: Dist::Built(dist.clone()),
1174                archive: self
1175                    .build_context
1176                    .cache()
1177                    .archive(&archive.id)
1178                    .into_boxed_path(),
1179                hashes: archive.hashes,
1180                filename: filename.clone(),
1181                cache: CacheInfo::from_timestamp(modified),
1182                build: None,
1183            })
1184        }
1185    }
1186
1187    /// Unzip a wheel into the cache, returning the path to the unzipped directory.
1188    async fn unzip_wheel(
1189        &self,
1190        path: &Path,
1191        target: &Path,
1192        dist: DistRef<'_>,
1193    ) -> Result<ArchiveId, Error> {
1194        let (temp_dir, files) = tokio::task::spawn_blocking({
1195            let path = path.to_owned();
1196            let root = self.build_context.cache().root().to_path_buf();
1197            move || -> Result<_, Error> {
1198                // Unzip the wheel into a temporary directory.
1199                let temp_dir = tempfile::tempdir_in(root).map_err(Error::CacheWrite)?;
1200                let reader = fs_err::File::open(&path).map_err(Error::CacheWrite)?;
1201                let files = uv_extract::unzip(reader, temp_dir.path())
1202                    .map_err(|err| Error::Extract(path.to_string_lossy().into_owned(), err))?;
1203                Ok((temp_dir, files))
1204            }
1205        })
1206        .await??;
1207
1208        // Before we make the wheel accessible by persisting it, ensure that the RECORD is valid.
1209        validate_and_heal_record(temp_dir.path(), files.iter(), dist)
1210            .map_err(Error::InstallWheelError)?;
1211
1212        // Persist the temporary directory to the directory store.
1213        let id = self
1214            .build_context
1215            .cache()
1216            .persist(temp_dir.keep(), target)
1217            .await
1218            .map_err(Error::CacheWrite)?;
1219
1220        Ok(id)
1221    }
1222
1223    /// Returns a GET [`reqwest::Request`] for the given URL.
1224    fn request(&self, url: DisplaySafeUrl) -> Result<reqwest::Request, reqwest::Error> {
1225        self.client
1226            .unmanaged
1227            .uncached_client(&url)
1228            .get(Url::from(url))
1229            .header(
1230                // `reqwest` defaults to accepting compressed responses.
1231                // Specify identity encoding to get consistent .whl downloading
1232                // behavior from servers. ref: https://github.com/pypa/pip/pull/1688
1233                "accept-encoding",
1234                reqwest::header::HeaderValue::from_static("identity"),
1235            )
1236            .build()
1237    }
1238
1239    /// Return the [`ManagedClient`] used by this resolver.
1240    pub fn client(&self) -> &ManagedClient<'a> {
1241        &self.client
1242    }
1243}
1244
1245/// A wrapper around `RegistryClient` that manages a concurrency limit.
1246pub struct ManagedClient<'a> {
1247    pub unmanaged: &'a RegistryClient,
1248    control: Arc<Semaphore>,
1249}
1250
1251impl<'a> ManagedClient<'a> {
1252    /// Create a new `ManagedClient` using the given client and concurrency semaphore.
1253    fn new(client: &'a RegistryClient, control: Arc<Semaphore>) -> Self {
1254        ManagedClient {
1255            unmanaged: client,
1256            control,
1257        }
1258    }
1259
1260    /// Perform a request using the client, respecting the concurrency limit.
1261    ///
1262    /// If the concurrency limit has been reached, this method will wait until a pending
1263    /// operation completes before executing the closure.
1264    pub async fn managed<F, T>(&self, f: impl FnOnce(&'a RegistryClient) -> F) -> T
1265    where
1266        F: Future<Output = T>,
1267    {
1268        let _permit = self.control.acquire().await.unwrap();
1269        f(self.unmanaged).await
1270    }
1271
1272    /// Perform a request using a client that internally manages the concurrency limit.
1273    ///
1274    /// The callback is passed the client and a semaphore. It must acquire the semaphore before
1275    /// any request through the client and drop it after.
1276    ///
1277    /// This method serves as an escape hatch for functions that may want to send multiple requests
1278    /// in parallel.
1279    pub async fn manual<F, T>(&'a self, f: impl FnOnce(&'a RegistryClient, &'a Semaphore) -> F) -> T
1280    where
1281        F: Future<Output = T>,
1282    {
1283        f(self.unmanaged, &self.control).await
1284    }
1285}
1286
1287/// Returns the value of the `Content-Length` header from the [`reqwest::Response`], if present.
1288fn content_length(response: &reqwest::Response) -> Option<u64> {
1289    response
1290        .headers()
1291        .get(reqwest::header::CONTENT_LENGTH)
1292        .and_then(|val| val.to_str().ok())
1293        .and_then(|val| val.parse::<u64>().ok())
1294}
1295
1296/// An asynchronous reader that reports progress as bytes are read.
1297struct ProgressReader<'a, R> {
1298    reader: R,
1299    index: usize,
1300    reporter: &'a dyn Reporter,
1301}
1302
1303impl<'a, R> ProgressReader<'a, R> {
1304    /// Create a new [`ProgressReader`] that wraps another reader.
1305    fn new(reader: R, index: usize, reporter: &'a dyn Reporter) -> Self {
1306        Self {
1307            reader,
1308            index,
1309            reporter,
1310        }
1311    }
1312}
1313
1314impl<R> AsyncRead for ProgressReader<'_, R>
1315where
1316    R: AsyncRead + Unpin,
1317{
1318    fn poll_read(
1319        mut self: Pin<&mut Self>,
1320        cx: &mut Context<'_>,
1321        buf: &mut ReadBuf<'_>,
1322    ) -> Poll<io::Result<()>> {
1323        Pin::new(&mut self.as_mut().reader)
1324            .poll_read(cx, buf)
1325            .map_ok(|()| {
1326                self.reporter
1327                    .on_download_progress(self.index, buf.filled().len() as u64);
1328            })
1329    }
1330}
1331
1332/// A pointer to an archive in the cache, fetched from an HTTP archive.
1333///
1334/// Encoded with `MsgPack`, and represented on disk by a `.http` file.
1335#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1336pub struct HttpArchivePointer {
1337    archive: Archive,
1338}
1339
1340impl HttpArchivePointer {
1341    /// Read an [`HttpArchivePointer`] from the cache.
1342    pub fn read_from(path: impl AsRef<Path>) -> Result<Option<Self>, Error> {
1343        match fs_err::File::open(path.as_ref()) {
1344            Ok(file) => {
1345                let data = DataWithCachePolicy::from_reader(file)?.data;
1346                let archive = rmp_serde::from_slice::<Archive>(&data)?;
1347                Ok(Some(Self { archive }))
1348            }
1349            Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
1350            Err(err) => Err(Error::CacheRead(err)),
1351        }
1352    }
1353
1354    /// Return the [`Archive`] from the pointer.
1355    pub fn into_archive(self) -> Archive {
1356        self.archive
1357    }
1358
1359    /// Return the [`CacheInfo`] from the pointer.
1360    pub fn to_cache_info(&self) -> CacheInfo {
1361        CacheInfo::default()
1362    }
1363
1364    /// Return the [`BuildInfo`] from the pointer.
1365    pub fn to_build_info(&self) -> Option<BuildInfo> {
1366        None
1367    }
1368}
1369
1370/// A pointer to an archive in the cache, fetched from a local path.
1371///
1372/// Encoded with `MsgPack`, and represented on disk by a `.rev` file.
1373#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1374pub struct PathArchivePointer {
1375    timestamp: Timestamp,
1376    archive: Archive,
1377}
1378
1379impl PathArchivePointer {
1380    /// Read an [`PathArchivePointer`] from the cache.
1381    pub fn read_from(path: impl AsRef<Path>) -> Result<Option<Self>, Error> {
1382        match fs_err::read(path) {
1383            Ok(cached) => Ok(Some(rmp_serde::from_slice::<Self>(&cached)?)),
1384            Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
1385            Err(err) => Err(Error::CacheRead(err)),
1386        }
1387    }
1388
1389    /// Write an [`PathArchivePointer`] to the cache.
1390    async fn write_to(&self, entry: &CacheEntry) -> Result<(), Error> {
1391        write_atomic(entry.path(), rmp_serde::to_vec(&self)?)
1392            .await
1393            .map_err(Error::CacheWrite)
1394    }
1395
1396    /// Returns `true` if the archive is up-to-date with the given modified timestamp.
1397    pub fn is_up_to_date(&self, modified: Timestamp) -> bool {
1398        self.timestamp == modified
1399    }
1400
1401    /// Return the [`Archive`] from the pointer.
1402    pub fn into_archive(self) -> Archive {
1403        self.archive
1404    }
1405
1406    /// Return the [`CacheInfo`] from the pointer.
1407    pub fn to_cache_info(&self) -> CacheInfo {
1408        CacheInfo::from_timestamp(self.timestamp)
1409    }
1410
1411    /// Return the [`BuildInfo`] from the pointer.
1412    pub fn to_build_info(&self) -> Option<BuildInfo> {
1413        None
1414    }
1415}
1416
1417#[derive(Debug, Clone)]
1418struct WheelTarget {
1419    /// The URL from which the wheel can be downloaded.
1420    url: DisplaySafeUrl,
1421    /// The expected extension of the wheel file.
1422    extension: WheelExtension,
1423    /// The expected size of the wheel file, if known.
1424    size: Option<u64>,
1425}
1426
1427impl TryFrom<&File> for WheelTarget {
1428    type Error = ToUrlError;
1429
1430    /// Determine the [`WheelTarget`] from a [`File`].
1431    fn try_from(file: &File) -> Result<Self, Self::Error> {
1432        let url = file.url.to_url()?;
1433        if let Some(zstd) = file.zstd.as_ref() {
1434            Ok(Self {
1435                url: add_tar_zst_extension(url),
1436                extension: WheelExtension::WhlZst,
1437                size: zstd.size,
1438            })
1439        } else {
1440            Ok(Self {
1441                url,
1442                extension: WheelExtension::Whl,
1443                size: file.size,
1444            })
1445        }
1446    }
1447}
1448
1449#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1450enum WheelExtension {
1451    /// A `.whl` file.
1452    Whl,
1453    /// A `.whl.tar.zst` file.
1454    WhlZst,
1455}
1456
1457/// Add `.tar.zst` to the end of the URL path, if it doesn't already exist.
1458#[must_use]
1459fn add_tar_zst_extension(mut url: DisplaySafeUrl) -> DisplaySafeUrl {
1460    let mut path = url.path().to_string();
1461
1462    if !path.ends_with(".tar.zst") {
1463        path.push_str(".tar.zst");
1464    }
1465
1466    url.set_path(&path);
1467    url
1468}
1469
1470#[cfg(test)]
1471mod tests {
1472    use super::*;
1473
1474    #[test]
1475    fn test_add_tar_zst_extension() {
1476        let url =
1477            DisplaySafeUrl::parse("https://files.pythonhosted.org/flask-3.1.0-py3-none-any.whl")
1478                .unwrap();
1479        assert_eq!(
1480            add_tar_zst_extension(url).as_str(),
1481            "https://files.pythonhosted.org/flask-3.1.0-py3-none-any.whl.tar.zst"
1482        );
1483
1484        let url = DisplaySafeUrl::parse(
1485            "https://files.pythonhosted.org/flask-3.1.0-py3-none-any.whl.tar.zst",
1486        )
1487        .unwrap();
1488        assert_eq!(
1489            add_tar_zst_extension(url).as_str(),
1490            "https://files.pythonhosted.org/flask-3.1.0-py3-none-any.whl.tar.zst"
1491        );
1492
1493        let url = DisplaySafeUrl::parse(
1494            "https://files.pythonhosted.org/flask-3.1.0%2Bcu124-py3-none-any.whl",
1495        )
1496        .unwrap();
1497        assert_eq!(
1498            add_tar_zst_extension(url).as_str(),
1499            "https://files.pythonhosted.org/flask-3.1.0%2Bcu124-py3-none-any.whl.tar.zst"
1500        );
1501    }
1502}