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