rialo-build-lib 0.10.1

Shared library for Rialo program building logic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Cargo build-script integration for Rialo PolkaVM artifact crates.
//!
//! This module exists for crates that need a local Rialo program artifact as
//! part of an otherwise normal Cargo build. On stable Cargo, the practical way
//! to do that is to use `build.rs` to compile a sibling program for the Rialo
//! custom RISC-V target, post-process its ELF into a `.polkavm` blob, and then
//! make that blob available to the current crate.
//!
//! # Problem
//!
//! Simply put, we want to express in the build system that the current host
//! build also depends on a sibling package's target-specific artifact.
//!
//! We want Cargo to:
//!
//! - build the current crate for the host as normal
//! - also build a sibling Cargo package for the Rialo custom RISC-V target
//! - then make the produced artifact available to the current build
//!
//! Stable Cargo *can* build multiple requested targets in one invocation, but
//! that is not enough here. The missing piece is a first-class dependency edge
//! for "this host crate also needs that sibling package's target-specific
//! artifact". If Cargo had that on stable, surfacing the result through a
//! host-built Rust library would be optional rather than part of the
//! workaround.
//!
//! On stable Cargo, that graph is still awkward to express natively:
//!
//! - artifact dependencies / binary dependencies are nightly-only behind
//!   `-Z bindeps`; see Cargo's unstable
//!   [`artifact-dependencies`](https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#artifact-dependencies)
//!   docs and [RFC 3028](https://rust-lang.github.io/rfcs/3028-cargo-binary-dependencies.html)
//! - forcing a different target for one package inside the graph is also
//!   unstable via
//!   [`per-package-target`](https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#per-package-target),
//!   and its tracking issue explicitly calls out rough edges around dependency
//!   interaction; see [cargo#9406](https://github.com/rust-lang/cargo/issues/9406)
//! - build scripts still do not receive a resolved target directory directly
//!   from Cargo; see Cargo's documented build-script environment variables and
//!   [cargo#9661](https://github.com/rust-lang/cargo/issues/9661)
//!
//! Until Cargo has that on stable, a `build.rs` bridge is the pragmatic
//! option. That is also an explicitly recognized workaround in
//! [RFC 3028](https://rust-lang.github.io/rfcs/3028-cargo-binary-dependencies.html),
//! which proposes artifact dependencies as the longer-term replacement for this
//! style of nested-Cargo integration. In that model, `build.rs` would likely
//! shrink to the Rialo-specific ELF -> `.polkavm` postprocessing step.
//!
//! # Scope
//!
//! This module adapts the shared compilation logic in [`crate::compilation`] to
//! Cargo's `build.rs` environment. It owns the Cargo-facing mechanics:
//! locating the sibling program relative to the current crate, emitting Cargo
//! build-script directives, deriving rerun inputs from the local Cargo package
//! graph via `cargo metadata`, and exposing the produced artifact through
//! `OUT_DIR` and `RIALO_BUILD_ARTIFACT_FILE`.
//!
//! The actual Rialo program compilation policy stays in
//! [`crate::compilation`]: toolchain resolution, target-dir resolution, builder
//! selection, nested Cargo environment sanitization, and the mechanics of
//! producing the program artifact.
//!
//! This module is for artifact crates that need to build one local Cargo
//! program into one PolkaVM blob using the currently supported Rialo custom
//! RISC-V path.
//!
//! # Change Detection
//!
//! Stable Cargo does not let us declare the sibling program crate as a native
//! artifact dependency, so build-script reruns must be driven by explicit
//! `cargo:rerun-if-*` directives.
//!
//! Today this module uses a broad but correct approximation:
//!
//! - watch `CARGO_TARGET_DIR`
//! - watch `RIALO_RUST_TOOLCHAIN_VERSION`
//! - watch the local Cargo package graph rooted at the source program
//! - watch the resolved `.rialo-toolchain` file when that file selected the
//!   toolchain version
//!
//! The package-graph watch set is intentionally broader than an exact compiler
//! dep-info file. That tradeoff keeps the implementation simple and reliable on
//! stable Cargo. If we later want narrower reruns, the likely refinement is to
//! consume the nested build's generated dep-info instead of broadening this API.

