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