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#[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 File,
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| 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
178pub(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
194pub(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 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 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 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 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 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 fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
398 Self {
399 fetcher: self.fetcher.with_reporter(reporter),
400 ..self
401 }
402 }
403}