Skip to main content

uv_resolver/
flat_index.rs

1use std::collections::BTreeMap;
2
3use rustc_hash::FxHashMap;
4use tracing::instrument;
5
6use uv_cache::Cache;
7use uv_client::{
8    FlatIndexClient, FlatIndexEntries, FlatIndexEntry, FlatIndexError, RegistryClient,
9};
10use uv_configuration::BuildOptions;
11use uv_distribution_filename::{DistFilename, SourceDistFilename, WheelFilename};
12use uv_distribution_types::{
13    Index, IndexEntryFilename, IndexLocations, IndexUrl, MinimumLibcVersion, RegistryBuiltWheel,
14    RegistrySourceDist, VerbatimFile,
15};
16use uv_normalize::PackageName;
17use uv_pep440::Version;
18use uv_platform_tags::{IncompatibleTag, TagCompatibility, Tags};
19use uv_preview::PreviewFeature;
20use uv_pypi_types::HashDigest;
21use uv_types::HashStrategy;
22
23use crate::prioritized_distribution::{
24    HashComparison, IncompatibleSource, IncompatibleWheel, PrioritizedDist, RegistryVariantsJson,
25    SourceDistCompatibility, WheelCompatibility,
26};
27
28/// Unfiltered entries from `--find-links`, indexed by [`PackageName`].
29#[derive(Debug, Clone, Default)]
30pub struct FlatIndex {
31    /// Entries are ranked using each resolver's platform and hash policies when requested.
32    index: FxHashMap<PackageName, Vec<FlatIndexEntry>>,
33    /// Whether any `--find-links` entries could not be resolved due to a lack of network
34    /// connectivity.
35    offline: bool,
36}
37
38impl FlatIndex {
39    /// Load the `--find-links` entries from the configured indexes.
40    pub async fn load(
41        client: &RegistryClient,
42        cache: &Cache,
43        index_locations: &IndexLocations,
44    ) -> Result<Self, FlatIndexError> {
45        let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), cache);
46        let entries = client
47            .fetch_all(index_locations.flat_indexes().map(Index::url))
48            .await?;
49        Ok(Self::from_entries(entries))
50    }
51
52    /// Collect all files from a `--find-links` target into a [`FlatIndex`].
53    #[instrument(skip_all)]
54    fn from_entries(entries: FlatIndexEntries) -> Self {
55        let mut index = FxHashMap::<PackageName, Vec<FlatIndexEntry>>::default();
56        let (entries, offline) = entries.into_parts();
57
58        for entry in entries {
59            index
60                .entry(entry.filename().name().clone())
61                .or_default()
62                .push(entry);
63        }
64
65        Self { index, offline }
66    }
67
68    /// Get the unfiltered entries for the given package name.
69    pub(crate) fn get(&self, package_name: &PackageName) -> Option<&[FlatIndexEntry]> {
70        self.index.get(package_name).map(Vec::as_slice)
71    }
72
73    /// Whether any `--find-links` entries could not be resolved due to a lack of network
74    /// connectivity.
75    pub(crate) fn offline(&self) -> bool {
76        self.offline
77    }
78}
79
80/// A set of [`PrioritizedDist`] from a `--find-links` entry for a single package, indexed
81/// by [`Version`].
82#[derive(Debug, Clone, Default)]
83pub struct FlatDistributions(BTreeMap<Version, PrioritizedDist>);
84
85impl FlatDistributions {
86    /// Rank the entries for a package using the resolver's platform and hash policies.
87    #[instrument(skip_all)]
88    pub(crate) fn from_entries(
89        entries: impl IntoIterator<Item = FlatIndexEntry>,
90        tags: Option<&Tags>,
91        hasher: &HashStrategy,
92        build_options: &BuildOptions,
93        minimum_libc_version: Option<MinimumLibcVersion>,
94    ) -> Self {
95        let mut distributions = Self::default();
96        for entry in entries {
97            let (filename, file, index) = entry.into_parts();
98            match filename {
99                IndexEntryFilename::DistFilename(filename) => distributions.add_file(
100                    file,
101                    filename,
102                    tags,
103                    hasher,
104                    build_options,
105                    index,
106                    minimum_libc_version,
107                ),
108                IndexEntryFilename::VariantJson(filename) => {
109                    distributions
110                        .0
111                        .entry(filename.version.clone())
112                        .or_default()
113                        .insert_variants_json(RegistryVariantsJson {
114                            filename,
115                            file,
116                            index,
117                        });
118                }
119            }
120        }
121        // Metadata alone does not make a package version installable.
122        distributions.0.retain(|_, dist| !dist.is_empty());
123        distributions
124    }
125
126    /// Returns an [`Iterator`] over the distributions.
127    pub(crate) fn iter(&self) -> impl Iterator<Item = (&Version, &PrioritizedDist)> {
128        self.0.iter()
129    }
130
131    /// Add the given [`VerbatimFile`] to the [`FlatDistributions`] for the given package.
132    fn add_file(
133        &mut self,
134        file: VerbatimFile,
135        filename: DistFilename,
136        tags: Option<&Tags>,
137        hasher: &HashStrategy,
138        build_options: &BuildOptions,
139        index: IndexUrl,
140        minimum_libc_version: Option<MinimumLibcVersion>,
141    ) {
142        let file = file.assume_canonical();
143
144        // No `requires-python` here: for source distributions, we don't have that information;
145        // for wheels, we read it lazily only when selected.
146        match filename {
147            DistFilename::WheelFilename(filename) => {
148                let version = filename.version.clone();
149
150                let compatibility = Self::wheel_compatibility(
151                    &filename,
152                    file.hashes.as_slice(),
153                    tags,
154                    hasher,
155                    build_options,
156                );
157                let dist = RegistryBuiltWheel {
158                    filename,
159                    file: Box::new(file),
160                    index,
161                    size_is_authoritative: false,
162                };
163                self.0.entry(version).or_default().insert_built(
164                    dist,
165                    vec![],
166                    compatibility,
167                    minimum_libc_version,
168                );
169            }
170            DistFilename::SourceDistFilename(filename) => {
171                let compatibility = Self::source_dist_compatibility(
172                    &filename,
173                    file.hashes.as_slice(),
174                    hasher,
175                    build_options,
176                );
177                let dist = RegistrySourceDist {
178                    name: filename.name.clone(),
179                    version: filename.version.clone(),
180                    ext: filename.extension,
181                    file: Box::new(file),
182                    index,
183                    wheels: vec![],
184                    size_is_authoritative: false,
185                };
186                self.0.entry(filename.version).or_default().insert_source(
187                    dist,
188                    vec![],
189                    compatibility,
190                );
191            }
192        }
193    }
194
195    fn source_dist_compatibility(
196        filename: &SourceDistFilename,
197        hashes: &[HashDigest],
198        hasher: &HashStrategy,
199        build_options: &BuildOptions,
200    ) -> SourceDistCompatibility {
201        // Check if source distributions are allowed for this package.
202        if build_options.no_build_package(&filename.name) {
203            return SourceDistCompatibility::Incompatible(IncompatibleSource::NoBuild);
204        }
205
206        // Check if the filename is PEP 625-compliant.
207        // TODO: Strengthen this check more; right now we allow `.zip`
208        // (which is not compliant) and we don't strictly
209        // enforce the formatting rules for the name or version.
210        if !filename.extension.is_pep625_compliant() {
211            return SourceDistCompatibility::Incompatible(IncompatibleSource::NotPep625Filename);
212        }
213
214        // Check if hashes line up
215        let hash_policy = hasher.archive_policy_for_package(&filename.name, &filename.version);
216        let hash = if hash_policy.requires_validation() {
217            if hashes.is_empty() {
218                HashComparison::Missing
219            } else if hash_policy.matches(hashes) {
220                HashComparison::Matched
221            } else {
222                HashComparison::Mismatched
223            }
224        } else {
225            HashComparison::Matched
226        };
227
228        SourceDistCompatibility::Compatible(hash)
229    }
230
231    fn wheel_compatibility(
232        filename: &WheelFilename,
233        hashes: &[HashDigest],
234        tags: Option<&Tags>,
235        hasher: &HashStrategy,
236        build_options: &BuildOptions,
237    ) -> WheelCompatibility {
238        if filename.variant().is_some() && !uv_preview::is_enabled(PreviewFeature::WheelVariants) {
239            return WheelCompatibility::Incompatible(IncompatibleWheel::Tag(
240                IncompatibleTag::Variant,
241            ));
242        }
243        // Check if binaries are allowed for this package.
244        if build_options.no_binary_package(&filename.name) {
245            return WheelCompatibility::Incompatible(IncompatibleWheel::NoBinary);
246        }
247
248        // Determine a compatibility for the wheel based on tags.
249        let priority = match tags {
250            Some(tags) => match filename.tag_compatibility(tags) {
251                TagCompatibility::Incompatible(tag) => {
252                    return WheelCompatibility::Incompatible(IncompatibleWheel::Tag(tag));
253                }
254                TagCompatibility::Compatible(priority) => Some(priority),
255            },
256            None => None,
257        };
258
259        // Check if hashes line up.
260        let hash_policy = hasher.archive_policy_for_package(&filename.name, &filename.version);
261        let hash = if hash_policy.requires_validation() {
262            if hashes.is_empty() {
263                HashComparison::Missing
264            } else if hash_policy.matches(hashes) {
265                HashComparison::Matched
266            } else {
267                HashComparison::Mismatched
268            }
269        } else {
270            HashComparison::Matched
271        };
272
273        WheelCompatibility::from_tag_priority(filename, hash, priority)
274    }
275}
276
277impl IntoIterator for FlatDistributions {
278    type Item = (Version, PrioritizedDist);
279    type IntoIter = std::collections::btree_map::IntoIter<Version, PrioritizedDist>;
280
281    fn into_iter(self) -> Self::IntoIter {
282        self.0.into_iter()
283    }
284}
285
286impl From<FlatDistributions> for BTreeMap<Version, PrioritizedDist> {
287    fn from(distributions: FlatDistributions) -> Self {
288        distributions.0
289    }
290}
291
292impl From<BTreeMap<Version, PrioritizedDist>> for FlatDistributions {
293    fn from(distributions: BTreeMap<Version, PrioritizedDist>) -> Self {
294        Self(distributions)
295    }
296}