Skip to main content

rbnx/cmd/
codegen.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// `rbnx codegen -p <package>` — one-shot codegen wrapper that replaces
3// the copy-pasted robonix-codegen + grpc_tools.protoc boilerplate in each
4// package's build.sh.
5//
6// For a given package root:
7//   1. Stage the system-wide .proto files (IDL + capabilities) into
8//      `<pkg>/rbnx-build/proto-staging/`. This dir is package-local and
9//      transient — no committed artefacts elsewhere in the tree.
10//   2. If --mcp: regenerate `<pkg>/robonix_mcp_types/`
11//      (robonix-codegen --lang mcp).
12//   3. Run grpc_tools.protoc on the staged + runtime protos, emitting
13//      `<pkg>/rbnx-build/codegen/proto_gen/`.
14//
15// Codegen owns only `rbnx-build/codegen/` and `rbnx-build/proto-staging/`.
16// In particular, it must never create, overwrite, or remove the colcon
17// workspace under `rbnx-build/ws/`; `rbnx start` injects generated Python
18// paths directly and sources a real colcon overlay when one exists.
19//
20// TODO: union package-local capabilities (`<pkg>/capabilities/`) and
21// package-local IDL (`<pkg>/interfaces/lib/`) into a staging dir before
22// running codegen — currently those are a copy-pasted snippet in a few
23// build.sh scripts.
24
25use anyhow::{Context, Result};
26use colored::*;
27use robonix_cli::{Config, SourcePathKey};
28use robonix_scribe::debug;
29use sha2::{Digest, Sha256};
30use std::path::{Path, PathBuf};
31use std::process::{Command, Output};
32use std::time::{SystemTime, UNIX_EPOCH};
33
34pub(crate) fn run_cmd(label: &str, cmd: &mut Command) -> Result<()> {
35    debug!("[codegen] {}: {:?}", label, cmd);
36    let status = cmd
37        .status()
38        .with_context(|| format!("failed to execute `{label}`"))?;
39    if !status.success() {
40        anyhow::bail!("{label} failed with {status}");
41    }
42    Ok(())
43}
44
45fn resolve_pkg_root(package: &Path) -> Result<PathBuf> {
46    let abs = if package.is_absolute() {
47        package.to_path_buf()
48    } else {
49        let base = std::env::var("RBNX_INVOCATION_CWD")
50            .map(PathBuf::from)
51            .unwrap_or(std::env::current_dir()?);
52        base.join(package)
53    };
54    let abs = abs
55        .canonicalize()
56        .with_context(|| format!("package path not found: {}", abs.display()))?;
57    if !abs.join("package_manifest.yaml").exists()
58        && !abs.join("robonix_manifest.yaml").exists()
59        && !abs.join("rbnx_manifest.yaml").exists()
60    {
61        eprintln!(
62            "{}: {} has no package_manifest.yaml (continuing anyway)",
63            "warn".yellow().bold(),
64            abs.display()
65        );
66    }
67    Ok(abs)
68}
69
70pub async fn execute(
71    config: Config,
72    package: Option<PathBuf>,
73    mcp: bool,
74    ros2: bool,
75    clean: bool,
76    out_dir: Option<PathBuf>,
77    python: Option<PathBuf>,
78) -> Result<()> {
79    let pkg_root = match package {
80        Some(p) => resolve_pkg_root(&p)?,
81        None => super::run_package::find_package_from_cwd()?,
82    };
83    let rust_root = config.resolve_source_path(SourcePathKey::RustRoot)?;
84    // <root>/capabilities — contract TOMLs (top level) + IDL under lib/.
85    let capabilities_dir = config.resolve_source_path(SourcePathKey::Capabilities)?;
86    // <root>/capabilities/lib — single canonical IDL search root.
87    // msg/srv references in contract TOMLs (e.g. `demo/srv/Hello`)
88    // resolve as `<root>/capabilities/lib/demo/srv/Hello.srv`.
89    let interfaces_lib = config.resolve_source_path(SourcePathKey::InterfacesLib)?;
90    let runtime_proto = config.resolve_source_path(SourcePathKey::RuntimeProto)?;
91    // Per-package overlay: `<pkg>/capabilities/` mirrors the global
92    // layout. When present we add it both as an IDL include
93    // (`<pkg>/capabilities/lib/`) and as a contracts root, so packages
94    // can ship their own msg/srv/contracts that merge with the global
95    // set (symmetric with how atlas's contract registry merges roots).
96    let pkg_caps = pkg_root.join("capabilities");
97    let pkg_caps_lib: Option<PathBuf> = {
98        let p = pkg_caps.join("lib");
99        p.is_dir().then_some(p)
100    };
101    // <pkg>/capabilities/ also gets passed to --contracts so per-package
102    // contracts merge with the global tree (atlas does the same merge
103    // at the registry level — this keeps codegen consistent).
104    let pkg_caps_root: Option<PathBuf> = pkg_caps.is_dir().then_some(pkg_caps);
105
106    // Codegen output convention: every package gets
107    // `<pkg>/rbnx-build/codegen/{proto_gen, robonix_mcp_types}`. Both robonix_api
108    // and rbnx-cli rely on this exact layout, so packages don't need to plumb
109    // paths anywhere — `rbnx codegen -p $PKG` is the whole story. The
110    // `--out-dir` flag stays as an escape hatch for unusual layouts but
111    // defaults to the convention.
112    let rbnx_build = pkg_root.join("rbnx-build");
113    let out_root = match out_dir {
114        Some(d) if d.is_absolute() => d,
115        Some(d) => pkg_root.join(d),
116        None => rbnx_build.join("codegen"),
117    };
118    let proto_gen = out_root.join("proto_gen");
119    let mcp_types = out_root.join("robonix_mcp_types");
120    // ROS 2 canonical message overlay (a colcon workspace of source). Only
121    // generated with --ros2; consumers colcon-build it and source
122    // install/setup.bash so their rclpy types are Robonix's.
123    let ros2_idl = out_root.join("ros2_idl");
124    // Per-invocation staging for the system-wide .proto files. No commits;
125    // grpc_tools.protoc reads from here in step 3.
126    // Keep codegen's own scribe log with the other build artefacts rather than
127    // letting it default to `./logs` inside the package checkout.
128    let codegen_log_dir = rbnx_build.join("logs");
129    let proto_staging = rbnx_build.join("proto-staging");
130
131    if clean {
132        clean_codegen_outputs([&proto_gen, &mcp_types, &ros2_idl, &proto_staging])?;
133    }
134    std::fs::create_dir_all(&proto_staging)?;
135
136    // Prefer the installed `robonix-codegen` binary on PATH (or in the
137    // workspace target dir) — `cargo run -p robonix-codegen` rebuilds /
138    // re-resolves the workspace on every invocation, which adds 100-300 ms
139    // even when nothing changed and floods the boot log with `Compiling…`
140    // lines that don't belong in a per-package codegen step. Falls back
141    // to `cargo run` only if neither binary is available, so a fresh
142    // checkout that hasn't done `cargo install` keeps working.
143    let direct_codegen = locate_codegen_bin(&rust_root);
144    let cargo_bin = if direct_codegen.is_none() {
145        if Path::new("/usr/bin/cargo").exists() {
146            Some("/usr/bin/cargo".to_string())
147        } else {
148            Some(std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()))
149        }
150    } else {
151        None
152    };
153
154    println!("{} package: {}", "[codegen]".bold(), pkg_root.display());
155    println!(
156        "{} robonix source: {}",
157        "[codegen]".bold(),
158        rust_root.display()
159    );
160
161    // 1. Stage system .proto into rbnx-build/proto-staging/.
162    //    Includes: global <root>/capabilities/lib + (if present) per-package
163    //    <pkg>/capabilities/lib. --contracts: global capabilities tree
164    //    (per-package contracts merging through codegen is a follow-up).
165    println!("{} robonix-codegen --lang proto ...", "[codegen]".bold());
166    let mut proto_cmd = build_codegen_cmd(
167        direct_codegen.as_ref(),
168        cargo_bin.as_deref(),
169        &rust_root,
170        &codegen_log_dir,
171    );
172    proto_cmd
173        .args(["--lang", "proto", "-I"])
174        .arg(&interfaces_lib);
175    if let Some(p) = pkg_caps_lib.as_ref() {
176        proto_cmd.arg("-I").arg(p);
177    }
178    proto_cmd.arg("--contracts").arg(&capabilities_dir);
179    if let Some(p) = pkg_caps_root.as_ref() {
180        proto_cmd.arg("--contracts").arg(p);
181    }
182    proto_cmd.arg("-o").arg(&proto_staging);
183    run_cmd("robonix-codegen proto", &mut proto_cmd)?;
184
185    // 2. Optional: MCP dataclasses.
186    if mcp {
187        println!("{} robonix-codegen --lang mcp ...", "[codegen]".bold());
188        std::fs::create_dir_all(&mcp_types).ok();
189        let mut mcp_cmd = build_codegen_cmd(
190            direct_codegen.as_ref(),
191            cargo_bin.as_deref(),
192            &rust_root,
193            &codegen_log_dir,
194        );
195        mcp_cmd.args(["--lang", "mcp", "-I"]).arg(&interfaces_lib);
196        // Include per-package <pkg>/capabilities/lib too — same merge
197        // semantics as the proto step, so per-pkg srv files (e.g.
198        // explore_rbnx's Explore.srv) emit their MCP Request/Response
199        // dataclasses alongside the global ones.
200        if let Some(p) = pkg_caps_lib.as_ref() {
201            mcp_cmd.arg("-I").arg(p);
202        }
203        mcp_cmd.arg("-o").arg(&mcp_types);
204        run_cmd("robonix-codegen mcp", &mut mcp_cmd)?;
205    }
206
207    // 3. Package-local Python stubs via grpc_tools.protoc.
208    //
209    // We shell out to the active python3's `grpcio-tools` package because
210    // generating Python `_pb2.py` + `_pb2_grpc.py` from `.proto` is what
211    // the standard protoc-with-grpc-python-plugin combo is designed to
212    // do, and there's no maintained Rust crate that emits Python stubs.
213    // Probe for both python3 and the module up front — the historical
214    // silent-ignore on failure left packages with "0 generated Servicers"
215    // at runtime and a debug session per missing dep.
216    //
217    // Unless a Python is named, the pinned toolchain rbnx manages is used.
218    // Whatever `python3` is on PATH may import grpc_tools yet mix versions
219    // (an app's venv with system site-packages plus a newer grpcio-tools in
220    // the user site), and its stubs then fail against the pinned runtime.
221    let (python_selection, python_info) = match select_codegen_python(python)? {
222        Some(selected) => {
223            let info = probe_python_grpc_tools(&selected.path)?;
224            if let Some(mismatch) = pinned_mismatch(&info) {
225                anyhow::bail!(
226                    "codegen Python selected by {} ({}) has {mismatch}; rbnx codegen needs \
227                     protobuf=={MANAGED_PROTOBUF}, grpcio-tools=={MANAGED_GRPC_TOOLS} and \
228                     grpcio=={MANAGED_GRPCIO}. Install those versions there, or unset \
229                     RBNX_CODEGEN_PYTHON and drop --python to use the managed toolchain.",
230                    selected.source,
231                    info.executable
232                );
233            }
234            (selected, info)
235        }
236        None => {
237            let path = managed_codegen_python()?;
238            let info = probe_python_grpc_tools(&path)?;
239            (
240                PythonSelection {
241                    path,
242                    source: "managed".to_string(),
243                },
244                info,
245            )
246        }
247    };
248    let python = &python_selection.path;
249    println!(
250        "{} Python: {} ({})",
251        "[codegen]".bold(),
252        python_info.executable,
253        python_info.version
254    );
255
256    println!(
257        "{} grpc_tools.protoc → {}",
258        "[codegen]".bold(),
259        proto_gen.display()
260    );
261    let proto_gen_pending = temporary_sibling(&proto_gen, "pending");
262    if proto_gen_pending.exists() {
263        std::fs::remove_dir_all(&proto_gen_pending)?;
264    }
265    std::fs::create_dir_all(&proto_gen_pending)?;
266    let mut proto_inputs = collect_proto_inputs(&runtime_proto, "runtime")?;
267    proto_inputs.extend(collect_proto_inputs(&proto_staging, "staged")?);
268    proto_inputs.sort_by(|a, b| a.logical_path.cmp(&b.logical_path));
269
270    let input_fingerprint = fingerprint_proto_inputs(&proto_inputs)?;
271    let mut protoc = python_command(python);
272    protoc
273        .args(["-m", "grpc_tools.protoc", "-I"])
274        .arg(&runtime_proto)
275        .arg("-I")
276        .arg(&proto_staging)
277        .arg(format!("--python_out={}", proto_gen_pending.display()))
278        .arg(format!("--grpc_python_out={}", proto_gen_pending.display()));
279    for input in &proto_inputs {
280        protoc.arg(&input.physical_path);
281    }
282    let status = protoc
283        .status()
284        .with_context(|| format!("failed to spawn {} -m grpc_tools.protoc", python.display()))?;
285    if !status.success() {
286        std::fs::remove_dir_all(&proto_gen_pending).ok();
287        anyhow::bail!(
288            "{} -m grpc_tools.protoc failed with {status}. \
289             Re-run with -v / RUST_LOG=debug to see protoc output.",
290            python.display()
291        );
292    }
293    if let Err(error) = validate_generated_imports(python, &proto_gen_pending) {
294        std::fs::remove_dir_all(&proto_gen_pending).ok();
295        return Err(error);
296    }
297    write_toolchain_metadata(
298        &proto_gen_pending.join("codegen-toolchain.json"),
299        &python_info,
300        &python_selection.source,
301        direct_codegen.as_deref(),
302        &rust_root,
303        &input_fingerprint,
304    )?;
305    publish_directory(&proto_gen_pending, &proto_gen)?;
306
307    // 3b. Optional: ROS 2 canonical message overlay (source). Emitted next
308    //     to proto_gen / robonix_mcp_types so it follows the same rbnx-build
309    //     convention. It still needs `colcon build` in a ROS 2 environment;
310    //     the package's build.sh does that (e.g. docker exec into the
311    //     container) and start.sh sources <ros2_idl>/install/setup.bash.
312    if ros2 {
313        println!("{} robonix-codegen --lang ros2 ...", "[codegen]".bold());
314        let mut ros2_cmd = build_codegen_cmd(
315            direct_codegen.as_ref(),
316            cargo_bin.as_deref(),
317            &rust_root,
318            &codegen_log_dir,
319        );
320        ros2_cmd.args(["--lang", "ros2", "-I"]).arg(&interfaces_lib);
321        if let Some(p) = pkg_caps_lib.as_ref() {
322            ros2_cmd.arg("-I").arg(p);
323        }
324        ros2_cmd.arg("-o").arg(&ros2_idl);
325        run_cmd("robonix-codegen ros2", &mut ros2_cmd)?;
326    }
327
328    println!(
329        "{} done — {}{}",
330        "[codegen]".green().bold(),
331        if mcp {
332            "proto+mcp+stubs"
333        } else {
334            "proto+stubs"
335        },
336        if mcp_types.exists() {
337            format!(" in {}", out_root.display())
338        } else {
339            String::new()
340        }
341    );
342    Ok(())
343}
344
345fn clean_codegen_outputs<'a>(paths: impl IntoIterator<Item = &'a PathBuf>) -> Result<()> {
346    for path in paths {
347        if path.exists() {
348            if path.is_dir() {
349                std::fs::remove_dir_all(path)
350            } else {
351                std::fs::remove_file(path)
352            }
353            .with_context(|| format!("remove codegen output {}", path.display()))?;
354        }
355    }
356    Ok(())
357}
358
359/// Locate a runnable `robonix-codegen` binary without going through cargo.
360/// Search order:
361///   1. `$ROBONIX_CODEGEN_BIN` (override for unusual layouts)
362///   2. `$CARGO_HOME/bin/robonix-codegen` / `~/.cargo/bin/robonix-codegen`
363///      — what `cargo install --path crates/robonix-codegen` puts there
364///   3. `<rust_root>/target/release/robonix-codegen`
365///   4. `<rust_root>/target/debug/robonix-codegen`
366///   5. anything matching `robonix-codegen` on `$PATH`
367///
368/// Returns `None` only when none of those exist; callers fall back to
369/// `cargo run -p robonix-codegen` which keeps a fresh-checkout workflow
370/// alive even before the user has installed any binaries.
371pub(crate) fn locate_codegen_bin(rust_root: &Path) -> Option<PathBuf> {
372    if let Ok(s) = std::env::var("ROBONIX_CODEGEN_BIN")
373        && !s.is_empty()
374    {
375        let p = PathBuf::from(s);
376        if p.is_file() {
377            return Some(p);
378        }
379    }
380    let cargo_home = std::env::var("CARGO_HOME")
381        .map(PathBuf::from)
382        .ok()
383        .or_else(|| dirs::home_dir().map(|h| h.join(".cargo")));
384    if let Some(home) = cargo_home {
385        let p = home.join("bin").join("robonix-codegen");
386        if p.is_file() {
387            return Some(p);
388        }
389    }
390    for profile in ["release", "debug"] {
391        let p = rust_root
392            .join("target")
393            .join(profile)
394            .join("robonix-codegen");
395        if p.is_file() {
396            return Some(p);
397        }
398    }
399    if let Ok(path_env) = std::env::var("PATH") {
400        for dir in std::env::split_paths(&path_env) {
401            let p = dir.join("robonix-codegen");
402            if p.is_file() {
403                return Some(p);
404            }
405        }
406    }
407    None
408}
409
410/// Probe the active python3 for `grpc_tools.protoc`. Bails with a single,
411/// copy-pasteable install instruction if either is missing — this is the
412/// only Python dep `rbnx codegen` reaches for, so making it explicit up
413/// front is the entire UX cost of not vendoring protoc + grpc_python_plugin.
414#[derive(Debug)]
415struct PythonInfo {
416    executable: String,
417    version: String,
418    grpcio_tools: String,
419    protobuf: String,
420    grpcio: String,
421    protoc_version: String,
422}
423
424#[derive(Debug, Clone)]
425struct ProtoInput {
426    logical_path: String,
427    physical_path: PathBuf,
428}
429
430#[derive(Debug, PartialEq, Eq)]
431struct PythonSelection {
432    path: PathBuf,
433    source: String,
434}
435
436/// The Python named by `--python`, else by `RBNX_CODEGEN_PYTHON`; `None`
437/// means the managed toolchain.
438fn resolve_python_selection(
439    cli: Option<PathBuf>,
440    environment: Option<std::ffi::OsString>,
441) -> Option<PythonSelection> {
442    if let Some(path) = cli {
443        return Some(PythonSelection {
444            path,
445            source: "cli".to_string(),
446        });
447    }
448    environment
449        .filter(|path| !path.is_empty())
450        .map(|path| PythonSelection {
451            path: PathBuf::from(path),
452            source: "environment".to_string(),
453        })
454}
455
456/// A command running `python` with the user site off, so packages under
457/// ~/.local never mix into the toolchain.
458fn python_command(python: &Path) -> Command {
459    let mut command = Command::new(python);
460    command.env("PYTHONNOUSERSITE", "1");
461    command
462}
463
464/// What differs from the pinned toolchain, if anything.
465fn pinned_mismatch(info: &PythonInfo) -> Option<String> {
466    let wrong: Vec<String> = [
467        ("protobuf", &info.protobuf, MANAGED_PROTOBUF),
468        ("grpcio-tools", &info.grpcio_tools, MANAGED_GRPC_TOOLS),
469        ("grpcio", &info.grpcio, MANAGED_GRPCIO),
470    ]
471    .into_iter()
472    .filter(|(_, found, wanted)| found.as_str() != *wanted)
473    .map(|(name, found, _)| format!("{name} {found}"))
474    .collect();
475    (!wrong.is_empty()).then(|| wrong.join(", "))
476}
477
478fn select_codegen_python(cli: Option<PathBuf>) -> Result<Option<PythonSelection>> {
479    let Some(selection) = resolve_python_selection(cli, std::env::var_os("RBNX_CODEGEN_PYTHON"))
480    else {
481        return Ok(None);
482    };
483    let candidate = &selection.path;
484    let output = python_command(candidate)
485        .arg("--version")
486        .output()
487        .with_context(|| {
488            format!(
489                "cannot execute codegen Python selected by {}: {}",
490                selection.source,
491                candidate.display()
492            )
493        })?;
494    if !output.status.success() {
495        anyhow::bail!(
496            "codegen Python selected by {} failed `--version`: {} ({})",
497            selection.source,
498            candidate.display(),
499            output.status
500        );
501    }
502    Ok(Some(selection))
503}
504
505// The managed toolchain's versions: the ones the Webots containers import
506// (examples/webots/scripts/run_python_codegen.sh), since stubs from a newer
507// protobuf major do not load in an older runtime.
508const MANAGED_PROTOBUF: &str = "6.33.6";
509const MANAGED_GRPC_TOOLS: &str = "1.76.0";
510const MANAGED_GRPCIO: &str = "1.80.0";
511
512/// A Python with the pinned codegen toolchain, under the robonix home,
513/// created with uv on first use and reused after that.
514fn managed_codegen_python() -> Result<PathBuf> {
515    let home = Config::robonix_home_dir()?;
516    let venv = home.join("codegen-venv");
517    let python = venv.join("bin").join("python");
518    if managed_python_ready(&python) {
519        return Ok(python);
520    }
521    println!(
522        "{} preparing grpcio-tools {MANAGED_GRPC_TOOLS} in {}",
523        "[codegen]".bold(),
524        venv.display()
525    );
526    std::fs::create_dir_all(&home).with_context(|| format!("create {}", home.display()))?;
527    // Built aside and moved into place, so packages generating in parallel
528    // never see a half-installed environment.
529    let staging = home.join(format!("codegen-venv.{}", std::process::id()));
530    let _ = std::fs::remove_dir_all(&staging);
531    let uv = |args: &[&str]| -> Result<()> {
532        let status = Command::new("uv").args(args).status().with_context(|| {
533            "`uv` is needed to prepare the codegen Python; install it from \
534             https://docs.astral.sh/uv/ or set RBNX_CODEGEN_PYTHON"
535        })?;
536        anyhow::ensure!(status.success(), "uv {} failed: {status}", args.join(" "));
537        Ok(())
538    };
539    let staging_python = staging.join("bin").join("python");
540    let installed = uv(&["venv", "--quiet", &staging.to_string_lossy()]).and_then(|()| {
541        uv(&[
542            "pip",
543            "install",
544            "--quiet",
545            "--python",
546            &staging_python.to_string_lossy(),
547            &format!("protobuf=={MANAGED_PROTOBUF}"),
548            &format!("grpcio-tools=={MANAGED_GRPC_TOOLS}"),
549            &format!("grpcio=={MANAGED_GRPCIO}"),
550        ])
551    });
552    if let Err(error) = installed {
553        let _ = std::fs::remove_dir_all(&staging);
554        return Err(error);
555    }
556    if std::fs::rename(&staging, &venv).is_err() {
557        // Another package finished first, or an old environment is in the
558        // way. Keep a working one; replace a broken one.
559        if managed_python_ready(&python) {
560            let _ = std::fs::remove_dir_all(&staging);
561        } else {
562            let _ = std::fs::remove_dir_all(&venv);
563            std::fs::rename(&staging, &venv)
564                .with_context(|| format!("move codegen Python into {}", venv.display()))?;
565        }
566    }
567    Ok(python)
568}
569
570/// The managed Python exists and still has exactly the pinned versions; an
571/// older one is rebuilt rather than reused.
572fn managed_python_ready(python: &Path) -> bool {
573    python.is_file()
574        && probe_python_grpc_tools(python).is_ok_and(|info| pinned_mismatch(&info).is_none())
575}
576
577fn probe_python_grpc_tools(python: &Path) -> Result<PythonInfo> {
578    const PROBE: &str = r#"
579import importlib.metadata as m, json, sys
580import grpc_tools.protoc
581def v(name):
582    try: return m.version(name)
583    except m.PackageNotFoundError: return "unknown"
584print(json.dumps({"executable": sys.executable, "version": sys.version.split()[0],
585                  "grpcio_tools": v("grpcio-tools"), "protobuf": v("protobuf"),
586                  "grpcio": v("grpcio")}, sort_keys=True))
587"#;
588    let mod_probe = python_command(python)
589        .args(["-c", PROBE])
590        .output()
591        .with_context(|| format!("failed to spawn {} for grpc_tools probe", python.display()))?;
592    if !mod_probe.status.success() {
593        anyhow::bail!(
594            "Python module 'grpc_tools' not importable from {}.\n\
595             `rbnx codegen` needs grpcio-tools to emit Python `_pb2.py` + `_pb2_grpc.py`.\n\
596             Install into the python3 above:\n\
597             \n    {} -m pip install grpcio-tools\n\
598             Probe stderr: {}",
599            python.display(),
600            python.display(),
601            String::from_utf8_lossy(&mod_probe.stderr).trim()
602        );
603    }
604    let value: serde_json::Value = serde_json::from_slice(&mod_probe.stdout)
605        .with_context(|| "codegen Python returned invalid toolchain probe metadata")?;
606    let get = |key: &str| {
607        value[key]
608            .as_str()
609            .map(str::to_owned)
610            .with_context(|| format!("codegen Python probe omitted `{key}`"))
611    };
612    let protoc_version = python_command(python)
613        .args(["-m", "grpc_tools.protoc", "--version"])
614        .output()
615        .with_context(|| {
616            format!(
617                "failed to query grpc_tools.protoc version via {}",
618                python.display()
619            )
620        })?;
621    if !protoc_version.status.success() {
622        anyhow::bail!(
623            "failed to query bundled grpc_tools.protoc version via {}: {}",
624            python.display(),
625            String::from_utf8_lossy(&protoc_version.stderr).trim()
626        );
627    }
628    Ok(PythonInfo {
629        executable: get("executable")?,
630        version: get("version")?,
631        grpcio_tools: get("grpcio_tools")?,
632        protobuf: get("protobuf")?,
633        grpcio: get("grpcio")?,
634        protoc_version: String::from_utf8_lossy(&protoc_version.stdout)
635            .trim()
636            .to_owned(),
637    })
638}
639
640fn collect_proto_inputs(root: &Path, namespace: &str) -> Result<Vec<ProtoInput>> {
641    let mut inputs = Vec::new();
642    for entry in std::fs::read_dir(root)
643        .with_context(|| format!("read proto input directory {}", root.display()))?
644    {
645        let path = entry?.path();
646        if path.extension().and_then(|s| s.to_str()) != Some("proto") {
647            continue;
648        }
649        let relative = path
650            .strip_prefix(root)
651            .with_context(|| format!("derive logical proto path for {}", path.display()))?;
652        inputs.push(ProtoInput {
653            logical_path: format!(
654                "{namespace}/{}",
655                relative.to_string_lossy().replace('\\', "/")
656            ),
657            physical_path: path,
658        });
659    }
660    Ok(inputs)
661}
662
663fn fingerprint_proto_inputs(proto_inputs: &[ProtoInput]) -> Result<String> {
664    let mut sorted = proto_inputs.to_vec();
665    sorted.sort_by(|a, b| a.logical_path.cmp(&b.logical_path));
666    let mut digest = Sha256::new();
667    for input in sorted {
668        let contents = std::fs::read(&input.physical_path).with_context(|| {
669            format!(
670                "read proto input for fingerprint: {}",
671                input.physical_path.display()
672            )
673        })?;
674        digest.update((input.logical_path.len() as u64).to_be_bytes());
675        digest.update(input.logical_path.as_bytes());
676        digest.update((contents.len() as u64).to_be_bytes());
677        digest.update(contents);
678    }
679    Ok(format!("{:x}", digest.finalize()))
680}
681
682fn temporary_sibling(path: &Path, label: &str) -> PathBuf {
683    let nonce = SystemTime::now()
684        .duration_since(UNIX_EPOCH)
685        .unwrap_or_default()
686        .as_nanos();
687    path.with_file_name(format!(
688        ".{}.{}-{}-{nonce}",
689        path.file_name().unwrap_or_default().to_string_lossy(),
690        label,
691        std::process::id()
692    ))
693}
694
695fn validate_generated_imports(python: &Path, generated: &Path) -> Result<()> {
696    const VALIDATE: &str = r#"
697import importlib, pathlib, sys, traceback
698root = pathlib.Path(sys.argv[1]).resolve()
699sys.path.insert(0, str(root))
700files = sorted(set(root.rglob("*_pb2.py")) | set(root.rglob("*_pb2_grpc.py")))
701if not files:
702    raise SystemExit("no generated *_pb2.py or *_pb2_grpc.py files found")
703failed = []
704for path in files:
705    name = ".".join(path.relative_to(root).with_suffix("").parts)
706    try:
707        importlib.import_module(name)
708    except Exception:
709        failed.append((str(path.relative_to(root)), traceback.format_exc()))
710if failed:
711    for path, error in failed:
712        print("IMPORT FAILED: " + path, file=sys.stderr)
713        print(error, file=sys.stderr)
714    raise SystemExit(f"{len(failed)} of {len(files)} generated modules failed import validation")
715print(f"validated {len(files)} generated Python modules")
716"#;
717    let output = python_command(python)
718        .arg("-c")
719        .arg(VALIDATE)
720        .arg(generated)
721        .output()
722        .with_context(|| {
723            format!(
724                "failed to run generated-stub validation with {}",
725                python.display()
726            )
727        })?;
728    ensure_success("generated Python import validation", output)
729}
730
731fn ensure_success(label: &str, output: Output) -> Result<()> {
732    if output.status.success() {
733        println!(
734            "{} {}",
735            "[codegen]".bold(),
736            String::from_utf8_lossy(&output.stdout).trim()
737        );
738        return Ok(());
739    }
740    anyhow::bail!(
741        "{label} failed with {}:\n{}",
742        output.status,
743        String::from_utf8_lossy(&output.stderr).trim()
744    )
745}
746
747fn publish_directory(pending: &Path, destination: &Path) -> Result<()> {
748    let backup = temporary_sibling(destination, "previous");
749    if destination.exists() {
750        std::fs::rename(destination, &backup).with_context(|| {
751            format!(
752                "preserve previous generated stubs {}",
753                destination.display()
754            )
755        })?;
756    }
757    if let Err(error) = std::fs::rename(pending, destination) {
758        if backup.exists() {
759            std::fs::rename(&backup, destination).ok();
760        }
761        return Err(error).with_context(|| {
762            format!(
763                "publish generated stubs atomically to {}",
764                destination.display()
765            )
766        });
767    }
768    if backup.exists() {
769        std::fs::remove_dir_all(backup)?;
770    }
771    Ok(())
772}
773
774fn write_toolchain_metadata(
775    path: &Path,
776    python: &PythonInfo,
777    selection_source: &str,
778    codegen_bin: Option<&Path>,
779    rust_root: &Path,
780    input_fingerprint: &str,
781) -> Result<()> {
782    let generator_version = codegen_bin.and_then(|bin| {
783        Command::new(bin)
784            .arg("--version")
785            .output()
786            .ok()
787            .filter(|output| output.status.success())
788            .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
789            .filter(|version| !version.is_empty())
790    });
791    let metadata = serde_json::json!({
792        "schema_version": 1,
793        "inputs": {
794            "algorithm": "sha256",
795            "proto_paths_and_contents": input_fingerprint
796        },
797        "generator": {
798            "kind": if codegen_bin.is_some() { "binary" } else { "cargo-run" },
799            "path": codegen_bin.map(|p| p.display().to_string()),
800            "version": generator_version,
801            "rust_root": rust_root.display().to_string()
802        },
803        "python": {
804            "executable": python.executable,
805            "selection_source": selection_source,
806            "version": python.version,
807            "grpcio_tools": python.grpcio_tools,
808            "bundled_protoc": python.protoc_version,
809            "protobuf": python.protobuf,
810            "grpcio": python.grpcio
811        }
812    });
813    std::fs::write(path, serde_json::to_vec_pretty(&metadata)?)
814        .with_context(|| format!("write codegen metadata {}", path.display()))
815}
816
817/// Build a fresh `Command` invoking `robonix-codegen` either directly
818/// (preferred — picks up `$ROBONIX_CODEGEN_BIN` / installed bin / target/
819/// in that order) or via `cargo run -p robonix-codegen` as a last
820/// resort. Caller appends the actual `--lang … -I … -o …` args.
821pub(crate) fn build_codegen_cmd(
822    direct: Option<&PathBuf>,
823    cargo: Option<&str>,
824    rust_root: &Path,
825    log_dir: &Path,
826) -> Command {
827    let mut cmd = if let Some(bin) = direct {
828        Command::new(bin)
829    } else {
830        let cargo = cargo.expect("either direct codegen bin or cargo bin must be set");
831        let mut cmd = Command::new(cargo);
832        cmd.args(["run", "-p", "robonix-codegen", "--manifest-path"])
833            .arg(rust_root.join("Cargo.toml"))
834            .arg("--");
835        cmd
836    };
837    // robonix-codegen logs through scribe, which falls back to `./logs` when
838    // SCRIBE_LOG_DIR is unset. Run from a package directory that put an
839    // untracked `logs/codegen.log` inside the checkout, next to the source
840    // rather than under `rbnx-build/` with every other build artefact, where
841    // it then showed up as a local edit in `git status`. Point it at the same
842    // place run_package.rs already uses.
843    cmd.env("SCRIBE_LOG_DIR", log_dir);
844    cmd
845}
846
847#[cfg(test)]
848mod tests {
849    use super::*;
850    use std::fs;
851    use std::time::{SystemTime, UNIX_EPOCH};
852
853    fn temp_root(label: &str) -> PathBuf {
854        let nonce = SystemTime::now()
855            .duration_since(UNIX_EPOCH)
856            .unwrap()
857            .as_nanos();
858        std::env::temp_dir().join(format!(
859            "rbnx-codegen-{label}-{}-{nonce}",
860            std::process::id()
861        ))
862    }
863
864    #[test]
865    fn clean_preserves_existing_colcon_workspace() {
866        let root = temp_root("preserve-colcon");
867        let codegen = root.join("rbnx-build/codegen");
868        let staging = root.join("rbnx-build/proto-staging");
869        let setup = root.join("rbnx-build/ws/install/setup.bash");
870        let original = b"# generated by colcon\nCOLCON_CURRENT_PREFIX=/real/overlay\n";
871
872        fs::create_dir_all(&codegen).unwrap();
873        fs::create_dir_all(&staging).unwrap();
874        fs::create_dir_all(setup.parent().unwrap()).unwrap();
875        fs::write(codegen.join("generated.py"), "generated").unwrap();
876        fs::write(staging.join("contracts.proto"), "staged").unwrap();
877        fs::write(&setup, original).unwrap();
878
879        clean_codegen_outputs([&codegen, &staging]).unwrap();
880
881        assert!(!codegen.exists());
882        assert!(!staging.exists());
883        assert_eq!(fs::read(&setup).unwrap(), original);
884        fs::remove_dir_all(root).unwrap();
885    }
886
887    #[test]
888    fn publish_directory_replaces_previous_tree() {
889        let root = temp_root("atomic-publish");
890        let destination = root.join("proto_gen");
891        let pending = root.join(".proto_gen.pending");
892        fs::create_dir_all(&destination).unwrap();
893        fs::create_dir_all(&pending).unwrap();
894        fs::write(destination.join("old_pb2.py"), "old").unwrap();
895        fs::write(pending.join("new_pb2.py"), "new").unwrap();
896
897        publish_directory(&pending, &destination).unwrap();
898
899        assert!(!pending.exists());
900        assert!(!destination.join("old_pb2.py").exists());
901        assert_eq!(
902            fs::read_to_string(destination.join("new_pb2.py")).unwrap(),
903            "new"
904        );
905        fs::remove_dir_all(root).unwrap();
906    }
907
908    #[test]
909    fn validates_every_generated_python_module() {
910        let root = temp_root("validate-imports");
911        fs::create_dir_all(&root).unwrap();
912        fs::write(root.join("hello_pb2.py"), "VALUE = 1\n").unwrap();
913        fs::write(
914            root.join("hello_pb2_grpc.py"),
915            "import hello_pb2\nVALUE = hello_pb2.VALUE\n",
916        )
917        .unwrap();
918
919        validate_generated_imports(Path::new("python3"), &root).unwrap();
920
921        fs::write(root.join("broken_pb2.py"), "raise RuntimeError('broken')\n").unwrap();
922        let error = validate_generated_imports(Path::new("python3"), &root).unwrap_err();
923        assert!(error.to_string().contains("broken_pb2.py"));
924        fs::remove_dir_all(root).unwrap();
925    }
926
927    #[test]
928    fn python_selection_precedence_is_cli_then_environment_then_managed() {
929        let env = Some(std::ffi::OsString::from("/env/python"));
930        assert_eq!(
931            resolve_python_selection(Some(PathBuf::from("/cli/python")), env.clone()),
932            Some(PythonSelection {
933                path: PathBuf::from("/cli/python"),
934                source: "cli".to_string(),
935            })
936        );
937        assert_eq!(
938            resolve_python_selection(None, env),
939            Some(PythonSelection {
940                path: PathBuf::from("/env/python"),
941                source: "environment".to_string(),
942            })
943        );
944        assert_eq!(resolve_python_selection(None, None), None);
945        assert_eq!(
946            resolve_python_selection(None, Some(std::ffi::OsString::new())),
947            None
948        );
949    }
950
951    /// The failure seen through Robonix Console: a venv that imports
952    /// grpc_tools, but from a newer grpcio-tools in the user site next to the
953    /// pinned runtime. The probe must run with the user site off and the
954    /// mixed versions must be refused rather than used.
955    #[test]
956    fn a_python_mixing_toolchain_versions_is_refused() {
957        use std::os::unix::fs::PermissionsExt;
958        let root = temp_root("mixed-python");
959        fs::create_dir_all(&root).unwrap();
960        let seen = root.join("user-site");
961        let python = root.join("python");
962        fs::write(
963            &python,
964            format!(
965                "#!/bin/sh\nprintf '%s' \"${{PYTHONNOUSERSITE:-}}\" > '{}'\n\
966                 if [ \"$1\" = -c ]; then\n\
967                 echo '{{\"executable\": \"/mixed/bin/python\", \"version\": \"3.10.12\", \
968                 \"grpcio_tools\": \"1.83.0\", \"protobuf\": \"6.33.6\", \"grpcio\": \"1.80.0\"}}'\n\
969                 else echo 'libprotoc 31.1'; fi\n",
970                seen.display()
971            ),
972        )
973        .unwrap();
974        fs::set_permissions(&python, fs::Permissions::from_mode(0o755)).unwrap();
975
976        // A test thread that forks while the script is still open for writing
977        // hands the write descriptor to its child until that child execs, and
978        // executing the script meanwhile fails with ETXTBSY. Wait it out.
979        let info = (0..100)
980            .find_map(|_| match probe_python_grpc_tools(&python) {
981                Err(e)
982                    if e.chain().any(|c| {
983                        c.downcast_ref::<std::io::Error>()
984                            .is_some_and(|io| io.kind() == std::io::ErrorKind::ExecutableFileBusy)
985                    }) =>
986                {
987                    std::thread::sleep(std::time::Duration::from_millis(10));
988                    None
989                }
990                other => Some(other),
991            })
992            .expect("the fake python stayed busy")
993            .unwrap();
994        assert_eq!(fs::read_to_string(&seen).unwrap(), "1");
995        assert_eq!(
996            pinned_mismatch(&info).as_deref(),
997            Some("grpcio-tools 1.83.0")
998        );
999        fs::remove_dir_all(&root).ok();
1000    }
1001
1002    #[test]
1003    fn proto_fingerprint_is_order_independent_and_content_sensitive() {
1004        let root = temp_root("fingerprint");
1005        fs::create_dir_all(&root).unwrap();
1006        let first = root.join("a.proto");
1007        let second = root.join("b.proto");
1008        fs::write(&first, "syntax = \"proto3\";\n").unwrap();
1009        fs::write(&second, "message B {}\n").unwrap();
1010
1011        let first_input = ProtoInput {
1012            logical_path: "runtime/a.proto".to_string(),
1013            physical_path: first.clone(),
1014        };
1015        let second_input = ProtoInput {
1016            logical_path: "staged/b.proto".to_string(),
1017            physical_path: second.clone(),
1018        };
1019        let forward =
1020            fingerprint_proto_inputs(&[first_input.clone(), second_input.clone()]).unwrap();
1021        let reverse =
1022            fingerprint_proto_inputs(&[second_input.clone(), first_input.clone()]).unwrap();
1023        assert_eq!(forward, reverse);
1024        assert_eq!(forward.len(), 64);
1025
1026        fs::write(&second, "message B { string value = 1; }\n").unwrap();
1027        let changed = fingerprint_proto_inputs(&[first_input, second_input]).unwrap();
1028        assert_ne!(forward, changed);
1029        fs::remove_dir_all(root).unwrap();
1030    }
1031
1032    #[test]
1033    fn proto_fingerprint_does_not_depend_on_clone_root() {
1034        let left = temp_root("fingerprint-left");
1035        let right = temp_root("fingerprint-right");
1036        fs::create_dir_all(&left).unwrap();
1037        fs::create_dir_all(&right).unwrap();
1038        let left_path = left.join("same.proto");
1039        let right_path = right.join("same.proto");
1040        fs::write(&left_path, "message Same {}\n").unwrap();
1041        fs::write(&right_path, "message Same {}\n").unwrap();
1042
1043        let left_hash = fingerprint_proto_inputs(&[ProtoInput {
1044            logical_path: "runtime/same.proto".to_string(),
1045            physical_path: left_path,
1046        }])
1047        .unwrap();
1048        let right_hash = fingerprint_proto_inputs(&[ProtoInput {
1049            logical_path: "runtime/same.proto".to_string(),
1050            physical_path: right_path,
1051        }])
1052        .unwrap();
1053
1054        assert_eq!(left_hash, right_hash);
1055        fs::remove_dir_all(left).unwrap();
1056        fs::remove_dir_all(right).unwrap();
1057    }
1058
1059    #[test]
1060    fn metadata_records_selection_protoc_and_fingerprint() {
1061        let root = temp_root("metadata");
1062        fs::create_dir_all(&root).unwrap();
1063        let path = root.join("codegen-toolchain.json");
1064        let python = PythonInfo {
1065            executable: "/venv/bin/python".to_string(),
1066            version: "3.12.1".to_string(),
1067            grpcio_tools: "1.70.0".to_string(),
1068            protobuf: "5.29.0".to_string(),
1069            grpcio: "1.70.0".to_string(),
1070            protoc_version: "libprotoc 29.3".to_string(),
1071        };
1072
1073        write_toolchain_metadata(
1074            &path,
1075            &python,
1076            "environment",
1077            None,
1078            &root,
1079            "0123456789abcdef",
1080        )
1081        .unwrap();
1082
1083        let value: serde_json::Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
1084        assert_eq!(value["python"]["selection_source"], "environment");
1085        assert_eq!(value["python"]["bundled_protoc"], "libprotoc 29.3");
1086        assert_eq!(
1087            value["inputs"]["proto_paths_and_contents"],
1088            "0123456789abcdef"
1089        );
1090        fs::remove_dir_all(root).unwrap();
1091    }
1092}
浙ICP备2023005800号-2 浙公网安备33010902005384号