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