nros/node_runtime.rs
1//! The executor-backed component runtime for nano-ros.
2//!
3//! [`MetadataRecorder`] (the planner sink) records what a [`Component`] /
4//! [`ExecutableNode`] declares. This module is the
5//! missing twin: it binds the same traits to a live [`Executor`] so
6//! a Node pkg can actually run — nodes, publishers,
7//! subscriptions, timers materialise as real executor handles, and
8//! every fired callback dispatches into
9//! [`ExecutableNode::on_callback`] with the right
10//! [`CallbackId`].
11//!
12//! Shape:
13//!
14//! ```ignore
15//! use nros::{Executor, ExecutorConfig};
16//! use nros::node_runtime::ExecutorNodeRuntime;
17//!
18//! let cfg = ExecutorConfig::from_env().node_name("talker_main");
19//! let executor = Executor::open(&cfg).unwrap();
20//! let mut runtime = ExecutorNodeRuntime::from_executor(executor);
21//! let _handle = runtime.register_node::<Talker>().unwrap();
22//! runtime.spin().unwrap();
23//! ```
24//!
25//! Owned-spin / board consumer: the macro-emitted `<pkg>::register(runtime)`
26//! wrapper installs each Node onto the runtime's executor
27//! through the uniform `install_node_typed` seam — the same seam the C/C++
28//! typed entries use. The codegen `run_plan(runtime)` body + `nros::main!`
29//! owned-spin loop drive one `register(runtime)?` per launch-XML `<node>`,
30//! then `runtime.spin()`. (The retired four-fn-ptr BSP-baker
31//! ABI — ~~`register_dispatch_slot`~~ / ~~`nros_run_components`~~ — is gone.)
32//!
33//! ## Coverage today
34//!
35//! Publishers, subscriptions, and repeating timers wire end-to-end:
36//! the live executor delivers callbacks; the bound
37//! [`ExecutableNode::on_callback`] body runs with a
38//! [`CallbackCtx`] backed by the per-component publisher resolver.
39//! Service servers / clients and action servers / clients wire
40//! end-to-end too: `create_entity` registers them on
41//! the executor with C-ABI trampolines that route inbound requests /
42//! goals into the component's `on_callback`, and the tick-time client /
43//! action surface ([`TickCtx`]) is backed by `RuntimeClientDispatch` /
44//! `RuntimeActions` over the live executor. Parameters are still a
45//! follow-up (registration succeeds; param callbacks don't fire yet).
46
47#![cfg(feature = "rmw-cffi")]
48
49// W5-endgame (issue 0843): the DECLARATION is gated too — a bare
50// `extern crate alloc` links the alloc crate into every image and rustc then
51// demands a `#[global_allocator]` even when nothing here allocates. This line
52// is what kept the first heap-free-tier image from linking.
53#[cfg(feature = "alloc")]
54extern crate alloc;
55
56#[cfg(feature = "alloc")]
57use alloc::{boxed::Box, vec::Vec};
58#[cfg(feature = "alloc")]
59use core::time::Duration;
60use core::{
61 cell::{Ref, RefCell, UnsafeCell},
62 marker::PhantomData,
63 mem::MaybeUninit,
64};
65use nros_node::executor::ffi::{
66 ActionClientCoreFfi as _, ActionClientRawHandleFfi as _, ActionServerRawHandleFfi as _,
67};
68
69// Via nros-core's re-export rather than a new direct dependency — every graph
70// containing `nros` would otherwise move (16 leaf lockfiles, measured on W5.1).
71use nros_core::heapless;
72// phase-515 R9: the raw service/client entry points this runtime drives are
73// the executor's FFI surface. Imported, never re-exported.
74use nros_node::executor::ffi::ExecutorFfi as _;
75use portable_atomic::{AtomicUsize, Ordering};
76#[cfg(feature = "alloc")]
77use portable_atomic_util::Arc;
78
79/// phase-391 W5 — entity/callback identifier, fixed-capacity.
80///
81/// Same bound as `nros_node::names::ResolvedName` (`MAX_RESOLVED_NAME_LEN` =
82/// 128): every string these registries hold is a resolved entity id, callback
83/// id, node name or namespace, i.e. name-shaped. An id that does not fit is a
84/// REGISTRATION error, never a truncation.
85type IdStr = heapless::String<{ nros_node::names::MAX_RESOLVED_NAME_LEN }>;
86
87/// W5-endgame alloc-off — nodes one component's `register()` may create.
88/// Components create one node in every in-tree class; 4 leaves room without
89/// costing anything that outlives registration (the sink is a stack local).
90const MAX_SINK_NODES: usize = 4;
91
92// phase-391 W5 (amended by W5-endgame step 2a): the per-cell registry bound,
93// PER KIND, is the `MAX_CELL_ENTITIES` knob — now spelled as `ComponentCell`'s
94// const-parameter DEFAULTS rather than a shared ~~`CELL_REG_CAP`~~ const, so the
95// macro can name tighter per-class bounds while every existing spelling keeps
96// the knob-capped layout. Was `DEFAULT_MAX_METADATA_ENTITIES` (32), borrowed
97// from the metadata twin — but that figure is per-PLAN-shaped and made every
98// cell ~20 KB up front. 8 is per-component-shaped; a component declaring more
99// gets a loud registration error naming `NROS_RUNTIME_MAX_CELL_ENTITIES`.
100
101/// issue 1130 -- a cell registry refused an entity. ONE spelling for all six
102/// sites (four registries, three ctx slabs, minus the overlap), so none of them
103/// can go back to a bare `Runtime`. Logged as well as returned: the install
104/// seam collapses every non-`ExecutorFull` error to `NodeRegister(pkg)`, so the
105/// console line is what a board with no debugger actually shows.
106fn cell_full(kind: &str) -> NodeDeclError {
107 nros_log::log_error!(
108 nros_log::get_logger("nros"),
109 "component cell registry full: this class creates more {} than its \
110 registry holds. Raise the class's ENTITY_BOUNDS, or \
111 NROS_RUNTIME_MAX_CELL_ENTITIES (build-time, default 8; derived from \
112 the image's declared entities when nothing states it).",
113 kind
114 );
115 NodeDeclError::CellRegistryFull
116}
117
118/// Owned copy of a name-shaped `&str`, or the registration error that says
119/// which knob-less bound it burst.
120fn id_str(s: &str) -> Result<IdStr, NodeDeclError> {
121 IdStr::try_from(s).map_err(|_| NodeDeclError::Runtime)
122}
123
124use crate::{
125 EmbeddedRawPublisher, Executor, GoalStatusCode, GoalUuid,
126 node::{
127 ActionExecutor, Callback, CallbackCtx, ClientDispatch, ExecutableNode, NodeContext,
128 NodeDeclError, NodeOptions, NodeResult, PublisherResolver, TickCtx, TimerOp,
129 },
130 node_metadata::{
131 CallbackEffectKind, CallbackId, EntityId, EntityKind, EntityMetadata, NodeId as MetaNodeId,
132 NodeMetadataError,
133 },
134};
135
136// Phase 212.N.7 closing sweep — ~~`component_register_symbol`~~ retired
137// (no live callers after the BSP baker + macro extern emit were
138// removed). The former re-export here is gone.
139
140// =============================================================================
141// Public types
142// =============================================================================
143
144/// Opaque handle returned by
145/// [`ExecutorNodeRuntime::register_node`].
146///
147/// `C` distinguishes handles at the type level so a caller who keeps
148/// the handle can later (post-M.5.a.3) recover a typed mut-state
149/// borrow. For today the handle is purely a witness that registration
150/// succeeded.
151pub struct RegisteredNode<C: ExecutableNode> {
152 component_idx: usize,
153 _phantom: PhantomData<fn() -> C>,
154}
155
156impl<C: ExecutableNode> RegisteredNode<C> {
157 /// Slot index of this component inside the runtime.
158 pub fn slot(&self) -> usize {
159 self.component_idx
160 }
161}
162
163/// Errors returned by the runtime entry points.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub enum ExecutorError {
166 /// One of the components' register / lifecycle calls failed.
167 Node(NodeDeclError),
168 /// The executor's spin loop returned an unexpected error.
169 SpinFailed,
170}
171
172impl From<NodeDeclError> for ExecutorError {
173 fn from(e: NodeDeclError) -> Self {
174 Self::Node(e)
175 }
176}
177
178// =============================================================================
179// Internal slot — type-erases the component's `State` so the runtime
180// can hold a heterogeneous vec.
181// =============================================================================
182
183trait ComponentSlot {
184 fn dispatch(&mut self, cb_id: &str, ctx: &mut CallbackCtx<'_>);
185 fn tick(&mut self, ctx: &mut TickCtx<'_>);
186}
187
188struct TypedSlot<C: ExecutableNode> {
189 state: C::State,
190 _phantom: PhantomData<fn() -> C>,
191}
192
193impl<C: ExecutableNode> ComponentSlot for TypedSlot<C> {
194 fn dispatch(&mut self, cb_id: &str, ctx: &mut CallbackCtx<'_>) {
195 C::on_callback(
196 &mut self.state,
197 Callback::__from_id(CallbackId::new(cb_id)),
198 ctx,
199 );
200 }
201 fn tick(&mut self, ctx: &mut TickCtx<'_>) {
202 C::tick(&mut self.state, ctx);
203 }
204}
205
206// Phase 258 (Track 2, w5) — ~~`BspDispatchSlot`~~ (the type-erased
207// four-fn-ptr BSP dispatch slot) is gone with the retired
208// ~~`register_dispatch_slot`~~ / ~~`nros_run_components`~~ BSP-baker path. The
209// only remaining `ComponentSlot` impl is `TypedSlot<C>` above (used by
210// `register_node` / `register_node_borrowed` / `install_node_typed`).
211
212/// Per-class slot storage the `nros::node!` macro emits.
213///
214/// One `static` of this type per macro expansion, so `C` is CONCRETE at the
215/// emission site and the storage is sized `size_of::<TypedSlot<C>>()` exactly —
216/// no byte-budget guessing on the FFI install path. The type is public API for
217/// the MACRO EMIT only; it never crosses the C ABI (the trampoline keeps its
218/// `(ptr, ptr, ptr) -> i32` shape), which is what keeps the const-generic
219/// parameter legal under the "no const generics on FFI-visible types" rule.
220///
221/// `N` is the per-class INSTANCE cap: the launch path bakes one identity per
222/// plan node and can name the same class twice, so this is an array, not one
223/// slot. Taking past `N` is a registration error (`take` returns `None`), the
224/// same Full shape as the executor's node table. Slots are one-shot — `next`
225/// never rewinds — so storage is never re-initialised under a stale reference.
226pub struct ComponentSlotStorage<
227 C: ExecutableNode,
228 const N: usize = { crate::config::MAX_CLASS_INSTANCES },
229 const PUBS: usize = { crate::config::MAX_CELL_ENTITIES },
230 const SVCS: usize = { crate::config::MAX_CELL_ENTITIES },
231 const ACTC: usize = { crate::config::MAX_CELL_ENTITIES },
232 const ACTS: usize = { crate::config::MAX_CELL_ENTITIES },
233 const SSRV: usize = { crate::config::MAX_CELL_ENTITIES },
234 const TIMS: usize = { crate::config::MAX_CELL_ENTITIES },
235> {
236 slots: [UnsafeCell<MaybeUninit<TypedSlot<C>>>; N],
237 /// W5-endgame step 2b (issue 0857) — the per-instance CELL lives here too,
238 /// so the whole component (state + registries) is `.bss`, not heap. Handed
239 /// out pairwise with its slot by `take`; the cell's `slot` field then
240 /// borrows the sibling region, which is sound because the two arrays are
241 /// distinct `UnsafeCell`s claimed by the same monotonic index.
242 cells: [UnsafeCell<MaybeUninit<ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>>>; N],
243 next: AtomicUsize,
244}
245
246// SAFETY: `take` hands each slot out at most once (monotonic `fetch_add`), so
247// no two references to the same `UnsafeCell` contents ever coexist.
248unsafe impl<
249 C: ExecutableNode,
250 const N: usize,
251 const PUBS: usize,
252 const SVCS: usize,
253 const ACTC: usize,
254 const ACTS: usize,
255 const SSRV: usize,
256 const TIMS: usize,
257> Sync for ComponentSlotStorage<C, N, PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>
258{
259}
260
261impl<
262 C: ExecutableNode,
263 const N: usize,
264 const PUBS: usize,
265 const SVCS: usize,
266 const ACTC: usize,
267 const ACTS: usize,
268 const SSRV: usize,
269 const TIMS: usize,
270> ComponentSlotStorage<C, N, PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>
271{
272 /// Const constructor — the macro emits `static STORE: ... = ...::new();`.
273 #[allow(clippy::new_without_default)]
274 pub const fn new() -> Self {
275 Self {
276 slots: [const { UnsafeCell::new(MaybeUninit::uninit()) }; N],
277 cells: [const { UnsafeCell::new(MaybeUninit::uninit()) }; N],
278 next: AtomicUsize::new(0),
279 }
280 }
281
282 /// Hand out the next uninitialised slot, or `None` past the instance cap.
283 ///
284 /// `clippy::mut_from_ref` fires because a `&mut` derived from a `&self` is
285 /// usually unsound. It is not here, and the reason is already written down
286 /// on the `unsafe impl Sync` above: the monotonic `fetch_add` hands each
287 /// index out at most once, so no two `&mut` to one `UnsafeCell` can coexist,
288 /// and `i >= N` bounds it. Allowed rather than restructured — the lint
289 /// cannot see the atomic, and the invariant is the point of the type.
290 #[allow(clippy::mut_from_ref)]
291 fn take(
292 &'static self,
293 ) -> Option<(
294 &'static mut MaybeUninit<TypedSlot<C>>,
295 &'static mut MaybeUninit<ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>>,
296 )> {
297 let i = self.next.fetch_add(1, Ordering::Relaxed);
298 if i >= N {
299 return None;
300 }
301 // SAFETY: `i` was claimed exactly once by the fetch_add above, so these
302 // are the only references that will ever exist to `slots[i]`'s /
303 // `cells[i]`'s contents; the storage is a `static`, so `'static` is
304 // honest.
305 Some(unsafe { (&mut *self.slots[i].get(), &mut *self.cells[i].get()) })
306 }
307}
308
309/// Placement-init a [`TypedSlot<C>`] into `slot` and erase it.
310///
311/// Both registration paths end here: the FFI path with a slot from the
312/// macro-emitted [`ComponentSlotStorage`], the dynamic path with one carved
313/// from the runtime's caller-supplied backing.
314fn place_slot<C: ExecutableNode>(
315 slot: &'static mut MaybeUninit<TypedSlot<C>>,
316) -> &'static mut dyn ComponentSlot
317where
318 C::State: 'static,
319{
320 slot.write(TypedSlot::<C> {
321 state: C::init(),
322 _phantom: PhantomData,
323 })
324}
325
326/// Issue 2075 — one controllable declared timer in a component cell.
327#[derive(Clone, Copy)]
328struct TimerSlot {
329 /// FNV-1a 64 of the timer's entity id. A hash, not an [`IdStr`]: an id
330 /// string is `MAX_RESOLVED_NAME_LEN` bytes, a row here is 16 + 1.
331 key: u64,
332 handle: crate::HandleId,
333 /// The op a context requested since the last tick, applied by
334 /// [`apply_timer_ops`]. The last request wins.
335 pending: Option<TimerOp>,
336}
337
338/// Issue 2075 — the key a timer's entity id is filed under (FNV-1a 64).
339fn timer_key(entity_id: &str) -> u64 {
340 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
341 for b in entity_id.as_bytes() {
342 h ^= u64::from(*b);
343 h = h.wrapping_mul(0x0000_0100_0000_01b3);
344 }
345 h
346}
347
348/// phase-391 W5-endgame step 2b (issue 0857) — the NON-GENERIC head of every
349/// `ComponentCell<..>`, guaranteed FIRST FIELD by the cell's `#[repr(C)]`.
350///
351/// The executor's enrolled-component state is a thin pointer to a cell whose
352/// const parameters only the enrolling monomorphization knows. The tick/drop
353/// trampolines are monomorphized alongside it and cast back to the concrete
354/// type; the one consumer that iterates ALL enrolled states regardless of
355/// class — the dispatch-stats fold — casts to this header instead. Both casts
356/// are sound because the header is the first field of a `repr(C)` struct, so
357/// a cell pointer IS a header pointer.
358struct CellHeader {
359 callback_dispatches: AtomicUsize,
360 message_dispatches: AtomicUsize,
361}
362
363/// Issue 1865 — the NON-GENERIC prefix of every `ComponentCell<..>`: its
364/// header and its slot, the two fields that precede every const-generic one.
365///
366/// [`ExecutorNodeRuntime::dispatch_callback`] must reach the component state
367/// of an ENROLLED cell (the install seam's) to hand it a deferred callback,
368/// and like the stats fold it cannot name the cell's const parameters. Under
369/// `#[repr(C)]` a field's offset depends only on the fields before it, so a
370/// `repr(C)` struct that repeats the first two fields has their offsets —
371/// asserted below rather than trusted, because reordering the cell's fields
372/// would otherwise turn this cast into a read of the wrong bytes.
373#[repr(C)]
374struct CellPrefix {
375 header: CellHeader,
376 slot: RefCell<&'static mut dyn ComponentSlot>,
377}
378
379const _: () = {
380 assert!(
381 core::mem::offset_of!(ComponentCell<0, 0, 0, 0, 0, 0>, header)
382 == core::mem::offset_of!(CellPrefix, header)
383 );
384 assert!(
385 core::mem::offset_of!(ComponentCell<0, 0, 0, 0, 0, 0>, slot)
386 == core::mem::offset_of!(CellPrefix, slot)
387 );
388 assert!(
389 core::mem::offset_of!(ComponentCell<1, 1, 1, 1, 1, 1>, slot)
390 == core::mem::offset_of!(CellPrefix, slot)
391 );
392};
393
394/// Shared per-component cell. Subscription / timer closures registered
395/// against the executor hold a [`CellHandle`] so they can dispatch +
396/// publish back through the resolver.
397///
398/// phase-391 W5-endgame step 2a (issue 0857) — generic over the four registry
399/// capacities, defaulted to the `MAX_CELL_ENTITIES` knob so every existing
400/// spelling (`ComponentCell`) keeps meaning the pool-capped layout. The
401/// per-class macro emission names tighter bounds; everything downstream of
402/// construction consumes the cell through the non-generic [`CellView`], so
403/// the const params never cross an FFI or public signature.
404#[repr(C)]
405struct ComponentCell<
406 const PUBS: usize = { crate::config::MAX_CELL_ENTITIES },
407 const SVCS: usize = { crate::config::MAX_CELL_ENTITIES },
408 const ACTC: usize = { crate::config::MAX_CELL_ENTITIES },
409 const ACTS: usize = { crate::config::MAX_CELL_ENTITIES },
410 const SSRV: usize = { crate::config::MAX_CELL_ENTITIES },
411 const TIMS: usize = { crate::config::MAX_CELL_ENTITIES },
412> {
413 /// W5-endgame step 2b — MUST stay first; see [`CellHeader`].
414 header: CellHeader,
415 /// phase-391 W5.3b — BORROWED from per-class or pool storage, not boxed.
416 /// The storage is `'static` (macro-emitted static / caller backing), so the
417 /// reference outlives every closure that dispatches through it.
418 slot: RefCell<&'static mut dyn ComponentSlot>,
419 publishers: RefCell<heapless::Vec<(IdStr, EmbeddedRawPublisher), PUBS>>,
420 // Phase 212.M-F.23 — declarative service/action CLIENT + action-SERVER
421 // handles, keyed by stable entity id, resolved during tick dispatch.
422 // Built at registration time on the single-node runtime (they mirrored the
423 // orchestration's ~~`GenClientDispatch`~~/~~`GenActionExec`~~ arrays, both
424 // retired). Service- and
425 // action-SERVER request/goal dispatch is owned by the executor (the
426 // trampolines registered in `create_entity`); only the action-server
427 // handle is kept here so the tick can complete goals / publish feedback.
428 service_clients: RefCell<heapless::Vec<(IdStr, crate::HandleId), SVCS>>,
429 action_clients: RefCell<heapless::Vec<(IdStr, usize), ACTC>>,
430 action_servers: RefCell<heapless::Vec<(IdStr, crate::internals::ActionServerRawHandle), ACTS>>,
431 /// Issue 2075 — the component's controllable declared timers, keyed by
432 /// the FNV-1a hash of the entity id, with the op a context requested.
433 /// Bounded by the class's `ENTITY_BOUNDS.timers`; a timer past the bound
434 /// registers and fires but is not in here.
435 timers: RefCell<heapless::Vec<TimerSlot, TIMS>>,
436 // W5-endgame ctx slabs (issue 0857) — the leaked trampoline contexts the
437 // sink used to `Box::into_raw` live INSIDE the cell, sized by the class's
438 // declared bounds, so the macro path allocates nothing. Monotonic
439 // counters; a full slab is a loud registration error. The entries die
440 // with the cell (executor drop), after which no trampoline can fire.
441 svc_ctxs: [UnsafeCell<MaybeUninit<ServiceServerCtx>>; SSRV],
442 svc_ctxs_used: core::cell::Cell<usize>,
443 act_srv_ctxs: [UnsafeCell<MaybeUninit<ActionServerCtx>>; ACTS],
444 act_srv_ctxs_used: core::cell::Cell<usize>,
445 act_cli_ctxs: [UnsafeCell<MaybeUninit<ActionClientCtx>>; ACTC],
446 act_cli_ctxs_used: core::cell::Cell<usize>,
447 // Phase 264 W4c — raw pointer to the executor's volatile parameter store, so a
448 // subscription/timer/service/action callback can read `ctx.parameter::<T>(name)`.
449 // The callback closures + leaked trampolines hold only a `CellHandle` (the
450 // executor is unreachable when they fire), so the store address is threaded HERE by
451 // `apply_param_services`' post-pass (mirrors the `run_ticks` disjoint borrow). Null
452 // until param services are registered. Stable for the executor's life: the server
453 // lives in a `Box<ParamState>`, and since phase-382 W2' its SLOTS live in
454 // caller-owned storage it merely borrows — a fixed-length table either way, so a
455 // declare never moves anything this pointer or a stored `&ParameterValue` names.
456 #[cfg(feature = "param-store")]
457 param_server: core::cell::Cell<*const nros_params::ParameterServer<'static>>,
458 // phase-426 W3 — WHICH node in that store this component's callbacks read.
459 //
460 // The store is keyed by node and the six parameter services are registered
461 // per node, so a cell holding the store address and nothing else can only
462 // answer for the executor's first node: every component on a multi-node
463 // executor read the primary's values. Set from the sink's own
464 // `create_node` result once `register()` has run — the raw index rather
465 // than a `NodeKey`, because `Cell<T>` wants a `Copy` payload and the key is
466 // exactly this byte. `NodeId::PRIMARY` (0) until then, which is what a
467 // component that declares no node means.
468 #[cfg(feature = "param-store")]
469 param_node: core::cell::Cell<u8>,
470}
471
472impl<
473 const PUBS: usize,
474 const SVCS: usize,
475 const ACTC: usize,
476 const ACTS: usize,
477 const SSRV: usize,
478 const TIMS: usize,
479> Drop for ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>
480{
481 fn drop(&mut self) {
482 // phase-391 W5.3b — the slot is BORROWED from one-shot storage, so the
483 // component state's destructor no longer rides a `Box` drop. Run it
484 // here instead: the cell drops exactly once (the executor's drop
485 // trampoline runs it in place on the enrolled path; the dynamic
486 // path's `Arc` drops it on runtime drop), and the
487 // storage slot is never handed out again (`take`/`next_slot` counters
488 // are monotonic), so nothing can observe the dropped bytes.
489 // W5-endgame ctx slabs — run the placed ctxs' destructors (their
490 // `CellHandle` may hold an `Arc` on the pooled arm). Monotonic
491 // counters bound the initialized prefix exactly.
492 for i in 0..self.svc_ctxs_used.get() {
493 // SAFETY: entries [0, used) were initialized by `place_service_ctx`
494 // and are dropped exactly once, here.
495 unsafe { (*self.svc_ctxs[i].get()).assume_init_drop() };
496 }
497 for i in 0..self.act_srv_ctxs_used.get() {
498 // SAFETY: as above, for `place_action_server_ctx`.
499 unsafe { (*self.act_srv_ctxs[i].get()).assume_init_drop() };
500 }
501 for i in 0..self.act_cli_ctxs_used.get() {
502 // SAFETY: as above, for `place_action_client_ctx`.
503 unsafe { (*self.act_cli_ctxs[i].get()).assume_init_drop() };
504 }
505 let slot: &mut &'static mut dyn ComponentSlot = self.slot.get_mut();
506 let p: *mut dyn ComponentSlot = &raw mut **slot;
507 // SAFETY: `p` targets storage uniquely owned by this cell (handed out
508 // at most once), reachable only through the reference being dropped
509 // with us; it is dropped at most once because the cell is.
510 unsafe { core::ptr::drop_in_place(p) };
511 }
512}
513
514impl<
515 const PUBS: usize,
516 const SVCS: usize,
517 const ACTC: usize,
518 const ACTS: usize,
519 const SSRV: usize,
520 const TIMS: usize,
521> ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>
522{
523 /// Phase 264 W4c — the executor's parameter store, or `None` until
524 /// `apply_param_services` threads it in. The deref is sound: single-threaded
525 /// executor, param services mutate the server only outside callback dispatch.
526 #[cfg(feature = "param-store")]
527 fn param_server(&self) -> Option<&nros_params::ParameterServer<'static>> {
528 let ptr = self.param_server.get();
529 if ptr.is_null() {
530 None
531 } else {
532 // SAFETY: `ptr` is the address of the executor's boxed `ParameterServer`
533 // (stable for the executor's life); param services mutate it before/after
534 // dispatch (`spin.rs` pre/post), never during, so no aliasing `&mut` is live.
535 Some(unsafe { &*ptr })
536 }
537 }
538}
539
540/// phase-391 W5-endgame step 1 (issue 0857) — the NON-GENERIC view every
541/// dispatch/tick path consumes instead of the concrete [`ComponentCell`].
542///
543/// Why a trait and not the cell: the endgame emits a per-class cell whose
544/// registries are sized to the class's DECLARED entity counts (const generics,
545/// which the "never public to other languages" rule confines to the macro
546/// emission), while the dynamic `register_node` path keeps pool-backed cells at
547/// the knob caps. Two cell layouts, ONE dispatch implementation — this trait is
548/// the seam that makes the split affordable. `Ref<'_, [T]>` erases the
549/// `heapless::Vec` capacity; `try_with_slot_mut` erases the slot's storage
550/// shape (borrowed `&'static mut dyn` today, fused inline in the per-class
551/// static tomorrow).
552///
553/// Object-safe on purpose: the FFI trampolines carry a THIN `*mut c_void`, so
554/// each concrete cell type casts back to itself and only then widens to
555/// `&dyn CellView`.
556trait CellView {
557 /// Bump the dispatch counters (`message` = payload was non-empty).
558 fn note_dispatch(&self, message: bool);
559 /// The publisher registered under `entity_id`, if this component declared
560 /// one. Holds the registry's shared borrow for the returned `Ref`'s life.
561 fn publisher(&self, entity_id: &str) -> Option<Ref<'_, EmbeddedRawPublisher>>;
562 fn service_clients(&self) -> Ref<'_, [(IdStr, crate::HandleId)]>;
563 fn action_clients(&self) -> Ref<'_, [(IdStr, usize)]>;
564 fn action_servers(&self) -> Ref<'_, [(IdStr, crate::internals::ActionServerRawHandle)]>;
565 /// Run `f` over the component slot unless it is already mutably borrowed
566 /// (a re-entrant dispatch on the same cell) — in which case the dispatch
567 /// is dropped, exactly as the pre-trait `try_borrow_mut` spelled it.
568 fn try_with_slot_mut(&self, f: &mut dyn FnMut(&mut dyn ComponentSlot));
569 /// The executor's parameter store, or `None` until `apply_param_services`
570 /// threads it in.
571 #[cfg(feature = "param-store")]
572 fn view_param_server(&self) -> Option<&nros_params::ParameterServer<'static>>;
573 /// phase-426 W3 — the node key this component's parameter reads are about.
574 /// Travels with the store, because a store keyed by node and a reader that
575 /// cannot name one is how every component read the primary's values.
576 #[cfg(feature = "param-store")]
577 fn view_param_node(&self) -> nros_params::NodeKey;
578 /// The `(callbacks, messages)` dispatch counters. Only the dynamic
579 /// runtime's stats fold reads them through the trait; the macro path's
580 /// fold reads the `CellHeader` directly.
581 #[cfg(feature = "alloc")]
582 fn dispatch_counts(&self) -> (usize, usize);
583 /// Registration-time registry appends. `Err(())` = registry full — the
584 /// component declared more entities of that kind than its cell's bound,
585 /// which the caller reports loudly (never a silent drop).
586 fn push_publisher(&self, id: IdStr, handle: EmbeddedRawPublisher) -> Result<(), ()>;
587 fn push_service_client(&self, id: IdStr, handle: crate::HandleId) -> Result<(), ()>;
588 fn push_action_client(&self, id: IdStr, entry_index: usize) -> Result<(), ()>;
589 fn push_action_server(
590 &self,
591 id: IdStr,
592 handle: crate::internals::ActionServerRawHandle,
593 ) -> Result<(), ()>;
594 /// W5-endgame ctx slabs — place a trampoline context into the cell's slab
595 /// and return its stable address for the executor's C-ABI registration.
596 /// `Err(())` = slab full (the class declared fewer of that kind than
597 /// `register()` creates). The entry lives — and is dropped — with the cell.
598 fn place_service_ctx(&self, ctx: ServiceServerCtx) -> Result<*mut core::ffi::c_void, ()>;
599 fn place_action_server_ctx(&self, ctx: ActionServerCtx) -> Result<*mut core::ffi::c_void, ()>;
600 fn place_action_client_ctx(&self, ctx: ActionClientCtx) -> Result<*mut core::ffi::c_void, ()>;
601 /// Issue 2075 — file a declared timer's handle under its id's key.
602 /// `Ok(true)` = filed; `Ok(false)` = the table is full, so the timer runs
603 /// but cannot be controlled by id; `Err(())` = another timer of this
604 /// component already has that key (an FNV-1a collision between two
605 /// distinct ids — the metadata already refuses a duplicate id).
606 fn push_timer(&self, key: u64, handle: crate::HandleId) -> Result<bool, ()>;
607 /// Issue 2075 — record `op` for the timer filed under `key`; `false` when
608 /// none is.
609 fn request_timer_op(&self, key: u64, op: TimerOp) -> bool;
610 /// Issue 2075 — hand every pending op to `f` and clear it.
611 fn drain_timer_ops(&self, f: &mut dyn FnMut(crate::HandleId, TimerOp));
612}
613
614impl<
615 const PUBS: usize,
616 const SVCS: usize,
617 const ACTC: usize,
618 const ACTS: usize,
619 const SSRV: usize,
620 const TIMS: usize,
621> CellView for ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>
622{
623 fn note_dispatch(&self, message: bool) {
624 self.header
625 .callback_dispatches
626 .fetch_add(1, Ordering::Relaxed);
627 if message {
628 self.header
629 .message_dispatches
630 .fetch_add(1, Ordering::Relaxed);
631 }
632 }
633
634 #[cfg(feature = "alloc")]
635 fn dispatch_counts(&self) -> (usize, usize) {
636 (
637 self.header.callback_dispatches.load(Ordering::Relaxed),
638 self.header.message_dispatches.load(Ordering::Relaxed),
639 )
640 }
641
642 fn push_publisher(&self, id: IdStr, handle: EmbeddedRawPublisher) -> Result<(), ()> {
643 self.publishers
644 .borrow_mut()
645 .push((id, handle))
646 .map_err(|_| ())
647 }
648
649 fn push_service_client(&self, id: IdStr, handle: crate::HandleId) -> Result<(), ()> {
650 self.service_clients
651 .borrow_mut()
652 .push((id, handle))
653 .map_err(|_| ())
654 }
655
656 fn push_action_client(&self, id: IdStr, entry_index: usize) -> Result<(), ()> {
657 self.action_clients
658 .borrow_mut()
659 .push((id, entry_index))
660 .map_err(|_| ())
661 }
662
663 fn push_action_server(
664 &self,
665 id: IdStr,
666 handle: crate::internals::ActionServerRawHandle,
667 ) -> Result<(), ()> {
668 self.action_servers
669 .borrow_mut()
670 .push((id, handle))
671 .map_err(|_| ())
672 }
673
674 fn place_service_ctx(&self, ctx: ServiceServerCtx) -> Result<*mut core::ffi::c_void, ()> {
675 let i = self.svc_ctxs_used.get();
676 if i >= SSRV {
677 return Err(());
678 }
679 self.svc_ctxs_used.set(i + 1);
680 // SAFETY: `i` is claimed exactly once (monotonic counter, single-
681 // threaded executor contract), so no other reference to this entry
682 // exists; the address is stable because the cell never moves after
683 // placement.
684 Ok(
685 unsafe { (*self.svc_ctxs[i].get()).write(ctx) as *mut ServiceServerCtx }
686 as *mut core::ffi::c_void,
687 )
688 }
689
690 fn place_action_server_ctx(&self, ctx: ActionServerCtx) -> Result<*mut core::ffi::c_void, ()> {
691 let i = self.act_srv_ctxs_used.get();
692 if i >= ACTS {
693 return Err(());
694 }
695 self.act_srv_ctxs_used.set(i + 1);
696 // SAFETY: as `place_service_ctx`.
697 Ok(
698 unsafe { (*self.act_srv_ctxs[i].get()).write(ctx) as *mut ActionServerCtx }
699 as *mut core::ffi::c_void,
700 )
701 }
702
703 fn place_action_client_ctx(&self, ctx: ActionClientCtx) -> Result<*mut core::ffi::c_void, ()> {
704 let i = self.act_cli_ctxs_used.get();
705 if i >= ACTC {
706 return Err(());
707 }
708 self.act_cli_ctxs_used.set(i + 1);
709 // SAFETY: as `place_service_ctx`.
710 Ok(
711 unsafe { (*self.act_cli_ctxs[i].get()).write(ctx) as *mut ActionClientCtx }
712 as *mut core::ffi::c_void,
713 )
714 }
715
716 fn push_timer(&self, key: u64, handle: crate::HandleId) -> Result<bool, ()> {
717 let mut timers = self.timers.borrow_mut();
718 if timers.iter().any(|t| t.key == key) {
719 return Err(());
720 }
721 Ok(timers
722 .push(TimerSlot {
723 key,
724 handle,
725 pending: None,
726 })
727 .is_ok())
728 }
729
730 fn request_timer_op(&self, key: u64, op: TimerOp) -> bool {
731 // `try_borrow_mut`: a request made while the table is being drained
732 // (a timer op reaching back into the component) is refused rather
733 // than panicking; nothing on the drain path calls back in today.
734 let Ok(mut timers) = self.timers.try_borrow_mut() else {
735 return false;
736 };
737 match timers.iter_mut().find(|t| t.key == key) {
738 Some(t) => {
739 t.pending = Some(op);
740 true
741 }
742 None => false,
743 }
744 }
745
746 fn drain_timer_ops(&self, f: &mut dyn FnMut(crate::HandleId, TimerOp)) {
747 let mut timers = self.timers.borrow_mut();
748 for t in timers.iter_mut() {
749 if let Some(op) = t.pending.take() {
750 f(t.handle, op);
751 }
752 }
753 }
754
755 fn publisher(&self, entity_id: &str) -> Option<Ref<'_, EmbeddedRawPublisher>> {
756 Ref::filter_map(self.publishers.borrow(), |pubs| {
757 pubs.iter().find(|(id, _)| id == entity_id).map(|(_, p)| p)
758 })
759 .ok()
760 }
761
762 fn service_clients(&self) -> Ref<'_, [(IdStr, crate::HandleId)]> {
763 Ref::map(self.service_clients.borrow(), |v| v.as_slice())
764 }
765
766 fn action_clients(&self) -> Ref<'_, [(IdStr, usize)]> {
767 Ref::map(self.action_clients.borrow(), |v| v.as_slice())
768 }
769
770 fn action_servers(&self) -> Ref<'_, [(IdStr, crate::internals::ActionServerRawHandle)]> {
771 Ref::map(self.action_servers.borrow(), |v| v.as_slice())
772 }
773
774 fn try_with_slot_mut(&self, f: &mut dyn FnMut(&mut dyn ComponentSlot)) {
775 if let Ok(mut slot) = self.slot.try_borrow_mut() {
776 f(*slot);
777 }
778 }
779
780 #[cfg(feature = "param-store")]
781 fn view_param_server(&self) -> Option<&nros_params::ParameterServer<'static>> {
782 self.param_server()
783 }
784
785 #[cfg(feature = "param-store")]
786 fn view_param_node(&self) -> nros_params::NodeKey {
787 nros_params::NodeKey::new(self.param_node.get())
788 }
789}
790
791/// phase-391 W5-endgame step 2b — the two ways a cell is held, one spelling.
792///
793/// The macro/FFI install path places its cell in per-class static storage and
794/// holds `&'static`; the dynamic `register_node` path (alloc-gated, hosted)
795/// keeps the `Arc` it always had — its cells are not 0857's embedded heap
796/// cost, and `Arc` gives them the drop-on-runtime-drop lifetime the dynamic
797/// path needs. Closures and leaked ctxs clone the HANDLE (a ref copy or an
798/// `Arc` bump) and dispatch through [`CellHandle::view`].
799#[derive(Clone)]
800enum CellHandle {
801 Static(&'static dyn CellView),
802 #[cfg(feature = "alloc")]
803 Pooled(Arc<ComponentCell>),
804}
805
806impl CellHandle {
807 fn view(&self) -> &dyn CellView {
808 match self {
809 CellHandle::Static(v) => *v,
810 #[cfg(feature = "alloc")]
811 CellHandle::Pooled(cell) => cell.as_ref(),
812 }
813 }
814}
815
816/// `PublisherResolver` implementation backed by a [`CellView`].
817struct CellResolver<'a> {
818 cell: &'a dyn CellView,
819}
820
821impl PublisherResolver for CellResolver<'_> {
822 fn publish_raw(&self, entity_id: &str, data: &[u8]) -> NodeResult<()> {
823 // issue 0736 — the two arms report DIFFERENT failures. A miss on
824 // the cell's publisher lookup (~~`lookup_publisher`~~ once) means this
825 // component declared no publisher for the
826 // entity, so nothing ever reached the transport; a `publish_raw` error
827 // means the transport had the sample and refused it. Both used to
828 // return `Runtime`, which is why a console full of "publish FAILED"
829 // could not distinguish a wiring bug from a congested link.
830 match self.cell.publisher(entity_id) {
831 Some(p) => p
832 .publish_serialized(data)
833 .map_err(|_| NodeDeclError::Runtime),
834 None => Err(NodeDeclError::UnknownPublisher),
835 }
836 }
837
838 fn request_timer(&self, entity_id: &str, op: TimerOp) -> NodeResult<()> {
839 if self.cell.request_timer_op(timer_key(entity_id), op) {
840 Ok(())
841 } else {
842 Err(NodeDeclError::UnknownTimer)
843 }
844 }
845}
846
847/// Issue 2075 — apply the timer ops this cell's contexts requested, against
848/// the executor. Runs on both sides of the component's tick: before it for
849/// the ops callbacks requested during the pass's dispatch, after it for those
850/// the tick itself requested. The executor's own `reset_timer` /
851/// `cancel_timer` are the ops (a reset re-seeds a clock timer's reading, so
852/// a timer declared stopped starts a FRESH period). A timer already released
853/// answers an error, which is dropped: there is nothing left to control.
854fn apply_timer_ops(cell: &dyn CellView, exec_ptr: *mut Executor<'static>) {
855 cell.drain_timer_ops(&mut |handle, op| {
856 // SAFETY: as `tick_one_cell`'s other executor uses: no callback is
857 // running and nothing else holds the executor between dispatches.
858 let executor = unsafe { &mut *exec_ptr };
859 let _ = match op {
860 TimerOp::Reset => executor.reset_timer(handle),
861 TimerOp::Cancel => executor.cancel_timer(handle),
862 };
863 });
864}
865
866// Phase 212.M-F.23 — the ~~`UnsupportedActions`~~ / ~~`UnsupportedClients`~~ tick-side
867// stubs are retired. Real service/action client + action-server dispatch on the
868// single-node runtime lives in `RuntimeClientDispatch` / `RuntimeActions`
869// (below), wired into `run_ticks`.
870
871// =============================================================================
872// ExecutorNodeRuntime
873// =============================================================================
874
875/// Executor-backed component runtime.
876///
877/// Owns the [`Executor`] and one slot per registered component. The
878/// register / spin lifecycle:
879///
880/// 1. [`from_executor`](Self::from_executor) wraps an open
881/// [`Executor`].
882/// 2. [`register_node`](Self::register_node) builds the
883/// component's `State`, runs [`Component::register`](crate::node::Component::register)
884/// against the live executor, whose registration sink materialises nodes /
885/// pubs / subs / timers on the real executor, and wires each
886/// subscription + timer callback to dispatch into
887/// [`ExecutableNode::on_callback`] with the right
888/// [`CallbackId`].
889/// 3. [`spin`](Self::spin) / [`spin_once`](Self::spin_once) drive the
890/// executor; between iterations every registered component's
891/// [`ExecutableNode::tick`] runs.
892#[cfg(feature = "alloc")]
893pub struct ExecutorNodeRuntime {
894 executor: Executor<'static>,
895 components: Vec<Arc<ComponentCell>>,
896 /// Issue 2020 -- the level that registered each of `components`, by
897 /// index (`Executor::registering_level` at registration; `None` before a
898 /// level runner set one). Only that level's pass ticks the component.
899 component_levels: Vec<Option<u8>>,
900 /// phase-391 W5.3b — slot storage for [`register_node`](Self::register_node).
901 /// Always present: the leaking constructor allocates it once, `new_in`
902 /// carves the caller's backing.
903 pool: ComponentPool,
904 /// phase-521 W6 — whether a component registered through
905 /// [`register_node`](Self::register_node) has a working `tick`
906 /// ([`ExecutableNode::HAS_TICK`]); see [`Self::entry_spin_budget`].
907 ticking: bool,
908}
909
910/// Bump view over the runtime's slot backing. Raw pointer, not a slice, so the
911/// runtime stays movable — the SLOTS never move; they live in the backing.
912#[cfg(feature = "alloc")]
913struct ComponentPool {
914 base: *mut MaybeUninit<u8>,
915 len_bytes: usize,
916 per_slot: usize,
917 capacity: usize,
918 next: usize,
919}
920
921// SAFETY: the pool is confined to the runtime (`&mut self` on every use); the
922// raw pointer targets `'static` backing handed over at construction.
923#[cfg(feature = "alloc")]
924unsafe impl Send for ComponentPool {}
925
926#[cfg(feature = "alloc")]
927impl ComponentPool {
928 /// Next disjoint slot window, or `None` when the pool is full.
929 fn next_slot(&mut self) -> Option<&'static mut [MaybeUninit<u8>]> {
930 if self.next >= self.capacity {
931 return None;
932 }
933 let off = self.next * self.per_slot;
934 debug_assert!(off + self.per_slot <= self.len_bytes);
935 self.next += 1;
936 // SAFETY: `base` points at `'static` backing of `len_bytes`; the
937 // window is in-bounds by the checks above and DISJOINT from every
938 // earlier one because `next` only increases.
939 Some(unsafe { core::slice::from_raw_parts_mut(self.base.add(off), self.per_slot) })
940 }
941}
942
943#[cfg(feature = "alloc")]
944impl ExecutorNodeRuntime {
945 /// Wrap an already-built [`Executor`], LEAKING the slot backing.
946 ///
947 /// The convenience constructor — allocates `RuntimeSizing::DEFAULT`'s
948 /// backing once and never frees it, exactly the relationship
949 /// `Executor::from_session` has to `Executor::open_in`. Use
950 /// [`new_in`](Self::new_in) on an image that must not allocate.
951 pub fn from_executor(executor: Executor<'static>) -> Self {
952 let sizing = crate::runtime_storage::RuntimeSizing::DEFAULT;
953 let backing: &'static mut [MaybeUninit<u64>] =
954 Vec::leak(alloc::vec![MaybeUninit::uninit(); sizing.u64_len()]);
955 // SAFETY: freshly leaked — `'static`, uniquely owned, exactly
956 // `u64_len()` words.
957 unsafe { Self::new_in(executor, backing, sizing) }
958 }
959
960 /// Wrap an already-built [`Executor`] over CALLER-SUPPLIED slot storage.
961 ///
962 /// Size `backing` with [`crate::runtime_storage::RuntimeSizing::u64_len`]; a short one panics,
963 /// naming both sizes (fail-loud on every profile — a short backing is
964 /// silent corruption, the `executor::storage::carve` lesson).
965 ///
966 /// # Safety
967 /// `backing` must be uniquely owned by this runtime for its whole life:
968 /// slots carved from it are handed out as `&'static mut`, so aliasing it
969 /// anywhere else is undefined behaviour.
970 pub unsafe fn new_in(
971 executor: Executor<'static>,
972 backing: &'static mut [MaybeUninit<u64>],
973 sizing: crate::runtime_storage::RuntimeSizing,
974 ) -> Self {
975 let need = sizing.u64_len();
976 assert!(
977 backing.len() >= need,
978 "component pool backing too small: {} u64 words < {} required for {} slot(s) \
979 of {} bytes — size it with RuntimeSizing::u64_len()",
980 backing.len(),
981 need,
982 sizing.components,
983 sizing.slot_bytes,
984 );
985 Self {
986 executor,
987 components: Vec::new(),
988 component_levels: Vec::new(),
989 pool: ComponentPool {
990 base: backing.as_mut_ptr() as *mut MaybeUninit<u8>,
991 len_bytes: backing.len() * 8,
992 per_slot: (sizing.slot_bytes.div_ceil(8) * 8).max(1),
993 capacity: sizing.components,
994 next: 0,
995 },
996 ticking: false,
997 }
998 }
999
1000 /// The budget this runtime's entry loop
1001 /// passes to [`spin_once`](Self::spin_once):
1002 /// [`Executor::entry_spin_budget`], or the 10 ms cadence while a component
1003 /// registered here has a working `tick` (it runs once per spin).
1004 pub fn entry_spin_budget(&self) -> Duration {
1005 if self.ticking {
1006 nros_node::ENTRY_POLL_BUDGET
1007 } else {
1008 self.executor.entry_spin_budget()
1009 }
1010 }
1011
1012 /// Borrow the underlying executor.
1013 pub fn executor(&self) -> &Executor<'static> {
1014 &self.executor
1015 }
1016
1017 /// The executor's address, through a raw runtime
1018 /// pointer and without a reference: what a level runner takes the
1019 /// executor's lock through before it touches the runtime
1020 /// ([`crate::levels::LevelCore`]).
1021 ///
1022 /// # Safety
1023 /// `this` points at a live runtime.
1024 pub unsafe fn executor_ptr(this: *mut Self) -> *mut Executor<'static> {
1025 // SAFETY: only the field address is computed.
1026 unsafe { core::ptr::addr_of_mut!((*this).executor) }
1027 }
1028
1029 /// [`spin_once`](Self::spin_once) on a runtime other
1030 /// level workers share: the executor's lock is taken first, the pass
1031 /// releases it around each user callback
1032 /// ([`Executor::spin_once_shared`]), and the components' ticks run under
1033 /// it. On a level image, only the boot level's components
1034 /// (and any registered before a level was set): each other level's pass
1035 /// ticks its own ([`crate::levels::LevelCore::spin_level_once`]).
1036 ///
1037 /// # Safety
1038 /// `this` points at a live runtime whose executor has the lock installed
1039 /// if any other thread can reach it, and no reference to the runtime is
1040 /// live in the caller.
1041 #[cfg(feature = "rmw-cffi")]
1042 pub unsafe fn spin_once_shared(
1043 this: *mut Self,
1044 timeout: Duration,
1045 ) -> nros_node::SpinOnceResult {
1046 // SAFETY: the caller's contract; the lock is taken before any
1047 // reference to the runtime exists.
1048 let exec = unsafe { Self::executor_ptr(this) };
1049 let _g = unsafe { nros_node::executor::exec_lock::ExecGuard::acquire(exec) };
1050 let result = unsafe { Executor::spin_once_shared(exec, timeout) };
1051 // SAFETY: under the lock no other thread touches the runtime.
1052 unsafe { (*this).run_ticks() };
1053 result
1054 }
1055
1056 /// Mutably borrow the underlying executor — for advanced wiring
1057 /// (parameter services, custom guard conditions). Don't use during
1058 /// [`spin`](Self::spin) from another thread; the runtime is
1059 /// single-threaded.
1060 pub fn executor_mut(&mut self) -> &mut Executor<'static> {
1061 &mut self.executor
1062 }
1063
1064 /// Lower a sched task's RTOS-agnostic scheduling
1065 /// policy onto this executor's DEFAULT scheduling context. One `Executor`
1066 /// per sched task means "the sched task's policy" == "this executor's default SC";
1067 /// per-group/per-handle bindings still take precedence.
1068 ///
1069 /// **Portable** across every board — call from each board's `run_sched_tasks`
1070 /// after building the runtime. Takes the sched task fields as primitives (not a
1071 /// `SchedTaskSpec`) so `nros` needs no board/platform dependency; a board passes
1072 /// `sched_task.class`, `sched_task.period_us`, … straight through.
1073 ///
1074 /// `real_time` + `budget_us` + `period_us` → [`SchedClass::Sporadic`](crate::SchedClass::Sporadic);
1075 /// `best_effort` → [`SchedClass::BestEffort`](crate::SchedClass::BestEffort); `time_triggered` +
1076 /// `period_us` → the cyclic dispatcher (major frame = period, window =
1077 /// `budget_us` or the whole frame); `deadline_us` sets the SC deadline and
1078 /// `deadline_policy` its action. A sched task with no class/budget/deadline
1079 /// leaves the default `Fifo` SC untouched (byte-identical pre-W3 behavior).
1080 pub fn apply_sched_task_sched_policy(
1081 &mut self,
1082 class: Option<&str>,
1083 period_us: Option<u64>,
1084 budget_us: Option<u64>,
1085 deadline_us: Option<u64>,
1086 deadline_policy: Option<&str>,
1087 ) {
1088 use crate::SchedContext;
1089 // Common backend (RFC-0052): the sched task→SchedContext lowering lives ONCE
1090 // in `SchedContext::from_sched_task_policy`, shared with the C / C++ entries
1091 // (`nros_{c,cpp}_create_sched_context_from_policy`) so the mapping never
1092 // drifts between languages. `None` → keep the default `Fifo` SC.
1093 let Some((sc, tt_frame)) = SchedContext::from_sched_task_policy(
1094 class,
1095 period_us,
1096 budget_us,
1097 deadline_us,
1098 deadline_policy,
1099 ) else {
1100 return;
1101 };
1102 if let Some(frame_us) = tt_frame {
1103 self.executor_mut()
1104 .register_time_triggered_dispatcher(frame_us);
1105 }
1106 self.executor_mut().set_default_sched_context(sc);
1107 }
1108
1109 /// Lower a LEVEL's policy onto its own
1110 /// scheduling context, the level-runner twin of
1111 /// [`apply_sched_task_sched_policy`](Self::apply_sched_task_sched_policy). Call it on
1112 /// the registering level (after the runner opened or adopted it), before
1113 /// its setup: what the setup registers then binds to the level's context
1114 /// instead of the executor's default, which every level on the core
1115 /// shares.
1116 ///
1117 /// `kernel_enforces_budget` says the kernel throttles the level's thread
1118 /// with the same budget and period (NuttX `SCHED_SPORADIC`, Linux
1119 /// `SCHED_DEADLINE`), so the executor does not enforce it a second time
1120 /// ([`Executor::defer_budget_to_kernel`](crate::Executor::defer_budget_to_kernel)).
1121 /// Returns the context, or `None` when the level declares no policy (it
1122 /// keeps the default) or no context slot was free (said on the console:
1123 /// the level then runs on the default context, unbudgeted by the
1124 /// executor).
1125 pub fn apply_level_sched_policy(
1126 &mut self,
1127 class: Option<&str>,
1128 period_us: Option<u64>,
1129 budget_us: Option<u64>,
1130 deadline_us: Option<u64>,
1131 deadline_policy: Option<&str>,
1132 kernel_enforces_budget: bool,
1133 ) -> Option<crate::SchedContextId> {
1134 use crate::SchedContext;
1135 let (sc, tt_frame) = SchedContext::from_sched_task_policy(
1136 class,
1137 period_us,
1138 budget_us,
1139 deadline_us,
1140 deadline_policy,
1141 )?;
1142 if let Some(frame_us) = tt_frame {
1143 self.executor_mut()
1144 .register_time_triggered_dispatcher(frame_us);
1145 }
1146 match self.executor_mut().set_level_sched_context(sc) {
1147 Ok(id) => {
1148 if kernel_enforces_budget {
1149 self.executor_mut().defer_budget_to_kernel(id);
1150 }
1151 Some(id)
1152 }
1153 Err(e) => {
1154 nros_log::log_warn!(
1155 nros_log::get_logger("nros"),
1156 "a level's sched context was not created ({}): the level runs on \
1157 the default context, unbudgeted by the executor",
1158 e
1159 );
1160 None
1161 }
1162 }
1163 }
1164
1165 /// Number of registered components.
1166 pub fn component_count(&self) -> usize {
1167 self.components.len()
1168 }
1169
1170 /// Register a [`Component`](crate::node::Component) (which must also be
1171 /// [`ExecutableNode`]) into this runtime. Builds the
1172 /// component's `State` (via [`ExecutableNode::init`]) and
1173 /// walks [`Component::register`](crate::node::Component::register) over the live executor — every
1174 /// declared node / pub / sub / timer materialises as a real
1175 /// executor handle, and subscription + timer callbacks are wired
1176 /// to dispatch into [`ExecutableNode::on_callback`].
1177 pub fn register_node<C: ExecutableNode + 'static>(&mut self) -> NodeResult<RegisteredNode<C>>
1178 where
1179 C::State: 'static,
1180 {
1181 // phase-391 W5.3b — draw slot storage from the runtime's pool instead
1182 // of boxing. Full → the executor-table-Full class (raise
1183 // NROS_RUNTIME_MAX_COMPONENTS); too big for `slot_bytes` → likewise a
1184 // registration error (raise NROS_RUNTIME_COMPONENT_SLOT_BYTES), never
1185 // a truncation.
1186 let raw = self.pool.next_slot().ok_or(NodeDeclError::ExecutorFull)?;
1187 if raw.len() < core::mem::size_of::<TypedSlot<C>>()
1188 || !(raw.as_ptr() as usize).is_multiple_of(core::mem::align_of::<TypedSlot<C>>())
1189 {
1190 return Err(NodeDeclError::Runtime);
1191 }
1192 // SAFETY: sized + aligned for `TypedSlot<C>` by the check above;
1193 // uniquely owned (`next_slot` windows are disjoint); `'static` backing.
1194 let slot_mu: &'static mut MaybeUninit<TypedSlot<C>> =
1195 unsafe { &mut *(raw.as_mut_ptr() as *mut MaybeUninit<TypedSlot<C>>) };
1196 let cell = Arc::new(ComponentCell {
1197 slot: RefCell::new(place_slot::<C>(slot_mu)),
1198 publishers: RefCell::new(heapless::Vec::new()),
1199 service_clients: RefCell::new(heapless::Vec::new()),
1200 action_clients: RefCell::new(heapless::Vec::new()),
1201 action_servers: RefCell::new(heapless::Vec::new()),
1202 timers: RefCell::new(heapless::Vec::new()),
1203 svc_ctxs: [const { UnsafeCell::new(MaybeUninit::uninit()) }; _],
1204 svc_ctxs_used: core::cell::Cell::new(0),
1205 act_srv_ctxs: [const { UnsafeCell::new(MaybeUninit::uninit()) }; _],
1206 act_srv_ctxs_used: core::cell::Cell::new(0),
1207 act_cli_ctxs: [const { UnsafeCell::new(MaybeUninit::uninit()) }; _],
1208 act_cli_ctxs_used: core::cell::Cell::new(0),
1209 header: CellHeader {
1210 callback_dispatches: AtomicUsize::new(0),
1211 message_dispatches: AtomicUsize::new(0),
1212 },
1213 // W4c — set by `apply_param_services` once the store exists.
1214 #[cfg(feature = "param-store")]
1215 param_server: core::cell::Cell::new(core::ptr::null()),
1216 // phase-426 W3 — overwritten below with the node `register()`
1217 // actually created.
1218 #[cfg(feature = "param-store")]
1219 param_node: core::cell::Cell::new(0),
1220 });
1221 let component_idx = self.components.len();
1222 self.ticking |= C::HAS_TICK;
1223 self.components.push(cell.clone());
1224 self.component_levels
1225 .push(self.executor.registering_level());
1226
1227 let mut sink = ExecutorSink {
1228 cell: CellHandle::Pooled(cell.clone()),
1229 nodes: heapless::Vec::new(),
1230 node_identity: LaunchIdentity::NONE, // direct API — no launch injection
1231 remaps: crate::node::LaunchParams::EMPTY, // direct API — no launch remaps
1232 qos_overrides: &[], // direct API — no plan overrides
1233 launch_params: crate::node::LaunchParams::EMPTY, // direct API -- no launch params
1234 };
1235 let result = {
1236 let mut frame = crate::node::ComponentFrame::new(&mut sink);
1237 let mut context = NodeContext::new(C::NAME, &mut self.executor, &mut frame);
1238 C::register(&mut context)
1239 };
1240 // phase-426 W3 — the node this component actually created, so its
1241 // callbacks read ITS parameters and not the primary's. First node: a
1242 // component declares one in every shipped shape, and the reads are
1243 // per COMPONENT, which is the granularity a cell has.
1244 #[cfg(feature = "param-store")]
1245 if let Some(node) = sink.nodes.first() {
1246 cell.param_node.set(node.node_id.raw());
1247 }
1248 if result.is_err() {
1249 // Roll back the slot push so `component_count` stays
1250 // consistent with what users observe.
1251 self.components.pop();
1252 self.component_levels.pop();
1253 }
1254 result?;
1255
1256 // W4c — capture the executor's volatile param store on the cell (if param
1257 // services were registered before this call) so the node's callbacks can read
1258 // `ctx.parameter::<T>(name)`. Mirrors the install-seam path.
1259 #[cfg(feature = "param-store")]
1260 if let Some(server) = self.executor.params() {
1261 cell.param_server.set(server as *const _);
1262 }
1263
1264 Ok(RegisteredNode {
1265 component_idx,
1266 _phantom: PhantomData,
1267 })
1268 }
1269
1270 // Phase 258 (Track 2, w5) — ~~`register_dispatch_slot`~~ (the four-fn-ptr
1271 // BSP registration) is gone with the retired ~~`register_dispatch_slot_dyn`~~
1272 // bridge + ~~`nros_run_components`~~. Owned-spin / BSP entries now register
1273 // through `install_node_typed` (the uniform install seam).
1274
1275 /// Drive one executor iteration + a `tick` per registered
1276 /// component.
1277 pub fn spin_once(&mut self, timeout: Duration) -> Result<(), ExecutorError> {
1278 let _result = self.executor.spin_once(timeout);
1279 self.run_ticks();
1280 Ok(())
1281 }
1282
1283 /// [`Self::spin_once`], returning the executor's own per-iteration counts
1284 /// instead of discarding them.
1285 ///
1286 /// `spin_once` throws away a `SpinOnceResult` that already carries exactly
1287 /// what a stalled sched task needs to be diagnosed: how many timers fired, how
1288 /// many subscription callbacks ran, and how many errored. Without it, "the
1289 /// sched task's timer never fires" and "the sched task's callback runs and its publish
1290 /// fails" are the same observation from outside the guest — a silent topic.
1291 pub fn spin_once_counted(
1292 &mut self,
1293 timeout: Duration,
1294 ) -> Result<nros_node::SpinOnceResult, ExecutorError> {
1295 let result = self.executor.spin_once(timeout);
1296 self.run_ticks();
1297 Ok(result)
1298 }
1299
1300 /// Route a signaled callback to
1301 /// every registered component slot.
1302 ///
1303 /// The RTIC (`nros-board-rtic-stm32f4`) and Embassy
1304 /// (`nros-board-embassy-stm32f4`) dispatch tasks dequeue a
1305 /// [`nros_platform::SignaledCallback`] envelope from their SPSC
1306 /// queue / Embassy channel and need a routing entry point that
1307 /// hands the callback off to the right Node's `on_callback`
1308 /// trampoline. This method is that entry point.
1309 ///
1310 /// # Strategy — linear scan
1311 ///
1312 /// Each registered slot dispatches through the codegen-emitted
1313 /// `d()` trampoline from `nros::node!()` (a ~~`dispatch_fn`~~ pointer once;
1314 /// see
1315 /// `packages/core/nros-macros/src/lib.rs`). That trampoline calls
1316 /// `<NodeTy as ExecutableNode>::on_callback`, whose body
1317 /// `match`es on the callback's own tag set
1318 /// (`Subscription` / `Timer` / `Service` / `Action` ids) and is a
1319 /// no-op for non-matching `cb_id`s. So a linear scan across every
1320 /// slot is correct — each slot self-filters and at most one
1321 /// component actually acts on a given `cb_id`. A focused
1322 /// `cb_id → slot` index is a separate follow-up; the trampoline's
1323 /// tag dispatch already gates the real work cheaply (string
1324 /// compare on statically known literals), so the linear scan is
1325 /// the minimum-viable wiring that closes the conceptual gap left
1326 /// by the B.3 / C.3 skeleton emits.
1327 ///
1328 /// # Borrow semantics
1329 ///
1330 /// Each `ComponentCell`'s slot lives behind a [`RefCell`]; the
1331 /// per-slot dispatch takes `try_borrow_mut` and is a no-op on
1332 /// re-entrancy. The runtime is single-threaded by construction
1333 /// (the dispatch task owns it via `&mut self`), so the borrow
1334 /// always succeeds in normal flow.
1335 ///
1336 /// # Both populations
1337 ///
1338 /// A component reaches this runtime one of two ways, and the
1339 /// two are disjoint (see the `observed_callback_counts` fold):
1340 /// [`register_node`](Self::register_node) pushes it to `components`, while
1341 /// the install seam every `nros::node!` `register(runtime)` goes through
1342 /// (`install_node_typed*` → `register_node_borrowed`) ENROLLS it in the
1343 /// executor and never pushes. This scanned `components` alone, so since
1344 /// the RTIC entry moved onto `register(runtime)` every signaled
1345 /// callback the RTIC/Embassy dispatch task forwarded reached no component.
1346 pub fn dispatch_callback(&mut self, cb_id: &str, ctx: &mut CallbackCtx<'_>) {
1347 for cell in &self.components {
1348 if let Ok(mut slot) = cell.slot.try_borrow_mut() {
1349 slot.dispatch(cb_id, ctx);
1350 }
1351 }
1352 for state in self.executor.enrolled_component_states() {
1353 // SAFETY: every enrolled state is a placed `ComponentCell` from
1354 // `register_node_borrowed` (the only enroll site), kept alive until
1355 // `Executor::drop`; `CellPrefix` is its layout-checked prefix.
1356 let cell = unsafe { &*(state as *const CellPrefix) };
1357 if let Ok(mut slot) = cell.slot.try_borrow_mut() {
1358 slot.dispatch(cb_id, ctx);
1359 }
1360 }
1361 }
1362
1363 /// Spin until the executor's halt flag is raised.
1364 ///
1365 /// This used to be `#[cfg(feature = "std")]` and described
1366 /// itself as hosted-only, but the body is `Duration` + `spin_once` +
1367 /// `is_halted`, none of which need an OS. The gate was describing a
1368 /// CONVENTION (a BSP usually wants its own loop so it can interleave
1369 /// board work) as if it were a requirement, and a bare-metal image that
1370 /// wants exactly this loop had to hand-roll it to get it.
1371 ///
1372 /// It does need `alloc`: the halt flag is an `Arc`, so a core-only image
1373 /// has no flag to poll.
1374 #[cfg(feature = "alloc")]
1375 pub fn spin(&mut self) -> Result<(), ExecutorError> {
1376 // 10 ms tick cadence — matches the existing executor spin
1377 // budgeting (see `SpinOptions::poll_interval`); short enough that
1378 // component `tick` hooks observe latency under one cycle.
1379 let tick = Duration::from_millis(10);
1380 while !self.executor.is_halted() {
1381 let _ = self.executor.spin_once(tick);
1382 self.run_ticks();
1383 }
1384 Ok(())
1385 }
1386
1387 /// Halt a running [`spin`](Self::spin). Idempotent.
1388 ///
1389 /// Forwards to `Executor::cancel()`, the rclcpp spelling.
1390 /// `Executor::halt` is now a deprecated forwarder onto it, so naming the old
1391 /// spelling here would be this crate warning at itself.
1392 #[cfg(feature = "alloc")]
1393 pub fn halt(&self) {
1394 self.executor.cancel();
1395 }
1396
1397 fn run_ticks(&mut self) {
1398 self.run_ticks_for(None);
1399 }
1400
1401 /// The registered components' ticks for one pass. Issue 2020 -- only
1402 /// those the pass's level owns (`Executor::pass_ticks_owner`):
1403 /// `band_level` is a level worker's band pass, `None` the executor's own
1404 /// worker (the boot level, or the only one).
1405 pub(crate) fn run_ticks_for(&mut self, band_level: Option<u8>) {
1406 // Per-component tick — each component's resolver is its own cell.
1407 // Phase 212.M-F.23: the tick reaches the executor (service-client
1408 // call_raw poll, action-server complete/feedback) through a raw
1409 // pointer so `&self.components` and `&mut self.executor` (disjoint
1410 // fields) can be live at once.
1411 let exec_ptr: *mut Executor<'static> = &mut self.executor;
1412 for (cell, owner) in self.components.iter().zip(&self.component_levels) {
1413 // SAFETY: a shared read of the executor between ticks; no tick
1414 // is running and the `&mut` above is not used meanwhile.
1415 if !unsafe { &*exec_ptr }.pass_ticks_owner(band_level, *owner) {
1416 continue;
1417 }
1418 tick_one_cell(cell.as_ref(), exec_ptr);
1419 }
1420 }
1421}
1422
1423/// Phase 258 (Track 2, 2a) — drive one component cell's `tick` against the
1424/// executor. The single source of truth for the per-component tick body,
1425/// shared by [`ExecutorNodeRuntime::run_ticks`] (the owned-runtime path) and
1426/// the executor-enrolled [`component_tick_trampoline`] (the `install` path).
1427///
1428/// `exec_ptr` is reached through a raw `*mut Executor<'static>` so the caller can hold
1429/// the component (`&ComponentCell`) and the executor live at once — they are
1430/// disjoint, and `RuntimeActions` / `RuntimeClientDispatch` reborrow `&mut`
1431/// per call (see their docs).
1432fn tick_one_cell(cell: &dyn CellView, exec_ptr: *mut Executor<'static>) {
1433 let resolver = CellResolver { cell };
1434 let service_clients = cell.service_clients();
1435 let action_clients = cell.action_clients();
1436 let action_servers = cell.action_servers();
1437 let mut actions = RuntimeActions {
1438 executor: exec_ptr,
1439 handles: &action_servers,
1440 };
1441 let mut clients = RuntimeClientDispatch {
1442 executor: exec_ptr,
1443 services: &service_clients,
1444 actions: &action_clients,
1445 };
1446 let mut graph = RuntimeGraph { executor: exec_ptr };
1447 let mut ctx = TickCtx::new(&resolver, &mut actions, &mut clients);
1448 ctx.set_graph(&mut graph);
1449 // W4c — `tick` reads `ctx.parameter::<T>(name)` from the store via the cell pointer
1450 // (the store is a separate `Box<ParamState>` allocation, so this does NOT alias the
1451 // `&mut Executor<'static>` the action/client tick calls reborrow through `exec_ptr`).
1452 #[cfg(feature = "param-store")]
1453 ctx.set_param_server(cell.view_param_server(), cell.view_param_node());
1454 // Issue 2075 — ops the pass's callbacks requested, then the tick, then
1455 // the ops the tick requested.
1456 apply_timer_ops(cell, exec_ptr);
1457 cell.try_with_slot_mut(&mut |slot| slot.tick(&mut ctx));
1458 apply_timer_ops(cell, exec_ptr);
1459}
1460
1461/// Phase 258 (Track 2, 2a) — executor `ComponentSlot.tick` trampoline. Casts
1462/// the enrolled state back to the component cell + `exec_ctx` back to the
1463/// executor and drives one tick. The layering-clean `extern "C"` shim the
1464/// `nros-node` [`Executor`] calls each `spin_once` (it can't name `nros`'s
1465/// [`ComponentCell`] — see [`register_node_borrowed`]'s enroll).
1466///
1467/// # Safety
1468/// `state` must be the placed `ComponentCell` enrolled via
1469/// [`Executor::enroll_component`] from [`register_node_borrowed`] (per-class
1470/// static storage or the alloc convenience's leaked box — live until
1471/// `component_drop_trampoline`); `exec_ctx` must be the live
1472/// `*mut Executor<'static>` the executor passes itself.
1473unsafe extern "C" fn component_tick_trampoline<
1474 const PUBS: usize,
1475 const SVCS: usize,
1476 const ACTC: usize,
1477 const ACTS: usize,
1478 const SSRV: usize,
1479 const TIMS: usize,
1480>(
1481 state: *mut core::ffi::c_void,
1482 exec_ctx: *mut core::ffi::c_void,
1483) {
1484 // SAFETY: `state` is a live placed `ComponentCell` (kept in place until
1485 // the drop trampoline); this monomorphization was enrolled alongside it,
1486 // so the cast target is the cell's true type.
1487 let cell = unsafe { &*(state as *const ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>) };
1488 tick_one_cell(cell, exec_ctx as *mut Executor<'static>);
1489}
1490
1491/// Phase 258 (Track 2, 2a; W5-endgame step 2b) — executor `ComponentSlot.drop`
1492/// trampoline. Drops the placed `ComponentCell` (which drops the component
1493/// state through its borrowed slot) IN PLACE — the storage itself is a
1494/// `static` (or the alloc convenience's leaked box, whose bytes are never
1495/// freed, matching its slot's documented leak). Run exactly once on
1496/// `Executor::drop`; the storage's monotonic `take` never re-hands the
1497/// region out, so nothing can observe the dropped bytes.
1498///
1499/// # Safety
1500/// `state` must be the placed `ComponentCell` enrolled via
1501/// [`Executor::enroll_component`], not yet dropped.
1502unsafe extern "C" fn component_drop_trampoline<
1503 const PUBS: usize,
1504 const SVCS: usize,
1505 const ACTC: usize,
1506 const ACTS: usize,
1507 const SSRV: usize,
1508 const TIMS: usize,
1509>(
1510 state: *mut core::ffi::c_void,
1511) {
1512 // SAFETY: enroll's contract above; dropped exactly once by the executor,
1513 // through the monomorphization enrolled with the cell.
1514 unsafe {
1515 core::ptr::drop_in_place(state as *mut ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>)
1516 };
1517}
1518
1519// =============================================================================
1520// Phase 212.N.7 step-3.3 — bridge to platform-side `NodeDispatchRuntime`.
1521// =============================================================================
1522//
1523// `nros_platform::NodeDispatchRuntime` is the board-side sink: object-safe +
1524// `no_std`. `BoardEntry::run` installs this `ExecutorNodeRuntime` impl on the
1525// per-boot `RuntimeCtx::runtime` slot. The owned-spin entry reaches the live
1526// executor through `executor_handle()` (a raw pointer crosses the layering wall
1527// cleanly) and installs via `nros::__macro::install_node_typed`. Phase 258 (w5) retired
1528// the old ~~`register_dispatch_slot_dyn`~~ four-fn-ptr bridge.
1529
1530#[cfg(feature = "alloc")]
1531impl ::nros_platform::NodeDispatchRuntime for ExecutorNodeRuntime {
1532 fn spin_once(&mut self, timeout_ms: u32) -> Result<(), ()> {
1533 Self::spin_once(self, Duration::from_millis(timeout_ms.into())).map_err(|_| ())
1534 }
1535
1536 fn entry_spin_budget_ms(&self) -> u32 {
1537 Self::entry_spin_budget(self)
1538 .as_millis()
1539 .min(u32::MAX as u128) as u32
1540 }
1541
1542 fn restart_timing(&mut self) {
1543 self.executor.restart_timing();
1544 }
1545
1546 fn executor_handle(&mut self) -> *mut core::ffi::c_void {
1547 // Phase 258 (Track 2, 2a) — hand the owned-spin entry a raw pointer to
1548 // the executor this runtime owns, so a Node pkg's `register(runtime)`
1549 // can install through `nros::__macro::install_node_typed` (same seam as the
1550 // C/C++ typed entries). The pointer is valid for the runtime's life
1551 // (the executor is an inline field); the install call uses it only
1552 // during registration, before any concurrent spin.
1553 &mut self.executor as *mut Executor<'static> as *mut core::ffi::c_void
1554 }
1555
1556 // phase-446 W6 -- record the contract's declared parameters on the owned
1557 // executor; `ExecutorSink`'s parameter arm checks each declaration against
1558 // them. Without `param-services` there is no store, so the default no-op.
1559 #[cfg(feature = "param-store")]
1560 fn apply_declared_params(
1561 &mut self,
1562 nodes: &'static [(&'static str, &'static str)],
1563 params: &'static [(&'static str, &'static str, u8)],
1564 ) -> Result<(), &'static str> {
1565 self.executor
1566 .set_declared_params(nros_params::DeclaredParams::new(nodes, params));
1567 Ok(())
1568 }
1569
1570 // RFC-0128 D2 (phase-554 W2) — one managed node: find the node its launch
1571 // entry created, give it a machine served under its own name, and drive
1572 // its own boot autostart. Only compiled with `lifecycle-services`; without
1573 // it the trait default no-op applies (and `nros::main!` const-asserts the
1574 // feature for an image that has managed nodes). Nothing here touches the
1575 // executor's own identity: an image registers a machine for exactly the
1576 // nodes its model marks managed.
1577 #[cfg(feature = "lifecycle-services")]
1578 fn apply_lifecycle_node(
1579 &mut self,
1580 namespace: &'static str,
1581 name: &'static str,
1582 autostart: u8,
1583 ) -> Result<(), &'static str> {
1584 let Some(node) = self.executor.managed_node_id(name, namespace) else {
1585 return Err(
1586 "the launch file marks this node managed, but no node with its \
1587 name and namespace is in the executor's node table: its \
1588 component did not create it under the launch name",
1589 );
1590 };
1591 manage_node(&mut self.executor, node, autostart)
1592 }
1593
1594 // RFC-0128 D2, ruled 2026-11-13 ("the code decides, as in ROS 2"): a
1595 // self-bringup has no launch file to mark a node managed, so the managed
1596 // nodes are exactly those whose own code registered a machine while its
1597 // component was built. Nothing is inferred from build order: a plain node
1598 // stays plain and publishes at once. Each code-managed node is driven to
1599 // the image's `[lifecycle] autostart`, in node-table order.
1600 #[cfg(feature = "lifecycle-services")]
1601 fn apply_lifecycle_self_bringup(&mut self, autostart: u8) -> Result<(), &'static str> {
1602 // SAFETY: each machine and its callbacks were registered by the
1603 // node's own component, which the runtime keeps alive for the
1604 // executor's life.
1605 unsafe { self.executor.drive_code_managed_autostart(autostart) }
1606 .map(|_| ())
1607 .map_err(|_| "a node's boot autostart transition was refused by its callback")
1608 }
1609
1610 // Phase 264 W4b -- register the 6 ROS 2 parameter services on the owned executor
1611 // and create the volatile param store. issue 1272 -- it no longer seeds the
1612 // launch `<param>` initials: those used to arrive here as one flat list and all
1613 // land on the primary node; now `ExecutorSink::seed_launch_params` declares each
1614 // node's own on the node `create_node` builds. Only
1615 // compiled with `param-services`; without it the trait default no-op applies, so a
1616 // `[param_services]` block is silently inert (the Entry opts in by enabling
1617 // `nros/param-services`). `nros::main!` calls this when `system.toml` declares
1618 // `[param_services]`. Reconfigured values (via `ros2 param set`) live in RAM until
1619 // the next boot — persistence is out of scope (issue 0080).
1620 // W4c note: `nros::main!` emits this BEFORE the per-node `register` calls, so the
1621 // store exists when each cell is created — `register_node_borrowed` / `register_node`
1622 // then capture the (stable, boxed) `ParameterServer` address on the cell, letting a
1623 // callback read `ctx.parameter::<T>(name)`. (The macro-path cells live in the
1624 // executor's tick registry, not `self.components`, so a post-pass here wouldn't reach
1625 // them — capture-at-registration does.)
1626 #[cfg(feature = "param-services")]
1627 fn apply_param_services(&mut self) -> Result<(), &'static str> {
1628 self.executor
1629 .register_parameter_services()
1630 .map_err(|e| capability_reason(&e))
1631 }
1632
1633 // phase-461 W6 — the `params` axis: build the store before the per-node
1634 // `register` calls (so each cell captures it, as above) and register no
1635 // service. `ros2 param` reaches nothing in such an image, by declaration.
1636 #[cfg(feature = "param-store")]
1637 fn apply_param_store(&mut self) -> Result<(), &'static str> {
1638 self.executor
1639 .register_parameter_store()
1640 .map_err(|e| capability_reason(&e))
1641 }
1642
1643 fn observed_callback_counts(&self) -> (usize, usize) {
1644 let direct = self
1645 .components
1646 .iter()
1647 .fold((0, 0), |(callbacks, messages), cell| {
1648 let (c, m) = cell.dispatch_counts();
1649 (callbacks + c, messages + m)
1650 });
1651 // issue #140 — install-seam components (`nros::node!` →
1652 // `install_node_typed*` → `register_node_borrowed`) never enter
1653 // `self.components`; their cells live only as the executor's enrolled
1654 // component slots (leaked `Arc<ComponentCell>`s). Without folding them
1655 // the hosted spin reported callbacks=0 for every macro-baked entry
1656 // (multihost robot2 et al.) while dispatch demonstrably ran. The two
1657 // populations are disjoint by construction: `register_node` pushes to
1658 // `components` and does not enroll; `register_node_borrowed` enrolls
1659 // and does not push.
1660 self.executor
1661 .enrolled_component_states()
1662 .fold(direct, |(callbacks, messages), state| {
1663 // SAFETY: every enrolled state is a leaked `Arc<ComponentCell>`
1664 // from `register_node_borrowed` (the only enroll site); the
1665 // executor keeps it alive until `Executor::drop`, and we only
1666 // read its atomic counters here.
1667 let header = unsafe { &*(state as *const CellHeader) };
1668 (
1669 callbacks + header.callback_dispatches.load(Ordering::Relaxed),
1670 messages + header.message_dispatches.load(Ordering::Relaxed),
1671 )
1672 })
1673 }
1674}
1675
1676// =============================================================================
1677// Internal sink — bridges `NodeRuntime` declarations onto the
1678// live executor.
1679// =============================================================================
1680
1681/// The launch `<node name= namespace=>` identity for one component: each half
1682/// `None` when the launch states none, and then the component's `NodeOptions`
1683/// value stands for that half (issue 2590).
1684#[derive(Clone, Copy, Debug, Default)]
1685pub(crate) struct LaunchIdentity {
1686 name: Option<&'static str>,
1687 namespace: Option<&'static str>,
1688}
1689
1690impl LaunchIdentity {
1691 /// No launch identity: the component's `NodeOptions` name and namespace.
1692 pub(crate) const NONE: Self = Self {
1693 name: None,
1694 namespace: None,
1695 };
1696}
1697
1698impl From<Option<(&'static str, &'static str)>> for LaunchIdentity {
1699 /// `nros::main!`'s form: both halves or neither.
1700 fn from(v: Option<(&'static str, &'static str)>) -> Self {
1701 match v {
1702 Some((name, namespace)) => Self {
1703 name: Some(name),
1704 namespace: Some(namespace),
1705 },
1706 None => Self::NONE,
1707 }
1708 }
1709}
1710
1711/// phase-483 W3 — the live component runtime's registration sink. It no
1712/// longer holds the executor: the [`crate::Node`] a component's `register`
1713/// holds borrows it, so the sink receives it per call (`FrameSink`).
1714struct ExecutorSink<'a> {
1715 cell: CellHandle,
1716 /// Per-registration node mapping: stable id → executor `NodeId` plus the
1717 /// EFFECTIVE `(name, namespace)` the node was created with (launch identity
1718 /// or the `NodeOptions` default) — phase-306 W3 needs it to expand
1719 /// `~`/relative entity names per node.
1720 /// W5-endgame alloc-off — heapless: a component class declares a small,
1721 /// statically bounded number of NODES (nearly always one). Full = loud
1722 /// registration error, the registries' rule.
1723 nodes: heapless::Vec<SinkNode, MAX_SINK_NODES>,
1724 /// Phase 268 W1 — launch-injected node identity `(name, namespace)` baked by
1725 /// `nros::main!` per component. When `Some`, `create_node` uses this identity
1726 /// instead of the `NodeOptions` default; `None` → default stands (backward-compat).
1727 ///
1728 /// Issue 2590 -- each half on its own: a C/C++ entry's launch may name a
1729 /// node without a namespace (or the reverse), and the half it leaves out is
1730 /// the `NodeOptions` one, as the C++ entry's `rclcpp` arm treats it.
1731 node_identity: LaunchIdentity,
1732 /// Phase 305 W3 (issue 0255) — launch `<remap from= to=/>` rules baked by
1733 /// `nros::main!` for this component, or handed in by a C/C++ entry as a
1734 /// flat `[from, to, ...]` array (issue 2590). Applied in `create_entity`
1735 /// via the shared `node_metadata::resolve_name` seam (exact-FQN match,
1736 /// first rule wins). Empty → names still get ROS 2 expansion, no
1737 /// substitution.
1738 remaps: crate::node::LaunchParams<'a>,
1739 /// Issue #52 — the component's baked QoS-override codes, installed on each
1740 /// node this sink creates (`Executor::set_node_qos_overrides`) BEFORE the
1741 /// component declares entities, so `create_publisher`/`create_subscription`
1742 /// fold the matching ones in. Empty → nothing installed, zero cost.
1743 qos_overrides: &'static [nros_node::executor::node_record::QoSOverrideCode],
1744 /// issue 1272 -- the launch `<param>` initials `nros::main!` baked for this
1745 /// component (`RuntimeCtx::params`). `create_node` seeds them on the node it
1746 /// builds (see [`ExecutorSink::seed_launch_params`]). Empty for the direct
1747 /// API, which has no launch.
1748 #[cfg_attr(not(feature = "param-store"), allow(dead_code))]
1749 launch_params: crate::node::LaunchParams<'a>,
1750}
1751
1752struct SinkNode {
1753 stable_id: IdStr,
1754 node_id: nros_node::executor::NodeId,
1755 name: IdStr,
1756 namespace: IdStr,
1757}
1758
1759impl ExecutorSink<'_> {
1760 fn lookup_node(&self, stable_id: &str) -> Option<&SinkNode> {
1761 self.nodes.iter().find(|n| n.stable_id == stable_id)
1762 }
1763
1764 /// issue 1272 -- declare this component's launch `<param>` initials on
1765 /// `node`, the node `create_node` has just built.
1766 ///
1767 /// Before 1272 `nros::main!` flattened every node's initials into one list
1768 /// and `apply_param_services` declared them all on `NodeId::PRIMARY`, ahead
1769 /// of the `register` calls: node 0 held every node's values, and a second
1770 /// node's identical name was refused as a duplicate. Seeding here keys each
1771 /// value on the `NodeId` construction actually returned, so no index has
1772 /// to be predicted and none can drift.
1773 ///
1774 /// Only when the executor already has a parameter store, i.e. the system
1775 /// declared `[param_services]` and `apply_param_services` ran before this
1776 /// `register` call. That is the condition the flat seed had.
1777 ///
1778 /// A `false` from the store is a refusal only if the name is still absent
1779 /// afterwards: the store also answers `false` for "already declared".
1780 #[cfg(feature = "param-store")]
1781 fn seed_launch_params(
1782 &mut self,
1783 executor: &mut Executor<'static>,
1784 node: nros_node::executor::NodeId,
1785 ) -> NodeResult<()> {
1786 if executor.params().is_none() {
1787 return Ok(());
1788 }
1789 let params = self.launch_params;
1790 for (name, raw) in params.iter() {
1791 // phase-446 seam: the value's type is inferred from the launch
1792 // string; a type declared in the contract replaces this call.
1793 // Issue 2638 -- `[a, b]` is an array; `[]` seeds nothing (ROS
1794 // gives an empty sequence no value) and a list ROS refuses is
1795 // refused here, never seeded as a string.
1796 let mut value = nros_params::ParameterValue::NotSet;
1797 match value.assign_launch_text(raw) {
1798 Ok(()) => {}
1799 Err(nros_params::LaunchTextError::EmptyList) => continue,
1800 Err(e) => {
1801 nros_log::log_error!(
1802 nros_log::get_logger("nros"),
1803 "launch parameter '{name}' = `{raw}` has no value the store can hold \
1804 ({e:?}): refusing it"
1805 );
1806 return Err(NodeDeclError::Runtime);
1807 }
1808 }
1809 // Issue 2969 -- declared AS a launch seed, so the code's own first
1810 // declaration of the name adopts it instead of being refused.
1811 if !executor.seed_launch_parameter_on_ref(node, name, &value)
1812 && executor.get_parameter_on(node, name).is_none()
1813 {
1814 // GitHub #4018 -- the line names the store's capacity and the
1815 // knob that sizes it, not only the refusal.
1816 executor.report_parameter_refused(node, name);
1817 return Err(NodeDeclError::ParameterRejected);
1818 }
1819 }
1820 Ok(())
1821 }
1822}
1823
1824/// Issue 2360 — run one `create_entity` arm in its OWN frame.
1825///
1826/// `create_entity` is one `match` over entity kinds, and LLVM sized its frame
1827/// for everything it inlined from every arm: 26,996 B on a Rust Zephyr action
1828/// server (5,504 B on a talker), live on the main stack whichever arm ran, with
1829/// the registration it calls stacked on top. Each arm is a closure passed
1830/// here, and a never-inlined generic is one instance per closure, so only the
1831/// arm that runs has its frame live.
1832#[inline(never)]
1833fn out_of_line<R>(f: impl FnOnce() -> R) -> R {
1834 f()
1835}
1836
1837impl crate::node::FrameSink for ExecutorSink<'_> {
1838 fn create_node(
1839 &mut self,
1840 executor: &mut Executor<'static>,
1841 id: MetaNodeId<'_>,
1842 options: NodeOptions<'_>,
1843 ) -> NodeResult<nros_node::executor::NodeId> {
1844 if self.nodes.iter().any(|n| n.stable_id == id.as_str()) {
1845 return Err(NodeDeclError::Runtime);
1846 }
1847 // Phase 268 W1 — launch wins over the NodeOptions default (RFC-0046).
1848 // When `nros::main!` injected an identity for this component, use it;
1849 // otherwise fall back to what the Node declared in its `create_node` call.
1850 let name = self.node_identity.name.unwrap_or(options.name);
1851 let ns = self.node_identity.namespace.unwrap_or(options.namespace);
1852 let node_id = executor
1853 .node_builder(name)
1854 .namespace(ns)
1855 .domain_id(options.domain_id)
1856 .build()
1857 .map_err(decl_err_from_node)?;
1858 // Issue 1419 — open this node in the census recorder so the entities
1859 // `register()` declares next attribute to it (the RMW seam carries no
1860 // node). The namespace the node LANDED in, read back from the
1861 // executor, as the C and C++ node entry points report it. No-op unless
1862 // `metadata-mode` is on -- and under `ACTIVE`, because the namespace
1863 // lookup is work an empty hook body does not remove (phase-463 W5 I4).
1864 if crate::census_hooks::ACTIVE {
1865 let landed = match executor.node(node_id).map(|r| r.namespace.as_str()) {
1866 Some(s) if !s.is_empty() => s,
1867 _ => "/",
1868 };
1869 crate::census_hooks::on_node_create(name, landed, options.domain_id);
1870 }
1871 // Issue #52 — install the bake BEFORE the component declares any
1872 // entity on this node; entities created earlier could not be folded.
1873 if !self.qos_overrides.is_empty() {
1874 executor.set_node_qos_overrides(node_id, self.qos_overrides);
1875 }
1876 // issue 1272 -- the launch values belong to the component's launch
1877 // node, which is the FIRST node it builds (the same node its cell reads
1878 // parameters from, see `register_node_borrowed`). Seeded before the
1879 // component declares any entity, so its own declarations adopt them.
1880 #[cfg(feature = "param-store")]
1881 if self.nodes.is_empty() {
1882 self.seed_launch_params(executor, node_id)?;
1883 }
1884 self.nodes
1885 .push(SinkNode {
1886 stable_id: id_str(id.as_str())?,
1887 node_id,
1888 name: id_str(name)?,
1889 namespace: id_str(ns)?,
1890 })
1891 .map_err(|_| NodeDeclError::Runtime)?;
1892 Ok(node_id)
1893 }
1894
1895 fn create_entity(
1896 &mut self,
1897 executor: &mut Executor<'static>,
1898 metadata: EntityMetadata,
1899 ) -> NodeResult<()> {
1900 // Phase 228.C tier gate: when this executor runs a specific tier
1901 // (`active_groups` set by codegen), an entity whose callback group
1902 // is not active on this sched task is a no-op — no RMW handle, no slot.
1903 // An unlabeled entity (`callback_group == None`) is wildcard-eligible
1904 // and always registers; the degenerate single-sched-task executor leaves
1905 // `active_groups == None`, so every entity registers (byte-identical
1906 // to pre-228 output).
1907 //
1908 // issue 1172 — the lookup moved ABOVE this gate because the gate is now
1909 // node-qualified. It used to ask "is this GROUP active", which cannot
1910 // tell node A's `ctrl` from node B's `ctrl`: two nodes may legitimately
1911 // declare the same group id on different sched tasks, and the sched task then
1912 // admitted entities it did not own. Reordering is safe — a missing node
1913 // was already `NodeDeclError::Runtime` three lines below, so the only
1914 // change is which error wins for an entity that is BOTH off-sched-task and
1915 // owned by an unknown node, and that combination is a bug either way.
1916 let (node, node_name, node_ns) = {
1917 let entry = self
1918 .lookup_node(metadata.node_id.as_str())
1919 .ok_or(NodeDeclError::Runtime)?;
1920 (entry.node_id, entry.name.clone(), entry.namespace.clone())
1921 };
1922 if let Some(group) = metadata.callback_group.as_ref()
1923 && !executor.group_active(node_name.as_str(), node_ns.as_str(), group.as_str())
1924 {
1925 return Ok(());
1926 }
1927 // Phase 305 W3 (issue 0255) — expand `~`/relative source names against
1928 // the owning node's identity and apply the launch remap rules (shared
1929 // `nros_node::names` seam) before any name reaches the wire.
1930 // Timers have no wire name; parameter names are NOT remapped (matches
1931 // ROS 2 basic name remapping — param remaps are a separate rule class).
1932 //
1933 // Two tiers: `self.remaps` is the launch projection and therefore
1934 // AUTHORITATIVE; the executor's `--ros-args` rules (installed by
1935 // `nros::Context::create_executor` from `init_with_args`) are the
1936 // FALLBACK, consulted only when no launch rule matched — RFC-0046's
1937 // precedence, and rcl's local-before-global. Executors no `Context`
1938 // seeded carry no argv rules, so for every generated image this is the
1939 // launch slice alone, as it always was.
1940 let resolved_name = match metadata.kind {
1941 EntityKind::Timer | EntityKind::Parameter => None,
1942 _ => Some(
1943 nros_node::names::resolve_name_layered(
1944 metadata.source_name.as_str(),
1945 &node_name,
1946 &node_ns,
1947 self.remaps.iter(),
1948 nros_node::ros_args::argv_fallback(&*executor, &node_name, &node_ns),
1949 )
1950 .map_err(|_| NodeDeclError::Runtime)?,
1951 ),
1952 };
1953 let entity_name = resolved_name.as_ref().map(|r| r.as_str()).unwrap_or("");
1954 match metadata.kind {
1955 EntityKind::Publisher => out_of_line(|| {
1956 // Issue 0306 — the node's DECLARED profile
1957 // (`create_publisher_for_topic_with_qos`) rides
1958 // `metadata.qos`; this used to call the default-QoS
1959 // constructor, so every declarative entity was created
1960 // `QoSProfile::default()` and a node's own QoS was silently
1961 // discarded. Plan overrides still win: they fold in below this,
1962 // inside the executor's create path.
1963 let handle = executor
1964 .node_mut(node)
1965 .create_generic_publisher_with_qos(
1966 entity_name,
1967 metadata.type_name,
1968 metadata.type_hash,
1969 metadata.qos,
1970 )
1971 .map_err(decl_err_from_node)?;
1972 let id_owned = id_str(metadata.id.as_str())?;
1973 // Registry full = this component declared more entities than
1974 // CELL_REG_CAP — a registration error, never a silent drop.
1975 self.cell
1976 .view()
1977 .push_publisher(id_owned, handle)
1978 .map_err(|_| cell_full("publishers"))?;
1979 Ok(())
1980 }),
1981 EntityKind::Subscription => out_of_line(|| {
1982 let cb_id = metadata
1983 .callback_id
1984 .as_ref()
1985 .ok_or(NodeDeclError::Runtime)?;
1986 let cb_id_owned = id_str(cb_id.as_str())?;
1987 let cell = self.cell.clone();
1988 // phase-457 W5 (issue 1522) — THE branch, and it is on the
1989 // CLASSIFIER, not on `metadata.safety`.
1990 //
1991 // The metadata recorder states this subscription's
1992 // `in_place_capable` from the same call, because a Rust probe
1993 // opens no executor and so observes no registration
1994 // (`registration_observer` never fires on this road). Testing
1995 // the flag here as well would make the probe's answer a second
1996 // opinion about this site rather than a reading of it — which
1997 // is exactly what W3 deleted from the CLI. Gated by
1998 // `check-declared-subscription-shape`: every variant of
1999 // `DeclaredSubscriptionShape` must be named in this arm, so a
2000 // third lowering cannot fall through to the basic path while
2001 // the probe keeps stating the basic path's answer.
2002 let shape = metadata.declared_subscription_shape();
2003 use nros_node::executor::declared_shape::DeclaredSubscriptionShape;
2004 // Issue 2349 -- a subscription that asked for the message's
2005 // metadata registers on the info path, and its callback reads
2006 // it as `CallbackCtx::message_info()`. Not in place: the
2007 // classifier says so, and the probe states the same.
2008 if shape == DeclaredSubscriptionShape::BufferedRawInfo {
2009 let cell_i = self.cell.clone();
2010 let cb_i = cb_id_owned.clone();
2011 executor
2012 .node_mut(node)
2013 .create_generic_subscription_with_info_and_rx_hint(
2014 entity_name,
2015 metadata.type_name,
2016 metadata.type_hash,
2017 metadata.qos,
2018 metadata.rx_bound,
2019 move |payload: &[u8], info: Option<&nros_core::MessageInfo>| {
2020 dispatch_into_cell_with_info(cell_i.view(), &cb_i, payload, info);
2021 },
2022 )
2023 .map_err(decl_err_from_node)?;
2024 return Ok(());
2025 }
2026 // Phase 250 (Wave 2b) — a `.safety()` subscription registers via
2027 // the integrity-aware generic path so `CallbackCtx::integrity()`
2028 // surfaces CRC + sequence gap/dup. Gated: when `safety-e2e` is off
2029 // `declared_subscription_shape` masks the flag, never answers
2030 // `BufferedRawSafety`, and the basic path below runs.
2031 #[cfg(feature = "safety-e2e")]
2032 if shape == DeclaredSubscriptionShape::BufferedRawSafety {
2033 let cell_s = self.cell.clone();
2034 let cb_s = cb_id_owned.clone();
2035 executor
2036 .node_mut(node)
2037 .create_generic_subscription_with_integrity_and_rx_hint(
2038 entity_name,
2039 metadata.type_name,
2040 metadata.type_hash,
2041 metadata.rx_bound,
2042 move |payload: &[u8], status: &nros_node::IntegrityStatus| {
2043 dispatch_into_cell_with_integrity(
2044 cell_s.view(),
2045 &cb_s,
2046 payload,
2047 status,
2048 );
2049 },
2050 )
2051 .map_err(decl_err_from_node)?;
2052 return Ok(());
2053 }
2054 // `DeclaredSubscriptionShape::BufferedRaw` — the only shape
2055 // left, named so the gate can see that this arm handles it.
2056 //
2057 // Issue 0306 — same as the publisher branch: honour the
2058 // node's declared profile instead of defaulting it.
2059 executor
2060 .node_mut(node)
2061 // Issue 2208 -- with the type's bound the declaration
2062 // recorded, so the backend gets the same `rx_buffer_hint`
2063 // the typed executor path gives it.
2064 .create_generic_subscription_with_qos_and_rx_hint(
2065 entity_name,
2066 metadata.type_name,
2067 metadata.type_hash,
2068 metadata.qos,
2069 metadata.rx_bound,
2070 move |payload: &[u8]| {
2071 dispatch_into_cell(cell.view(), &cb_id_owned, payload);
2072 },
2073 )
2074 .map_err(decl_err_from_node)?;
2075 Ok(())
2076 }),
2077 EntityKind::Timer => out_of_line(|| {
2078 let cb_id = metadata
2079 .callback_id
2080 .as_ref()
2081 .ok_or(NodeDeclError::Runtime)?;
2082 let cb_id_owned = id_str(cb_id.as_str())?;
2083 // Issue #505 — prefer the microsecond field; fall back to
2084 // the millisecond one only for metadata that predates it.
2085 let period = match metadata.period_us {
2086 Some(us) => nros_node::TimerDuration::from_micros(us),
2087 None => nros_node::TimerDuration::from_millis(
2088 metadata.period_ms.ok_or(NodeDeclError::Runtime)?,
2089 ),
2090 };
2091 let cell = self.cell.clone();
2092 // phase-430 W4 — ONE registrar for both spellings. A timer
2093 // declared with no clock carries `TimerClockSource::Steady`,
2094 // which is the arena entry `register_timer` built anyway (same
2095 // fields, same seed), so the wall case is unchanged and a `Ros`
2096 // one now reaches the executor at all. Before W4 this site
2097 // called `register_timer` unconditionally and the declarative
2098 // surface could not express a clock, which is why a
2099 // `nros::main!` component had no way to own a ROS-time timer.
2100 //
2101 // Issue 2038 — and ONE registrar for the call info and the
2102 // autostart flag too: `register_timer_with_info` is the entry
2103 // `register_timer_on_clock` builds (same arena entry, same
2104 // seed) with the dispatcher's `TimerCallInfo` handed to the
2105 // closure and rcl's `autostart` honoured, the call
2106 // `Node::create_timer_with_info` makes. The info reaches the
2107 // component as `CallbackCtx::timer_info`.
2108 let autostart = metadata.timer_autostart;
2109 let handle = executor
2110 .register_timer_with_info(
2111 period,
2112 metadata.timer_clock,
2113 autostart,
2114 move |info: &nros_node::TimerCallInfo| {
2115 dispatch_timer_into_cell(cell.view(), &cb_id_owned, info);
2116 },
2117 )
2118 .map_err(decl_err_from_node)?;
2119 // Issue 2075 — file the handle so a context can reset or
2120 // cancel it by id. A full table leaves the timer running and
2121 // uncontrollable (`UnknownTimer` names the bound when it is
2122 // asked for); a key collision is a loud registration error.
2123 self.cell
2124 .view()
2125 .push_timer(timer_key(metadata.id.as_str()), handle)
2126 .map_err(|()| NodeDeclError::Metadata(NodeMetadataError::DuplicateId))?;
2127 // Issue 1419 — a Rust timer never reaches the RMW, so this hook
2128 // is how it enters the census. Recorded AFTER the tier gate
2129 // above, so a sched-task entry's census holds each timer once, on
2130 // the sched task that owns it. `Wall` on the steady clock, `Clock`
2131 // on any other — the split the C and C++ entry points report.
2132 crate::census_hooks::on_timer_create(
2133 match metadata.timer_clock {
2134 nros_node::executor::TimerClockSource::Steady => {
2135 crate::node_metadata::TimerKind::Wall
2136 }
2137 _ => crate::node_metadata::TimerKind::Clock,
2138 },
2139 period.as_millis(),
2140 );
2141 Ok(())
2142 }),
2143 // Phase 212.M-F.23 — service / action client + server dispatch on
2144 // the single-node runtime. The executor-level `register_*_on`
2145 // calls add an arena dispatch entry, so inbound requests / goals
2146 // are serviced inside `spin_once`; the leaked `*Ctx` trampoline
2147 // contexts bridge back into the component's `on_callback`. Client
2148 // handles are stashed in the cell for the tick-side dispatch
2149 // (`RuntimeClientDispatch` / `RuntimeActions` in `run_ticks`).
2150 EntityKind::ServiceServer => out_of_line(|| {
2151 let cb_id = metadata
2152 .callback_id
2153 .as_ref()
2154 .ok_or(NodeDeclError::Runtime)?;
2155 let ctx = self
2156 .cell
2157 .view()
2158 .place_service_ctx(ServiceServerCtx {
2159 cell: self.cell.clone(),
2160 callback_id: id_str(cb_id.as_str())?,
2161 })
2162 .map_err(|_| cell_full("service servers"))?;
2163 executor
2164 .register_service_raw_sized_on::<1024, 1024>(
2165 node,
2166 entity_name,
2167 metadata.type_name,
2168 metadata.type_hash,
2169 crate::QoSProfile::services_default(),
2170 service_server_trampoline,
2171 ctx,
2172 )
2173 .map_err(decl_err_from_node)?;
2174 Ok(())
2175 }),
2176 EntityKind::ServiceClient => out_of_line(|| {
2177 let hid = executor
2178 .register_service_client_raw_sized_on::<1024>(
2179 node,
2180 entity_name,
2181 metadata.type_name,
2182 metadata.type_hash,
2183 crate::QoSProfile::services_default(),
2184 None,
2185 core::ptr::null_mut(),
2186 )
2187 .map_err(decl_err_from_node)?;
2188 self.cell
2189 .view()
2190 .push_service_client(id_str(metadata.id.as_str())?, hid)
2191 .map_err(|_| cell_full("service clients"))?;
2192 Ok(())
2193 }),
2194 EntityKind::ActionServer => out_of_line(|| {
2195 let goal_cb = metadata
2196 .callback_id
2197 .as_ref()
2198 .ok_or(NodeDeclError::Runtime)?;
2199 let cancel_cb = metadata
2200 .action_cancel_callback_id
2201 .as_ref()
2202 .ok_or(NodeDeclError::Runtime)?;
2203 let accepted_cb = metadata
2204 .action_accepted_callback_id
2205 .as_ref()
2206 .map(|c| id_str(c.as_str()))
2207 .transpose()?;
2208 let ctx = self
2209 .cell
2210 .view()
2211 .place_action_server_ctx(ActionServerCtx {
2212 cell: self.cell.clone(),
2213 goal_callback_id: id_str(goal_cb.as_str())?,
2214 cancel_callback_id: id_str(cancel_cb.as_str())?,
2215 accepted_callback_id: accepted_cb,
2216 })
2217 .map_err(|_| cell_full("action servers"))?;
2218 let handle = executor
2219 .register_action_server_raw_sized::<1024, 1024, 1024, 4>(
2220 crate::internals::RawActionServerSpec {
2221 node_id: Some(node),
2222 action_name: entity_name,
2223 type_name: metadata.type_name,
2224 type_hash: metadata.type_hash,
2225 hashes: metadata.action_hashes.ok_or(NodeDeclError::Runtime)?,
2226 qos: crate::QoSProfile::services_default(),
2227 goal_callback: action_goal_trampoline,
2228 cancel_callback: action_cancel_trampoline,
2229 accepted_callback: Some(action_accepted_trampoline),
2230 context: ctx,
2231 },
2232 )
2233 .map_err(decl_err_from_node)?;
2234 self.cell
2235 .view()
2236 .push_action_server(id_str(metadata.id.as_str())?, handle)
2237 .map_err(|_| cell_full("action servers"))?;
2238 Ok(())
2239 }),
2240 EntityKind::ActionClient => out_of_line(|| {
2241 // A bound `callback_id` (set by
2242 // `create_action_client_with_callbacks_for_name`) delivers the
2243 // terminal goal result to the component via `on_callback`; the
2244 // optional `action_accepted_callback_id` slot carries the
2245 // feedback callback (reused — unused on a client). The executor
2246 // auto-drives accept → feedback → result during spin and invokes
2247 // these trampolines. No callbacks → send-goal only.
2248 let (result_callback, feedback_callback, ctx) = match metadata.callback_id.as_ref()
2249 {
2250 Some(result_cb) => {
2251 let feedback_cb = metadata
2252 .action_accepted_callback_id
2253 .as_ref()
2254 .map(|c| id_str(c.as_str()))
2255 .transpose()?;
2256 let ctx = self
2257 .cell
2258 .view()
2259 .place_action_client_ctx(ActionClientCtx {
2260 cell: self.cell.clone(),
2261 result_callback_id: id_str(result_cb.as_str())?,
2262 feedback_callback_id: feedback_cb.clone(),
2263 })
2264 .map_err(|_| cell_full("action clients"))?;
2265 let fb = feedback_cb.map(|_| action_feedback_trampoline as _);
2266 (Some(action_result_trampoline as _), fb, ctx)
2267 }
2268 None => (None, None, core::ptr::null_mut()),
2269 };
2270 let handle = executor
2271 .register_action_client_raw_sized::<1024, 1024, 1024>(
2272 crate::internals::RawActionClientSpec {
2273 node_id: Some(node),
2274 action_name: entity_name,
2275 type_name: metadata.type_name,
2276 type_hash: metadata.type_hash,
2277 hashes: metadata.action_hashes.ok_or(NodeDeclError::Runtime)?,
2278 goal_response_callback: None,
2279 feedback_callback,
2280 result_callback,
2281 cancel_response_callback: None,
2282 context: ctx,
2283 },
2284 )
2285 .map_err(decl_err_from_node)?;
2286 self.cell
2287 .view()
2288 .push_action_client(id_str(metadata.id.as_str())?, handle.entry_index())
2289 .map_err(|_| cell_full("action clients"))?;
2290 Ok(())
2291 }),
2292 EntityKind::Parameter => out_of_line(|| {
2293 // Issue 2360 -- ONE value, filled in place. A `ParameterValue`
2294 // is as large as its largest variant (~8 KiB at the default
2295 // capacities). Built by value, every arm of the conversion and
2296 // the `unwrap_or` fallback kept its own copy in this frame:
2297 // 24,960 B of main stack on thumbv7m for one declared
2298 // parameter.
2299 let mut value = nros_params::ParameterValue::NotSet;
2300 param_default_into(metadata.parameter_default.as_ref(), &mut value);
2301 // Issue 1419 — the declaration as the code made it, BEFORE the
2302 // store answers and whether or not `param-services` gives this
2303 // image a store at all: the census describes the code.
2304 crate::census_hooks::on_param_declare(metadata.source_name.as_str(), &value);
2305 // Phase 212.M-F.23 Wave 2 — declarative parameter dispatch on
2306 // the single-node runtime. The first declared parameter lazily
2307 // stands up the 6 ROS 2 parameter services for this executor's
2308 // node; `spin_once` drives those service servers thereafter
2309 // (`#[cfg(param-services)]` block at spin.rs). The declared
2310 // source default seeds the value. With `param-services` off the
2311 // arm is a no-op (entity declared, no RMW handle) — byte-
2312 // identical to the pre-Wave-2 behavior.
2313 #[cfg(feature = "param-store")]
2314 {
2315 // Issue 1897 -- a store-only build has no services to
2316 // stand up; it builds the store and serves nothing.
2317 if executor.params().is_none() {
2318 #[cfg(feature = "param-services")]
2319 executor
2320 .register_parameter_services()
2321 .map_err(decl_err_from_node)?;
2322 #[cfg(not(feature = "param-services"))]
2323 executor
2324 .register_parameter_store()
2325 .map_err(decl_err_from_node)?;
2326 }
2327 let name = metadata.source_name.as_str();
2328 // phase-446 W6 -- the code must declare what the node's
2329 // contract declares: the store was sized from it (W4). A
2330 // node whose contract has no `params:` is not checked.
2331 if let Err(m) = executor.declared_params().check(
2332 node_ns.as_str(),
2333 node_name.as_str(),
2334 name,
2335 value.param_type(),
2336 ) {
2337 let passed = nros_params::declared::type_name(value.param_type());
2338 match m.declared {
2339 // phase-446 W6
2340 None => nros_log::log_error!(
2341 nros_log::get_logger("nros"),
2342 "node '{}': parameter '{}' is not declared in its contract \
2343 ({}, `params:`). The parameter store is sized from that \
2344 declaration; declare it there with its type, or stop \
2345 declaring it in the code.",
2346 m.node,
2347 name,
2348 m.contract
2349 ),
2350 // phase-446 W6
2351 Some(declared) => nros_log::log_error!(
2352 nros_log::get_logger("nros"),
2353 "node '{}': parameter '{}' is declared `{}` in its contract \
2354 ({}) but the code declares it as `{}`. Fix the contract or \
2355 the code so they state one type.",
2356 m.node,
2357 name,
2358 nros_params::declared::type_name(declared),
2359 m.contract,
2360 passed
2361 ),
2362 }
2363 return Err(NodeDeclError::Runtime);
2364 }
2365 // Same rule as `seed_launch_params`: already-declared is
2366 // not a refusal (the launch seed may have declared it
2367 // first); refused-and-absent is — and it gets its own
2368 // variant, not the opaque `Runtime` (issue 1260). On THIS
2369 // entity's node, not the executor's primary (issue 1272):
2370 // a second node declaring a name the first also declares
2371 // is its own parameter, not a duplicate.
2372 // Issue 2969 -- a launch seed for this name is adopted by
2373 // the one store rule every language shares: kept if it has
2374 // the declared type, refused naming the cause if not.
2375 match executor.adopt_launch_seed_on(node, name, value.param_type(), None) {
2376 Some(Ok(())) => return Ok(()),
2377 Some(Err(e)) => {
2378 nros_log::log_error!(
2379 nros_log::get_logger("nros"),
2380 "parameter '{name}': {e}"
2381 );
2382 return Err(NodeDeclError::ParameterRejected);
2383 }
2384 None => {}
2385 }
2386 if !executor.declare_parameter_on_ref(node, name, &value)
2387 && executor.get_parameter_on(node, name).is_none()
2388 {
2389 // GitHub #4018 -- capacity and knob, not only "refused".
2390 executor.report_parameter_refused(node, name);
2391 return Err(NodeDeclError::ParameterRejected);
2392 }
2393 }
2394 Ok(())
2395 }),
2396 }
2397 }
2398
2399 fn record_callback_effect(
2400 &mut self,
2401 _executor: &mut Executor<'static>,
2402 _callback_id: CallbackId<'_>,
2403 _kind: CallbackEffectKind,
2404 _entity_id: EntityId<'_>,
2405 ) -> NodeResult<()> {
2406 // Planner concern only — the live runtime doesn't need the
2407 // effect graph at spin time.
2408 Ok(())
2409 }
2410}
2411
2412/// Lower a source-recorded [`ParameterDefault`] into the executor-facing
2413/// [`nros_params::ParameterValue`] used to seed a declared parameter. Scalar
2414/// defaults carry their value directly; the array variants record only the
2415/// declared type (no element data at the source layer) so they seed as
2416/// `NotSet` — the parameter is still declared, just without a concrete array
2417/// default. A `Double` default is stored as a string at the metadata layer and
2418/// parsed here (unparseable → `0.0`).
2419/// Write a declared parameter's source default into `out`, in place.
2420///
2421/// Issue 2360. This used to return the value, and a `ParameterValue` is as
2422/// large as its largest variant (~8 KiB at the default capacities), so each
2423/// match arm and the string arm's `unwrap_or` fallback built a full-size copy
2424/// in the caller's frame. Writing through `out` keeps exactly one: the
2425/// caller's. A string longer than the store's string capacity is `NotSet`, as
2426/// before.
2427#[inline(never)]
2428fn param_default_into(
2429 default: Option<&crate::node_metadata::ParameterDefault>,
2430 out: &mut nros_params::ParameterValue,
2431) {
2432 use crate::node_metadata::ParameterDefault;
2433 use nros_params::ParameterValue;
2434 match default {
2435 None => *out = ParameterValue::NotSet,
2436 Some(ParameterDefault::Bool(b)) => *out = ParameterValue::Bool(*b),
2437 Some(ParameterDefault::Integer(i)) => *out = ParameterValue::Integer(*i),
2438 Some(ParameterDefault::Double(s)) => {
2439 *out = ParameterValue::Double(s.as_str().parse::<f64>().unwrap_or(0.0))
2440 }
2441 Some(ParameterDefault::String(s)) => {
2442 *out = ParameterValue::String(Default::default());
2443 let fits = match out {
2444 ParameterValue::String(dst) => dst.push_str(s.as_str()).is_ok(),
2445 _ => false,
2446 };
2447 if !fits {
2448 *out = ParameterValue::NotSet;
2449 }
2450 }
2451 Some(
2452 ParameterDefault::BoolArray
2453 | ParameterDefault::IntegerArray
2454 | ParameterDefault::DoubleArray
2455 | ParameterDefault::StringArray,
2456 ) => *out = ParameterValue::NotSet,
2457 }
2458}
2459
2460fn dispatch_into_cell(cell: &dyn CellView, cb_id: &str, payload: &[u8]) {
2461 cell.note_dispatch(!payload.is_empty());
2462 let resolver = CellResolver { cell };
2463 let mut ctx = CallbackCtx::new(payload, &resolver);
2464 // W4c — let the callback read `ctx.parameter::<T>(name)` from the executor's store
2465 // (threaded onto the cell by `apply_param_services`; `None` until then).
2466 #[cfg(feature = "param-store")]
2467 ctx.set_param_server(cell.view_param_server(), cell.view_param_node());
2468 // If the slot is already borrowed (a re-entrant publish from a
2469 // tick hook on the same cell, etc.) the view drops this dispatch. In
2470 // practice the borrow succeeds because subscription / timer
2471 // callbacks run sequentially under the single-threaded executor.
2472 cell.try_with_slot_mut(&mut |slot| slot.dispatch(cb_id, &mut ctx));
2473}
2474
2475// Issue 2349.
2476/// Dispatch a subscription message into the component's `on_callback` with
2477/// the message's metadata attached, read as `CallbackCtx::message_info()`.
2478/// The metadata twin of [`dispatch_into_cell`].
2479fn dispatch_into_cell_with_info(
2480 cell: &dyn CellView,
2481 cb_id: &str,
2482 payload: &[u8],
2483 info: Option<&nros_core::MessageInfo>,
2484) {
2485 cell.note_dispatch(!payload.is_empty());
2486 let resolver = CellResolver { cell };
2487 let mut ctx = CallbackCtx::new(payload, &resolver);
2488 // `None` from a backend that reports no metadata: the callback then reads
2489 // `message_info()` as `None`, which is what that backend can say.
2490 if let Some(info) = info {
2491 ctx.set_message_info(info);
2492 }
2493 #[cfg(feature = "param-store")]
2494 ctx.set_param_server(cell.view_param_server(), cell.view_param_node());
2495 cell.try_with_slot_mut(&mut |slot| slot.dispatch(cb_id, &mut ctx));
2496}
2497
2498/// Issue 2038 — dispatch a declared timer's activation into the component's
2499/// `on_callback`, with its call info readable as `CallbackCtx::timer_info`.
2500/// The timer twin of [`dispatch_into_cell`] (a timer has no payload).
2501fn dispatch_timer_into_cell(cell: &dyn CellView, cb_id: &str, info: &nros_node::TimerCallInfo) {
2502 cell.note_dispatch(false);
2503 let resolver = CellResolver { cell };
2504 let mut ctx = CallbackCtx::new(&[], &resolver);
2505 ctx.set_timer_info(*info);
2506 #[cfg(feature = "param-store")]
2507 ctx.set_param_server(cell.view_param_server(), cell.view_param_node());
2508 cell.try_with_slot_mut(&mut |slot| slot.dispatch(cb_id, &mut ctx));
2509}
2510
2511/// Phase 250 (Wave 2b) — dispatch a `.safety()` subscription message into the
2512/// component's `on_callback` with its E2E [`IntegrityStatus`] attached, read via
2513/// `CallbackCtx::integrity()`. The integrity-aware twin of [`dispatch_into_cell`].
2514#[cfg(feature = "safety-e2e")]
2515fn dispatch_into_cell_with_integrity(
2516 cell: &dyn CellView,
2517 cb_id: &str,
2518 payload: &[u8],
2519 status: &nros_node::IntegrityStatus,
2520) {
2521 cell.note_dispatch(!payload.is_empty());
2522 let resolver = CellResolver { cell };
2523 let mut ctx = CallbackCtx::new_with_integrity(payload, &resolver, status);
2524 // W4c — param store for a `.safety()` subscription callback too.
2525 #[cfg(feature = "param-store")]
2526 ctx.set_param_server(cell.view_param_server(), cell.view_param_node());
2527 cell.try_with_slot_mut(&mut |slot| slot.dispatch(cb_id, &mut ctx));
2528}
2529
2530// =============================================================================
2531// Phase 212.M-F.23 — service / action SERVER trampolines + tick-side client /
2532// action dispatch.
2533//
2534// The executor's raw service/action-server registration takes C-ABI fn
2535// pointers, so the runtime leaks a `*Ctx` (lives for the runtime's lifetime,
2536// like the executor) holding the owning `ComponentCell` + the declared
2537// callback ids. Each trampoline rebuilds a `CallbackCtx` and routes into the
2538// component's `on_callback`, exactly as the orchestration codegen's
2539// svc_tramp_* / goal_tramp_* do for the Entry path.
2540// =============================================================================
2541
2542/// Leaked context for a service-server arena callback.
2543struct ServiceServerCtx {
2544 cell: CellHandle,
2545 callback_id: IdStr,
2546}
2547
2548/// Leaked context for an action-server arena callback (goal + cancel + the
2549/// optional accepted hook all share one).
2550struct ActionServerCtx {
2551 cell: CellHandle,
2552 goal_callback_id: IdStr,
2553 cancel_callback_id: IdStr,
2554 accepted_callback_id: Option<IdStr>,
2555}
2556
2557/// Leaked context for an action-CLIENT result + feedback callbacks.
2558struct ActionClientCtx {
2559 cell: CellHandle,
2560 result_callback_id: IdStr,
2561 feedback_callback_id: Option<IdStr>,
2562}
2563
2564/// Action-client result callback: the executor's spin auto-drives the goal to
2565/// completion and hands the terminal result CDR here; route it into the
2566/// component's `on_callback` (read with `CallbackCtx::message`).
2567unsafe extern "C" fn action_result_trampoline(
2568 _goal_id: *const GoalUuid,
2569 _status: GoalStatusCode,
2570 result_data: *const u8,
2571 result_len: usize,
2572 ctx: *mut core::ffi::c_void,
2573) {
2574 let actx = unsafe { &*(ctx as *const ActionClientCtx) };
2575 let result_slice = unsafe { core::slice::from_raw_parts(result_data, result_len) };
2576 dispatch_into_cell(actx.cell.view(), &actx.result_callback_id, result_slice);
2577}
2578
2579/// Action-client feedback callback: route each feedback CDR into the
2580/// component's `on_callback` under the bound feedback callback id.
2581unsafe extern "C" fn action_feedback_trampoline(
2582 _goal_id: *const GoalUuid,
2583 feedback_data: *const u8,
2584 feedback_len: usize,
2585 ctx: *mut core::ffi::c_void,
2586) {
2587 let actx = unsafe { &*(ctx as *const ActionClientCtx) };
2588 let Some(cb_id) = actx.feedback_callback_id.as_ref() else {
2589 return;
2590 };
2591 let feedback_slice = unsafe { core::slice::from_raw_parts(feedback_data, feedback_len) };
2592 dispatch_into_cell(actx.cell.view(), cb_id, feedback_slice);
2593}
2594
2595/// Service-server request callback: deserialize-side runs in the component's
2596/// `on_callback` via `CallbackCtx::with_reply`; the executor sends the reply
2597/// from the bytes written into `resp`.
2598unsafe extern "C" fn service_server_trampoline(
2599 req: *const u8,
2600 req_len: usize,
2601 resp: *mut u8,
2602 resp_cap: usize,
2603 resp_len: *mut usize,
2604 ctx: *mut core::ffi::c_void,
2605) -> bool {
2606 let sctx = unsafe { &*(ctx as *const ServiceServerCtx) };
2607 let req_slice = unsafe { core::slice::from_raw_parts(req, req_len) };
2608 let resp_slice = unsafe { core::slice::from_raw_parts_mut(resp, resp_cap) };
2609 let mut written = 0usize;
2610 let view = sctx.cell.view();
2611 let resolver = CellResolver { cell: view };
2612 let mut cb = CallbackCtx::with_reply(req_slice, &resolver, resp_slice, &mut written);
2613 // W4c — service-server callback can read `ctx.parameter::<T>(name)` too.
2614 #[cfg(feature = "param-store")]
2615 cb.set_param_server(view.view_param_server(), view.view_param_node());
2616 view.try_with_slot_mut(&mut |slot| slot.dispatch(&sctx.callback_id, &mut cb));
2617 unsafe { *resp_len = written };
2618 true
2619}
2620
2621/// Action-server goal callback → component `on_callback` with a goal decision.
2622unsafe extern "C" fn action_goal_trampoline(
2623 _goal_id: *const GoalUuid,
2624 goal_data: *const u8,
2625 goal_len: usize,
2626 ctx: *mut core::ffi::c_void,
2627) -> crate::GoalResponse {
2628 let actx = unsafe { &*(ctx as *const ActionServerCtx) };
2629 let goal_slice = unsafe { core::slice::from_raw_parts(goal_data, goal_len) };
2630 let mut resp = crate::GoalResponse::Reject;
2631 let view = actx.cell.view();
2632 let resolver = CellResolver { cell: view };
2633 let mut cb = CallbackCtx::with_goal_decision(goal_slice, &resolver, &mut resp);
2634 // W4c — action goal callback can read `ctx.parameter::<T>(name)` too.
2635 #[cfg(feature = "param-store")]
2636 cb.set_param_server(view.view_param_server(), view.view_param_node());
2637 view.try_with_slot_mut(&mut |slot| slot.dispatch(&actx.goal_callback_id, &mut cb));
2638 resp
2639}
2640
2641/// Action-server cancel callback → component `on_callback` with a cancel
2642/// decision. The cancel callback has no goal payload.
2643unsafe extern "C" fn action_cancel_trampoline(
2644 _goal_id: *const GoalUuid,
2645 _status: GoalStatusCode,
2646 ctx: *mut core::ffi::c_void,
2647) -> crate::CancelResponse {
2648 let actx = unsafe { &*(ctx as *const ActionServerCtx) };
2649 let mut resp = crate::CancelResponse::Reject;
2650 let view = actx.cell.view();
2651 let resolver = CellResolver { cell: view };
2652 let mut cb = CallbackCtx::with_cancel_decision(&[], &resolver, &mut resp);
2653 // W4c — action cancel callback can read `ctx.parameter::<T>(name)` too.
2654 #[cfg(feature = "param-store")]
2655 cb.set_param_server(view.view_param_server(), view.view_param_node());
2656 view.try_with_slot_mut(&mut |slot| slot.dispatch(&actx.cancel_callback_id, &mut cb));
2657 resp
2658}
2659
2660/// Action-server accepted hook → component `on_callback` (no decision, no
2661/// payload). No-op when the component didn't declare an accepted callback.
2662unsafe extern "C" fn action_accepted_trampoline(
2663 _goal_id: *const GoalUuid,
2664 ctx: *mut core::ffi::c_void,
2665) {
2666 let actx = unsafe { &*(ctx as *const ActionServerCtx) };
2667 let Some(cb_id) = actx.accepted_callback_id.as_ref() else {
2668 return;
2669 };
2670 dispatch_into_cell(actx.cell.view(), cb_id, &[]);
2671}
2672
2673/// phase-572 W2 -- the tick's graph queries. Holds the executor's raw
2674/// pointer and nothing else: each query reborrows `&mut Executor` for that one
2675/// call and runs the executor's own graph method inside it, the way
2676/// `RuntimeActions` and `RuntimeClientDispatch` do. No session pointer is
2677/// taken or kept, so nothing outlives the call (phase-573's ruling on this
2678/// path: the tick runs between callback dispatch, where the executor is free).
2679struct RuntimeGraph {
2680 executor: *mut Executor<'static>,
2681}
2682
2683impl RuntimeGraph {
2684 /// The executor, for the length of the caller's one query.
2685 fn executor(&mut self) -> &mut Executor<'static> {
2686 // SAFETY: see the type's doc -- the tick driver hands a live executor
2687 // that nothing else references during the tick, and the borrow ends
2688 // with the query that asked for it.
2689 unsafe { &mut *self.executor }
2690 }
2691}
2692
2693impl crate::node::GraphQuery for RuntimeGraph {
2694 fn get_node_names(
2695 &mut self,
2696 visit: &mut dyn FnMut(&str, &str) -> bool,
2697 ) -> Result<(), crate::NodeError> {
2698 let executor = self.executor();
2699 crate::node::GraphQuery::get_node_names(executor, visit)
2700 }
2701 fn get_node_names_with_enclaves(
2702 &mut self,
2703 visit: &mut dyn FnMut(&str, &str, Option<&str>) -> bool,
2704 ) -> Result<(), crate::NodeError> {
2705 let executor = self.executor();
2706 crate::node::GraphQuery::get_node_names_with_enclaves(executor, visit)
2707 }
2708 fn get_topic_names_and_types(
2709 &mut self,
2710 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2711 ) -> Result<(), crate::NodeError> {
2712 let executor = self.executor();
2713 crate::node::GraphQuery::get_topic_names_and_types(executor, visit)
2714 }
2715 fn get_service_names_and_types(
2716 &mut self,
2717 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2718 ) -> Result<(), crate::NodeError> {
2719 let executor = self.executor();
2720 crate::node::GraphQuery::get_service_names_and_types(executor, visit)
2721 }
2722 fn count_publishers(&mut self, topic_name: &str) -> Result<usize, crate::NodeError> {
2723 let executor = self.executor();
2724 crate::node::GraphQuery::count_publishers(executor, topic_name)
2725 }
2726 fn count_subscriptions(&mut self, topic_name: &str) -> Result<usize, crate::NodeError> {
2727 let executor = self.executor();
2728 crate::node::GraphQuery::count_subscriptions(executor, topic_name)
2729 }
2730 fn count_clients(&mut self, service_name: &str) -> Result<usize, crate::NodeError> {
2731 let executor = self.executor();
2732 crate::node::GraphQuery::count_clients(executor, service_name)
2733 }
2734 fn count_services(&mut self, service_name: &str) -> Result<usize, crate::NodeError> {
2735 let executor = self.executor();
2736 crate::node::GraphQuery::count_services(executor, service_name)
2737 }
2738 fn get_publisher_names_and_types_by_node(
2739 &mut self,
2740 node_name: &str,
2741 node_namespace: &str,
2742 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2743 ) -> Result<(), crate::NodeError> {
2744 let executor = self.executor();
2745 crate::node::GraphQuery::get_publisher_names_and_types_by_node(
2746 executor,
2747 node_name,
2748 node_namespace,
2749 visit,
2750 )
2751 }
2752 fn get_subscription_names_and_types_by_node(
2753 &mut self,
2754 node_name: &str,
2755 node_namespace: &str,
2756 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2757 ) -> Result<(), crate::NodeError> {
2758 let executor = self.executor();
2759 crate::node::GraphQuery::get_subscription_names_and_types_by_node(
2760 executor,
2761 node_name,
2762 node_namespace,
2763 visit,
2764 )
2765 }
2766 fn get_service_names_and_types_by_node(
2767 &mut self,
2768 node_name: &str,
2769 node_namespace: &str,
2770 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2771 ) -> Result<(), crate::NodeError> {
2772 let executor = self.executor();
2773 crate::node::GraphQuery::get_service_names_and_types_by_node(
2774 executor,
2775 node_name,
2776 node_namespace,
2777 visit,
2778 )
2779 }
2780 fn get_client_names_and_types_by_node(
2781 &mut self,
2782 node_name: &str,
2783 node_namespace: &str,
2784 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2785 ) -> Result<(), crate::NodeError> {
2786 let executor = self.executor();
2787 crate::node::GraphQuery::get_client_names_and_types_by_node(
2788 executor,
2789 node_name,
2790 node_namespace,
2791 visit,
2792 )
2793 }
2794 fn get_publishers_info_by_topic(
2795 &mut self,
2796 topic_name: &str,
2797 visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
2798 ) -> Result<(), crate::NodeError> {
2799 let executor = self.executor();
2800 crate::node::GraphQuery::get_publishers_info_by_topic(executor, topic_name, visit)
2801 }
2802 fn get_subscriptions_info_by_topic(
2803 &mut self,
2804 topic_name: &str,
2805 visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
2806 ) -> Result<(), crate::NodeError> {
2807 let executor = self.executor();
2808 crate::node::GraphQuery::get_subscriptions_info_by_topic(executor, topic_name, visit)
2809 }
2810}
2811
2812/// Tick-side service/action CLIENT dispatch — the single-node runtime's own
2813/// (it mirrored the orchestration's ~~`GenClientDispatch`~~, since retired). Resolves the per-component client
2814/// handle arrays + a `*mut Executor<'static>` (the tick borrows `&components` while
2815/// needing `&mut executor`, so the executor is reached through a raw pointer,
2816/// reborrowed `&mut` per call; no aliasing — `executor` and `components` are
2817/// disjoint fields).
2818struct RuntimeClientDispatch<'a> {
2819 executor: *mut Executor<'static>,
2820 services: &'a [(IdStr, crate::HandleId)],
2821 actions: &'a [(IdStr, usize)],
2822}
2823
2824impl RuntimeClientDispatch<'_> {
2825 fn service(&self, entity: &str) -> NodeResult<crate::HandleId> {
2826 self.services
2827 .iter()
2828 .find(|(e, _)| e == entity)
2829 .map(|(_, h)| *h)
2830 .ok_or(NodeDeclError::Runtime)
2831 }
2832
2833 fn action_entry(&self, entity: &str) -> NodeResult<usize> {
2834 self.actions
2835 .iter()
2836 .find(|(e, _)| e == entity)
2837 .map(|(_, i)| *i)
2838 .ok_or(NodeDeclError::Runtime)
2839 }
2840}
2841
2842impl ClientDispatch for RuntimeClientDispatch<'_> {
2843 fn call_raw(
2844 &mut self,
2845 service_entity: &str,
2846 request_cdr: &[u8],
2847 response_buf: &mut [u8],
2848 ) -> NodeResult<usize> {
2849 use nros_rmw::ClientTrait;
2850 let hid = self.service(service_entity)?;
2851 {
2852 let executor = unsafe { &mut *self.executor };
2853 let slot = executor.resolve_handle(hid).ok_or(NodeDeclError::Runtime)?;
2854 let entry =
2855 unsafe { executor.service_client_entry_mut(slot) }.ok_or(NodeDeclError::Runtime)?;
2856 let seq = entry
2857 .handle
2858 .send_request_raw(request_cdr)
2859 .map_err(|_| NodeDeclError::Runtime)?;
2860 // Issue 2009 — only the reply naming this request completes the
2861 // call; an earlier call's late reply is dropped.
2862 entry.record_send(seq, false);
2863 }
2864 // Bounded wait — caps total time so the tick loop stays responsive.
2865 for _ in 0..200 {
2866 let executor = unsafe { &mut *self.executor };
2867 executor.spin_once(core::time::Duration::from_millis(10));
2868 let slot = executor.resolve_handle(hid).ok_or(NodeDeclError::Runtime)?;
2869 let entry =
2870 unsafe { executor.service_client_entry_mut(slot) }.ok_or(NodeDeclError::Runtime)?;
2871 match entry.take_reply(response_buf) {
2872 Ok(Some(len)) => return Ok(len),
2873 Ok(None) => continue,
2874 Err(_) => return Err(NodeDeclError::Runtime),
2875 }
2876 }
2877 // Timed out: forget the call, so its reply — if it still comes — is
2878 // dropped rather than returned by the next `call_raw` (issue 2009).
2879 let executor = unsafe { &mut *self.executor };
2880 if let Some(slot) = executor.resolve_handle(hid)
2881 && let Some(entry) = unsafe { executor.service_client_entry_mut(slot) }
2882 {
2883 entry.sequences.clear();
2884 }
2885 Err(NodeDeclError::Runtime)
2886 }
2887
2888 fn service_is_ready(&self, service_entity: &str) -> NodeResult<bool> {
2889 use nros_rmw::ClientTrait;
2890 let hid = self.service(service_entity)?;
2891 let executor = unsafe { &mut *self.executor };
2892 let slot = executor.resolve_handle(hid).ok_or(NodeDeclError::Runtime)?;
2893 let entry =
2894 unsafe { executor.service_client_entry_mut(slot) }.ok_or(NodeDeclError::Runtime)?;
2895 // `Err` here is the backend's "cannot say" (XRCE has no discovery
2896 // channel); it is folded into the same `Runtime` the trait default
2897 // returns, so a caller has ONE branch for "did not get an answer".
2898 entry
2899 .handle
2900 .service_is_ready()
2901 .map_err(|_| NodeDeclError::Runtime)
2902 }
2903
2904 fn action_server_is_ready(&self, action_entity: &str) -> NodeResult<bool> {
2905 let entry_index = self.action_entry(action_entity)?;
2906 let executor = unsafe { &mut *self.executor };
2907 let core = unsafe { executor.action_client_core_mut(entry_index) }
2908 .ok_or(NodeDeclError::Runtime)?;
2909 // As for `service_is_ready`: the backend's "cannot say" folds into the
2910 // trait default's `Runtime`, one branch for "no answer".
2911 core.server_readiness().map_err(|_| NodeDeclError::Runtime)
2912 }
2913
2914 fn send_goal_raw(&mut self, action_entity: &str, goal_cdr: &[u8]) -> NodeResult<GoalUuid> {
2915 let entry_index = self.action_entry(action_entity)?;
2916 let executor = unsafe { &mut *self.executor };
2917 let core = unsafe { executor.action_client_core_mut(entry_index) }
2918 .ok_or(NodeDeclError::Runtime)?;
2919 let goal_id = core.send_goal_raw(goal_cdr).map_err(decl_err_from_node)?;
2920 // rclcpp-style: request the result immediately. The server queues the
2921 // get_result request until the goal terminates, then replies — the
2922 // executor's spin auto-delivers it to the bound result callback (the
2923 // executor never auto-sends this request, so the declarative client
2924 // must). Best-effort: a transport hiccup just means no result callback.
2925 let _ = core.send_get_result_request(&goal_id);
2926 Ok(goal_id)
2927 }
2928}
2929
2930/// Tick-side action-SERVER execution (it mirrored the retired
2931/// ~~`GenActionExec`~~). Lets a
2932/// component complete goals / publish feedback / enumerate active goals from
2933/// its `tick` via `TickCtx`.
2934struct RuntimeActions<'a> {
2935 executor: *mut Executor<'static>,
2936 handles: &'a [(IdStr, crate::internals::ActionServerRawHandle)],
2937}
2938
2939impl RuntimeActions<'_> {
2940 fn handle(&self, entity: &str) -> NodeResult<crate::internals::ActionServerRawHandle> {
2941 self.handles
2942 .iter()
2943 .find(|(e, _)| e == entity)
2944 .map(|(_, h)| *h)
2945 .ok_or(NodeDeclError::Runtime)
2946 }
2947}
2948
2949impl ActionExecutor for RuntimeActions<'_> {
2950 fn complete_goal_raw(
2951 &mut self,
2952 action_entity: &str,
2953 goal_id: &GoalUuid,
2954 status: GoalStatusCode,
2955 result: &[u8],
2956 ) -> NodeResult<()> {
2957 let handle = self.handle(action_entity)?;
2958 let executor = unsafe { &mut *self.executor };
2959 // issue 0796 — a result too large for the server's RESULT_BUF is
2960 // reported rather than silently dropped.
2961 handle
2962 .complete_goal_raw(executor, goal_id, status, result)
2963 .map_err(|_| NodeDeclError::Runtime)
2964 }
2965
2966 fn publish_feedback_raw(
2967 &mut self,
2968 action_entity: &str,
2969 goal_id: &GoalUuid,
2970 feedback: &[u8],
2971 ) -> NodeResult<()> {
2972 let handle = self.handle(action_entity)?;
2973 let executor = unsafe { &mut *self.executor };
2974 handle
2975 .publish_feedback_raw(executor, goal_id, feedback)
2976 .map_err(|_| NodeDeclError::Runtime)
2977 }
2978
2979 fn for_each_active_goal(
2980 &self,
2981 action_entity: &str,
2982 visit: &mut dyn FnMut(&GoalUuid, GoalStatusCode),
2983 ) {
2984 if let Ok(handle) = self.handle(action_entity) {
2985 let executor = unsafe { &*self.executor };
2986 handle.for_each_active_goal(executor, |g| visit(&g.goal_id, g.status));
2987 }
2988 }
2989}
2990
2991// Phase 258 (Track 2, w5) — the typed BSP fn-ptr aliases (~~`NodeRegisterFn`~~ /
2992// ~~`NodeInitFn`~~ / ~~`NodeDispatchFn`~~ / ~~`NodeTickFn`~~) are gone with the retired
2993// ~~`register_dispatch_slot`~~ / ~~`nros_run_components`~~ BSP-baker path. The
2994// macro-emitted `register(runtime)` wrapper now installs via the
2995// `install_node_typed` seam (Track 2 w4).
2996
2997/// Phase 257 (W0-B) — register an [`ExecutableNode`] `C` against a **borrowed**
2998/// executor (the shared cffi `Executor` a foreign-language typed entry hands in via
2999/// its `nros::global_handle()` / `Node::executor_handle()`), returning the live
3000/// [`ComponentCell`].
3001///
3002/// Unlike [`ExecutorNodeRuntime::register_node`] this owns neither the executor nor a
3003/// components list: the executor's per-entity callbacks hold `CellHandle`s
3004/// clones (see [`ExecutorSink`]), so the cell stays alive for the executor's lifetime
3005/// via dispatch alone — the caller may drop the returned cell (pub/sub/timer nodes, the
3006/// W0-B target) or stash it to drive `tick` (service-client/action nodes; phase-257 D2).
3007/// The node self-creates its node (its `Node::NAME`) on the shared executor (phase-257
3008/// D7 Option C — Rust nodes in a foreign entry self-name, no entry-side qos-override).
3009/// Issue 0095 — preserve executor callback-table exhaustion through the
3010/// `NodeError → NodeDeclError` collapse so the register seam (and ultimately
3011/// the `nros::main!` entry) can name `NROS_EXECUTOR_MAX_CBS` instead of an
3012/// opaque `NodeRegister`. Every other `NodeError` stays `Runtime`.
3013fn decl_err_from_node(e: nros_node::NodeError) -> NodeDeclError {
3014 // Issue 0428 — `NodeDeclError::Runtime` collapses every non-`ExecutorFull`
3015 // cause into one opaque `NodeRegister("<pkg>")`, "four collapses away from the
3016 // cause" (node.rs). That is how a Cyclone descriptor/transport failure was
3017 // mis-diagnosed twice. Surface the real variant on the error path (rare — this
3018 // only runs when a declaration is already failing), so the register seam names
3019 // WHAT failed, not just WHERE.
3020 // issue 0589 — `nros_log`, not `std::eprintln!`: std stdio is fatal on Zephyr
3021 // native_sim, and this crate cannot gate on the platform. Routing it here
3022 // also means a `no_std` image gets the diagnostic, which the old
3023 // `cfg(feature = "std")` arm never delivered.
3024 if !matches!(e, nros_node::NodeError::ExecutorFull) {
3025 nros_log::log_error!(
3026 nros_log::get_logger("nros"),
3027 "node declaration failed — NodeError::{e:?}"
3028 );
3029 }
3030 // The same diagnostic through the `log` facade (every RTOS board bridges
3031 // it); without this the collapse left only an opaque `NodeRegister("<pkg>")`
3032 // on embedded — e.g. a static subscriber-pool exhaustion
3033 // (NROS_RMW_SUBSCRIBER_SLOTS) surfaced with no cause at all. phase-359 W10
3034 // stage B: this was `not(std)`, and `nros` has no `std` any more; on a host
3035 // with a `log` logger installed the line appears twice, on an error path
3036 // that only runs when a declaration is already failing.
3037 if !matches!(e, nros_node::NodeError::ExecutorFull) {
3038 log::error!("nros: node declaration failed — NodeError::{e:?}");
3039 }
3040 match e {
3041 nros_node::NodeError::ExecutorFull => NodeDeclError::ExecutorFull,
3042 _ => NodeDeclError::Runtime,
3043 }
3044}
3045
3046fn register_node_borrowed<
3047 'p,
3048 C: ExecutableNode + 'static,
3049 const PUBS: usize,
3050 const SVCS: usize,
3051 const ACTC: usize,
3052 const ACTS: usize,
3053 const SSRV: usize,
3054 const TIMS: usize,
3055>(
3056 executor: &mut Executor<'static>,
3057 params: crate::node::LaunchParams<'p>,
3058 node_identity: LaunchIdentity,
3059 remaps: crate::node::LaunchParams<'p>,
3060 qos_overrides: &'static [nros_node::executor::node_record::QoSOverrideCode],
3061 slot_mu: &'static mut MaybeUninit<TypedSlot<C>>,
3062 cell_mu: &'static mut MaybeUninit<ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>>,
3063) -> NodeResult<&'static ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>>
3064where
3065 C::State: 'static,
3066{
3067 // W5-endgame step 2b (issue 0857) — the cell is PLACED into caller
3068 // storage (the per-class static's paired region, or the alloc
3069 // convenience's leaked box), never `Arc`'d: 0857 measured the Arc'd cell
3070 // at ~17.5 KiB of heap per component. Closures and leaked ctxs hold a
3071 // `CellHandle::Static` copy; the executor's drop trampoline runs the
3072 // cell's destructor in place.
3073 let cell: &'static ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS> =
3074 cell_mu.write(ComponentCell {
3075 slot: RefCell::new(place_slot::<C>(slot_mu)),
3076 publishers: RefCell::new(heapless::Vec::new()),
3077 service_clients: RefCell::new(heapless::Vec::new()),
3078 action_clients: RefCell::new(heapless::Vec::new()),
3079 action_servers: RefCell::new(heapless::Vec::new()),
3080 timers: RefCell::new(heapless::Vec::new()),
3081 svc_ctxs: [const { UnsafeCell::new(MaybeUninit::uninit()) }; _],
3082 svc_ctxs_used: core::cell::Cell::new(0),
3083 act_srv_ctxs: [const { UnsafeCell::new(MaybeUninit::uninit()) }; _],
3084 act_srv_ctxs_used: core::cell::Cell::new(0),
3085 act_cli_ctxs: [const { UnsafeCell::new(MaybeUninit::uninit()) }; _],
3086 act_cli_ctxs_used: core::cell::Cell::new(0),
3087 header: CellHeader {
3088 callback_dispatches: AtomicUsize::new(0),
3089 message_dispatches: AtomicUsize::new(0),
3090 },
3091 // W4c — set by `apply_param_services` once the store exists (it runs after this).
3092 #[cfg(feature = "param-store")]
3093 param_server: core::cell::Cell::new(core::ptr::null()),
3094 // phase-426 W3 — overwritten below with the node `register()` created.
3095 #[cfg(feature = "param-store")]
3096 param_node: core::cell::Cell::new(0),
3097 });
3098 let mut sink = ExecutorSink {
3099 cell: CellHandle::Static(cell),
3100 nodes: heapless::Vec::new(),
3101 // Phase 268 W1 — thread the per-component identity bake (RFC-0046).
3102 node_identity,
3103 // Phase 305 W3 (issue 0255) — thread the per-component remap bake.
3104 remaps,
3105 // Issue #52 — thread the per-component QoS-override bake.
3106 qos_overrides,
3107 // issue 1272 -- the launch `<param>` initials, seeded on the node
3108 // `create_node` builds rather than on the executor's primary node.
3109 launch_params: params,
3110 };
3111 {
3112 let mut frame = crate::node::ComponentFrame::new(&mut sink);
3113 let mut context = NodeContext::new(C::NAME, &mut *executor, &mut frame);
3114 // Phase 264 W4a — seed the baked launch-param initials so `register()` can read
3115 // them via `NodeContext::param`.
3116 context.set_launch_params(params);
3117 C::register(&mut context)?;
3118 }
3119 // phase-426 W3 — see the sibling in `register_node`: the cell records the
3120 // node it created, so `ctx.parameter::<T>(name)` reads that node's slot.
3121 #[cfg(feature = "param-store")]
3122 if let Some(node) = sink.nodes.first() {
3123 cell.param_node.set(node.node_id.raw());
3124 }
3125
3126 // Phase 258 (Track 2, 2a) — enroll the cell in the executor's component
3127 // tick registry so `install`'d nodes tick (closes phase-257 D2: poll-only
3128 // service-client/action nodes have no callbacks keeping the cell alive AND
3129 // never ran `tick`). The executor runs `tick` each `spin_once` and runs
3130 // the cell's destructor in place on `Executor::drop`. Harmless for
3131 // pub/sub/timer-only nodes — their tick body is a no-op. Registry-full
3132 // (`MAX_NODES`) proceeds without a tick slot; the placed cell then simply
3133 // lives (and leaks its component state's destructor) with its storage,
3134 // which a monotonic `take` never re-hands out.
3135 let raw =
3136 cell as *const ComponentCell<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS> as *mut core::ffi::c_void;
3137 // SAFETY: `raw` is the freshly placed cell; the enrolled trampoline
3138 // monomorphizations match its exact type (borrow on tick, drop_in_place
3139 // on executor drop).
3140 let _ = unsafe {
3141 executor.enroll_component_ticking(
3142 raw,
3143 component_tick_trampoline::<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>,
3144 component_drop_trampoline::<PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>,
3145 C::HAS_TICK,
3146 )
3147 };
3148
3149 // W4c — capture the executor's volatile param store on the cell so this node's
3150 // callbacks can read `ctx.parameter::<T>(name)`. Non-null only when `nros::main!`
3151 // emitted `apply_param_services` BEFORE this register call (`[param_services]`
3152 // declared); otherwise the store is absent and the field stays null.
3153 #[cfg(feature = "param-store")]
3154 if let Some(server) = executor.params() {
3155 cell.param_server.set(server as *const _);
3156 }
3157
3158 Ok(cell)
3159}
3160
3161/// Issue 1535 — the install seam's return code for a refused executor handle:
3162/// `-1` for null (unchanged), `-4` for an nros-cpp context that was not
3163/// unwrapped with `nros_cpp_executor_inner`.
3164fn install_handle_refusal_code(refusal: crate::executor_handle::HandleRefusal) -> i32 {
3165 match refusal {
3166 crate::executor_handle::HandleRefusal::Null => -1,
3167 crate::executor_handle::HandleRefusal::CppContext => -4,
3168 }
3169}
3170
3171/// C-ABI typed component install. Recovers the shared `Executor`
3172/// from the handle a typed entry passes — a bare `*mut Executor<'static>`. A C/C++
3173/// entry's `rclcpp::global_handle()` is NOT one: it is an nros-cpp context, and
3174/// the entry unwraps it with `nros_cpp_executor_inner` first. Registers
3175/// `C` on it via `register_node_borrowed` (private helper). The component's `ComponentCell`
3176/// is PLACED in caller/leaked storage (W5-endgame step 2b) and dropped in place by the
3177/// executor on `Executor::drop`. Returns `0` on success, `-1` on a null handle or a
3178/// registration error, `-4` on an nros-cpp context that was not unwrapped.
3179///
3180/// This backs the `__nros_component_<pkg>_install(node, executor, self, ...)` symbol
3181/// `nros::node!()` emits — the uniform cross-language install seam.
3182///
3183/// # Safety
3184/// `executor` must be the live `*mut Executor<'static>` handle a typed entry passes (its
3185/// `nros::global_handle()` / a node's `executor_handle()`), valid for the call.
3186#[cfg(feature = "alloc")]
3187pub unsafe fn install_node_typed<C: ExecutableNode + 'static>(
3188 executor: *mut core::ffi::c_void,
3189) -> i32
3190where
3191 C::State: 'static,
3192{
3193 // SAFETY: forwarded per this fn's contract; no baked params.
3194 unsafe { install_node_typed_with_params::<C>(executor, &[]) }
3195}
3196
3197/// W4a — same as [`install_node_typed`] but seeds the node's [`NodeContext`] with the
3198/// launch-baked `<param>` initial values, so a `register`/`init`-time `ctx.param(name)`
3199/// observes the compile-time launch value. `params` must outlive the call.
3200///
3201/// # Safety
3202/// `executor` must be the live `*mut Executor<'static>` handle a typed entry passes, valid for the call.
3203#[cfg(feature = "alloc")]
3204pub unsafe fn install_node_typed_with_params<C: ExecutableNode + 'static>(
3205 executor: *mut core::ffi::c_void,
3206 params: &[(&str, &str)],
3207) -> i32
3208where
3209 C::State: 'static,
3210{
3211 // SAFETY: forwarded per this fn's contract; no identity injection.
3212 unsafe { install_node_typed_with_node_identity::<C>(executor, params, None) }
3213}
3214
3215/// Same as [`install_node_typed_with_params`] but also injects the
3216/// launch `<node name= namespace=>` identity so `ExecutorSink::create_node` uses it
3217/// instead of the `NodeOptions` default. `None` → backward-compatible
3218/// (NodeOptions stands). `nros::node!()` calls this variant to carry the identity from
3219/// `RuntimeCtx::node_identity` set by `nros::main!` per component. `params` and
3220/// `node_identity` strings must outlive the call (both are `'static` in the macro emit).
3221///
3222/// # Safety
3223/// `executor` must be the live `*mut Executor<'static>` handle a typed entry passes, valid for the call.
3224#[cfg(feature = "alloc")]
3225pub unsafe fn install_node_typed_with_node_identity<C: ExecutableNode + 'static>(
3226 executor: *mut core::ffi::c_void,
3227 params: &[(&str, &str)],
3228 node_identity: Option<(&'static str, &'static str)>,
3229) -> i32
3230where
3231 C::State: 'static,
3232{
3233 // SAFETY: forwarded per this fn's contract; no remap rules.
3234 unsafe { install_node_typed_with_launch::<C>(executor, params, node_identity, &[], &[]) }
3235}
3236
3237/// Same as [`install_node_typed_with_node_identity`]
3238/// but also carries the launch `<remap from= to=/>` rules `nros::main!` baked for
3239/// this component (`RuntimeCtx::remaps`). `ExecutorSink::create_entity` applies
3240/// them (plus `~`/relative expansion) before any entity name reaches the wire.
3241/// All slices must outlive the call (`'static` promoted in the macro emit).
3242///
3243/// # Safety
3244/// `executor` must be the live `*mut Executor<'static>` handle a typed entry passes, valid for the call.
3245#[cfg(feature = "alloc")]
3246pub unsafe fn install_node_typed_with_launch<C: ExecutableNode + 'static>(
3247 executor: *mut core::ffi::c_void,
3248 params: &[(&str, &str)],
3249 node_identity: Option<(&'static str, &'static str)>,
3250 remaps: &[(&str, &str)],
3251 qos_overrides: &'static [nros_node::executor::node_record::QoSOverrideCode],
3252) -> i32
3253where
3254 C::State: 'static,
3255{
3256 // Issue 1535 — the ONE handle check: null, or an nros-cpp context a C/C++
3257 // entry forgot to unwrap, is refused before anything is written through it.
3258 let exec: &mut Executor<'static> = match unsafe {
3259 crate::executor_handle::executor_from_handle(executor, "install_node_typed")
3260 } {
3261 Ok(exec) => exec,
3262 Err(refusal) => return install_handle_refusal_code(refusal),
3263 };
3264 // phase-391 W5.3b — the alloc convenience: leak exactly-sized slot storage
3265 // per call, the same relationship `from_executor` has to `new_in`. The
3266 // macro-emitted entries call the `_in` twin with their per-class static
3267 // instead, so GENERATED images do not take this branch.
3268 let slot_mu: &'static mut MaybeUninit<TypedSlot<C>> =
3269 Box::leak(Box::new(MaybeUninit::uninit()));
3270 // W5-endgame step 2b — the cell leaks the same way; its destructor still
3271 // runs (executor drop trampoline, in place), only the bytes stay.
3272 let cell_mu: &'static mut MaybeUninit<ComponentCell> =
3273 Box::leak(Box::new(MaybeUninit::uninit()));
3274 match register_node_borrowed::<C, _, _, _, _, _, _>(
3275 exec,
3276 crate::node::LaunchParams::Pairs(params),
3277 LaunchIdentity::from(node_identity),
3278 crate::node::LaunchParams::Pairs(remaps),
3279 qos_overrides,
3280 slot_mu,
3281 cell_mu,
3282 ) {
3283 Ok(_cell) => 0,
3284 // Issue 0095 — distinct code for executor-table exhaustion so the macro
3285 // register seam can name `NROS_EXECUTOR_MAX_CBS` instead of an opaque
3286 // `NodeRegister`. Every other failure stays the generic `-1`.
3287 Err(NodeDeclError::ExecutorFull) => -2,
3288 Err(_) => -1,
3289 }
3290}
3291
3292/// [`install_node_typed_with_launch`] over the CALLER's
3293/// per-class slot storage: the heap-free FFI install path. The `nros::node!`
3294/// macro emits one `static ComponentSlotStorage<C>` per expansion and calls
3295/// this twin; the C ABI trampoline above it keeps its `(ptr, ptr, ptr) -> i32`
3296/// shape, so nothing foreign changes.
3297///
3298/// Returns `-3` when the class's instance cap is exhausted — raise
3299/// `NROS_RUNTIME_MAX_CLASS_INSTANCES`. (Distinct from `-2`, the executor
3300/// callback-table Full.) Returns `-4` for an nros-cpp context handle that the
3301/// C/C++ caller did not unwrap with `nros_cpp_executor_inner`.
3302///
3303/// # Safety
3304/// `executor` must be null, an nros-cpp context (refused), or the live
3305/// `*mut Executor<'static>` handle a typed entry passes, valid for the call.
3306pub unsafe fn install_node_typed_with_launch_in<
3307 C: ExecutableNode + 'static,
3308 const N: usize,
3309 const PUBS: usize,
3310 const SVCS: usize,
3311 const ACTC: usize,
3312 const ACTS: usize,
3313 const SSRV: usize,
3314 const TIMS: usize,
3315>(
3316 executor: *mut core::ffi::c_void,
3317 store: &'static ComponentSlotStorage<C, N, PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>,
3318 params: &[(&str, &str)],
3319 node_identity: Option<(&'static str, &'static str)>,
3320 remaps: &[(&str, &str)],
3321 qos_overrides: &'static [nros_node::executor::node_record::QoSOverrideCode],
3322) -> i32
3323where
3324 C::State: 'static,
3325{
3326 // SAFETY: forwarded per this fn's contract.
3327 unsafe {
3328 install_in_with_launch_params(
3329 executor,
3330 store,
3331 crate::node::LaunchParams::Pairs(params),
3332 LaunchIdentity::from(node_identity),
3333 crate::node::LaunchParams::Pairs(remaps),
3334 qos_overrides,
3335 )
3336 }
3337}
3338
3339/// [`install_node_typed_in`] carrying the launch `<param>` initials a C or C++
3340/// entry passes as a flat C-string array: `kv` holds `2 * n_pairs` pointers,
3341/// `[name0, value0, name1, value1, ...]`. This backs the component's C-ABI
3342/// install symbol, so a Rust component installed by a foreign entry sees the
3343/// same `ctx.param(name)` values one installed by `nros::main!` does.
3344///
3345/// The array is read in place and only for the duration of the call; a null
3346/// `kv` with `n_pairs == 0` means no params.
3347///
3348/// It carries the rest of the node's launch facts the `nros::main!` road
3349/// carries, so the component lands where the launch says:
3350/// - `name` / `namespace`: the launch `<node name= namespace=>`, each NULL
3351/// when the launch states none, and then the component's `NodeOptions`
3352/// value stands for that half;
3353/// - `remaps` / `n_remaps`: the node's launch `<remap from= to=/>` rules as a
3354/// flat `[from0, to0, from1, to1, ...]` array (NULL + 0 for none), applied
3355/// to every name the component declares.
3356///
3357/// Returns `-5`, before the class's storage is taken, when an array is null
3358/// with a non-zero count, or any string is null (except `name`/`namespace`)
3359/// or not UTF-8. Every other code is as for
3360/// [`install_node_typed_with_launch_in`].
3361///
3362/// # Safety
3363/// As [`install_node_typed_with_launch_in`]; and when `n_pairs > 0`, `kv`
3364/// must point to `2 * n_pairs` readable pointers, each null or a
3365/// NUL-terminated string, all valid for the call (`remaps` likewise).
3366/// `name` and `namespace` must each be NULL or a NUL-terminated string that
3367/// lives as long as the image: the node keeps it (a generated entry passes
3368/// string literals).
3369#[allow(clippy::too_many_arguments)] // the C-ABI seam's arguments, forwarded one for one
3370pub unsafe fn install_node_typed_with_c_params_in<
3371 C: ExecutableNode + 'static,
3372 const N: usize,
3373 const PUBS: usize,
3374 const SVCS: usize,
3375 const ACTC: usize,
3376 const ACTS: usize,
3377 const SSRV: usize,
3378 const TIMS: usize,
3379>(
3380 executor: *mut core::ffi::c_void,
3381 store: &'static ComponentSlotStorage<C, N, PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>,
3382 kv: *const *const core::ffi::c_char,
3383 n_pairs: usize,
3384 name: *const core::ffi::c_char,
3385 namespace: *const core::ffi::c_char,
3386 remaps: *const *const core::ffi::c_char,
3387 n_remaps: usize,
3388) -> i32
3389where
3390 C::State: 'static,
3391{
3392 // issue 2568 -- the C++ entry's Rust arm reaches the component through
3393 // this seam, and before it carried no params `ctx.param()` answered the
3394 // default for every launch `<param>`.
3395 // SAFETY: forwarded per this fn's contract.
3396 let Some(params) = (unsafe { crate::node::LaunchParams::from_c_pairs(kv, n_pairs) }) else {
3397 nros_log::log_error!(
3398 nros_log::get_logger("nros"),
3399 "component install refused its launch parameters: the array is null or \
3400 holds a null or non-UTF-8 string ({n_pairs} pair(s))"
3401 );
3402 return -5;
3403 };
3404 // Issue 2590 -- and before it carried no identity or remaps, the node took
3405 // its `NodeOptions` name and every launch remap was dropped.
3406 // SAFETY: forwarded per this fn's contract.
3407 let Some(remaps) = (unsafe { crate::node::LaunchParams::from_c_pairs(remaps, n_remaps) })
3408 else {
3409 nros_log::log_error!(
3410 nros_log::get_logger("nros"),
3411 "component install refused its launch remaps: the array is null or \
3412 holds a null or non-UTF-8 string ({n_remaps} rule(s))"
3413 );
3414 return -5;
3415 };
3416 // SAFETY: each NULL or a NUL-terminated string living as long as the image,
3417 // per this fn's contract.
3418 let (Some(name), Some(namespace)) = (unsafe { static_c_str(name) }, unsafe {
3419 static_c_str(namespace)
3420 }) else {
3421 nros_log::log_error!(
3422 nros_log::get_logger("nros"),
3423 "component install refused its launch node name or namespace: not UTF-8"
3424 );
3425 return -5;
3426 };
3427 // SAFETY: forwarded per this fn's contract.
3428 unsafe {
3429 install_in_with_launch_params(
3430 executor,
3431 store,
3432 params,
3433 LaunchIdentity { name, namespace },
3434 remaps,
3435 &[],
3436 )
3437 }
3438}
3439
3440/// A launch identity half from a C string: `Some(None)` for NULL (the launch
3441/// states none), `Some(Some(s))` for a UTF-8 string, `None` when it is not
3442/// UTF-8.
3443///
3444/// # Safety
3445/// `p` is NULL or a NUL-terminated string that lives as long as the image.
3446unsafe fn static_c_str(p: *const core::ffi::c_char) -> Option<Option<&'static str>> {
3447 if p.is_null() {
3448 return Some(None);
3449 }
3450 // SAFETY: per this fn's contract.
3451 let bytes = unsafe { core::ffi::CStr::from_ptr(p) }.to_bytes();
3452 core::str::from_utf8(bytes).ok().map(Some)
3453}
3454
3455/// The one body behind both `_in` installs.
3456///
3457/// # Safety
3458/// As [`install_node_typed_with_launch_in`].
3459unsafe fn install_in_with_launch_params<
3460 C: ExecutableNode + 'static,
3461 const N: usize,
3462 const PUBS: usize,
3463 const SVCS: usize,
3464 const ACTC: usize,
3465 const ACTS: usize,
3466 const SSRV: usize,
3467 const TIMS: usize,
3468>(
3469 executor: *mut core::ffi::c_void,
3470 store: &'static ComponentSlotStorage<C, N, PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>,
3471 params: crate::node::LaunchParams<'_>,
3472 node_identity: LaunchIdentity,
3473 remaps: crate::node::LaunchParams<'_>,
3474 qos_overrides: &'static [nros_node::executor::node_record::QoSOverrideCode],
3475) -> i32
3476where
3477 C::State: 'static,
3478{
3479 // Issue 1535 — checked BEFORE the class's storage is taken, so a refused
3480 // handle leaves the slot for a corrected retry.
3481 let exec: &mut Executor<'static> = match unsafe {
3482 crate::executor_handle::executor_from_handle(executor, "install_node_typed_in")
3483 } {
3484 Ok(exec) => exec,
3485 Err(refusal) => return install_handle_refusal_code(refusal),
3486 };
3487 let Some((slot_mu, cell_mu)) = store.take() else {
3488 return -3;
3489 };
3490 match register_node_borrowed::<C, _, _, _, _, _, _>(
3491 exec,
3492 params,
3493 node_identity,
3494 remaps,
3495 qos_overrides,
3496 slot_mu,
3497 cell_mu,
3498 ) {
3499 Ok(_cell) => 0,
3500 Err(NodeDeclError::ExecutorFull) => -2,
3501 Err(_) => -1,
3502 }
3503}
3504
3505/// [`install_node_typed`] over caller storage; see
3506/// [`install_node_typed_with_launch_in`].
3507///
3508/// # Safety
3509/// As [`install_node_typed_with_launch_in`].
3510pub unsafe fn install_node_typed_in<
3511 C: ExecutableNode + 'static,
3512 const N: usize,
3513 const PUBS: usize,
3514 const SVCS: usize,
3515 const ACTC: usize,
3516 const ACTS: usize,
3517 const SSRV: usize,
3518 const TIMS: usize,
3519>(
3520 executor: *mut core::ffi::c_void,
3521 store: &'static ComponentSlotStorage<C, N, PUBS, SVCS, ACTC, ACTS, SSRV, TIMS>,
3522) -> i32
3523where
3524 C::State: 'static,
3525{
3526 // SAFETY: forwarded per this fn's contract.
3527 unsafe { install_node_typed_with_launch_in(executor, store, &[], None, &[], &[]) }
3528}
3529
3530// Phase 258 (Track 2, w5) — ~~`nros_run_components`~~ (the BSP shim that registered
3531// every component via the four-fn-ptr ~~`register_dispatch_slot`~~ then spun) is
3532// gone. It had no callers; owned-spin / BSP entries register through the
3533// `install_node_typed` seam + drive `ExecutorNodeRuntime::spin`.
3534
3535/// RFC-0128 D2/D6 — register `node`'s machine (keeping one its component
3536/// already registered) and drive its boot autostart. The transitions run with
3537/// no callbacks of the entry's own: a component's registered callbacks run,
3538/// otherwise each takes the default-success path.
3539#[cfg(all(feature = "alloc", feature = "lifecycle-services"))]
3540fn manage_node(
3541 executor: &mut Executor<'static>,
3542 node: nros_node::executor::NodeId,
3543 autostart: u8,
3544) -> Result<(), &'static str> {
3545 executor
3546 .register_managed_node_on(node)
3547 .map_err(|e| capability_reason(&e))?;
3548 // SAFETY: any callbacks on this machine were registered by the node's own
3549 // component, which the runtime keeps alive for the executor's life.
3550 unsafe { executor.drive_lifecycle_autostart_on(node, autostart) }
3551 .map_err(|_| "the node's boot autostart transition was refused by its callback")
3552}
3553
3554/// issue 0460 — map a `NodeError` to a static reason a capability failure can
3555/// carry across the `nros-platform` trait boundary (which cannot name
3556/// `NodeError`). Static strings, so this works on `no_std` targets with no
3557/// allocator and no `log` dependency in this crate.
3558///
3559/// Both matches are EXHAUSTIVE on purpose. A wildcard arm is how this issue got
3560/// its diagnostic — `NodeRegister("lifecycle")` named the capability and
3561/// nothing about the cause — and a `_ =>` here would reintroduce exactly that
3562/// for whichever variant is added next. The compile error is the point.
3563///
3564/// Gated on `alloc` as well, because its only callers are
3565/// `ExecutorNodeRuntime`'s capability hooks, and that runtime is `alloc`-only.
3566/// A heap-free C++ image with a carved parameter store (`param-store`, no
3567/// `alloc`) compiled it with nothing calling it, which `-D warnings` refuses
3568/// (issue 2115).
3569#[cfg(all(
3570 feature = "alloc",
3571 any(feature = "lifecycle-services", feature = "param-store")
3572))]
3573fn capability_reason(e: &nros_node::NodeError) -> &'static str {
3574 use nros_node::NodeError;
3575 match e {
3576 NodeError::Transport(t) => capability_transport_reason(t),
3577 NodeError::NameTooLong => {
3578 "NameTooLong (the node FQN or a service name overflowed its fixed buffer)"
3579 }
3580 NodeError::ExecutorFull => {
3581 "ExecutorFull (no callback slot left — raise CONFIG_NROS_EXECUTOR_MAX_CBS; \
3582 a capability's services are not counted by the model)"
3583 }
3584 NodeError::NodeTableFull => "NodeTableFull (NROS_EXECUTOR_MAX_NODES reached)",
3585 NodeError::NotInitialized => "NotInitialized (a required subsystem was never registered)",
3586 NodeError::BackendMismatch => "BackendMismatch (the RMW is not the executor's session)",
3587 NodeError::BufferTooSmall => "BufferTooSmall",
3588 NodeError::Serialization => "Serialization",
3589 NodeError::Deserialization => "Deserialization",
3590 NodeError::ActionCreationFailed => "ActionCreationFailed",
3591 NodeError::ServiceRequestFailed => "ServiceRequestFailed",
3592 NodeError::ServiceReplyFailed => "ServiceReplyFailed",
3593 NodeError::Timeout => "Timeout",
3594 NodeError::RequestInFlight => "RequestInFlight",
3595 NodeError::NoSchedContextSlot => "NoSchedContextSlot",
3596 NodeError::InvalidSchedContextBinding => "InvalidSchedContextBinding",
3597 // issue 0790 added this variant and did not add the arm; the exhaustive
3598 // match above did exactly what its doc comment says it is for, and the
3599 // lanes that were run could not see it (`--all-targets` enables `test`,
3600 // which pulls in a different cfg path, and `cargo doc` does no
3601 // exhaustiveness checking, so the parity lane stayed green over it).
3602 NodeError::ShutdownCallbacksFull => {
3603 "ShutdownCallbacksFull (the executor's pre/on-shutdown callback table is \
3604 full — raise NROS_EXECUTOR_MAX_SHUTDOWN_CBS)"
3605 }
3606 NodeError::LifecycleAlreadyRegistered => {
3607 "LifecycleAlreadyRegistered (this node already has a lifecycle state machine)"
3608 }
3609 NodeError::LifecycleNodeUnnamed => {
3610 "LifecycleNodeUnnamed (a lifecycle state machine needs a declared node; this \
3611 image declares none and the executor has no name)"
3612 }
3613 // phase-454 W10. The two numbers and the topic are already on the log
3614 // by the time this renders — this string is the CLASS, and a reason
3615 // that repeated the numbers without the topic would be worse than one
3616 // that points at the line which has all three.
3617 NodeError::DeclaredDepthMismatch => {
3618 "DeclaredDepthMismatch (this subscription's QoS depth disagrees with the depth \
3619 the contract sidecar declares for that topic — the log line above names the \
3620 topic and both numbers; depth multiplies the executor arena, so the two must \
3621 state one number)"
3622 }
3623 // issue 1256. Same shape: the policy, the topic and both values are on
3624 // the log line above.
3625 NodeError::DeclaredQosMismatch => {
3626 "DeclaredQosMismatch (this subscription's QoS reliability or durability \
3627 disagrees with what the contract sidecar declares for that topic — the log \
3628 line above names the policy, the topic and both values; an incompatible-QoS \
3629 match never delivers)"
3630 }
3631 }
3632}
3633
3634/// The `NodeError::Transport` payload, which is the half that actually names
3635/// what the RMW refused. `Backend(&'static str)` passes its own diagnostic
3636/// straight through — it is already the string the backend wanted to say.
3637///
3638/// Unlike `capability_reason` above this one keeps a wildcard, for
3639/// `TransportError::BackendDynamic`, which is gated on `nros-rmw/alloc`. This
3640/// function is compiled only with `nros/alloc`, which turns that on, so the
3641/// variant always exists here; the wildcard stands for it rather than naming
3642/// it, so its text is what any unmapped variant looks like. (Before issue 2115
3643/// this function was compiled without `alloc` too, where the variant does not
3644/// exist and the wildcard was an `unreachable_patterns` error.)
3645#[cfg(all(
3646 feature = "alloc",
3647 any(feature = "lifecycle-services", feature = "param-store")
3648))]
3649fn capability_transport_reason(t: &nros_rmw::TransportError) -> &'static str {
3650 use nros_rmw::TransportError as T;
3651 match t {
3652 T::Backend(s) => s,
3653 T::ServiceServerCreationFailed => {
3654 "Transport::ServiceServerCreationFailed (the RMW refused to declare the queryable)"
3655 }
3656 T::ServiceClientCreationFailed => "Transport::ServiceClientCreationFailed",
3657 T::PublisherCreationFailed => "Transport::PublisherCreationFailed",
3658 T::SubscriberCreationFailed => "Transport::SubscriberCreationFailed",
3659 T::ConnectionFailed => "Transport::ConnectionFailed (no session to the router)",
3660 T::Disconnected => "Transport::Disconnected",
3661 T::SessionLost => "Transport::SessionLost (the Agent restarted; re-open the executor)",
3662 T::TopicNameInvalid => "Transport::TopicNameInvalid",
3663 T::NodeNameNonExistent => "Transport::NodeNameNonExistent",
3664 // phase-417 G7 — the variant carries the refused `QoSPolicyMask` bit
3665 // now, and this function's return type has no room for it: a
3666 // `&'static str` cannot be composed, and a second table of twelve
3667 // pre-written sentences is exactly the parallel vocabulary the bit's
3668 // own name exists to avoid. The policy is already on the line ABOVE
3669 // this one — `nros_node`'s `validate_qos_or_report` logs it at ERROR
3670 // at the refusing create — so this string is the CLASS and points at
3671 // the line that has the name, the same shape `DeclaredDepthMismatch`
3672 // uses two arms up. A Rust caller holding the error reads
3673 // `err.qos_policy_name()` and needs neither.
3674 T::IncompatibleQos(_) => {
3675 "Transport::IncompatibleQos (the backend does not honour a policy this \
3676 profile states — the log line above names which)"
3677 }
3678 T::IncompatibleAbi => "Transport::IncompatibleAbi",
3679 T::InvalidConfig => "Transport::InvalidConfig",
3680 T::InvalidArgument => "Transport::InvalidArgument",
3681 T::Unsupported => "Transport::Unsupported (the backend does not implement this)",
3682 T::BadAlloc => "Transport::BadAlloc",
3683 T::PublishFailed => "Transport::PublishFailed",
3684 T::ServiceRequestFailed => "Transport::ServiceRequestFailed",
3685 T::ServiceReplyFailed => "Transport::ServiceReplyFailed",
3686 T::SerializationError => "Transport::SerializationError",
3687 T::DeserializationError => "Transport::DeserializationError",
3688 T::BufferTooSmall => "Transport::BufferTooSmall",
3689 T::MessageTooLarge => "Transport::MessageTooLarge",
3690 T::Timeout => "Transport::Timeout",
3691 T::WouldBlock => "Transport::WouldBlock",
3692 T::TooLarge => "Transport::TooLarge",
3693 T::TaskStartFailed => "Transport::TaskStartFailed",
3694 T::PollFailed => "Transport::PollFailed",
3695 T::KeepaliveFailed => "Transport::KeepaliveFailed",
3696 T::JoinFailed => "Transport::JoinFailed",
3697 T::LoanNotSupported => "Transport::LoanNotSupported",
3698 T::NoData => "Transport::NoData",
3699 _ => "Transport::<variant with no reason mapping — add it here>",
3700 }
3701}
3702
3703// =============================================================================
3704// Tests
3705// =============================================================================
3706//
3707// Concrete `Executor` construction needs a real RMW backend session
3708// (with `rmw-cffi` on, `Executor::from_session` takes the cffi
3709// session). MockSession only exists when `rmw-cffi` is off — so the
3710// unit tests that exercise live timer firing live in
3711// `packages/testing/nros-tests/tests/phase212_m5a2_component_runtime.rs`
3712// gated behind the `component-runtime-test` feature (pulls
3713// `nros-rmw-zenoh`). The compile-only smoke here verifies the public
3714// types are reachable through the umbrella surface.
3715
3716/// Seed the contract rank of the node the
3717/// NEXT `register` call creates, `(name, namespace)`, on the executor the
3718/// runtime holds: 0 is the most urgent, as the derivation normalises it
3719/// (`nros_orchestration_ir::levels::node_ranks`). `nros::main!` emits it before
3720/// each ranked node's `register`, the Rust twin of the C/C++ packs'
3721/// `nros_cpp_bind_node_rank`.
3722///
3723/// A runtime with no executor handle (no live executor) has nothing to
3724/// order and seeds nothing. A binding that does not fit the node-name table
3725/// is refused with the node's name, never dropped.
3726pub fn seed_node_rank(
3727 runtime: &mut nros_platform::RuntimeCtx<'_>,
3728 name: &'static str,
3729 namespace: &'static str,
3730 rank: u8,
3731) -> Result<(), nros_platform::RuntimeError> {
3732 let handle = runtime.runtime.executor_handle();
3733 if handle.is_null() {
3734 return Ok(());
3735 }
3736 // SAFETY: a non-null handle from the runtime sink is its live executor
3737 // (or an nros-cpp context, which the one handle check refuses), and
3738 // nothing else borrows it during this call.
3739 let exec = unsafe { crate::executor_handle::executor_from_handle(handle, "seed_node_rank") }
3740 .map_err(|_| nros_platform::RuntimeError::NodeRegister(name))?;
3741 exec.bind_node_rank(name, namespace, rank)
3742 .map_err(|_| nros_platform::RuntimeError::NodeRegister(name))
3743}
3744
3745#[cfg(test)]
3746mod tests {
3747 use super::*;
3748 use crate::node::Component;
3749
3750 /// Issue 2360 -- the in-place conversion gives what the by-value one gave:
3751 /// the string arm is `from_string`'s answer (`NotSet` when the string does
3752 /// not fit the store's capacity), a double is parsed, and an array default
3753 /// is `NotSet`. Each case starts from a value of a DIFFERENT variant, so a
3754 /// stale payload left in `out` would show.
3755 #[test]
3756 fn a_parameter_default_is_written_in_place() {
3757 use crate::node_metadata::{MetadataString, ParameterDefault};
3758 use core::fmt::Write as _;
3759 use nros_params::ParameterValue;
3760 let text = |s: &str| MetadataString::try_from(s).unwrap();
3761 // `ParameterValue` has no `PartialEq`; its `Debug` names the variant
3762 // and the payload, which is what these cases compare.
3763 let shown = |v: &ParameterValue| {
3764 let mut out: heapless::String<512> = heapless::String::new();
3765 write!(out, "{v:?}").unwrap();
3766 out
3767 };
3768 let convert = |d: Option<&ParameterDefault>| {
3769 let mut out = ParameterValue::Integer(7);
3770 param_default_into(d, &mut out);
3771 shown(&out)
3772 };
3773 assert_eq!(convert(None), shown(&ParameterValue::NotSet));
3774 assert_eq!(
3775 convert(Some(&ParameterDefault::Bool(true))),
3776 shown(&ParameterValue::Bool(true))
3777 );
3778 assert_eq!(
3779 convert(Some(&ParameterDefault::Integer(-3))),
3780 shown(&ParameterValue::Integer(-3))
3781 );
3782 assert_eq!(
3783 convert(Some(&ParameterDefault::Double(text("2.5")))),
3784 shown(&ParameterValue::Double(2.5))
3785 );
3786 assert_eq!(
3787 convert(Some(&ParameterDefault::Double(text("not a number")))),
3788 shown(&ParameterValue::Double(0.0))
3789 );
3790 for s in ["", "hello", "a longer default string than most"] {
3791 let mut out = ParameterValue::Bool(false);
3792 param_default_into(Some(&ParameterDefault::String(text(s))), &mut out);
3793 assert_eq!(
3794 shown(&out),
3795 shown(&ParameterValue::from_string(s).unwrap_or(ParameterValue::NotSet)),
3796 "string default {s:?}"
3797 );
3798 }
3799 assert_eq!(
3800 convert(Some(&ParameterDefault::StringArray)),
3801 shown(&ParameterValue::NotSet)
3802 );
3803 }
3804
3805 #[test]
3806 fn handle_slot_is_observable() {
3807 // Trivial smoke — the handle type carries the slot index.
3808 let h = RegisteredNode::<DummyComp> {
3809 component_idx: 7,
3810 _phantom: PhantomData,
3811 };
3812 assert_eq!(h.slot(), 7);
3813 }
3814
3815 /// Issue 0857 — the per-class store pays its DECLARED capacity, and the
3816 /// publisher registry is where the bytes are.
3817 ///
3818 /// The same quantity `nm -S` reads off a linked image, without the link
3819 /// step. Measured both ways on `examples/workspaces/rust`'s
3820 /// `linux_service_server_entry` (2026-09-06, one build dir, one file
3821 /// changed): `__NROS_COMPONENT_service_server_pkg_SLOT_STORE` is 50,824 B
3822 /// of `.bss` when the class declares nothing and 568 B when it declares
3823 /// `EntityBounds::exact(0, 1, 0, 0, 0)`.
3824 ///
3825 /// The assertions are on the SHAPE rather than on those two literals,
3826 /// because both move with the knob, with `DEFAULT_LOAN_BUF` and with the
3827 /// target's pointer width. What must not move is the direction: one
3828 /// publisher slot is kilobytes, and declaring less costs less.
3829 #[test]
3830 fn a_declared_cell_pays_for_what_it_declares() {
3831 use core::mem::size_of;
3832 const N: usize = crate::config::MAX_CLASS_INSTANCES;
3833 type Zero = ComponentSlotStorage<DummyComp, N, 0, 0, 0, 0, 0, 0>;
3834 type OnePub = ComponentSlotStorage<DummyComp, N, 1, 0, 0, 0, 0, 0>;
3835 type Capped = ComponentSlotStorage<DummyComp>;
3836 // Issue 2075 -- a controllable-timer row is a hash and a handle, not
3837 // a name: at most 32 B an instance (16 B of payload plus the op and
3838 // padding), so the table the knob default carries is small.
3839 type OneTimer = ComponentSlotStorage<DummyComp, N, 0, 0, 0, 0, 0, 1>;
3840 assert!(
3841 size_of::<OneTimer>() - size_of::<Zero>() <= 32 * N,
3842 "a timer row costs {} B for {N} instances; it should be a hash + a handle",
3843 size_of::<OneTimer>() - size_of::<Zero>()
3844 );
3845
3846 let zero = size_of::<Zero>();
3847 let one_pub = size_of::<OnePub>();
3848 let capped = size_of::<Capped>();
3849
3850 // `EmbeddedRawPublisher` embeds a `TxArena<DEFAULT_LOAN_BUF>`, so ONE
3851 // publisher slot is the whole reason the knob-capped default is
3852 // measured in tens of kilobytes. If this ever drops below a kilobyte
3853 // the issue's cost model has changed and the sweep is worth revisiting.
3854 assert!(
3855 one_pub - zero >= 1024 * N,
3856 "a publisher registry slot should cost >= 1 KiB per instance; \
3857 zero={zero} one_pub={one_pub} N={N}"
3858 );
3859
3860 // Declaring nothing must cost strictly less than the knob caps —
3861 // unless the knob itself is 0, in which case they are the same store.
3862 if crate::config::MAX_CELL_ENTITIES > 0 {
3863 assert!(
3864 zero < capped,
3865 "declaring nothing ({zero} B) is not cheaper than the knob caps \
3866 ({capped} B at MAX_CELL_ENTITIES={})",
3867 crate::config::MAX_CELL_ENTITIES
3868 );
3869 assert!(
3870 capped - zero >= (one_pub - zero) * crate::config::MAX_CELL_ENTITIES,
3871 "the knob-capped store should carry MAX_CELL_ENTITIES publisher \
3872 slots at least; zero={zero} one_pub={one_pub} capped={capped}"
3873 );
3874 }
3875 }
3876
3877 struct DummyComp;
3878 impl Component for DummyComp {
3879 const NAME: &'static str = "dummy";
3880 fn register(_ctx: &mut NodeContext<'_>) -> NodeResult<()> {
3881 Ok(())
3882 }
3883 }
3884 impl ExecutableNode for DummyComp {
3885 type State = ();
3886 fn init() -> Self::State {}
3887 fn on_callback(_s: &mut (), _cb: Callback<'_>, _ctx: &mut CallbackCtx<'_>) {}
3888 }
3889}