Skip to main content

hydro_deploy/rust_crate/
build.rs

1use std::error::Error;
2use std::fmt::Display;
3use std::io::BufRead;
4use std::path::{Path, PathBuf};
5use std::process::{Command, ExitStatus, Stdio};
6use std::sync::OnceLock;
7
8use cargo_metadata::diagnostic::Diagnostic;
9use memo_map::MemoMap;
10use tokio::sync::OnceCell;
11
12use crate::HostTargetType;
13use crate::progress::ProgressTracker;
14
15/// Build parameters for [`build_crate_memoized`].
16#[derive(PartialEq, Eq, Hash, Clone)]
17pub struct BuildParams {
18    /// The working directory for the build, where the `cargo build` command will be run. Crate root.
19    /// [`Self::new`] canonicalizes this path.
20    src: PathBuf,
21    /// The workspace root encompassing the build, which may be a parent of `src` in a multi-crate
22    /// workspace.
23    workspace_root: PathBuf,
24    /// `--bin` binary name parameter.
25    bin: Option<String>,
26    /// `--example` parameter.
27    example: Option<String>,
28    /// `--profile` parameter.
29    profile: Option<String>,
30    rustflags: Option<String>,
31    target_dir: Option<PathBuf>,
32    // Environment variables available during build
33    build_env: Vec<(String, String)>,
34    no_default_features: bool,
35    /// `--target <linux>` if cross-compiling for linux ([`HostTargetType::Linux`]).
36    target_type: HostTargetType,
37    /// If set, the build uses dynamic linking: `src` is a generated trybuild `dylib-examples`
38    /// crate whose examples link against the trybuild dylib with this cargo package name.
39    dylib_package: Option<String>,
40    /// `--features` flags, will be comma-delimited.
41    features: Option<Vec<String>>,
42    /// `--config` flag
43    config: Vec<String>,
44}
45impl BuildParams {
46    /// Creates a new `BuildParams` and canonicalizes the `src` path.
47    #[expect(clippy::too_many_arguments, reason = "internal code")]
48    pub fn new(
49        src: impl AsRef<Path>,
50        workspace_root: impl AsRef<Path>,
51        bin: Option<String>,
52        example: Option<String>,
53        profile: Option<String>,
54        rustflags: Option<String>,
55        target_dir: Option<PathBuf>,
56        build_env: Vec<(String, String)>,
57        no_default_features: bool,
58        target_type: HostTargetType,
59        dylib_package: Option<String>,
60        features: Option<Vec<String>>,
61        config: Vec<String>,
62    ) -> Self {
63        // `fs::canonicalize` prepends windows paths with the `r"\\?\"`
64        // https://stackoverflow.com/questions/21194530/what-does-mean-when-prepended-to-a-file-path
65        // However, this breaks the `include!(concat!(env!("OUT_DIR"), "/my/forward/slash/path.rs"))`
66        // Rust codegen pattern on windows. To help mitigate this happening in third party crates, we
67        // instead use `dunce::canonicalize` which is the same as `fs::canonicalize` but avoids the
68        // `\\?\` prefix when possible.
69        let src = dunce::canonicalize(src.as_ref()).unwrap_or_else(|e| {
70            panic!(
71                "Failed to canonicalize path `{}` for build: {e}.",
72                src.as_ref().display(),
73            )
74        });
75
76        let workspace_root = dunce::canonicalize(workspace_root.as_ref()).unwrap_or_else(|e| {
77            panic!(
78                "Failed to canonicalize path `{}` for build: {e}.",
79                workspace_root.as_ref().display(),
80            )
81        });
82
83        BuildParams {
84            src,
85            workspace_root,
86            bin,
87            example,
88            profile,
89            rustflags,
90            target_dir,
91            build_env,
92            no_default_features,
93            target_type,
94            dylib_package,
95            features,
96            config,
97        }
98    }
99}
100
101/// Information about a built crate. See [`build_crate_memoized`].
102pub struct BuildOutput {
103    /// The binary contents as a byte array.
104    pub bin_data: Vec<u8>,
105    /// The path to the binary file. [`Self::bin_data`] has a copy of the content.
106    pub bin_path: PathBuf,
107    /// Directories to put on the dynamic library search path when running the binary,
108    /// containing any necessary dylibs (empty for statically linked builds).
109    pub shared_library_paths: Vec<PathBuf>,
110}
111impl BuildOutput {
112    /// A unique ID for the binary, based its contents.
113    pub fn unique_id(&self) -> impl use<> + Display {
114        blake3::hash(&self.bin_data).to_hex()
115    }
116}
117
118/// Build memoization cache.
119static BUILDS: OnceLock<MemoMap<BuildParams, OnceCell<BuildOutput>>> = OnceLock::new();
120
121pub async fn build_crate_memoized(params: BuildParams) -> Result<&'static BuildOutput, BuildError> {
122    BUILDS
123        .get_or_init(MemoMap::new)
124        .get_or_insert(&params, Default::default)
125        .get_or_try_init(move || {
126            ProgressTracker::rich_leaf("build", move |set_msg| async move {
127                tokio::task::spawn_blocking(move || {
128                    let base_target_dir = params
129                        .target_dir
130                        .clone()
131                        .unwrap_or_else(|| params.src.join("target"));
132                    let job_name = params
133                        .bin
134                        .as_deref()
135                        .or(params.example.as_deref())
136                        .unwrap_or("default");
137
138                    // The `--target` passed to cargo, if any. Local builds pass none; cargo then
139                    // applies `CARGO_BUILD_TARGET` from the environment, if set.
140                    let explicit_target = match params.target_type {
141                        HostTargetType::Local => None,
142                        HostTargetType::Linux(crate::LinuxCompileType::Glibc) => Some("x86_64-unknown-linux-gnu"),
143                        HostTargetType::Linux(crate::LinuxCompileType::Musl) => Some("x86_64-unknown-linux-musl"),
144                    };
145                    let target_triple = explicit_target
146                        .map(str::to_owned)
147                        .or_else(|| std::env::var("CARGO_BUILD_TARGET").ok());
148
149                    // The target-dir layers this build uses (see `ArtifactDirs`).
150                    let dirs = hydro_concurrent_cargo::ArtifactDirs::new(
151                        hydro_concurrent_cargo::profile_dir_name(params.profile.as_deref()),
152                        target_triple.as_deref(),
153                    );
154
155                    // Only use prebuild + per-job target dirs for dylib mode.
156                    // Without dylib, build directly into the base target dir.
157                    let (per_job_target_dir, _prebuild_guard, _cargo_lock) = if params.dylib_package.is_some() {
158                        let jobs_dir = base_target_dir.join("jobs");
159                        let per_job = hydro_concurrent_cargo::setup_job_dir(&jobs_dir, job_name, &base_target_dir, &dirs);
160
161                        let features = params.features.clone().unwrap_or_default();
162                        let staged_paths = vec![
163                            params.src.join("src").join("__staged.rs"),
164                            params.src.join("Cargo.lock"),
165                            std::env::current_exe().unwrap(),
166                        ];
167
168                        let src = params.src.clone();
169                        let profile = params.profile.clone();
170                        let no_default_features = params.no_default_features;
171                        let features_for_closure = features.clone();
172                        let config = params.config.clone();
173                        let rustflags = params.rustflags.clone();
174                        let build_env = params.build_env.clone();
175
176                        // In dylib mode `src` is the generated project's `dylib-examples` crate.
177                        let project_dir = params.src.parent().unwrap();
178                        let (prebuild_guard, cargo_lock) = hydro_concurrent_cargo::run_prebuild(
179                            &base_target_dir,
180                            &dirs,
181                            project_dir.file_name().unwrap().to_str().unwrap(),
182                            &features,
183                            params.rustflags.as_deref().unwrap_or_default(),
184                            &staged_paths,
185                            |prebuild_target| {
186                                set_msg("building dependencies".to_owned());
187                                hydro_concurrent_cargo::set_dylib_lib_name(
188                                    project_dir,
189                                    params.rustflags.as_deref().unwrap_or_default(),
190                                );
191
192                                // Prebuild the dylib-examples lib (`src` in dylib mode), which
193                                // transitively builds the trybuild dylib *as a dependency*.
194                                // This matters: cargo passes `-C prefer-dynamic` to dylib
195                                // crates when they are built as dependencies (linking libstd
196                                // dynamically), but *not* when they are the primary build
197                                // target — and the two variants share a cargo fingerprint. If
198                                // the dylib were prebuilt as a primary target, the cached
199                                // variant would statically link libstd and the final example
200                                // builds would fail to link ("cannot satisfy dependencies so
201                                // `std` only shows up once").
202                                let mut lib_cmd = Command::new("cargo");
203                                lib_cmd.current_dir(&src);
204                                lib_cmd.args(["build", "--locked", "--lib"]);
205                                if let Some(profile) = profile.as_ref() {
206                                    lib_cmd.args(["--profile", profile]);
207                                }
208                                if let Some(target) = explicit_target {
209                                    lib_cmd.args(["--target", target]);
210                                }
211                                if no_default_features {
212                                    lib_cmd.arg("--no-default-features");
213                                }
214                                if !features_for_closure.is_empty() {
215                                    lib_cmd.args(["--features", &features_for_closure.join(",")]);
216                                }
217                                for c in &config {
218                                    lib_cmd.args(["--config", c]);
219                                }
220                                lib_cmd.args(["--target-dir", prebuild_target.to_str().unwrap()]);
221                                if let Some(rustflags) = rustflags.as_ref() {
222                                    lib_cmd.env("RUSTFLAGS", rustflags);
223                                }
224                                for (k, v) in &build_env {
225                                    lib_cmd.env(k, v);
226                                }
227                                let lib_status = lib_cmd
228                                    .stdin(Stdio::null())
229                                    .status()
230                                    .unwrap();
231                                assert!(lib_status.success(), "dep prebuild failed")
232                            },
233                        );
234
235                        (per_job, Some(prebuild_guard), Some(cargo_lock))
236                    } else {
237                        (base_target_dir.clone(), None, None)
238                    };
239
240                    hydro_concurrent_cargo::log_build_event(&base_target_dir, "deploy: starting final build");
241
242                    // Populate per-job build/ dir. Hold guard for entire final build.
243                    let _job_build_guard = if params.dylib_package.is_some() {
244                        Some(hydro_concurrent_cargo::populate_job_build_dir(&per_job_target_dir, &base_target_dir, &dirs))
245                    } else {
246                        None
247                    };
248
249                    let mut command = Command::new("cargo");
250                    command.args(["build", if params.dylib_package.is_some() { "--frozen" } else { "--locked" }]);
251
252                    if let Some(profile) = params.profile.as_ref() {
253                        command.args(["--profile", profile]);
254                    }
255
256                    if let Some(bin) = params.bin.as_ref() {
257                        command.args(["--bin", bin]);
258                    }
259
260                    if let Some(example) = params.example.as_ref() {
261                        command.args(["--example", example]);
262                    }
263
264                    if let Some(target) = explicit_target {
265                        command.args(["--target", target]);
266                    }
267
268                    if params.no_default_features {
269                        command.arg("--no-default-features");
270                    }
271
272                    if let Some(features) = params.features {
273                        command.args(["--features", &features.join(",")]);
274                    }
275
276                    for config in &params.config {
277                        command.args(["--config", config]);
278                    }
279
280                    command.arg("--message-format=json-diagnostic-rendered-ansi");
281                    command.args(["--target-dir", per_job_target_dir.to_str().unwrap()]);
282
283                    if let Some(rustflags) = params.rustflags.as_ref() {
284                        command.env("RUSTFLAGS", rustflags);
285                    }
286
287                    for (k, v) in params.build_env {
288                        command.env(k, v);
289                    }
290
291                    let mut spawned = command
292                        .current_dir(&params.src)
293                        .stdout(Stdio::piped())
294                        .stderr(Stdio::piped())
295                        .stdin(Stdio::null())
296                        .spawn()
297                        .unwrap();
298
299                    let reader = std::io::BufReader::new(spawned.stdout.take().unwrap());
300                    let stderr_reader = std::io::BufReader::new(spawned.stderr.take().unwrap());
301
302                    let stderr_worker = std::thread::spawn(move || {
303                        let mut stderr_lines = Vec::new();
304                        for line in stderr_reader.lines() {
305                            let Ok(line) = line else {
306                                break;
307                            };
308                            set_msg(line.clone());
309                            stderr_lines.push(line);
310                        }
311                        stderr_lines
312                    });
313
314                    let mut diagnostics = Vec::new();
315                    let mut text_lines = Vec::new();
316                    for message in cargo_metadata::Message::parse_stream(reader) {
317                        match message.unwrap() {
318                            cargo_metadata::Message::CompilerArtifact(artifact) => {
319                                let is_output = if params.example.is_some() {
320                                    artifact.target.kind.iter().any(|k| "example" == k)
321                                } else {
322                                    artifact.target.kind.iter().any(|k| "bin" == k)
323                                };
324
325                                if is_output {
326                                    let path = artifact.executable.unwrap();
327                                    let path_buf: PathBuf = path.clone().into();
328                                    let path = path.into_string();
329                                    let data = std::fs::read(path).unwrap();
330                                    let exit_status = spawned.wait().unwrap();
331
332                                    let stderr_lines = stderr_worker.join().unwrap();
333
334                                    // Check for unexpected recompilations (only in dylib mode with prebuild).
335                                    if params.dylib_package.is_some() {
336                                        for line in &stderr_lines {
337                                            if line.contains("Compiling") {
338                                                assert!(
339                                                    line.contains("dylib-examples")
340                                                        || line.contains(job_name),
341                                                    "unexpected recompilation in deploy final build: {line}\nfull stderr:\n{}",
342                                                    stderr_lines.join("\n")
343                                                );
344                                            }
345                                        }
346                                    }
347
348                                    assert!(exit_status.success(), "deploy final build failed:\n{}", stderr_lines.join("\n"));
349
350                                    return Ok(BuildOutput {
351                                        bin_data: data,
352                                        bin_path: path_buf,
353                                        shared_library_paths: if let Some(dylib_package) = &params.dylib_package {
354                                            hydro_concurrent_cargo::dylib_search_dirs(
355                                                dylib_package,
356                                                &per_job_target_dir.join(&dirs.target),
357                                                &base_target_dir.join(&dirs.target),
358                                            )
359                                        } else {
360                                            Vec::new()
361                                        },
362                                    });
363                                }
364                            }
365                            cargo_metadata::Message::CompilerMessage(mut msg) => {
366                                // Update the path displayed to enable clicking in IDE.
367                                // TODO(mingwei): deduplicate code with hydro_lang sim/graph.rs
368                                if let Some(rendered) = msg.message.rendered.as_mut() {
369                                    let file_names = msg
370                                        .message
371                                        .spans
372                                        .iter()
373                                        .map(|s| &s.file_name)
374                                        .collect::<std::collections::BTreeSet<_>>();
375                                    for file_name in file_names {
376                                        if Path::new(file_name).is_relative() {
377                                            *rendered = rendered.replace(
378                                                file_name,
379                                                &format!(
380                                                    "(full path) {}/{file_name}",
381                                                    params.workspace_root.display(),
382                                                ),
383                                            )
384                                        }
385                                    }
386                                }
387                                ProgressTracker::println(msg.message.to_string());
388                                diagnostics.push(msg.message);
389                            }
390                            cargo_metadata::Message::TextLine(line) => {
391                                ProgressTracker::println(&line);
392                                text_lines.push(line);
393                            }
394                            cargo_metadata::Message::BuildFinished(_) => {}
395                            cargo_metadata::Message::BuildScriptExecuted(_) => {}
396                            msg => panic!("Unexpected message type: {:?}", msg),
397                        }
398                    }
399
400                    let exit_status = spawned.wait().unwrap();
401                    if exit_status.success() {
402                        Err(BuildError::NoBinaryEmitted)
403                    } else {
404                        let stderr_lines = stderr_worker
405                            .join()
406                            .expect("Stderr worker unexpectedly panicked.");
407
408                        Err(BuildError::FailedToBuildCrate {
409                            exit_status,
410                            diagnostics,
411                            text_lines,
412                            stderr_lines,
413                        })
414                    }
415                })
416                .await
417                .map_err(|_| BuildError::TokioJoinError)?
418            })
419        })
420        .await
421}
422
423#[derive(Clone, Debug)]
424pub enum BuildError {
425    FailedToBuildCrate {
426        exit_status: ExitStatus,
427        diagnostics: Vec<Diagnostic>,
428        text_lines: Vec<String>,
429        stderr_lines: Vec<String>,
430    },
431    TokioJoinError,
432    NoBinaryEmitted,
433}
434
435impl Display for BuildError {
436    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
437        match self {
438            Self::FailedToBuildCrate {
439                exit_status,
440                diagnostics,
441                text_lines,
442                stderr_lines,
443            } => {
444                writeln!(f, "Failed to build crate ({})", exit_status)?;
445                writeln!(f, "Diagnostics ({}):", diagnostics.len())?;
446                for diagnostic in diagnostics {
447                    write!(f, "{}", diagnostic)?;
448                }
449                writeln!(f, "Text output ({} lines):", text_lines.len())?;
450                for line in text_lines {
451                    writeln!(f, "{}", line)?;
452                }
453                writeln!(f, "Stderr output ({} lines):", stderr_lines.len())?;
454                for line in stderr_lines {
455                    writeln!(f, "{}", line)?;
456                }
457            }
458            Self::TokioJoinError => {
459                write!(f, "Failed to spawn tokio blocking task.")?;
460            }
461            Self::NoBinaryEmitted => {
462                write!(f, "`cargo build` succeeded but no binary was emitted.")?;
463            }
464        }
465        Ok(())
466    }
467}
468
469impl Error for BuildError {}