nros/node.rs
1//! Rust component API shared by metadata discovery and generated runtimes.
2
3// phase-483 W3 — the component API (`Component`, `NodeContext`,
4// `DeclarativeNode`) registers into a live executor and exists only with
5// `rmw-cffi`. Without it this module still carries the metadata vocabulary the
6// C/C++ adapters use, and the declaration helpers the component API calls go
7// unused.
8#![cfg_attr(not(feature = "rmw-cffi"), allow(unused_imports, dead_code))]
9
10use core::marker::PhantomData;
11
12#[cfg(feature = "param-store")]
13use nros_params::ParameterServerOps as _; // phase-515 R10 stage 2
14
15// issue 0413 — the descriptor-registration bound. `MessageForRmw` is
16// `RosMessage` alone unless a descriptor-needing backend is linked, in which
17// case it also requires `nros_serdes::schema::Message` (the schema the Cyclone
18// descriptor builder walks). Generated message crates implement both.
19use nros_node::rmw_type_registry::MessageForRmw;
20
21use crate::{
22 ActionTag, CallbackId, CancelResponse, EntityId, GoalResponse, GoalStatusCode, GoalUuid,
23 ParameterType, QoSProfile, RosAction, RosMessage, RosService, ServiceTag, SubscriptionTag,
24 TimerClockSource, TimerDuration,
25 heapless::Vec,
26 node_metadata::{
27 CallbackEffectKind, EntityKind, EntityMetadata, EntityMetadataSpec, MetadataRecorder,
28 MetadataString, NodeId, NodeMetadataError, ParameterDefault, SourceLocationMetadata,
29 copy_str, entity_metadata,
30 },
31};
32
33// Phase 212.N.7 step-6 closing sweep — ~~`component_register_symbol`~~
34// removed. It built the legacy `__nros_component_<pkg>_register`
35// symbol name for the M.5.a BSP baker to look up by literal. step-6
36// retired the macro emit + step-4 deleted the FreeRTOS BSP baker
37// crate that was the sole live consumer. The Phase 212.N Entry pkg
38// path calls `<pkg>::register(runtime)` through the path API, so this
39// helper has no live callers.
40
41/// Result type for component declarations.
42pub type NodeResult<T = ()> = Result<T, NodeDeclError>;
43
44/// Register `M`'s runtime type descriptor with a descriptor-needing backend
45/// (Cyclone DDS), from the DECLARATIVE path — issue 0413.
46///
47/// The imperative API's typed creators (`Node::create_publisher_with_qos::<M>`
48/// in `nros-node`) already call `register_type::<M>()` before asking the cffi
49/// vtable for the entity, because Cyclone resolves topic types through a
50/// RUNTIME registry and `dds_create_topic` fails without it.
51///
52/// The declarative Node API does not reach those creators. `NodeContext`
53/// records `EntityMetadata` and the sink calls the type-ERASED
54/// `create_generic_publisher_with_qos(topic, type_name, type_hash, qos)` —
55/// which has a type NAME and no `M`, so it cannot register anything. The
56/// descriptor was therefore never built, `find_descriptor` returned null in
57/// `publisher.cpp`, and the entity failed with `NROS_RMW_RET_UNSUPPORTED` ->
58/// `TransportError::PublisherCreationFailed` -> `NodeDeclError::Runtime` ->
59/// `RuntimeError::NodeRegister("<pkg>")`, four collapses away from the cause.
60///
61/// So it is registered HERE, at the last point that still knows `M`. A no-op
62/// unless a descriptor-needing backend installed a registrar
63/// (`nros_rmw::register_type_descriptor` returns `Ok` when the slot is empty),
64/// so zenoh / XRCE builds are unaffected.
65///
66/// Why this only surfaced now: every native Rust example was
67/// `[package.metadata.nros.application]` (imperative, typed creators) until
68/// phase-338 W3 made them Node-class. C and C++ were never affected — they use
69/// the static `descriptors.cpp` table, which is why `c/talker` published
70/// normally against the same backend while `rust/talker` could not.
71#[inline]
72fn register_declared_type<M: nros_node::rmw_type_registry::MessageForRmw>() -> NodeResult<()> {
73 nros_node::rmw_type_registry::register_type::<M>().map_err(|_| NodeDeclError::Runtime)
74}
75
76/// issue 0413, service half — register both payload types of `S`.
77///
78/// Services reach the same type-erased sink path as publishers, so the
79/// descriptor has to be built here too. The bound is a WHERE-CLAUSE on the
80/// declarative methods rather than on `RosService` itself: `RosService` lives in
81/// `nros-core`, which cannot depend on `nros-node` where `MessageForRmw` is
82/// defined. Generated service crates satisfy it (their payloads implement
83/// `schema::Message`); a hand-rolled service used only with zenoh/XRCE is
84/// unaffected, because `MessageForRmw` collapses to `RosMessage` when no
85/// descriptor-needing backend is linked.
86#[inline]
87fn register_declared_service<S: RosService>() -> NodeResult<()>
88where
89 S::Request: nros_node::rmw_type_registry::MessageForRmw,
90 S::Reply: nros_node::rmw_type_registry::MessageForRmw,
91{
92 register_declared_type::<S::Request>()?;
93 register_declared_type::<S::Reply>()
94}
95
96/// Node declaration error.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum NodeDeclError {
99 /// Metadata recorder rejected the declaration.
100 Metadata(NodeMetadataError),
101 /// Host/runtime discovery could not find `nros::node!` export.
102 MissingExport,
103 /// Generated runtime rejected the declaration.
104 Runtime,
105 /// The executor's fixed callback-entry table is full — a timer /
106 /// subscription / service / action could not claim a slot (issue 0095).
107 /// Carries the capacity cause through the `NodeError → NodeDeclError`
108 /// collapse so the register seam can name `NROS_EXECUTOR_MAX_CBS`.
109 ExecutorFull,
110 /// A publish named an entity this component has no publisher for — the
111 /// LOOKUP failed, nothing was ever handed to the transport.
112 ///
113 /// issue 0736 — split out of [`Self::Runtime`], which the publish path
114 /// returned for BOTH "the transport rejected the sample" and "there is no
115 /// such publisher": ~~`lookup_publisher(...).unwrap_or(Err(Runtime))`~~. Those
116 /// are different bugs in different layers with different fixes, and from a
117 /// serial console they were the same line. Exactly the conflation #572
118 /// removed one level out, where discarding the result made "the timer never
119 /// fired" and "every publish failed" the same observation.
120 UnknownPublisher,
121 /// The parameter store refused a declaration and the name is still absent:
122 /// the store is full, or it rejected the value. A name already declared is
123 /// NOT this — the store answers `false` for that too, but the parameter is
124 /// there.
125 ///
126 /// Split out of [`Self::Runtime`] for the reason [`Self::UnknownPublisher`]
127 /// was (issue 0736): a refused parameter and a rejected transport handle are
128 /// different faults with different fixes, and one opaque variant made them
129 /// the same line on a serial console.
130 ParameterRejected,
131 /// A component CELL registry is full -- the class creates more entities of
132 /// one kind (publishers, service servers/clients, action servers/clients)
133 /// than its registry holds.
134 ///
135 /// issue 1130 -- split out of [`Self::Runtime`] BEFORE that capacity became
136 /// derivable. phase-412's rule: a derived count is safe only where
137 /// exhaustion NAMES the knob, and a bare "component runtime rejected
138 /// declaration" named nothing. The capacity is the class's `ENTITY_BOUNDS`
139 /// when it states one, else `NROS_RUNTIME_MAX_CELL_ENTITIES`.
140 CellRegistryFull,
141 /// Issue 2075 — a `reset_timer` / `cancel_timer` named an entity this
142 /// component has no CONTROLLABLE timer for: it declared no such timer,
143 /// or its class's [`EntityBounds::timers`] holds fewer timers than it
144 /// declares (the timers past the bound still run; they just cannot be
145 /// reset or cancelled by id).
146 UnknownTimer,
147}
148
149impl NodeDeclError {
150 /// Human-readable static message for diagnostics that cross FFI/plugin boundaries.
151 pub const fn message(self) -> &'static str {
152 match self {
153 Self::Metadata(NodeMetadataError::Capacity) => "component metadata capacity exceeded",
154 Self::Metadata(NodeMetadataError::NameTooLong) => "component metadata name too long",
155 Self::Metadata(NodeMetadataError::UnknownNode) => {
156 "component entity references an unknown node"
157 }
158 Self::Metadata(NodeMetadataError::UnknownEntity) => {
159 "component callback effect references an unknown entity"
160 }
161 Self::Metadata(NodeMetadataError::DuplicateId) => {
162 "component metadata contains a duplicate stable ID"
163 }
164 Self::MissingExport => "package has no exported nros component",
165 Self::Runtime => "component runtime rejected declaration",
166 Self::UnknownPublisher => "no publisher declared for that entity",
167 Self::UnknownTimer => {
168 "no controllable timer for that entity — it was not declared, or \
169 the class's ENTITY_BOUNDS.timers (EntityBounds::with_timers) holds \
170 fewer timers than it declares"
171 }
172 Self::ParameterRejected => {
173 "the parameter store refused the declaration (the store is full, or it \
174 rejected the value). A full store is sized by `max_parameters` under \
175 `[knobs.params]` in system.toml, NROS_PARAMS_MAX_PARAMETERS or \
176 CONFIG_NROS_PARAMS_MAX_PARAMETERS; left unstated, declaring every node's \
177 parameters under `params:` in the contract derives it"
178 }
179 Self::ExecutorFull => {
180 "executor callback table full — raise NROS_EXECUTOR_MAX_CBS \
181 (build-time, default 4)"
182 }
183 Self::CellRegistryFull => {
184 "component cell registry full — raise the class's ENTITY_BOUNDS, \
185 or NROS_RUNTIME_MAX_CELL_ENTITIES (build-time, default 8) for a \
186 class that states none"
187 }
188 }
189 }
190}
191
192impl From<NodeMetadataError> for NodeDeclError {
193 fn from(value: NodeMetadataError) -> Self {
194 Self::Metadata(value)
195 }
196}
197
198#[cfg(test)]
199mod cell_registry_full_tests {
200 use super::NodeDeclError;
201
202 /// Issue 1130 -- the precondition for deriving the cell capacity: running
203 /// out NAMES both remedies, where it used to read "component runtime
204 /// rejected declaration".
205 #[test]
206 fn a_full_cell_registry_names_the_knob_and_the_class_bound() {
207 let m = NodeDeclError::CellRegistryFull.message();
208 assert!(m.contains("NROS_RUNTIME_MAX_CELL_ENTITIES"), "{m}");
209 assert!(m.contains("ENTITY_BOUNDS"), "{m}");
210 assert_ne!(m, NodeDeclError::Runtime.message());
211 }
212
213 /// Issue 2075 -- `exact` asks for no timer table (a class that states its
214 /// bounds pays for none), `with_timers` adds one, the knob default has
215 /// one, and running out names the bound.
216 #[test]
217 fn timer_bounds_default_to_none_under_exact_and_name_the_bound() {
218 use super::EntityBounds;
219 let exact = EntityBounds::exact(1, 0, 0, 0, 0);
220 assert_eq!(exact.timers, 0);
221 assert_eq!(exact.with_timers(2).timers, 2);
222 assert_eq!(exact.with_timers(2).publishers, 1);
223 assert_eq!(
224 EntityBounds::knob_caps().timers,
225 crate::config::MAX_CELL_ENTITIES
226 );
227 let m = NodeDeclError::UnknownTimer.message();
228 assert!(m.contains("ENTITY_BOUNDS.timers"), "{m}");
229 }
230}
231
232/// issue 0413, action half — register every wire payload type of `A`.
233///
234/// Mirrors the eight `register_type::<A::…>()` calls the IMPERATIVE action
235/// creator makes (`nros-node/src/executor/action.rs`); the declarative path
236/// reaches the same type-erased sink and would otherwise register none of them.
237/// `A::register_protocol_types()` covers the fixed `action_msgs` types the
238/// cancel/status plumbing serializes, exactly as the imperative path does.
239#[inline]
240fn register_declared_action<A: RosAction>() -> NodeResult<()>
241where
242 A::Goal: nros_node::rmw_type_registry::MessageForRmw,
243 A::Result: nros_node::rmw_type_registry::MessageForRmw,
244 A::Feedback: nros_node::rmw_type_registry::MessageForRmw,
245 A::SendGoalRequest: nros_node::rmw_type_registry::MessageForRmw,
246 A::SendGoalResponse: nros_node::rmw_type_registry::MessageForRmw,
247 A::GetResultRequest: nros_node::rmw_type_registry::MessageForRmw,
248 A::GetResultResponse: nros_node::rmw_type_registry::MessageForRmw,
249 A::FeedbackMessage: nros_node::rmw_type_registry::MessageForRmw,
250{
251 register_declared_type::<A::Goal>()?;
252 register_declared_type::<A::Result>()?;
253 register_declared_type::<A::Feedback>()?;
254 register_declared_type::<A::SendGoalRequest>()?;
255 register_declared_type::<A::SendGoalResponse>()?;
256 register_declared_type::<A::GetResultRequest>()?;
257 register_declared_type::<A::GetResultResponse>()?;
258 register_declared_type::<A::FeedbackMessage>()?;
259 A::register_protocol_types().map_err(|()| NodeDeclError::Runtime)
260}
261
262/// A component class's declared
263/// upper bounds, PER ENTITY KIND, for sizing its cell registries at compile
264/// time.
265///
266/// The runtime's per-class cell storage is static, so its registries pay
267/// their CAPACITY whether or not entities fill it — and one publisher slot
268/// costs ~1.35 KiB (the loan arena rides inside). The default is the
269/// `NROS_RUNTIME_MAX_CELL_ENTITIES` knob per kind, which always works;
270/// a class that declares its real bounds pays exactly what it uses.
271/// Declaring FEWER than `register()` creates is a loud registration error
272/// (registry full), never a silent drop.
273///
274/// Public and non-generic on purpose (the `ExecutorSizing` rule): the const
275/// generics this feeds stay behind the `nros::node!` macro emission, so no
276/// other language ever sees them.
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub struct EntityBounds {
279 /// Publishers this class creates (each slot ~1.35 KiB — the big one).
280 pub publishers: usize,
281 /// Service servers (sizes the trampoline-context slab, not a registry).
282 pub service_servers: usize,
283 /// Service clients.
284 pub service_clients: usize,
285 /// Action clients.
286 pub action_clients: usize,
287 /// Action servers.
288 pub action_servers: usize,
289 /// Timers the component can START, RESET or CANCEL by id
290 /// ([`CallbackCtx::reset_timer`] / [`TickCtx::cancel_timer`]). Sizes a
291 /// small id-to-handle table (16 B a row), not the timers themselves: a
292 /// timer past this bound still registers and fires, it just cannot be
293 /// controlled, and naming it answers [`NodeDeclError::UnknownTimer`].
294 pub timers: usize,
295}
296
297impl EntityBounds {
298 /// The knob-capped default (`NROS_RUNTIME_MAX_CELL_ENTITIES` per kind).
299 pub const fn knob_caps() -> Self {
300 Self {
301 publishers: crate::config::MAX_CELL_ENTITIES,
302 service_servers: crate::config::MAX_CELL_ENTITIES,
303 service_clients: crate::config::MAX_CELL_ENTITIES,
304 action_clients: crate::config::MAX_CELL_ENTITIES,
305 action_servers: crate::config::MAX_CELL_ENTITIES,
306 timers: crate::config::MAX_CELL_ENTITIES,
307 }
308 }
309
310 /// Exact bounds, spelled positionally:
311 /// `(publishers, service_servers, service_clients, action_clients, action_servers)`.
312 ///
313 /// Controllable timers default to 0 here, so a class that
314 /// states exact bounds pays nothing for the timer table it did not ask
315 /// for. Its timers still run; add [`with_timers`](Self::with_timers) to
316 /// reset or cancel them by id.
317 pub const fn exact(
318 publishers: usize,
319 service_servers: usize,
320 service_clients: usize,
321 action_clients: usize,
322 action_servers: usize,
323 ) -> Self {
324 Self {
325 publishers,
326 service_servers,
327 service_clients,
328 action_clients,
329 action_servers,
330 timers: 0,
331 }
332 }
333
334 /// These bounds with `timers` controllable timers: how many
335 /// declared timers the component can start, reset or cancel by id.
336 ///
337 /// ```ignore
338 /// const ENTITY_BOUNDS: nros::EntityBounds =
339 /// nros::EntityBounds::exact(1, 0, 0, 0, 0).with_timers(2);
340 /// ```
341 pub const fn with_timers(self, timers: usize) -> Self {
342 Self { timers, ..self }
343 }
344}
345
346/// Rust component entry point.
347#[cfg(feature = "rmw-cffi")]
348pub trait Component {
349 /// Source component name used in metadata and diagnostics.
350 const NAME: &'static str;
351
352 /// Phase 216.A.3 — declares which dispatch strategy this Node
353 /// requires from the runtime. Defaults to
354 /// [`crate::DispatchStrategy::Inline`] so every existing component
355 /// keeps compiling without source change; the substrate (Phase
356 /// 216.A.2) and `nros check` (Phase 216.D.1) consume it to
357 /// pick / validate the board-side dispatch path.
358 const DISPATCH: crate::DispatchStrategy = crate::DispatchStrategy::Inline;
359
360 /// phase-391 W5-endgame step 2c — this class's per-kind entity bounds,
361 /// sizing its static cell registries. Defaults to the knob caps so every
362 /// existing component keeps compiling; declare [`EntityBounds::exact`]
363 /// to stop paying for capacity `register()` never fills.
364 const ENTITY_BOUNDS: EntityBounds = EntityBounds::knob_caps();
365
366 /// Declare nodes, entities, callbacks, params, and optional effects.
367 fn register(context: &mut NodeContext<'_>) -> NodeResult<()>;
368}
369
370pub use nros_node::{IntoNodeOptions, NodeOptions};
371
372/// Runtime callback event delivered to an executable Node.
373///
374/// The value carries the source callback name declared by the component, but
375/// does not expose the generated/internal callback ID type to product code.
376#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
377pub struct Callback<'a> {
378 id: CallbackId<'a>,
379}
380
381impl<'a> Callback<'a> {
382 /// Borrow the source callback name.
383 pub const fn as_str(self) -> &'a str {
384 self.id.as_str()
385 }
386
387 /// Return true when this callback matches `name`.
388 pub fn is_named(self, name: &str) -> bool {
389 self.as_str() == name
390 }
391
392 /// Build a callback event from the internal/generated callback ID.
393 #[doc(hidden)]
394 pub const fn __from_id(id: CallbackId<'a>) -> Self {
395 Self { id }
396 }
397}
398
399/// Declaration sink implemented by metadata recorders and generated runtimes.
400pub trait NodeRuntime {
401 /// Declare a component node.
402 fn create_node(&mut self, id: NodeId<'_>, options: NodeOptions<'_>) -> NodeResult<()>;
403
404 /// Declare a publisher, subscription, timer, service, action, or parameter.
405 fn create_entity(&mut self, metadata: EntityMetadata) -> NodeResult<()>;
406
407 /// Add optional callback effect metadata.
408 fn record_callback_effect(
409 &mut self,
410 callback_id: CallbackId<'_>,
411 kind: CallbackEffectKind,
412 entity_id: EntityId<'_>,
413 ) -> NodeResult<()>;
414}
415
416impl<const MAX_NODES: usize, const MAX_ENTITIES: usize, const MAX_CALLBACKS: usize> NodeRuntime
417 for MetadataRecorder<MAX_NODES, MAX_ENTITIES, MAX_CALLBACKS>
418{
419 fn create_node(&mut self, id: NodeId<'_>, options: NodeOptions<'_>) -> NodeResult<()> {
420 self.push_node(id, options.name, options.namespace, options.domain_id)?;
421 Ok(())
422 }
423
424 fn create_entity(&mut self, mut metadata: EntityMetadata) -> NodeResult<()> {
425 // phase-457 W5 (issue 1522) — state this subscription's registration
426 // path, because on THIS road nothing will observe it.
427 //
428 // `Executor::open_subscription` reports `in_place_capable` to
429 // `registration_observer`, which is how the C/C++ probes get theirs.
430 // The Rust probe (`record_node_metadata::<C>`) runs `register()`
431 // against this recorder and opens no executor, so that seam never
432 // fires and every Rust endpoint's row refused — leaving every consumer
433 // on the receive-region budget for a fact the declaration determines.
434 //
435 // This is the ONE `NodeRuntime` seam a Rust declaration crosses; the
436 // C/C++ adapters reach the recorder through `push_entity` and are
437 // untouched, so their observed fact still wins its own way.
438 //
439 // Not a second opinion: `declared_subscription_shape` is the same call
440 // the declarative registrar branches on, and its
441 // `in_place_capable()` is the same expression the entry point writes
442 // into its `SubscriptionRequest`. Gated by
443 // `check-declared-subscription-shape`.
444 if metadata.kind == EntityKind::Subscription && metadata.in_place_capable.is_none() {
445 let shape = metadata.declared_subscription_shape();
446 metadata.in_place_capable = Some(shape.in_place_capable());
447 // Issue 2348 -- and the BUFFERED row, which the same observation
448 // carries on the C/C++ road (`buffered_row` is "present together
449 // with `in_place_capable` or not at all"). Without it the composer
450 // fell to the backend's default and priced a Cyclone listener at
451 // its type's bound while the runtime claimed `RX_BUF`.
452 metadata.buffered_row = Some(if shape.claims_closure_buffer() {
453 crate::node_metadata::BufferedRow::Unbounded
454 } else {
455 crate::node_metadata::BufferedRow::TypedBound
456 });
457 }
458 self.push_entity(metadata)?;
459 Ok(())
460 }
461
462 fn record_callback_effect(
463 &mut self,
464 callback_id: CallbackId<'_>,
465 kind: CallbackEffectKind,
466 entity_id: EntityId<'_>,
467 ) -> NodeResult<()> {
468 self.push_callback_effect(callback_id, kind, entity_id)?;
469 Ok(())
470 }
471}
472
473/// phase-483 W3 — where a component's declarations go while its `register`
474/// runs: the live component runtime (`ExecutorSink`, which owns the
475/// component's cell) or the metadata recorder (the host probe). Both receive
476/// the executor explicitly, because the [`crate::Node`] a component holds
477/// borrows that same executor; a sink that held it too would alias it.
478#[cfg(feature = "rmw-cffi")]
479pub(crate) trait FrameSink {
480 /// Create the executor node a component asked for and return its id.
481 fn create_node(
482 &mut self,
483 executor: &mut crate::Executor<'static>,
484 id: NodeId<'_>,
485 options: NodeOptions<'_>,
486 ) -> NodeResult<nros_node::executor::NodeId>;
487
488 /// Declare one entity.
489 fn create_entity(
490 &mut self,
491 executor: &mut crate::Executor<'static>,
492 metadata: EntityMetadata,
493 ) -> NodeResult<()>;
494
495 /// Record one callback effect.
496 fn record_callback_effect(
497 &mut self,
498 executor: &mut crate::Executor<'static>,
499 callback_id: CallbackId<'_>,
500 kind: CallbackEffectKind,
501 entity_id: EntityId<'_>,
502 ) -> NodeResult<()>;
503}
504
505/// The most nodes one component registration may create. A component
506/// declares one in every shipped shape.
507#[cfg(feature = "rmw-cffi")]
508const MAX_FRAME_NODES: usize = 4;
509
510#[cfg(feature = "rmw-cffi")]
511struct FrameNode {
512 exec_id: nros_node::executor::NodeId,
513 stable: MetadataString,
514 group: Option<MetadataString>,
515}
516
517/// phase-483 W3 — one component registration in progress. Installed on the
518/// executor (`Executor::__set_component_frame`) for exactly the lifetime of
519/// the [`NodeContext`] that owns it, which is how a [`DeclarativeNode`]
520/// method on a plain [`crate::Node`] finds the sink.
521#[cfg(feature = "rmw-cffi")]
522pub(crate) struct ComponentFrame<'a> {
523 pub(crate) sink: &'a mut dyn FrameSink,
524 nodes: Vec<FrameNode, MAX_FRAME_NODES>,
525}
526
527#[cfg(feature = "rmw-cffi")]
528impl<'a> ComponentFrame<'a> {
529 pub(crate) fn new(sink: &'a mut dyn FrameSink) -> Self {
530 Self {
531 sink,
532 nodes: Vec::new(),
533 }
534 }
535
536 fn push(&mut self, exec_id: nros_node::executor::NodeId, stable: &str) -> NodeResult<()> {
537 self.nodes
538 .push(FrameNode {
539 exec_id,
540 stable: copy_str(stable)?,
541 group: None,
542 })
543 .map_err(|_| NodeDeclError::Metadata(NodeMetadataError::Capacity))
544 }
545
546 fn node(&self, exec_id: nros_node::executor::NodeId) -> NodeResult<&FrameNode> {
547 self.nodes
548 .iter()
549 .find(|n| n.exec_id == exec_id)
550 .ok_or(NodeDeclError::Metadata(NodeMetadataError::UnknownNode))
551 }
552
553 fn stable_id_of(&self, exec_id: nros_node::executor::NodeId) -> NodeResult<NodeId<'_>> {
554 Ok(NodeId::new(self.node(exec_id)?.stable.as_str()))
555 }
556
557 fn group_of(&self, exec_id: nros_node::executor::NodeId) -> Option<MetadataString> {
558 self.node(exec_id).ok().and_then(|n| n.group.clone())
559 }
560
561 fn set_group(&mut self, stable: &str, group: Option<MetadataString>) -> NodeResult<()> {
562 let node = self
563 .nodes
564 .iter_mut()
565 .find(|n| n.stable.as_str() == stable)
566 .ok_or(NodeDeclError::Metadata(NodeMetadataError::UnknownNode))?;
567 node.group = group;
568 Ok(())
569 }
570}
571
572/// The registration frame installed on `executor`, or `Runtime` when no
573/// component registration is in progress.
574///
575/// The `'static` is a lie told to the borrow checker and kept honest by
576/// [`NodeContext`]: the frame is installed when the context is built and
577/// cleared when it drops, and every caller here runs inside that window and
578/// drops the reference before returning.
579#[cfg(feature = "rmw-cffi")]
580fn frame_mut(
581 executor: &crate::Executor<'static>,
582) -> NodeResult<&'static mut ComponentFrame<'static>> {
583 let ptr = executor.__component_frame().ok_or(NodeDeclError::Runtime)?;
584 // SAFETY: installed by `NodeContext::new` from a `&mut ComponentFrame`
585 // that outlives the context, and cleared by its `Drop`; the frame is
586 // separate memory from the executor, so this does not alias the
587 // executor borrow the caller also holds.
588 Ok(unsafe { &mut *ptr.cast::<ComponentFrame<'static>>().as_ptr() })
589}
590
591/// The metadata recorder as a registration sink — the host probe's road.
592///
593/// It records every declaration and ALSO creates the node on the executor
594/// the probe opened on the `metadata` backend, so the component's `register`
595/// gets a real [`crate::Node`] exactly as it does on a board.
596#[cfg(feature = "rmw-cffi")]
597pub(crate) struct RecordSink<'r> {
598 pub(crate) recorder: &'r mut dyn NodeRuntime,
599}
600
601#[cfg(feature = "rmw-cffi")]
602impl FrameSink for RecordSink<'_> {
603 fn create_node(
604 &mut self,
605 executor: &mut crate::Executor<'static>,
606 id: NodeId<'_>,
607 options: NodeOptions<'_>,
608 ) -> NodeResult<nros_node::executor::NodeId> {
609 self.recorder.create_node(id, options)?;
610 executor
611 .node_builder(options.name)
612 .namespace(options.namespace)
613 .domain_id(options.domain_id)
614 .build()
615 .map_err(|_| NodeDeclError::Runtime)
616 }
617
618 fn create_entity(
619 &mut self,
620 _executor: &mut crate::Executor<'static>,
621 metadata: EntityMetadata,
622 ) -> NodeResult<()> {
623 self.recorder.create_entity(metadata)
624 }
625
626 fn record_callback_effect(
627 &mut self,
628 _executor: &mut crate::Executor<'static>,
629 callback_id: CallbackId<'_>,
630 kind: CallbackEffectKind,
631 entity_id: EntityId<'_>,
632 ) -> NodeResult<()> {
633 self.recorder
634 .record_callback_effect(callback_id, kind, entity_id)
635 }
636}
637
638/// The fourteen graph queries as inherent methods of a component context,
639/// each forwarded to `self.$graph()`: a method yielding
640/// `Result<&mut dyn GraphQuery, NodeError>`. One spelling for `TickCtx` and
641/// `NodeContext`, so the two surfaces cannot drift apart.
642macro_rules! graph_query_forwarders {
643 ($graph:ident) => {
644 /// Every node on the graph: `visit(name, namespace)`, stop on `false`.
645 /// What has been DISCOVERED, never blocking: empty means "not seen
646 /// yet".
647 pub fn get_node_names(
648 &mut self,
649 visit: &mut dyn FnMut(&str, &str) -> bool,
650 ) -> Result<(), crate::NodeError> {
651 self.$graph()?.get_node_names(visit)
652 }
653 /// Every node with its enclave: `visit(name, namespace, enclave)`.
654 pub fn get_node_names_with_enclaves(
655 &mut self,
656 visit: &mut dyn FnMut(&str, &str, Option<&str>) -> bool,
657 ) -> Result<(), crate::NodeError> {
658 self.$graph()?.get_node_names_with_enclaves(visit)
659 }
660 /// Every topic with its types: `visit(topic, types)` once per topic.
661 pub fn get_topic_names_and_types(
662 &mut self,
663 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
664 ) -> Result<(), crate::NodeError> {
665 self.$graph()?.get_topic_names_and_types(visit)
666 }
667 /// Every service with its types: `visit(service, types)`.
668 pub fn get_service_names_and_types(
669 &mut self,
670 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
671 ) -> Result<(), crate::NodeError> {
672 self.$graph()?.get_service_names_and_types(visit)
673 }
674 /// The graph's publisher count on `topic_name` (not this node's).
675 pub fn count_publishers(&mut self, topic_name: &str) -> Result<usize, crate::NodeError> {
676 self.$graph()?.count_publishers(topic_name)
677 }
678 /// The graph's subscription count on `topic_name`.
679 pub fn count_subscriptions(&mut self, topic_name: &str) -> Result<usize, crate::NodeError> {
680 self.$graph()?.count_subscriptions(topic_name)
681 }
682 /// The graph's client count on `service_name`.
683 pub fn count_clients(&mut self, service_name: &str) -> Result<usize, crate::NodeError> {
684 self.$graph()?.count_clients(service_name)
685 }
686 /// The graph's server count on `service_name`.
687 pub fn count_services(&mut self, service_name: &str) -> Result<usize, crate::NodeError> {
688 self.$graph()?.count_services(service_name)
689 }
690 /// The topics a node publishes: `visit(topic, types)`.
691 pub fn get_publisher_names_and_types_by_node(
692 &mut self,
693 node_name: &str,
694 node_namespace: &str,
695 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
696 ) -> Result<(), crate::NodeError> {
697 self.$graph()?
698 .get_publisher_names_and_types_by_node(node_name, node_namespace, visit)
699 }
700 /// The topics a node subscribes to: `visit(topic, types)`.
701 pub fn get_subscription_names_and_types_by_node(
702 &mut self,
703 node_name: &str,
704 node_namespace: &str,
705 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
706 ) -> Result<(), crate::NodeError> {
707 self.$graph()?.get_subscription_names_and_types_by_node(
708 node_name,
709 node_namespace,
710 visit,
711 )
712 }
713 /// The services a node serves: `visit(service, types)`.
714 pub fn get_service_names_and_types_by_node(
715 &mut self,
716 node_name: &str,
717 node_namespace: &str,
718 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
719 ) -> Result<(), crate::NodeError> {
720 self.$graph()?
721 .get_service_names_and_types_by_node(node_name, node_namespace, visit)
722 }
723 /// The services a node is a client of: `visit(service, types)`.
724 pub fn get_client_names_and_types_by_node(
725 &mut self,
726 node_name: &str,
727 node_namespace: &str,
728 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
729 ) -> Result<(), crate::NodeError> {
730 self.$graph()?
731 .get_client_names_and_types_by_node(node_name, node_namespace, visit)
732 }
733 /// The publishers on `topic_name`, one visit each.
734 pub fn get_publishers_info_by_topic(
735 &mut self,
736 topic_name: &str,
737 visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
738 ) -> Result<(), crate::NodeError> {
739 self.$graph()?
740 .get_publishers_info_by_topic(topic_name, visit)
741 }
742 /// The subscriptions on `topic_name`, one visit each.
743 pub fn get_subscriptions_info_by_topic(
744 &mut self,
745 topic_name: &str,
746 visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
747 ) -> Result<(), crate::NodeError> {
748 self.$graph()?
749 .get_subscriptions_info_by_topic(topic_name, visit)
750 }
751 };
752}
753
754/// Node declaration context — what a component's
755/// [`register`](Component::register) receives.
756///
757/// It creates REAL nodes. [`create_node`](Self::create_node)
758/// returns a [`crate::Node`], the same type `Executor::create_node` gives a
759/// standalone program, so a component's node code and a program's node code
760/// are one code. The component-only declarations are the
761/// [`DeclarativeNode`] methods on that node.
762#[cfg(feature = "rmw-cffi")]
763pub struct NodeContext<'a> {
764 component_name: &'static str,
765 executor: &'a mut crate::Executor<'static>,
766 /// Phase 264 W4a — this node instance's parameters, the COMPILE-BAKED initial
767 /// values from the launch `<param name=… value=…/>` entries (`nros::main!`
768 /// bakes them + threads them through `install_node_typed_with_params`). Empty
769 /// for the metadata-recorder / no-launch paths. A node reads them in
770 /// `register()` via [`param`](Self::param) and stashes the typed value on its
771 /// `State` (RFC-0004 §10 — baked initials; runtime reconfig is W4b).
772 params: LaunchParams<'a>,
773 // Issue 2589.
774 /// Launch parameters read before this context created its
775 /// node. `register()` usually reads them first, when the census has no
776 /// node to attribute them to, so they are held here and recorded against
777 /// the node once it exists.
778 #[cfg(feature = "metadata-mode")]
779 pending_reads: core::cell::RefCell<alloc::vec::Vec<alloc::string::String>>,
780 /// Whether this context has created its node yet.
781 #[cfg(feature = "metadata-mode")]
782 node_created: core::cell::Cell<bool>,
783}
784
785/// The launch `<param>` initials one component install carries, in either of
786/// the two shapes an entry can hand them over.
787///
788/// A Rust entry (`nros::main!`) bakes a `&[(&str, &str)]`. A C or C++ entry
789/// cannot name that type, so it passes a flat `const char*` array through the
790/// component's C-ABI install seam: `[key0, value0, key1, value1, ...]`.
791/// Reading that array in place, rather than copying it into a bounded buffer,
792/// keeps the install free of a heap and of a per-node parameter cap; the array
793/// only has to outlive the install call, because every reader runs inside it.
794// issue 2568 -- the C++ entry's Rust arm used to carry no params at all, so
795// `ctx.param()` answered the default whatever the launch file said.
796#[cfg(feature = "rmw-cffi")]
797#[derive(Clone, Copy)]
798pub(crate) enum LaunchParams<'a> {
799 /// Baked by a Rust entry.
800 Pairs(&'a [(&'a str, &'a str)]),
801 /// A validated flat C-string array (see [`LaunchParams::from_c_pairs`]).
802 Flat(&'a [*const core::ffi::c_char]),
803}
804
805#[cfg(feature = "rmw-cffi")]
806impl<'a> LaunchParams<'a> {
807 /// No launch params.
808 pub(crate) const EMPTY: Self = Self::Pairs(&[]);
809
810 /// Wrap a flat `[key, value, ...]` C-string array of `n_pairs` pairs.
811 ///
812 /// Every pointer is checked non-null and every string valid UTF-8 HERE,
813 /// once, so the readers borrow the bytes without re-checking. `None` when
814 /// a check fails, or when `kv` is null with a non-zero count.
815 ///
816 /// # Safety
817 /// When `n_pairs > 0`, `kv` must point to `2 * n_pairs` readable pointers,
818 /// each null or a NUL-terminated string, all valid for `'a`.
819 pub(crate) unsafe fn from_c_pairs(
820 kv: *const *const core::ffi::c_char,
821 n_pairs: usize,
822 ) -> Option<Self> {
823 if n_pairs == 0 {
824 return Some(Self::EMPTY);
825 }
826 if kv.is_null() {
827 return None;
828 }
829 let len = n_pairs.checked_mul(2)?;
830 // SAFETY: per this fn's contract, `kv` holds `2 * n_pairs` pointers.
831 let flat: &'a [*const core::ffi::c_char] = unsafe { core::slice::from_raw_parts(kv, len) };
832 for &p in flat {
833 if p.is_null() {
834 return None;
835 }
836 // SAFETY: non-null and NUL-terminated per the contract.
837 let bytes = unsafe { core::ffi::CStr::from_ptr(p) }.to_bytes();
838 if core::str::from_utf8(bytes).is_err() {
839 return None;
840 }
841 }
842 Some(Self::Flat(flat))
843 }
844
845 /// Every `(name, value)` pair, in launch order.
846 pub(crate) fn iter(self) -> impl Iterator<Item = (&'a str, &'a str)> {
847 let (pairs, flat): (&'a [(&'a str, &'a str)], &'a [*const core::ffi::c_char]) = match self {
848 Self::Pairs(p) => (p, &[]),
849 Self::Flat(f) => (&[], f),
850 };
851 pairs.iter().copied().chain(flat.chunks_exact(2).map(|kv| {
852 // SAFETY: `from_c_pairs` checked both pointers non-null and both
853 // strings UTF-8, and its contract keeps them alive for `'a`.
854 unsafe { (flat_str(kv[0]), flat_str(kv[1])) }
855 }))
856 }
857
858 /// The value of launch parameter `name`, if the launch set one.
859 pub(crate) fn get(self, name: &str) -> Option<&'a str> {
860 self.iter().find(|(k, _)| *k == name).map(|(_, v)| v)
861 }
862}
863
864/// # Safety
865/// `p` must be a non-null, NUL-terminated, valid UTF-8 string alive for `'a`.
866#[cfg(feature = "rmw-cffi")]
867unsafe fn flat_str<'a>(p: *const core::ffi::c_char) -> &'a str {
868 // SAFETY: per this fn's contract.
869 unsafe { core::str::from_utf8_unchecked(core::ffi::CStr::from_ptr(p).to_bytes()) }
870}
871
872#[cfg(feature = "rmw-cffi")]
873impl<'a> NodeContext<'a> {
874 /// Build a context over `executor`, installing `frame` on it until this
875 /// context drops.
876 pub(crate) fn new(
877 component_name: &'static str,
878 executor: &'a mut crate::Executor<'static>,
879 frame: &'a mut ComponentFrame<'_>,
880 ) -> Self {
881 executor.__set_component_frame(Some(core::ptr::NonNull::from(frame).cast()));
882 Self {
883 component_name,
884 executor,
885 params: LaunchParams::EMPTY,
886 #[cfg(feature = "metadata-mode")]
887 pending_reads: core::cell::RefCell::new(alloc::vec::Vec::new()),
888 #[cfg(feature = "metadata-mode")]
889 node_created: core::cell::Cell::new(false),
890 }
891 }
892
893 /// Seed this node instance's baked launch parameters (called by
894 /// `install_node_typed_with_params` before `Component::register`).
895 pub fn set_params(&mut self, params: &'a [(&'a str, &'a str)]) {
896 self.params = LaunchParams::Pairs(params);
897 }
898
899 /// Seed the launch parameters in either shape an entry hands them over.
900 pub(crate) fn set_launch_params(&mut self, params: LaunchParams<'a>) {
901 self.params = params;
902 }
903
904 /// The baked initial value of launch parameter `name`, or
905 /// `None` if the launch declared no `<param name="…"/>` for this node
906 /// instance. Read in `register()` and parse/stash on `State`.
907 pub fn param(&self, name: &str) -> Option<&'a str> {
908 // Issue 2589: the census sees the read, so a contract row for it is
909 // not called a phantom.
910 #[cfg(feature = "metadata-mode")]
911 if self.node_created.get() {
912 crate::census_hooks::on_param_read(name);
913 } else {
914 self.pending_reads.borrow_mut().push(name.into());
915 }
916 self.params.get(name)
917 }
918
919 /// Source component name.
920 pub const fn component_name(&self) -> &'static str {
921 self.component_name
922 }
923
924 /// Create a node with an explicit stable node ID.
925 ///
926 /// Generated/internal form; product code should use
927 /// [`create_node`](Self::create_node).
928 #[doc(hidden)]
929 pub fn create_node_with_id(
930 &mut self,
931 id: NodeId<'_>,
932 options: NodeOptions<'_>,
933 ) -> NodeResult<crate::Node<'_, 'static>> {
934 let frame = frame_mut(self.executor)?;
935 let exec_id = frame.sink.create_node(self.executor, id, options)?;
936 frame.push(exec_id, id.as_str())?;
937 #[cfg(feature = "metadata-mode")]
938 if !self.node_created.replace(true) {
939 for name in self.pending_reads.take() {
940 crate::census_hooks::on_param_read(&name);
941 }
942 }
943 Ok(self.executor.node_mut(exec_id))
944 }
945
946 /// Create this component's node — rclrs's `executor.create_node(options)`.
947 ///
948 /// The node's name is the launch file's when it names one, otherwise
949 /// `options.name`, which is also the component-stable node id the
950 /// declarations are keyed on.
951 ///
952 /// Takes rclrs's `impl IntoNodeOptions`, so
953 /// `context.create_node("talker")` reads as rclrs does. Unlike the
954 /// executor's, a component's options are applied as written.
955 pub fn create_node<'o>(
956 &mut self,
957 options: impl IntoNodeOptions<'o>,
958 ) -> NodeResult<crate::Node<'_, 'static>> {
959 let options = options.into_node_options();
960 self.create_node_with_id(NodeId::new(options.name), options)
961 }
962
963 /// Record optional effects for a callback not tied to a node.
964 #[doc(hidden)]
965 pub fn callback<'id>(&mut self, id: CallbackId<'id>) -> CallbackEffects<'_, 'id> {
966 CallbackEffects {
967 executor: self.executor,
968 id,
969 }
970 }
971}
972
973/// phase-572 W2 -- the graph queries at registration. The context holds the
974/// executor for the whole of `register()`, so each query is that executor's
975/// own call. At boot the graph is mostly not discovered yet: an early answer
976/// is partial, never an error.
977#[cfg(feature = "rmw-cffi")]
978impl NodeContext<'_> {
979 fn graph_query(&mut self) -> Result<&mut dyn GraphQuery, crate::NodeError> {
980 Ok(&mut *self.executor)
981 }
982
983 graph_query_forwarders!(graph_query);
984}
985
986#[cfg(feature = "rmw-cffi")]
987impl Drop for NodeContext<'_> {
988 fn drop(&mut self) {
989 self.executor.__set_component_frame(None);
990 }
991}
992
993/// The DECLARATIVE entity constructors, on the one node type.
994///
995/// A component's `register` creates its node with
996/// [`NodeContext::create_node`] and gets a [`crate::Node`], the same type a
997/// standalone program gets from `Executor::create_node`. Everything rclrs's
998/// node has is an inherent method there. The constructors here are the RTOS
999/// extension a component adds on top: each one DECLARES an entity — a stable
1000/// id, a callback NAME, effects — to the component runtime, which owns the
1001/// entity in the component's static cell and dispatches its callback by name
1002/// to [`ExecutableNode::on_callback`]. That is what framework dispatch
1003/// (RTIC/Embassy) and the metadata probe need, and what a closure cannot give
1004/// them.
1005///
1006/// Only callable inside a component's `register`: outside one there is no
1007/// component to declare into, and every method answers
1008/// [`NodeDeclError::Runtime`].
1009///
1010/// The explicit-id forms that would collide with an rclrs-named inherent
1011/// method on `Node` are spelled `declare_*` (`declare_publisher`,
1012/// `declare_subscription`, `declare_timer`, …).
1013#[cfg(feature = "rmw-cffi")]
1014pub trait DeclarativeNode {
1015 /// The component-stable id of this node. Not a user API.
1016 #[doc(hidden)]
1017 fn __node_id(&mut self) -> NodeResult<NodeId<'static>>;
1018
1019 /// Hand one entity declaration to the component runtime. Not a user API.
1020 #[doc(hidden)]
1021 fn __declare_entity(&mut self, metadata: EntityMetadata) -> NodeResult<()>;
1022
1023 /// The executor the node borrows. Not a user API.
1024 #[doc(hidden)]
1025 fn __executor_mut(&mut self) -> &mut crate::Executor<'static>;
1026
1027 /// Set the sticky callback-group label applied to every entity
1028 /// declared after this call (until changed again). The group is the
1029 /// symbolic name the node author exposes; `system.toml` maps it to a
1030 /// scheduling sched task (RFC-0015). Entities declared while no group is set
1031 /// remain unlabeled (wildcard-eligible).
1032 #[track_caller]
1033 fn callback_group(&mut self, group: &str) -> NodeResult<&mut Self>
1034 where
1035 Self: Sized,
1036 {
1037 let group = copy_str(group)?;
1038 let executor = self.__executor_mut() as *mut crate::Executor<'static>;
1039 // SAFETY: `executor` is the node's own borrow, live for this call.
1040 let frame = frame_mut(unsafe { &*executor })?;
1041 let node = self.__node_id()?;
1042 frame.set_group(node.as_str(), Some(group))?;
1043 Ok(self)
1044 }
1045
1046 /// Declare a publisher with default QoS. Stable publisher ID is required.
1047 #[track_caller]
1048 #[doc(hidden)]
1049 fn declare_publisher<'entity, M: MessageForRmw>(
1050 &mut self,
1051 id: EntityId<'entity>,
1052 topic: &str,
1053 ) -> NodeResult<NodePublisher<'entity, M>> {
1054 self.declare_publisher_with_qos::<M>(id, topic, QoSProfile::default())
1055 }
1056
1057 /// Declare a publisher using `topic` as the stable entity ID.
1058 ///
1059 /// Use the explicit [`declare_publisher`](Self::declare_publisher) form when
1060 /// a node declares more than one publisher on the same topic or needs a
1061 /// stable metadata ID that differs from the ROS topic name.
1062 #[track_caller]
1063 fn create_publisher_for_topic<'entity, M: MessageForRmw>(
1064 &mut self,
1065 topic: &'entity str,
1066 ) -> NodeResult<NodePublisher<'entity, M>> {
1067 self.create_publisher_for_topic_with_qos::<M>(topic, QoSProfile::default())
1068 }
1069
1070 /// Declare a publisher with explicit QoS, using `topic` as the stable entity ID.
1071 #[track_caller]
1072 fn create_publisher_for_topic_with_qos<'entity, M: MessageForRmw>(
1073 &mut self,
1074 topic: &'entity str,
1075 qos: QoSProfile,
1076 ) -> NodeResult<NodePublisher<'entity, M>> {
1077 self.declare_publisher_with_qos::<M>(EntityId::new(topic), topic, qos)
1078 }
1079
1080 /// Declare a publisher with explicit QoS.
1081 #[track_caller]
1082 #[doc(hidden)]
1083 fn declare_publisher_with_qos<'entity, M: MessageForRmw>(
1084 &mut self,
1085 id: EntityId<'entity>,
1086 topic: &str,
1087 qos: QoSProfile,
1088 ) -> NodeResult<NodePublisher<'entity, M>> {
1089 register_declared_type::<M>()?;
1090 let mut metadata = entity_metadata(EntityMetadataSpec {
1091 id,
1092 node_id: self.__node_id()?,
1093 kind: EntityKind::Publisher,
1094 source_name: topic,
1095 // issue 0413 — `MessageForRmw` can pull `schema::Message` into scope,
1096 // which also has a `TYPE_NAME`; disambiguate to the ROS-facing one.
1097 type_name: <M as RosMessage>::TYPE_NAME,
1098 type_hash: <M as RosMessage>::TYPE_HASH,
1099 qos,
1100 })?;
1101 metadata.source = SourceLocationMetadata::caller()?;
1102 self.__declare_entity(metadata)?;
1103 Ok(NodePublisher::new(id))
1104 }
1105
1106 /// Declare a subscription. Stable subscription and callback IDs are required.
1107 #[track_caller]
1108 #[doc(hidden)]
1109 fn declare_subscription<'entity, 'callback, M: MessageForRmw>(
1110 &mut self,
1111 id: EntityId<'entity>,
1112 callback_id: CallbackId<'callback>,
1113 topic: &str,
1114 ) -> NodeResult<NodeSubscription<'entity, M>> {
1115 self.declare_subscription_with_qos::<M>(id, callback_id, topic, QoSProfile::default())
1116 }
1117
1118 /// Declare a subscription using `callback_id` as the stable entity ID.
1119 ///
1120 /// Generated/internal form; product code should use
1121 /// [`create_subscription_for_callback_name`](Self::create_subscription_for_callback_name).
1122 #[track_caller]
1123 #[doc(hidden)]
1124 fn create_subscription_for_callback<'callback, M: MessageForRmw>(
1125 &mut self,
1126 callback_id: CallbackId<'callback>,
1127 topic: &str,
1128 ) -> NodeResult<NodeSubscription<'callback, M>> {
1129 self.create_subscription_for_callback_with_qos::<M>(
1130 callback_id,
1131 topic,
1132 QoSProfile::default(),
1133 )
1134 }
1135
1136 /// Declare a subscription using `callback_name` as the source callback
1137 /// name and synthesized entity ID.
1138 #[track_caller]
1139 fn create_subscription_for_callback_name<'callback, M: MessageForRmw>(
1140 &mut self,
1141 callback_name: &'callback str,
1142 topic: &str,
1143 ) -> NodeResult<NodeSubscription<'callback, M>> {
1144 self.create_subscription_for_callback::<M>(CallbackId::new(callback_name), topic)
1145 }
1146
1147 /// Phase 250 (Wave 2b) — declare a subscription with E2E message-integrity
1148 /// validation enabled (the declarative `.safety()` opt-in). Identical to
1149 /// [`create_subscription_for_callback_name`](Self::create_subscription_for_callback_name)
1150 /// but flags the entity so the runtime registers it via
1151 /// `create_generic_subscription_with_integrity`; the callback then reads
1152 /// [`CallbackCtx::integrity`](CallbackCtx::integrity) alongside the message.
1153 /// The config-driven `[safety]` axis (Wave 4 codegen) emits this call; it is
1154 /// also usable by hand. Ungated — when `safety-e2e` is off the flag is simply
1155 /// ignored and the subscription registers as a basic one.
1156 #[track_caller]
1157 fn create_subscription_for_callback_name_with_safety<'callback, M: MessageForRmw>(
1158 &mut self,
1159 callback_name: &'callback str,
1160 topic: &str,
1161 ) -> NodeResult<NodeSubscription<'callback, M>> {
1162 let callback_id = CallbackId::new(callback_name);
1163 let id = EntityId::new(callback_id.as_str());
1164 register_declared_type::<M>()?;
1165 let mut metadata = entity_metadata(EntityMetadataSpec {
1166 id,
1167 node_id: self.__node_id()?,
1168 kind: EntityKind::Subscription,
1169 source_name: topic,
1170 // issue 0413 — `MessageForRmw` can pull `schema::Message` into scope,
1171 // which also has a `TYPE_NAME`; disambiguate to the ROS-facing one.
1172 type_name: <M as RosMessage>::TYPE_NAME,
1173 type_hash: <M as RosMessage>::TYPE_HASH,
1174 qos: QoSProfile::default(),
1175 })?;
1176 metadata.callback_id = Some(copy_str(callback_id.as_str())?);
1177 metadata.callback_source = SourceLocationMetadata::caller()?;
1178 metadata.source = metadata.callback_source.clone();
1179 metadata.safety = true;
1180 // Issue 2208 -- the backend's `rx_buffer_hint`, from the type.
1181 metadata.rx_bound = <M as RosMessage>::MAX_SERIALIZED_BOUND;
1182 self.__declare_entity(metadata)?;
1183 Ok(NodeSubscription::new(id))
1184 }
1185
1186 /// Declare a subscription whose callback can read the message's metadata
1187 /// through [`CallbackCtx::message_info`](CallbackCtx::message_info): its
1188 /// timestamps, publisher GID and sequence number. Otherwise identical to
1189 /// [`create_subscription_for_callback_name`](Self::create_subscription_for_callback_name).
1190 ///
1191 /// Opt-in because it has a cost: the metadata is staged beside the
1192 /// payload, so this subscription cannot dispatch in place and claims a
1193 /// receive region (the build sizes it so). A plain declaration pays
1194 /// nothing.
1195 #[track_caller]
1196 fn create_subscription_for_callback_name_with_message_info<'callback, M: MessageForRmw>(
1197 &mut self,
1198 callback_name: &'callback str,
1199 topic: &str,
1200 ) -> NodeResult<NodeSubscription<'callback, M>> {
1201 let callback_id = CallbackId::new(callback_name);
1202 let id = EntityId::new(callback_id.as_str());
1203 register_declared_type::<M>()?;
1204 let mut metadata = entity_metadata(EntityMetadataSpec {
1205 id,
1206 node_id: self.__node_id()?,
1207 kind: EntityKind::Subscription,
1208 source_name: topic,
1209 // issue 0413 — `MessageForRmw` can pull `schema::Message` into scope,
1210 // which also has a `TYPE_NAME`; disambiguate to the ROS-facing one.
1211 type_name: <M as RosMessage>::TYPE_NAME,
1212 type_hash: <M as RosMessage>::TYPE_HASH,
1213 qos: QoSProfile::default(),
1214 })?;
1215 metadata.callback_id = Some(copy_str(callback_id.as_str())?);
1216 metadata.callback_source = SourceLocationMetadata::caller()?;
1217 metadata.source = metadata.callback_source.clone();
1218 metadata.message_info = true;
1219 // Issue 2208 -- the backend's `rx_buffer_hint`, from the type.
1220 metadata.rx_bound = <M as RosMessage>::MAX_SERIALIZED_BOUND;
1221 self.__declare_entity(metadata)?;
1222 Ok(NodeSubscription::new(id))
1223 }
1224
1225 /// Declare a subscription with explicit QoS, using `callback_id` as the stable entity ID.
1226 #[track_caller]
1227 #[doc(hidden)]
1228 fn create_subscription_for_callback_with_qos<'callback, M: MessageForRmw>(
1229 &mut self,
1230 callback_id: CallbackId<'callback>,
1231 topic: &str,
1232 qos: QoSProfile,
1233 ) -> NodeResult<NodeSubscription<'callback, M>> {
1234 self.declare_subscription_with_qos::<M>(
1235 EntityId::new(callback_id.as_str()),
1236 callback_id,
1237 topic,
1238 qos,
1239 )
1240 }
1241
1242 /// Declare a subscription using `topic` as both the stable entity ID and callback ID.
1243 #[track_caller]
1244 fn create_subscription_for_topic<'entity, M: MessageForRmw>(
1245 &mut self,
1246 topic: &'entity str,
1247 ) -> NodeResult<NodeSubscription<'entity, M>> {
1248 self.create_subscription_for_topic_with_qos::<M>(topic, QoSProfile::default())
1249 }
1250
1251 /// Declare a subscription with explicit QoS, using `topic` as both IDs.
1252 #[track_caller]
1253 fn create_subscription_for_topic_with_qos<'entity, M: MessageForRmw>(
1254 &mut self,
1255 topic: &'entity str,
1256 qos: QoSProfile,
1257 ) -> NodeResult<NodeSubscription<'entity, M>> {
1258 self.declare_subscription_with_qos::<M>(
1259 EntityId::new(topic),
1260 CallbackId::new(topic),
1261 topic,
1262 qos,
1263 )
1264 }
1265
1266 /// Declare a subscription with explicit QoS.
1267 #[track_caller]
1268 #[doc(hidden)]
1269 fn declare_subscription_with_qos<'entity, 'callback, M: MessageForRmw>(
1270 &mut self,
1271 id: EntityId<'entity>,
1272 callback_id: CallbackId<'callback>,
1273 topic: &str,
1274 qos: QoSProfile,
1275 ) -> NodeResult<NodeSubscription<'entity, M>> {
1276 // Phase 380 W4 — a subscription whose receive buffer provably cannot
1277 // hold its own message type fails the BUILD, not the field.
1278 //
1279 // Without this the sample is received, ACKed, and then dropped, and
1280 // `report_dropped_take` can only say "raise the knob" because nothing
1281 // knows what value would have worked (issues 0757, 0776). The number is
1282 // known at compile time for any BOUNDED type, so the check costs
1283 // nothing at runtime and cannot be forgotten at a call site.
1284 //
1285 // `bound_fits`, not `buffer_fits`: an UNBOUNDED type passes, because
1286 // there is nothing to prove and no finite buffer fits a `String` — the
1287 // other predicate would refuse the most common message in ROS. Both
1288 // encodings are checked and the larger taken; the peer chooses the
1289 // encoding at runtime, so sizing from XCDR1 alone is a trap.
1290 // Only where `MessageForRmw` guarantees a schema. The other arm accepts a
1291 // hand-written `RosMessage` with none (see `rmw_type_registry`), and
1292 // requiring one there would make codegen mandatory for a user's own
1293 // message type — too large a price for a build assertion. Backends that
1294 // register type descriptors already demand the schema, so this is free
1295 // there and absent elsewhere; `size::bound_fits` stays public so a
1296 // caller can assert it explicitly.
1297 const {
1298 assert!(
1299 subscription_buffer_checked::<M>(),
1300 "this message type's maximum serialized size exceeds \
1301 NROS_EXECUTOR_SUBSCRIPTION_BUFFER_BYTES — every sample would be received, \
1302 ACKed and then DROPPED. Raise the knob to at least the type's \
1303 bound (`<M as nros_serdes::schema::Message>::MAX_SERIALIZED_SIZE_XCDR2`)."
1304 )
1305 }
1306 register_declared_type::<M>()?;
1307 let mut metadata = entity_metadata(EntityMetadataSpec {
1308 id,
1309 node_id: self.__node_id()?,
1310 kind: EntityKind::Subscription,
1311 source_name: topic,
1312 // issue 0413 — `MessageForRmw` can pull `schema::Message` into scope,
1313 // which also has a `TYPE_NAME`; disambiguate to the ROS-facing one.
1314 type_name: <M as RosMessage>::TYPE_NAME,
1315 type_hash: <M as RosMessage>::TYPE_HASH,
1316 qos,
1317 })?;
1318 metadata.callback_id = Some(copy_str(callback_id.as_str())?);
1319 metadata.callback_source = SourceLocationMetadata::caller()?;
1320 metadata.source = metadata.callback_source.clone();
1321 // Issue 2208 -- the backend's `rx_buffer_hint`, from the type. The
1322 // runtime registers this subscription type-erased, so this is the
1323 // last place `M` is known.
1324 metadata.rx_bound = <M as RosMessage>::MAX_SERIALIZED_BOUND;
1325 self.__declare_entity(metadata)?;
1326 Ok(NodeSubscription::new(id))
1327 }
1328
1329 /// Declare a subscription whose stable entity and callback IDs are
1330 /// both synthesized from the topic literal, returning a
1331 /// [`SubscriptionTag`] the Node author stores on `Self::State` and
1332 /// matches against the `Callback<'_>` delivered to
1333 /// [`ExecutableNode::on_callback`].
1334 ///
1335 /// Use this on the Phase 216.A Deferred Node path where the Node
1336 /// author does not need to invent a separate stable entity ID — the
1337 /// topic literal becomes both the entity ID and the callback ID,
1338 /// and the returned tag preserves that identifier for compile-time
1339 /// `state.sub_chatter == cb` matches in `on_callback`.
1340 #[track_caller]
1341 fn create_subscription_static<M: MessageForRmw>(
1342 &mut self,
1343 topic: &'static str,
1344 ) -> NodeResult<SubscriptionTag> {
1345 let id = EntityId::new(topic);
1346 let callback_id = CallbackId::new(topic);
1347 register_declared_type::<M>()?;
1348 let mut metadata = entity_metadata(EntityMetadataSpec {
1349 id,
1350 node_id: self.__node_id()?,
1351 kind: EntityKind::Subscription,
1352 source_name: topic,
1353 // issue 0413 — `MessageForRmw` can pull `schema::Message` into scope,
1354 // which also has a `TYPE_NAME`; disambiguate to the ROS-facing one.
1355 type_name: <M as RosMessage>::TYPE_NAME,
1356 type_hash: <M as RosMessage>::TYPE_HASH,
1357 qos: QoSProfile::default(),
1358 })?;
1359 metadata.callback_id = Some(copy_str(callback_id.as_str())?);
1360 metadata.callback_source = SourceLocationMetadata::caller()?;
1361 metadata.source = metadata.callback_source.clone();
1362 // Issue 2208 -- the backend's `rx_buffer_hint`, from the type.
1363 metadata.rx_bound = <M as RosMessage>::MAX_SERIALIZED_BOUND;
1364 self.__declare_entity(metadata)?;
1365 Ok(SubscriptionTag::new(topic))
1366 }
1367
1368 /// Declare a timer. Stable timer and callback IDs are required.
1369 #[track_caller]
1370 #[doc(hidden)]
1371 fn declare_timer<'entity, 'callback>(
1372 &mut self,
1373 id: EntityId<'entity>,
1374 callback_id: CallbackId<'callback>,
1375 period: TimerDuration,
1376 ) -> NodeResult<NodeTimer<'entity>> {
1377 // phase-430 W4 — the wall spelling IS the `Steady` clock, so it is the
1378 // same declaration with the axis defaulted rather than a second body.
1379 // `#[track_caller]` on both hops keeps `SourceLocationMetadata::caller`
1380 // pointing at the component, not at this line.
1381 self.declare_timer_on_clock(id, callback_id, period, TimerClockSource::Steady)
1382 }
1383
1384 /// Declare a timer using `callback_id` as the stable timer entity ID.
1385 #[track_caller]
1386 #[doc(hidden)]
1387 fn create_timer_for_callback<'callback>(
1388 &mut self,
1389 callback_id: CallbackId<'callback>,
1390 period: TimerDuration,
1391 ) -> NodeResult<NodeTimer<'callback>> {
1392 self.declare_timer(EntityId::new(callback_id.as_str()), callback_id, period)
1393 }
1394
1395 /// Declare a timer using `callback_name` as the source callback name and
1396 /// synthesized entity ID.
1397 #[track_caller]
1398 fn create_timer_for_callback_name<'callback>(
1399 &mut self,
1400 callback_name: &'callback str,
1401 period: TimerDuration,
1402 ) -> NodeResult<NodeTimer<'callback>> {
1403 self.create_timer_for_callback(CallbackId::new(callback_name), period)
1404 }
1405
1406 /// Declare a timer on a chosen CLOCK — phase-430 W4, the declarative
1407 /// spelling of [`Executor::register_timer_on_clock`](crate::Executor::register_timer_on_clock)
1408 /// and the counterpart of C++'s `create_timer(clock, period, cb)`.
1409 ///
1410 /// [`create_timer`](Self::create_timer) is this with
1411 /// [`TimerClockSource::Steady`], which is the WALL case and is what every
1412 /// timer declared before W4 gets: the runtime registers it exactly as it
1413 /// always did. A [`TimerClockSource::Ros`] timer instead follows `/clock` —
1414 /// it stops while the simulator is paused and tracks a bag's replay rate —
1415 /// and with no `/clock` source installed it reads system time, the same
1416 /// fallback `rclcpp::Clock` has.
1417 #[track_caller]
1418 #[doc(hidden)]
1419 fn declare_timer_on_clock<'entity, 'callback>(
1420 &mut self,
1421 id: EntityId<'entity>,
1422 callback_id: CallbackId<'callback>,
1423 period: TimerDuration,
1424 clock: TimerClockSource,
1425 ) -> NodeResult<NodeTimer<'entity>> {
1426 self.declare_timer_with_autostart(id, callback_id, period, clock, true)
1427 }
1428
1429 /// The ONE timer declaration — issue 2038. Every other timer verb on this
1430 /// trait is this with `autostart = true` (and, for the wall spellings,
1431 /// [`TimerClockSource::Steady`]).
1432 ///
1433 /// `autostart == false` declares the timer STOPPED: the runtime registers
1434 /// it cancelled (rcl's `rcl_timer_init2(..., autostart = false)`, the same
1435 /// executor call `Node::create_timer_with_info` makes), so it does not fire
1436 /// until it is reset.
1437 #[track_caller]
1438 #[doc(hidden)]
1439 fn declare_timer_with_autostart<'entity, 'callback>(
1440 &mut self,
1441 id: EntityId<'entity>,
1442 callback_id: CallbackId<'callback>,
1443 period: TimerDuration,
1444 clock: TimerClockSource,
1445 autostart: bool,
1446 ) -> NodeResult<NodeTimer<'entity>> {
1447 let mut metadata = entity_metadata(EntityMetadataSpec {
1448 id,
1449 node_id: self.__node_id()?,
1450 kind: EntityKind::Timer,
1451 source_name: "",
1452 type_name: "",
1453 type_hash: "",
1454 qos: QoSProfile::default(),
1455 })?;
1456 metadata.callback_id = Some(copy_str(callback_id.as_str())?);
1457 metadata.callback_source = SourceLocationMetadata::caller()?;
1458 metadata.source = metadata.callback_source.clone();
1459 metadata.period_ms = Some(period.as_millis());
1460 metadata.period_us = Some(period.as_micros());
1461 metadata.timer_clock = clock;
1462 metadata.timer_autostart = autostart;
1463 self.__declare_entity(metadata)?;
1464 Ok(NodeTimer::new(id))
1465 }
1466
1467 /// [`declare_timer_on_clock`](Self::declare_timer_on_clock) using
1468 /// `callback_id` as the stable timer entity ID.
1469 #[track_caller]
1470 #[doc(hidden)]
1471 fn create_timer_for_callback_on_clock<'callback>(
1472 &mut self,
1473 callback_id: CallbackId<'callback>,
1474 period: TimerDuration,
1475 clock: TimerClockSource,
1476 ) -> NodeResult<NodeTimer<'callback>> {
1477 self.declare_timer_on_clock(
1478 EntityId::new(callback_id.as_str()),
1479 callback_id,
1480 period,
1481 clock,
1482 )
1483 }
1484
1485 /// [`declare_timer_on_clock`](Self::declare_timer_on_clock) using
1486 /// `callback_name` as the source callback name and synthesized entity ID —
1487 /// the spelling a `nros::main!` component writes:
1488 ///
1489 /// ```ignore
1490 /// node.create_timer_for_callback_name_on_clock(
1491 /// "on_tick",
1492 /// TimerDuration::from_millis(100),
1493 /// TimerClockSource::Ros,
1494 /// )?;
1495 /// ```
1496 #[track_caller]
1497 fn create_timer_for_callback_name_on_clock<'callback>(
1498 &mut self,
1499 callback_name: &'callback str,
1500 period: TimerDuration,
1501 clock: TimerClockSource,
1502 ) -> NodeResult<NodeTimer<'callback>> {
1503 self.create_timer_for_callback_on_clock(CallbackId::new(callback_name), period, clock)
1504 }
1505
1506 /// [`create_timer_for_callback_name_on_clock`](Self::create_timer_for_callback_name_on_clock)
1507 /// with rcl's `autostart` flag — issue 2038, the declarative spelling of
1508 /// [`Node::create_timer_with_info`](crate::Node::create_timer_with_info)'s
1509 /// flag and of C++'s `create_wall_timer(period, cb, group, autostart)`.
1510 ///
1511 /// `autostart == false` declares the timer STOPPED: it is registered
1512 /// cancelled and does not fire until it is reset. Like every declared timer,
1513 /// its callback can read the activation's call info with
1514 /// [`CallbackCtx::timer_info`].
1515 ///
1516 /// ```ignore
1517 /// node.create_timer_for_callback_name_with_autostart(
1518 /// "on_tick",
1519 /// TimerDuration::from_millis(100),
1520 /// TimerClockSource::Steady,
1521 /// false,
1522 /// )?;
1523 /// ```
1524 #[track_caller]
1525 fn create_timer_for_callback_name_with_autostart<'callback>(
1526 &mut self,
1527 callback_name: &'callback str,
1528 period: TimerDuration,
1529 clock: TimerClockSource,
1530 autostart: bool,
1531 ) -> NodeResult<NodeTimer<'callback>> {
1532 self.declare_timer_with_autostart(
1533 EntityId::new(callback_name),
1534 CallbackId::new(callback_name),
1535 period,
1536 clock,
1537 autostart,
1538 )
1539 }
1540
1541 /// Declare a service server. Stable service and callback IDs are required.
1542 #[track_caller]
1543 #[doc(hidden)]
1544 fn create_service_server<
1545 'entity,
1546 'callback,
1547 S: RosService<
1548 Request: nros_node::rmw_type_registry::MessageForRmw,
1549 Reply: nros_node::rmw_type_registry::MessageForRmw,
1550 >,
1551 >(
1552 &mut self,
1553 id: EntityId<'entity>,
1554 callback_id: CallbackId<'callback>,
1555 service_name: &str,
1556 ) -> NodeResult<NodeServiceServer<'entity, S>> {
1557 register_declared_service::<S>()?;
1558 let mut metadata = entity_metadata(EntityMetadataSpec {
1559 id,
1560 node_id: self.__node_id()?,
1561 kind: EntityKind::ServiceServer,
1562 source_name: service_name,
1563 type_name: S::SERVICE_NAME,
1564 type_hash: S::SERVICE_HASH,
1565 qos: QoSProfile::default(),
1566 })?;
1567 metadata.callback_id = Some(copy_str(callback_id.as_str())?);
1568 metadata.callback_source = SourceLocationMetadata::caller()?;
1569 metadata.source = metadata.callback_source.clone();
1570 self.__declare_entity(metadata)?;
1571 Ok(NodeServiceServer::new(id))
1572 }
1573
1574 /// Declare a service server using `name` as both the stable entity ID
1575 /// and callback ID.
1576 #[track_caller]
1577 fn create_service_server_for_name<
1578 'entity,
1579 S: RosService<
1580 Request: nros_node::rmw_type_registry::MessageForRmw,
1581 Reply: nros_node::rmw_type_registry::MessageForRmw,
1582 >,
1583 >(
1584 &mut self,
1585 name: &'entity str,
1586 ) -> NodeResult<NodeServiceServer<'entity, S>> {
1587 self.create_service_server::<S>(EntityId::new(name), CallbackId::new(name), name)
1588 }
1589
1590 /// Declare a service server using `name` as the stable entity ID and
1591 /// `callback_name` as the source callback name.
1592 #[track_caller]
1593 fn create_service_server_for_name_with_callback<
1594 'entity,
1595 S: RosService<
1596 Request: nros_node::rmw_type_registry::MessageForRmw,
1597 Reply: nros_node::rmw_type_registry::MessageForRmw,
1598 >,
1599 >(
1600 &mut self,
1601 name: &'entity str,
1602 callback_name: &str,
1603 ) -> NodeResult<NodeServiceServer<'entity, S>> {
1604 self.create_service_server::<S>(EntityId::new(name), CallbackId::new(callback_name), name)
1605 }
1606
1607 /// Declare a service server whose stable entity and callback IDs are
1608 /// both synthesized from the service-name literal, returning a
1609 /// [`ServiceTag`] the Node author stores on `Self::State` and matches
1610 /// against the `Callback<'_>` delivered to
1611 /// [`ExecutableNode::on_callback`].
1612 ///
1613 /// Tag-only registration is restricted to the SERVER side: clients
1614 /// need a USABLE handle (`NodeServiceClient`) to issue requests, so
1615 /// use the existing
1616 /// [`create_service_client_for_name`](Self::create_service_client_for_name) builder
1617 /// for the client side.
1618 #[track_caller]
1619 fn create_service_static<
1620 S: RosService<
1621 Request: nros_node::rmw_type_registry::MessageForRmw,
1622 Reply: nros_node::rmw_type_registry::MessageForRmw,
1623 >,
1624 >(
1625 &mut self,
1626 name: &'static str,
1627 ) -> NodeResult<ServiceTag> {
1628 self.create_service_server_for_name::<S>(name)?;
1629 Ok(ServiceTag::new(name))
1630 }
1631
1632 /// Declare a service client. Stable service client ID is required.
1633 #[track_caller]
1634 #[doc(hidden)]
1635 fn create_service_client<
1636 'entity,
1637 S: RosService<
1638 Request: nros_node::rmw_type_registry::MessageForRmw,
1639 Reply: nros_node::rmw_type_registry::MessageForRmw,
1640 >,
1641 >(
1642 &mut self,
1643 id: EntityId<'entity>,
1644 service_name: &str,
1645 ) -> NodeResult<NodeServiceClient<'entity, S>> {
1646 register_declared_service::<S>()?;
1647 let mut metadata = entity_metadata(EntityMetadataSpec {
1648 id,
1649 node_id: self.__node_id()?,
1650 kind: EntityKind::ServiceClient,
1651 source_name: service_name,
1652 type_name: S::SERVICE_NAME,
1653 type_hash: S::SERVICE_HASH,
1654 qos: QoSProfile::default(),
1655 })?;
1656 metadata.source = SourceLocationMetadata::caller()?;
1657 self.__declare_entity(metadata)?;
1658 Ok(NodeServiceClient::new(id))
1659 }
1660
1661 /// Declare a service client using `name` as the stable entity ID.
1662 #[track_caller]
1663 fn create_service_client_for_name<
1664 'entity,
1665 S: RosService<
1666 Request: nros_node::rmw_type_registry::MessageForRmw,
1667 Reply: nros_node::rmw_type_registry::MessageForRmw,
1668 >,
1669 >(
1670 &mut self,
1671 name: &'entity str,
1672 ) -> NodeResult<NodeServiceClient<'entity, S>> {
1673 self.create_service_client::<S>(EntityId::new(name), name)
1674 }
1675
1676 /// Declare an action server. Stable action and callback IDs are required.
1677 #[track_caller]
1678 #[doc(hidden)]
1679 fn declare_action_server<
1680 'entity,
1681 'callback,
1682 A: RosAction<
1683 Goal: nros_node::rmw_type_registry::MessageForRmw,
1684 Result: nros_node::rmw_type_registry::MessageForRmw,
1685 Feedback: nros_node::rmw_type_registry::MessageForRmw,
1686 SendGoalRequest: nros_node::rmw_type_registry::MessageForRmw,
1687 SendGoalResponse: nros_node::rmw_type_registry::MessageForRmw,
1688 GetResultRequest: nros_node::rmw_type_registry::MessageForRmw,
1689 GetResultResponse: nros_node::rmw_type_registry::MessageForRmw,
1690 FeedbackMessage: nros_node::rmw_type_registry::MessageForRmw,
1691 >,
1692 >(
1693 &mut self,
1694 id: EntityId<'entity>,
1695 callback_id: CallbackId<'callback>,
1696 action_name: &str,
1697 ) -> NodeResult<NodeActionServer<'entity, A>> {
1698 self.create_action_server_with_callbacks::<A>(
1699 id,
1700 callback_id,
1701 callback_id,
1702 callback_id,
1703 action_name,
1704 )
1705 }
1706
1707 /// Declare an action server with distinct goal/cancel/accepted callbacks.
1708 #[track_caller]
1709 #[doc(hidden)]
1710 fn create_action_server_with_callbacks<
1711 'entity,
1712 'goal,
1713 'cancel,
1714 'accepted,
1715 A: RosAction<
1716 Goal: nros_node::rmw_type_registry::MessageForRmw,
1717 Result: nros_node::rmw_type_registry::MessageForRmw,
1718 Feedback: nros_node::rmw_type_registry::MessageForRmw,
1719 SendGoalRequest: nros_node::rmw_type_registry::MessageForRmw,
1720 SendGoalResponse: nros_node::rmw_type_registry::MessageForRmw,
1721 GetResultRequest: nros_node::rmw_type_registry::MessageForRmw,
1722 GetResultResponse: nros_node::rmw_type_registry::MessageForRmw,
1723 FeedbackMessage: nros_node::rmw_type_registry::MessageForRmw,
1724 >,
1725 >(
1726 &mut self,
1727 id: EntityId<'entity>,
1728 goal_callback_id: CallbackId<'goal>,
1729 cancel_callback_id: CallbackId<'cancel>,
1730 accepted_callback_id: CallbackId<'accepted>,
1731 action_name: &str,
1732 ) -> NodeResult<NodeActionServer<'entity, A>> {
1733 register_declared_action::<A>()?;
1734 let mut metadata = entity_metadata(EntityMetadataSpec {
1735 id,
1736 node_id: self.__node_id()?,
1737 kind: EntityKind::ActionServer,
1738 source_name: action_name,
1739 type_name: A::ACTION_NAME,
1740 type_hash: A::ACTION_HASH,
1741 qos: QoSProfile::default(),
1742 })?;
1743 metadata.action_hashes = Some(nros_node::ActionEndpointHashes::of::<A>());
1744 metadata.callback_id = Some(copy_str(goal_callback_id.as_str())?);
1745 metadata.callback_source = SourceLocationMetadata::caller()?;
1746 metadata.action_cancel_callback_id = Some(copy_str(cancel_callback_id.as_str())?);
1747 metadata.action_cancel_source = metadata.callback_source.clone();
1748 metadata.action_accepted_callback_id = Some(copy_str(accepted_callback_id.as_str())?);
1749 metadata.action_accepted_source = metadata.callback_source.clone();
1750 metadata.source = metadata.callback_source.clone();
1751 self.__declare_entity(metadata)?;
1752 Ok(NodeActionServer::new(id))
1753 }
1754
1755 /// Declare an action server using `name` as the stable entity ID and
1756 /// default goal/cancel/accepted callback ID.
1757 #[track_caller]
1758 fn create_action_server_for_name<
1759 'entity,
1760 A: RosAction<
1761 Goal: nros_node::rmw_type_registry::MessageForRmw,
1762 Result: nros_node::rmw_type_registry::MessageForRmw,
1763 Feedback: nros_node::rmw_type_registry::MessageForRmw,
1764 SendGoalRequest: nros_node::rmw_type_registry::MessageForRmw,
1765 SendGoalResponse: nros_node::rmw_type_registry::MessageForRmw,
1766 GetResultRequest: nros_node::rmw_type_registry::MessageForRmw,
1767 GetResultResponse: nros_node::rmw_type_registry::MessageForRmw,
1768 FeedbackMessage: nros_node::rmw_type_registry::MessageForRmw,
1769 >,
1770 >(
1771 &mut self,
1772 name: &'entity str,
1773 ) -> NodeResult<NodeActionServer<'entity, A>> {
1774 self.declare_action_server::<A>(EntityId::new(name), CallbackId::new(name), name)
1775 }
1776
1777 /// Declare an action server using `name` as the stable entity ID and
1778 /// explicit source callback names for goal, cancel, and accepted events.
1779 #[track_caller]
1780 fn create_action_server_for_name_with_callbacks<
1781 'entity,
1782 A: RosAction<
1783 Goal: nros_node::rmw_type_registry::MessageForRmw,
1784 Result: nros_node::rmw_type_registry::MessageForRmw,
1785 Feedback: nros_node::rmw_type_registry::MessageForRmw,
1786 SendGoalRequest: nros_node::rmw_type_registry::MessageForRmw,
1787 SendGoalResponse: nros_node::rmw_type_registry::MessageForRmw,
1788 GetResultRequest: nros_node::rmw_type_registry::MessageForRmw,
1789 GetResultResponse: nros_node::rmw_type_registry::MessageForRmw,
1790 FeedbackMessage: nros_node::rmw_type_registry::MessageForRmw,
1791 >,
1792 >(
1793 &mut self,
1794 name: &'entity str,
1795 goal_callback_name: &str,
1796 cancel_callback_name: &str,
1797 accepted_callback_name: &str,
1798 ) -> NodeResult<NodeActionServer<'entity, A>> {
1799 self.create_action_server_with_callbacks::<A>(
1800 EntityId::new(name),
1801 CallbackId::new(goal_callback_name),
1802 CallbackId::new(cancel_callback_name),
1803 CallbackId::new(accepted_callback_name),
1804 name,
1805 )
1806 }
1807
1808 /// Declare an action server whose stable entity and callback IDs are
1809 /// both synthesized from the action-name literal, returning an
1810 /// [`ActionTag`] the Node author stores on `Self::State` and matches
1811 /// against the `Callback<'_>` delivered to
1812 /// [`ExecutableNode::on_callback`].
1813 ///
1814 /// The synthesized callback ID is shared by the goal / cancel /
1815 /// accepted callbacks (matching the default behavior of
1816 /// [`declare_action_server`](Self::declare_action_server)).
1817 ///
1818 /// Tag-only registration is restricted to the SERVER side: clients
1819 /// need a USABLE handle (`NodeActionClient`) to dispatch goals, so
1820 /// use the existing
1821 /// [`create_action_client_for_name`](Self::create_action_client_for_name) builder
1822 /// for the client side.
1823 #[track_caller]
1824 fn create_action_static<
1825 A: RosAction<
1826 Goal: nros_node::rmw_type_registry::MessageForRmw,
1827 Result: nros_node::rmw_type_registry::MessageForRmw,
1828 Feedback: nros_node::rmw_type_registry::MessageForRmw,
1829 SendGoalRequest: nros_node::rmw_type_registry::MessageForRmw,
1830 SendGoalResponse: nros_node::rmw_type_registry::MessageForRmw,
1831 GetResultRequest: nros_node::rmw_type_registry::MessageForRmw,
1832 GetResultResponse: nros_node::rmw_type_registry::MessageForRmw,
1833 FeedbackMessage: nros_node::rmw_type_registry::MessageForRmw,
1834 >,
1835 >(
1836 &mut self,
1837 name: &'static str,
1838 ) -> NodeResult<ActionTag> {
1839 self.create_action_server_for_name::<A>(name)?;
1840 Ok(ActionTag::new(name))
1841 }
1842
1843 /// Declare an action client. Stable action client ID is required.
1844 #[track_caller]
1845 #[doc(hidden)]
1846 fn declare_action_client<
1847 'entity,
1848 A: RosAction<
1849 Goal: nros_node::rmw_type_registry::MessageForRmw,
1850 Result: nros_node::rmw_type_registry::MessageForRmw,
1851 Feedback: nros_node::rmw_type_registry::MessageForRmw,
1852 SendGoalRequest: nros_node::rmw_type_registry::MessageForRmw,
1853 SendGoalResponse: nros_node::rmw_type_registry::MessageForRmw,
1854 GetResultRequest: nros_node::rmw_type_registry::MessageForRmw,
1855 GetResultResponse: nros_node::rmw_type_registry::MessageForRmw,
1856 FeedbackMessage: nros_node::rmw_type_registry::MessageForRmw,
1857 >,
1858 >(
1859 &mut self,
1860 id: EntityId<'entity>,
1861 action_name: &str,
1862 ) -> NodeResult<NodeActionClient<'entity, A>> {
1863 register_declared_action::<A>()?;
1864 let mut metadata = entity_metadata(EntityMetadataSpec {
1865 id,
1866 node_id: self.__node_id()?,
1867 kind: EntityKind::ActionClient,
1868 source_name: action_name,
1869 type_name: A::ACTION_NAME,
1870 type_hash: A::ACTION_HASH,
1871 qos: QoSProfile::default(),
1872 })?;
1873 metadata.action_hashes = Some(nros_node::ActionEndpointHashes::of::<A>());
1874 metadata.source = SourceLocationMetadata::caller()?;
1875 self.__declare_entity(metadata)?;
1876 Ok(NodeActionClient::new(id))
1877 }
1878
1879 /// Declare an action client using `name` as the stable entity ID.
1880 #[track_caller]
1881 fn create_action_client_for_name<
1882 'entity,
1883 A: RosAction<
1884 Goal: nros_node::rmw_type_registry::MessageForRmw,
1885 Result: nros_node::rmw_type_registry::MessageForRmw,
1886 Feedback: nros_node::rmw_type_registry::MessageForRmw,
1887 SendGoalRequest: nros_node::rmw_type_registry::MessageForRmw,
1888 SendGoalResponse: nros_node::rmw_type_registry::MessageForRmw,
1889 GetResultRequest: nros_node::rmw_type_registry::MessageForRmw,
1890 GetResultResponse: nros_node::rmw_type_registry::MessageForRmw,
1891 FeedbackMessage: nros_node::rmw_type_registry::MessageForRmw,
1892 >,
1893 >(
1894 &mut self,
1895 name: &'entity str,
1896 ) -> NodeResult<NodeActionClient<'entity, A>> {
1897 self.declare_action_client::<A>(EntityId::new(name), name)
1898 }
1899
1900 /// Declare an action client that delivers the goal RESULT + FEEDBACK to
1901 /// named callbacks (Phase 212.M-F.23). `name` is the stable entity ID. The
1902 /// executor auto-drives accept → feedback stream → result during spin and
1903 /// dispatches `ExecutableNode::on_callback` with `result_callback_name`
1904 /// (payload = result CDR) on completion, and with `feedback_callback_name`
1905 /// (payload = feedback CDR) per feedback message. Read either with
1906 /// `CallbackCtx::message::<A::Result>()` / `::<A::Feedback>()`. Without
1907 /// these the client can only `send_goal`; result + feedback are dropped.
1908 ///
1909 /// (Layout note: the action-client variant reuses the server-side
1910 /// `action_accepted_callback_id` metadata slot for the feedback callback —
1911 /// that field is unused on a client, so no new schema field is needed.)
1912 #[track_caller]
1913 fn create_action_client_with_callbacks_for_name<
1914 'entity,
1915 A: RosAction<
1916 Goal: nros_node::rmw_type_registry::MessageForRmw,
1917 Result: nros_node::rmw_type_registry::MessageForRmw,
1918 Feedback: nros_node::rmw_type_registry::MessageForRmw,
1919 SendGoalRequest: nros_node::rmw_type_registry::MessageForRmw,
1920 SendGoalResponse: nros_node::rmw_type_registry::MessageForRmw,
1921 GetResultRequest: nros_node::rmw_type_registry::MessageForRmw,
1922 GetResultResponse: nros_node::rmw_type_registry::MessageForRmw,
1923 FeedbackMessage: nros_node::rmw_type_registry::MessageForRmw,
1924 >,
1925 >(
1926 &mut self,
1927 name: &'entity str,
1928 result_callback_name: &str,
1929 feedback_callback_name: &str,
1930 ) -> NodeResult<NodeActionClient<'entity, A>> {
1931 register_declared_action::<A>()?;
1932 let mut metadata = entity_metadata(EntityMetadataSpec {
1933 id: EntityId::new(name),
1934 node_id: self.__node_id()?,
1935 kind: EntityKind::ActionClient,
1936 source_name: name,
1937 type_name: A::ACTION_NAME,
1938 type_hash: A::ACTION_HASH,
1939 qos: QoSProfile::default(),
1940 })?;
1941 metadata.action_hashes = Some(nros_node::ActionEndpointHashes::of::<A>());
1942 metadata.callback_id = Some(copy_str(result_callback_name)?);
1943 metadata.action_accepted_callback_id = Some(copy_str(feedback_callback_name)?);
1944 metadata.callback_source = SourceLocationMetadata::caller()?;
1945 metadata.source = metadata.callback_source.clone();
1946 self.__declare_entity(metadata)?;
1947 Ok(NodeActionClient::new(EntityId::new(name)))
1948 }
1949
1950 /// Declare a parameter. Stable parameter ID is required.
1951 ///
1952 /// phase-515 R10: spelled `declare_parameter` until `Node` gained rclrs's
1953 /// inherent `declare_parameter::<T>(name)`, which an inherent method wins
1954 /// over a trait one with.
1955 #[track_caller]
1956 #[doc(hidden)]
1957 fn declare_parameter_with_id<'entity>(
1958 &mut self,
1959 id: EntityId<'entity>,
1960 name: &str,
1961 parameter_type: ParameterType,
1962 ) -> NodeResult<NodeParameter<'entity>> {
1963 self.declare_parameter_with_default(id, name, ParameterDefault::for_type(parameter_type)?)
1964 }
1965
1966 /// Declare a parameter with a concrete source default.
1967 #[track_caller]
1968 #[doc(hidden)]
1969 fn declare_parameter_with_default<'entity>(
1970 &mut self,
1971 id: EntityId<'entity>,
1972 name: &str,
1973 default: ParameterDefault,
1974 ) -> NodeResult<NodeParameter<'entity>> {
1975 let mut metadata = entity_metadata(EntityMetadataSpec {
1976 id,
1977 node_id: self.__node_id()?,
1978 kind: EntityKind::Parameter,
1979 source_name: name,
1980 type_name: "",
1981 type_hash: "",
1982 qos: QoSProfile::default(),
1983 })?;
1984 metadata.parameter_type = Some(default.parameter_type());
1985 metadata.parameter_default = Some(default);
1986 metadata.source = SourceLocationMetadata::caller()?;
1987 self.__declare_entity(metadata)?;
1988 Ok(NodeParameter::new(id))
1989 }
1990
1991 /// Declare a parameter using `name` as the generated stable entity ID.
1992 #[track_caller]
1993 fn declare_parameter_for_name<'entity>(
1994 &mut self,
1995 name: &'entity str,
1996 parameter_type: ParameterType,
1997 ) -> NodeResult<NodeParameter<'entity>> {
1998 self.declare_parameter_with_id(EntityId::new(name), name, parameter_type)
1999 }
2000
2001 /// Declare a parameter with a concrete source default, using `name` as
2002 /// the generated stable entity ID.
2003 #[track_caller]
2004 fn declare_parameter_for_name_with_default<'entity>(
2005 &mut self,
2006 name: &'entity str,
2007 default: ParameterDefault,
2008 ) -> NodeResult<NodeParameter<'entity>> {
2009 self.declare_parameter_with_default(EntityId::new(name), name, default)
2010 }
2011
2012 /// Record optional effects for a callback.
2013 #[doc(hidden)]
2014 fn callback<'callback>(&mut self, id: CallbackId<'callback>) -> CallbackEffects<'_, 'callback> {
2015 CallbackEffects {
2016 executor: self.__executor_mut(),
2017 id,
2018 }
2019 }
2020
2021 /// Record optional effects for a named callback without exposing
2022 /// `CallbackId` at the declaration site.
2023 fn callback_for_name<'callback>(
2024 &mut self,
2025 name: &'callback str,
2026 ) -> CallbackEffects<'_, 'callback> {
2027 self.callback(CallbackId::new(name))
2028 }
2029}
2030
2031#[cfg(feature = "rmw-cffi")]
2032impl DeclarativeNode for crate::Node<'_, 'static> {
2033 fn __node_id(&mut self) -> NodeResult<NodeId<'static>> {
2034 let exec_id = self.id();
2035 frame_mut(self.__executor())?.stable_id_of(exec_id)
2036 }
2037
2038 fn __declare_entity(&mut self, mut metadata: EntityMetadata) -> NodeResult<()> {
2039 let exec_id = self.id();
2040 let executor = self.__executor();
2041 let frame = frame_mut(executor)?;
2042 if metadata.callback_group.is_none() {
2043 metadata.callback_group = frame.group_of(exec_id);
2044 }
2045 frame.sink.create_entity(executor, metadata)
2046 }
2047
2048 fn __executor_mut(&mut self) -> &mut crate::Executor<'static> {
2049 self.__executor()
2050 }
2051}
2052
2053/// Builder for optional callback effect metadata.
2054#[cfg(feature = "rmw-cffi")]
2055pub struct CallbackEffects<'ctx, 'id> {
2056 executor: &'ctx mut crate::Executor<'static>,
2057 id: CallbackId<'id>,
2058}
2059
2060#[cfg(feature = "rmw-cffi")]
2061impl<'ctx, 'id> CallbackEffects<'ctx, 'id> {
2062 /// Record that callback reads from an entity.
2063 #[doc(hidden)]
2064 pub fn reads(self, entity_id: EntityId<'_>) -> NodeResult<Self> {
2065 let frame = frame_mut(self.executor)?;
2066 frame.sink.record_callback_effect(
2067 self.executor,
2068 self.id,
2069 CallbackEffectKind::Reads,
2070 entity_id,
2071 )?;
2072 Ok(self)
2073 }
2074
2075 /// Record that callback reads from a declared entity handle.
2076 pub fn reads_entity(self, entity: &impl DeclaredEntity) -> NodeResult<Self> {
2077 self.reads(entity.entity_id())
2078 }
2079
2080 /// Record that callback publishes via an entity.
2081 #[doc(hidden)]
2082 pub fn publishes(self, entity_id: EntityId<'_>) -> NodeResult<Self> {
2083 let frame = frame_mut(self.executor)?;
2084 frame.sink.record_callback_effect(
2085 self.executor,
2086 self.id,
2087 CallbackEffectKind::Publishes,
2088 entity_id,
2089 )?;
2090 Ok(self)
2091 }
2092
2093 /// Record that callback publishes via a declared entity handle.
2094 pub fn publishes_entity(self, entity: &impl DeclaredEntity) -> NodeResult<Self> {
2095 self.publishes(entity.entity_id())
2096 }
2097
2098 /// Record that callback writes to an entity or parameter.
2099 #[doc(hidden)]
2100 pub fn writes(self, entity_id: EntityId<'_>) -> NodeResult<Self> {
2101 let frame = frame_mut(self.executor)?;
2102 frame.sink.record_callback_effect(
2103 self.executor,
2104 self.id,
2105 CallbackEffectKind::Writes,
2106 entity_id,
2107 )?;
2108 Ok(self)
2109 }
2110
2111 /// Record that callback writes to a declared entity handle.
2112 pub fn writes_entity(self, entity: &impl DeclaredEntity) -> NodeResult<Self> {
2113 self.writes(entity.entity_id())
2114 }
2115}
2116
2117/// A declared source-level entity handle that can be referenced by callback effects.
2118#[doc(hidden)]
2119pub trait DeclaredEntity {
2120 /// Stable entity ID for metadata and generated runtime lookup.
2121 fn entity_id(&self) -> EntityId<'_>;
2122}
2123
2124macro_rules! component_handle {
2125 ($name:ident $(, $type_param:ident)?) => {
2126 /// Source-level component entity handle.
2127 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2128 pub struct $name<'id $(, $type_param)?> {
2129 id: EntityId<'id>,
2130 _marker: PhantomData<($($type_param,)?)>,
2131 }
2132
2133 impl<'id $(, $type_param)?> $name<'id $(, $type_param)?> {
2134 const fn new(id: EntityId<'id>) -> Self {
2135 Self {
2136 id,
2137 _marker: PhantomData,
2138 }
2139 }
2140
2141 /// Stable entity ID.
2142 #[doc(hidden)]
2143 pub const fn id(&self) -> EntityId<'id> {
2144 self.id
2145 }
2146 }
2147
2148 impl<'id $(, $type_param)?> DeclaredEntity for $name<'id $(, $type_param)?> {
2149 fn entity_id(&self) -> EntityId<'_> {
2150 self.id
2151 }
2152 }
2153 };
2154}
2155
2156component_handle!(NodePublisher, M);
2157component_handle!(NodeSubscription, M);
2158component_handle!(NodeServiceServer, S);
2159component_handle!(NodeServiceClient, S);
2160component_handle!(NodeActionServer, A);
2161component_handle!(NodeActionClient, A);
2162component_handle!(NodeTimer);
2163component_handle!(NodeParameter);
2164
2165// ============================================================================
2166// Phase 172 W.5.1 — executable component layer (callback bodies)
2167// ============================================================================
2168//
2169// The declarative `Node::register` above stays the planning/metadata SSOT.
2170// This layer binds *runnable* bodies: the generated runtime builds the
2171// component `State` once, then routes each fired callback to `on_callback` with
2172// a `CallbackCtx` that exposes the triggering payload + an immediate publish
2173// path. Publishers are self-contained transport handles
2174// (`EmbeddedRawPublisher::publish_raw(&self)`), so a body publishes immediately
2175// mid-spin with no executor re-entrancy and no deferred queue (causality
2176// preserved). Shared state across a component's callbacks is `&mut State`
2177// behind the generated runtime's `'static` storage — `no_std`, no `alloc`.
2178
2179/// Resolves a component publisher by its stable [`EntityId`] for the
2180/// callback-body publish path (W.5.1).
2181///
2182/// The generated runtime implements this over its owned `'static` publishers;
2183/// metadata/discovery mode never constructs a [`CallbackCtx`], so it need not
2184/// implement this.
2185pub trait PublisherResolver {
2186 /// Publish raw CDR bytes through the publisher with this stable entity id.
2187 /// `Err(NodeDeclError::Runtime)` if no such publisher is registered or the
2188 /// transport rejects the write.
2189 fn publish_raw(&self, entity_id: &str, data: &[u8]) -> NodeResult<()>;
2190
2191 /// Issue 2075 — request that the declared timer `entity_id` be reset
2192 /// (started, or restarted on a fresh period) or cancelled. The component
2193 /// runtime records it and applies it at the component's next tick, where
2194 /// the executor is free. The default answers
2195 /// [`NodeDeclError::UnknownTimer`]: a resolver with no timer table controls
2196 /// nothing.
2197 #[doc(hidden)]
2198 fn request_timer(&self, entity_id: &str, op: TimerOp) -> NodeResult<()> {
2199 let _ = (entity_id, op);
2200 Err(NodeDeclError::UnknownTimer)
2201 }
2202}
2203
2204/// What [`CallbackCtx::reset_timer`] / [`CallbackCtx::cancel_timer`]
2205/// (and their [`TickCtx`] twins) ask of a declared timer.
2206#[doc(hidden)]
2207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2208pub enum TimerOp {
2209 /// rcl's `rcl_timer_reset`: clear the cancelled state and start a fresh
2210 /// period. Starts a timer declared with `autostart = false`.
2211 Reset,
2212 /// rcl's `rcl_timer_cancel`: the timer stops firing until reset.
2213 Cancel,
2214}
2215
2216/// Where a service / action-result callback body writes its reply (W.5.3): the
2217/// generated trampoline lends a `buf`; the body fills it via
2218/// [`CallbackCtx::reply`] and the trampoline reads `*written` back out.
2219struct ReplySink<'a> {
2220 buf: &'a mut [u8],
2221 written: &'a mut usize,
2222}
2223
2224/// Where an action goal / cancel-decision callback writes its accept/reject
2225/// (W.5.3): the generated trampoline lends the out-slot, the body fills it via
2226/// [`CallbackCtx::set_goal_response`] / [`set_cancel_response`](CallbackCtx::set_cancel_response),
2227/// and the trampoline returns it. Decisions need no executor — unlike feedback /
2228/// result, which do (see the action-execution note in Phase 172 W.5.3).
2229enum DecisionSink<'a> {
2230 Goal(&'a mut GoalResponse),
2231 Cancel(&'a mut CancelResponse),
2232}
2233
2234/// Context handed to an executable component callback body (W.5.1).
2235///
2236/// Carries the triggering payload (raw CDR — empty for timers) plus the
2237/// publisher resolver, so a body can read its message and publish immediately.
2238/// Service / action-result callbacks additionally carry a `ReplySink` the body
2239/// fills via [`reply`](Self::reply); action goal / cancel callbacks carry a
2240/// `DecisionSink` the body fills via
2241/// [`set_goal_response`](Self::set_goal_response) /
2242/// [`set_cancel_response`](Self::set_cancel_response) (W.5.3).
2243/// issue 0461 — bytes of `unique_identifier_msgs/UUID` that precede the goal
2244/// fields in a SendGoal request. A fixed `uint8[16]` array: no length prefix.
2245const GOAL_UUID_LEN: usize = 16;
2246
2247pub struct CallbackCtx<'a> {
2248 payload: &'a [u8],
2249 publishers: &'a dyn PublisherResolver,
2250 reply: Option<ReplySink<'a>>,
2251 decision: Option<DecisionSink<'a>>,
2252 /// Phase 250 (Wave 2) — E2E message-integrity status for a subscription that
2253 /// opted in via `.safety()`; `None` for every other callback (timers,
2254 /// services, non-safety subscriptions). Read with
2255 /// [`integrity`](Self::integrity). Gated with the capability so it is
2256 /// zero-cost when `safety-e2e` is off.
2257 #[cfg(feature = "safety-e2e")]
2258 integrity: Option<&'a crate::IntegrityStatus>,
2259 /// Phase 264 W4c — the executor's volatile parameter store, threaded by the dispatch
2260 /// site from the component cell (`None` until `[param_services]` registers the store).
2261 /// Read with [`parameter`](Self::parameter). Gated so it is zero-cost when
2262 /// `param-services` is off.
2263 #[cfg(feature = "param-store")]
2264 params: Option<&'a crate::ParameterServer<'a>>,
2265 /// phase-426 W3 — WHICH node's parameters `parameter()` reads.
2266 ///
2267 /// One set of six parameter services is registered per node and the store
2268 /// is keyed the same way, so a context that carries the store without the
2269 /// key can only ever answer for one node — which is how every component on
2270 /// a multi-node executor came to read the primary's values.
2271 #[cfg(feature = "param-store")]
2272 param_node: nros_params::NodeKey,
2273 /// Issue 2038 — the activation's call info, for a TIMER callback the
2274 /// runtime dispatched (`None` for every other callback). Read with
2275 /// [`timer_info`](Self::timer_info).
2276 timer_info: Option<crate::TimerCallInfo>,
2277 /// The metadata of the message being dispatched, for a subscription
2278 /// declared with
2279 /// [`create_subscription_for_callback_name_with_message_info`](DeclarativeNode::create_subscription_for_callback_name_with_message_info)
2280 /// (`None` for every other callback). Read with
2281 /// [`message_info`](Self::message_info). A reference, so a context that
2282 /// carries none costs one pointer.
2283 message_info: Option<&'a crate::MessageInfo>,
2284}
2285
2286impl<'a> CallbackCtx<'a> {
2287 /// Build a callback context with no reply sink (timer / subscription).
2288 /// `payload` is the entity's raw CDR (empty slice for timers).
2289 pub fn new(payload: &'a [u8], publishers: &'a dyn PublisherResolver) -> Self {
2290 Self {
2291 payload,
2292 publishers,
2293 reply: None,
2294 decision: None,
2295 #[cfg(feature = "safety-e2e")]
2296 integrity: None,
2297 #[cfg(feature = "param-store")]
2298 params: None,
2299 // phase-426 W3 — the store is keyed by node and this context does
2300 // not know which one until the dispatch site says so
2301 // (`set_param_server`). PRIMARY until then, which is the executor's
2302 // first node and what a single-node image means.
2303 #[cfg(feature = "param-store")]
2304 param_node: nros_params::NodeKey::PRIMARY,
2305 timer_info: None,
2306 message_info: None,
2307 }
2308 }
2309
2310 /// Build a subscription context carrying E2E
2311 /// [`IntegrityStatus`](crate::IntegrityStatus) (the declarative `.safety()`
2312 /// path). The body reads both the message ([`message`](Self::message)) and
2313 /// the status ([`integrity`](Self::integrity)) in one callback, mirroring the
2314 /// imperative `FnMut(&M, &IntegrityStatus)` shape.
2315 #[cfg(feature = "safety-e2e")]
2316 pub fn new_with_integrity(
2317 payload: &'a [u8],
2318 publishers: &'a dyn PublisherResolver,
2319 integrity: &'a crate::IntegrityStatus,
2320 ) -> Self {
2321 Self {
2322 payload,
2323 publishers,
2324 reply: None,
2325 decision: None,
2326 integrity: Some(integrity),
2327 #[cfg(feature = "param-store")]
2328 params: None,
2329 // phase-426 W3 — the store is keyed by node and this context does
2330 // not know which one until the dispatch site says so
2331 // (`set_param_server`). PRIMARY until then, which is the executor's
2332 // first node and what a single-node image means.
2333 #[cfg(feature = "param-store")]
2334 param_node: nros_params::NodeKey::PRIMARY,
2335 timer_info: None,
2336 message_info: None,
2337 }
2338 }
2339
2340 /// Build a callback context with a reply sink (service / action-result;
2341 /// W.5.3). The body fills `reply_buf` via [`reply`](Self::reply); the
2342 /// generated trampoline reads `*reply_written` back as the response length.
2343 pub fn with_reply(
2344 payload: &'a [u8],
2345 publishers: &'a dyn PublisherResolver,
2346 reply_buf: &'a mut [u8],
2347 reply_written: &'a mut usize,
2348 ) -> Self {
2349 *reply_written = 0;
2350 Self {
2351 payload,
2352 publishers,
2353 reply: Some(ReplySink {
2354 buf: reply_buf,
2355 written: reply_written,
2356 }),
2357 decision: None,
2358 #[cfg(feature = "safety-e2e")]
2359 integrity: None,
2360 #[cfg(feature = "param-store")]
2361 params: None,
2362 // phase-426 W3 — the store is keyed by node and this context does
2363 // not know which one until the dispatch site says so
2364 // (`set_param_server`). PRIMARY until then, which is the executor's
2365 // first node and what a single-node image means.
2366 #[cfg(feature = "param-store")]
2367 param_node: nros_params::NodeKey::PRIMARY,
2368 timer_info: None,
2369 message_info: None,
2370 }
2371 }
2372
2373 /// Build a context for an action **goal** callback (W.5.3): the body decides
2374 /// accept/reject via [`set_goal_response`](Self::set_goal_response); the
2375 /// generated trampoline returns `*out`. `payload` is the goal CDR.
2376 pub fn with_goal_decision(
2377 payload: &'a [u8],
2378 publishers: &'a dyn PublisherResolver,
2379 out: &'a mut GoalResponse,
2380 ) -> Self {
2381 Self {
2382 payload,
2383 publishers,
2384 reply: None,
2385 decision: Some(DecisionSink::Goal(out)),
2386 #[cfg(feature = "safety-e2e")]
2387 integrity: None,
2388 #[cfg(feature = "param-store")]
2389 params: None,
2390 // phase-426 W3 — the store is keyed by node and this context does
2391 // not know which one until the dispatch site says so
2392 // (`set_param_server`). PRIMARY until then, which is the executor's
2393 // first node and what a single-node image means.
2394 #[cfg(feature = "param-store")]
2395 param_node: nros_params::NodeKey::PRIMARY,
2396 timer_info: None,
2397 message_info: None,
2398 }
2399 }
2400
2401 /// Build a context for an action **cancel** callback (W.5.3): the body decides
2402 /// accept/reject via [`set_cancel_response`](Self::set_cancel_response).
2403 pub fn with_cancel_decision(
2404 payload: &'a [u8],
2405 publishers: &'a dyn PublisherResolver,
2406 out: &'a mut CancelResponse,
2407 ) -> Self {
2408 Self {
2409 payload,
2410 publishers,
2411 reply: None,
2412 decision: Some(DecisionSink::Cancel(out)),
2413 #[cfg(feature = "safety-e2e")]
2414 integrity: None,
2415 #[cfg(feature = "param-store")]
2416 params: None,
2417 // phase-426 W3 — the store is keyed by node and this context does
2418 // not know which one until the dispatch site says so
2419 // (`set_param_server`). PRIMARY until then, which is the executor's
2420 // first node and what a single-node image means.
2421 #[cfg(feature = "param-store")]
2422 param_node: nros_params::NodeKey::PRIMARY,
2423 timer_info: None,
2424 message_info: None,
2425 }
2426 }
2427
2428 /// Thread the executor's volatile parameter store into this context.
2429 /// The dispatch site calls this after construction (the store reaches the callback via
2430 /// the component cell, not the constructor args). No-op-equivalent when `None`.
2431 #[cfg(feature = "param-store")]
2432 pub fn set_param_server(
2433 &mut self,
2434 params: Option<&'a crate::ParameterServer<'a>>,
2435 node: nros_params::NodeKey,
2436 ) {
2437 self.params = params;
2438 self.param_node = node;
2439 }
2440
2441 /// Read this node's parameter `name` as `T`, or `None` if the
2442 /// parameter is undeclared, the wrong type, or `[param_services]` is not enabled.
2443 /// Returns the **live** value — the launch-baked initial, or whatever a `ros2 param
2444 /// set` last wrote (values are volatile, lost at the next boot).
2445 #[cfg(feature = "param-store")]
2446 pub fn parameter<T: crate::ParameterVariant>(&self, name: &str) -> Option<T> {
2447 self.params
2448 // phase-426 W3 — the store is keyed by node, and the key is the
2449 // component's OWN node, threaded in beside the store by the
2450 // dispatch site. Reading PRIMARY here (which is what this did
2451 // until W3) makes the second node on an executor read its
2452 // sibling's values.
2453 .and_then(|server| server.get(self.param_node, name))
2454 .and_then(T::from_parameter_value)
2455 }
2456
2457 /// Set the action goal-callback's accept/reject decision (W.5.3). `Err` when
2458 /// the callback is not a goal decision.
2459 pub fn set_goal_response(&mut self, response: GoalResponse) -> NodeResult<()> {
2460 match &mut self.decision {
2461 Some(DecisionSink::Goal(slot)) => {
2462 **slot = response;
2463 Ok(())
2464 }
2465 _ => Err(NodeDeclError::Runtime),
2466 }
2467 }
2468
2469 /// Set the action cancel-callback's accept/reject decision (W.5.3). `Err` when
2470 /// the callback is not a cancel decision.
2471 ///
2472 /// `CancelResponse` here is the PER-GOAL decision
2473 /// (`Reject` / `Accept`), the twin of [`GoalResponse`] and the same two
2474 /// values C's `rclc_cancel_response_t` and C++'s `nros::CancelResponse`
2475 /// carry. It used to be the `action_msgs/srv/CancelGoal` RPC return code
2476 /// (now `nros_core::CancelResponseCode`), so answering "cancel this goal"
2477 /// was spelled `CancelResponse::Ok` — a whole-request status code used to
2478 /// decide one goal.
2479 pub fn set_cancel_response(&mut self, response: CancelResponse) -> NodeResult<()> {
2480 match &mut self.decision {
2481 Some(DecisionSink::Cancel(slot)) => {
2482 **slot = response;
2483 Ok(())
2484 }
2485 _ => Err(NodeDeclError::Runtime),
2486 }
2487 }
2488
2489 /// Write the service / action reply as raw CDR bytes (W.5.3). `Err` when the
2490 /// callback has no reply sink (timer / subscription) or the reply exceeds the
2491 /// lent buffer.
2492 pub fn reply_raw(&mut self, data: &[u8]) -> NodeResult<()> {
2493 let sink = self.reply.as_mut().ok_or(NodeDeclError::Runtime)?;
2494 if data.len() > sink.buf.len() {
2495 return Err(NodeDeclError::Runtime);
2496 }
2497 sink.buf[..data.len()].copy_from_slice(data);
2498 *sink.written = data.len();
2499 Ok(())
2500 }
2501
2502 /// Serialize `msg` and write it as the service / action reply (W.5.3).
2503 pub fn reply<M: RosMessage, const N: usize>(&mut self, msg: &M) -> NodeResult<()> {
2504 let mut buf = [0u8; N];
2505 let mut writer =
2506 crate::CdrWriter::new_with_header(&mut buf).map_err(|_| NodeDeclError::Runtime)?;
2507 msg.serialize(&mut writer)
2508 .map_err(|_| NodeDeclError::Runtime)?;
2509 let len = writer.position();
2510 self.reply_raw(&buf[..len])
2511 }
2512
2513 /// Raw CDR payload of the triggering message / request. Empty for timers.
2514 pub fn payload(&self) -> &[u8] {
2515 self.payload
2516 }
2517
2518 /// The call info of the timer activation being dispatched:
2519 /// when it was due (`expected_call_time`) and when the executor ran it
2520 /// (`actual_call_time`), in nanoseconds on the timer's clock. `Some` only
2521 /// in a declared TIMER's callback; `None` for subscriptions, services and
2522 /// actions. The same two numbers `Node::create_timer_with_info` and C++'s
2523 /// `rclcpp::TimerInfo` receive — one producer, the executor's dispatcher.
2524 pub fn timer_info(&self) -> Option<&crate::TimerCallInfo> {
2525 self.timer_info.as_ref()
2526 }
2527
2528 /// The metadata of the message being dispatched: its source and
2529 /// received timestamps, its publisher GID and its sequence number (the
2530 /// stock ROS `MessageInfo`). `Some` only in the callback of a subscription
2531 /// declared with
2532 /// [`create_subscription_for_callback_name_with_message_info`](DeclarativeNode::create_subscription_for_callback_name_with_message_info);
2533 /// `None` for every other callback, and from a backend that reports no
2534 /// metadata. A field the backend does not fill reads its default, as
2535 /// `MessageInfo` documents.
2536 ///
2537 /// Asking costs the subscription its in-place dispatch: the metadata has
2538 /// to be staged beside the payload, so the subscription claims a receive
2539 /// region where a plain one would not. That is why it is opt-in.
2540 pub fn message_info(&self) -> Option<&crate::MessageInfo> {
2541 self.message_info
2542 }
2543
2544 /// Attach the dispatched message's metadata. The runtime's
2545 /// subscription dispatch calls this after construction, as it does
2546 /// `set_timer_info`.
2547 #[doc(hidden)]
2548 pub fn set_message_info(&mut self, info: &'a crate::MessageInfo) {
2549 self.message_info = Some(info);
2550 }
2551
2552 /// Attach a timer activation's call info. The runtime's
2553 /// timer dispatch calls this after construction, as it does
2554 /// `set_param_server`.
2555 #[doc(hidden)]
2556 pub fn set_timer_info(&mut self, info: crate::TimerCallInfo) {
2557 self.timer_info = Some(info);
2558 }
2559
2560 /// Reset the declared timer `timer`: rclcpp's
2561 /// `TimerBase::reset()`. Starts a timer declared with `autostart = false`
2562 /// ([`DeclarativeNode::create_timer_for_callback_name_with_autostart`]),
2563 /// and restarts a running one on a fresh period.
2564 ///
2565 /// The request is applied at this component's next tick, in the same
2566 /// spin, once the callbacks of the pass have run: a callback does not hold
2567 /// the executor. `timer` is the timer's entity id, which for the
2568 /// `..._for_callback_name` verbs is the callback name. Answers
2569 /// [`NodeDeclError::UnknownTimer`] when this component has no controllable
2570 /// timer by that id (see [`EntityBounds::timers`]).
2571 ///
2572 /// ```ignore
2573 /// ctx.reset_timer(nros::EntityId::new("on_tick"))?;
2574 /// ```
2575 pub fn reset_timer(&self, timer: EntityId<'_>) -> NodeResult<()> {
2576 self.publishers
2577 .request_timer(timer.as_str(), TimerOp::Reset)
2578 }
2579
2580 /// Cancel the declared timer `timer`: rclcpp's
2581 /// `TimerBase::cancel()`. It stops firing until [`reset_timer`](Self::reset_timer).
2582 /// Applied at the next tick, like `reset_timer`.
2583 pub fn cancel_timer(&self, timer: EntityId<'_>) -> NodeResult<()> {
2584 self.publishers
2585 .request_timer(timer.as_str(), TimerOp::Cancel)
2586 }
2587
2588 /// E2E message-integrity status (CRC + sequence gap/dup)
2589 /// for this dispatch. `Some` only when the firing subscription opted in via
2590 /// `.safety()`; `None` for timers, services, and non-safety subscriptions.
2591 /// Read it alongside [`message`](Self::message) — the status describes the
2592 /// message you just received.
2593 #[cfg(feature = "safety-e2e")]
2594 pub fn integrity(&self) -> Option<&crate::IntegrityStatus> {
2595 self.integrity
2596 }
2597
2598 /// Deserialize the triggering payload as `M` (subscription / service-request
2599 /// bodies). `Err` if the payload is malformed for `M`.
2600 pub fn message<M: RosMessage>(&self) -> NodeResult<M> {
2601 let mut reader =
2602 crate::CdrReader::new_with_header(self.payload).map_err(|_| NodeDeclError::Runtime)?;
2603 // issue 0461 — an action GOAL callback's payload is the whole SendGoal
2604 // request, `[CDR header][goal_id uuid][goal fields]`. Without this skip
2605 // the reader is sitting on the uuid and a goal type decodes its first
2606 // four bytes — the goal counter, so every goal looked like `order = 1`.
2607 //
2608 // The goal_id reaches the callback by other means (the server's
2609 // `for_each_active_goal_for_name`), so it is framing here, not data.
2610 // Same shape as the typed `try_accept_goal` path, which has always
2611 // skipped it and has always decoded correctly.
2612 if matches!(self.decision, Some(DecisionSink::Goal(_))) {
2613 for _ in 0..GOAL_UUID_LEN {
2614 let _ = reader.read_u8();
2615 }
2616 }
2617 M::deserialize(&mut reader).map_err(|_| NodeDeclError::Runtime)
2618 }
2619
2620 /// Publish raw CDR bytes through the named publisher entity (immediate).
2621 #[doc(hidden)]
2622 pub fn publish_raw(&self, publisher: EntityId<'_>, data: &[u8]) -> NodeResult<()> {
2623 self.publishers.publish_raw(publisher.as_str(), data)
2624 }
2625
2626 /// Serialize `msg` into an `N`-byte stack buffer and publish it (immediate).
2627 /// `N` must be ≥ the CDR-encoded size of `msg`; the generated runtime picks
2628 /// it from the message type.
2629 #[doc(hidden)]
2630 pub fn publish<M: RosMessage, const N: usize>(
2631 &self,
2632 publisher: EntityId<'_>,
2633 msg: &M,
2634 ) -> NodeResult<()> {
2635 let mut buf = [0u8; N];
2636 let mut writer =
2637 crate::CdrWriter::new_with_header(&mut buf).map_err(|_| NodeDeclError::Runtime)?;
2638 msg.serialize(&mut writer)
2639 .map_err(|_| NodeDeclError::Runtime)?;
2640 let len = writer.position();
2641 self.publish_raw(publisher, &buf[..len])
2642 }
2643
2644 /// Serialize `msg` and publish through the entity synthesized from `topic`.
2645 ///
2646 /// This pairs with
2647 /// [`DeclarativeNode::create_publisher_for_topic`], allowing simple callback
2648 /// bodies to use the ROS topic literal instead of restating an unrelated
2649 /// stable entity ID.
2650 pub fn publish_to_topic<M: RosMessage, const N: usize>(
2651 &self,
2652 topic: &str,
2653 msg: &M,
2654 ) -> NodeResult<()> {
2655 self.publish::<M, N>(EntityId::new(topic), msg)
2656 }
2657}
2658
2659/// The executable counterpart of [`Component`] (W.5.1).
2660///
2661/// `register` (declarative) stays the planning SSOT; this binds runnable
2662/// bodies. The generated runtime builds [`State`](ExecutableNode::State) once via
2663/// [`init`](ExecutableNode::init), then routes every fired callback to
2664/// [`on_callback`](ExecutableNode::on_callback). Trait-dispatch (no boxed `dyn`, no
2665/// `alloc`) keeps it `no_std`.
2666/// Executor-backed action operations a [`TickCtx`] drives (W.5.6).
2667///
2668/// Action result/feedback need `&mut Executor` (`complete_goal_raw` /
2669/// `publish_feedback_raw`), which a mid-spin *callback* can't hold (the executor
2670/// is borrowed) — so they run from [`ExecutableNode::tick`], between spins.
2671/// The generated runtime implements this over the real executor + the action
2672/// servers' handles (resolved by stable action entity id); the component never
2673/// sees the executor directly. Kept as a trait so [`TickCtx`] stays `no_std` +
2674/// free of the `rmw-cffi`-gated `Executor` type.
2675pub trait ActionExecutor {
2676 /// Complete the goal `goal_id` on action `action_entity` with raw CDR result.
2677 fn complete_goal_raw(
2678 &mut self,
2679 action_entity: &str,
2680 goal_id: &GoalUuid,
2681 status: GoalStatusCode,
2682 result: &[u8],
2683 ) -> NodeResult<()>;
2684
2685 /// Publish raw CDR feedback for `goal_id` on action `action_entity`.
2686 fn publish_feedback_raw(
2687 &mut self,
2688 action_entity: &str,
2689 goal_id: &GoalUuid,
2690 feedback: &[u8],
2691 ) -> NodeResult<()>;
2692
2693 /// Visit every goal on `action_entity` that has been accepted but not yet
2694 /// completed, with its id + current status. The execution seam: a `tick` body
2695 /// has no other way to learn an accepted goal's id (the goal-decision callback
2696 /// doesn't surface it), so it iterates here to drive feedback / completion.
2697 fn for_each_active_goal(
2698 &self,
2699 action_entity: &str,
2700 visit: &mut dyn FnMut(&GoalUuid, GoalStatusCode),
2701 );
2702}
2703
2704/// Executor-backed CLIENT operations a [`TickCtx`] drives.
2705///
2706/// Service-client `call` + action-client `send_goal` need `&mut Executor`
2707/// (the W.5.6 client handles live on the executor), which a mid-spin
2708/// callback can't hold. They run from [`ExecutableNode::tick`], between
2709/// spins. The generated runtime impls this over the real executor + the
2710/// service/action client handles (resolved by stable client entity id); the
2711/// component never sees the executor directly. Kept as a trait so [`TickCtx`]
2712/// stays `no_std` + free of the `rmw-cffi`-gated `Executor` type.
2713///
2714/// Mirrors the sibling [`ActionExecutor`] (server-side ops). Splitting
2715/// client vs server keeps each trait small + lets an implementor (the
2716/// single-node runtime's tick-side client dispatch; once the codegen-side
2717/// ~~`GenClientDispatch`~~) resolve client handles independently from
2718/// server handles.
2719pub trait ClientDispatch {
2720 /// Issue a service-client request on `service_entity` carrying CDR
2721 /// `request_cdr`; block on the reply, write the response CDR into
2722 /// `response_buf`, return the response length in bytes.
2723 ///
2724 /// The synchronous block is built on the executor-driven
2725 /// `send_request_raw` + `take_response_raw` pair (phase-301: the
2726 /// RMW layer has no blocking call) — the tick hook drives the
2727 /// executor between callback dispatch, so a blocked `call_raw`
2728 /// does not starve other callbacks (each tick yields back to the
2729 /// runtime after returning).
2730 fn call_raw(
2731 &mut self,
2732 service_entity: &str,
2733 request_cdr: &[u8],
2734 response_buf: &mut [u8],
2735 ) -> NodeResult<usize>;
2736
2737 /// Send an action-client goal request on `action_entity` carrying
2738 /// CDR `goal_cdr`; return the assigned [`GoalUuid`] (server-stamped on
2739 /// the goal-accept response). Result + feedback streams arrive via
2740 /// callback dispatch — not this method.
2741 fn send_goal_raw(&mut self, action_entity: &str, goal_cdr: &[u8]) -> NodeResult<GoalUuid>;
2742
2743 /// Whether a server for the service client `service_entity` is CURRENTLY
2744 /// discoverable — `rclcpp::ClientBase::service_is_ready`, for a tick.
2745 ///
2746 /// phase-428 W13. Three answers: `Ok(true)`, `Ok(false)`, or `Err` when
2747 /// the backend cannot say (no discovery channel, or the entity is
2748 /// unknown). A tick that gates its first `call_raw` on `Ok(true)` and
2749 /// treats `Err` as "call anyway" keeps the request-is-the-probe behaviour
2750 /// on backends without discovery and stops sending into the void on the
2751 /// ones with it.
2752 ///
2753 /// Default `Err(NodeDeclError::Runtime)` — "cannot say" — so an
2754 /// implementor that predates this method (the orchestration codegen's
2755 /// dispatch) keeps its shape.
2756 fn service_is_ready(&self, service_entity: &str) -> NodeResult<bool> {
2757 let _ = service_entity;
2758 Err(NodeDeclError::Runtime)
2759 }
2760
2761 /// Whether a server for the action client `action_entity` is CURRENTLY
2762 /// discoverable — `rclcpp_action::Client::action_server_is_ready`, for a
2763 /// tick. Same three answers as [`Self::service_is_ready`], read off the
2764 /// action's `send_goal` service (issue 1918): a goal sent before the server
2765 /// has declared it is answered by nobody, and the declarative client sends
2766 /// ONCE.
2767 fn action_server_is_ready(&self, action_entity: &str) -> NodeResult<bool> {
2768 let _ = action_entity;
2769 Err(NodeDeclError::Runtime)
2770 }
2771}
2772
2773// phase-572 W2.
2774/// The ROS graph queries a component context forwards: the
2775/// fourteen the executor's [`Node`](crate::Node) has, which are rclrs's names,
2776/// with the executor's visitor signatures. Object-safe, so a context holds it
2777/// as `&mut dyn GraphQuery`.
2778///
2779/// Every answer is what has been DISCOVERED and never blocks: an empty visit
2780/// or a low count is "not seen yet", never proof of absence, and
2781/// `Err(Transport(Unsupported))` from a backend with no graph is a different
2782/// answer from empty.
2783///
2784/// An implementor reaches the executor's session for the length of ONE call
2785/// and keeps nothing: no session pointer outlives the query.
2786pub trait GraphQuery {
2787 /// `visit(name, namespace)` per node on the graph.
2788 fn get_node_names(
2789 &mut self,
2790 visit: &mut dyn FnMut(&str, &str) -> bool,
2791 ) -> Result<(), crate::NodeError>;
2792 /// `visit(name, namespace, enclave)`; `enclave` is `None` where the
2793 /// backend does not track one.
2794 fn get_node_names_with_enclaves(
2795 &mut self,
2796 visit: &mut dyn FnMut(&str, &str, Option<&str>) -> bool,
2797 ) -> Result<(), crate::NodeError>;
2798 /// `visit(topic, types)` once per distinct topic.
2799 fn get_topic_names_and_types(
2800 &mut self,
2801 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2802 ) -> Result<(), crate::NodeError>;
2803 /// `visit(service, types)` once per distinct service.
2804 fn get_service_names_and_types(
2805 &mut self,
2806 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2807 ) -> Result<(), crate::NodeError>;
2808 /// Publishers visible on `topic_name`.
2809 fn count_publishers(&mut self, topic_name: &str) -> Result<usize, crate::NodeError>;
2810 /// Subscriptions visible on `topic_name`.
2811 fn count_subscriptions(&mut self, topic_name: &str) -> Result<usize, crate::NodeError>;
2812 /// Clients visible on `service_name`.
2813 fn count_clients(&mut self, service_name: &str) -> Result<usize, crate::NodeError>;
2814 /// Servers visible on `service_name`.
2815 fn count_services(&mut self, service_name: &str) -> Result<usize, crate::NodeError>;
2816 /// The topics node `node_name` in `node_namespace` publishes.
2817 fn get_publisher_names_and_types_by_node(
2818 &mut self,
2819 node_name: &str,
2820 node_namespace: &str,
2821 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2822 ) -> Result<(), crate::NodeError>;
2823 /// The topics node `node_name` in `node_namespace` subscribes to.
2824 fn get_subscription_names_and_types_by_node(
2825 &mut self,
2826 node_name: &str,
2827 node_namespace: &str,
2828 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2829 ) -> Result<(), crate::NodeError>;
2830 /// The services node `node_name` in `node_namespace` serves.
2831 fn get_service_names_and_types_by_node(
2832 &mut self,
2833 node_name: &str,
2834 node_namespace: &str,
2835 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2836 ) -> Result<(), crate::NodeError>;
2837 /// The services node `node_name` in `node_namespace` is a client of.
2838 fn get_client_names_and_types_by_node(
2839 &mut self,
2840 node_name: &str,
2841 node_namespace: &str,
2842 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2843 ) -> Result<(), crate::NodeError>;
2844 /// The publishers on `topic_name`, one visit each.
2845 fn get_publishers_info_by_topic(
2846 &mut self,
2847 topic_name: &str,
2848 visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
2849 ) -> Result<(), crate::NodeError>;
2850 /// The subscriptions on `topic_name`, one visit each.
2851 fn get_subscriptions_info_by_topic(
2852 &mut self,
2853 topic_name: &str,
2854 visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
2855 ) -> Result<(), crate::NodeError>;
2856}
2857
2858/// The executor answers each query with its own graph method: the same
2859/// session path its [`Node`](crate::Node) uses, never a second implementation.
2860#[cfg(feature = "rmw-cffi")]
2861impl GraphQuery for crate::Executor<'_> {
2862 fn get_node_names(
2863 &mut self,
2864 visit: &mut dyn FnMut(&str, &str) -> bool,
2865 ) -> Result<(), crate::NodeError> {
2866 crate::Executor::get_node_names(self, &mut |name, ns, _enclave| visit(name, ns))
2867 }
2868 fn get_node_names_with_enclaves(
2869 &mut self,
2870 visit: &mut dyn FnMut(&str, &str, Option<&str>) -> bool,
2871 ) -> Result<(), crate::NodeError> {
2872 crate::Executor::get_node_names(self, visit)
2873 }
2874 fn get_topic_names_and_types(
2875 &mut self,
2876 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2877 ) -> Result<(), crate::NodeError> {
2878 crate::Executor::get_topic_names_and_types(self, visit)
2879 }
2880 fn get_service_names_and_types(
2881 &mut self,
2882 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2883 ) -> Result<(), crate::NodeError> {
2884 crate::Executor::get_service_names_and_types(self, visit)
2885 }
2886 fn count_publishers(&mut self, topic_name: &str) -> Result<usize, crate::NodeError> {
2887 crate::Executor::count_publishers(self, topic_name)
2888 }
2889 fn count_subscriptions(&mut self, topic_name: &str) -> Result<usize, crate::NodeError> {
2890 crate::Executor::count_subscribers(self, topic_name)
2891 }
2892 fn count_clients(&mut self, service_name: &str) -> Result<usize, crate::NodeError> {
2893 crate::Executor::count_clients(self, service_name)
2894 }
2895 fn count_services(&mut self, service_name: &str) -> Result<usize, crate::NodeError> {
2896 crate::Executor::count_services(self, service_name)
2897 }
2898 fn get_publisher_names_and_types_by_node(
2899 &mut self,
2900 node_name: &str,
2901 node_namespace: &str,
2902 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2903 ) -> Result<(), crate::NodeError> {
2904 crate::Executor::get_publisher_names_and_types_by_node(
2905 self,
2906 node_name,
2907 node_namespace,
2908 visit,
2909 )
2910 }
2911 fn get_subscription_names_and_types_by_node(
2912 &mut self,
2913 node_name: &str,
2914 node_namespace: &str,
2915 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2916 ) -> Result<(), crate::NodeError> {
2917 crate::Executor::get_subscription_names_and_types_by_node(
2918 self,
2919 node_name,
2920 node_namespace,
2921 visit,
2922 )
2923 }
2924 fn get_service_names_and_types_by_node(
2925 &mut self,
2926 node_name: &str,
2927 node_namespace: &str,
2928 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2929 ) -> Result<(), crate::NodeError> {
2930 crate::Executor::get_service_names_and_types_by_node(self, node_name, node_namespace, visit)
2931 }
2932 fn get_client_names_and_types_by_node(
2933 &mut self,
2934 node_name: &str,
2935 node_namespace: &str,
2936 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2937 ) -> Result<(), crate::NodeError> {
2938 crate::Executor::get_client_names_and_types_by_node(self, node_name, node_namespace, visit)
2939 }
2940 fn get_publishers_info_by_topic(
2941 &mut self,
2942 topic_name: &str,
2943 visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
2944 ) -> Result<(), crate::NodeError> {
2945 crate::Executor::get_publishers_info_by_topic(self, topic_name, visit)
2946 }
2947 fn get_subscriptions_info_by_topic(
2948 &mut self,
2949 topic_name: &str,
2950 visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
2951 ) -> Result<(), crate::NodeError> {
2952 crate::Executor::get_subscriptions_info_by_topic(self, topic_name, visit)
2953 }
2954}
2955
2956/// Context handed to [`ExecutableNode::tick`] (W.5.6 + M-F.4): the per-spin
2957/// hook that runs *between* callback dispatch, where the executor is free.
2958/// Exposes the immediate publish path (like `CallbackCtx`) plus executor-backed
2959/// action-server ops (complete goal / publish feedback) AND executor-backed
2960/// client-side ops (service `call` / action-client `send_goal`). Callbacks
2961/// can't perform any of these since they don't hold the executor.
2962pub struct TickCtx<'a> {
2963 publishers: &'a dyn PublisherResolver,
2964 actions: &'a mut dyn ActionExecutor,
2965 clients: &'a mut dyn ClientDispatch,
2966 /// Phase 264 W4c — the executor's volatile parameter store, threaded by the tick
2967 /// driver (`tick_one_cell` already holds the executor). `None` until
2968 /// `[param_services]` registers the store. Read with [`parameter`](Self::parameter).
2969 #[cfg(feature = "param-store")]
2970 params: Option<&'a crate::ParameterServer<'a>>,
2971 /// phase-426 W3 — WHICH node's parameters `parameter()` reads.
2972 ///
2973 /// One set of six parameter services is registered per node and the store
2974 /// is keyed the same way, so a context that carries the store without the
2975 /// key can only ever answer for one node — which is how every component on
2976 /// a multi-node executor came to read the primary's values.
2977 #[cfg(feature = "param-store")]
2978 param_node: nros_params::NodeKey,
2979 /// phase-572 W2 -- the graph queries, threaded by the tick driver
2980 /// (`set_graph`). `None` until then, and each query then answers
2981 /// `NotInitialized`.
2982 graph: Option<&'a mut dyn GraphQuery>,
2983}
2984
2985impl<'a> TickCtx<'a> {
2986 /// Build a tick context (called by the generated runtime each spin).
2987 pub fn new(
2988 publishers: &'a dyn PublisherResolver,
2989 actions: &'a mut dyn ActionExecutor,
2990 clients: &'a mut dyn ClientDispatch,
2991 ) -> Self {
2992 Self {
2993 publishers,
2994 actions,
2995 clients,
2996 #[cfg(feature = "param-store")]
2997 params: None,
2998 // phase-426 W3 — the store is keyed by node and this context does
2999 // not know which one until the dispatch site says so
3000 // (`set_param_server`). PRIMARY until then, which is the executor's
3001 // first node and what a single-node image means.
3002 #[cfg(feature = "param-store")]
3003 param_node: nros_params::NodeKey::PRIMARY,
3004 graph: None,
3005 }
3006 }
3007
3008 /// Thread the graph queries in: the tick driver's own [`GraphQuery`],
3009 /// which reaches the executor for the length of each call.
3010 pub fn set_graph(&mut self, graph: &'a mut dyn GraphQuery) {
3011 self.graph = Some(graph);
3012 }
3013
3014 fn graph_query(&mut self) -> Result<&mut dyn GraphQuery, crate::NodeError> {
3015 match self.graph.as_deref_mut() {
3016 Some(g) => Ok(g),
3017 None => Err(crate::NodeError::NotInitialized),
3018 }
3019 }
3020
3021 graph_query_forwarders!(graph_query);
3022
3023 /// Thread the executor's volatile parameter store in (the tick
3024 /// driver holds the executor directly). No-op-equivalent when `None`.
3025 #[cfg(feature = "param-store")]
3026 pub fn set_param_server(
3027 &mut self,
3028 params: Option<&'a crate::ParameterServer<'a>>,
3029 node: nros_params::NodeKey,
3030 ) {
3031 self.params = params;
3032 self.param_node = node;
3033 }
3034
3035 /// Read this node's parameter `name` as `T` during `tick`, or `None`
3036 /// if undeclared, the wrong type, or `[param_services]` is off. Returns the live
3037 /// value (baked initial or last `ros2 param set`; volatile, lost at the next boot).
3038 #[cfg(feature = "param-store")]
3039 pub fn parameter<T: crate::ParameterVariant>(&self, name: &str) -> Option<T> {
3040 self.params
3041 // phase-426 W3 — the store is keyed by node, and the key is the
3042 // component's OWN node, threaded in beside the store by the
3043 // dispatch site. Reading PRIMARY here (which is what this did
3044 // until W3) makes the second node on an executor read its
3045 // sibling's values.
3046 .and_then(|server| server.get(self.param_node, name))
3047 .and_then(T::from_parameter_value)
3048 }
3049
3050 /// Reset the declared timer `timer` from `tick`: rclcpp's
3051 /// `TimerBase::reset()`. See [`CallbackCtx::reset_timer`]; from a tick the
3052 /// request is applied as soon as `tick` returns.
3053 pub fn reset_timer(&self, timer: EntityId<'_>) -> NodeResult<()> {
3054 self.publishers
3055 .request_timer(timer.as_str(), TimerOp::Reset)
3056 }
3057
3058 /// Cancel the declared timer `timer` from `tick`: rclcpp's
3059 /// `TimerBase::cancel()`. See [`CallbackCtx::cancel_timer`].
3060 pub fn cancel_timer(&self, timer: EntityId<'_>) -> NodeResult<()> {
3061 self.publishers
3062 .request_timer(timer.as_str(), TimerOp::Cancel)
3063 }
3064
3065 /// Publish raw CDR bytes through the named publisher entity (immediate).
3066 #[doc(hidden)]
3067 pub fn publish_raw(&self, publisher: EntityId<'_>, data: &[u8]) -> NodeResult<()> {
3068 self.publishers.publish_raw(publisher.as_str(), data)
3069 }
3070
3071 /// Serialize `msg` into an `N`-byte stack buffer and publish it (immediate).
3072 #[doc(hidden)]
3073 pub fn publish<M: RosMessage, const N: usize>(
3074 &self,
3075 publisher: EntityId<'_>,
3076 msg: &M,
3077 ) -> NodeResult<()> {
3078 let mut buf = [0u8; N];
3079 let mut writer =
3080 crate::CdrWriter::new_with_header(&mut buf).map_err(|_| NodeDeclError::Runtime)?;
3081 msg.serialize(&mut writer)
3082 .map_err(|_| NodeDeclError::Runtime)?;
3083 let len = writer.position();
3084 self.publish_raw(publisher, &buf[..len])
3085 }
3086
3087 /// Serialize `msg` and publish through the entity synthesized from `topic`.
3088 ///
3089 /// This pairs with [`DeclarativeNode::create_publisher_for_topic`] for
3090 /// executable tick hooks.
3091 pub fn publish_to_topic<M: RosMessage, const N: usize>(
3092 &self,
3093 topic: &str,
3094 msg: &M,
3095 ) -> NodeResult<()> {
3096 self.publish::<M, N>(EntityId::new(topic), msg)
3097 }
3098
3099 /// Complete an action goal with a typed result (W.5.6 — needs the executor,
3100 /// hence tick-only).
3101 #[doc(hidden)]
3102 pub fn complete_goal<R: RosMessage, const N: usize>(
3103 &mut self,
3104 action: EntityId<'_>,
3105 goal_id: &GoalUuid,
3106 status: GoalStatusCode,
3107 result: &R,
3108 ) -> NodeResult<()> {
3109 // RFC-0069 / issue 0418 — NO inner encapsulation header. ROS 2's
3110 // `<Action>_GetResult_Response` is ONE CDR message: `[header][status][result
3111 // fields]`. This used to write a second header inside the envelope, which
3112 // made the payload `[outer][status][pad][INNER][fields]` — self-consistent
3113 // with nano-ros's own raw consumer and undecodable by any `rcl_action` peer
3114 // or by nano-ros's TYPED path.
3115 //
3116 // The issue-#35 corruption that motivated the old header ("the reader eats
3117 // the first data word … `sequence` deserialized to len 0") is now prevented
3118 // on the READ side instead: the executor splices the envelope's encap onto
3119 // the body before the callback sees it, so `CallbackCtx::message` still
3120 // receives a well-formed CDR message. Producer and consumer changed
3121 // together — either alone reproduces #35.
3122 let mut buf = [0u8; N];
3123 let mut writer = crate::CdrWriter::new(&mut buf);
3124 result
3125 .serialize(&mut writer)
3126 .map_err(|_| NodeDeclError::Runtime)?;
3127 let len = writer.position();
3128 self.actions
3129 .complete_goal_raw(action.as_str(), goal_id, status, &buf[..len])
3130 }
3131
3132 /// Complete an action goal on the action entity synthesized from `name`.
3133 ///
3134 /// This pairs with
3135 /// [`DeclarativeNode::create_action_server_for_name`] and
3136 /// [`DeclarativeNode::create_action_server_for_name_with_callbacks`].
3137 pub fn complete_goal_for_name<R: RosMessage, const N: usize>(
3138 &mut self,
3139 name: &str,
3140 goal_id: &GoalUuid,
3141 status: GoalStatusCode,
3142 result: &R,
3143 ) -> NodeResult<()> {
3144 self.complete_goal::<R, N>(EntityId::new(name), goal_id, status, result)
3145 }
3146
3147 /// Visit each active (accepted, not yet completed) goal on `action` with its
3148 /// id + status — how a `tick` body discovers goals to feed / complete. Collect
3149 /// the ids you want to act on, then call [`Self::publish_feedback`] /
3150 /// [`Self::complete_goal`] after the visit returns (those borrow `self`
3151 /// mutably, so they can't run inside `visit`).
3152 #[doc(hidden)]
3153 pub fn for_each_active_goal(
3154 &self,
3155 action: EntityId<'_>,
3156 visit: &mut dyn FnMut(&GoalUuid, GoalStatusCode),
3157 ) {
3158 self.actions.for_each_active_goal(action.as_str(), visit);
3159 }
3160
3161 /// Visit active goals on the action entity synthesized from `name`.
3162 pub fn for_each_active_goal_for_name(
3163 &self,
3164 name: &str,
3165 visit: &mut dyn FnMut(&GoalUuid, GoalStatusCode),
3166 ) {
3167 self.for_each_active_goal(EntityId::new(name), visit);
3168 }
3169
3170 /// Publish typed feedback for an active action goal (W.5.6 — tick-only).
3171 #[doc(hidden)]
3172 pub fn publish_feedback<F: RosMessage, const N: usize>(
3173 &mut self,
3174 action: EntityId<'_>,
3175 goal_id: &GoalUuid,
3176 feedback: &F,
3177 ) -> NodeResult<()> {
3178 // RFC-0069 / issue 0418 — NO inner encapsulation header; see
3179 // `complete_goal` above. ROS 2's `<Action>_FeedbackMessage` is ONE CDR
3180 // message: `[header][goal_id][feedback fields]`. The executor frames
3181 // `[header][goal_id]` and this payload is the fields alone.
3182 let mut buf = [0u8; N];
3183 let mut writer = crate::CdrWriter::new(&mut buf);
3184 feedback
3185 .serialize(&mut writer)
3186 .map_err(|_| NodeDeclError::Runtime)?;
3187 let len = writer.position();
3188 self.actions
3189 .publish_feedback_raw(action.as_str(), goal_id, &buf[..len])
3190 }
3191
3192 /// Publish feedback on the action entity synthesized from `name`.
3193 pub fn publish_feedback_for_name<F: RosMessage, const N: usize>(
3194 &mut self,
3195 name: &str,
3196 goal_id: &GoalUuid,
3197 feedback: &F,
3198 ) -> NodeResult<()> {
3199 self.publish_feedback::<F, N>(EntityId::new(name), goal_id, feedback)
3200 }
3201
3202 /// Issue a service-client raw-CDR request and block on the reply
3203 /// (M-F.4 — tick-only). Writes the response CDR into `response_buf`
3204 /// and returns the response length in bytes.
3205 #[doc(hidden)]
3206 pub fn call_raw(
3207 &mut self,
3208 service: EntityId<'_>,
3209 request_cdr: &[u8],
3210 response_buf: &mut [u8],
3211 ) -> NodeResult<usize> {
3212 self.clients
3213 .call_raw(service.as_str(), request_cdr, response_buf)
3214 }
3215
3216 /// Whether a server for the service client `service` is CURRENTLY
3217 /// discoverable (M-F.4 — tick-only). Mirrors
3218 /// `rclcpp::ClientBase::service_is_ready`; see
3219 /// [`ClientDispatch::service_is_ready`] for the three answers. There is no
3220 /// blocking `wait_for_service` here because a tick must not block the
3221 /// executor that drives it — check once per tick and return, which is the
3222 /// rclcpp `while (!wait_for_service(1s)) { "waiting again..." }` idiom
3223 /// with the timer as the cadence.
3224 #[doc(hidden)]
3225 pub fn service_is_ready(&self, service: EntityId<'_>) -> NodeResult<bool> {
3226 self.clients.service_is_ready(service.as_str())
3227 }
3228
3229 /// [`Self::service_is_ready`] through the entity synthesized from `name`.
3230 pub fn service_is_ready_for_name(&self, name: &str) -> NodeResult<bool> {
3231 self.service_is_ready(EntityId::new(name))
3232 }
3233
3234 /// Whether a server for the action client `action` is CURRENTLY
3235 /// discoverable (tick-only) — `rclcpp_action::Client::action_server_is_ready`.
3236 /// Gate a goal on `Ok(true)` and treat `Err` ("the backend cannot say") as
3237 /// "send anyway": a goal sent to a server nobody has declared yet is lost,
3238 /// because the send is not retried. Check once per tick, the
3239 /// way [`Self::service_is_ready`] documents.
3240 #[doc(hidden)]
3241 pub fn action_server_is_ready(&self, action: EntityId<'_>) -> NodeResult<bool> {
3242 self.clients.action_server_is_ready(action.as_str())
3243 }
3244
3245 /// [`Self::action_server_is_ready`] through the entity synthesized from `name`.
3246 pub fn action_server_is_ready_for_name(&self, name: &str) -> NodeResult<bool> {
3247 self.action_server_is_ready(EntityId::new(name))
3248 }
3249
3250 /// Issue a raw service-client request through the entity synthesized
3251 /// from `name`.
3252 pub fn call_raw_for_name(
3253 &mut self,
3254 name: &str,
3255 request_cdr: &[u8],
3256 response_buf: &mut [u8],
3257 ) -> NodeResult<usize> {
3258 self.call_raw(EntityId::new(name), request_cdr, response_buf)
3259 }
3260
3261 /// Issue a typed service-client request and decode the reply
3262 /// (M-F.4 — tick-only). `REQ_N` / `RESP_N` stack-size the request /
3263 /// response CDR buffers; size them via
3264 /// `<<Req as RosMessage>::SerializedSize as nros::SerializedSize>::SIZE`.
3265 #[doc(hidden)]
3266 pub fn call<Req: RosMessage, Resp: RosMessage, const REQ_N: usize, const RESP_N: usize>(
3267 &mut self,
3268 service: EntityId<'_>,
3269 request: &Req,
3270 ) -> NodeResult<Resp> {
3271 let mut req_buf = [0u8; REQ_N];
3272 let mut writer =
3273 crate::CdrWriter::new_with_header(&mut req_buf).map_err(|_| NodeDeclError::Runtime)?;
3274 request
3275 .serialize(&mut writer)
3276 .map_err(|_| NodeDeclError::Runtime)?;
3277 let req_len = writer.position();
3278
3279 let mut resp_buf = [0u8; RESP_N];
3280 let resp_len =
3281 self.clients
3282 .call_raw(service.as_str(), &req_buf[..req_len], &mut resp_buf)?;
3283
3284 let mut reader = crate::CdrReader::new_with_header(&resp_buf[..resp_len])
3285 .map_err(|_| NodeDeclError::Runtime)?;
3286 Resp::deserialize(&mut reader).map_err(|_| NodeDeclError::Runtime)
3287 }
3288
3289 /// Issue a typed service-client request through the entity synthesized
3290 /// from `name`.
3291 pub fn call_for_name<
3292 Req: RosMessage,
3293 Resp: RosMessage,
3294 const REQ_N: usize,
3295 const RESP_N: usize,
3296 >(
3297 &mut self,
3298 name: &str,
3299 request: &Req,
3300 ) -> NodeResult<Resp> {
3301 self.call::<Req, Resp, REQ_N, RESP_N>(EntityId::new(name), request)
3302 }
3303
3304 /// Send a raw-CDR action-client goal and return the assigned
3305 /// [`GoalUuid`] (M-F.4 — tick-only). Result + feedback streams arrive
3306 /// via callback dispatch; this method only kicks off the request.
3307 #[doc(hidden)]
3308 pub fn send_goal_raw(&mut self, action: EntityId<'_>, goal_cdr: &[u8]) -> NodeResult<GoalUuid> {
3309 self.clients.send_goal_raw(action.as_str(), goal_cdr)
3310 }
3311
3312 /// Send a raw-CDR action-client goal through the entity synthesized
3313 /// from `name`.
3314 pub fn send_goal_raw_for_name(&mut self, name: &str, goal_cdr: &[u8]) -> NodeResult<GoalUuid> {
3315 self.send_goal_raw(EntityId::new(name), goal_cdr)
3316 }
3317
3318 /// Send a typed action-client goal and return the assigned
3319 /// [`GoalUuid`] (M-F.4 — tick-only). `N` stack-sizes the goal CDR
3320 /// buffer.
3321 #[doc(hidden)]
3322 pub fn send_goal<G: RosMessage, const N: usize>(
3323 &mut self,
3324 action: EntityId<'_>,
3325 goal: &G,
3326 ) -> NodeResult<GoalUuid> {
3327 // RFC-0069 / issue 0418 — NO inner encapsulation header, same rule as
3328 // `publish_feedback` / `complete_goal`. ROS 2's `<Action>_SendGoal_Request`
3329 // is ONE CDR message: `[header][goal_id][goal fields]`. `send_goal_raw`
3330 // frames `[header][goal_id]`, so this payload is the fields alone.
3331 //
3332 // Issue 0448: this path used `new_with_header` and shipped a SECOND
3333 // encapsulation (`header|uuid|header|fields`) — 4 bytes over the ROS 2
3334 // layout. Fast-DDS sizes its reader history from the type and drops the
3335 // sample outright ("Change payload size of '28' bytes is larger than the
3336 // history payload size of '27'"), so the goal never reached the server
3337 // and the client saw a zeroed default result. nros-c / nros-cpp already
3338 // stripped the header; only this Rust path was missed.
3339 //
3340 // Confirmed independently while root-causing issue 0461: the extra
3341 // header also made every SERVER decode the wrong offset over zenoh
3342 // (C/C++ read the inner header as the first field, so an order of 10
3343 // arrived as 256). Same defect, a second symptom.
3344 let mut buf = [0u8; N];
3345 let mut writer = crate::CdrWriter::new(&mut buf);
3346 goal.serialize(&mut writer)
3347 .map_err(|_| NodeDeclError::Runtime)?;
3348 let len = writer.position();
3349 self.clients.send_goal_raw(action.as_str(), &buf[..len])
3350 }
3351
3352 /// Send a typed action-client goal through the entity synthesized
3353 /// from `name`.
3354 pub fn send_goal_for_name<G: RosMessage, const N: usize>(
3355 &mut self,
3356 name: &str,
3357 goal: &G,
3358 ) -> NodeResult<GoalUuid> {
3359 self.send_goal::<G, N>(EntityId::new(name), goal)
3360 }
3361}
3362
3363#[cfg(feature = "rmw-cffi")]
3364pub trait ExecutableNode: Component {
3365 /// Per-instance mutable state shared across the component's callbacks.
3366 type State;
3367
3368 /// Build the initial state (called once by the generated runtime).
3369 fn init() -> Self::State;
3370
3371 /// Run the body for `callback`. `ctx` exposes the triggering payload + the
3372 /// immediate publish path. Bodies match on the source callback name declared
3373 /// by `create_*_for_callback_name` and related helpers.
3374 fn on_callback(state: &mut Self::State, callback: Callback<'_>, ctx: &mut CallbackCtx<'_>);
3375
3376 /// Per-spin execution hook (W.5.6), run *between* callback dispatch by the
3377 /// generated runtime — where the executor is free, so this is the only place
3378 /// a component can complete action goals / publish feedback (via `ctx`) or do
3379 /// periodic work. Default: no-op (timer/sub/service-only components).
3380 fn tick(_state: &mut Self::State, _ctx: &mut TickCtx<'_>) {}
3381
3382 /// phase-521 W6 (RFC-0113 D2) — whether [`tick`](Self::tick) does any
3383 /// work. A tick runs once per spin, so while any registered component
3384 /// ticks the entry keeps a 10 ms spin cadence; once none does, the entry
3385 /// parks until its next deadline or arrival. Defaults to `true`, the safe
3386 /// reading for a component that overrides `tick`. A component with no
3387 /// tick says `false`.
3388 const HAS_TICK: bool = true;
3389}
3390
3391/// Emit a no-op [`ExecutableNode`] impl for a declarative-only component
3392/// (W.5.1). The generated runtime calls `on_callback` unconditionally, so a
3393/// component instantiated into a generated binary must impl `ExecutableNode`;
3394/// components without callback bodies use this to satisfy that contract:
3395///
3396/// ```ignore
3397/// pub struct Node;
3398/// impl nros::Component for Node { /* register(...) */ }
3399/// nros::declarative_component!(Node);
3400/// ```
3401#[macro_export]
3402macro_rules! declarative_component {
3403 ($ty:ty) => {
3404 impl $crate::ExecutableNode for $ty {
3405 type State = ();
3406 const HAS_TICK: bool = false;
3407 fn init() -> Self::State {}
3408 fn on_callback(
3409 _state: &mut Self::State,
3410 _callback: $crate::Callback<'_>,
3411 _ctx: &mut $crate::CallbackCtx<'_>,
3412 ) {
3413 }
3414 }
3415 };
3416}
3417
3418/// Run component registration against a metadata recorder, on `executor`.
3419///
3420/// Registration creates real nodes, so it needs an executor even
3421/// on the probe's road — open one on the `metadata` backend
3422/// (`ExecutorConfig::new("").rmw("metadata")`). The recorder receives every
3423/// declaration exactly as it did when it was the whole runtime.
3424#[cfg(feature = "rmw-cffi")]
3425pub fn register_node<C: Component>(
3426 recorder: &mut dyn NodeRuntime,
3427 executor: &mut crate::Executor<'static>,
3428) -> NodeResult<()> {
3429 let mut sink = RecordSink { recorder };
3430 let mut frame = ComponentFrame::new(&mut sink);
3431 let mut context = NodeContext::new(C::NAME, executor, &mut frame);
3432 C::register(&mut context)
3433}
3434
3435/// Run `f` against a [`NodeContext`] whose declarations go to `recorder`,
3436/// on `executor` (opened on the `metadata` backend). The tests of the
3437/// declarative surface use it; the probe uses [`record_node_metadata`].
3438#[cfg(feature = "rmw-cffi")]
3439#[doc(hidden)]
3440pub fn __record_with_context<T>(
3441 component_name: &'static str,
3442 recorder: &mut dyn NodeRuntime,
3443 executor: &mut crate::Executor<'static>,
3444 f: impl FnOnce(&mut NodeContext<'_>) -> T,
3445) -> T {
3446 let mut sink = RecordSink { recorder };
3447 let mut frame = ComponentFrame::new(&mut sink);
3448 let mut context = NodeContext::new(component_name, executor, &mut frame);
3449 f(&mut context)
3450}
3451
3452/// Run component registration against an in-memory metadata recorder, on an
3453/// executor the caller opened on the `metadata` backend.
3454#[cfg(feature = "rmw-cffi")]
3455pub fn record_node_metadata<C: Component>(
3456 recorder: &mut dyn NodeRuntime,
3457 executor: &mut crate::Executor<'static>,
3458) -> NodeResult<()> {
3459 register_node::<C>(recorder, executor)
3460}
3461
3462// Issue 2650.
3463/// [`record_node_metadata`], also watching the parameter prose the component's
3464/// code sets, so the sidecar states the longest `description` and
3465/// `additional_constraints` (`0` when none) instead of saying nothing.
3466///
3467/// Those lengths size `NROS_PARAMS_MAX_DESCRIPTION_BYTES` and
3468/// `NROS_PARAMS_MAX_CONSTRAINTS_BYTES`, and a sidecar that does not state them
3469/// leaves every image the probe ran at the 256-byte default. The only observer
3470/// used to be `metadata_mode`'s, which writes to that module's global recorder,
3471/// so the Rust harness, which records into its own, never stated them.
3472#[cfg(all(feature = "rmw-cffi", feature = "probe-descriptor-text"))]
3473pub fn record_node_metadata_watching_prose<C: Component>(
3474 recorder: &mut MetadataRecorder,
3475 executor: &mut crate::Executor<'static>,
3476) -> NodeResult<()> {
3477 use core::sync::atomic::{AtomicUsize, Ordering};
3478 use nros_params::descriptor_text_observer::{
3479 DescriptorText, clear_descriptor_text_observer, set_descriptor_text_observer,
3480 };
3481 // The observer is a plain `fn`, so the lengths travel through statics; the
3482 // harness records one component per process.
3483 static DESCRIPTION: AtomicUsize = AtomicUsize::new(0);
3484 static CONSTRAINTS: AtomicUsize = AtomicUsize::new(0);
3485 DESCRIPTION.store(0, Ordering::Relaxed);
3486 CONSTRAINTS.store(0, Ordering::Relaxed);
3487 set_descriptor_text_observer(|text, len| {
3488 let slot = match text {
3489 DescriptorText::Description => &DESCRIPTION,
3490 DescriptorText::Constraints => &CONSTRAINTS,
3491 };
3492 slot.fetch_max(len, Ordering::Relaxed);
3493 });
3494 let result = register_node::<C>(recorder, executor);
3495 clear_descriptor_text_observer();
3496 recorder.arm_descriptor_text();
3497 recorder.observe_descriptor_text(false, DESCRIPTION.load(Ordering::Relaxed));
3498 recorder.observe_descriptor_text(true, CONSTRAINTS.load(Ordering::Relaxed));
3499 // With `metadata-mode` also compiled in, opening a node re-installs that
3500 // module's observer over the one above, so the lengths land in its
3501 // recorder: take them from there too.
3502 #[cfg(feature = "metadata-mode")]
3503 {
3504 let (d, c) = crate::metadata_mode::descriptor_text_seen();
3505 recorder.observe_descriptor_text(false, d.unwrap_or(0));
3506 recorder.observe_descriptor_text(true, c.unwrap_or(0));
3507 }
3508 result
3509}
3510
3511#[cfg(test)]
3512mod tests {
3513 use super::*;
3514 use crate::{CdrReader, CdrWriter, DeserError, SerError};
3515
3516 #[derive(Debug, Clone, Copy, Default)]
3517 struct TestMsg;
3518
3519 impl crate::Serialize for TestMsg {
3520 fn serialize(&self, _writer: &mut CdrWriter) -> Result<(), SerError> {
3521 Ok(())
3522 }
3523 }
3524
3525 impl crate::Deserialize for TestMsg {
3526 fn deserialize(_reader: &mut CdrReader) -> Result<Self, DeserError> {
3527 Ok(Self)
3528 }
3529 }
3530
3531 impl RosMessage for TestMsg {
3532 const TYPE_NAME: &'static str = "test_msgs::msg::dds_::Test_";
3533 const TYPE_HASH: &'static str = "test_hash";
3534 }
3535
3536 // Phase 380 W4 — `MessageForRmw` now also requires a field schema, because
3537 // that is where a subscription's size bound comes from. `TestMsg` is an
3538 // empty struct, so its schema is the empty slice and its bound is just the
3539 // encapsulation header — which is exactly what the build assertion should
3540 // see for it.
3541 impl nros_serdes::schema::Message for TestMsg {
3542 const TYPE_NAME: &'static str = "test_msgs/msg/Test";
3543 const FIELDS: &'static [nros_serdes::schema::Field] = &[];
3544 }
3545
3546 #[cfg(feature = "rmw-cffi")]
3547 struct TalkerComponent;
3548
3549 #[cfg(feature = "rmw-cffi")]
3550 impl Component for TalkerComponent {
3551 const NAME: &'static str = "talker_component";
3552
3553 fn register(context: &mut NodeContext<'_>) -> NodeResult<()> {
3554 let mut node =
3555 context.create_node_with_id(NodeId::new("node"), NodeOptions::new("talker"))?;
3556 let _publisher =
3557 node.declare_publisher::<TestMsg>(EntityId::new("pub_chatter"), "chatter")?;
3558 let _subscription = node.declare_subscription::<TestMsg>(
3559 EntityId::new("sub_cmd"),
3560 CallbackId::new("on_cmd"),
3561 "~/cmd",
3562 )?;
3563 let _timer = node.declare_timer(
3564 EntityId::new("timer_tick"),
3565 CallbackId::new("on_tick"),
3566 TimerDuration::from_millis(10),
3567 )?;
3568 let _parameter = node.declare_parameter_with_id(
3569 EntityId::new("param_gain"),
3570 "gain",
3571 ParameterType::Double,
3572 )?;
3573 node.callback(CallbackId::new("on_tick"))
3574 .publishes(EntityId::new("pub_chatter"))?
3575 .writes(EntityId::new("param_gain"))?;
3576 Ok(())
3577 }
3578 }
3579
3580 #[test]
3581 fn component_missing_export_error_message_is_clear() {
3582 assert_eq!(
3583 NodeDeclError::MissingExport.message(),
3584 "package has no exported nros component"
3585 );
3586 }
3587
3588 // W.5.1 — an executable component callback runs its body: mutates state +
3589 // publishes immediately through the resolver (the substrate the generator
3590 // will wire). `TalkerComponent` already impls `Node` (declarative);
3591 // here it also impls `ExecutableNode`.
3592 #[cfg(feature = "rmw-cffi")]
3593 impl ExecutableNode for TalkerComponent {
3594 type State = u32;
3595
3596 fn init() -> u32 {
3597 0
3598 }
3599
3600 fn on_callback(state: &mut u32, callback: Callback<'_>, ctx: &mut CallbackCtx<'_>) {
3601 if callback.as_str() == "on_tick" {
3602 *state += 1;
3603 // Publish through the declared publisher entity.
3604 let _ = ctx.publish::<TestMsg, 64>(EntityId::new("pub_chatter"), &TestMsg);
3605 }
3606 }
3607 }
3608
3609 #[cfg(feature = "rmw-cffi")]
3610 #[test]
3611 fn executable_component_callback_publishes_and_mutates_state() {
3612 use core::cell::RefCell;
3613
3614 struct RecordingResolver {
3615 last: RefCell<Option<(MetadataString, usize)>>,
3616 }
3617 impl PublisherResolver for RecordingResolver {
3618 fn publish_raw(&self, entity_id: &str, data: &[u8]) -> NodeResult<()> {
3619 *self.last.borrow_mut() = Some((copy_str(entity_id)?, data.len()));
3620 Ok(())
3621 }
3622 }
3623
3624 let resolver = RecordingResolver {
3625 last: RefCell::new(None),
3626 };
3627 let mut state = TalkerComponent::init();
3628 let mut ctx = CallbackCtx::new(&[], &resolver);
3629
3630 // An unrelated callback id does nothing.
3631 TalkerComponent::on_callback(
3632 &mut state,
3633 Callback::__from_id(CallbackId::new("other")),
3634 &mut ctx,
3635 );
3636 assert_eq!(state, 0);
3637 assert!(resolver.last.borrow().is_none());
3638
3639 // The bound callback bumps state + publishes through "pub_chatter".
3640 TalkerComponent::on_callback(
3641 &mut state,
3642 Callback::__from_id(CallbackId::new("on_tick")),
3643 &mut ctx,
3644 );
3645 assert_eq!(state, 1);
3646 let last = resolver.last.borrow();
3647 let (entity, len) = last.as_ref().expect("a publish was recorded");
3648 assert_eq!(entity.as_str(), "pub_chatter");
3649 // Empty TestMsg ⇒ just the 4-byte CDR header.
3650 assert_eq!(*len, 4);
3651 }
3652
3653 // issue 2568 -- the flat `[name, value, ...]` array a C/C++ entry hands a
3654 // Rust component's install reads back as the same pairs a Rust entry bakes.
3655 #[cfg(feature = "rmw-cffi")]
3656 #[test]
3657 fn flat_c_launch_params_read_back_by_name() {
3658 let kv: [*const core::ffi::c_char; 4] = [
3659 c"speed".as_ptr(),
3660 c"2.5".as_ptr(),
3661 c"frame".as_ptr(),
3662 c"map".as_ptr(),
3663 ];
3664 let p = unsafe { LaunchParams::from_c_pairs(kv.as_ptr(), 2) }.expect("valid array");
3665 assert_eq!(p.get("speed"), Some("2.5"));
3666 assert_eq!(p.get("frame"), Some("map"));
3667 assert_eq!(p.get("absent"), None);
3668 assert_eq!(p.iter().count(), 2);
3669 }
3670
3671 #[cfg(feature = "rmw-cffi")]
3672 #[test]
3673 fn flat_c_launch_params_refuse_a_malformed_array() {
3674 // No params: null with a zero count is the empty set.
3675 let none = unsafe { LaunchParams::from_c_pairs(core::ptr::null(), 0) }.expect("empty");
3676 assert_eq!(none.iter().count(), 0);
3677 // A null array with a count, a null entry, or non-UTF-8 bytes.
3678 assert!(unsafe { LaunchParams::from_c_pairs(core::ptr::null(), 1) }.is_none());
3679 let with_null: [*const core::ffi::c_char; 2] = [c"k".as_ptr(), core::ptr::null()];
3680 assert!(unsafe { LaunchParams::from_c_pairs(with_null.as_ptr(), 1) }.is_none());
3681 let bad = [0xffu8, 0];
3682 let not_utf8: [*const core::ffi::c_char; 2] = [c"k".as_ptr(), bad.as_ptr().cast()];
3683 assert!(unsafe { LaunchParams::from_c_pairs(not_utf8.as_ptr(), 1) }.is_none());
3684 }
3685
3686 // W.5.3 — a service-style body writes its reply through the CallbackCtx
3687 // reply sink; the trampoline reads `*written` back. A timer/sub ctx (no
3688 // sink) rejects a reply.
3689 #[test]
3690 fn callback_ctx_reply_sink_roundtrips() {
3691 struct NoopResolver;
3692 impl PublisherResolver for NoopResolver {
3693 fn publish_raw(&self, _entity_id: &str, _data: &[u8]) -> NodeResult<()> {
3694 Ok(())
3695 }
3696 }
3697 let resolver = NoopResolver;
3698 let mut reply_buf = [0u8; 64];
3699 let mut written = 0usize;
3700 {
3701 let mut ctx = CallbackCtx::with_reply(&[], &resolver, &mut reply_buf, &mut written);
3702 ctx.reply::<TestMsg, 64>(&TestMsg).unwrap();
3703 }
3704 // Empty TestMsg ⇒ just the 4-byte CDR header.
3705 assert_eq!(written, 4);
3706
3707 // A reply-less ctx (timer / subscription) rejects a reply.
3708 let mut ctx2 = CallbackCtx::new(&[], &resolver);
3709 assert!(ctx2.reply_raw(&[1, 2, 3]).is_err());
3710 }
3711
3712 // Issue 2038 — a context carries a timer's call info only when the
3713 // dispatch site attached one; every constructor starts without.
3714 #[test]
3715 fn callback_ctx_timer_info_is_attached_by_the_dispatch_site() {
3716 struct NoopResolver;
3717 impl PublisherResolver for NoopResolver {
3718 fn publish_raw(&self, _entity_id: &str, _data: &[u8]) -> NodeResult<()> {
3719 Ok(())
3720 }
3721 }
3722 let resolver = NoopResolver;
3723 let mut ctx = CallbackCtx::new(&[], &resolver);
3724 assert!(ctx.timer_info().is_none());
3725 let info = crate::TimerCallInfo {
3726 expected_call_time: 1_000,
3727 actual_call_time: 1_250,
3728 clock: crate::TimerClockSource::Ros,
3729 ..Default::default()
3730 };
3731 ctx.set_timer_info(info);
3732 assert_eq!(ctx.timer_info(), Some(&info));
3733 assert_eq!(ctx.timer_info().map(|i| i.lateness_ns()), Some(250));
3734 }
3735
3736 // Phase 264 W4c — a callback reads the live parameter value through
3737 // `CallbackCtx::parameter::<T>` once the dispatch site threads the store in.
3738 #[cfg(feature = "param-store")]
3739 #[test]
3740 fn callback_ctx_reads_param() {
3741 struct NoopResolver;
3742 impl PublisherResolver for NoopResolver {
3743 fn publish_raw(&self, _entity_id: &str, _data: &[u8]) -> NodeResult<()> {
3744 Ok(())
3745 }
3746 }
3747 let resolver = NoopResolver;
3748
3749 // No store threaded ⇒ every read is None (param-services off / not registered).
3750 let ctx_none = CallbackCtx::new(&[], &resolver);
3751 assert_eq!(ctx_none.parameter::<i64>("speed"), None);
3752
3753 // Seed a store with the typed value a `ros2 param set speed 7` would land on.
3754 // phase-382 W2' — the slots are the caller's; a local `ParameterStorage`
3755 // is the shape a test wants, sized for what it actually declares rather
3756 // than the build-time `MAX_PARAMETERS` default.
3757 // phase-426 W1/W3 — every store call names the node it is about.
3758 // `talker` is the executor's first node, `listener` its second.
3759 let talker = nros_params::NodeKey::PRIMARY;
3760 let listener = nros_params::NodeKey::new(1);
3761 let mut storage = crate::ParameterStorage::<4>::new();
3762 let mut server = crate::ParameterServer::new_in(storage.as_table());
3763 assert!(server.declare(talker, "speed", crate::ParameterValue::Integer(7)));
3764 assert!(server.declare(listener, "speed", crate::ParameterValue::Integer(99)));
3765
3766 let mut ctx = CallbackCtx::new(&[], &resolver);
3767 ctx.set_param_server(Some(&server), talker);
3768 assert_eq!(ctx.parameter::<i64>("speed"), Some(7));
3769 // Wrong type ⇒ None, not a panic.
3770 assert_eq!(ctx.parameter::<bool>("speed"), None);
3771 // Undeclared ⇒ None.
3772 assert_eq!(ctx.parameter::<i64>("missing"), None);
3773
3774 // phase-426 W3 — the SIBLING's identically-named parameter is a
3775 // different parameter, and the context reads the node it was given.
3776 // Before W3 this ctx was pinned to PRIMARY, so a listener component
3777 // read the talker's 7.
3778 let mut sibling = CallbackCtx::new(&[], &resolver);
3779 sibling.set_param_server(Some(&server), listener);
3780 assert_eq!(sibling.parameter::<i64>("speed"), Some(99));
3781 }
3782
3783 // Phase 250 Wave 2 — the declarative `.safety()` surface: a normal ctx has
3784 // no integrity status; one built with `new_with_integrity` exposes it, read
3785 // alongside the message in the same callback (Shape A).
3786 #[cfg(feature = "safety-e2e")]
3787 #[test]
3788 fn callback_ctx_integrity_surface() {
3789 struct NoopResolver;
3790 impl PublisherResolver for NoopResolver {
3791 fn publish_raw(&self, _entity_id: &str, _data: &[u8]) -> NodeResult<()> {
3792 Ok(())
3793 }
3794 }
3795 let resolver = NoopResolver;
3796
3797 // Non-safety dispatch (timer / plain sub) → None.
3798 let ctx = CallbackCtx::new(&[], &resolver);
3799 assert!(ctx.integrity().is_none());
3800
3801 // Safety dispatch → the status rides alongside the payload.
3802 let status = crate::IntegrityStatus {
3803 gap: 2,
3804 duplicate: false,
3805 crc_valid: Some(true),
3806 };
3807 let ctx = CallbackCtx::new_with_integrity(&[], &resolver, &status);
3808 let got = ctx.integrity().expect("safety ctx carries status");
3809 assert_eq!(got.gap, 2);
3810 assert!(!got.duplicate);
3811 assert_eq!(got.crc_valid, Some(true));
3812 }
3813
3814 // Issue 2349.
3815 #[test]
3816 fn callback_ctx_message_info_surface() {
3817 struct NoopResolver;
3818 impl PublisherResolver for NoopResolver {
3819 fn publish_raw(&self, _entity_id: &str, _data: &[u8]) -> NodeResult<()> {
3820 Ok(())
3821 }
3822 }
3823 let resolver = NoopResolver;
3824
3825 // A plain dispatch carries none.
3826 let ctx = CallbackCtx::new(&[], &resolver);
3827 assert!(ctx.message_info().is_none());
3828
3829 // The metadata dispatch attaches it, unchanged.
3830 let info =
3831 crate::MessageInfo::with_timestamps(crate::Time::new(5, 0), crate::Time::new(6, 0));
3832 let mut ctx = CallbackCtx::new(&[], &resolver);
3833 ctx.set_message_info(&info);
3834 assert_eq!(ctx.message_info(), Some(&info));
3835 }
3836
3837 // W.5.3 — an action goal / cancel body sets its accept/reject decision
3838 // through the CallbackCtx decision sink; the trampoline returns `*out`. A
3839 // wrong-kind setter (or a sink-less ctx) errors.
3840 #[test]
3841 fn callback_ctx_decision_sink() {
3842 struct NoopResolver;
3843 impl PublisherResolver for NoopResolver {
3844 fn publish_raw(&self, _entity_id: &str, _data: &[u8]) -> NodeResult<()> {
3845 Ok(())
3846 }
3847 }
3848 let resolver = NoopResolver;
3849
3850 let mut gr = GoalResponse::Reject;
3851 {
3852 let mut ctx = CallbackCtx::with_goal_decision(&[], &resolver, &mut gr);
3853 ctx.set_goal_response(GoalResponse::AcceptAndExecute)
3854 .unwrap();
3855 // Wrong-kind setter on a goal ctx errors.
3856 assert!(ctx.set_cancel_response(CancelResponse::Accept).is_err());
3857 }
3858 assert!(matches!(gr, GoalResponse::AcceptAndExecute));
3859
3860 let mut cr = CancelResponse::Reject;
3861 {
3862 let mut ctx = CallbackCtx::with_cancel_decision(&[], &resolver, &mut cr);
3863 ctx.set_cancel_response(CancelResponse::Accept).unwrap();
3864 }
3865 assert!(matches!(cr, CancelResponse::Accept));
3866
3867 // A timer/sub ctx (no decision sink) rejects both.
3868 let mut ctx3 = CallbackCtx::new(&[], &resolver);
3869 assert!(ctx3.set_goal_response(GoalResponse::Reject).is_err());
3870 assert!(ctx3.set_cancel_response(CancelResponse::Accept).is_err());
3871 }
3872
3873 // W.5.6 — the tick hook publishes (immediate) + drives executor-backed action
3874 // ops (complete goal / publish feedback) through the ActionExecutor seam.
3875 #[test]
3876 fn tick_ctx_publish_and_action_ops() {
3877 use core::cell::Cell;
3878 struct RecPub {
3879 published: Cell<bool>,
3880 }
3881 impl PublisherResolver for RecPub {
3882 fn publish_raw(&self, _entity_id: &str, _data: &[u8]) -> NodeResult<()> {
3883 self.published.set(true);
3884 Ok(())
3885 }
3886 }
3887 struct RecAct {
3888 completed: bool,
3889 fed: bool,
3890 visited: usize,
3891 }
3892 impl ActionExecutor for RecAct {
3893 fn complete_goal_raw(
3894 &mut self,
3895 _action_entity: &str,
3896 _goal_id: &GoalUuid,
3897 _status: GoalStatusCode,
3898 _result: &[u8],
3899 ) -> NodeResult<()> {
3900 self.completed = true;
3901 Ok(())
3902 }
3903 fn publish_feedback_raw(
3904 &mut self,
3905 _action_entity: &str,
3906 _goal_id: &GoalUuid,
3907 _feedback: &[u8],
3908 ) -> NodeResult<()> {
3909 self.fed = true;
3910 Ok(())
3911 }
3912 fn for_each_active_goal(
3913 &self,
3914 _action_entity: &str,
3915 visit: &mut dyn FnMut(&GoalUuid, GoalStatusCode),
3916 ) {
3917 // One pretend-active goal, so the tick body has something to drive.
3918 visit(&GoalUuid::zero(), GoalStatusCode::Executing);
3919 }
3920 }
3921
3922 struct RecClients;
3923 impl ClientDispatch for RecClients {
3924 fn call_raw(
3925 &mut self,
3926 _service: &str,
3927 _req: &[u8],
3928 _resp: &mut [u8],
3929 ) -> NodeResult<usize> {
3930 Err(NodeDeclError::Runtime)
3931 }
3932 fn send_goal_raw(&mut self, _action: &str, _goal: &[u8]) -> NodeResult<GoalUuid> {
3933 Err(NodeDeclError::Runtime)
3934 }
3935 }
3936
3937 let pubs = RecPub {
3938 published: Cell::new(false),
3939 };
3940 let mut acts = RecAct {
3941 completed: false,
3942 fed: false,
3943 visited: 0,
3944 };
3945 let mut clients = RecClients;
3946 let goal = GoalUuid::zero();
3947 let mut seen = 0usize;
3948 {
3949 let mut ctx = TickCtx::new(&pubs, &mut acts, &mut clients);
3950 ctx.publish::<TestMsg, 64>(EntityId::new("pub_x"), &TestMsg)
3951 .unwrap();
3952 // Discover the active goal the way a real tick body does, then act on it.
3953 ctx.for_each_active_goal(EntityId::new("act"), &mut |_id, _status| seen += 1);
3954 ctx.publish_feedback::<TestMsg, 64>(EntityId::new("act"), &goal, &TestMsg)
3955 .unwrap();
3956 ctx.complete_goal::<TestMsg, 64>(
3957 EntityId::new("act"),
3958 &goal,
3959 GoalStatusCode::Succeeded,
3960 &TestMsg,
3961 )
3962 .unwrap();
3963 }
3964 acts.visited = seen;
3965 assert!(pubs.published.get());
3966 assert!(acts.completed);
3967 assert!(acts.fed);
3968 assert_eq!(acts.visited, 1);
3969 }
3970
3971 /// Phase 216.A.3 — `Node::DISPATCH` defaults to
3972 /// `DispatchStrategy::Inline` so every pre-216 `impl Node`
3973 /// keeps compiling unchanged.
3974 #[cfg(feature = "rmw-cffi")]
3975 #[test]
3976 fn node_dispatch_default_is_inline() {
3977 struct Dummy;
3978 impl Component for Dummy {
3979 const NAME: &'static str = "dummy";
3980 fn register(_: &mut NodeContext<'_>) -> NodeResult<()> {
3981 Ok(())
3982 }
3983 }
3984 assert_eq!(Dummy::DISPATCH, crate::DispatchStrategy::Inline);
3985 }
3986
3987 // Phase 216.A.5 — `nros::node!()` emits the
3988 // `__nros_node_<pkg>_dispatch_strategy()` ABI export. We invoke the
3989 // macro on a dummy Node + ExecutableNode pair in a private sub-module
3990 // here so the macro expansion lives inside the `nros` crate itself;
3991 // the emitted `#[unsafe(no_mangle)] extern "C"` symbol is global, so
3992 // the test below re-declares + calls it. If the macro stopped
3993 // emitting the symbol (or renamed it) this would link-fail.
3994 //
3995 // `<pkg>` resolves to `CARGO_PKG_NAME` after
3996 // `sanitize_pkg_name_for_symbol`. The `nros` crate's pkg name is
3997 // literal `nros`, so the expected symbol is
3998 // `__nros_node_nros_dispatch_strategy`.
3999 // Phase 216 final wave — the macro emit now references
4000 // `::nros::Executor` (rmw-cffi-gated) in addition to the existing
4001 // alloc-gated `__private_node_state_into_raw`. Gate the test on
4002 // both features so the macro invocation only attempts to expand
4003 // when every referenced symbol is present.
4004 #[cfg(all(feature = "alloc", feature = "rmw-cffi", feature = "macros"))]
4005 mod dispatch_probe_macro_test {
4006 // `extern crate self as nros;` at the crate root (in `lib.rs`,
4007 // `cfg(test)`-gated) lets the `::nros::*` paths the macro emits
4008 // resolve in-crate.
4009 use super::*;
4010
4011 pub struct DispatchProbe;
4012
4013 impl Component for DispatchProbe {
4014 const NAME: &'static str = "dispatch_probe";
4015 // Default `DISPATCH = Inline` ⇒ discriminant 0.
4016 fn register(_: &mut NodeContext<'_>) -> NodeResult<()> {
4017 Ok(())
4018 }
4019 }
4020
4021 impl ExecutableNode for DispatchProbe {
4022 type State = ();
4023 fn init() -> Self::State {}
4024 fn on_callback(
4025 _state: &mut Self::State,
4026 _callback: Callback<'_>,
4027 _ctx: &mut CallbackCtx<'_>,
4028 ) {
4029 }
4030 }
4031
4032 // Emits both the per-pkg `register` wrapper AND the new
4033 // `__nros_node_nros_dispatch_strategy` ABI symbol.
4034 nros_macros::node!(DispatchProbe);
4035 }
4036
4037 // Also `macros`: this asserts the ABI symbol the `node!` invocation above
4038 // emits, so without the macro there is nothing to assert and the extern
4039 // would not resolve.
4040 #[cfg(all(feature = "alloc", feature = "rmw-cffi", feature = "macros"))]
4041 #[test]
4042 fn node_macro_emits_dispatch_strategy_symbol() {
4043 // Re-declare the ABI export the macro just emitted. If the macro
4044 // elides the symbol (or renames it) this fails to link — exactly
4045 // the regression the test is meant to catch.
4046 unsafe extern "C" {
4047 fn __nros_node_nros_dispatch_strategy() -> u8;
4048 }
4049 let strategy = unsafe { __nros_node_nros_dispatch_strategy() };
4050 // The probe Node uses the default `DISPATCH = Inline`
4051 // (discriminant 0) — confirms the macro is splicing
4052 // `<Type as Component>::DISPATCH as u8`, not a hard-coded zero.
4053 assert_eq!(strategy, crate::DispatchStrategy::Inline as u8);
4054 assert_eq!(strategy, 0);
4055 }
4056}
4057
4058/// The build-time receive-buffer check a subscription makes, as the IMAGE
4059/// build sees it.
4060///
4061/// Issue 2942 -- the metadata probe compiles each component with the crate's
4062/// default `NROS_EXECUTOR_SUBSCRIPTION_BUFFER_BYTES`, before the image's
4063/// closure-derived value exists, so a bounded message over the default failed
4064/// the probe although the image would have been sized for it. The probe
4065/// never receives a sample; the image build (which gets the derived buffer)
4066/// keeps the check. Keyed on `probe-descriptor-text`, the feature only the
4067/// probe harness names: a host image also has `metadata-mode` (its census
4068/// producer), so that one would silence the check in real images.
4069#[cfg(not(feature = "probe-descriptor-text"))]
4070const fn subscription_buffer_checked<M: MessageForRmw>() -> bool {
4071 nros_node::rmw_type_registry::subscription_buffer_ok::<M>()
4072}
4073
4074/// See the image-build twin: the probe build does not check the buffer.
4075// `M` is unused here on purpose: the signature must match the twin's, which
4076// the one call site names with `::<M>`.
4077#[cfg(feature = "probe-descriptor-text")]
4078#[allow(clippy::extra_unused_type_parameters)]
4079const fn subscription_buffer_checked<M: MessageForRmw>() -> bool {
4080 true
4081}