use std::{
    collections::{BTreeSet, HashMap, HashSet},
    env, fs,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use cargo_metadata::{Metadata, Package, PackageId};

use crate::compilation;

const ARTIFACT_ENV_VAR: &str = "RIALO_BUILD_ARTIFACT_FILE";

/// Create a build-script helper for compiling a PolkaVM artifact from a local
/// Cargo program crate.
pub fn setup_polkavm_artifact_build() -> PolkaVmArtifactBuild {
    PolkaVmArtifactBuild::default()
}

/// Thin build-script adapter over the shared compilation path.
#[derive(Debug, Default)]
pub struct PolkaVmArtifactBuild {
    program_path: Option<PathBuf>,
    toolchain_version_override: Option<String>,
}

/// Result of running a build-script artifact build.
#[derive(Debug)]
pub struct BuildScriptResult {
    /// Path to the compiled artifact in `OUT_DIR`.
    pub artifact_path: PathBuf,
}

impl PolkaVmArtifactBuild {
    /// Set the source program path relative to the artifact crate.
    pub fn program_path(mut self, program_path: impl Into<PathBuf>) -> Self {
        self.program_path = Some(program_path.into());
        self
    }

    /// Set an explicit Rialo Rust toolchain version override.
    pub fn toolchain_version(mut self, version: impl Into<String>) -> Self {
        self.toolchain_version_override = Some(version.into());
        self
    }

    /// Compile the configured program and emit Cargo build-script directives.
    pub fn run(self) -> Result<BuildScriptResult> {
        emit_rerun_if_env_changed("CARGO_TARGET_DIR");
        emit_rerun_if_env_changed("RIALO_RUST_TOOLCHAIN_VERSION");

        let manifest_dir = env_path("CARGO_MANIFEST_DIR")?;
        let out_dir = env_path("OUT_DIR")?;
        let relative_program_path = self
            .program_path
            .context("PolkaVM artifact build requires a program path")?;
        let program_path = manifest_dir.join(relative_program_path);

        emit_rerun_if_changed_for_local_package_graph(&program_path)?;

        // Resolve the nested build's target directory. When running inside a
        // build script, the outer cargo holds `target/{profile}/.cargo-lock`
        // for the entire build. If the nested cargo targets the same profile
        // directory, it deadlocks waiting for that lock.
        //
        // To avoid this, we place the nested build in a `rialo-build/`
        // subdirectory under the resolved target root. This gives the nested
        // cargo its own lock file while keeping artifacts under `target/` so
        // CI caching picks them up. Registry crates in `~/.cargo/registry`
        // are still shared.
        let base_target_dir = crate::resolve_target_dir_for_program(&program_path, None)?;
        let target_dir_override = base_target_dir.join("rialo-build");

        let result = compilation::compile_program(&compilation::CompileProgramRequest {
            program_path: program_path.clone(),
            output_dir: out_dir.clone(),
            target_dir_override: Some(target_dir_override),
            toolchain_version_override: self.toolchain_version_override,
        })?;
        if let Some(source_path) = result.resolved_toolchain.source_path.as_deref() {
            emit_rerun_if_changed(source_path);
        }

        let artifact_file_name = result
            .program_binary
            .file_name()
            .context("Compiled program artifact has no file name")?;
        let artifact_path = out_dir.join(artifact_file_name);

        fs::copy(&result.program_binary, &artifact_path).with_context(|| {
            format!(
                "Failed to copy {} to {}",
                result.program_binary.display(),
                artifact_path.display()
            )
        })?;

        // Also write to a stable, discoverable path under the program's own
        // `target/rialo-build/<package>-riscv/` so external tools (e.g.
        // `rialo client program deploy-venus`) can find the binary without
        // parsing Cargo's fingerprint-hashed OUT_DIR. Mirrors the
        // `<package>-wasm/rex_components.bin` convention written by the
        // Venus rex build helper.
        write_stable_polkavm_artifact(
            &program_path,
            &result.package_name,
            &result.program_binary,
            artifact_file_name,
        )?;

        println!(
            "cargo:rustc-env={ARTIFACT_ENV_VAR}={}",
            artifact_file_name.to_string_lossy()
        );

        Ok(BuildScriptResult { artifact_path })
    }
}

/// Write the compiled `.polkavm` to `<program-dir>/target/rialo-build/<package>-riscv/`.
///
/// Uses tempfile + rename so a partial write can never leave a truncated
/// payload at the destination. The CLI's `program deploy-venus` reads this
/// path directly, so atomicity matters.
fn write_stable_polkavm_artifact(
    program_path: &Path,
    package_name: &str,
    source_binary: &Path,
    artifact_file_name: &std::ffi::OsStr,
) -> Result<()> {
    let stable_dir = program_path
        .join("target")
        .join("rialo-build")
        .join(format!("{package_name}-riscv"));
    fs::create_dir_all(&stable_dir).with_context(|| {
        format!(
            "Failed to create stable artifact directory {}",
            stable_dir.display()
        )
    })?;
    let stable_path = stable_dir.join(artifact_file_name);
    let tmp_path = stable_dir.join(format!("{}.tmp", artifact_file_name.to_string_lossy()));
    // Best-effort cleanup of any leftover tempfile from a previous failed write.
    let _ = fs::remove_file(&tmp_path);
    fs::copy(source_binary, &tmp_path).with_context(|| {
        format!(
            "Failed to copy {} to {}",
            source_binary.display(),
            tmp_path.display()
        )
    })?;
    fs::rename(&tmp_path, &stable_path).with_context(|| {
        format!(
            "Failed to rename {} to {}",
            tmp_path.display(),
            stable_path.display()
        )
    })?;
    // Plain stdout: this is the success path and shouldn't surface as a yellow
    // `warning:` on every successful build. `cargo:warning=` is reserved for
    // stale-scrub and failure-path messages that the user actually needs to see.
    println!("Wrote stable PolkaVM artifact to {}", stable_path.display());
    Ok(())
}

fn env_path(var_name: &str) -> Result<PathBuf> {
    let value = env::var_os(var_name)
        .with_context(|| format!("{var_name} is not available in this build script"))?;
    Ok(PathBuf::from(value))
}

fn emit_rerun_if_env_changed(var_name: &str) {
    println!("cargo:rerun-if-env-changed={var_name}");
}

fn emit_rerun_if_changed(path: &Path) {
    println!("cargo:rerun-if-changed={}", path.display());
}

/// Emit `rerun-if-changed` directives for the local Cargo package graph rooted
/// at `program_path`.
fn emit_rerun_if_changed_for_local_package_graph(program_path: &Path) -> Result<()> {
    for path in local_package_graph_watch_paths(program_path)? {
        emit_rerun_if_changed(&path);
    }
    Ok(())
}

fn local_package_graph_watch_paths(program_path: &Path) -> Result<Vec<PathBuf>> {
    let metadata = cargo_metadata::MetadataCommand::new()
        .manifest_path(program_path.join("Cargo.toml"))
        .exec()
        .with_context(|| {
            format!(
                "Failed to load Cargo metadata for {}",
                program_path.display()
            )
        })?;

    let root_package = root_package(&metadata, program_path)?;
    let local_package_ids = local_package_closure(&metadata, &root_package.id)?;
    let mut watched_paths = BTreeSet::new();

    watched_paths.insert(metadata.workspace_root.as_std_path().join("Cargo.toml"));

    let lockfile = metadata.workspace_root.as_std_path().join("Cargo.lock");
    if lockfile.exists() {
        watched_paths.insert(lockfile);
    }

    for package in metadata
        .packages
        .iter()
        .filter(|package| package.source.is_none() && local_package_ids.contains(&package.id))
    {
        watched_paths.insert(package.manifest_path.as_std_path().to_path_buf());

        let package_dir = package
            .manifest_path
            .as_std_path()
            .parent()
            .context("Package manifest path has no parent directory")?;

        let src_dir = package_dir.join("src");
        if src_dir.exists() {
            watched_paths.insert(src_dir);
        }

        let build_script = package_dir.join("build.rs");
        if build_script.exists() {
            watched_paths.insert(build_script);
        }
    }

    Ok(watched_paths.into_iter().collect())
}

fn root_package<'a>(metadata: &'a Metadata, program_path: &Path) -> Result<&'a Package> {
    let manifest_path = program_path
        .join("Cargo.toml")
        .canonicalize()
        .with_context(|| format!("Failed to canonicalize {}", program_path.display()))?;

    metadata
        .packages
        .iter()
        .find(|package| {
            package
                .manifest_path
                .as_std_path()
                .canonicalize()
                .ok()
                .as_ref()
                == Some(&manifest_path)
        })
        .with_context(|| format!("Failed to locate package for {}", program_path.display()))
}

