Skip to main content

uv_dispatch/
lib.rs

1//! Avoid cyclic crate dependencies between [resolver][`uv_resolver`],
2//! [installer][`uv_installer`] and [build frontend][`uv_build_frontend`] through [`BuildDispatch`]
3//! implementing [`BuildContext`].
4
5use std::ffi::{OsStr, OsString};
6use std::future::{self, Future};
7use std::path::Path;
8
9use anyhow::Result;
10use futures::FutureExt;
11use itertools::Itertools;
12use rustc_hash::FxHashMap;
13use thiserror::Error;
14use tracing::{debug, instrument, trace};
15
16use uv_build_backend::{Error as BuildBackendError, check_direct_build};
17use uv_build_frontend::{SourceBuild, SourceBuildContext};
18use uv_cache::Cache;
19use uv_client::RegistryClient;
20use uv_configuration::{
21    BuildKind, BuildOptions, Constraints, DependencyModifiers, HashCheckingMode, IndexStrategy,
22    NoSources, Reinstall,
23};
24use uv_configuration::{BuildOutput, Concurrency};
25use uv_distribution::DistributionDatabase;
26use uv_distribution_filename::DistFilename;
27use uv_distribution_types::{
28    CachedDist, ConfigSettings, DependencyMetadata, ExtraBuildRequires, ExtraBuildVariables,
29    Identifier, IndexCapabilities, IndexLocations, IsBuildBackendError, Name,
30    PackageConfigSettings, Requirement, Resolution, SourceDist, VersionOrUrlRef,
31};
32use uv_git::GitResolver;
33use uv_installer::{InstallationStrategy, Installer, Plan, Planner, Preparer, SitePackages};
34use uv_preview::Preview;
35use uv_pypi_types::Conflicts;
36use uv_python_interpreter::{Interpreter, PythonEnvironment};
37use uv_requirements::LookaheadResolver;
38use uv_resolver::{
39    ExcludeNewer, FlatIndex, Flexibility, InMemoryIndex, Manifest, OptionsBuilder,
40    PythonRequirement, Resolver, ResolverEnvironment,
41};
42use uv_static::TarBackend;
43use uv_types::{
44    AnyErrorBuild, BuildArena, BuildContext, BuildIsolation, BuildStack, EmptyInstalledPackages,
45    HashStrategy, HashVerification, InFlight, ResolvedRequirements, SourceTreeEditablePolicy,
46};
47use uv_workspace::WorkspaceCache;
48
49#[derive(Debug, Error)]
50pub enum BuildDispatchError {
51    #[error(transparent)]
52    BuildFrontend(#[from] AnyErrorBuild),
53
54    #[error(transparent)]
55    BuildBackend(#[from] BuildBackendError),
56
57    #[error(transparent)]
58    Tags(#[from] uv_platform_tags::TagsError),
59
60    #[error(transparent)]
61    Resolve(#[from] uv_resolver::ResolveError),
62
63    #[error(
64        "No solution found when resolving: {}",
65        requirements.iter().format_with(", ", |requirement, f| f(&format_args!("`{requirement}`")))
66    )]
67    ResolveRequirements {
68        requirements: Vec<Requirement>,
69        #[source]
70        source: uv_resolver::ResolveError,
71    },
72
73    #[error(transparent)]
74    Join(#[from] tokio::task::JoinError),
75
76    #[error(transparent)]
77    Anyhow(#[from] anyhow::Error),
78
79    #[error(transparent)]
80    Prepare(#[from] uv_installer::PrepareError),
81
82    #[error("Failed to uninstall build dependencies")]
83    UninstallBuildDependencies(#[source] uv_installer::UninstallError),
84
85    #[error("Failed to install build dependencies")]
86    InstallBuildDependencies(#[source] uv_installer::InstallError),
87
88    #[error(transparent)]
89    Plan(#[from] uv_installer::PlanError),
90
91    #[error(transparent)]
92    Lookahead(#[from] uv_requirements::Error),
93}
94
95impl uv_errors::Hinted for BuildDispatchError {
96    fn hints(&self) -> uv_errors::Hints<'_> {
97        match self {
98            Self::BuildFrontend(err) => err.hints(),
99            Self::Plan(error) => error.hints(),
100            Self::Resolve(err) | Self::ResolveRequirements { source: err, .. } => err.hints(),
101            Self::BuildBackend(_)
102            | Self::Tags(_)
103            | Self::Join(_)
104            | Self::Anyhow(_)
105            | Self::Prepare(_)
106            | Self::UninstallBuildDependencies(_)
107            | Self::InstallBuildDependencies(_)
108            | Self::Lookahead(_) => uv_errors::Hints::none(),
109        }
110    }
111}
112
113impl IsBuildBackendError for BuildDispatchError {
114    fn is_user_failure(&self) -> bool {
115        match self {
116            Self::BuildFrontend(error) => error.is_user_failure(),
117            Self::Resolve(error) | Self::ResolveRequirements { source: error, .. } => {
118                error.is_user_failure()
119            }
120            Self::Prepare(error) => error.is_user_failure(),
121            Self::Lookahead(error) => error.is_user_failure(),
122            Self::BuildBackend(_)
123            | Self::Tags(_)
124            | Self::Join(_)
125            | Self::Anyhow(_)
126            | Self::UninstallBuildDependencies(_)
127            | Self::InstallBuildDependencies(_)
128            | Self::Plan(_) => false,
129        }
130    }
131
132    fn is_build_backend_error(&self) -> bool {
133        match self {
134            Self::BuildBackend(_)
135            | Self::Tags(_)
136            | Self::Resolve(_)
137            | Self::ResolveRequirements { .. }
138            | Self::Join(_)
139            | Self::Anyhow(_)
140            | Self::Prepare(_)
141            | Self::UninstallBuildDependencies(_)
142            | Self::InstallBuildDependencies(_)
143            | Self::Plan(_)
144            | Self::Lookahead(_) => false,
145            Self::BuildFrontend(err) => err.is_build_backend_error(),
146        }
147    }
148}
149
150/// The main implementation of [`BuildContext`], used by the CLI, see [`BuildContext`]
151/// documentation.
152#[derive(Clone)]
153pub struct BuildDispatch<'a> {
154    client: &'a RegistryClient,
155    cache: &'a Cache,
156    constraints: &'a Constraints,
157    interpreter: &'a Interpreter,
158    index_locations: &'a IndexLocations,
159    index_strategy: IndexStrategy,
160    flat_index: &'a FlatIndex,
161    shared_state: SharedState,
162    dependency_metadata: &'a DependencyMetadata,
163    build_isolation: BuildIsolation<'a>,
164    extra_build_requires: &'a ExtraBuildRequires,
165    extra_build_variables: &'a ExtraBuildVariables,
166    link_mode: uv_install_wheel::LinkMode,
167    build_options: &'a BuildOptions,
168    config_settings: &'a ConfigSettings,
169    config_settings_package: &'a PackageConfigSettings,
170    base_hasher: &'a HashStrategy,
171    build_hash_checking: HashCheckingMode,
172    exclude_newer: ExcludeNewer,
173    source_build_context: SourceBuildContext,
174    build_extra_env_vars: FxHashMap<OsString, OsString>,
175    sources: NoSources,
176    source_tree_editable_policy: SourceTreeEditablePolicy,
177    workspace_cache: WorkspaceCache,
178    concurrency: Concurrency,
179    preview: Preview,
180    tar_backend: TarBackend,
181}
182
183impl<'a> BuildDispatch<'a> {
184    // TODO(charlie): Review call sites and consider if we want to make some of the parameters
185    // optional.
186    pub fn new(
187        client: &'a RegistryClient,
188        cache: &'a Cache,
189        constraints: &'a Constraints,
190        interpreter: &'a Interpreter,
191        index_locations: &'a IndexLocations,
192        flat_index: &'a FlatIndex,
193        dependency_metadata: &'a DependencyMetadata,
194        shared_state: SharedState,
195        index_strategy: IndexStrategy,
196        config_settings: &'a ConfigSettings,
197        config_settings_package: &'a PackageConfigSettings,
198        build_isolation: BuildIsolation<'a>,
199        extra_build_requires: &'a ExtraBuildRequires,
200        extra_build_variables: &'a ExtraBuildVariables,
201        link_mode: uv_install_wheel::LinkMode,
202        build_options: &'a BuildOptions,
203        hasher: &'a HashStrategy,
204        exclude_newer: ExcludeNewer,
205        sources: NoSources,
206        source_tree_editable_policy: SourceTreeEditablePolicy,
207        workspace_cache: WorkspaceCache,
208        concurrency: Concurrency,
209        preview: Preview,
210    ) -> Self {
211        Self {
212            client,
213            cache,
214            constraints,
215            interpreter,
216            index_locations,
217            flat_index,
218            shared_state,
219            dependency_metadata,
220            index_strategy,
221            config_settings,
222            config_settings_package,
223            build_isolation,
224            extra_build_requires,
225            extra_build_variables,
226            link_mode,
227            build_options,
228            base_hasher: hasher,
229            build_hash_checking: match hasher.verification() {
230                HashVerification::Required(_) => HashCheckingMode::Require,
231                HashVerification::Unspecified | HashVerification::IfPresent(_) => {
232                    HashCheckingMode::Verify
233                }
234            },
235            exclude_newer,
236            source_build_context: SourceBuildContext::new(concurrency.builds_semaphore.clone()),
237            build_extra_env_vars: FxHashMap::default(),
238            sources,
239            source_tree_editable_policy,
240            workspace_cache,
241            concurrency,
242            preview,
243            tar_backend: TarBackend::from_env(),
244        }
245    }
246
247    /// Fork the dispatch with a different hash strategy.
248    ///
249    /// In-memory resolution, download, and build caches are reset, since they may depend on the
250    /// previous policy.
251    #[must_use]
252    pub fn fork<'fork>(&'fork self, hasher: &'fork HashStrategy) -> BuildDispatch<'fork> {
253        BuildDispatch {
254            base_hasher: hasher,
255            shared_state: SharedState {
256                build_arena: BuildArena::default(),
257                ..self.shared_state.fork()
258            },
259            source_build_context: SourceBuildContext::new(
260                self.concurrency.builds_semaphore.clone(),
261            ),
262            ..self.clone()
263        }
264    }
265
266    /// Set the environment variables to be used when building a source distribution.
267    #[must_use]
268    pub fn with_build_extra_env_vars<I, K, V>(mut self, sdist_build_env_variables: I) -> Self
269    where
270        I: IntoIterator<Item = (K, V)>,
271        K: AsRef<OsStr>,
272        V: AsRef<OsStr>,
273    {
274        self.build_extra_env_vars = sdist_build_env_variables
275            .into_iter()
276            .map(|(key, value)| (key.as_ref().to_owned(), value.as_ref().to_owned()))
277            .collect();
278        self
279    }
280
281    /// Set the hash-checking mode for build dependencies.
282    ///
283    /// When hashes are required, hashes from backend-generated requirements are not trusted.
284    #[must_use]
285    pub fn with_build_hash_checking(mut self, mode: HashCheckingMode) -> Self {
286        self.build_hash_checking = mode;
287        self
288    }
289
290    fn require_build_hashes(&self) -> bool {
291        self.build_hash_checking.is_require()
292    }
293}
294
295#[allow(refining_impl_trait)]
296impl BuildContext for BuildDispatch<'_> {
297    type SourceDistBuilder = SourceBuild;
298
299    fn tar_backend(&self) -> TarBackend {
300        self.tar_backend
301    }
302
303    fn interpreter(&self) -> impl Future<Output = &Interpreter> + '_ {
304        future::ready(self.interpreter)
305    }
306
307    fn cache(&self) -> &Cache {
308        self.cache
309    }
310
311    fn git(&self) -> &GitResolver {
312        &self.shared_state.git
313    }
314
315    fn build_arena(&self) -> &BuildArena<SourceBuild> {
316        &self.shared_state.build_arena
317    }
318
319    fn capabilities(&self) -> &IndexCapabilities {
320        &self.shared_state.capabilities
321    }
322
323    fn dependency_metadata(&self) -> &DependencyMetadata {
324        self.dependency_metadata
325    }
326
327    fn build_options(&self) -> &BuildOptions {
328        self.build_options
329    }
330
331    fn build_isolation(&self) -> BuildIsolation<'_> {
332        self.build_isolation
333    }
334
335    fn config_settings(&self) -> &ConfigSettings {
336        self.config_settings
337    }
338
339    fn config_settings_package(&self) -> &PackageConfigSettings {
340        self.config_settings_package
341    }
342
343    fn sources(&self) -> &NoSources {
344        &self.sources
345    }
346
347    fn source_tree_editable_policy(&self) -> SourceTreeEditablePolicy {
348        self.source_tree_editable_policy
349    }
350
351    fn locations(&self) -> &IndexLocations {
352        self.index_locations
353    }
354
355    fn workspace_cache(&self) -> &WorkspaceCache {
356        &self.workspace_cache
357    }
358
359    fn extra_build_requires(&self) -> &ExtraBuildRequires {
360        self.extra_build_requires
361    }
362
363    fn extra_build_variables(&self) -> &ExtraBuildVariables {
364        self.extra_build_variables
365    }
366
367    async fn resolve<'data>(
368        &'data self,
369        requirements: &'data [Requirement],
370        hash_override: Option<&'data HashStrategy>,
371        build_stack: &'data BuildStack,
372    ) -> Result<ResolvedRequirements, BuildDispatchError> {
373        let python_requirement = PythonRequirement::from_interpreter(self.interpreter);
374        let marker_env = self.interpreter.to_resolver_marker_environment();
375        let resolver_env = ResolverEnvironment::specific(marker_env);
376        let tags = self.interpreter.tags()?;
377
378        let active_requirements = requirements.iter().filter(|requirement| {
379            requirement.evaluate_markers(Some(self.interpreter.markers()), &[])
380        });
381        let previous_hasher = hash_override;
382        let hasher = match previous_hasher {
383            Some(hasher) if self.require_build_hashes() => hasher
384                .clone()
385                .augment_with_metadata_requirements(active_requirements),
386            previous_hasher => previous_hasher
387                .unwrap_or(self.base_hasher)
388                .clone()
389                .augment_with_requirements(active_requirements),
390        }
391        .map_err(uv_requirements::Error::from)?;
392
393        // Walk any URL requirements transitively so their sub-URLs (for example, a workspace
394        // member that depends on another workspace member) are known before the resolver runs
395        // its URL allow-list check. This mirrors what the project resolver does in
396        // `uv_requirements::LookaheadResolver` and prevents a `DisallowedUrl` error when one
397        // `build-system.requires` entry pulls in another URL dependency.
398        let modifiers = DependencyModifiers::default();
399        let (lookaheads, hasher) = LookaheadResolver::new(
400            requirements,
401            self.constraints,
402            &modifiers,
403            &hasher,
404            &self.shared_state.index,
405            DistributionDatabase::new(
406                self.client,
407                self,
408                self.concurrency.downloads_semaphore.clone(),
409            )
410            .with_build_stack(build_stack),
411        )
412        .resolve(&resolver_env)
413        .await?;
414
415        let manifest = Manifest::simple(requirements.to_vec())
416            .with_constraints(self.constraints.clone())
417            .with_lookaheads(lookaheads);
418
419        let resolver = Resolver::new(
420            manifest,
421            OptionsBuilder::new()
422                .exclude_newer(self.exclude_newer.clone())
423                .index_strategy(self.index_strategy)
424                .build_options(self.build_options.clone())
425                .flexibility(Flexibility::Fixed)
426                .build(),
427            &python_requirement,
428            resolver_env,
429            self.interpreter.markers(),
430            // Conflicting groups only make sense when doing universal resolution.
431            Conflicts::empty(),
432            Some(tags),
433            self.flat_index,
434            &self.shared_state.index,
435            &hasher,
436            self,
437            EmptyInstalledPackages,
438            DistributionDatabase::new(
439                self.client,
440                self,
441                self.concurrency.downloads_semaphore.clone(),
442            )
443            .with_build_stack(build_stack),
444        )?;
445        let resolution = Resolution::from(resolver.resolve().await.map_err(|source| {
446            BuildDispatchError::ResolveRequirements {
447                requirements: requirements.to_vec(),
448                source,
449            }
450        })?);
451        Ok(ResolvedRequirements::new(resolution, hasher))
452    }
453
454    #[instrument(
455        skip(self, requirements, venv),
456        fields(
457            resolution = requirements.resolution().distributions().map(ToString::to_string).join(", "),
458            venv = ?venv.root()
459        )
460    )]
461    async fn install<'data>(
462        &'data self,
463        requirements: &'data ResolvedRequirements,
464        venv: &'data PythonEnvironment,
465        build_stack: &'data BuildStack,
466    ) -> Result<Vec<CachedDist>, BuildDispatchError> {
467        let resolution = requirements.resolution();
468        let hasher = requirements.hasher();
469
470        debug!(
471            "Installing `{}` in `{}`",
472            resolution
473                .distributions()
474                .map(ToString::to_string)
475                .join("`, `"),
476            venv.root().display(),
477        );
478
479        // Determine the current environment markers.
480        let tags = self.interpreter.tags()?;
481
482        // Determine the set of installed packages.
483        let site_packages = SitePackages::from_environment(venv)?;
484
485        let Plan {
486            cached,
487            remote,
488            reinstalls,
489            extraneous: _,
490        } = Planner::new(resolution).build(
491            site_packages,
492            InstallationStrategy::Permissive,
493            &Reinstall::default(),
494            self.build_options,
495            hasher,
496            self.index_locations,
497            self.config_settings,
498            self.config_settings_package,
499            self.extra_build_requires(),
500            self.extra_build_variables,
501            self.cache(),
502            venv,
503            tags,
504        )?;
505
506        // Nothing to do.
507        if remote.is_empty() && cached.is_empty() && reinstalls.is_empty() {
508            debug!("No build requirements to install for build");
509            return Ok(vec![]);
510        }
511
512        // Verify that none of the missing distributions are already in the build stack.
513        for dist in &remote {
514            let id = dist.distribution_id();
515            if build_stack.contains(&id) {
516                return Err(BuildDispatchError::BuildFrontend(
517                    uv_build_frontend::Error::CyclicBuildDependency(dist.name().clone()).into(),
518                ));
519            }
520        }
521
522        // Download any missing distributions.
523        let wheels = if remote.is_empty() {
524            vec![]
525        } else {
526            let preparer = Preparer::new(
527                self.cache,
528                tags,
529                hasher,
530                self.build_options,
531                DistributionDatabase::new(
532                    self.client,
533                    self,
534                    self.concurrency.downloads_semaphore.clone(),
535                )
536                .with_build_stack(build_stack),
537            );
538
539            debug!(
540                "Downloading and building requirement{} for build: {}",
541                if remote.len() == 1 { "" } else { "s" },
542                remote.iter().map(ToString::to_string).join(", ")
543            );
544
545            preparer
546                .prepare(remote, &self.shared_state.in_flight, resolution)
547                .await?
548        };
549
550        // Remove any unnecessary packages.
551        if !reinstalls.is_empty() {
552            let layout = venv.interpreter().layout();
553            for dist_info in &reinstalls {
554                let summary = uv_installer::uninstall(dist_info, &layout)
555                    .await
556                    .map_err(BuildDispatchError::UninstallBuildDependencies)?;
557                debug!(
558                    "Uninstalled {} ({} file{}, {} director{})",
559                    dist_info.name(),
560                    summary.file_count,
561                    if summary.file_count == 1 { "" } else { "s" },
562                    summary.dir_count,
563                    if summary.dir_count == 1 { "y" } else { "ies" },
564                );
565            }
566        }
567
568        // Install the resolved distributions.
569        let mut wheels = wheels.into_iter().chain(cached).collect::<Vec<_>>();
570        if !wheels.is_empty() {
571            debug!(
572                "Installing build requirement{}: {}",
573                if wheels.len() == 1 { "" } else { "s" },
574                wheels.iter().map(ToString::to_string).join(", ")
575            );
576            wheels = Installer::new(venv, self.preview)
577                .with_link_mode(self.link_mode)
578                .with_cache(self.cache)
579                .install(wheels)
580                .await
581                .map_err(BuildDispatchError::InstallBuildDependencies)?;
582        }
583
584        Ok(wheels)
585    }
586
587    #[instrument(skip_all, fields(version_id = version_id, subdirectory = ?subdirectory))]
588    async fn setup_build<'data>(
589        &'data self,
590        source: &'data Path,
591        subdirectory: Option<&'data Path>,
592        install_path: &'data Path,
593        stop_discovery_at: Option<&'data Path>,
594        version_id: Option<&'data str>,
595        dist: Option<&'data SourceDist>,
596        sources: &'data NoSources,
597        build_kind: BuildKind,
598        build_output: BuildOutput,
599        mut build_stack: BuildStack,
600    ) -> Result<SourceBuild, uv_build_frontend::Error> {
601        let dist_name = dist.map(uv_distribution_types::Name::name);
602        let dist_version = dist
603            .map(uv_distribution_types::DistributionMetadata::version_or_url)
604            .and_then(|version| match version {
605                VersionOrUrlRef::Version(version) => Some(version),
606                VersionOrUrlRef::Url(_) => None,
607            });
608
609        // Push the current distribution onto the build stack, to prevent cyclic dependencies.
610        if let Some(dist) = dist {
611            build_stack.insert(dist.distribution_id());
612        }
613
614        // Get package-specific config settings if available; otherwise, use global settings.
615        let config_settings = if let Some(name) = dist_name {
616            if let Some(package_settings) = self.config_settings_package.get(name) {
617                package_settings.clone().merge(self.config_settings.clone())
618            } else {
619                self.config_settings.clone()
620            }
621        } else {
622            self.config_settings.clone()
623        };
624
625        // Get package-specific environment variables if available.
626        let mut environment_variables = self.build_extra_env_vars.clone();
627        if let Some(name) = dist_name {
628            if let Some(package_vars) = self.extra_build_variables.get(name) {
629                environment_variables.extend(
630                    package_vars
631                        .iter()
632                        .map(|(key, value)| (OsString::from(key), OsString::from(value))),
633                );
634            }
635        }
636
637        let builder = SourceBuild::setup(
638            source,
639            subdirectory,
640            install_path,
641            stop_discovery_at,
642            dist_name,
643            dist_version,
644            self.interpreter,
645            self,
646            self.source_build_context.clone(),
647            version_id,
648            self.index_locations,
649            sources.clone(),
650            self.workspace_cache(),
651            config_settings,
652            self.build_isolation,
653            self.extra_build_requires,
654            &build_stack,
655            build_kind,
656            environment_variables,
657            build_output,
658            self.client.credentials_cache(),
659        )
660        .boxed_local()
661        .await?;
662        Ok(builder)
663    }
664
665    async fn direct_build<'data>(
666        &'data self,
667        source: &'data Path,
668        subdirectory: Option<&'data Path>,
669        output_dir: &'data Path,
670        sources: NoSources,
671        build_kind: BuildKind,
672        version_id: Option<&'data str>,
673    ) -> Result<Option<DistFilename>, BuildDispatchError> {
674        let source_tree = if let Some(subdir) = subdirectory {
675            source.join(subdir)
676        } else {
677            source.to_path_buf()
678        };
679
680        // Only perform the direct build if the backend is uv in a compatible version.
681        let source_tree_str = source_tree.display().to_string();
682        let identifier = version_id.unwrap_or_else(|| &source_tree_str);
683        if let Err(reason) = check_direct_build(
684            &source_tree,
685            uv_version::version(),
686            &self.interpreter.to_resolver_marker_environment(),
687            self.constraints.requirements().cloned().map(Into::into),
688        ) {
689            trace!("Requirements for direct build not matched because {reason}");
690            return Ok(None);
691        }
692
693        debug!("Performing direct build for {identifier}");
694
695        let output_dir = output_dir.to_path_buf();
696        let tar_backend = self.tar_backend;
697        let filename = tokio::task::spawn_blocking(move || -> Result<_, BuildBackendError> {
698            let filename = match build_kind {
699                BuildKind::Wheel => {
700                    let wheel = uv_build_backend::build_wheel(
701                        &source_tree,
702                        &output_dir,
703                        None,
704                        uv_version::version(),
705                        sources.is_none(),
706                    )?;
707                    DistFilename::WheelFilename(wheel)
708                }
709                BuildKind::Sdist => {
710                    let source_dist = uv_build_backend::build_source_dist(
711                        &source_tree,
712                        &output_dir,
713                        uv_version::version(),
714                        sources.is_none(),
715                        tar_backend,
716                    )?;
717                    DistFilename::SourceDistFilename(source_dist)
718                }
719                BuildKind::Editable => {
720                    let wheel = uv_build_backend::build_editable(
721                        &source_tree,
722                        &output_dir,
723                        None,
724                        uv_version::version(),
725                        sources.is_none(),
726                    )?;
727                    DistFilename::WheelFilename(wheel)
728                }
729            };
730            Ok(filename)
731        })
732        .await??;
733
734        Ok(Some(filename))
735    }
736}
737
738/// Shared state used during resolution and installation.
739///
740/// All elements are `Arc`s, so we can clone freely.
741#[derive(Default, Clone)]
742pub struct SharedState {
743    /// The resolved Git references.
744    git: GitResolver,
745    /// The discovered capabilities for each registry index.
746    capabilities: IndexCapabilities,
747    /// The fetched package versions and metadata.
748    index: InMemoryIndex,
749    /// The downloaded distributions.
750    in_flight: InFlight,
751    /// Build directories for any PEP 517 builds executed during resolution or installation.
752    build_arena: BuildArena<SourceBuild>,
753}
754
755impl SharedState {
756    /// Fork the [`SharedState`], creating a new in-memory index and in-flight cache.
757    ///
758    /// State that is universally applicable (like the Git resolver and index capabilities)
759    /// are retained.
760    #[must_use]
761    fn fork(&self) -> Self {
762        Self {
763            git: self.git.clone(),
764            capabilities: self.capabilities.clone(),
765            build_arena: self.build_arena.clone(),
766            ..Default::default()
767        }
768    }
769
770    /// Return the [`GitResolver`] used by the [`SharedState`].
771    pub fn git(&self) -> &GitResolver {
772        &self.git
773    }
774
775    /// Return the [`InMemoryIndex`] used by the [`SharedState`].
776    pub fn index(&self) -> &InMemoryIndex {
777        &self.index
778    }
779
780    /// Return mutable access to the index owner. Removing cached entries additionally requires
781    /// exclusive access to the index's shared storage.
782    fn index_mut(&mut self) -> &mut InMemoryIndex {
783        &mut self.index
784    }
785
786    /// Return the [`InFlight`] used by the [`SharedState`].
787    pub fn in_flight(&self) -> &InFlight {
788        &self.in_flight
789    }
790}
791
792/// A [`SharedState`] instance to use for universal resolution.
793#[derive(Default, Clone)]
794pub struct UniversalState(SharedState);
795
796impl std::ops::Deref for UniversalState {
797    type Target = SharedState;
798
799    fn deref(&self) -> &Self::Target {
800        &self.0
801    }
802}
803
804impl UniversalState {
805    /// Return mutable access to the index owner between lock operations.
806    pub fn index_mut(&mut self) -> &mut InMemoryIndex {
807        self.0.index_mut()
808    }
809
810    /// Fork the [`UniversalState`] to create a [`PlatformState`].
811    pub fn fork(&self) -> PlatformState {
812        PlatformState(self.0.fork())
813    }
814}
815
816/// A [`SharedState`] instance to use for platform-specific resolution.
817#[derive(Default, Clone)]
818pub struct PlatformState(SharedState);
819
820impl std::ops::Deref for PlatformState {
821    type Target = SharedState;
822
823    fn deref(&self) -> &Self::Target {
824        &self.0
825    }
826}
827
828impl PlatformState {
829    /// Fork the [`PlatformState`] to create a [`UniversalState`].
830    pub fn fork(&self) -> UniversalState {
831        UniversalState(self.0.fork())
832    }
833
834    /// Create a [`SharedState`] from the [`PlatformState`].
835    pub fn into_inner(self) -> SharedState {
836        self.0
837    }
838}