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));
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
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));
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            {
812                CacheControl::Override(header)
813            }
814            Connectivity::Online => CacheControl::from(
815                self.build_context
816                    .cache()
817                    .freshness(&http_entry, Some(&filename.name), None)
818                    .map_err(Error::CacheRead)?,
819            ),
820            Connectivity::Offline => CacheControl::AllowStale,
821        };
822
823        let archive = self
824            .client
825            .managed(|client| {
826                client.cached_client().get_serde_with_retry(
827                    req,
828                    &http_entry,
829                    cache_control.clone(),
830                    download,
831                )
832            })
833            .await
834            .map_err(|err| match err {
835                CachedClientError::Callback { err, .. } => err,
836                CachedClientError::Client(err) => Error::Client(err),
837            })?;
838
839        // If the archive is missing the required hashes, or has since been removed, force a refresh.
840        let archive = Some(archive)
841            .filter(|archive| archive.has_digests(hashes))
842            .filter(|archive| archive.exists(self.build_context.cache()));
843
844        let archive = if let Some(archive) = archive {
845            archive
846        } else {
847            self.client
848                .managed(async |client| {
849                    client
850                        .cached_client()
851                        .skip_cache_with_retry(
852                            self.request(url)?,
853                            &http_entry,
854                            cache_control,
855                            download,
856                        )
857                        .await
858                        .map_err(|err| match err {
859                            CachedClientError::Callback { err, .. } => err,
860                            CachedClientError::Client(err) => Error::Client(err),
861                        })
862                })
863                .await?
864        };
865
866        Ok(archive)
867    }
868
869    /// Download a wheel from a URL, then unzip it into the cache.
870    async fn download_wheel(
871        &self,
872        url: DisplaySafeUrl,
873        index: Option<&IndexUrl>,
874        filename: &WheelFilename,
875        extension: WheelExtension,
876        size: Option<u64>,
877        wheel_entry: &CacheEntry,
878        dist: &BuiltDist,
879        hashes: HashPolicy<'_>,
880    ) -> Result<Archive, Error> {
881        // Acquire an advisory lock, to guard against concurrent writes.
882        #[cfg(windows)]
883        let _lock = {
884            let lock_entry = wheel_entry.with_file(format!("{}.lock", filename.stem()));
885            lock_entry.lock().await.map_err(Error::CacheLock)?
886        };
887
888        // Create an entry for the HTTP cache.
889        let http_entry = wheel_entry.with_file(format!("{}.http", filename.cache_key()));
890
891        let download = |response: reqwest::Response| {
892            async {
893                let size = size.or_else(|| content_length(&response));
894
895                let progress = self
896                    .reporter
897                    .as_ref()
898                    .map(|reporter| (reporter, reporter.on_download_start(dist.name(), size)));
899
900                let reader = response
901                    .bytes_stream()
902                    .map_err(|err| self.handle_response_errors(err))
903                    .into_async_read();
904                let algorithms = http_hash_algorithms(hashes);
905                let mut hashers = algorithms.into_iter().map(Hasher::from).collect::<Vec<_>>();
906                let mut hasher = uv_extract::hash::HashReader::new(reader.compat(), &mut hashers);
907
908                // Download the wheel to a temporary file.
909                let temp_file = tempfile::tempfile_in(self.build_context.cache().root())
910                    .map_err(Error::CacheWrite)?;
911                let mut writer = tokio::io::BufWriter::new(fs_err::tokio::File::from_std(
912                    // It's an unnamed file on Linux so that's the best approximation.
913                    fs_err::File::from_parts(temp_file, self.build_context.cache().root()),
914                ));
915
916                match progress {
917                    Some((reporter, progress)) => {
918                        // Wrap the reader in a progress reporter. This will report 100% progress once
919                        // the download is complete, before the wheel is unzipped.
920                        let mut reader = ProgressReader::new(&mut hasher, progress, &**reporter);
921
922                        tokio::io::copy(&mut reader, &mut writer)
923                            .await
924                            .map_err(Error::CacheWrite)?;
925                    }
926                    None => {
927                        tokio::io::copy(&mut hasher, &mut writer)
928                            .await
929                            .map_err(Error::CacheWrite)?;
930                    }
931                }
932
933                // Unzip the wheel to a temporary directory.
934                let temp_dir = tempfile::tempdir_in(self.build_context.cache().root())
935                    .map_err(Error::CacheWrite)?;
936                let mut file = writer.into_inner();
937                file.seek(io::SeekFrom::Start(0))
938                    .await
939                    .map_err(Error::CacheWrite)?;
940
941                let target = temp_dir.path().to_owned();
942                let files = match extension {
943                    WheelExtension::Whl => {
944                        let file = file.into_std().await;
945                        tokio::task::spawn_blocking(move || uv_extract::unzip(file, &target))
946                            .await?
947                    }
948                    WheelExtension::WhlZst => uv_extract::stream::untar_zst(file, &target).await,
949                }
950                .map_err(|err| Error::Extract(filename.to_string(), err))?;
951                let hashes = hashers.into_iter().map(HashDigest::from).collect();
952
953                // Before we make the wheel accessible by persisting it, ensure that the RECORD is
954                // valid.
955                validate_and_heal_record(temp_dir.path(), files.iter(), dist)
956                    .map_err(Error::InstallWheelError)?;
957
958                // Persist the temporary directory to the directory store.
959                let id = self
960                    .build_context
961                    .cache()
962                    .persist(temp_dir.keep(), wheel_entry.path())
963                    .await
964                    .map_err(Error::CacheRead)?;
965
966                if let Some((reporter, progress)) = progress {
967                    reporter.on_download_complete(dist.name(), progress);
968                }
969
970                Ok(Archive::new(id, hashes, filename.clone()))
971            }
972            .instrument(info_span!("wheel", wheel = %dist))
973        };
974
975        // Fetch the archive from the cache, or download it if necessary.
976        let req = self.request(url.clone())?;
977
978        // Determine the cache control policy for the URL.
979        let cache_control = match self.client.unmanaged.connectivity() {
980            Connectivity::Online
981                if let Some(header) = index.and_then(|index| {
982                    self.build_context
983                        .locations()
984                        .artifact_cache_control_for(index)
985                }) =>
986            {
987                CacheControl::Override(header)
988            }
989            Connectivity::Online => CacheControl::from(
990                self.build_context
991                    .cache()
992                    .freshness(&http_entry, Some(&filename.name), None)
993                    .map_err(Error::CacheRead)?,
994            ),
995            Connectivity::Offline => CacheControl::AllowStale,
996        };
997
998        let archive = self
999            .client
1000            .managed(|client| {
1001                client.cached_client().get_serde_with_retry(
1002                    req,
1003                    &http_entry,
1004                    cache_control.clone(),
1005                    download,
1006                )
1007            })
1008            .await
1009            .map_err(|err| match err {
1010                CachedClientError::Callback { err, .. } => err,
1011                CachedClientError::Client(err) => Error::Client(err),
1012            })?;
1013
1014        // If the archive is missing the required hashes, or has since been removed, force a refresh.
1015        let archive = Some(archive)
1016            .filter(|archive| archive.has_digests(hashes))
1017            .filter(|archive| archive.exists(self.build_context.cache()));
1018
1019        let archive = if let Some(archive) = archive {
1020            archive
1021        } else {
1022            self.client
1023                .managed(async |client| {
1024                    client
1025                        .cached_client()
1026                        .skip_cache_with_retry(
1027                            self.request(url)?,
1028                            &http_entry,
1029                            cache_control,
1030                            download,
1031                        )
1032                        .await
1033                        .map_err(|err| match err {
1034                            CachedClientError::Callback { err, .. } => err,
1035                            CachedClientError::Client(err) => Error::Client(err),
1036                        })
1037                })
1038                .await?
1039        };
1040
1041        Ok(archive)
1042    }
1043
1044    /// Load a wheel from a local path.
1045    async fn load_wheel(
1046        &self,
1047        path: &Path,
1048        filename: &WheelFilename,
1049        extension: WheelExtension,
1050        wheel_entry: CacheEntry,
1051        dist: &BuiltDist,
1052        hashes: HashPolicy<'_>,
1053    ) -> Result<LocalWheel, Error> {
1054        #[cfg(windows)]
1055        let _lock = {
1056            let lock_entry = wheel_entry.with_file(format!("{}.lock", filename.stem()));
1057            lock_entry.lock().await.map_err(Error::CacheLock)?
1058        };
1059
1060        // Determine the last-modified time of the wheel.
1061        let modified = Timestamp::from_path(path).map_err(Error::CacheRead)?;
1062
1063        // Attempt to read the archive pointer from the cache.
1064        let pointer_entry = wheel_entry.with_file(format!("{}.rev", filename.cache_key()));
1065        let pointer = PathArchivePointer::read_from(&pointer_entry)?;
1066
1067        // Extract the archive from the pointer.
1068        let archive = pointer
1069            .filter(|pointer| pointer.is_up_to_date(modified))
1070            .map(PathArchivePointer::into_archive)
1071            .filter(|archive| archive.has_digests(hashes));
1072
1073        // If the file is already unzipped, and the cache is up-to-date, return it.
1074        if let Some(archive) = archive {
1075            Ok(LocalWheel {
1076                dist: Dist::Built(dist.clone()),
1077                archive: self
1078                    .build_context
1079                    .cache()
1080                    .archive(&archive.id)
1081                    .into_boxed_path(),
1082                hashes: archive.hashes,
1083                filename: filename.clone(),
1084                cache: CacheInfo::from_timestamp(modified),
1085                build: None,
1086            })
1087        } else if hashes.is_none() {
1088            // Otherwise, unzip the wheel.
1089            let archive = Archive::new(
1090                self.unzip_wheel(path, wheel_entry.path(), DistRef::Built(dist))
1091                    .await?,
1092                HashDigests::empty(),
1093                filename.clone(),
1094            );
1095
1096            // Write the archive pointer to the cache.
1097            let pointer = PathArchivePointer {
1098                timestamp: modified,
1099                archive: archive.clone(),
1100            };
1101            pointer.write_to(&pointer_entry).await?;
1102
1103            Ok(LocalWheel {
1104                dist: Dist::Built(dist.clone()),
1105                archive: self
1106                    .build_context
1107                    .cache()
1108                    .archive(&archive.id)
1109                    .into_boxed_path(),
1110                hashes: archive.hashes,
1111                filename: filename.clone(),
1112                cache: CacheInfo::from_timestamp(modified),
1113                build: None,
1114            })
1115        } else {
1116            // If necessary, compute the hashes of the wheel.
1117            let file = fs_err::tokio::File::open(path)
1118                .await
1119                .map_err(Error::CacheRead)?;
1120            let temp_dir = tempfile::tempdir_in(self.build_context.cache().root())
1121                .map_err(Error::CacheWrite)?;
1122
1123            // Create a hasher for each hash algorithm.
1124            let algorithms = hashes.algorithms();
1125            let mut hashers = algorithms.into_iter().map(Hasher::from).collect::<Vec<_>>();
1126            let mut hasher = uv_extract::hash::HashReader::new(file, &mut hashers);
1127
1128            // Unzip the wheel to a temporary directory.
1129            let files = match extension {
1130                WheelExtension::Whl => {
1131                    uv_extract::stream::unzip(path.display(), &mut hasher, temp_dir.path())
1132                        .await
1133                        .map_err(|err| Error::Extract(filename.to_string(), err))?
1134                }
1135                WheelExtension::WhlZst => {
1136                    uv_extract::stream::untar_zst(&mut hasher, temp_dir.path())
1137                        .await
1138                        .map_err(|err| Error::Extract(filename.to_string(), err))?
1139                }
1140            };
1141
1142            // Exhaust the reader to compute the hash.
1143            hasher.finish().await.map_err(Error::HashExhaustion)?;
1144
1145            let hashes = hashers.into_iter().map(HashDigest::from).collect();
1146
1147            // Before we make the wheel accessible by persisting it, ensure that the RECORD is
1148            // valid.
1149            validate_and_heal_record(temp_dir.path(), files.iter(), dist)
1150                .map_err(Error::InstallWheelError)?;
1151
1152            // Persist the temporary directory to the directory store.
1153            let id = self
1154                .build_context
1155                .cache()
1156                .persist(temp_dir.keep(), wheel_entry.path())
1157                .await
1158                .map_err(Error::CacheWrite)?;
1159
1160            // Create an archive.
1161            let archive = Archive::new(id, hashes, filename.clone());
1162
1163            // Write the archive pointer to the cache.
1164            let pointer = PathArchivePointer {
1165                timestamp: modified,
1166                archive: archive.clone(),
1167            };
1168            pointer.write_to(&pointer_entry).await?;
1169
1170            Ok(LocalWheel {
1171                dist: Dist::Built(dist.clone()),
1172                archive: self
1173                    .build_context
1174                    .cache()
1175                    .archive(&archive.id)
1176                    .into_boxed_path(),
1177                hashes: archive.hashes,
1178                filename: filename.clone(),
1179                cache: CacheInfo::from_timestamp(modified),
1180                build: None,
1181            })
1182        }
1183    }
1184
1185    /// Unzip a wheel into the cache, returning the path to the unzipped directory.
1186    async fn unzip_wheel(
1187        &self,
1188        path: &Path,
1189        target: &Path,
1190        dist: DistRef<'_>,
1191    ) -> Result<ArchiveId, Error> {
1192        let (temp_dir, files) = tokio::task::spawn_blocking({
1193            let path = path.to_owned();
1194            let root = self.build_context.cache().root().to_path_buf();
1195            move || -> Result<_, Error> {
1196                // Unzip the wheel into a temporary directory.
1197                let temp_dir = tempfile::tempdir_in(root).map_err(Error::CacheWrite)?;
1198                let reader = fs_err::File::open(&path).map_err(Error::CacheWrite)?;
1199                let files = uv_extract::unzip(reader, temp_dir.path())
1200                    .map_err(|err| Error::Extract(path.to_string_lossy().into_owned(), err))?;
1201                Ok((temp_dir, files))
1202            }
1203        })
1204        .await??;
1205
1206        // Before we make the wheel accessible by persisting it, ensure that the RECORD is valid.
1207        validate_and_heal_record(temp_dir.path(), files.iter(), dist)
1208            .map_err(Error::InstallWheelError)?;
1209
1210        // Persist the temporary directory to the directory store.
1211        let id = self
1212            .build_context
1213            .cache()
1214            .persist(temp_dir.keep(), target)
1215            .await
1216            .map_err(Error::CacheWrite)?;
1217
1218        Ok(id)
1219    }
1220
1221    /// Returns a GET [`reqwest::Request`] for the given URL.
1222    fn request(&self, url: DisplaySafeUrl) -> Result<reqwest::Request, reqwest::Error> {
1223        self.client
1224            .unmanaged
1225            .uncached_client(&url)
1226            .get(Url::from(url))
1227            .header(
1228                // `reqwest` defaults to accepting compressed responses.
1229                // Specify identity encoding to get consistent .whl downloading
1230                // behavior from servers. ref: https://github.com/pypa/pip/pull/1688
1231                "accept-encoding",
1232                reqwest::header::HeaderValue::from_static("identity"),
1233            )
1234            .build()
1235    }
1236
1237    /// Return the [`ManagedClient`] used by this resolver.
1238    pub fn client(&self) -> &ManagedClient<'a> {
1239        &self.client
1240    }
1241}
1242
1243/// A wrapper around `RegistryClient` that manages a concurrency limit.
1244pub struct ManagedClient<'a> {
1245    pub unmanaged: &'a RegistryClient,
1246    control: Arc<Semaphore>,
1247}
1248
1249impl<'a> ManagedClient<'a> {
1250    /// Create a new `ManagedClient` using the given client and concurrency semaphore.
1251    fn new(client: &'a RegistryClient, control: Arc<Semaphore>) -> Self {
1252        ManagedClient {
1253            unmanaged: client,
1254            control,
1255        }
1256    }
1257
1258    /// Perform a request using the client, respecting the concurrency limit.
1259    ///
1260    /// If the concurrency limit has been reached, this method will wait until a pending
1261    /// operation completes before executing the closure.
1262    pub async fn managed<F, T>(&self, f: impl FnOnce(&'a RegistryClient) -> F) -> T
1263    where
1264        F: Future<Output = T>,
1265    {
1266        let _permit = self.control.acquire().await.unwrap();
1267        f(self.unmanaged).await
1268    }
1269
1270    /// Perform a request using a client that internally manages the concurrency limit.
1271    ///
1272    /// The callback is passed the client and a semaphore. It must acquire the semaphore before
1273    /// any request through the client and drop it after.
1274    ///
1275    /// This method serves as an escape hatch for functions that may want to send multiple requests
1276    /// in parallel.
1277    pub async fn manual<F, T>(&'a self, f: impl FnOnce(&'a RegistryClient, &'a Semaphore) -> F) -> T
1278    where
1279        F: Future<Output = T>,
1280    {
1281        f(self.unmanaged, &self.control).await
1282    }
1283}
1284
1285/// Returns the value of the `Content-Length` header from the [`reqwest::Response`], if present.
1286fn content_length(response: &reqwest::Response) -> Option<u64> {
1287    response
1288        .headers()
1289        .get(reqwest::header::CONTENT_LENGTH)
1290        .and_then(|val| val.to_str().ok())
1291        .and_then(|val| val.parse::<u64>().ok())
1292}
1293
1294/// An asynchronous reader that reports progress as bytes are read.
1295struct ProgressReader<'a, R> {
1296    reader: R,
1297    index: usize,
1298    reporter: &'a dyn Reporter,
1299}
1300
1301impl<'a, R> ProgressReader<'a, R> {
1302    /// Create a new [`ProgressReader`] that wraps another reader.
1303    fn new(reader: R, index: usize, reporter: &'a dyn Reporter) -> Self {
1304        Self {
1305            reader,
1306            index,
1307            reporter,
1308        }
1309    }
1310}
1311
1312impl<R> AsyncRead for ProgressReader<'_, R>
1313where
1314    R: AsyncRead + Unpin,
1315{
1316    fn poll_read(
1317        mut self: Pin<&mut Self>,
1318        cx: &mut Context<'_>,
1319        buf: &mut ReadBuf<'_>,
1320    ) -> Poll<io::Result<()>> {
1321        Pin::new(&mut self.as_mut().reader)
1322            .poll_read(cx, buf)
1323            .map_ok(|()| {
1324                self.reporter
1325                    .on_download_progress(self.index, buf.filled().len() as u64);
1326            })
1327    }
1328}
1329
1330/// A pointer to an archive in the cache, fetched from an HTTP archive.
1331///
1332/// Encoded with `MsgPack`, and represented on disk by a `.http` file.
1333#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1334pub struct HttpArchivePointer {
1335    archive: Archive,
1336}
1337
1338impl HttpArchivePointer {
1339    /// Read an [`HttpArchivePointer`] from the cache.
1340    pub fn read_from(path: impl AsRef<Path>) -> Result<Option<Self>, Error> {
1341        match fs_err::File::open(path.as_ref()) {
1342            Ok(file) => {
1343                let data = DataWithCachePolicy::from_reader(file)?.data;
1344                let archive = rmp_serde::from_slice::<Archive>(&data)?;
1345                Ok(Some(Self { archive }))
1346            }
1347            Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
1348            Err(err) => Err(Error::CacheRead(err)),
1349        }
1350    }
1351
1352    /// Return the [`Archive`] from the pointer.
1353    pub fn into_archive(self) -> Archive {
1354        self.archive
1355    }
1356
1357    /// Return the [`CacheInfo`] from the pointer.
1358    pub fn to_cache_info(&self) -> CacheInfo {
1359        CacheInfo::default()
1360    }
1361
1362    /// Return the [`BuildInfo`] from the pointer.
1363    pub fn to_build_info(&self) -> Option<BuildInfo> {
1364        None
1365    }
1366}
1367
1368/// A pointer to an archive in the cache, fetched from a local path.
1369///
1370/// Encoded with `MsgPack`, and represented on disk by a `.rev` file.
1371#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1372pub struct PathArchivePointer {
1373    timestamp: Timestamp,
1374    archive: Archive,
1375}
1376
1377impl PathArchivePointer {
1378    /// Read an [`PathArchivePointer`] from the cache.
1379    pub fn read_from(path: impl AsRef<Path>) -> Result<Option<Self>, Error> {
1380        match fs_err::read(path) {
1381            Ok(cached) => Ok(Some(rmp_serde::from_slice::<Self>(&cached)?)),
1382            Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
1383            Err(err) => Err(Error::CacheRead(err)),
1384        }
1385    }
1386
1387    /// Write an [`PathArchivePointer`] to the cache.
1388    async fn write_to(&self, entry: &CacheEntry) -> Result<(), Error> {
1389        write_atomic(entry.path(), rmp_serde::to_vec(&self)?)
1390            .await
1391            .map_err(Error::CacheWrite)
1392    }
1393
1394    /// Returns `true` if the archive is up-to-date with the given modified timestamp.
1395    pub fn is_up_to_date(&self, modified: Timestamp) -> bool {
1396        self.timestamp == modified
1397    }
1398
1399    /// Return the [`Archive`] from the pointer.
1400    pub fn into_archive(self) -> Archive {
1401        self.archive
1402    }
1403
1404    /// Return the [`CacheInfo`] from the pointer.
1405    pub fn to_cache_info(&self) -> CacheInfo {
1406        CacheInfo::from_timestamp(self.timestamp)
1407    }
1408
1409    /// Return the [`BuildInfo`] from the pointer.
1410    pub fn to_build_info(&self) -> Option<BuildInfo> {
1411        None
1412    }
1413}
1414
1415#[derive(Debug, Clone)]
1416struct WheelTarget {
1417    /// The URL from which the wheel can be downloaded.
1418    url: DisplaySafeUrl,
1419    /// The expected extension of the wheel file.
1420    extension: WheelExtension,
1421    /// The expected size of the wheel file, if known.
1422    size: Option<u64>,
1423}
1424
1425impl TryFrom<&File> for WheelTarget {
1426    type Error = ToUrlError;
1427
1428    /// Determine the [`WheelTarget`] from a [`File`].
1429    fn try_from(file: &File) -> Result<Self, Self::Error> {
1430        let url = file.url.to_url()?;
1431        if let Some(zstd) = file.zstd.as_ref() {
1432            Ok(Self {
1433                url: add_tar_zst_extension(url),
1434                extension: WheelExtension::WhlZst,
1435                size: zstd.size,
1436            })
1437        } else {
1438            Ok(Self {
1439                url,
1440                extension: WheelExtension::Whl,
1441                size: file.size,
1442            })
1443        }
1444    }
1445}
1446
1447#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1448enum WheelExtension {
1449    /// A `.whl` file.
1450    Whl,
1451    /// A `.whl.tar.zst` file.
1452    WhlZst,
1453}
1454
1455/// Add `.tar.zst` to the end of the URL path, if it doesn't already exist.
1456#[must_use]
1457fn add_tar_zst_extension(mut url: DisplaySafeUrl) -> DisplaySafeUrl {
1458    let mut path = url.path().to_string();
1459
1460    if !path.ends_with(".tar.zst") {
1461        path.push_str(".tar.zst");
1462    }
1463
1464    url.set_path(&path);
1465    url
1466}
1467
1468#[cfg(test)]
1469mod tests {
1470    use super::*;
1471
1472    #[test]
1473    fn test_add_tar_zst_extension() {
1474        let url =
1475            DisplaySafeUrl::parse("https://files.pythonhosted.org/flask-3.1.0-py3-none-any.whl")
1476                .unwrap();
1477        assert_eq!(
1478            add_tar_zst_extension(url).as_str(),
1479            "https://files.pythonhosted.org/flask-3.1.0-py3-none-any.whl.tar.zst"
1480        );
1481
1482        let url = DisplaySafeUrl::parse(
1483            "https://files.pythonhosted.org/flask-3.1.0-py3-none-any.whl.tar.zst",
1484        )
1485        .unwrap();
1486        assert_eq!(
1487            add_tar_zst_extension(url).as_str(),
1488            "https://files.pythonhosted.org/flask-3.1.0-py3-none-any.whl.tar.zst"
1489        );
1490
1491        let url = DisplaySafeUrl::parse(
1492            "https://files.pythonhosted.org/flask-3.1.0%2Bcu124-py3-none-any.whl",
1493        )
1494        .unwrap();
1495        assert_eq!(
1496            add_tar_zst_extension(url).as_str(),
1497            "https://files.pythonhosted.org/flask-3.1.0%2Bcu124-py3-none-any.whl.tar.zst"
1498        );
1499    }
1500}