fn local_package_closure(metadata: &Metadata, root_id: &PackageId) -> Result<HashSet<PackageId>> {
    let resolve = metadata
        .resolve
        .as_ref()
        .context("Cargo metadata did not include a resolved package graph")?;

    let edges: HashMap<&PackageId, Vec<&PackageId>> = resolve
        .nodes
        .iter()
        .map(|node| (&node.id, node.deps.iter().map(|dep| &dep.pkg).collect()))
        .collect();

    let package_lookup: HashMap<&PackageId, &Package> = metadata
        .packages
        .iter()
        .map(|package| (&package.id, package))
        .collect();

    let mut visited = HashSet::new();
    let mut stack = vec![root_id.clone()];

    while let Some(package_id) = stack.pop() {
        if !visited.insert(package_id.clone()) {
            continue;
        }

        for dependency_id in edges.get(&package_id).into_iter().flatten() {
            let Some(package) = package_lookup.get(dependency_id) else {
                continue;
            };

            if package.source.is_none() {
                stack.push((*dependency_id).clone());
            }
        }
    }

    Ok(visited)
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::local_package_graph_watch_paths;

    #[test]
    fn local_package_graph_watch_paths_include_local_packages_and_workspace_files() {
        let tempdir = tempfile::tempdir().expect("create tempdir");
        let workspace_root = tempdir.path();

        fs::write(
            workspace_root.join("Cargo.toml"),
            r#"[workspace]
members = ["app", "dep"]
resolver = "2"
"#,
        )
        .expect("write workspace Cargo.toml");

        fs::create_dir_all(workspace_root.join("app/src")).expect("create app/src");
        fs::write(
            workspace_root.join("app/Cargo.toml"),
            r#"[package]
name = "app"
version = "0.1.0"
edition = "2021"

[dependencies]
dep = { path = "../dep" }
"#,
        )
        .expect("write app Cargo.toml");
        fs::write(workspace_root.join("app/src/lib.rs"), "pub fn app() {}\n")
            .expect("write app lib.rs");

        fs::create_dir_all(workspace_root.join("dep/src")).expect("create dep/src");
        fs::write(
            workspace_root.join("dep/Cargo.toml"),
            r#"[package]
name = "dep"
version = "0.1.0"
edition = "2021"
"#,
        )
        .expect("write dep Cargo.toml");
        fs::write(workspace_root.join("dep/src/lib.rs"), "pub fn dep() {}\n")
            .expect("write dep lib.rs");
        fs::write(workspace_root.join("dep/build.rs"), "fn main() {}\n")
            .expect("write dep build.rs");
        fs::write(workspace_root.join("Cargo.lock"), "").expect("write Cargo.lock");

        let watched_paths = local_package_graph_watch_paths(&workspace_root.join("app"))
            .expect("collect watched paths");

        assert!(watched_paths.contains(&workspace_root.join("Cargo.toml")));
        assert!(watched_paths.contains(&workspace_root.join("Cargo.lock")));
        assert!(watched_paths.contains(&workspace_root.join("app/Cargo.toml")));
        assert!(watched_paths.contains(&workspace_root.join("app/src")));
        assert!(watched_paths.contains(&workspace_root.join("dep/Cargo.toml")));
        assert!(watched_paths.contains(&workspace_root.join("dep/src")));
        assert!(watched_paths.contains(&workspace_root.join("dep/build.rs")));
    }
}