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