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::default(),
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(self.client, self, self.concurrency.downloads)
268                .with_build_stack(build_stack),
269        )?;
270        let resolution = Resolution::from(resolver.resolve().await.with_context(|| {
271            format!(
272                "No solution found when resolving: {}",
273                requirements
274                    .iter()
275                    .map(|requirement| format!("`{requirement}`"))
276                    .join(", ")
277            )
278        })?);
279        Ok(resolution)
280    }
281
282    #[instrument(
283        skip(self, resolution, venv),
284        fields(
285            resolution = resolution.distributions().map(ToString::to_string).join(", "),
286            venv = ?venv.root()
287        )
288    )]
289    async fn install<'data>(
290        &'data self,
291        resolution: &'data Resolution,
292        venv: &'data PythonEnvironment,
293        build_stack: &'data BuildStack,
294    ) -> Result<Vec<CachedDist>, BuildDispatchError> {
295        debug!(
296            "Installing in {} in {}",
297            resolution
298                .distributions()
299                .map(ToString::to_string)
300                .join(", "),
301            venv.root().display(),
302        );
303
304        // Determine the current environment markers.
305        let tags = self.interpreter.tags()?;
306
307        // Determine the set of installed packages.
308        let site_packages = SitePackages::from_environment(venv)?;
309
310        let Plan {
311            cached,
312            remote,
313            reinstalls,
314            extraneous: _,
315        } = Planner::new(resolution).build(
316            site_packages,
317            InstallationStrategy::Permissive,
318            &Reinstall::default(),
319            self.build_options,
320            self.hasher,
321            self.index_locations,
322            self.config_settings,
323            self.config_settings_package,
324            self.extra_build_requires(),
325            self.extra_build_variables,
326            self.cache(),
327            venv,
328            tags,
329        )?;
330
331        // Nothing to do.
332        if remote.is_empty() && cached.is_empty() && reinstalls.is_empty() {
333            debug!("No build requirements to install for build");
334            return Ok(vec![]);
335        }
336
337        // Verify that none of the missing distributions are already in the build stack.
338        for dist in &remote {
339            let id = dist.distribution_id();
340            if build_stack.contains(&id) {
341                return Err(BuildDispatchError::BuildFrontend(
342                    uv_build_frontend::Error::CyclicBuildDependency(dist.name().clone()).into(),
343                ));
344            }
345        }
346
347        // Download any missing distributions.
348        let wheels = if remote.is_empty() {
349            vec![]
350        } else {
351            let preparer = Preparer::new(
352                self.cache,
353                tags,
354                self.hasher,
355                self.build_options,
356                DistributionDatabase::new(self.client, self, self.concurrency.downloads)
357                    .with_build_stack(build_stack),
358            );
359
360            debug!(
361                "Downloading and building requirement{} for build: {}",
362                if remote.len() == 1 { "" } else { "s" },
363                remote.iter().map(ToString::to_string).join(", ")
364            );
365
366            preparer
367                .prepare(remote, &self.shared_state.in_flight, resolution)
368                .await?
369        };
370
371        // Remove any unnecessary packages.
372        if !reinstalls.is_empty() {
373            for dist_info in &reinstalls {
374                let summary = uv_installer::uninstall(dist_info)
375                    .await
376                    .context("Failed to uninstall build dependencies")?;
377                debug!(
378                    "Uninstalled {} ({} file{}, {} director{})",
379                    dist_info.name(),
380                    summary.file_count,
381                    if summary.file_count == 1 { "" } else { "s" },
382                    summary.dir_count,
383                    if summary.dir_count == 1 { "y" } else { "ies" },
384                );
385            }
386        }
387
388        // Install the resolved distributions.
389        let mut wheels = wheels.into_iter().chain(cached).collect::<Vec<_>>();
390        if !wheels.is_empty() {
391            debug!(
392                "Installing build requirement{}: {}",
393                if wheels.len() == 1 { "" } else { "s" },
394                wheels.iter().map(ToString::to_string).join(", ")
395            );
396            wheels = Installer::new(venv, self.preview)
397                .with_link_mode(self.link_mode)
398                .with_cache(self.cache)
399                .install(wheels)
400                .await
401                .context("Failed to install build dependencies")?;
402        }
403
404        Ok(wheels)
405    }
406
407    #[instrument(skip_all, fields(version_id = version_id, subdirectory = ?subdirectory))]
408    async fn setup_build<'data>(
409        &'data self,
410        source: &'data Path,
411        subdirectory: Option<&'data Path>,
412        install_path: &'data Path,
413        version_id: Option<&'data str>,
414        dist: Option<&'data SourceDist>,
415        sources: &'data NoSources,
416        build_kind: BuildKind,
417        build_output: BuildOutput,
418        mut build_stack: BuildStack,
419    ) -> Result<SourceBuild, uv_build_frontend::Error> {
420        let dist_name = dist.map(uv_distribution_types::Name::name);
421        let dist_version = dist
422            .map(uv_distribution_types::DistributionMetadata::version_or_url)
423            .and_then(|version| match version {
424                VersionOrUrlRef::Version(version) => Some(version),
425                VersionOrUrlRef::Url(_) => None,
426            });
427
428        // Note we can only prevent builds by name for packages with names
429        // unless all builds are disabled.
430        if self
431            .build_options
432            .no_build_requirement(dist_name)
433            // We always allow editable builds
434            && !matches!(build_kind, BuildKind::Editable)
435        {
436            let err = if let Some(dist) = dist {
437                uv_build_frontend::Error::NoSourceDistBuild(dist.name().clone())
438            } else {
439                uv_build_frontend::Error::NoSourceDistBuilds
440            };
441            return Err(err);
442        }
443
444        // Push the current distribution onto the build stack, to prevent cyclic dependencies.
445        if let Some(dist) = dist {
446            build_stack.insert(dist.distribution_id());
447        }
448
449        // Get package-specific config settings if available; otherwise, use global settings.
450        let config_settings = if let Some(name) = dist_name {
451            if let Some(package_settings) = self.config_settings_package.get(name) {
452                package_settings.clone().merge(self.config_settings.clone())
453            } else {
454                self.config_settings.clone()
455            }
456        } else {
457            self.config_settings.clone()
458        };
459
460        // Get package-specific environment variables if available.
461        let mut environment_variables = self.build_extra_env_vars.clone();
462        if let Some(name) = dist_name {
463            if let Some(package_vars) = self.extra_build_variables.get(name) {
464                environment_variables.extend(
465                    package_vars
466                        .iter()
467                        .map(|(key, value)| (OsString::from(key), OsString::from(value))),
468                );
469            }
470        }
471
472        let builder = SourceBuild::setup(
473            source,
474            subdirectory,
475            install_path,
476            dist_name,
477            dist_version,
478            self.interpreter,
479            self,
480            self.source_build_context.clone(),
481            version_id,
482            self.index_locations,
483            sources.clone(),
484            self.workspace_cache(),
485            config_settings,
486            self.build_isolation,
487            self.extra_build_requires,
488            &build_stack,
489            build_kind,
490            environment_variables,
491            build_output,
492            self.concurrency.builds,
493            self.client.credentials_cache(),
494            self.preview,
495        )
496        .boxed_local()
497        .await?;
498        Ok(builder)
499    }
500
501    async fn direct_build<'data>(
502        &'data self,
503        source: &'data Path,
504        subdirectory: Option<&'data Path>,
505        output_dir: &'data Path,
506        sources: NoSources,
507        build_kind: BuildKind,
508        version_id: Option<&'data str>,
509    ) -> Result<Option<DistFilename>, BuildDispatchError> {
510        let source_tree = if let Some(subdir) = subdirectory {
511            source.join(subdir)
512        } else {
513            source.to_path_buf()
514        };
515
516        // Only perform the direct build if the backend is uv in a compatible version.
517        let source_tree_str = source_tree.display().to_string();
518        let identifier = version_id.unwrap_or_else(|| &source_tree_str);
519        if !check_direct_build(&source_tree, identifier) {
520            trace!("Requirements for direct build not matched: {identifier}");
521            return Ok(None);
522        }
523
524        debug!("Performing direct build for {identifier}");
525
526        let output_dir = output_dir.to_path_buf();
527        let preview = self.preview;
528        let filename = tokio::task::spawn_blocking(move || -> Result<_> {
529            let filename = match build_kind {
530                BuildKind::Wheel => {
531                    let wheel = uv_build_backend::build_wheel(
532                        &source_tree,
533                        &output_dir,
534                        None,
535                        uv_version::version(),
536                        sources.is_none(),
537                        preview,
538                    )?;
539                    DistFilename::WheelFilename(wheel)
540                }
541                BuildKind::Sdist => {
542                    let source_dist = uv_build_backend::build_source_dist(
543                        &source_tree,
544                        &output_dir,
545                        uv_version::version(),
546                        sources.is_none(),
547                    )?;
548                    DistFilename::SourceDistFilename(source_dist)
549                }
550                BuildKind::Editable => {
551                    let wheel = uv_build_backend::build_editable(
552                        &source_tree,
553                        &output_dir,
554                        None,
555                        uv_version::version(),
556                        sources.is_none(),
557                        preview,
558                    )?;
559                    DistFilename::WheelFilename(wheel)
560                }
561            };
562            Ok(filename)
563        })
564        .await??;
565
566        Ok(Some(filename))
567    }
568}
569
570/// Shared state used during resolution and installation.
571///
572/// All elements are `Arc`s, so we can clone freely.
573#[derive(Default, Clone)]
574pub struct SharedState {
575    /// The resolved Git references.
576    git: GitResolver,
577    /// The discovered capabilities for each registry index.
578    capabilities: IndexCapabilities,
579    /// The fetched package versions and metadata.
580    index: InMemoryIndex,
581    /// The downloaded distributions.
582    in_flight: InFlight,
583    /// Build directories for any PEP 517 builds executed during resolution or installation.
584    build_arena: BuildArena<SourceBuild>,
585}
586
587impl SharedState {
588    /// Fork the [`SharedState`], creating a new in-memory index and in-flight cache.
589    ///
590    /// State that is universally applicable (like the Git resolver and index capabilities)
591    /// are retained.
592    #[must_use]
593    pub fn fork(&self) -> Self {
594        Self {
595            git: self.git.clone(),
596            capabilities: self.capabilities.clone(),
597            build_arena: self.build_arena.clone(),
598            ..Default::default()
599        }
600    }
601
602    /// Return the [`GitResolver`] used by the [`SharedState`].
603    pub fn git(&self) -> &GitResolver {
604        &self.git
605    }
606
607    /// Return the [`InMemoryIndex`] used by the [`SharedState`].
608    pub fn index(&self) -> &InMemoryIndex {
609        &self.index
610    }
611
612    /// Return the [`InFlight`] used by the [`SharedState`].
613    pub fn in_flight(&self) -> &InFlight {
614        &self.in_flight
615    }
616
617    /// Return the [`IndexCapabilities`] used by the [`SharedState`].
618    pub fn capabilities(&self) -> &IndexCapabilities {
619        &self.capabilities
620    }
621
622    /// Return the [`BuildArena`] used by the [`SharedState`].
623    pub fn build_arena(&self) -> &BuildArena<SourceBuild> {
624        &self.build_arena
625    }
626}