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, IndexStrategy, NoSources, Overrides, Reinstall,
22};
23use uv_configuration::{BuildOutput, Concurrency, Excludes};
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 overrides = Overrides::default();
332        let excludes = Excludes::default();
333        let (lookaheads, hasher) = LookaheadResolver::new(
334            requirements,
335            self.constraints,
336            &overrides,
337            &excludes,
338            &hasher,
339            &self.shared_state.index,
340            DistributionDatabase::new(
341                self.client,
342                self,
343                self.concurrency.downloads_semaphore.clone(),
344            )
345            .with_build_stack(build_stack),
346        )
347        .resolve(&resolver_env)
348        .await?;
349
350        let manifest = Manifest::simple(requirements.to_vec())
351            .with_constraints(self.constraints.clone())
352            .with_lookaheads(lookaheads);
353
354        let resolver = Resolver::new(
355            manifest,
356            OptionsBuilder::new()
357                .exclude_newer(self.exclude_newer.clone())
358                .index_strategy(self.index_strategy)
359                .build_options(self.build_options.clone())
360                .flexibility(Flexibility::Fixed)
361                .build(),
362            &python_requirement,
363            resolver_env,
364            self.interpreter.markers(),
365            // Conflicting groups only make sense when doing universal resolution.
366            Conflicts::empty(),
367            Some(tags),
368            self.flat_index,
369            &self.shared_state.index,
370            &hasher,
371            self,
372            EmptyInstalledPackages,
373            DistributionDatabase::new(
374                self.client,
375                self,
376                self.concurrency.downloads_semaphore.clone(),
377            )
378            .with_build_stack(build_stack),
379        )?;
380        let resolution = Resolution::from(resolver.resolve().await.with_context(|| {
381            format!(
382                "No solution found when resolving: {}",
383                requirements
384                    .iter()
385                    .map(|requirement| format!("`{requirement}`"))
386                    .join(", ")
387            )
388        })?);
389        Ok(ResolvedRequirements::new(resolution, hasher))
390    }
391
392    #[instrument(
393        skip(self, requirements, venv),
394        fields(
395            resolution = requirements.resolution().distributions().map(ToString::to_string).join(", "),
396            venv = ?venv.root()
397        )
398    )]
399    async fn install<'data>(
400        &'data self,
401        requirements: &'data ResolvedRequirements,
402        venv: &'data PythonEnvironment,
403        build_stack: &'data BuildStack,
404    ) -> Result<Vec<CachedDist>, BuildDispatchError> {
405        let resolution = requirements.resolution();
406        let hasher = requirements.hasher();
407
408        debug!(
409            "Installing in {} in {}",
410            resolution
411                .distributions()
412                .map(ToString::to_string)
413                .join(", "),
414            venv.root().display(),
415        );
416
417        // Determine the current environment markers.
418        let tags = self.interpreter.tags()?;
419
420        // Determine the set of installed packages.
421        let site_packages = SitePackages::from_environment(venv)?;
422
423        let Plan {
424            cached,
425            remote,
426            reinstalls,
427            extraneous: _,
428        } = Planner::new(resolution).build(
429            site_packages,
430            InstallationStrategy::Permissive,
431            &Reinstall::default(),
432            self.build_options,
433            hasher,
434            self.index_locations,
435            self.config_settings,
436            self.config_settings_package,
437            self.extra_build_requires(),
438            self.extra_build_variables,
439            self.cache(),
440            venv,
441            tags,
442        )?;
443
444        // Nothing to do.
445        if remote.is_empty() && cached.is_empty() && reinstalls.is_empty() {
446            debug!("No build requirements to install for build");
447            return Ok(vec![]);
448        }
449
450        // Verify that none of the missing distributions are already in the build stack.
451        for dist in &remote {
452            let id = dist.distribution_id();
453            if build_stack.contains(&id) {
454                return Err(BuildDispatchError::BuildFrontend(
455                    uv_build_frontend::Error::CyclicBuildDependency(dist.name().clone()).into(),
456                ));
457            }
458        }
459
460        // Download any missing distributions.
461        let wheels = if remote.is_empty() {
462            vec![]
463        } else {
464            let preparer = Preparer::new(
465                self.cache,
466                tags,
467                hasher,
468                self.build_options,
469                DistributionDatabase::new(
470                    self.client,
471                    self,
472                    self.concurrency.downloads_semaphore.clone(),
473                )
474                .with_build_stack(build_stack),
475            );
476
477            debug!(
478                "Downloading and building requirement{} for build: {}",
479                if remote.len() == 1 { "" } else { "s" },
480                remote.iter().map(ToString::to_string).join(", ")
481            );
482
483            preparer
484                .prepare(remote, &self.shared_state.in_flight, resolution)
485                .await?
486        };
487
488        // Remove any unnecessary packages.
489        if !reinstalls.is_empty() {
490            let layout = venv.interpreter().layout();
491            for dist_info in &reinstalls {
492                let summary = uv_installer::uninstall(dist_info, &layout)
493                    .await
494                    .context("Failed to uninstall build dependencies")?;
495                debug!(
496                    "Uninstalled {} ({} file{}, {} director{})",
497                    dist_info.name(),
498                    summary.file_count,
499                    if summary.file_count == 1 { "" } else { "s" },
500                    summary.dir_count,
501                    if summary.dir_count == 1 { "y" } else { "ies" },
502                );
503            }
504        }
505
506        // Install the resolved distributions.
507        let mut wheels = wheels.into_iter().chain(cached).collect::<Vec<_>>();
508        if !wheels.is_empty() {
509            debug!(
510                "Installing build requirement{}: {}",
511                if wheels.len() == 1 { "" } else { "s" },
512                wheels.iter().map(ToString::to_string).join(", ")
513            );
514            wheels = Installer::new(venv, self.preview)
515                .with_link_mode(self.link_mode)
516                .with_cache(self.cache)
517                .install(wheels)
518                .await
519                .context("Failed to install build dependencies")?;
520        }
521
522        Ok(wheels)
523    }
524
525    #[instrument(skip_all, fields(version_id = version_id, subdirectory = ?subdirectory))]
526    async fn setup_build<'data>(
527        &'data self,
528        source: &'data Path,
529        subdirectory: Option<&'data Path>,
530        install_path: &'data Path,
531        stop_discovery_at: Option<&'data Path>,
532        version_id: Option<&'data str>,
533        dist: Option<&'data SourceDist>,
534        sources: &'data NoSources,
535        build_kind: BuildKind,
536        build_output: BuildOutput,
537        mut build_stack: BuildStack,
538    ) -> Result<SourceBuild, uv_build_frontend::Error> {
539        let dist_name = dist.map(uv_distribution_types::Name::name);
540        let dist_version = dist
541            .map(uv_distribution_types::DistributionMetadata::version_or_url)
542            .and_then(|version| match version {
543                VersionOrUrlRef::Version(version) => Some(version),
544                VersionOrUrlRef::Url(_) => None,
545            });
546
547        // Push the current distribution onto the build stack, to prevent cyclic dependencies.
548        if let Some(dist) = dist {
549            build_stack.insert(dist.distribution_id());
550        }
551
552        // Get package-specific config settings if available; otherwise, use global settings.
553        let config_settings = if let Some(name) = dist_name {
554            if let Some(package_settings) = self.config_settings_package.get(name) {
555                package_settings.clone().merge(self.config_settings.clone())
556            } else {
557                self.config_settings.clone()
558            }
559        } else {
560            self.config_settings.clone()
561        };
562
563        // Get package-specific environment variables if available.
564        let mut environment_variables = self.build_extra_env_vars.clone();
565        if let Some(name) = dist_name {
566            if let Some(package_vars) = self.extra_build_variables.get(name) {
567                environment_variables.extend(
568                    package_vars
569                        .iter()
570                        .map(|(key, value)| (OsString::from(key), OsString::from(value))),
571                );
572            }
573        }
574
575        let builder = SourceBuild::setup(
576            source,
577            subdirectory,
578            install_path,
579            stop_discovery_at,
580            dist_name,
581            dist_version,
582            self.interpreter,
583            self,
584            self.source_build_context.clone(),
585            version_id,
586            self.index_locations,
587            sources.clone(),
588            self.workspace_cache(),
589            config_settings,
590            self.build_isolation,
591            self.extra_build_requires,
592            &build_stack,
593            build_kind,
594            environment_variables,
595            build_output,
596            self.client.credentials_cache(),
597        )
598        .boxed_local()
599        .await?;
600        Ok(builder)
601    }
602
603    async fn direct_build<'data>(
604        &'data self,
605        source: &'data Path,
606        subdirectory: Option<&'data Path>,
607        output_dir: &'data Path,
608        sources: NoSources,
609        build_kind: BuildKind,
610        version_id: Option<&'data str>,
611    ) -> Result<Option<DistFilename>, BuildDispatchError> {
612        let source_tree = if let Some(subdir) = subdirectory {
613            source.join(subdir)
614        } else {
615            source.to_path_buf()
616        };
617
618        // Only perform the direct build if the backend is uv in a compatible version.
619        let source_tree_str = source_tree.display().to_string();
620        let identifier = version_id.unwrap_or_else(|| &source_tree_str);
621        if let Err(reason) = check_direct_build(
622            &source_tree,
623            uv_version::version(),
624            &self.interpreter.to_resolver_marker_environment(),
625            self.constraints.requirements().cloned().map(Into::into),
626        ) {
627            trace!("Requirements for direct build not matched because {reason}");
628            return Ok(None);
629        }
630
631        debug!("Performing direct build for {identifier}");
632
633        let output_dir = output_dir.to_path_buf();
634        let filename = tokio::task::spawn_blocking(move || -> Result<_> {
635            let filename = match build_kind {
636                BuildKind::Wheel => {
637                    let wheel = uv_build_backend::build_wheel(
638                        &source_tree,
639                        &output_dir,
640                        None,
641                        uv_version::version(),
642                        sources.is_none(),
643                    )?;
644                    DistFilename::WheelFilename(wheel)
645                }
646                BuildKind::Sdist => {
647                    let source_dist = uv_build_backend::build_source_dist(
648                        &source_tree,
649                        &output_dir,
650                        uv_version::version(),
651                        sources.is_none(),
652                    )?;
653                    DistFilename::SourceDistFilename(source_dist)
654                }
655                BuildKind::Editable => {
656                    let wheel = uv_build_backend::build_editable(
657                        &source_tree,
658                        &output_dir,
659                        None,
660                        uv_version::version(),
661                        sources.is_none(),
662                    )?;
663                    DistFilename::WheelFilename(wheel)
664                }
665            };
666            Ok(filename)
667        })
668        .await??;
669
670        Ok(Some(filename))
671    }
672}
673
674/// Shared state used during resolution and installation.
675///
676/// All elements are `Arc`s, so we can clone freely.
677#[derive(Default, Clone)]
678pub struct SharedState {
679    /// The resolved Git references.
680    git: GitResolver,
681    /// The discovered capabilities for each registry index.
682    capabilities: IndexCapabilities,
683    /// The fetched package versions and metadata.
684    index: InMemoryIndex,
685    /// The downloaded distributions.
686    in_flight: InFlight,
687    /// Build directories for any PEP 517 builds executed during resolution or installation.
688    build_arena: BuildArena<SourceBuild>,
689}
690
691impl SharedState {
692    /// Fork the [`SharedState`], creating a new in-memory index and in-flight cache.
693    ///
694    /// State that is universally applicable (like the Git resolver and index capabilities)
695    /// are retained.
696    #[must_use]
697    pub fn fork(&self) -> Self {
698        Self {
699            git: self.git.clone(),
700            capabilities: self.capabilities.clone(),
701            build_arena: self.build_arena.clone(),
702            ..Default::default()
703        }
704    }
705
706    /// Return the [`GitResolver`] used by the [`SharedState`].
707    pub fn git(&self) -> &GitResolver {
708        &self.git
709    }
710
711    /// Return the [`InMemoryIndex`] used by the [`SharedState`].
712    pub fn index(&self) -> &InMemoryIndex {
713        &self.index
714    }
715
716    /// Return mutable access to the index owner. Removing cached entries additionally requires
717    /// exclusive access to the index's shared storage.
718    pub fn index_mut(&mut self) -> &mut InMemoryIndex {
719        &mut self.index
720    }
721
722    /// Return the [`InFlight`] used by the [`SharedState`].
723    pub fn in_flight(&self) -> &InFlight {
724        &self.in_flight
725    }
726}