Skip to main content

uv_dispatch/
lib.rs

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