Skip to main content

uv_resolver/resolver/
provider.rs

1use std::future::Future;
2use std::sync::Arc;
3pub use uv_resolver_types::MetadataResponse;
4pub(crate) use uv_resolver_types::MetadataUnavailable;
5use uv_resolver_types::VariantsJsonMetadataError;
6
7use uv_client::MetadataFormat;
8use uv_configuration::BuildOptions;
9use uv_distribution::{DistributionDatabase, Reporter};
10use uv_distribution_types::{
11    BuiltDist, Dist, File, IndexCapabilities, IndexLocations, IndexMetadata, IndexMetadataRef,
12    IndexUrl, InstalledDist, MinimumLibcVersion, RequestedDist, RequiresPython,
13    VariantsJsonContent,
14};
15use uv_normalize::PackageName;
16use uv_platform_tags::Tags;
17use uv_static::EnvVars;
18use uv_types::{BuildContext, HashStrategy};
19
20use crate::ExcludeNewer;
21use crate::flat_index::{FlatDistributions, FlatIndex};
22use crate::version_map::VersionMap;
23use crate::yanks::AllowedYanks;
24
25pub type PackageVersionsResult = Result<VersionsResponse, uv_client::Error>;
26pub type WheelMetadataResult = Result<MetadataResponse, uv_distribution::Error>;
27
28/// The outcome of an index-level variant metadata lookup.
29///
30/// A recoverable failure belongs in [`Self::Unavailable`] so the resolver can store it and replay
31/// it when it revisits the package version. Fatal client errors are returned separately and abort
32/// resolution.
33#[derive(Debug)]
34pub enum VariantsJsonResponse {
35    /// The variant metadata was fetched successfully.
36    Found(Vec<u8>),
37    /// The package version cannot be used.
38    Unavailable(MetadataUnavailable),
39}
40
41/// The response when requesting versions for a package
42#[derive(Debug)]
43pub enum VersionsResponse {
44    /// The package was found in the registry with the included versions
45    Found(Vec<VersionMap>),
46    /// The package was not found in the registry
47    NotFound,
48    /// The package was not found in the local registry
49    NoIndex,
50    /// The package was not found in the cache and the network is not available.
51    Offline,
52}
53
54pub trait ResolverProvider {
55    /// Get the version map for a package.
56    fn get_package_versions<'io>(
57        &'io self,
58        package_name: &'io PackageName,
59        index: Option<&'io IndexMetadata>,
60    ) -> impl Future<Output = PackageVersionsResult> + 'io;
61
62    /// Get the metadata for a distribution.
63    ///
64    /// For a wheel, this is done by querying it (remote) metadata. For a source distribution, we
65    /// (fetch and) build the source distribution and return the metadata from the built
66    /// distribution.
67    fn get_or_build_wheel_metadata<'io>(
68        &'io self,
69        dist: &'io Dist,
70    ) -> impl Future<Output = WheelMetadataResult> + 'io;
71
72    /// Get embedded variant metadata for a wheel being considered by the solver.
73    fn get_wheel_variant_metadata<'io>(
74        &'io self,
75        wheel: &'io BuiltDist,
76    ) -> impl Future<Output = Result<Option<VariantsJsonContent>, uv_distribution::Error>> + 'io;
77
78    /// Get the metadata for an installed distribution.
79    fn get_installed_metadata<'io>(
80        &'io self,
81        dist: &'io InstalledDist,
82    ) -> impl Future<Output = WheelMetadataResult> + 'io;
83
84    /// Fetch the index-level variant metadata for a package version.
85    fn fetch_variants_json<'io>(
86        &'io self,
87        package_name: &'io PackageName,
88        file: &'io File,
89        index: &'io IndexUrl,
90    ) -> impl Future<Output = Result<VariantsJsonResponse, uv_client::Error>> + 'io;
91
92    /// Set the [`Reporter`] to use for this installer.
93    #[must_use]
94    fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self;
95}
96
97/// The main IO backend for the resolver, which does cached requests network requests using the
98/// [`RegistryClient`] and [`DistributionDatabase`].
99pub struct DefaultResolverProvider<'a, Context: BuildContext> {
100    /// The [`DistributionDatabase`] used to build source distributions.
101    fetcher: DistributionDatabase<'a, Context>,
102    /// These are the entries from `--find-links` that act as overrides for index responses.
103    flat_index: &'a FlatIndex,
104    tags: Option<Tags>,
105    requires_python: RequiresPython,
106    allowed_yanks: AllowedYanks,
107    hasher: &'a HashStrategy,
108    exclude_newer: ExcludeNewer,
109    available_version_cutoff: Option<jiff::Timestamp>,
110    index_locations: &'a IndexLocations,
111    build_options: &'a BuildOptions,
112    capabilities: &'a IndexCapabilities,
113    minimum_libc_version: Option<MinimumLibcVersion>,
114}
115
116impl<'a, Context: BuildContext> DefaultResolverProvider<'a, Context> {
117    /// Reads the flat index entries and builds the provider.
118    pub fn new(
119        fetcher: DistributionDatabase<'a, Context>,
120        flat_index: &'a FlatIndex,
121        tags: Option<&'a Tags>,
122        requires_python: &'a RequiresPython,
123        allowed_yanks: AllowedYanks,
124        hasher: &'a HashStrategy,
125        exclude_newer: ExcludeNewer,
126        index_locations: &'a IndexLocations,
127        build_options: &'a BuildOptions,
128        capabilities: &'a IndexCapabilities,
129        minimum_libc_version: Option<MinimumLibcVersion>,
130    ) -> Self {
131        Self {
132            fetcher,
133            flat_index,
134            tags: tags.cloned(),
135            requires_python: requires_python.clone(),
136            allowed_yanks,
137            hasher,
138            exclude_newer,
139            available_version_cutoff: std::env::var(
140                EnvVars::UV_INTERNAL__TEST_AVAILABLE_VERSION_CUTOFF,
141            )
142            .ok()
143            .and_then(|value| value.parse().ok()),
144            index_locations,
145            build_options,
146            capabilities,
147            minimum_libc_version,
148        }
149    }
150
151    fn effective_exclude_newer(
152        &self,
153        package_name: &PackageName,
154        index: &uv_distribution_types::IndexUrl,
155    ) -> Option<jiff::Timestamp> {
156        self.exclude_newer.exclude_newer_package_for_index(
157            package_name,
158            self.index_locations.exclude_newer_for(index, package_name),
159        )
160    }
161
162    /// Honor index-specific status codes when classifying metadata failures.
163    fn classify_metadata_error(
164        &self,
165        error: uv_client::Error,
166        index: Option<&IndexUrl>,
167    ) -> Result<MetadataUnavailable, uv_client::Error> {
168        if let uv_client::ErrorKind::WrappedReqwestError(_, http) = error.kind()
169            && let Some(status) = http.status()
170            && index.is_some_and(|index| self.index_locations.ignores_error_code_for(index, status))
171        {
172            return Ok(MetadataUnavailable::Network(status));
173        }
174        classify_metadata_error(error)
175    }
176}
177
178/// Classify a metadata failure shared by index and direct URL requests.
179pub(super) fn classify_metadata_error(
180    error: uv_client::Error,
181) -> Result<MetadataUnavailable, uv_client::Error> {
182    let retries = error.retries();
183    let duration = error.duration();
184    match error.into_kind() {
185        uv_client::ErrorKind::Offline(_) => Ok(MetadataUnavailable::Offline),
186        uv_client::ErrorKind::MetadataParseError(_, _, error) => {
187            Ok(MetadataUnavailable::InvalidMetadata(Arc::new(*error)))
188        }
189        uv_client::ErrorKind::Metadata(_, error) => Ok(classify_wheel_metadata_error(error)),
190        kind => Err(uv_client::Error::new(kind, retries, duration)),
191    }
192}
193
194/// Classify errors reading metadata from a wheel archive.
195pub(super) fn classify_wheel_metadata_error(error: uv_metadata::Error) -> MetadataUnavailable {
196    match error {
197        uv_metadata::Error::InvalidVariantMetadata(source) => {
198            MetadataUnavailable::InvalidVariantMetadata(Arc::new(VariantsJsonMetadataError::Wheel(
199                source,
200            )))
201        }
202        error => MetadataUnavailable::InvalidStructure(Arc::new(error)),
203    }
204}
205
206impl<Context: BuildContext> ResolverProvider for DefaultResolverProvider<'_, Context> {
207    /// Make a "Simple API" request for the package and convert the result to a [`VersionMap`].
208    async fn get_package_versions<'io>(
209        &'io self,
210        package_name: &'io PackageName,
211        index: Option<&'io IndexMetadata>,
212    ) -> PackageVersionsResult {
213        let result = self
214            .fetcher
215            .client()
216            .manual(|client, semaphore| {
217                client.simple_detail(
218                    package_name,
219                    index.map(IndexMetadataRef::from),
220                    self.capabilities,
221                    semaphore,
222                )
223            })
224            .await;
225
226        // If a package is pinned to an explicit index, ignore any `--find-links` entries.
227        let flat_index = index.is_none().then_some(self.flat_index);
228        let flat_distributions = flat_index
229            .and_then(|flat_index| flat_index.get(package_name))
230            .map(|entries| {
231                FlatDistributions::from_entries(
232                    entries.iter().cloned(),
233                    self.tags.as_ref(),
234                    self.hasher,
235                    self.build_options,
236                    self.minimum_libc_version,
237                )
238            });
239
240        match result {
241            Ok(results) => Ok(VersionsResponse::Found(
242                results
243                    .into_iter()
244                    .map(|(index, metadata)| {
245                        let included_version_cutoff =
246                            self.effective_exclude_newer(package_name, index);
247                        let available_version_cutoff = included_version_cutoff
248                            .is_none()
249                            .then_some(self.available_version_cutoff)
250                            .flatten();
251
252                        match metadata {
253                            MetadataFormat::Simple(metadata) => VersionMap::from_simple_metadata(
254                                metadata,
255                                package_name,
256                                index.clone(),
257                                self.tags.clone(),
258                                self.requires_python.clone(),
259                                self.allowed_yanks.clone(),
260                                self.hasher.clone(),
261                                included_version_cutoff,
262                                available_version_cutoff,
263                                flat_distributions.clone(),
264                                self.build_options,
265                                self.minimum_libc_version,
266                            ),
267                            MetadataFormat::Flat(metadata) => VersionMap::from_flat_metadata(
268                                metadata,
269                                self.tags.as_ref(),
270                                self.hasher,
271                                self.build_options,
272                                self.minimum_libc_version,
273                            ),
274                        }
275                    })
276                    .collect(),
277            )),
278            Err(err) => match err.kind() {
279                uv_client::ErrorKind::RemotePackageNotFound(_) => {
280                    if let Some(flat_index) = flat_distributions {
281                        Ok(VersionsResponse::Found(vec![VersionMap::from(flat_index)]))
282                    } else {
283                        Ok(VersionsResponse::NotFound)
284                    }
285                }
286                uv_client::ErrorKind::NoIndex(_) => {
287                    if let Some(flat_index) = flat_distributions {
288                        Ok(VersionsResponse::Found(vec![VersionMap::from(flat_index)]))
289                    } else if flat_index.is_some_and(FlatIndex::offline) {
290                        Ok(VersionsResponse::Offline)
291                    } else {
292                        Ok(VersionsResponse::NoIndex)
293                    }
294                }
295                uv_client::ErrorKind::Offline(_) => {
296                    if let Some(flat_index) = flat_distributions {
297                        Ok(VersionsResponse::Found(vec![VersionMap::from(flat_index)]))
298                    } else {
299                        Ok(VersionsResponse::Offline)
300                    }
301                }
302                _ => Err(err),
303            },
304        }
305    }
306
307    /// Fetch the metadata for a distribution, building it if necessary.
308    async fn get_or_build_wheel_metadata<'io>(&'io self, dist: &'io Dist) -> WheelMetadataResult {
309        match self
310            .fetcher
311            .get_or_build_wheel_metadata(dist, self.hasher.metadata_policy(dist))
312            .await
313        {
314            Ok(metadata) => Ok(MetadataResponse::Found(metadata)),
315            Err(err) => match err {
316                uv_distribution::Error::Client(client) => {
317                    // Both outcomes describe a failed request. A recoverable failure lets the
318                    // resolver reject the candidate and backtrack; other client errors abort resolution.
319                    match self.classify_metadata_error(client, dist.index()) {
320                        Ok(reason) => Ok(MetadataResponse::Unavailable(reason)),
321                        Err(error) => Err(error.into()),
322                    }
323                }
324                uv_distribution::Error::WheelMetadataVersionMismatch { .. } => {
325                    Ok(MetadataResponse::Unavailable(
326                        MetadataUnavailable::InconsistentMetadata(Arc::new(err)),
327                    ))
328                }
329                uv_distribution::Error::WheelMetadataNameMismatch { .. } => {
330                    Ok(MetadataResponse::Unavailable(
331                        MetadataUnavailable::InconsistentMetadata(Arc::new(err)),
332                    ))
333                }
334                uv_distribution::Error::Metadata(err) => Ok(MetadataResponse::Unavailable(
335                    MetadataUnavailable::InvalidMetadata(Arc::new(err)),
336                )),
337                uv_distribution::Error::WheelMetadata(_, err) => Ok(MetadataResponse::Unavailable(
338                    classify_wheel_metadata_error(*err),
339                )),
340                uv_distribution::Error::RequiresPython(requires_python, version) => {
341                    Ok(MetadataResponse::Unavailable(
342                        MetadataUnavailable::RequiresPython(requires_python, version),
343                    ))
344                }
345                err => Ok(MetadataResponse::Error(
346                    Box::new(RequestedDist::Installable(dist.clone())),
347                    Arc::new(err),
348                )),
349            },
350        }
351    }
352
353    async fn get_wheel_variant_metadata(
354        &self,
355        wheel: &BuiltDist,
356    ) -> Result<Option<VariantsJsonContent>, uv_distribution::Error> {
357        self.fetcher
358            .get_wheel_variant_metadata(wheel, self.hasher.archive_policy(wheel))
359            .await
360    }
361
362    /// Return the metadata for an installed distribution.
363    async fn get_installed_metadata<'io>(
364        &'io self,
365        dist: &'io InstalledDist,
366    ) -> WheelMetadataResult {
367        match self.fetcher.get_installed_metadata(dist).await {
368            Ok(metadata) => Ok(MetadataResponse::Found(metadata)),
369            Err(err) => Ok(MetadataResponse::Error(
370                Box::new(RequestedDist::Installed(dist.clone())),
371                Arc::new(err),
372            )),
373        }
374    }
375
376    async fn fetch_variants_json<'io>(
377        &'io self,
378        package_name: &'io PackageName,
379        file: &'io File,
380        index: &'io IndexUrl,
381    ) -> Result<VariantsJsonResponse, uv_client::Error> {
382        match self
383            .fetcher
384            .client()
385            .managed(|client| client.fetch_variants_json(package_name, file, index))
386            .await
387        {
388            Ok(contents) => Ok(VariantsJsonResponse::Found(contents)),
389            Err(error) => match self.classify_metadata_error(error, Some(index)) {
390                Ok(reason) => Ok(VariantsJsonResponse::Unavailable(reason)),
391                Err(error) => Err(error),
392            },
393        }
394    }
395
396    /// Set the [`Reporter`] to use for this installer.
397    fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
398        Self {
399            fetcher: self.fetcher.with_reporter(reporter),
400            ..self
401        }
402    }
403}