1use 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
77pub 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 #[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 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 let tags = self.interpreter.tags()?;
306
307 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 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 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 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 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 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 if self
431 .build_options
432 .no_build_requirement(dist_name)
433 && !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 if let Some(dist) = dist {
446 build_stack.insert(dist.distribution_id());
447 }
448
449 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 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 )
495 .boxed_local()
496 .await?;
497 Ok(builder)
498 }
499
500 async fn direct_build<'data>(
501 &'data self,
502 source: &'data Path,
503 subdirectory: Option<&'data Path>,
504 output_dir: &'data Path,
505 sources: NoSources,
506 build_kind: BuildKind,
507 version_id: Option<&'data str>,
508 ) -> Result<Option<DistFilename>, BuildDispatchError> {
509 let source_tree = if let Some(subdir) = subdirectory {
510 source.join(subdir)
511 } else {
512 source.to_path_buf()
513 };
514
515 let source_tree_str = source_tree.display().to_string();
517 let identifier = version_id.unwrap_or_else(|| &source_tree_str);
518 if !check_direct_build(&source_tree, identifier) {
519 trace!("Requirements for direct build not matched: {identifier}");
520 return Ok(None);
521 }
522
523 debug!("Performing direct build for {identifier}");
524
525 let output_dir = output_dir.to_path_buf();
526 let preview = self.preview;
527 let filename = tokio::task::spawn_blocking(move || -> Result<_> {
528 let filename = match build_kind {
529 BuildKind::Wheel => {
530 let wheel = uv_build_backend::build_wheel(
531 &source_tree,
532 &output_dir,
533 None,
534 uv_version::version(),
535 sources.is_none(),
536 preview,
537 )?;
538 DistFilename::WheelFilename(wheel)
539 }
540 BuildKind::Sdist => {
541 let source_dist = uv_build_backend::build_source_dist(
542 &source_tree,
543 &output_dir,
544 uv_version::version(),
545 sources.is_none(),
546 )?;
547 DistFilename::SourceDistFilename(source_dist)
548 }
549 BuildKind::Editable => {
550 let wheel = uv_build_backend::build_editable(
551 &source_tree,
552 &output_dir,
553 None,
554 uv_version::version(),
555 sources.is_none(),
556 preview,
557 )?;
558 DistFilename::WheelFilename(wheel)
559 }
560 };
561 Ok(filename)
562 })
563 .await??;
564
565 Ok(Some(filename))
566 }
567}
568
569#[derive(Default, Clone)]
573pub struct SharedState {
574 git: GitResolver,
576 capabilities: IndexCapabilities,
578 index: InMemoryIndex,
580 in_flight: InFlight,
582 build_arena: BuildArena<SourceBuild>,
584}
585
586impl SharedState {
587 #[must_use]
592 pub fn fork(&self) -> Self {
593 Self {
594 git: self.git.clone(),
595 capabilities: self.capabilities.clone(),
596 build_arena: self.build_arena.clone(),
597 ..Default::default()
598 }
599 }
600
601 pub fn git(&self) -> &GitResolver {
603 &self.git
604 }
605
606 pub fn index(&self) -> &InMemoryIndex {
608 &self.index
609 }
610
611 pub fn in_flight(&self) -> &InFlight {
613 &self.in_flight
614 }
615
616 pub fn capabilities(&self) -> &IndexCapabilities {
618 &self.capabilities
619 }
620
621 pub fn build_arena(&self) -> &BuildArena<SourceBuild> {
623 &self.build_arena
624 }
625}