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::path::Path;
7
8use anyhow::{Context, Result};
9use futures::FutureExt;
10use itertools::Itertools;
11use rustc_hash::FxHashMap;
12use thiserror::Error;
13use tracing::{debug, instrument, trace};
14
15use uv_build_backend::check_direct_build;
16use uv_build_frontend::{SourceBuild, SourceBuildContext};
17use uv_cache::Cache;
18use uv_client::RegistryClient;
19use uv_configuration::{BuildKind, BuildOptions, Constraints, IndexStrategy, NoSources, Reinstall};
20use uv_configuration::{BuildOutput, Concurrency};
21use uv_distribution::DistributionDatabase;
22use uv_distribution_filename::DistFilename;
23use uv_distribution_types::{
24    CachedDist, ConfigSettings, DependencyMetadata, ExtraBuildRequires, ExtraBuildVariables,
25    Identifier, IndexCapabilities, IndexLocations, IsBuildBackendError, Name,
26    PackageConfigSettings, Requirement, Resolution, SourceDist, VersionOrUrlRef,
27};
28use uv_git::GitResolver;
29use uv_installer::{InstallationStrategy, Installer, Plan, Planner, Preparer, SitePackages};
30use uv_preview::Preview;
31use uv_pypi_types::Conflicts;
32use uv_python::{Interpreter, PythonEnvironment};
33use uv_resolver::{
34    ExcludeNewer, FlatIndex, Flexibility, InMemoryIndex, Manifest, OptionsBuilder,
35    PythonRequirement, Resolver, ResolverEnvironment,
36};
37use uv_types::{
38    AnyErrorBuild, BuildArena, BuildContext, BuildIsolation, BuildStack, EmptyInstalledPackages,
39    HashStrategy, InFlight,
40};
41use uv_workspace::WorkspaceCache;
42
43#[derive(Debug, Error)]
44pub enum BuildDispatchError {
45    #[error(transparent)]
46    BuildFrontend(#[from] AnyErrorBuild),
47
48    #[error(transparent)]
49    Tags(#[from] uv_platform_tags::TagsError),
50
51    #[error(transparent)]
52    Resolve(#[from] uv_resolver::ResolveError),
53
54    #[error(transparent)]
55    Join(#[from] tokio::task::JoinError),
56
57    #[error(transparent)]
58    Anyhow(#[from] anyhow::Error),
59
60    #[error(transparent)]
61    Prepare(#[from] uv_installer::PrepareError),
62}
63
64impl IsBuildBackendError for BuildDispatchError {
65    fn is_build_backend_error(&self) -> bool {
66        match self {
67            Self::Tags(_)
68            | Self::Resolve(_)
69            | Self::Join(_)
70            | Self::Anyhow(_)
71            | Self::Prepare(_) => false,
72            Self::BuildFrontend(err) => err.is_build_backend_error(),
73        }
74    }
75}
76
77/// The main implementation of [`BuildContext`], used by the CLI, see [`BuildContext`]
78/// documentation.
79pub struct BuildDispatch<'a> {
80    client: &'a RegistryClient,
81    cache: &'a Cache,
82    constraints: &'a Constraints,
83    interpreter: &'a Interpreter,
84    index_locations: &'a IndexLocations,
85    index_strategy: IndexStrategy,
86    flat_index: &'a FlatIndex,
87    shared_state: SharedState,
88    dependency_metadata: &'a DependencyMetadata,
89    build_isolation: BuildIsolation<'a>,
90    extra_build_requires: &'a ExtraBuildRequires,
91    extra_build_variables: &'a ExtraBuildVariables,
92    link_mode: uv_install_wheel::LinkMode,
93    build_options: &'a BuildOptions,
94    config_settings: &'a ConfigSettings,
95    config_settings_package: &'a PackageConfigSettings,
96    hasher: &'a HashStrategy,
97    exclude_newer: ExcludeNewer,
98    source_build_context: SourceBuildContext,
99    build_extra_env_vars: FxHashMap<OsString, OsString>,
100    sources: NoSources,
101    workspace_cache: WorkspaceCache,
102    concurrency: Concurrency,
103    preview: Preview,
104}
105
106impl<'a> BuildDispatch<'a> {
107    pub fn new(
108        client: &'a RegistryClient,
109        cache: &'a Cache,
110        constraints: &'a Constraints,
111        interpreter: &'a Interpreter,
112        index_locations: &'a IndexLocations,
113        flat_index: &'a FlatIndex,
114        dependency_metadata: &'a DependencyMetadata,
115        shared_state: SharedState,
116        index_strategy: IndexStrategy,
117        config_settings: &'a ConfigSettings,
118        config_settings_package: &'a PackageConfigSettings,
119        build_isolation: BuildIsolation<'a>,
120        extra_build_requires: &'a ExtraBuildRequires,
121        extra_build_variables: &'a ExtraBuildVariables,
122        link_mode: uv_install_wheel::LinkMode,
123        build_options: &'a BuildOptions,
124        hasher: &'a HashStrategy,
125        exclude_newer: ExcludeNewer,
126        sources: NoSources,
127        workspace_cache: WorkspaceCache,
128        concurrency: Concurrency,
129        preview: Preview,
130    ) -> Self {
131        Self {
132            client,
133            cache,
134            constraints,
135            interpreter,
136            index_locations,
137            flat_index,
138            shared_state,
139            dependency_metadata,
140            index_strategy,
141            config_settings,
142            config_settings_package,
143            build_isolation,
144            extra_build_requires,
145            extra_build_variables,
146            link_mode,
147            build_options,
148            hasher,
149            exclude_newer,
150            source_build_context: SourceBuildContext::new(concurrency.builds_semaphore.clone()),
151            build_extra_env_vars: FxHashMap::default(),
152            sources,
153            workspace_cache,
154            concurrency,
155            preview,
156        }
157    }
158
159    /// Set the environment variables to be used when building a source distribution.
160    #[must_use]
161    pub fn with_build_extra_env_vars<I, K, V>(mut self, sdist_build_env_variables: I) -> Self
162    where
163        I: IntoIterator<Item = (K, V)>,
164        K: AsRef<OsStr>,
165        V: AsRef<OsStr>,
166    {
167        self.build_extra_env_vars = sdist_build_env_variables
168            .into_iter()
169            .map(|(key, value)| (key.as_ref().to_owned(), value.as_ref().to_owned()))
170            .collect();
171        self
172    }
173}
174
175#[allow(refining_impl_trait)]
176impl BuildContext for BuildDispatch<'_> {
177    type SourceDistBuilder = SourceBuild;
178
179    async fn interpreter(&self) -> &Interpreter {
180        self.interpreter
181    }
182
183    fn cache(&self) -> &Cache {
184        self.cache
185    }
186
187    fn git(&self) -> &GitResolver {
188        &self.shared_state.git
189    }
190
191    fn build_arena(&self) -> &BuildArena<SourceBuild> {
192        &self.shared_state.build_arena
193    }
194
195    fn capabilities(&self) -> &IndexCapabilities {
196        &self.shared_state.capabilities
197    }
198
199    fn dependency_metadata(&self) -> &DependencyMetadata {
200        self.dependency_metadata
201    }
202
203    fn build_options(&self) -> &BuildOptions {
204        self.build_options
205    }
206
207    fn build_isolation(&self) -> BuildIsolation<'_> {
208        self.build_isolation
209    }
210
211    fn config_settings(&self) -> &ConfigSettings {
212        self.config_settings
213    }
214
215    fn config_settings_package(&self) -> &PackageConfigSettings {
216        self.config_settings_package
217    }
218
219    fn sources(&self) -> &NoSources {
220        &self.sources
221    }
222
223    fn locations(&self) -> &IndexLocations {
224        self.index_locations
225    }
226
227    fn workspace_cache(&self) -> &WorkspaceCache {
228        &self.workspace_cache
229    }
230
231    fn extra_build_requires(&self) -> &ExtraBuildRequires {
232        self.extra_build_requires
233    }
234
235    fn extra_build_variables(&self) -> &ExtraBuildVariables {
236        self.extra_build_variables
237    }
238
239    async fn resolve<'data>(
240        &'data self,
241        requirements: &'data [Requirement],
242        build_stack: &'data BuildStack,
243    ) -> Result<Resolution, BuildDispatchError> {
244        let python_requirement = PythonRequirement::from_interpreter(self.interpreter);
245        let marker_env = self.interpreter.resolver_marker_environment();
246        let tags = self.interpreter.tags()?;
247
248        let resolver = Resolver::new(
249            Manifest::simple(requirements.to_vec()).with_constraints(self.constraints.clone()),
250            OptionsBuilder::new()
251                .exclude_newer(self.exclude_newer.clone())
252                .index_strategy(self.index_strategy)
253                .build_options(self.build_options.clone())
254                .flexibility(Flexibility::Fixed)
255                .build(),
256            &python_requirement,
257            ResolverEnvironment::specific(marker_env),
258            self.interpreter.markers(),
259            // Conflicting groups only make sense when doing universal resolution.
260            Conflicts::empty(),
261            Some(tags),
262            self.flat_index,
263            &self.shared_state.index,
264            self.hasher,
265            self,
266            EmptyInstalledPackages,
267            DistributionDatabase::new(
268                self.client,
269                self,
270                self.concurrency.downloads_semaphore.clone(),
271            )
272            .with_build_stack(build_stack),
273        )?;
274        let resolution = Resolution::from(resolver.resolve().await.with_context(|| {
275            format!(
276                "No solution found when resolving: {}",
277                requirements
278                    .iter()
279                    .map(|requirement| format!("`{requirement}`"))
280                    .join(", ")
281            )
282        })?);
283        Ok(resolution)
284    }
285
286    #[instrument(
287        skip(self, resolution, venv),
288        fields(
289            resolution = resolution.distributions().map(ToString::to_string).join(", "),
290            venv = ?venv.root()
291        )
292    )]
293    async fn install<'data>(
294        &'data self,
295        resolution: &'data Resolution,
296        venv: &'data PythonEnvironment,
297        build_stack: &'data BuildStack,
298    ) -> Result<Vec<CachedDist>, BuildDispatchError> {
299        debug!(
300            "Installing in {} in {}",
301            resolution
302                .distributions()
303                .map(ToString::to_string)
304                .join(", "),
305            venv.root().display(),
306        );
307
308        // Determine the current environment markers.
309        let tags = self.interpreter.tags()?;
310
311        // Determine the set of installed packages.
312        let site_packages = SitePackages::from_environment(venv)?;
313
314        let Plan {
315            cached,
316            remote,
317            reinstalls,
318            extraneous: _,
319        } = Planner::new(resolution).build(
320            site_packages,
321            InstallationStrategy::Permissive,
322            &Reinstall::default(),
323            self.build_options,
324            self.hasher,
325            self.index_locations,
326            self.config_settings,
327            self.config_settings_package,
328            self.extra_build_requires(),
329            self.extra_build_variables,
330            self.cache(),
331            venv,
332            tags,
333        )?;
334
335        // Nothing to do.
336        if remote.is_empty() && cached.is_empty() && reinstalls.is_empty() {
337            debug!("No build requirements to install for build");
338            return Ok(vec![]);
339        }
340
341        // Verify that none of the missing distributions are already in the build stack.
342        for dist in &remote {
343            let id = dist.distribution_id();
344            if build_stack.contains(&id) {
345                return Err(BuildDispatchError::BuildFrontend(
346                    uv_build_frontend::Error::CyclicBuildDependency(dist.name().clone()).into(),
347                ));
348            }
349        }
350
351        // Download any missing distributions.
352        let wheels = if remote.is_empty() {
353            vec![]
354        } else {
355            let preparer = Preparer::new(
356                self.cache,
357                tags,
358                self.hasher,
359                self.build_options,
360                DistributionDatabase::new(
361                    self.client,
362                    self,
363                    self.concurrency.downloads_semaphore.clone(),
364                )
365                .with_build_stack(build_stack),
366            );
367
368            debug!(
369                "Downloading and building requirement{} for build: {}",
370                if remote.len() == 1 { "" } else { "s" },
371                remote.iter().map(ToString::to_string).join(", ")
372            );
373
374            preparer
375                .prepare(remote, &self.shared_state.in_flight, resolution)
376                .await?
377        };
378
379        // Remove any unnecessary packages.
380        if !reinstalls.is_empty() {
381            for dist_info in &reinstalls {
382                let summary = uv_installer::uninstall(dist_info)
383                    .await
384                    .context("Failed to uninstall build dependencies")?;
385                debug!(
386                    "Uninstalled {} ({} file{}, {} director{})",
387                    dist_info.name(),
388                    summary.file_count,
389                    if summary.file_count == 1 { "" } else { "s" },
390                    summary.dir_count,
391                    if summary.dir_count == 1 { "y" } else { "ies" },
392                );
393            }
394        }
395
396        // Install the resolved distributions.
397        let mut wheels = wheels.into_iter().chain(cached).collect::<Vec<_>>();
398        if !wheels.is_empty() {
399            debug!(
400                "Installing build requirement{}: {}",
401                if wheels.len() == 1 { "" } else { "s" },
402                wheels.iter().map(ToString::to_string).join(", ")
403            );
404            wheels = Installer::new(venv, self.preview)
405                .with_link_mode(self.link_mode)
406                .with_cache(self.cache)
407                .install(wheels)
408                .await
409                .context("Failed to install build dependencies")?;
410        }
411
412        Ok(wheels)
413    }
414
415    #[instrument(skip_all, fields(version_id = version_id, subdirectory = ?subdirectory))]
416    async fn setup_build<'data>(
417        &'data self,
418        source: &'data Path,
419        subdirectory: Option<&'data Path>,
420        install_path: &'data Path,
421        version_id: Option<&'data str>,
422        dist: Option<&'data SourceDist>,
423        sources: &'data NoSources,
424        build_kind: BuildKind,
425        build_output: BuildOutput,
426        mut build_stack: BuildStack,
427    ) -> Result<SourceBuild, uv_build_frontend::Error> {
428        let dist_name = dist.map(uv_distribution_types::Name::name);
429        let dist_version = dist
430            .map(uv_distribution_types::DistributionMetadata::version_or_url)
431            .and_then(|version| match version {
432                VersionOrUrlRef::Version(version) => Some(version),
433                VersionOrUrlRef::Url(_) => None,
434            });
435
436        // Note we can only prevent builds by name for packages with names
437        // unless all builds are disabled.
438        if self
439            .build_options
440            .no_build_requirement(dist_name)
441            // We always allow editable builds
442            && !matches!(build_kind, BuildKind::Editable)
443        {
444            let err = if let Some(dist) = dist {
445                uv_build_frontend::Error::NoSourceDistBuild(dist.name().clone())
446            } else {
447                uv_build_frontend::Error::NoSourceDistBuilds
448            };
449            return Err(err);
450        }
451
452        // Push the current distribution onto the build stack, to prevent cyclic dependencies.
453        if let Some(dist) = dist {
454            build_stack.insert(dist.distribution_id());
455        }
456
457        // Get package-specific config settings if available; otherwise, use global settings.
458        let config_settings = if let Some(name) = dist_name {
459            if let Some(package_settings) = self.config_settings_package.get(name) {
460                package_settings.clone().merge(self.config_settings.clone())
461            } else {
462                self.config_settings.clone()
463            }
464        } else {
465            self.config_settings.clone()
466        };
467
468        // Get package-specific environment variables if available.
469        let mut environment_variables = self.build_extra_env_vars.clone();
470        if let Some(name) = dist_name {
471            if let Some(package_vars) = self.extra_build_variables.get(name) {
472                environment_variables.extend(
473                    package_vars
474                        .iter()
475                        .map(|(key, value)| (OsString::from(key), OsString::from(value))),
476                );
477            }
478        }
479
480        let builder = SourceBuild::setup(
481            source,
482            subdirectory,
483            install_path,
484            dist_name,
485            dist_version,
486            self.interpreter,
487            self,
488            self.source_build_context.clone(),
489            version_id,
490            self.index_locations,
491            sources.clone(),
492            self.workspace_cache(),
493            config_settings,
494            self.build_isolation,
495            self.extra_build_requires,
496            &build_stack,
497            build_kind,
498            environment_variables,
499            build_output,
500            self.client.credentials_cache(),
501        )
502        .boxed_local()
503        .await?;
504        Ok(builder)
505    }
506
507    async fn direct_build<'data>(
508        &'data self,
509        source: &'data Path,
510        subdirectory: Option<&'data Path>,
511        output_dir: &'data Path,
512        sources: NoSources,
513        build_kind: BuildKind,
514        version_id: Option<&'data str>,
515    ) -> Result<Option<DistFilename>, BuildDispatchError> {
516        let source_tree = if let Some(subdir) = subdirectory {
517            source.join(subdir)
518        } else {
519            source.to_path_buf()
520        };
521
522        // Only perform the direct build if the backend is uv in a compatible version.
523        let source_tree_str = source_tree.display().to_string();
524        let identifier = version_id.unwrap_or_else(|| &source_tree_str);
525        if !check_direct_build(&source_tree, identifier) {
526            trace!("Requirements for direct build not matched: {identifier}");
527            return Ok(None);
528        }
529
530        debug!("Performing direct build for {identifier}");
531
532        let output_dir = output_dir.to_path_buf();
533        let preview = self.preview;
534        let filename = tokio::task::spawn_blocking(move || -> Result<_> {
535            let filename = match build_kind {
536                BuildKind::Wheel => {
537                    let wheel = uv_build_backend::build_wheel(
538                        &source_tree,
539                        &output_dir,
540                        None,
541                        uv_version::version(),
542                        sources.is_none(),
543                        preview,
544                    )?;
545                    DistFilename::WheelFilename(wheel)
546                }
547                BuildKind::Sdist => {
548                    let source_dist = uv_build_backend::build_source_dist(
549                        &source_tree,
550                        &output_dir,
551                        uv_version::version(),
552                        sources.is_none(),
553                    )?;
554                    DistFilename::SourceDistFilename(source_dist)
555                }
556                BuildKind::Editable => {
557                    let wheel = uv_build_backend::build_editable(
558                        &source_tree,
559                        &output_dir,
560                        None,
561                        uv_version::version(),
562                        sources.is_none(),
563                        preview,
564                    )?;
565                    DistFilename::WheelFilename(wheel)
566                }
567            };
568            Ok(filename)
569        })
570        .await??;
571
572        Ok(Some(filename))
573    }
574}
575
576/// Shared state used during resolution and installation.
577///
578/// All elements are `Arc`s, so we can clone freely.
579#[derive(Default, Clone)]
580pub struct SharedState {
581    /// The resolved Git references.
582    git: GitResolver,
583    /// The discovered capabilities for each registry index.
584    capabilities: IndexCapabilities,
585    /// The fetched package versions and metadata.
586    index: InMemoryIndex,
587    /// The downloaded distributions.
588    in_flight: InFlight,
589    /// Build directories for any PEP 517 builds executed during resolution or installation.
590    build_arena: BuildArena<SourceBuild>,
591}
592
593impl SharedState {
594    /// Fork the [`SharedState`], creating a new in-memory index and in-flight cache.
595    ///
596    /// State that is universally applicable (like the Git resolver and index capabilities)
597    /// are retained.
598    #[must_use]
599    pub fn fork(&self) -> Self {
600        Self {
601            git: self.git.clone(),
602            capabilities: self.capabilities.clone(),
603            build_arena: self.build_arena.clone(),
604            ..Default::default()
605        }
606    }
607
608    /// Return the [`GitResolver`] used by the [`SharedState`].
609    pub fn git(&self) -> &GitResolver {
610        &self.git
611    }
612
613    /// Return the [`InMemoryIndex`] used by the [`SharedState`].
614    pub fn index(&self) -> &InMemoryIndex {
615        &self.index
616    }
617
618    /// Return the [`InFlight`] used by the [`SharedState`].
619    pub fn in_flight(&self) -> &InFlight {
620        &self.in_flight
621    }
622
623    /// Return the [`IndexCapabilities`] used by the [`SharedState`].
624    pub fn capabilities(&self) -> &IndexCapabilities {
625        &self.capabilities
626    }
627
628    /// Return the [`BuildArena`] used by the [`SharedState`].
629    pub fn build_arena(&self) -> &BuildArena<SourceBuild> {
630        &self.build_arena
631    }
632}