Skip to main content

nros_platform/board/
runtime.rs

1//! [`RuntimeCtx`] — Phase 212.N.1.
2//!
3//! Per-invocation runtime context handed to `BoardEntry::run`'s
4//! `setup` callback. Carries the overlay knobs the codegen
5//! `run_plan(runtime)` body reads:
6//!
7//! - **params** — `(key, value)` pairs from launch XML
8//!   `<param name="…" value="…"/>`, projected here by `nros sync` at BUILD
9//!   time. NOT from `--ros-args -p k:=v`: a generated entry reads no argv,
10//!   and the hosted `nros::init_with_args` parse refuses `-p` rather than
11//!   pretending to honour it (runtime parameters are RFC-0015 §9's channel).
12//! - **remaps** — `(from, to)` topic/service renames, from launch
13//!   `<remap from= to=/>` by the same build-time projection.
14//! - **env** — environment-style key/value pairs (POSIX `getenv`
15//!   shape) accessible from no_std boards via this struct rather
16//!   than a `libc::getenv` call.
17//! - **runtime** — `&mut dyn NodeDispatchRuntime` sink the
18//!   codegen-emitted `run_plan(runtime)` body forwards each Node
19//!   pkg's `register(runtime)` call into (Phase 212.N.7 step-3.2).
20//!   Populated by each `BoardEntry::run` impl after opening its
21//!   executor; defaults to a no-op sink when constructed via
22//!   [`RuntimeCtx::with_runtime`].
23//!
24//! ## no_std-safe shape
25//!
26//! Slice-of-tuples kept on the boot stack. No allocation, no
27//! `core::collections`. Codegen owns the storage and passes a
28//! `&mut RuntimeCtx<'_>` whose backing slices live in `static`s.
29//!
30//! Hosted boards (POSIX) may instead build a longer-lived owned
31//! variant on the heap; the trait surface is slice-based so
32//! both shapes work.
33
34use super::dispatch::DispatchStrategy;
35
36/// Layer-clean substitute for `nros::node_metadata::CallbackId` +
37/// `nros::node::CallbackCtx` at the [`NodeDispatchRuntime`] boundary
38/// (Phase 216.A.2). `nros-platform` sits below `nros` in the dep
39/// graph, so the trait surface cannot reference those types
40/// directly. The `nros`-side runtime impl wraps a real
41/// `(CallbackId, &mut CallbackCtx)` pair into this opaque shape
42/// before invoking [`NodeDispatchRuntime::signal_callback`]; the
43/// concrete dispatcher casts `ctx_ptr` back to
44/// `&mut nros::CallbackCtx<'_>` at the call site.
45///
46/// `#[repr(C)]` keeps the layout stable across the (same-language
47/// today, FFI-shaped tomorrow) `nros-platform` ↔ `nros` boundary.
48#[repr(C)]
49pub struct SignaledCallback<'a> {
50    /// Stable identifier string carried by `nros::CallbackId(&'a str)`.
51    pub cb_id: &'a str,
52
53    /// Erased pointer to the `nros::CallbackCtx<'_>` the dispatcher
54    /// will drive. The `nros`-side `NodeDispatchRuntime` impl casts
55    /// back to `&mut nros::CallbackCtx<'_>` before invoking the
56    /// component body.
57    pub ctx_ptr: *mut core::ffi::c_void,
58}
59
60// Phase 258 (Track 2, w5) — the opaque per-Node `extern "Rust" fn()` aliases
61// (`NodeRegisterFn` / `NodeInitFn` / `NodeDispatchFn` / `NodeTickFn`) are gone.
62// They anchored the retired `register_dispatch_slot_dyn` four-fn-ptr bridge
63// (owned-spin declarative register), which the install seam replaced — Rust
64// owned-spin now registers via `RuntimeCtx::runtime.executor_handle()` +
65// `nros::install_node_typed` like the C/C++ typed entries.
66
67/// Node runtime sink the codegen-emitted `run_plan(runtime)`
68/// body talks to (Phase 212.N.7 step-3.1).
69///
70/// Object-safe + `no_std`. The concrete impl
71/// (`ExecutorNodeRuntime` in `nros`) owns the live executor;
72/// `BoardEntry::run` installs it on the per-boot
73/// [`RuntimeCtx::runtime`] slot before invoking the user `setup`
74/// closure.
75///
76/// Phase 214.K.1 — renamed from `NodeRuntime` to disambiguate from
77/// the user-facing `nros::NodeRuntime` metadata-sink trait in
78/// `packages/api/nros/src/node.rs:112`. The two traits live at
79/// different layers (board-side dispatch sink vs user-side metadata
80/// declaration sink) and the previous shared name forced explicit
81/// `nros_platform::` / `nros::` qualification at every use site +
82/// produced confusing `impl NodeRuntime for X` ambiguity. The
83/// phase-214.K.1 `NodeRuntime` deprecation alias was removed in phase-313
84/// W1 (issue #0243); use `NodeDispatchRuntime` directly.
85pub trait NodeDispatchRuntime {
86    /// Drive the underlying executor for at most `timeout_ms`
87    /// milliseconds. `Ok(())` on a clean spin (including timeout);
88    /// `Err(())` if the executor surfaces a spin error.
89    ///
90    /// `Result<_, ()>` is deliberate: the board entry-point callers
91    /// (`nros-board-{freertos,nuttx,threadx}` spin loops) only
92    /// `{:?}`-print the error and `B::exit_failure()` — a typed enum
93    /// would carry no extra info across the trait boundary, since the
94    /// underlying `ExecutorError` from `nros::node_runtime` is mapped
95    /// to `()` at the impl site (`impl NodeDispatchRuntime for
96    /// ExecutorNodeRuntime`). `#[allow]` keeps the surface narrow.
97    #[allow(clippy::result_unit_err)]
98    fn spin_once(&mut self, timeout_ms: u32) -> Result<(), ()>;
99
100    /// Phase 264 W2 — register the REP-2002 lifecycle services on the underlying
101    /// executor + drive boot autostart. `autostart`: 0 = none, 1 = configure,
102    /// 2 = configure+activate. Default no-op (non-executor runtimes, or `nros`
103    /// built without `lifecycle-services`); the `ExecutorNodeRuntime` impl in
104    /// `nros` does the real work behind that feature. `nros::main!` calls this
105    /// (via [`RuntimeCtx::apply_lifecycle`]) when `system.toml` declares
106    /// `[lifecycle]`, mirroring the bake's `generate.rs::render_lifecycle_fn`.
107    /// issue 0460 — the `Err` carries a STATIC REASON, not `()`.
108    ///
109    /// A capability that fails to register is reported by the caller as
110    /// `RuntimeError::NodeRegister("lifecycle")`, which names WHICH capability
111    /// and nothing about WHY. On Zephyr that opaque string was the entire
112    /// diagnostic for three dead entries: the image printed nothing after
113    /// "Network ready" and the cause could only be guessed at. `&'static str`
114    /// rather than a typed error because this trait lives below `nros-node` and
115    /// cannot name `NodeError`.
116    fn apply_lifecycle(&mut self, autostart: u8) -> Result<(), &'static str> {
117        let _ = autostart;
118        Ok(())
119    }
120
121    /// Phase 264 W4b -- register the 6 ROS 2 parameter services on the underlying
122    /// executor and create its volatile RAM param store. Launch `<param>`
123    /// initials are NOT passed here (issue 1272): each node's are seeded on that
124    /// node as it is built, from the `params` slice `nros::main!` sets before
125    /// the node's `register` call. After this,
126    /// `ros2 param list/get/set` works against the running node; reconfigured values
127    /// live in RAM until the next boot (RFC-0004 §10; persistence is out of scope,
128    /// issue 0080). Default no-op (non-executor runtimes, or `nros` built without
129    /// `param-services`); the `ExecutorNodeRuntime` impl in `nros` does the real work
130    /// behind that feature. `nros::main!` calls this (via
131    /// [`RuntimeCtx::apply_param_services`]) when `system.toml` declares
132    /// `[param_services]`, mirroring the bake's `generate.rs::render_param_persistence_fn`.
133    /// issue 0460 — the `Err` carries a STATIC REASON, not `()`.
134    ///
135    /// A capability that fails to register is reported by the caller as
136    /// `RuntimeError::NodeRegister("lifecycle")`, which names WHICH capability
137    /// and nothing about WHY. On Zephyr that opaque string was the entire
138    /// diagnostic for three dead entries: the image printed nothing after
139    /// "Network ready" and the cause could only be guessed at. `&'static str`
140    /// rather than a typed error because this trait lives below `nros-node` and
141    /// cannot name `NodeError`.
142    fn apply_param_services(&mut self) -> Result<(), &'static str> {
143        Ok(())
144    }
145
146    /// phase-461 W6 -- build the parameter STORE and register no service: the
147    /// `params` capability axis. `nros::main!` calls this (via
148    /// [`RuntimeCtx::apply_param_store`]) before the per-node `register` calls
149    /// when the system declares `params` and not `param_services`. Default
150    /// no-op (non-executor runtimes, or `nros` built without `param-store`,
151    /// which the entry const-asserts against).
152    fn apply_param_store(&mut self) -> Result<(), &'static str> {
153        Ok(())
154    }
155
156    /// Phase 258 (Track 2, 2a) — raw `*mut Executor` (as `void*`) for the
157    /// owned-spin entry, so a Node pkg's `register(runtime)` wrapper can call
158    /// the uniform `__nros_component_<pkg>_install(.., executor, ..)` seam
159    /// (`nros::install_node_typed`) instead of the retired opaque-fn-ptr
160    /// `register_dispatch_slot_dyn` bridge. A pointer crosses the
161    /// `nros-platform` → `nros` layering wall cleanly (the concrete
162    /// `ExecutorNodeRuntime` lives in `nros`; this trait can't name it).
163    ///
164    /// Default `null` — sinks without a live executor (e.g.
165    /// [`NullNodeRuntime`], framework-dispatch-only runtimes) report no
166    /// handle; the install path treats null as a registration error.
167    fn executor_handle(&mut self) -> *mut core::ffi::c_void {
168        core::ptr::null_mut()
169    }
170
171    /// phase-446 W6 -- hand the executor the parameters each node's contract
172    /// DECLARES, so a node whose code declares a parameter its contract does
173    /// not (or with another type) refuses the boot naming the node, the
174    /// parameter and the contract.
175    ///
176    /// `nodes` is `(node FQN, contract)`; `params` is `(node FQN, name,
177    /// rcl_interfaces type code)`. Plain tuples because this trait lives below
178    /// `nros-params` and cannot name its types. `nros::main!` calls this before
179    /// any node registers. Default no-op: a runtime with no parameter store
180    /// has nothing to check.
181    fn apply_declared_params(
182        &mut self,
183        nodes: &'static [(&'static str, &'static str)],
184        params: &'static [(&'static str, &'static str, u8)],
185    ) -> Result<(), &'static str> {
186        let _ = (nodes, params);
187        Ok(())
188    }
189
190    /// Observability counters from hosted/runtime tests.
191    ///
192    /// Returns `(all_callbacks, message_callbacks)`. Implementations
193    /// that cannot observe callback dispatch keep the default zeros.
194    fn observed_callback_counts(&self) -> (usize, usize) {
195        (0, 0)
196    }
197
198    /// Hand a signaled callback to the framework-side dispatcher
199    /// (Phase 216.A.2). Only meaningful for `DispatchStrategy::Deferred`
200    /// (RTIC / Embassy) runtimes — `Inline` runtimes drive callbacks
201    /// directly from `spin_once` and never call this. The default panic
202    /// surfaces the mis-wire loudly rather than silently dropping the
203    /// callback signal.
204    fn signal_callback(&mut self, _cb: SignaledCallback<'_>) {
205        panic!("signal_callback not implemented for Inline runtime");
206    }
207
208    /// Declare how this runtime delivers callbacks (Phase 216.A.2).
209    /// `nros check` (Phase 216.D.1) cross-validates each Node pkg's
210    /// `Node::DISPATCH` against this value. Defaults to `Inline` so
211    /// every existing impl reports the historical behavior unchanged.
212    fn dispatch_strategy(&self) -> DispatchStrategy {
213        DispatchStrategy::Inline
214    }
215}
216
217/// No-op [`NodeDispatchRuntime`] for tests / placeholders. Every call
218/// returns `Err(())` so callers that depend on a populated runtime
219/// fail loud rather than silently no-op.
220///
221/// `BoardEntry::run` impls replace this with a real
222/// `ExecutorNodeRuntime`-backed sink before invoking the user
223/// `setup` closure.
224#[derive(Debug, Default)]
225pub struct NullNodeRuntime;
226
227impl NodeDispatchRuntime for NullNodeRuntime {
228    fn spin_once(&mut self, _timeout_ms: u32) -> Result<(), ()> {
229        Err(())
230    }
231}
232
233/// Runtime context handed to `BoardEntry::run(setup)`.
234///
235/// All three overlay slices may be empty. A board's launch overlay
236/// typically populates `params` + `remaps`; `env` is rarely set on
237/// embedded.
238pub struct RuntimeCtx<'a> {
239    /// `<param name=… value=…/>` from launch XML, baked here by
240    /// `nros::main!` from the resolved model at BUILD time.
241    ///
242    /// NOT `-p name:=value` CLI overrides: a generated entry reads no argv,
243    /// and the hosted `nros::init_with_args` parse refuses `-p` loudly, so
244    /// launch is the only producer of these.
245    pub params: &'a [(&'a str, &'a str)],
246
247    /// Topic / service / action remaps: `(from, to)`, set per component by
248    /// `nros::main!` from the model's launch `<remap>` rules (phase-306 W3,
249    /// issue 0255). `nros::node!`'s `register` forwards them into
250    /// `install_node_typed_with_launch`, where entity creation expands
251    /// `~`/relative names and substitutes matching rules (exact-FQN match,
252    /// first rule wins).
253    ///
254    /// These are AUTHORITATIVE rules: `ExecutorSink::create_entity` passes
255    /// them as `nros_node::names::resolve_name_layered`'s authoritative tier,
256    /// beneath which the executor's `--ros-args` rules (installed by a hosted
257    /// `nros::Context`) can only apply to a name the launch projected no rule
258    /// for.
259    pub remaps: &'a [(&'a str, &'a str)],
260
261    /// Environment-style key/value pairs (mostly POSIX). Empty on
262    /// embedded boards.
263    pub env: &'a [(&'a str, &'a str)],
264
265    /// Phase 268 W1 — launch-injected node identity `(name, namespace)` for
266    /// the NEXT `register()` call, set by `nros::main!` per component before
267    /// each `<pkg>::register(runtime)?` call. `None` → the node's own
268    /// `create_node(NodeOptions::new("…"))` default stands (backward-compatible).
269    /// Reset to `None` after every register in the self-bringup arm so a prior
270    /// component's identity never leaks into the next (RFC-0046).
271    pub node_identity: Option<(&'static str, &'static str)>,
272
273    /// Issue #52 — per-node QoS overrides for the NEXT `register()` call, baked
274    /// by `nros::main!` from the model's
275    /// `qos_overrides.<topic>.<role>.<policy>` params. Same reset discipline as
276    /// `params`/`remaps`: `&[]` when the node has none, so a prior component's
277    /// table never leaks into the next.
278    ///
279    /// Primitive `(topic, role, policy, value)` codes — the SAME wire form the
280    /// C and C++ ABIs use — because `nros-platform` sits below `nros-rmw` in the
281    /// layer graph and a typed `QoSOverride` field here would invert it. The
282    /// register seam installs them via `Executor::set_node_qos_overrides`, which
283    /// decodes at entity-create time.
284    pub qos_overrides: &'static [(&'static str, u8, u8, u32)],
285
286    /// Node runtime sink. `BoardEntry::run` populates this with
287    /// the live `ExecutorNodeRuntime`-backed impl before invoking
288    /// the user `setup` closure. The codegen-emitted
289    /// `run_plan(runtime)` body calls `<pkg>::register(runtime)` once per Node
290    /// pkg, which installs through `runtime.executor_handle()` +
291    /// `nros::install_node_typed` (Phase 258, Track 2).
292    ///
293    /// Defaults to a [`NullNodeRuntime`] when the context is
294    /// built via [`RuntimeCtx::with_runtime`]. That sink errors
295    /// every call so test fixtures that forget to wire a real runtime
296    /// fail loud.
297    pub runtime: &'a mut dyn NodeDispatchRuntime,
298}
299
300impl core::fmt::Debug for RuntimeCtx<'_> {
301    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
302        f.debug_struct("RuntimeCtx")
303            .field("params", &self.params)
304            .field("remaps", &self.remaps)
305            .field("qos_overrides", &self.qos_overrides)
306            .field("env", &self.env)
307            .field("node_identity", &self.node_identity)
308            .field("runtime", &"<dyn NodeDispatchRuntime>")
309            .finish()
310    }
311}
312
313impl<'a> RuntimeCtx<'a> {
314    /// Build a [`RuntimeCtx`] with no params / remaps / env and the
315    /// given runtime sink. The common shape `BoardEntry::run`
316    /// constructs after opening its executor.
317    ///
318    /// For test fixtures that don't need a populated runtime, pass a
319    /// `&mut NullNodeRuntime` — every call against the sink
320    /// returns `Err(())`, surfacing the missing wiring.
321    pub fn with_runtime(runtime: &'a mut dyn NodeDispatchRuntime) -> Self {
322        Self {
323            params: &[],
324            remaps: &[],
325            env: &[],
326            node_identity: None,
327            qos_overrides: &[],
328            runtime,
329        }
330    }
331
332    /// Build a [`RuntimeCtx`] with explicit overlay slices + runtime
333    /// sink (Phase 212.N.7 step-3.2).
334    pub fn new(
335        runtime: &'a mut dyn NodeDispatchRuntime,
336        params: &'a [(&'a str, &'a str)],
337        remaps: &'a [(&'a str, &'a str)],
338        env: &'a [(&'a str, &'a str)],
339    ) -> Self {
340        Self {
341            params,
342            remaps,
343            env,
344            node_identity: None,
345            qos_overrides: &[],
346            runtime,
347        }
348    }
349
350    /// Phase 264 W2 — register lifecycle services + drive autostart on the runtime
351    /// sink (forwards to [`NodeDispatchRuntime::apply_lifecycle`]). `nros::main!`
352    /// emits this after the per-node `register` calls when `system.toml` declares
353    /// `[lifecycle]`. No-op unless `nros` is built with `lifecycle-services`.
354    pub fn apply_lifecycle(&mut self, autostart: u8) -> Result<(), &'static str> {
355        self.runtime.apply_lifecycle(autostart)
356    }
357
358    /// Phase 264 W4b -- register the ROS 2 parameter services and create the
359    /// volatile param store (forwards to
360    /// [`NodeDispatchRuntime::apply_param_services`]). `nros::main!` emits this
361    /// BEFORE the per-node `register` calls when `system.toml` declares
362    /// `[param_services]`, so the store exists when each node is built and that
363    /// node's launch `<param>` initials ([`RuntimeCtx::params`]) are seeded on it
364    /// (issue 1272). No-op unless `nros` is built with `param-services`.
365    pub fn apply_param_services(&mut self) -> Result<(), &'static str> {
366        self.runtime.apply_param_services()
367    }
368
369    /// phase-461 W6 -- build the parameter store without its services
370    /// (forwards to [`NodeDispatchRuntime::apply_param_store`]). Emitted where
371    /// [`Self::apply_param_services`] would be, for a system declaring
372    /// `params` alone. No-op unless `nros` is built with `param-store`.
373    pub fn apply_param_store(&mut self) -> Result<(), &'static str> {
374        self.runtime.apply_param_store()
375    }
376
377    /// Lookup a param by name; first match wins. Linear scan
378    /// because the slice is typically small (≤ a dozen entries).
379    pub fn param(&self, name: &str) -> Option<&'a str> {
380        self.params
381            .iter()
382            .find(|(k, _)| *k == name)
383            .map(|(_, v)| *v)
384    }
385
386    /// Lookup a remap by the original (`from`) name; returns the
387    /// rewritten name when remapped, else `None`.
388    pub fn remap(&self, from: &str) -> Option<&'a str> {
389        self.remaps
390            .iter()
391            .find(|(k, _)| *k == from)
392            .map(|(_, v)| *v)
393    }
394
395    /// Lookup an env entry by name.
396    pub fn env_var(&self, name: &str) -> Option<&'a str> {
397        self.env.iter().find(|(k, _)| *k == name).map(|(_, v)| *v)
398    }
399
400    /// phase-446 W6 -- the contract's declared parameters (forwards to
401    /// [`NodeDispatchRuntime::apply_declared_params`]). `nros::main!` emits
402    /// this before the per-node `register` calls.
403    pub fn apply_declared_params(
404        &mut self,
405        nodes: &'static [(&'static str, &'static str)],
406        params: &'static [(&'static str, &'static str, u8)],
407    ) -> Result<(), &'static str> {
408        self.runtime.apply_declared_params(nodes, params)
409    }
410}
411
412/// Error returned by the codegen-emitted `run_plan(runtime)` body
413/// (Phase 212.N.4) and by Node pkg `register(runtime)` wrappers
414/// (Phase 212.N.7 step-2).
415///
416/// `no_std`-safe — variants are string-typed so embedded Entry pkgs
417/// don't need to pull `thiserror`/`anyhow` to print. The
418/// out-of-tree `nros-build` codegen library re-exports this type so
419/// emitted code references `::nros_platform::RuntimeError`, NOT
420/// `::nros_build::RuntimeError` — the embedded Entry pkg's runtime
421/// path then doesn't need `nros-build` as a runtime dep (build-dep
422/// only).
423#[derive(Debug)]
424#[non_exhaustive]
425pub enum RuntimeError {
426    /// A node's `register(runtime)` call failed. The string carries the
427    /// node pkg name.
428    ///
429    /// Phase 212.N.12 hard-renamed the legacy `ComponentRegister` variant
430    /// to `NodeRegister` to match the rclcpp_components / ROS 2 launch.xml
431    /// `<node pkg=…>` convention.
432    NodeRegister(&'static str),
433
434    /// issue 0460 — a CAPABILITY (`[lifecycle]`, `[param_services]`) failed to
435    /// register, with the reason.
436    ///
437    /// Distinct from [`NodeRegister`](Self::NodeRegister) because reusing it
438    /// forced the capability name to be the whole message: three Zephyr entries
439    /// died reporting `NodeRegister("lifecycle")`, which says WHICH capability
440    /// and nothing about WHY, and the image printed nothing else. Two static
441    /// strings rather than a log call, because not every entry crate depends on
442    /// `log` — the first attempt emitted `::log::error!` from the macro and
443    /// broke `linux_rust_qos_entry` with `cannot find 'log' in the crate root`.
444    Capability {
445        /// `"lifecycle"` / `"param_services"`.
446        name: &'static str,
447        /// Why registration failed, from the runtime that attempted it.
448        reason: &'static str,
449    },
450
451    /// Issue 0095 — a node's `register` failed specifically because the
452    /// executor's fixed callback-entry table (`NROS_EXECUTOR_MAX_CBS`) is full.
453    /// Distinct from the opaque [`NodeRegister`](Self::NodeRegister) so the user
454    /// sees the actionable knob. The string carries the node pkg name.
455    ExecutorFull(&'static str),
456
457    /// The hosted Entry spin loop failed or did not observe the
458    /// requested runtime condition before its bounded test deadline.
459    Spin,
460}
461
462impl core::fmt::Display for RuntimeError {
463    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
464        match self {
465            Self::NodeRegister(msg) => write!(f, "node register failed: {msg}"),
466            Self::ExecutorFull(msg) => write!(
467                f,
468                "node '{msg}' register failed: executor callback table full — \
469                 raise NROS_EXECUTOR_MAX_CBS (build-time env, default 4)"
470            ),
471            Self::Capability { name, reason } => write!(
472                f,
473                "capability '[{name}]' failed to register: {reason} — the system \
474                 declares it, so the entry cannot run without it"
475            ),
476            Self::Spin => write!(f, "entry spin failed"),
477        }
478    }
479}