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, IndexCapabilities, IndexLocations, IndexMetadata, IndexMetadataRef, IndexUrl,
12 InstalledDist, MinimumLibcVersion, RequestedDist, RequiresPython, VariantsJsonContent,
13 VerbatimFile,
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#[derive(Debug)]
34pub enum VariantsJsonResponse {
35 Found(Vec<u8>),
37 Unavailable(MetadataUnavailable),
39}
40
41#[derive(Debug)]
43pub enum VersionsResponse {
44 Found(Vec<VersionMap>),
46 NotFound,
48 NoIndex,
50 Offline,
52}
53
54pub trait ResolverProvider {
55 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 fn get_or_build_wheel_metadata<'io>(
68 &'io self,
69 dist: &'io Dist,
70 ) -> impl Future<Output = WheelMetadataResult> + 'io;
71
72 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 fn get_installed_metadata<'io>(
80 &'io self,
81 dist: &'io InstalledDist,
82 ) -> impl Future<Output = WheelMetadataResult> + 'io;
83
84 fn fetch_variants_json<'io>(
86 &'io self,
87 package_name: &'io PackageName,
88 file: &'io VerbatimFile,
89 index: &'io IndexUrl,
90 ) -> impl Future<Output = Result<VariantsJsonResponse, uv_client::Error>> + 'io;
91
92 #[must_use]
94 fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self;
95}
96
97pub struct DefaultResolverProvider<'a, Context: BuildContext> {
100 fetcher: DistributionDatabase<'a, Context>,
102 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 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 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| {
171 self.index_locations
172 .request_policy(index)
173 .ignores_error_code(status)
174 })
175 {
176 return Ok(MetadataUnavailable::Network(status));
177 }
178 classify_metadata_error(error)
179 }
180}
181
182pub(super) fn classify_metadata_error(
184 error: uv_client::Error,
185) -> Result<MetadataUnavailable, uv_client::Error> {
186 let retries = error.retries();
187 let duration = error.duration();
188 match error.into_kind() {
189 uv_client::ErrorKind::Offline(_) => Ok(MetadataUnavailable::Offline),
190 uv_client::ErrorKind::MetadataParseError(_, _, error) => {
191 Ok(MetadataUnavailable::InvalidMetadata(Arc::new(*error)))
192 }
193 uv_client::ErrorKind::Metadata(_, error) => Ok(classify_wheel_metadata_error(error)),
194 kind => Err(uv_client::Error::new(kind, retries, duration)),
195 }
196}
197
198pub(super) fn classify_wheel_metadata_error(error: uv_metadata::Error) -> MetadataUnavailable {
200 match error {
201 uv_metadata::Error::InvalidVariantMetadata(source) => {
202 MetadataUnavailable::InvalidVariantMetadata(Arc::new(VariantsJsonMetadataError::Wheel(
203 source,
204 )))
205 }
206 error => MetadataUnavailable::InvalidStructure(Arc::new(error)),
207 }
208}
209
210impl<Context: BuildContext> ResolverProvider for DefaultResolverProvider<'_, Context> {
211 async fn get_package_versions<'io>(
213 &'io self,
214 package_name: &'io PackageName,
215 index: Option<&'io IndexMetadata>,
216 ) -> PackageVersionsResult {
217 let result = self
218 .fetcher
219 .client()
220 .manual(|client, semaphore| {
221 client.simple_detail(
222 package_name,
223 index.map(IndexMetadataRef::from),
224 self.capabilities,
225 semaphore,
226 )
227 })
228 .await;
229
230 let flat_index = index.is_none().then_some(self.flat_index);
232 let flat_distributions = flat_index
233 .and_then(|flat_index| flat_index.get(package_name))
234 .map(|entries| {
235 FlatDistributions::from_entries(
236 entries.iter().cloned(),
237 self.tags.as_ref(),
238 self.hasher,
239 self.build_options,
240 self.minimum_libc_version,
241 )
242 });
243
244 match result {
245 Ok(results) => Ok(VersionsResponse::Found(
246 results
247 .into_iter()
248 .map(|(index, metadata)| {
249 let included_version_cutoff =
250 self.effective_exclude_newer(package_name, index);
251 let available_version_cutoff = included_version_cutoff
252 .is_none()
253 .then_some(self.available_version_cutoff)
254 .flatten();
255
256 match metadata {
257 MetadataFormat::Simple(metadata) => VersionMap::from_simple_metadata(
258 metadata,
259 package_name,
260 self.fetcher.client().index_locations().route_for(index),
261 self.tags.clone(),
262 self.requires_python.clone(),
263 self.allowed_yanks.clone(),
264 self.hasher.clone(),
265 included_version_cutoff,
266 available_version_cutoff,
267 flat_distributions.clone(),
268 self.build_options,
269 self.minimum_libc_version,
270 ),
271 MetadataFormat::Flat(metadata) => VersionMap::from_flat_metadata(
272 metadata,
273 self.tags.as_ref(),
274 self.hasher,
275 self.build_options,
276 self.minimum_libc_version,
277 ),
278 }
279 })
280 .collect(),
281 )),
282 Err(err) => match err.kind() {
283 uv_client::ErrorKind::RemotePackageNotFound(_) => {
284 if let Some(flat_index) = flat_distributions {
285 Ok(VersionsResponse::Found(vec![VersionMap::from(flat_index)]))
286 } else {
287 Ok(VersionsResponse::NotFound)
288 }
289 }
290 uv_client::ErrorKind::NoIndex(_) => {
291 if let Some(flat_index) = flat_distributions {
292 Ok(VersionsResponse::Found(vec![VersionMap::from(flat_index)]))
293 } else if flat_index.is_some_and(FlatIndex::offline) {
294 Ok(VersionsResponse::Offline)
295 } else {
296 Ok(VersionsResponse::NoIndex)
297 }
298 }
299 uv_client::ErrorKind::Offline(_) => {
300 if let Some(flat_index) = flat_distributions {
301 Ok(VersionsResponse::Found(vec![VersionMap::from(flat_index)]))
302 } else {
303 Ok(VersionsResponse::Offline)
304 }
305 }
306 _ => Err(err),
307 },
308 }
309 }
310
311 async fn get_or_build_wheel_metadata<'io>(&'io self, dist: &'io Dist) -> WheelMetadataResult {
313 match self
314 .fetcher
315 .get_or_build_wheel_metadata(dist, self.hasher.metadata_policy(dist))
316 .await
317 {
318 Ok(metadata) => Ok(MetadataResponse::Found(metadata)),
319 Err(err) => match err {
320 uv_distribution::Error::Client(client) => {
321 match self.classify_metadata_error(client, dist.index()) {
324 Ok(reason) => Ok(MetadataResponse::Unavailable(reason)),
325 Err(error) => Err(error.into()),
326 }
327 }
328 uv_distribution::Error::WheelMetadataVersionMismatch { .. } => {
329 Ok(MetadataResponse::Unavailable(
330 MetadataUnavailable::InconsistentMetadata(Arc::new(err)),
331 ))
332 }
333 uv_distribution::Error::WheelMetadataNameMismatch { .. } => {
334 Ok(MetadataResponse::Unavailable(
335 MetadataUnavailable::InconsistentMetadata(Arc::new(err)),
336 ))
337 }
338 uv_distribution::Error::Metadata(err) => Ok(MetadataResponse::Unavailable(
339 MetadataUnavailable::InvalidMetadata(Arc::new(err)),
340 )),
341 uv_distribution::Error::WheelMetadata(_, err) => Ok(MetadataResponse::Unavailable(
342 classify_wheel_metadata_error(*err),
343 )),
344 uv_distribution::Error::RequiresPython(requires_python, version) => {
345 Ok(MetadataResponse::Unavailable(
346 MetadataUnavailable::RequiresPython(requires_python, version),
347 ))
348 }
349 err => Ok(MetadataResponse::Error(
350 Box::new(RequestedDist::Installable(dist.clone())),
351 Arc::new(err),
352 )),
353 },
354 }
355 }
356
357 async fn get_wheel_variant_metadata(
358 &self,
359 wheel: &BuiltDist,
360 ) -> Result<Option<VariantsJsonContent>, uv_distribution::Error> {
361 self.fetcher
362 .get_wheel_variant_metadata(wheel, self.hasher.archive_policy(wheel))
363 .await
364 }
365
366 async fn get_installed_metadata<'io>(
368 &'io self,
369 dist: &'io InstalledDist,
370 ) -> WheelMetadataResult {
371 match self.fetcher.get_installed_metadata(dist).await {
372 Ok(metadata) => Ok(MetadataResponse::Found(metadata)),
373 Err(err) => Ok(MetadataResponse::Error(
374 Box::new(RequestedDist::Installed(dist.clone())),
375 Arc::new(err),
376 )),
377 }
378 }
379
380 async fn fetch_variants_json<'io>(
381 &'io self,
382 package_name: &'io PackageName,
383 file: &'io VerbatimFile,
384 index: &'io IndexUrl,
385 ) -> Result<VariantsJsonResponse, uv_client::Error> {
386 match self
387 .fetcher
388 .client()
389 .managed(|client| client.fetch_variants_json(package_name, file, index))
390 .await
391 {
392 Ok(contents) => Ok(VariantsJsonResponse::Found(contents)),
393 Err(error) => match self.classify_metadata_error(error, Some(index)) {
394 Ok(reason) => Ok(VariantsJsonResponse::Unavailable(reason)),
395 Err(error) => Err(error),
396 },
397 }
398 }
399
400 fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
402 Self {
403 fetcher: self.fetcher.with_reporter(reporter),
404 ..self
405 }
406 }
407}