Skip to main content

nros/
env.rs

1//! The hosted edge of configuration: the process environment.
2//!
3//! Every env var nano-ros honours is read HERE and
4//! nowhere else. The core (`nros-node`) takes values — `ExecutorConfig::
5//! resolve_with` accepts an [`EnvRung`](nros_node::EnvRung) of already-resolved fields — so it
6//! needs no `std`, no `env` capability, and no stub on the five ports that have
7//! no environment to read.
8//!
9//! That is the difference between this and the ABI ports W10 made for the
10//! clock, sleep, tasks and the log sink: those name capabilities every RTOS
11//! HAS. A process environment is not one. Modelling it as an ABI entry would
12//! have put `return 0` in five ports and permanent surface in the header, for a
13//! facility that exists on one platform family.
14//!
15//! **One reader, through the C library**. The
16//! environment is read with `getenv`, not `std::env`. A process environment is
17//! a property of the PROCESS, not of the Rust standard library: threadx-linux
18//! and freertos-posix are `#![no_std]` images that are still Linux processes
19//! with a C library, and a measurement showed what happens when they stop
20//! honouring `$ROS_DOMAIN_ID` (parallel cells shared a domain and heard each
21//! other). There used to be two readers — this one on `std::env` and
22//! ~~`host_env`~~ on `getenv` — with the same variables and rules; they are one
23//! now, and `nros` needs no `std` to be a hosted edge. The edge is "a C library
24//! is linked", which on this tree is `target_os = "linux"`; a cross target has
25//! no `getenv` and this module does not exist there.
26//!
27//! Strings are borrowed from the process environment, which outlives the boot,
28//! so the resolved config's `&'static str` fields point straight into it. No
29//! cache is needed (the old `std::env` reader kept a `OnceLock` only to turn an
30//! owned `String` into a `&'static str`, and its staleness was a bug).
31//! Nothing in nano-ros calls `setenv` after boot.
32//!
33//! What lives here:
34//!
35//! * [`ExecutorConfigEnvExt::from_env`] — the constructor that used to be an
36//!   inherent method on `ExecutorConfig`. Bring the trait into scope (the
37//!   prelude has it) and the call site spelling is unchanged. `env` feature.
38//! * [`resolve_hosted`](crate::env::resolve_hosted) / [`try_resolve_hosted`](crate::env::try_resolve_hosted) — the boot-config precedence ladder
39//!   with the environment rung on top. The C / C++ entries call these on every
40//!   Linux build, `env` or not.
41//! * [`rmw_selector`] — the one `$NROS_RMW` reader.
42//! * [`var`](crate::env::var) / [`read_file`](crate::env::read_file) — the two C-library reads the hosted `init*`
43//!   entries need (`$RMW_IMPLEMENTATION`, `--params-file`).
44//! * [`write_file`](crate::env::write_file), [`rename`](crate::env::rename), [`set_var`](crate::env::set_var), [`exe_name`](crate::env::exe_name), [`thread_key`](crate::env::thread_key),
45//!   [`exit`](crate::env::exit) — the rest of the hosted PROCESS edge, for the C / C++ surfaces.
46//!   `nros-c` and `nros-cpp` write their census,
47//!   metadata and profile files through these instead of `std::fs` /
48//!   `std::process`, so the image root never links libstd: a census is a
49//!   property of a process with a C library, not of the Rust standard library.
50//!   One spelling of each C-library call, here, rather than one per crate.
51
52use core::ffi::{CStr, c_char};
53
54use crate::retired_env::RETIRED_ENV_VARS;
55use nros_node::{BootConfig, BootConfigError, EnvRung, ExecutorConfig, RMW_SELECTOR_CAP};
56use nros_rmw::SessionMode;
57
58unsafe extern "C" {
59    fn getenv(name: *const c_char) -> *const c_char;
60}
61
62/// `$NAME` as a C string, or `None` when unset — the one `getenv` call.
63fn raw(name: &CStr) -> Option<&'static CStr> {
64    // SAFETY: `name` is NUL-terminated; `getenv` returns NULL or a pointer to
65    // a NUL-terminated string in the process environment, which lives for the
66    // process, so a non-NULL result is a valid `'static` C string.
67    unsafe {
68        let p = getenv(name.as_ptr());
69        (!p.is_null()).then(|| CStr::from_ptr(p))
70    }
71}
72
73/// `$NAME` as UTF-8, or `None` when unset or not UTF-8 (`std::env::var`'s two
74/// `Err` cases, which the old std reader also treated as unset).
75///
76/// `name` is a Rust string; one longer than 63 bytes, or one holding a NUL,
77/// is no variable this tree reads and answers `None`.
78pub fn var(name: &str) -> Option<&'static str> {
79    let mut buf = [0u8; 64];
80    if name.len() >= buf.len() || name.as_bytes().contains(&0) {
81        return None;
82    }
83    buf[..name.len()].copy_from_slice(name.as_bytes());
84    let cname = CStr::from_bytes_until_nul(&buf).ok()?;
85    raw(cname)?.to_str().ok()
86}
87
88fn non_empty(v: Option<&'static str>) -> Option<&'static str> {
89    v.filter(|s| !s.is_empty())
90}
91
92/// `path` as a NUL-terminated buffer for the C library, or `None` when it holds
93/// a NUL byte (no file is named by such a path).
94#[cfg(feature = "alloc")]
95fn c_path(path: &str) -> Option<alloc::vec::Vec<u8>> {
96    if path.as_bytes().contains(&0) {
97        return None;
98    }
99    let mut cpath = alloc::vec::Vec::with_capacity(path.len() + 1);
100    cpath.extend_from_slice(path.as_bytes());
101    cpath.push(0);
102    Some(cpath)
103}
104
105/// A whole file, through the C library — `std::fs::read_to_string` for a
106/// crate with no `std`. `--params-file` reads through it, and so do the
107/// C / C++ surfaces' own params-file entries.
108///
109/// The error is a short reason (`"cannot be opened"`, `"is not UTF-8"`, ...),
110/// for the caller to put beside the path it already holds.
111#[cfg(feature = "alloc")]
112pub fn read_file(path: &str) -> Result<alloc::string::String, &'static str> {
113    use core::ffi::c_void;
114    unsafe extern "C" {
115        fn fopen(path: *const c_char, mode: *const c_char) -> *mut c_void;
116        fn fread(ptr: *mut c_void, size: usize, n: usize, f: *mut c_void) -> usize;
117        fn ferror(f: *mut c_void) -> i32;
118        fn fclose(f: *mut c_void) -> i32;
119    }
120    let Some(cpath) = c_path(path) else {
121        return Err("names a path holding a NUL byte");
122    };
123    // SAFETY: both strings are NUL-terminated; `f` is checked before use and
124    // closed exactly once; `fread` writes at most `chunk.len()` bytes.
125    let bytes = unsafe {
126        let f = fopen(cpath.as_ptr().cast(), c"rb".as_ptr());
127        if f.is_null() {
128            return Err("cannot be opened");
129        }
130        let mut out = alloc::vec::Vec::new();
131        let mut chunk = [0u8; 4096];
132        loop {
133            let n = fread(chunk.as_mut_ptr().cast(), 1, chunk.len(), f);
134            out.extend_from_slice(&chunk[..n]);
135            if n < chunk.len() {
136                break;
137            }
138        }
139        let failed = ferror(f) != 0;
140        fclose(f);
141        if failed {
142            return Err("cannot be read");
143        }
144        out
145    };
146    alloc::string::String::from_utf8(bytes).map_err(|_| "is not UTF-8")
147}
148
149/// Write `bytes` to `path`, creating or truncating it — `std::fs::write` for a
150/// crate with no `std`. The error is a short reason, as for [`read_file`].
151#[cfg(feature = "alloc")]
152pub fn write_file(path: &str, bytes: &[u8]) -> Result<(), &'static str> {
153    use core::ffi::c_void;
154    unsafe extern "C" {
155        fn fopen(path: *const c_char, mode: *const c_char) -> *mut c_void;
156        fn fwrite(ptr: *const c_void, size: usize, n: usize, f: *mut c_void) -> usize;
157        fn fclose(f: *mut c_void) -> i32;
158    }
159    let Some(cpath) = c_path(path) else {
160        return Err("names a path holding a NUL byte");
161    };
162    // SAFETY: both strings are NUL-terminated; `f` is checked before use and
163    // closed exactly once; `fwrite` reads at most `bytes.len()` bytes.
164    unsafe {
165        let f = fopen(cpath.as_ptr().cast(), c"wb".as_ptr());
166        if f.is_null() {
167            return Err("cannot be opened for writing");
168        }
169        let written = fwrite(bytes.as_ptr().cast(), 1, bytes.len(), f);
170        // `fclose` flushes: a full disk shows up here, not in `fwrite`.
171        let closed = fclose(f) == 0;
172        if written != bytes.len() || !closed {
173            return Err("cannot be written");
174        }
175    }
176    Ok(())
177}
178
179/// Rename `from` to `to`, replacing `to` — `std::fs::rename`. Same filesystem
180/// only, which is how its callers use it (write-then-rename beside the target).
181#[cfg(feature = "alloc")]
182pub fn rename(from: &str, to: &str) -> Result<(), &'static str> {
183    unsafe extern "C" {
184        fn rename(from: *const c_char, to: *const c_char) -> i32;
185    }
186    let (Some(f), Some(t)) = (c_path(from), c_path(to)) else {
187        return Err("names a path holding a NUL byte");
188    };
189    // SAFETY: both strings are NUL-terminated and live for the call.
190    match unsafe { rename(f.as_ptr().cast(), t.as_ptr().cast()) } {
191        0 => Ok(()),
192        _ => Err("cannot be renamed"),
193    }
194}
195
196/// Set `$name` to `value` for this process — `std::env::set_var`.
197///
198/// # Safety
199///
200/// The process must be single-threaded, or no other thread may read or write
201/// the environment during the call: `setenv` is not thread-safe, which is why
202/// `std::env::set_var` is `unsafe` too. Its callers run in the boot funnel,
203/// before any executor or sched task exists.
204#[cfg(feature = "alloc")]
205pub unsafe fn set_var(name: &str, value: &str) {
206    unsafe extern "C" {
207        fn setenv(name: *const c_char, value: *const c_char, overwrite: i32) -> i32;
208    }
209    let (Some(n), Some(v)) = (c_path(name), c_path(value)) else {
210        return;
211    };
212    // SAFETY: both strings are NUL-terminated; the caller upholds the
213    // single-threaded condition.
214    unsafe { setenv(n.as_ptr().cast(), v.as_ptr().cast(), 1) };
215}
216
217/// The file name of this process's executable (`/proc/self/exe`'s last
218/// component) — what `std::env::current_exe()` + `file_name()` gave. `None`
219/// when the link cannot be read.
220#[cfg(feature = "alloc")]
221pub fn exe_name() -> Option<alloc::string::String> {
222    unsafe extern "C" {
223        fn readlink(path: *const c_char, buf: *mut c_char, len: usize) -> isize;
224    }
225    let mut buf = [0u8; 4096];
226    // SAFETY: the path is NUL-terminated; `readlink` writes at most
227    // `buf.len()` bytes and returns how many (it does not NUL-terminate).
228    let n = unsafe {
229        readlink(
230            c"/proc/self/exe".as_ptr(),
231            buf.as_mut_ptr().cast(),
232            buf.len(),
233        )
234    };
235    let full = core::str::from_utf8(buf.get(..usize::try_from(n).ok()?)?).ok()?;
236    Some(alloc::string::String::from(
237        full.rsplit('/').next().unwrap_or(full),
238    ))
239}
240
241/// A key unique to the calling thread among live threads — the address a
242/// `thread_local!` would give, without `std`. `pthread_t` on Linux is the
243/// thread's descriptor address.
244pub fn thread_key() -> usize {
245    unsafe extern "C" {
246        fn pthread_self() -> usize;
247    }
248    // SAFETY: `pthread_self` has no preconditions and cannot fail.
249    unsafe { pthread_self() }
250}
251
252/// End the process with `code`, running `atexit` handlers and flushing stdio —
253/// `std::process::exit`.
254pub fn exit(code: i32) -> ! {
255    unsafe extern "C" {
256        fn exit(code: i32) -> !;
257    }
258    // SAFETY: `exit` has no preconditions; it does not return.
259    unsafe { exit(code) }
260}
261
262/// **The** answer to "which RMW backend did the user select" — one reader, one
263/// semantic, for every consumer.
264///
265/// This variable had FOUR readers with THREE
266/// semantics: `Executor::open` read it as raw OS bytes, `nros`'s
267/// `open_session` as a UTF-8 string filtered for empty, `nros-c`'s entry as a
268/// string passed through EVEN WHEN EMPTY, and `nros::init` as a string with an
269/// `RMW_IMPLEMENTATION` fallback the other three did not have. "Which backend
270/// did the user ask for" had four answers in one process.
271///
272/// Two decisions are baked in, and both are deliberate:
273///
274/// * **`$NROS_RMW` only.** `$RMW_IMPLEMENTATION` is NOT folded in, though it
275///   was tempting and one reader did it. The two carry different vocabularies:
276///   this selector is matched against the cffi registry's canonical names
277///   (`zenoh`, `dds`, `cyclonedds`), while `RMW_IMPLEMENTATION` holds ROS names
278///   (`rmw_cyclonedds_cpp`). Feeding a ROS name to `resolve_backend` yields
279///   `Unknown` — an ERROR — where today it is ignored and the unique-backend
280///   path runs. Unifying them without a mapping would convert "ignored" into
281///   "fails to start". The hosted `init` keeps its fallback for the
282///   `Context.rmw` HINT, which is a different quantity.
283/// * **Empty or non-UTF-8 means unset.** A name that is not UTF-8 cannot match
284///   a registry entry, so treating it as absent is what the caller wants.
285///
286/// The return is `heapless::String` rather than `&str` because
287/// `RMW_SELECTOR_CAP` is a real bound, not a guess: it is the capacity of
288/// `Executor::primary_rmw_name`, so a longer value cannot name a registry slot
289/// and is reported as unset rather than truncated into a different backend's
290/// name.
291pub fn rmw_selector() -> Option<nros_core::heapless::String<RMW_SELECTOR_CAP>> {
292    let s = non_empty(var("NROS_RMW"))?;
293    nros_core::heapless::String::try_from(s).ok()
294}
295
296/// The environment as an [`EnvRung`], for [`ExecutorConfig::resolve_with`].
297fn env_rung() -> Result<EnvRung<'static>, BootConfigError> {
298    // phase-484 W8c — a retired alias is REFUSED, never ignored: an ignored
299    // `ZENOH_LOCATOR` dials the default router and reads as "no delivery".
300    // Presence alone refuses (an empty value is still somebody's intent), and
301    // the refusal is logged here so the C / C++ shims, which only get a
302    // return code, still name the replacement. Only presence is tested, so a
303    // non-UTF-8 value still refuses.
304    for &(name, replacement) in RETIRED_ENV_VARS {
305        let mut cname = [0u8; 32];
306        cname[..name.len()].copy_from_slice(name.as_bytes());
307        let cname = CStr::from_bytes_until_nul(&cname).expect("retired env name fits");
308        if raw(cname).is_some() {
309            let err = BootConfigError::RetiredEnvVar { name, replacement };
310            nros_log::log_error!(nros_log::get_logger("nros"), "{}", err);
311            return Err(err);
312        }
313    }
314    // Issue 0330 — a SET locator is the env's answer even when empty; the
315    // active backend substitutes its own default for an empty one.
316    let locator = var("NROS_LOCATOR");
317    let mode = match var("NROS_SESSION_MODE") {
318        Some("peer") => SessionMode::Peer,
319        _ => SessionMode::Client,
320    };
321    let domain_id = match non_empty(var("ROS_DOMAIN_ID")) {
322        // #206 — malformed is an ERROR, not a silent skip. The parse lives
323        // here rather than in the core because only this side has the text.
324        Some(s) => Some(
325            s.trim()
326                .parse::<u32>()
327                .map_err(|_| BootConfigError::DomainIdParse)?,
328        ),
329        None => None,
330    };
331    let rmw = non_empty(var("NROS_RMW")).filter(|s| s.len() <= RMW_SELECTOR_CAP);
332    Ok(EnvRung {
333        locator,
334        domain_id,
335        // Session mode has no baked rung to fall through to, so `Client` is
336        // always the answer when the variable says nothing.
337        mode: Some(mode),
338        // Issue 0794 — an EMPTY name or namespace is not a declaration: `""`
339        // is what an unset one already resolves to.
340        node_name: non_empty(var("NROS_NODE_NAME")),
341        namespace: non_empty(var("NROS_NODE_NAMESPACE")),
342        rmw,
343    })
344}
345
346/// Which rung answered one field, for the boot line.
347fn source(env: bool, baked: bool) -> &'static str {
348    if env {
349        "env"
350    } else if baked {
351        "baked"
352    } else {
353        "default"
354    }
355}
356
357/// The boot line: what each identity field resolved to, and FROM WHERE.
358///
359/// A misspelled variable does nothing, and without this line nothing says so:
360/// the image runs on its baked domain and reads as "no delivery". One line,
361/// short enough for `nros_log`'s 256-byte buffer (a body that does not fit is
362/// dropped, not truncated), so the locator is the field that can be elided.
363fn report(env: &EnvRung<'_>, baked: &BootConfig<'_>, cfg: &ExecutorConfig<'_>) {
364    let locator = if cfg.locator.is_empty() {
365        "(backend default)"
366    } else if cfg.locator.len() > 96 {
367        "(long)"
368    } else {
369        cfg.locator
370    };
371    nros_log::log_info!(
372        nros_log::get_logger("nros"),
373        "boot config: domain {} ({}), locator {} ({}), rmw {} ({})",
374        cfg.domain_id,
375        source(env.domain_id.is_some(), baked.domain_id.is_some()),
376        locator,
377        source(env.locator.is_some(), baked.locator.is_some()),
378        cfg.rmw.unwrap_or("(unique)"),
379        source(env.rmw.is_some(), baked.rmw.is_some()),
380    );
381}
382
383/// The boot-config precedence ladder with the environment on top:
384/// `env (var set) > baked > compiled default`.
385///
386/// Fails loud on invalid identity input (repo rule: a bad domain id at boot is
387/// a configuration error, never a silent domain-0 node). FFI shims that need a
388/// return code call [`try_resolve_hosted`].
389pub fn resolve_hosted<'a>(baked: BootConfig<'a>) -> ExecutorConfig<'a> {
390    match try_resolve_hosted(baked) {
391        Ok(cfg) => cfg,
392        Err(e) => panic!("nros boot-config resolution failed: {e}"),
393    }
394}
395
396/// Fallible [`resolve_hosted`] — returns [`BootConfigError`] instead of
397/// panicking, so the C / C++ FFI shims can surface a return code.
398///
399/// - `ROS_DOMAIN_ID` set but non-numeric → `DomainIdParse` (the older C++
400///   header silently collapsed this to domain 0; the resolver silently ignored
401///   it — both were wrong).
402/// - any resolved domain id > `DOMAIN_ID_MAX` → `DomainIdRange`, INCLUDING a
403///   baked one (the DDS backend would only fail later).
404///
405/// Logs one line naming each field's source (`report`).
406pub fn try_resolve_hosted<'a>(
407    baked: BootConfig<'a>,
408) -> Result<ExecutorConfig<'a>, BootConfigError> {
409    let env = env_rung()?;
410    let cfg = ExecutorConfig::try_resolve_with(baked, Some(env))?;
411    report(&env, &baked, &cfg);
412    Ok(cfg)
413}
414
415/// Where the environment overrides a value the image's
416/// `system.toml` STATED, each as `(env, stated)`. Only a value both sides
417/// state and that differs is reported: an unstated one has nothing to
418/// override, and an equal one changes nothing.
419#[derive(Debug, Default, PartialEq, Eq)]
420pub struct StatementOverrides<'a> {
421    /// `$ROS_DOMAIN_ID` against `domain_id`.
422    pub domain_id: Option<(u32, u32)>,
423    /// `$NROS_LOCATOR` against `locator`.
424    pub locator: Option<(&'a str, &'a str)>,
425}
426
427/// The pure decision behind [`warn_env_overrides_statement`].
428pub fn env_overrides_statement<'a>(
429    stated: &BootConfig<'a>,
430    env: &EnvRung<'a>,
431) -> StatementOverrides<'a> {
432    StatementOverrides {
433        domain_id: match (env.domain_id, stated.domain_id) {
434            (Some(e), Some(s)) if e != s => Some((e, s)),
435            _ => None,
436        },
437        locator: match (env.locator, stated.locator) {
438            (Some(e), Some(s)) if e != s => Some((e, s)),
439            _ => None,
440        },
441    }
442}
443
444/// On a host the environment WINS over what the image's
445/// `system.toml` states (a user ruling, for testing convenience), and says so
446/// at boot, one warning per field, through `nros_log`.
447///
448/// `stated` is the image's statement and nothing else, which is why only the
449/// `linux` board and the host C/C++ runners call this, where the baked rung
450/// IS the statement. An RTOS simulator's baked rung is its board config
451/// whether or not anything was stated, so it would report a default as a
452/// statement. A malformed environment is not reported here: the resolver
453/// refuses it, and says why, right after.
454pub fn warn_env_overrides_statement(stated: &BootConfig<'_>) {
455    let Ok(env) = env_rung() else {
456        return;
457    };
458    let o = env_overrides_statement(stated, &env);
459    if let Some((e, s)) = o.domain_id {
460        nros_log::log_warn!(
461            nros_log::get_logger("nros"),
462            "ROS_DOMAIN_ID={} overrides system.toml's domain_id={}",
463            e,
464            s
465        );
466    }
467    if let Some((e, s)) = o.locator {
468        nros_log::log_warn!(
469            nros_log::get_logger("nros"),
470            "NROS_LOCATOR={} overrides system.toml's locator={}",
471            e,
472            s
473        );
474    }
475}
476
477/// `ExecutorConfig::from_env()`, as an extension trait.
478///
479/// This was an inherent method on `ExecutorConfig`, which is
480/// defined in `nros-node`; an inherent method cannot be moved to another crate
481/// and keep its spelling, and the spelling is what ~26 call sites (most of them
482/// user-facing native examples) are written against. A trait keeps
483/// `ExecutorConfig::from_env()` working wherever it is in scope — the
484/// [`prelude`](crate::prelude) carries it, so a consumer that already writes
485/// `use nros::prelude::*` changes nothing at all.
486#[cfg(feature = "env")]
487pub trait ExecutorConfigEnvExt {
488    /// Create a configuration from environment variables.
489    ///
490    /// Reads:
491    /// - `NROS_LOCATOR` — Middleware locator. Unset ⇒ empty (issue 0330: the
492    ///   active RMW backend applies its own default; e.g. zenoh dials
493    ///   `nros_rmw_zenoh::DEFAULT_LOCATOR`). The retired name `ZENOH_LOCATOR`
494    ///   is refused (phase-484 W8c) — see [`BootConfigError::RetiredEnvVar`].
495    /// - `ROS_DOMAIN_ID` — ROS 2 domain ID (default: `0`).
496    /// - `NROS_SESSION_MODE` — `"client"` or `"peer"` (default: `"client"`).
497    ///   The retired name `ZENOH_MODE` is refused (phase-484 W8c).
498    /// - `NROS_RMW` — the backend selector, through [`rmw_selector`]. issue
499    ///   0687: `Executor::open` used to read this itself; it now takes
500    ///   `ExecutorConfig::rmw`, so a config built here still selects the
501    ///   backend the user named.
502    ///
503    /// The returned `&'static str` fields point into the process environment,
504    /// read live on every call.
505    ///
506    /// **Panics** on a malformed or out-of-range `$ROS_DOMAIN_ID` or a set
507    /// retired alias (`ZENOH_LOCATOR` / `ZENOH_MODE`), like
508    /// [`resolve_hosted`] and the C / C++ entries. A boot identity that cannot
509    /// be resolved is a configuration error; the alternative is a node silently
510    /// running on domain 0, which is what issue #206 removed everywhere else.
511    fn from_env() -> ExecutorConfig<'static>;
512}
513
514#[cfg(feature = "env")]
515impl ExecutorConfigEnvExt for ExecutorConfig<'static> {
516    fn from_env() -> ExecutorConfig<'static> {
517        // issue 0687 — `from_env` IS `resolve_hosted` with nothing baked. The
518        // one field that does NOT come from the rung is `node_name`: `from_env`
519        // has never honoured `$NROS_NODE_NAME` (its doc lists what it reads),
520        // and callers chain `.node_name(..)` immediately.
521        ExecutorConfig {
522            node_name: "node",
523            ..resolve_hosted(BootConfig::default())
524        }
525    }
526}
527
528/// Process-wide mutex that serialises every test that touches the process
529/// environment — the ones that MUTATE it (`EnvGuard` below) and the ones that
530/// only READ it through `init()` / `Context::from_env()` (`init.rs`).
531///
532/// `cargo test` runs `#[test]`s in parallel within a single binary by default,
533/// and the reader reads the live environment on every call. So a reader that
534/// does not hold this lock can
535/// observe a sibling's `ROS_DOMAIN_ID=abc` halfway through: `init.rs`'s
536/// `plain_args_pass_through_to_init` compared two reads and got `Ok(..)` vs
537/// `Err(EnvParseFailed)` under `just ci gate`. It lived in `env.rs`'s private
538/// test module, so the readers in `init.rs` could not take it. (`cargo
539/// nextest` runs each test in its own process, so the lock is uncontended
540/// there, but taking it is still correct.)
541///
542/// Poison-TOLERANT, deliberately: three tests assert that a bad
543/// `$ROS_DOMAIN_ID` panics, and a panic while this guard is alive poisons the
544/// mutex — which would then fail every LATER test for a reason that has
545/// nothing to do with what it asserts (measured: 3 intended failures became
546/// 8). The data behind the lock is `()`; there is no invariant a panic could
547/// have broken.
548#[cfg(all(test, feature = "env"))]
549pub(crate) fn test_env_lock() -> std::sync::MutexGuard<'static, ()> {
550    static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
551    LOCK.get_or_init(|| std::sync::Mutex::new(()))
552        .lock()
553        .unwrap_or_else(|e| e.into_inner())
554}
555
556#[cfg(all(test, feature = "env"))]
557mod tests {
558    use super::*;
559
560    /// Issue 2714's user ruling, the whole grid: the environment overriding
561    /// a value is reported exactly when BOTH state it and they differ — for
562    /// the domain and the locator alike, each on its own.
563    #[test]
564    fn an_override_is_reported_exactly_when_both_state_it_and_differ() {
565        let env = |d: Option<u32>, l: Option<&'static str>| EnvRung {
566            domain_id: d,
567            locator: l,
568            ..Default::default()
569        };
570        let stated = |d: Option<u32>, l: Option<&'static str>| BootConfig {
571            domain_id: d,
572            locator: l,
573            ..Default::default()
574        };
575        for (e, st, want) in [
576            (None, None, None),
577            (Some(5), None, None),
578            (None, Some(7), None),
579            (Some(7), Some(7), None),
580            (Some(5), Some(7), Some((5, 7))),
581            (Some(5), Some(0), Some((5, 0))),
582        ] {
583            assert_eq!(
584                env_overrides_statement(&stated(st, None), &env(e, None)).domain_id,
585                want,
586                "domain: env {e:?}, stated {st:?}"
587            );
588        }
589        for (e, st, want) in [
590            (None, None, None),
591            (Some("tcp/e:1"), None, None),
592            (None, Some("tcp/s:2"), None),
593            (Some("tcp/s:2"), Some("tcp/s:2"), None),
594            (
595                Some("tcp/e:1"),
596                Some("tcp/s:2"),
597                Some(("tcp/e:1", "tcp/s:2")),
598            ),
599        ] {
600            assert_eq!(
601                env_overrides_statement(&stated(None, st), &env(None, e)).locator,
602                want,
603                "locator: env {e:?}, stated {st:?}"
604            );
605        }
606        // Each field on its own: a differing domain says nothing about an
607        // agreeing locator.
608        let both = env_overrides_statement(
609            &stated(Some(7), Some("tcp/s:2")),
610            &env(Some(5), Some("tcp/s:2")),
611        );
612        assert_eq!(
613            both,
614            StatementOverrides {
615                domain_id: Some((5, 7)),
616                locator: None
617            }
618        );
619    }
620
621    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
622        super::test_env_lock()
623    }
624
625    /// RAII guard that saves and restores a single env var.
626    struct EnvGuard {
627        key: &'static str,
628        prev: Option<std::ffi::OsString>,
629    }
630
631    impl EnvGuard {
632        fn set(key: &'static str, value: &str) -> Self {
633            let prev = std::env::var_os(key);
634            // SAFETY: serialised via env_lock().
635            unsafe { std::env::set_var(key, value) };
636            Self { key, prev }
637        }
638
639        fn unset(key: &'static str) -> Self {
640            let prev = std::env::var_os(key);
641            // SAFETY: serialised via env_lock().
642            unsafe { std::env::remove_var(key) };
643            Self { key, prev }
644        }
645    }
646
647    impl Drop for EnvGuard {
648        fn drop(&mut self) {
649            // SAFETY: serialised via env_lock().
650            unsafe {
651                match &self.prev {
652                    Some(v) => std::env::set_var(self.key, v),
653                    None => std::env::remove_var(self.key),
654                }
655            }
656        }
657    }
658
659    /// `resolve_hosted(BootConfig::default())` must be field-for-field
660    /// identical to `from_env()`, regardless of what env vars are set.
661    #[test]
662    fn noop_resolve_matches_from_env() {
663        let _g = env_lock();
664
665        let resolved = resolve_hosted(BootConfig::default());
666        let env_cfg = ExecutorConfig::from_env();
667
668        assert_eq!(resolved.locator, env_cfg.locator);
669        assert_eq!(resolved.mode, env_cfg.mode);
670        assert_eq!(resolved.domain_id, env_cfg.domain_id);
671        assert_eq!(resolved.node_name, env_cfg.node_name);
672        assert_eq!(resolved.namespace, env_cfg.namespace);
673        assert_eq!(resolved.rmw, env_cfg.rmw);
674    }
675
676    #[test]
677    fn env_overrides_baked_on_hosted() {
678        let _g = env_lock();
679        let _e = EnvGuard::set("NROS_LOCATOR", "tcp/env:7447");
680
681        let baked = BootConfig {
682            locator: Some("tcp/baked:9999"),
683            ..Default::default()
684        };
685        let resolved = resolve_hosted(baked);
686
687        // Issue 0607 — the exact env string is observable: the reader has no
688        // process-global cache for an earlier test to have frozen.
689        assert_eq!(
690            resolved.locator, "tcp/env:7447",
691            "env locator must win over baked, with its own value"
692        );
693    }
694
695    #[test]
696    fn baked_used_when_env_unset_on_hosted() {
697        let _g = env_lock();
698        let _e1 = EnvGuard::unset("NROS_LOCATOR");
699
700        let baked = BootConfig {
701            locator: Some("tcp/baked-only:8888"),
702            ..Default::default()
703        };
704        let resolved = resolve_hosted(baked);
705
706        assert_eq!(
707            resolved.locator, "tcp/baked-only:8888",
708            "baked locator must be used when env var is absent"
709        );
710    }
711
712    #[test]
713    fn per_field_independence_baked_name_env_locator() {
714        let _g = env_lock();
715        let _e = EnvGuard::set("NROS_LOCATOR", "tcp/env:7447");
716        let _n = EnvGuard::unset("NROS_NODE_NAME");
717
718        let baked = BootConfig {
719            node_name: Some("my_talker"),
720            ..Default::default()
721        };
722        let resolved = resolve_hosted(baked);
723
724        assert_eq!(resolved.locator, "tcp/env:7447");
725        assert_eq!(
726            resolved.node_name, "my_talker",
727            "baked node_name must apply even when locator comes from env"
728        );
729    }
730
731    #[test]
732    fn try_resolve_malformed_domain_env_errors() {
733        let _l = env_lock();
734        let _g = EnvGuard::set("ROS_DOMAIN_ID", "not-a-number");
735        let err = match try_resolve_hosted(BootConfig::default()) {
736            Err(e) => e,
737            Ok(_) => panic!("expected DomainIdParse error"),
738        };
739        assert_eq!(err, BootConfigError::DomainIdParse);
740    }
741
742    /// The retired name of `replacement` in [`RETIRED_ENV_VARS`] (the table is
743    /// sorted by the replacing row's name, so a position names nothing).
744    fn alias_of(replacement: &str) -> &'static str {
745        RETIRED_ENV_VARS
746            .iter()
747            .find(|(_, r)| *r == replacement)
748            .map(|(a, _)| *a)
749            .expect("a retired alias of the replacement")
750    }
751
752    /// RFC-0140 D4 (phase-581 W6) -- EVERY `run:` retirement refuses the boot,
753    /// naming its replacement: generated from the registry's table, so a new
754    /// retirement (`XRCE_SERIAL_BAUD`, the Cyclone test controls) is a new case.
755    #[test]
756    fn every_retired_run_time_name_is_refused_naming_its_replacement() {
757        let _l = env_lock();
758        let _guards: alloc::vec::Vec<_> = RETIRED_ENV_VARS
759            .iter()
760            .map(|&(a, _)| EnvGuard::unset(a))
761            .collect();
762        assert!(RETIRED_ENV_VARS.len() >= 5, "{RETIRED_ENV_VARS:?}");
763        for &(name, replacement) in RETIRED_ENV_VARS {
764            let _set = EnvGuard::set(name, "1");
765            let err = match try_resolve_hosted(BootConfig::default()) {
766                Err(e) => e,
767                Ok(_) => panic!("{name} set: expected RetiredEnvVar"),
768            };
769            assert_eq!(err, BootConfigError::RetiredEnvVar { name, replacement });
770            assert!(alloc::format!("{err}").contains(replacement), "{err}");
771        }
772    }
773
774    /// phase-484 W8c — a retired alias REFUSES, naming its replacement, and
775    /// does so even beside a canonical value (half-migrated env is still a
776    /// mistake somebody should hear about).
777    #[test]
778    fn retired_zenoh_locator_is_refused_naming_nros_locator() {
779        let _l = env_lock();
780        let locator_alias = alias_of("NROS_LOCATOR");
781        let mode_alias = alias_of("NROS_SESSION_MODE");
782        let _a = EnvGuard::set(locator_alias, "tcp/legacy:7447");
783        let _b = EnvGuard::unset("NROS_LOCATOR");
784        let _c = EnvGuard::unset(mode_alias);
785        let err = match try_resolve_hosted(BootConfig::default()) {
786            Err(e) => e,
787            Ok(cfg) => panic!("expected RetiredEnvVar, resolved {:?}", cfg.locator),
788        };
789        assert_eq!(
790            err,
791            BootConfigError::RetiredEnvVar {
792                name: locator_alias,
793                replacement: "NROS_LOCATOR"
794            }
795        );
796        let msg = alloc::format!("{err}");
797        assert!(msg.contains("NROS_LOCATOR"), "{msg}");
798
799        let _d = EnvGuard::set("NROS_LOCATOR", "tcp/canonical:7447");
800        assert!(try_resolve_hosted(BootConfig::default()).is_err());
801    }
802
803    #[test]
804    fn retired_zenoh_mode_is_refused_naming_nros_session_mode() {
805        let _l = env_lock();
806        let locator_alias = alias_of("NROS_LOCATOR");
807        let mode_alias = alias_of("NROS_SESSION_MODE");
808        let _a = EnvGuard::unset(locator_alias);
809        let _b = EnvGuard::set(mode_alias, "peer");
810        let err = match try_resolve_hosted(BootConfig::default()) {
811            Err(e) => e,
812            Ok(_) => panic!("expected RetiredEnvVar"),
813        };
814        assert_eq!(
815            err,
816            BootConfigError::RetiredEnvVar {
817                name: mode_alias,
818                replacement: "NROS_SESSION_MODE"
819            }
820        );
821    }
822
823    /// Positive control for the two refusals above: the canonical name alone
824    /// resolves, with its own value.
825    #[test]
826    fn canonical_nros_locator_resolves_when_no_retired_alias_set() {
827        let _l = env_lock();
828        let _a = EnvGuard::unset(alias_of("NROS_LOCATOR"));
829        let _b = EnvGuard::unset(alias_of("NROS_SESSION_MODE"));
830        let _c = EnvGuard::set("NROS_LOCATOR", "tcp/canonical:7447");
831        let cfg = try_resolve_hosted(BootConfig::default()).expect("canonical resolves");
832        assert_eq!(cfg.locator, "tcp/canonical:7447");
833    }
834
835    #[test]
836    fn try_resolve_domain_env_over_max_errors() {
837        let _l = env_lock();
838        let _g = EnvGuard::set("ROS_DOMAIN_ID", "233");
839        let err = match try_resolve_hosted(BootConfig::default()) {
840            Err(e) => e,
841            Ok(_) => panic!("expected DomainIdRange error"),
842        };
843        assert_eq!(err, BootConfigError::DomainIdRange);
844    }
845
846    #[test]
847    fn try_resolve_node_name_env_rung() {
848        let _l = env_lock();
849        let _g = EnvGuard::set("NROS_NODE_NAME", "env_node");
850        let baked = BootConfig {
851            node_name: Some("baked_node"),
852            ..BootConfig::default()
853        };
854        let cfg = match try_resolve_hosted(baked) {
855            Ok(c) => c,
856            Err(e) => panic!("resolve failed: {e}"),
857        };
858        assert_eq!(
859            cfg.node_name, "env_node",
860            "env rung must override baked with its own value"
861        );
862    }
863
864    /// issue 0794 — the hosted edge fills the namespace rung.
865    ///
866    /// Before, `EnvRung` had no namespace field, so this variable could not
867    /// exist: a hosted node's namespace came from the baked rung or from a
868    /// hand-written `ExecutorConfig::namespace(..)` — the per-board lore
869    /// RFC-0045 exists to abolish.
870    #[test]
871    fn try_resolve_namespace_env_rung() {
872        let _l = env_lock();
873        let baked = BootConfig {
874            namespace: Some("/baked"),
875            ..BootConfig::default()
876        };
877
878        let g = EnvGuard::set("NROS_NODE_NAMESPACE", "/robot1");
879        let cfg = try_resolve_hosted(baked).expect("resolve ok");
880        assert_eq!(
881            cfg.namespace, "/robot1",
882            "env rung must override the baked namespace with its own value"
883        );
884        drop(g);
885
886        // Unset falls through to baked, which is the rung below it.
887        let _g = EnvGuard::unset("NROS_NODE_NAMESPACE");
888        let cfg = try_resolve_hosted(baked).expect("resolve ok");
889        assert_eq!(cfg.namespace, "/baked");
890
891        // EMPTY is unset, not "override back to root": `""` is already what an
892        // unset namespace resolves to, so honouring it would give `NROS_NODE_
893        // NAMESPACE=` a meaning no caller can distinguish from absence.
894        let _g = EnvGuard::set("NROS_NODE_NAMESPACE", "");
895        let cfg = try_resolve_hosted(baked).expect("resolve ok");
896        assert_eq!(cfg.namespace, "/baked");
897    }
898
899    /// issue 0687 — the selector reaches the config, which is how
900    /// `Executor::open` still honours `$NROS_RMW` now that it does not read the
901    /// environment itself. Both halves are asserted: a set value arrives, and
902    /// an EMPTY value means unset rather than "a backend named the empty
903    /// string" (which is what `nros-c` used to pass through).
904    #[test]
905    fn selector_reaches_the_config() {
906        let _l = env_lock();
907
908        let _g = EnvGuard::set("NROS_RMW", "cyclonedds");
909        assert_eq!(rmw_selector().as_deref(), Some("cyclonedds"));
910        assert_eq!(
911            ExecutorConfig::from_env().rmw,
912            Some("cyclonedds"),
913            "from_env must carry the selector"
914        );
915        assert_eq!(
916            resolve_hosted(BootConfig::default()).rmw,
917            Some("cyclonedds")
918        );
919
920        let _g = EnvGuard::set("NROS_RMW", "");
921        assert_eq!(rmw_selector(), None, "empty means unset");
922        assert_eq!(ExecutorConfig::from_env().rmw, None);
923    }
924
925    /// issue 0687 — `from_env` and `resolve_hosted(default)` are the same
926    /// resolution, and this asserts the fields the type does not force.
927    #[test]
928    fn from_env_is_resolve_hosted_with_nothing_baked() {
929        let _l = env_lock();
930        let _g = EnvGuard::set("NROS_LOCATOR", "tcp/agree:7447");
931        let _d = EnvGuard::set("ROS_DOMAIN_ID", "42");
932
933        let a = ExecutorConfig::from_env();
934        let b = resolve_hosted(BootConfig::default());
935        assert_eq!(a.locator, b.locator);
936        assert_eq!(a.domain_id, b.domain_id);
937        assert_eq!(a.mode, b.mode);
938        assert_eq!(a.rmw, b.rmw);
939        assert_eq!(a.namespace, b.namespace);
940        // The one deliberate divergence: `from_env` does not take the node name
941        // from the environment, and never has.
942        assert_eq!(a.node_name, "node");
943    }
944
945    /// A malformed `$ROS_DOMAIN_ID` must fail LOUD here, as it does for
946    /// `resolve_hosted` and the C / C++ entries. It used to resolve to domain 0
947    /// silently — the #206 defect, surviving on this one path.
948    #[test]
949    #[should_panic(expected = "boot-config resolution failed")]
950    fn from_env_rejects_a_malformed_domain() {
951        let _l = env_lock();
952        let _g = EnvGuard::set("ROS_DOMAIN_ID", "not-a-number");
953        let _ = ExecutorConfig::from_env();
954    }
955
956    /// …and an out-of-range one, which the same path used to coerce to 0.
957    #[test]
958    #[should_panic(expected = "boot-config resolution failed")]
959    fn from_env_rejects_an_out_of_range_domain() {
960        let _l = env_lock();
961        let _g = EnvGuard::set("ROS_DOMAIN_ID", "300");
962        let _ = ExecutorConfig::from_env();
963    }
964
965    /// A selector longer than the executor's identity capacity cannot name a
966    /// registry slot, so it is unset rather than truncated into some other
967    /// backend's name.
968    #[test]
969    fn overlong_selector_is_unset_not_truncated() {
970        let _l = env_lock();
971        let long = "x".repeat(RMW_SELECTOR_CAP + 1);
972        let _g = EnvGuard::set("NROS_RMW", &long);
973        assert_eq!(rmw_selector(), None);
974    }
975}