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="…"/>` or `--ros-args -p k:=v`.
9//! - **remaps** — `(from, to)` topic/service renames.
10//! - **env** — environment-style key/value pairs (POSIX `getenv`
11//! shape) accessible from no_std boards via this struct rather
12//! than a `libc::getenv` call.
13//! - **runtime** — `&mut dyn NodeDispatchRuntime` sink the
14//! codegen-emitted `run_plan(runtime)` body forwards each Node
15//! pkg's `register(runtime)` call into (Phase 212.N.7 step-3.2).
16//! Populated by each `BoardEntry::run` impl after opening its
17//! executor; defaults to a no-op sink when constructed via
18//! [`RuntimeCtx::with_runtime`].
19//!
20//! ## no_std-safe shape
21//!
22//! Slice-of-tuples kept on the boot stack. No allocation, no
23//! `core::collections`. Codegen owns the storage and passes a
24//! `&mut RuntimeCtx<'_>` whose backing slices live in `static`s.
25//!
26//! Hosted boards (POSIX) may instead build a longer-lived owned
27//! variant on the heap; the trait surface is slice-based so
28//! both shapes work.
29
30use super::dispatch::DispatchStrategy;
31
32/// Layer-clean substitute for `nros::node_metadata::CallbackId` +
33/// `nros::node::CallbackCtx` at the [`NodeDispatchRuntime`] boundary
34/// (Phase 216.A.2). `nros-platform` sits below `nros` in the dep
35/// graph, so the trait surface cannot reference those types
36/// directly. The `nros`-side runtime impl wraps a real
37/// `(CallbackId, &mut CallbackCtx)` pair into this opaque shape
38/// before invoking [`NodeDispatchRuntime::signal_callback`]; the
39/// concrete dispatcher casts `ctx_ptr` back to
40/// `&mut nros::CallbackCtx<'_>` at the call site.
41///
42/// `#[repr(C)]` keeps the layout stable across the (same-language
43/// today, FFI-shaped tomorrow) `nros-platform` ↔ `nros` boundary.
44#[repr(C)]
45pub struct SignaledCallback<'a> {
46 /// Stable identifier string carried by `nros::CallbackId(&'a str)`.
47 pub cb_id: &'a str,
48
49 /// Erased pointer to the `nros::CallbackCtx<'_>` the dispatcher
50 /// will drive. The `nros`-side `NodeDispatchRuntime` impl casts
51 /// back to `&mut nros::CallbackCtx<'_>` before invoking the
52 /// component body.
53 pub ctx_ptr: *mut core::ffi::c_void,
54}
55
56// Phase 258 (Track 2, w5) — the opaque per-Node `extern "Rust" fn()` aliases
57// (`NodeRegisterFn` / `NodeInitFn` / `NodeDispatchFn` / `NodeTickFn`) are gone.
58// They anchored the retired `register_dispatch_slot_dyn` four-fn-ptr bridge
59// (owned-spin declarative register), which the install seam replaced — Rust
60// owned-spin now registers via `RuntimeCtx::runtime.executor_handle()` +
61// `nros::install_node_typed` like the C/C++ typed entries.
62
63/// Node runtime sink the codegen-emitted `run_plan(runtime)`
64/// body talks to (Phase 212.N.7 step-3.1).
65///
66/// Object-safe + `no_std`. The concrete impl
67/// (`ExecutorNodeRuntime` in `nros`) owns the live executor;
68/// `BoardEntry::run` installs it on the per-boot
69/// [`RuntimeCtx::runtime`] slot before invoking the user `setup`
70/// closure.
71///
72/// Phase 214.K.1 — renamed from `NodeRuntime` to disambiguate from
73/// the user-facing `nros::NodeRuntime` metadata-sink trait in
74/// `packages/core/nros/src/node.rs:112`. The two traits live at
75/// different layers (board-side dispatch sink vs user-side metadata
76/// declaration sink) and the previous shared name forced explicit
77/// `nros_platform::` / `nros::` qualification at every use site +
78/// produced confusing `impl NodeRuntime for X` ambiguity. A
79/// `#[deprecated]` `pub use NodeDispatchRuntime as NodeRuntime;`
80/// re-export sits at the crate module level for one release cycle.
81pub trait NodeDispatchRuntime {
82 /// Drive the underlying executor for at most `timeout_ms`
83 /// milliseconds. `Ok(())` on a clean spin (including timeout);
84 /// `Err(())` if the executor surfaces a spin error.
85 ///
86 /// `Result<_, ()>` is deliberate: the board entry-point callers
87 /// (`nros-board-{freertos,nuttx,threadx}` spin loops) only
88 /// `{:?}`-print the error and `B::exit_failure()` — a typed enum
89 /// would carry no extra info across the trait boundary, since the
90 /// underlying `ExecutorError` from `nros::node_runtime` is mapped
91 /// to `()` at the impl site (`impl NodeDispatchRuntime for
92 /// ExecutorNodeRuntime`). `#[allow]` keeps the surface narrow.
93 #[allow(clippy::result_unit_err)]
94 fn spin_once(&mut self, timeout_ms: u32) -> Result<(), ()>;
95
96 /// Phase 264 W2 — register the REP-2002 lifecycle services on the underlying
97 /// executor + drive boot autostart. `autostart`: 0 = none, 1 = configure,
98 /// 2 = configure+activate. Default no-op (non-executor runtimes, or `nros`
99 /// built without `lifecycle-services`); the `ExecutorNodeRuntime` impl in
100 /// `nros` does the real work behind that feature. `nros::main!` calls this
101 /// (via [`RuntimeCtx::apply_lifecycle`]) when `system.toml` declares
102 /// `[lifecycle]`, mirroring the bake's `generate.rs::render_lifecycle_fn`.
103 #[allow(clippy::result_unit_err)]
104 fn apply_lifecycle(&mut self, autostart: u8) -> Result<(), ()> {
105 let _ = autostart;
106 Ok(())
107 }
108
109 /// Phase 264 W4b — register the 6 ROS 2 parameter services on the underlying
110 /// executor + seed a volatile RAM param store with the launch-baked `<param>`
111 /// initials (`params` is the aggregate `(name, value)` slice, value as the raw
112 /// launch string — the impl infers the `ParameterValue` type). After this,
113 /// `ros2 param list/get/set` works against the running node; reconfigured values
114 /// live in RAM until the next boot (RFC-0004 §10; persistence is out of scope,
115 /// issue 0080). Default no-op (non-executor runtimes, or `nros` built without
116 /// `param-services`); the `ExecutorNodeRuntime` impl in `nros` does the real work
117 /// behind that feature. `nros::main!` calls this (via
118 /// [`RuntimeCtx::apply_param_services`]) when `system.toml` declares
119 /// `[param_services]`, mirroring the bake's `generate.rs::render_param_persistence_fn`.
120 #[allow(clippy::result_unit_err)]
121 fn apply_param_services(&mut self, params: &[(&str, &str)]) -> Result<(), ()> {
122 let _ = params;
123 Ok(())
124 }
125
126 /// Phase 258 (Track 2, 2a) — raw `*mut Executor` (as `void*`) for the
127 /// owned-spin entry, so a Node pkg's `register(runtime)` wrapper can call
128 /// the uniform `__nros_component_<pkg>_install(.., executor, ..)` seam
129 /// (`nros::install_node_typed`) instead of the retired opaque-fn-ptr
130 /// `register_dispatch_slot_dyn` bridge. A pointer crosses the
131 /// `nros-platform` → `nros` layering wall cleanly (the concrete
132 /// `ExecutorNodeRuntime` lives in `nros`; this trait can't name it).
133 ///
134 /// Default `null` — sinks without a live executor (e.g.
135 /// [`NullNodeRuntime`], framework-dispatch-only runtimes) report no
136 /// handle; the install path treats null as a registration error.
137 fn executor_handle(&mut self) -> *mut core::ffi::c_void {
138 core::ptr::null_mut()
139 }
140
141 /// Observability counters from hosted/runtime tests.
142 ///
143 /// Returns `(all_callbacks, message_callbacks)`. Implementations
144 /// that cannot observe callback dispatch keep the default zeros.
145 fn observed_callback_counts(&self) -> (usize, usize) {
146 (0, 0)
147 }
148
149 /// Hand a signaled callback to the framework-side dispatcher
150 /// (Phase 216.A.2). Only meaningful for `DispatchStrategy::Deferred`
151 /// (RTIC / Embassy) runtimes — `Inline` runtimes drive callbacks
152 /// directly from `spin_once` and never call this. The default panic
153 /// surfaces the mis-wire loudly rather than silently dropping the
154 /// callback signal.
155 fn signal_callback(&mut self, _cb: SignaledCallback<'_>) {
156 panic!("signal_callback not implemented for Inline runtime");
157 }
158
159 /// Declare how this runtime delivers callbacks (Phase 216.A.2).
160 /// `nros check` (Phase 216.D.1) cross-validates each Node pkg's
161 /// `Node::DISPATCH` against this value. Defaults to `Inline` so
162 /// every existing impl reports the historical behavior unchanged.
163 fn dispatch_strategy(&self) -> DispatchStrategy {
164 DispatchStrategy::Inline
165 }
166}
167
168/// No-op [`NodeDispatchRuntime`] for tests / placeholders. Every call
169/// returns `Err(())` so callers that depend on a populated runtime
170/// fail loud rather than silently no-op.
171///
172/// `BoardEntry::run` impls replace this with a real
173/// `ExecutorNodeRuntime`-backed sink before invoking the user
174/// `setup` closure.
175#[derive(Debug, Default)]
176pub struct NullNodeRuntime;
177
178impl NodeDispatchRuntime for NullNodeRuntime {
179 fn spin_once(&mut self, _timeout_ms: u32) -> Result<(), ()> {
180 Err(())
181 }
182}
183
184/// Runtime context handed to `BoardEntry::run(setup)`.
185///
186/// All three overlay slices may be empty. A board's launch overlay
187/// typically populates `params` + `remaps`; `env` is rarely set on
188/// embedded.
189pub struct RuntimeCtx<'a> {
190 /// `<param name=… value=…/>` from launch XML, or
191 /// `-p name:=value` CLI overrides.
192 pub params: &'a [(&'a str, &'a str)],
193
194 /// Topic / service / action remaps: `(from, to)`.
195 pub remaps: &'a [(&'a str, &'a str)],
196
197 /// Environment-style key/value pairs (mostly POSIX). Empty on
198 /// embedded boards.
199 pub env: &'a [(&'a str, &'a str)],
200
201 /// Phase 268 W1 — launch-injected node identity `(name, namespace)` for
202 /// the NEXT `register()` call, set by `nros::main!` per component before
203 /// each `<pkg>::register(runtime)?` call. `None` → the node's own
204 /// `create_node(NodeOptions::new("…"))` default stands (backward-compatible).
205 /// Reset to `None` after every register in the self-bringup arm so a prior
206 /// component's identity never leaks into the next (RFC-0046).
207 pub node_identity: Option<(&'static str, &'static str)>,
208
209 /// Node runtime sink. `BoardEntry::run` populates this with
210 /// the live `ExecutorNodeRuntime`-backed impl before invoking
211 /// the user `setup` closure. The codegen-emitted
212 /// `run_plan(runtime)` body calls `<pkg>::register(runtime)` once per Node
213 /// pkg, which installs through `runtime.executor_handle()` +
214 /// `nros::install_node_typed` (Phase 258, Track 2).
215 ///
216 /// Defaults to a [`NullNodeRuntime`] when the context is
217 /// built via [`RuntimeCtx::with_runtime`]. That sink errors
218 /// every call so test fixtures that forget to wire a real runtime
219 /// fail loud.
220 pub runtime: &'a mut dyn NodeDispatchRuntime,
221}
222
223impl core::fmt::Debug for RuntimeCtx<'_> {
224 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
225 f.debug_struct("RuntimeCtx")
226 .field("params", &self.params)
227 .field("remaps", &self.remaps)
228 .field("env", &self.env)
229 .field("node_identity", &self.node_identity)
230 .field("runtime", &"<dyn NodeDispatchRuntime>")
231 .finish()
232 }
233}
234
235impl<'a> RuntimeCtx<'a> {
236 /// Build a [`RuntimeCtx`] with no params / remaps / env and the
237 /// given runtime sink. The common shape `BoardEntry::run`
238 /// constructs after opening its executor.
239 ///
240 /// For test fixtures that don't need a populated runtime, pass a
241 /// `&mut NullNodeRuntime` — every call against the sink
242 /// returns `Err(())`, surfacing the missing wiring.
243 pub fn with_runtime(runtime: &'a mut dyn NodeDispatchRuntime) -> Self {
244 Self {
245 params: &[],
246 remaps: &[],
247 env: &[],
248 node_identity: None,
249 runtime,
250 }
251 }
252
253 /// Build a [`RuntimeCtx`] with explicit overlay slices + runtime
254 /// sink (Phase 212.N.7 step-3.2).
255 pub fn new(
256 runtime: &'a mut dyn NodeDispatchRuntime,
257 params: &'a [(&'a str, &'a str)],
258 remaps: &'a [(&'a str, &'a str)],
259 env: &'a [(&'a str, &'a str)],
260 ) -> Self {
261 Self {
262 params,
263 remaps,
264 env,
265 node_identity: None,
266 runtime,
267 }
268 }
269
270 /// Phase 264 W2 — register lifecycle services + drive autostart on the runtime
271 /// sink (forwards to [`NodeDispatchRuntime::apply_lifecycle`]). `nros::main!`
272 /// emits this after the per-node `register` calls when `system.toml` declares
273 /// `[lifecycle]`. No-op unless `nros` is built with `lifecycle-services`.
274 #[allow(clippy::result_unit_err)]
275 pub fn apply_lifecycle(&mut self, autostart: u8) -> Result<(), ()> {
276 self.runtime.apply_lifecycle(autostart)
277 }
278
279 /// Phase 264 W4b — register the ROS 2 parameter services + seed the volatile
280 /// param store from the launch-baked `<param>` initials (forwards to
281 /// [`NodeDispatchRuntime::apply_param_services`]). `nros::main!` emits this after
282 /// the per-node `register` calls when `system.toml` declares `[param_services]`.
283 /// No-op unless `nros` is built with `param-services`.
284 #[allow(clippy::result_unit_err)]
285 pub fn apply_param_services(&mut self, params: &[(&str, &str)]) -> Result<(), ()> {
286 self.runtime.apply_param_services(params)
287 }
288
289 /// Lookup a param by name; first match wins. Linear scan
290 /// because the slice is typically small (≤ a dozen entries).
291 pub fn param(&self, name: &str) -> Option<&'a str> {
292 self.params
293 .iter()
294 .find(|(k, _)| *k == name)
295 .map(|(_, v)| *v)
296 }
297
298 /// Lookup a remap by the original (`from`) name; returns the
299 /// rewritten name when remapped, else `None`.
300 pub fn remap(&self, from: &str) -> Option<&'a str> {
301 self.remaps
302 .iter()
303 .find(|(k, _)| *k == from)
304 .map(|(_, v)| *v)
305 }
306
307 /// Lookup an env entry by name.
308 pub fn env_var(&self, name: &str) -> Option<&'a str> {
309 self.env.iter().find(|(k, _)| *k == name).map(|(_, v)| *v)
310 }
311}
312
313/// Error returned by the codegen-emitted `run_plan(runtime)` body
314/// (Phase 212.N.4) and by Node pkg `register(runtime)` wrappers
315/// (Phase 212.N.7 step-2).
316///
317/// `no_std`-safe — variants are string-typed so embedded Entry pkgs
318/// don't need to pull `thiserror`/`anyhow` to print. The
319/// out-of-tree `nros-build` codegen library re-exports this type so
320/// emitted code references `::nros_platform::RuntimeError`, NOT
321/// `::nros_build::RuntimeError` — the embedded Entry pkg's runtime
322/// path then doesn't need `nros-build` as a runtime dep (build-dep
323/// only).
324#[derive(Debug)]
325#[non_exhaustive]
326pub enum RuntimeError {
327 /// A node's `register(runtime)` call failed. The string carries the
328 /// node pkg name.
329 ///
330 /// Phase 212.N.12 hard-renamed the legacy `ComponentRegister` variant
331 /// to `NodeRegister` to match the rclcpp_components / ROS 2 launch.xml
332 /// `<node pkg=…>` convention.
333 NodeRegister(&'static str),
334
335 /// Issue 0095 — a node's `register` failed specifically because the
336 /// executor's fixed callback-entry table (`NROS_EXECUTOR_MAX_CBS`) is full.
337 /// Distinct from the opaque [`NodeRegister`](Self::NodeRegister) so the user
338 /// sees the actionable knob. The string carries the node pkg name.
339 ExecutorFull(&'static str),
340
341 /// The hosted Entry spin loop failed or did not observe the
342 /// requested runtime condition before its bounded test deadline.
343 Spin,
344}
345
346impl core::fmt::Display for RuntimeError {
347 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
348 match self {
349 Self::NodeRegister(msg) => write!(f, "node register failed: {msg}"),
350 Self::ExecutorFull(msg) => write!(
351 f,
352 "node '{msg}' register failed: executor callback table full — \
353 raise NROS_EXECUTOR_MAX_CBS (build-time env, default 4)"
354 ),
355 Self::Spin => write!(f, "entry spin failed"),
356 }
357 }
358}