Skip to main content

nros_node/executor/
node.rs

1//! Node — borrows the session to create typed entities.
2
3use core::marker::PhantomData;
4
5use nros_core::{RosAction, RosMessage, RosService};
6use nros_rmw::{ActionInfo, QoSProfile, ServiceInfo, Session as _, TopicInfo, TransportError};
7
8use crate::{
9    rmw_type_registry::{MessageForRmw, register_type},
10    session,
11};
12
13use super::{
14    handles::{
15        ActionClient, ActionClientCallback, ActionServer, EmbeddedPublisher, EmbeddedServiceClient,
16        EmbeddedServiceServer, ServiceClientCallback, Subscription,
17    },
18    types::NodeError,
19};
20
21/// Validate a profile against what the backend honours, and SAY WHICH POLICY
22/// when it does not — phase-417 G7.
23///
24/// Six `create_*` paths ran `qos.validate_against(…).map_err(NodeError::Transport)`
25/// and that was the whole diagnostic: the C caller saw `RCLC_RET_REJECTED`, the
26/// C++ caller `NROS_CPP_RET_NOT_ALLOWED`, and neither could learn WHICH policy
27/// the backend declined — while `rmw_vtable.h`'s `supported_qos_policies` block
28/// told the reader those creates fail "naming a policy". This is the one place
29/// that sentence becomes true for a caller who only gets a return code.
30///
31/// ONE helper rather than a log line per site, for the reason CLAUDE.md's "fix
32/// the CLASS" rule gives: six copies of a diagnostic are six places for the
33/// wording, the logger name and the fallback to drift, and this family has
34/// already paid that twice (the sizes-header mirror, the Zephyr unset-variable
35/// guard).
36///
37/// The policy NAME comes from [`nros_rmw::QoSPolicyMask::NAMED`] by way of
38/// `TransportError::qos_policy_name`, so this crate states no policy vocabulary
39/// of its own, and the token a C++ caller reads out of
40/// `nros::qos_policy_kind_to_cstr` is the same byte string that appears here.
41pub(crate) fn validate_qos_or_report(
42    qos: &QoSProfile,
43    supported: nros_rmw::QoSPolicyMask,
44    kind: &str,
45    name: &str,
46) -> Result<(), NodeError> {
47    match qos.validate_against(supported) {
48        Ok(()) => Ok(()),
49        Err(err) => {
50            nros_log::log_error!(
51                nros_log::get_logger("nros_node"),
52                "qos: {} '{}' refused — the backend does not honour {}",
53                kind,
54                name,
55                // `None` is a real answer, not a missing one: a refusal
56                // relayed from a C backend crosses `rmw_ret_t`, which has no
57                // room for a mask, so no policy was identified. Naming a
58                // neighbouring one would be the plausible wrong answer.
59                err.qos_policy_name()
60                    .unwrap_or("a QoS policy it did not name")
61            );
62            Err(NodeError::Transport(err))
63        }
64    }
65}
66
67// Issue 2920.
68/// Who chose an endpoint's base profile, which decides what happens to a
69/// policy the backend cannot carry.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub(crate) enum ProfileOrigin {
72    /// An application asked for it: a requirement, refused when unsupported.
73    Application,
74    /// The runtime chose it for its own endpoint: a preference, fitted by
75    /// `fit_runtime_qos`. Built only by the `/rosout` and
76    /// `/parameter_events` writers, so an image with neither never makes one.
77    #[cfg_attr(
78        not(any(feature = "rosout", feature = "param-services")),
79        allow(dead_code)
80    )]
81    Runtime,
82}
83
84// Issue 2920.
85/// Fit a profile the RUNTIME chose for one of its own endpoints
86/// (`/rosout`, `/parameter_events`, the lifecycle services and
87/// `transition_event`) to what `supported` honours, and say once, per
88/// endpoint, which policies that dropped.
89///
90/// The rule is [`QoSProfile::fit_to_supported`]'s: a runtime profile is a
91/// preference, so a policy the backend cannot carry steps down instead of
92/// refusing the endpoint. Only the runtime's own base profile comes here.
93/// Whatever a person wrote and is folded on afterwards (a per-topic override,
94/// a declared contract, an application profile) is still validated and
95/// refused naming the policy.
96pub fn fit_runtime_qos(
97    qos: QoSProfile,
98    supported: nros_rmw::QoSPolicyMask,
99    kind: &str,
100    name: &str,
101) -> QoSProfile {
102    let (fitted, dropped) = qos.fit_to_supported(supported);
103    if dropped != nros_rmw::QoSPolicyMask::NONE {
104        report_runtime_qos_fitted(kind, name, dropped);
105    }
106    fitted
107}
108
109/// Cold: it formats. One line per policy, so a profile that loses two says
110/// both.
111#[cold]
112#[inline(never)]
113fn report_runtime_qos_fitted(kind: &str, name: &str, dropped: nros_rmw::QoSPolicyMask) {
114    for (bit, policy) in nros_rmw::QoSPolicyMask::NAMED {
115        if dropped.contains(*bit) {
116            nros_log::log_info!(
117                nros_log::get_logger("nros_node"),
118                "qos: {} '{}' created without {}: this RMW does not honour it, and \
119                 the profile is the runtime's own default, not one the application \
120                 asked for",
121                kind,
122                name,
123                policy.to_str().unwrap_or("a QoS policy")
124            );
125        }
126    }
127}
128
129// ============================================================================
130// Node
131// ============================================================================
132
133/// Backend-agnostic node — borrows the session to create typed entities.
134pub struct NodeHandle<'a> {
135    name: heapless::String<64>,
136    namespace: heapless::String<64>,
137    session: &'a mut session::ConcreteSession,
138    /// The executor's remap rules, both tiers (issue 1971: the launch table in
139    /// flash plus the runtime table). Consulted only to SUBSTITUTE a name some
140    /// rule matches — see `NodeHandle::remapped`.
141    remaps: super::spin::RemapView<'a>,
142    domain_id: u32,
143    /// Phase 211.H — per-node QoS overrides lowered from the launch
144    /// `qos_overrides.<topic>.<role>.<policy>` params and baked into a
145    /// `&'static` table by the entry codegen. Folded into each entity's
146    /// `QoSProfile` at `create_publisher`/`create_subscription` time
147    /// (setup-time, no alloc). Empty (`&[]`) by default → zero cost for
148    /// systems without overrides.
149    qos_overrides: &'static [nros_rmw::QoSOverride],
150    /// RFC-0052 W3b.4 — baked contract-monitor table (mirror of
151    /// `qos_overrides`): `create_publisher` attaches the matching
152    /// endpoint's counter cell so `publish` can bump it lock-free.
153    monitors: &'static [crate::executor::monitor::MonitorSpec],
154    /// W3b.5 — baked subscriber age-contract table + epoch clock;
155    /// `create_subscription` attaches the matching endpoint's age cell.
156    age_monitors: &'static [crate::executor::monitor::AgeMonitorSpec],
157    epoch_us_fn: Option<fn() -> u64>,
158    /// The executor node's publish gate, when this handle stands for a node
159    /// in the executor's table. Every publisher it creates reads it.
160    publish_gate: Option<core::ptr::NonNull<crate::executor::node_record::PublishGate>>,
161}
162
163impl<'a> NodeHandle<'a> {
164    /// Create a new node (called by Executor::create_node).
165    pub(crate) fn new(
166        name: heapless::String<64>,
167        namespace: heapless::String<64>,
168        session: &'a mut session::ConcreteSession,
169        remaps: super::spin::RemapView<'a>,
170        domain_id: u32,
171    ) -> Self {
172        Self {
173            name,
174            namespace,
175            session,
176            remaps,
177            domain_id,
178            qos_overrides: &[],
179            monitors: &[],
180            age_monitors: &[],
181            epoch_us_fn: None,
182            publish_gate: None,
183        }
184    }
185
186    /// Bind this handle to an executor node's publish gate.
187    pub(crate) fn set_publish_gate(
188        &mut self,
189        gate: core::ptr::NonNull<crate::executor::node_record::PublishGate>,
190    ) {
191        self.publish_gate = Some(gate);
192    }
193
194    fn publisher_gate(&self) -> crate::lifecycle::PublisherGate {
195        match self.publish_gate {
196            Some(g) => crate::lifecycle::PublisherGate::of(g),
197            None => crate::lifecycle::PublisherGate::none(),
198        }
199    }
200
201    /// Install the plan's QoS-override table on this node. Called
202    /// by the generated entry BEFORE the component constructs its entities, so
203    /// `create_publisher`/`create_subscription` fold the matching overrides in.
204    /// The table is `&'static` (codegen bakes it as a `static`), so there is no
205    /// lifetime to thread and no runtime allocation. Plan = authority: an
206    /// override for a topic the entity creates is applied transparently (the
207    /// user's `create_publisher(topic)` call is unchanged, matching rclcpp).
208    pub fn set_qos_overrides(&mut self, overrides: &'static [nros_rmw::QoSOverride]) {
209        self.qos_overrides = overrides;
210    }
211
212    /// Install the executor's monitor table on this node
213    /// (called by the entry glue / fixture alongside `set_qos_overrides`).
214    pub fn set_monitors(&mut self, monitors: &'static [crate::executor::monitor::MonitorSpec]) {
215        self.monitors = monitors;
216    }
217
218    /// W3b.5 — install the subscriber age-contract table + epoch clock
219    /// (auto-seeded from the executor's `set_age_table` / config epoch).
220    pub fn set_age_monitors(
221        &mut self,
222        table: &'static [crate::executor::monitor::AgeMonitorSpec],
223        epoch_us: Option<fn() -> u64>,
224    ) {
225        self.age_monitors = table;
226        self.epoch_us_fn = epoch_us;
227    }
228
229    /// The installed QoS-override table (empty unless the entry set one).
230    #[must_use]
231    pub fn qos_overrides(&self) -> &'static [nros_rmw::QoSOverride] {
232        self.qos_overrides
233    }
234
235    /// Get the node name.
236    pub fn name(&self) -> &str {
237        &self.name
238    }
239
240    /// The serialization format this node's entities speak.
241    ///
242    /// The counterpart to ROS 2's `rmw_get_serialization_format()`, asked of
243    /// the node rather than the process: an `Executor::open_multi` image holds
244    /// two sessions and has no single answer, which is the case the reserved
245    /// vtable slot was cut for.
246    ///
247    /// A single-backend image already knows this at compile time — see
248    /// [`crate::session::IMAGE_SERIALIZATION_FORMAT`], which is what the
249    /// entity-creation assertions compare against. Use this accessor when the
250    /// answer must be a value: a bridge, a diagnostic, a tool.
251    ///
252    /// **`None` means the backend has not said** — the same discipline the C
253    /// entry point `rclc_node_get_serialization_format` has always kept by
254    /// returning NULL, and the one `rmw_vtable.h` states for the slot
255    /// underneath. It is not a synonym for `"cdr"`.
256    #[must_use]
257    pub fn serialization_format(&self) -> Option<&'static str> {
258        nros_rmw::Session::serialization_format(&*self.session)
259    }
260
261    /// The RMW backend behind this node, by name — the counterpart to ROS 2's
262    /// `rmw_get_implementation_identifier()` (rclpy's
263    /// `get_rmw_implementation_identifier()`), asked of the node because an
264    /// `Executor::open_multi` image holds two sessions.
265    ///
266    /// The nano-ros backend name (`"zenoh"`, `"cyclonedds"`, `"xrce"`,
267    /// `"uorb"`), never a stock `rmw_*_cpp` name: a zenoh image speaks
268    /// `rmw_zenoh_cpp`'s wire but is not that implementation, and code that
269    /// branches on the identifier is asking about the implementation. A
270    /// backend reached through the C ABI that states no name answers the name
271    /// it was registered under. `None` = the backend has not said.
272    #[must_use]
273    pub fn rmw_implementation_identifier(&self) -> Option<&'static str> {
274        nros_rmw::Session::implementation_identifier(&*self.session)
275    }
276
277    /// Return the [`nros_log::Logger`] NAMED FOR THIS NODE.
278    ///
279    /// Loggers are interned in nros-log's bounded global table
280    /// ([`nros_log::MAX_LOGGERS`] slots). If the caller has
281    /// pre-registered a `'static Logger` whose name matches this
282    /// node's name (via [`nros_log::register_logger`]), this method
283    /// returns that exact reference — so subsequent `nros_*!` calls
284    /// share per-logger runtime threshold state with any other call
285    /// site that resolves the same name.
286    ///
287    /// Otherwise one is CREATED under the node's name, in
288    /// nros-log's bounded arena. It used to answer
289    /// [`nros_log::DEFAULT_LOGGER`] instead, which kept the API total by
290    /// making every node in an image share the name `"nros"`: no record could
291    /// say which node emitted it, and `set_level` on one node's handle moved
292    /// every other node's bar with it. [`nros_log::resolve_logger`] is the one
293    /// spelling of this resolution; the catch-all remains the fallback for an
294    /// exhausted arena, and it reports itself when it fires.
295    ///
296    /// ```ignore
297    /// // Pre-register if you want a `'static` logger you can also name
298    /// // from elsewhere in the image:
299    /// static MY_NODE_LOGGER: nros_log::Logger =
300    ///     nros_log::Logger::new("my_node");
301    /// nros_log::register_logger(&MY_NODE_LOGGER);
302    ///
303    /// // Inside any node-creating code:
304    /// let logger = node.logger();
305    /// nros_log::log_info!(logger, "started; domain = {}", node.domain_id());
306    /// ```
307    #[must_use]
308    pub fn logger(&self) -> &'static nros_log::Logger {
309        nros_log::resolve_node_logger(self.name())
310    }
311
312    /// Get the domain ID.
313    pub fn domain_id(&self) -> u32 {
314        self.domain_id
315    }
316
317    /// Set the domain ID.
318    pub fn set_domain_id(&mut self, domain_id: u32) {
319        self.domain_id = domain_id;
320    }
321
322    /// Get a mutable reference to the underlying session.
323    pub fn session_mut(&mut self) -> &mut session::ConcreteSession {
324        self.session
325    }
326
327    // ------------------------------------------------------------------
328    // Routing-info builders (Phase 91.F)
329    //
330    // Every `create_*` below threads the same node identity (domain_id +
331    // name + namespace) into a TopicInfo / ServiceInfo / ActionInfo. The
332    // shape repeats verbatim ~12 times across this file. Centralised
333    // here so a future change to the routing-info shape (e.g. adding a
334    // security context) updates one site instead of twelve, and
335    // so the per-`create_*` function bodies focus on the parts that
336    // actually differ between them.
337    // ------------------------------------------------------------------
338
339    // Associated fns (NOT `&self` methods) so the returned `*Info`
340    // value's borrow tracks only the explicit `&str` arguments, not
341    // the whole `Node`. A `&self` form would block the immediately-
342    // following `self.session.create_*(&info, …)` mut borrow on the
343    // `name` / `namespace` reborrow held inside the returned `*Info`,
344    // because going through a method call hides the field-disjoint
345    // path that lets `&self.name` + `&mut self.session` coexist.
346    fn topic_info<'b>(
347        domain_id: u32,
348        node_name: &'b str,
349        namespace: &'b str,
350        topic_name: &'b str,
351        type_name: &'b str,
352        type_hash: &'b str,
353    ) -> TopicInfo<'b> {
354        TopicInfo::new(topic_name, type_name, type_hash)
355            .with_domain(domain_id)
356            .with_node_name(node_name)
357            .with_namespace(namespace)
358    }
359
360    fn service_info<'b>(
361        domain_id: u32,
362        node_name: &'b str,
363        namespace: &'b str,
364        service_name: &'b str,
365        type_name: &'b str,
366        type_hash: &'b str,
367    ) -> ServiceInfo<'b> {
368        ServiceInfo::new(service_name, type_name, type_hash)
369            .with_domain(domain_id)
370            .with_node_name(node_name)
371            .with_namespace(namespace)
372    }
373
374    fn action_info<'b>(
375        domain_id: u32,
376        action_name: &'b str,
377        type_name: &'b str,
378        type_hash: &'b str,
379    ) -> ActionInfo<'b> {
380        // Action root only needs the domain — per-channel ServiceInfo /
381        // TopicInfo derived from action_info.{send_goal,cancel_goal,...}_key()
382        // carry the full node identity via service_info() / topic_info().
383        ActionInfo::new(action_name, type_name, type_hash).with_domain(domain_id)
384    }
385
386    /// The name a rule in either tier sends `source` to, or `None` when no
387    /// rule matches — in which case the caller passes `source` through
388    /// UNCHANGED, exactly as this handle always has.
389    ///
390    /// Launch rules (`Executor::declare_remap`) are authoritative and
391    /// `--ros-args` rules are the fallback, through
392    /// [`crate::names::remap_layered`] — the same two tiers
393    /// `Executor::resolve_entity_name_for` gives the C and C++ roads and
394    /// `ExecutorSink` gives Rust components.
395    ///
396    /// Substitution-only, deliberately. This handle has never expanded a name
397    /// (`~`/relative) before handing it to the backend, and doing so now for
398    /// every entity would move wire names nobody asked to move. A matched rule
399    /// yields a fully-qualified name, which is what every other road hands the
400    /// backend too.
401    ///
402    /// Before this the handle consulted no remap at all: a rule declared on
403    /// the executor reached C, C++ and component entities and silently missed
404    /// every entity created through `Executor::create_node`'s handle.
405    fn remapped(&self, source: &str) -> Option<crate::names::ResolvedName> {
406        crate::names::remap_layered(
407            source,
408            &self.name,
409            &self.namespace,
410            self.remaps.launch_rules(&self.name, &self.namespace),
411            self.remaps.argv_rules(&self.name, &self.namespace),
412        )
413    }
414
415    // -- Publishers --
416
417    /// Create a publisher for the given topic.
418    pub fn create_publisher<M: MessageForRmw>(
419        &mut self,
420        topic_name: &str,
421    ) -> Result<EmbeddedPublisher<M>, NodeError> {
422        self.create_publisher_with_qos::<M>(topic_name, QoSProfile::default())
423    }
424
425    /// Create a publisher with custom QoS settings.
426    pub fn create_publisher_with_qos<M: MessageForRmw>(
427        &mut self,
428        topic_name: &str,
429        qos: QoSProfile,
430    ) -> Result<EmbeddedPublisher<M>, NodeError> {
431        // RFC-0088 / phase-421 W1 — the message's declared format must be the
432        // one the linked backend speaks. Universal: the const lives on
433        // `RosMessage`, which `MessageForRmw` requires under every backend.
434        crate::format_check::assert_message_format::<M>();
435        // Phase 212.K.7.6.b — under `rmw-cyclonedds`, ensure the runtime
436        // type-descriptor exists before the cffi vtable creates the
437        // entity. No-op for other RMWs.
438        register_type::<M>()?;
439        // Phase 211.H — fold any plan qos_overrides for this topic+publisher
440        // into the profile (setup-time, no alloc) BEFORE validation, so an
441        // override the backend can't honour still errors loudly below.
442        let qos = qos.apply_overrides(
443            topic_name,
444            nros_rmw::QoSOverrideRole::Publisher,
445            self.qos_overrides,
446        );
447        // Phase 108.B — synchronous QoS validation against backend's
448        // `supported_qos_policies()` mask. No silent downgrade.
449        let remapped = self.remapped(topic_name);
450        let topic = Self::topic_info(
451            self.domain_id,
452            &self.name,
453            &self.namespace,
454            remapped.as_deref().unwrap_or(topic_name),
455            <M as RosMessage>::TYPE_NAME,
456            <M as RosMessage>::TYPE_HASH,
457        );
458        // issue 1608 -- the publisher half of the declared-QoS check. BEFORE
459        // validation, so a policy the contract raises this publisher to is
460        // one the backend is asked whether it can honour.
461        let qos = crate::declared_qos::honour_publisher(topic.type_name, topic.name, qos)?;
462        validate_qos_or_report(
463            &qos,
464            nros_rmw::Session::supported_qos_policies(self.session),
465            "publisher",
466            topic_name,
467        )?;
468        let handle = self
469            .session
470            .create_publisher(&topic, qos)
471            .map_err(|_| NodeError::Transport(TransportError::PublisherCreationFailed))?;
472        // RFC-0052 W3b.4 — attach the contracted endpoint's counter cell
473        // (exact topic-name match against the baked table; None = free).
474        let monitor = self
475            .monitors
476            .iter()
477            .find(|m| m.topic == topic_name)
478            .map(|m| m.cell);
479        Ok(EmbeddedPublisher {
480            handle,
481            gate: self.publisher_gate(),
482            event_regs: crate::executor::handles::empty_event_regs(),
483            monitor,
484            epoch: self.epoch_us_fn,
485            _phantom: PhantomData,
486        })
487    }
488
489    /// Create a typeless publisher for non-ROS wire formats (e.g. PX4 uORB
490    /// raw POD bytes, custom binary protocols). The caller supplies the
491    /// `type_name` and `type_hash` strings used by backends that need them
492    /// for liveliness/discovery; backends that don't (uORB) can pass any
493    /// stable string.
494    pub fn create_publisher_raw(
495        &mut self,
496        topic_name: &str,
497        type_name: &str,
498        type_hash: &str,
499    ) -> Result<crate::executor::handles::EmbeddedRawPublisher, NodeError> {
500        self.create_publisher_raw_with_qos(topic_name, type_name, type_hash, QoSProfile::default())
501    }
502
503    /// Typeless publisher with custom QoS.
504    pub fn create_publisher_raw_with_qos(
505        &mut self,
506        topic_name: &str,
507        type_name: &str,
508        type_hash: &str,
509        qos: QoSProfile,
510    ) -> Result<crate::executor::handles::EmbeddedRawPublisher, NodeError> {
511        // Phase 211.H — apply plan qos_overrides (publisher side) before validate.
512        let qos = qos.apply_overrides(
513            topic_name,
514            nros_rmw::QoSOverrideRole::Publisher,
515            self.qos_overrides,
516        );
517        let remapped = self.remapped(topic_name);
518        let topic = Self::topic_info(
519            self.domain_id,
520            &self.name,
521            &self.namespace,
522            remapped.as_deref().unwrap_or(topic_name),
523            type_name,
524            type_hash,
525        );
526        // issue 1608 -- see `create_publisher_with_qos`.
527        let qos = crate::declared_qos::honour_publisher(topic.type_name, topic.name, qos)?;
528        validate_qos_or_report(
529            &qos,
530            nros_rmw::Session::supported_qos_policies(self.session),
531            "publisher",
532            topic_name,
533        )?;
534        let handle = self
535            .session
536            .create_publisher(&topic, qos)
537            .map_err(|_| NodeError::Transport(TransportError::PublisherCreationFailed))?;
538        Ok(crate::executor::handles::EmbeddedRawPublisher {
539            handle,
540            gate: self.publisher_gate(),
541            arena: crate::executor::handles::TxArena::new(),
542            event_regs: crate::executor::handles::empty_event_regs(),
543            // Issue 1676 — the typed path's rule, verbatim.
544            monitor: self
545                .monitors
546                .iter()
547                .find(|m| m.topic == topic_name)
548                .map(|m| m.cell),
549        })
550    }
551
552    /// The customizable publisher **builder** (the `clone` tier;
553    /// see `docs/design/0022-entity-api-tiers.md`). Pick a mode with `.typed::<M>()`
554    /// or `.generic(type, hash)`, set knobs (`.qos`), then `.build()`. The
555    /// convenient `create_publisher` / `create_publisher_raw` are the `fork`
556    /// tier — sugar over this with defaults.
557    pub fn publisher<'t>(&mut self, topic: &'t str) -> PublisherBuilder<'_, 'a, 't> {
558        PublisherBuilder {
559            node: self,
560            topic,
561            qos: QoSProfile::default(),
562        }
563    }
564
565    // -- Subscriptions --
566
567    /// Create a subscription for the given topic.
568    pub fn create_subscription<M: MessageForRmw>(
569        &mut self,
570        topic_name: &str,
571    ) -> Result<Subscription<M>, NodeError> {
572        self.create_subscription_sized::<M, { crate::config::DEFAULT_RX_BUF_SIZE }>(topic_name)
573    }
574
575    /// Create a subscription with custom buffer size.
576    pub fn create_subscription_sized<M: MessageForRmw, const RX_BUF: usize>(
577        &mut self,
578        topic_name: &str,
579    ) -> Result<Subscription<M, RX_BUF>, NodeError> {
580        self.create_subscription_with_qos::<M, RX_BUF>(topic_name, QoSProfile::default())
581    }
582
583    /// Create a subscription with custom QoS and buffer size.
584    pub fn create_subscription_with_qos<M: MessageForRmw, const RX_BUF: usize>(
585        &mut self,
586        topic_name: &str,
587        qos: QoSProfile,
588    ) -> Result<Subscription<M, RX_BUF>, NodeError> {
589        // RFC-0088 / phase-421 W1 — the message's declared format must be the
590        // one the linked backend speaks. Universal: the const lives on
591        // `RosMessage`, which `MessageForRmw` requires under every backend.
592        crate::format_check::assert_message_format::<M>();
593        // Phase 212.K.7.6.b — see `create_publisher_with_qos`.
594        register_type::<M>()?;
595        // Phase 211.H — apply plan qos_overrides (subscription side) before validate.
596        let qos = qos.apply_overrides(
597            topic_name,
598            nros_rmw::QoSOverrideRole::Subscription,
599            self.qos_overrides,
600        );
601        validate_qos_or_report(
602            &qos,
603            nros_rmw::Session::supported_qos_policies(self.session),
604            "subscription",
605            topic_name,
606        )?;
607        let remapped = self.remapped(topic_name);
608        let topic = Self::topic_info(
609            self.domain_id,
610            &self.name,
611            &self.namespace,
612            remapped.as_deref().unwrap_or(topic_name),
613            <M as RosMessage>::TYPE_NAME,
614            <M as RosMessage>::TYPE_HASH,
615        );
616        // phase-454 W10/W13 — see the same line in `executor/spin.rs`.
617        let qos = crate::declared_qos::honour(topic.type_name, topic.name, qos)?;
618        // phase-519 W3b — and the declared arrival rate, likewise.
619        let topic = crate::declared_qos::with_declared_arrival_rate(topic);
620        let handle = self
621            .session
622            .create_subscription(&topic, qos)
623            .map_err(NodeError::Transport)?;
624        // W3b.5 — attach the contracted endpoint's age cell (stamped
625        // types only). Issue 2215: with no epoch source the take is still
626        // recorded, unaged.
627        let age_mon = match <M as RosMessage>::STAMP_OFFSET {
628            Some(_) => self
629                .age_monitors
630                .iter()
631                .find(|a| a.topic == topic_name)
632                .map(|a| (a.cell, self.epoch_us_fn)),
633            None => None,
634        };
635        Ok(Subscription {
636            handle,
637            buffer: [0u8; RX_BUF],
638            event_regs: crate::executor::handles::empty_event_regs(),
639            age_mon,
640            _phantom: PhantomData,
641        })
642    }
643
644    /// Create a typeless subscription. Caller decodes raw bytes themselves.
645    pub fn create_subscription_raw(
646        &mut self,
647        topic_name: &str,
648        type_name: &str,
649        type_hash: &str,
650    ) -> Result<crate::executor::handles::RawSubscription, NodeError> {
651        self.create_subscription_raw_sized::<{ crate::config::DEFAULT_RX_BUF_SIZE }>(
652            topic_name, type_name, type_hash,
653        )
654    }
655
656    /// Typeless subscription with custom buffer size.
657    pub fn create_subscription_raw_sized<const RX_BUF: usize>(
658        &mut self,
659        topic_name: &str,
660        type_name: &str,
661        type_hash: &str,
662    ) -> Result<crate::executor::handles::RawSubscription<RX_BUF>, NodeError> {
663        // Phase 211.H — apply plan qos_overrides (subscription side) before
664        // validate, mirroring `create_publisher_raw_with_qos`. The raw entity
665        // paths honour node overrides exactly like the typed ones — an
666        // override the active RMW can't meet errors loudly, never silently.
667        let qos = QoSProfile::default().apply_overrides(
668            topic_name,
669            nros_rmw::QoSOverrideRole::Subscription,
670            self.qos_overrides,
671        );
672        validate_qos_or_report(
673            &qos,
674            nros_rmw::Session::supported_qos_policies(self.session),
675            "subscription",
676            topic_name,
677        )?;
678        let remapped = self.remapped(topic_name);
679        let topic = Self::topic_info(
680            self.domain_id,
681            &self.name,
682            &self.namespace,
683            remapped.as_deref().unwrap_or(topic_name),
684            type_name,
685            type_hash,
686        );
687        // phase-454 W10/W13 — the raw path costs the arena exactly what
688        // the typed one does, so leaving it out would make the declared depth
689        // enforceable everywhere except in the images that decode bytes
690        // themselves.
691        let qos = crate::declared_qos::honour(topic.type_name, topic.name, qos)?;
692        // phase-519 W3b — and the declared arrival rate, likewise.
693        let topic = crate::declared_qos::with_declared_arrival_rate(topic);
694        let handle = self
695            .session
696            .create_subscription(&topic, qos)
697            .map_err(NodeError::Transport)?;
698        Ok(crate::executor::handles::RawSubscription {
699            handle,
700            buffer: [0u8; RX_BUF],
701            event_regs: crate::executor::handles::empty_event_regs(),
702        })
703    }
704
705    // -- Services --
706
707    /// Create a service server.
708    pub fn create_service<Svc: RosService>(
709        &mut self,
710        service_name: &str,
711    ) -> Result<EmbeddedServiceServer<Svc>, NodeError>
712    where
713        Svc::Request: MessageForRmw,
714        Svc::Reply: MessageForRmw,
715    {
716        self.create_service_sized::<Svc, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }>(service_name, QoSProfile::services_default())
717    }
718
719    /// Service server with an explicit QoS profile (applied to
720    /// both the request + reply endpoints; rclcpp's `create_service(name, qos)`).
721    pub fn create_service_with_qos<Svc: RosService>(
722        &mut self,
723        service_name: &str,
724        qos: QoSProfile,
725    ) -> Result<EmbeddedServiceServer<Svc>, NodeError>
726    where
727        Svc::Request: MessageForRmw,
728        Svc::Reply: MessageForRmw,
729    {
730        self.create_service_sized::<Svc, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }>(service_name, qos)
731    }
732
733    /// Create a service server with custom buffer sizes + QoS.
734    pub fn create_service_sized<Svc: RosService, const REQ_BUF: usize, const REPLY_BUF: usize>(
735        &mut self,
736        service_name: &str,
737        qos: QoSProfile,
738    ) -> Result<EmbeddedServiceServer<Svc, REQ_BUF, REPLY_BUF>, NodeError>
739    where
740        Svc::Request: MessageForRmw,
741        Svc::Reply: MessageForRmw,
742    {
743        // Phase 212.K.7.6.b — register both halves of the service round-trip
744        // under cyclonedds. No-op for other RMWs.
745        register_type::<Svc::Request>()?;
746        register_type::<Svc::Reply>()?;
747        // Phase 193.5 — validate the service profile against the backend's
748        // supported policies (mirrors pub/sub); no silent downgrade. RELIABLE is
749        // effectively required for request/reply, so a backend that only honours
750        // a fixed profile rejects an incompatible request here.
751        validate_qos_or_report(
752            &qos,
753            nros_rmw::Session::supported_qos_policies(self.session),
754            "service",
755            service_name,
756        )?;
757        let remapped = self.remapped(service_name);
758        let info = Self::service_info(
759            self.domain_id,
760            &self.name,
761            &self.namespace,
762            remapped.as_deref().unwrap_or(service_name),
763            Svc::SERVICE_NAME,
764            Svc::SERVICE_HASH,
765        );
766        let handle = self
767            .session
768            .create_service(&info, qos)
769            .map_err(NodeError::Transport)?;
770        Ok(EmbeddedServiceServer {
771            handle,
772            req_buffer: [0u8; REQ_BUF],
773            reply_buffer: [0u8; REPLY_BUF],
774            _phantom: PhantomData,
775        })
776    }
777
778    /// Create a service client.
779    pub fn create_client<Svc: RosService>(
780        &mut self,
781        service_name: &str,
782    ) -> Result<EmbeddedServiceClient<Svc>, NodeError>
783    where
784        Svc::Request: MessageForRmw,
785        Svc::Reply: MessageForRmw,
786    {
787        self.create_client_sized::<Svc, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }>(service_name, QoSProfile::services_default())
788    }
789
790    /// Service client with an explicit QoS profile.
791    pub fn create_client_with_qos<Svc: RosService>(
792        &mut self,
793        service_name: &str,
794        qos: QoSProfile,
795    ) -> Result<EmbeddedServiceClient<Svc>, NodeError>
796    where
797        Svc::Request: MessageForRmw,
798        Svc::Reply: MessageForRmw,
799    {
800        self.create_client_sized::<Svc, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }>(service_name, qos)
801    }
802
803    /// Create a service client with custom buffer sizes + QoS.
804    pub fn create_client_sized<Svc: RosService, const REQ_BUF: usize, const REPLY_BUF: usize>(
805        &mut self,
806        service_name: &str,
807        qos: QoSProfile,
808    ) -> Result<EmbeddedServiceClient<Svc, REQ_BUF, REPLY_BUF>, NodeError>
809    where
810        Svc::Request: MessageForRmw,
811        Svc::Reply: MessageForRmw,
812    {
813        // Phase 212.K.7.6.b — see `create_service_sized`.
814        register_type::<Svc::Request>()?;
815        register_type::<Svc::Reply>()?;
816        // Phase 193.5 — validate against the backend's supported policies (no
817        // silent downgrade); request/reply effectively requires RELIABLE.
818        validate_qos_or_report(
819            &qos,
820            nros_rmw::Session::supported_qos_policies(self.session),
821            "client",
822            service_name,
823        )?;
824        let remapped = self.remapped(service_name);
825        let info = Self::service_info(
826            self.domain_id,
827            &self.name,
828            &self.namespace,
829            remapped.as_deref().unwrap_or(service_name),
830            Svc::SERVICE_NAME,
831            Svc::SERVICE_HASH,
832        );
833        let handle = self
834            .session
835            .create_client(&info, qos)
836            .map_err(|_| NodeError::Transport(TransportError::ServiceClientCreationFailed))?;
837        Ok(EmbeddedServiceClient {
838            handle,
839            req_buffer: [0u8; REQ_BUF],
840            reply_buffer: [0u8; REPLY_BUF],
841            in_flight: false,
842            pending: nros_rmw::RequestCorrelator::new(),
843            _phantom: PhantomData,
844        })
845    }
846
847    /// Typeless service server. L1 counterpart of [`Self::create_service`]
848    /// for the C / C++ FFI shims and callers that own their own
849    /// scheduler. Returns a [`crate::executor::handles::RawServiceServer`]
850    /// which polls request bytes directly.
851    pub fn create_service_raw(
852        &mut self,
853        service_name: &str,
854        type_name: &str,
855        type_hash: &str,
856    ) -> Result<crate::executor::handles::RawServiceServer, NodeError> {
857        self.create_service_raw_sized::<
858            { crate::config::DEFAULT_RX_BUF_SIZE },
859            { crate::config::DEFAULT_RX_BUF_SIZE },
860        >(service_name, type_name, type_hash)
861    }
862
863    /// Typeless service server with custom buffer sizes.
864    pub fn create_service_raw_sized<const REQ_BUF: usize, const RESP_BUF: usize>(
865        &mut self,
866        service_name: &str,
867        type_name: &str,
868        type_hash: &str,
869    ) -> Result<crate::executor::handles::RawServiceServer<REQ_BUF, RESP_BUF>, NodeError> {
870        let remapped = self.remapped(service_name);
871        let info = Self::service_info(
872            self.domain_id,
873            &self.name,
874            &self.namespace,
875            remapped.as_deref().unwrap_or(service_name),
876            type_name,
877            type_hash,
878        );
879        let handle = self
880            .session
881            .create_service(&info, QoSProfile::services_default())
882            .map_err(NodeError::Transport)?;
883        Ok(crate::executor::handles::RawServiceServer::new(handle))
884    }
885
886    /// Typeless service client. L1 counterpart of [`Self::create_client`].
887    pub fn create_client_raw(
888        &mut self,
889        service_name: &str,
890        type_name: &str,
891        type_hash: &str,
892    ) -> Result<crate::executor::handles::RawServiceClient, NodeError> {
893        self.create_client_raw_sized::<
894            { crate::config::DEFAULT_RX_BUF_SIZE },
895            { crate::config::DEFAULT_RX_BUF_SIZE },
896        >(service_name, type_name, type_hash)
897    }
898
899    /// Typeless service client with custom buffer sizes.
900    pub fn create_client_raw_sized<const REQ_BUF: usize, const REPLY_BUF: usize>(
901        &mut self,
902        service_name: &str,
903        type_name: &str,
904        type_hash: &str,
905    ) -> Result<crate::executor::handles::RawServiceClient<REQ_BUF, REPLY_BUF>, NodeError> {
906        let remapped = self.remapped(service_name);
907        let info = Self::service_info(
908            self.domain_id,
909            &self.name,
910            &self.namespace,
911            remapped.as_deref().unwrap_or(service_name),
912            type_name,
913            type_hash,
914        );
915        let handle = self
916            .session
917            .create_client(&info, QoSProfile::services_default())
918            .map_err(|_| NodeError::Transport(TransportError::ServiceClientCreationFailed))?;
919        Ok(crate::executor::handles::RawServiceClient::new(handle))
920    }
921
922    // -- Actions --
923
924    /// Typeless action server. Builds the 5
925    /// transport channels (`send_goal` / `cancel_goal` / `get_result`
926    /// services + `feedback` / `status` publishers) and returns the
927    /// raw `ActionServerCore` directly. Caller owns scheduling —
928    /// drives `try_recv_goal_request` / `publish_feedback_raw` /
929    /// `complete_goal_raw` / `try_handle_cancel` /
930    /// `try_handle_get_result_raw` on the returned core.
931    pub fn create_action_server_raw(
932        &mut self,
933        action_name: &str,
934        type_name: &str,
935        type_hash: &str,
936    ) -> Result<
937        super::action_core::ActionServerCore<
938            { crate::config::DEFAULT_RX_BUF_SIZE },
939            { crate::config::DEFAULT_RX_BUF_SIZE },
940            { crate::config::DEFAULT_RX_BUF_SIZE },
941            4,
942        >,
943        NodeError,
944    > {
945        self.create_action_server_raw_sized::<
946            { crate::config::DEFAULT_RX_BUF_SIZE },
947            { crate::config::DEFAULT_RX_BUF_SIZE },
948            { crate::config::DEFAULT_RX_BUF_SIZE },
949            4,
950        >(action_name, type_name, type_hash)
951    }
952
953    /// Typeless action server with custom buffer + goal-slot sizes.
954    pub fn create_action_server_raw_sized<
955        const GOAL_BUF: usize,
956        const RESULT_BUF: usize,
957        const FEEDBACK_BUF: usize,
958        const MAX_GOALS: usize,
959    >(
960        &mut self,
961        action_name: &str,
962        type_name: &str,
963        type_hash: &str,
964    ) -> Result<
965        super::action_core::ActionServerCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
966        NodeError,
967    > {
968        let remapped = self.remapped(action_name);
969        let action_name = remapped.as_deref().unwrap_or(action_name);
970        let action_info = Self::action_info(self.domain_id, action_name, type_name, type_hash);
971
972        // Issue 0454 / phase-354 W3 — per-CHANNEL DDS type, not the bare
973        // action type (see `action_channel_type`). These two `_raw_sized`
974        // constructors are the last holders of the phase-338 W3 defect: the
975        // type name is baked into the keyexpr, so `…Fibonacci_` never matches a
976        // peer advertising `…Fibonacci_SendGoal_`.
977        let send_goal_type: heapless::String<256> =
978            super::action_core::action_channel_type(type_name, "SendGoal");
979        let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
980        let send_goal_info = Self::service_info(
981            self.domain_id,
982            &self.name,
983            &self.namespace,
984            &send_goal_keyexpr,
985            &send_goal_type,
986            type_hash,
987        );
988        let send_goal_server = self
989            .session
990            .create_service(&send_goal_info, QoSProfile::services_default())
991            .map_err(|_| NodeError::ActionCreationFailed)?;
992
993        let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
994        let cancel_goal_info = Self::service_info(
995            self.domain_id,
996            &self.name,
997            &self.namespace,
998            &cancel_goal_keyexpr,
999            "action_msgs::srv::dds_::CancelGoal_",
1000            type_hash,
1001        );
1002        let cancel_goal_server = self
1003            .session
1004            .create_service(&cancel_goal_info, QoSProfile::services_default())
1005            .map_err(|_| NodeError::ActionCreationFailed)?;
1006
1007        let get_result_type: heapless::String<256> =
1008            super::action_core::action_channel_type(type_name, "GetResult");
1009        let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
1010        let get_result_info = Self::service_info(
1011            self.domain_id,
1012            &self.name,
1013            &self.namespace,
1014            &get_result_keyexpr,
1015            &get_result_type,
1016            type_hash,
1017        );
1018        let get_result_server = self
1019            .session
1020            .create_service(&get_result_info, QoSProfile::services_default())
1021            .map_err(|_| NodeError::ActionCreationFailed)?;
1022
1023        let feedback_type: heapless::String<256> =
1024            super::action_core::action_channel_type(type_name, "FeedbackMessage");
1025        let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
1026        let feedback_topic = Self::topic_info(
1027            self.domain_id,
1028            &self.name,
1029            &self.namespace,
1030            &feedback_keyexpr,
1031            &feedback_type,
1032            type_hash,
1033        );
1034        let feedback_publisher = self
1035            .session
1036            .create_publisher(&feedback_topic, QoSProfile::QOS_PROFILE_DEFAULT)
1037            .map_err(|_| NodeError::ActionCreationFailed)?;
1038
1039        let status_keyexpr: heapless::String<256> = action_info.status_key();
1040        let status_topic = Self::topic_info(
1041            self.domain_id,
1042            &self.name,
1043            &self.namespace,
1044            &status_keyexpr,
1045            "action_msgs::msg::dds_::GoalStatusArray_",
1046            type_hash,
1047        );
1048        let status_publisher = self
1049            .session
1050            .create_publisher(&status_topic, QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT)
1051            .map_err(|_| NodeError::ActionCreationFailed)?;
1052
1053        Ok(super::action_core::ActionServerCore {
1054            send_goal_server,
1055            cancel_goal_server,
1056            get_result_server,
1057            feedback_publisher,
1058            status_publisher,
1059            active_goals: heapless::Vec::new(),
1060            completed_results: heapless::Vec::new(),
1061            pending_get_results: heapless::Vec::new(),
1062            result_slab: [0u8; RESULT_BUF],
1063            result_slab_used: 0,
1064            goal_buffer: [0u8; GOAL_BUF],
1065            feedback_buffer: [0u8; FEEDBACK_BUF],
1066            cancel_buffer: [0u8; 256],
1067        })
1068    }
1069
1070    /// Typeless action client. Same shape as
1071    /// `create_action_server_raw` but builds the 3 service clients
1072    /// + 1 feedback subscriber, returns the raw `ActionClientCore`.
1073    pub fn create_action_client_raw(
1074        &mut self,
1075        action_name: &str,
1076        type_name: &str,
1077        type_hash: &str,
1078    ) -> Result<
1079        super::action_core::ActionClientCore<
1080            { crate::config::DEFAULT_RX_BUF_SIZE },
1081            { crate::config::DEFAULT_RX_BUF_SIZE },
1082            { crate::config::DEFAULT_RX_BUF_SIZE },
1083        >,
1084        NodeError,
1085    > {
1086        self.create_action_client_raw_sized::<
1087            { crate::config::DEFAULT_RX_BUF_SIZE },
1088            { crate::config::DEFAULT_RX_BUF_SIZE },
1089            { crate::config::DEFAULT_RX_BUF_SIZE },
1090        >(action_name, type_name, type_hash)
1091    }
1092
1093    /// Typeless action client with custom buffer sizes.
1094    pub fn create_action_client_raw_sized<
1095        const GOAL_BUF: usize,
1096        const RESULT_BUF: usize,
1097        const FEEDBACK_BUF: usize,
1098    >(
1099        &mut self,
1100        action_name: &str,
1101        type_name: &str,
1102        type_hash: &str,
1103    ) -> Result<super::action_core::ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>, NodeError>
1104    {
1105        let remapped = self.remapped(action_name);
1106        let action_name = remapped.as_deref().unwrap_or(action_name);
1107        let action_info = Self::action_info(self.domain_id, action_name, type_name, type_hash);
1108
1109        // Issue 0454 / phase-354 W3 — per-CHANNEL DDS type, not the bare
1110        // action type (see `action_channel_type`). These two `_raw_sized`
1111        // constructors are the last holders of the phase-338 W3 defect: the
1112        // type name is baked into the keyexpr, so `…Fibonacci_` never matches a
1113        // peer advertising `…Fibonacci_SendGoal_`.
1114        let send_goal_type: heapless::String<256> =
1115            super::action_core::action_channel_type(type_name, "SendGoal");
1116        let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
1117        let send_goal_info = Self::service_info(
1118            self.domain_id,
1119            &self.name,
1120            &self.namespace,
1121            &send_goal_keyexpr,
1122            &send_goal_type,
1123            type_hash,
1124        );
1125        let send_goal_client = self
1126            .session
1127            .create_client(&send_goal_info, QoSProfile::services_default())
1128            .map_err(|_| NodeError::ActionCreationFailed)?;
1129
1130        let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
1131        let cancel_goal_info = Self::service_info(
1132            self.domain_id,
1133            &self.name,
1134            &self.namespace,
1135            &cancel_goal_keyexpr,
1136            "action_msgs::srv::dds_::CancelGoal_",
1137            type_hash,
1138        );
1139        let cancel_goal_client = self
1140            .session
1141            .create_client(&cancel_goal_info, QoSProfile::services_default())
1142            .map_err(|_| NodeError::ActionCreationFailed)?;
1143
1144        let get_result_type: heapless::String<256> =
1145            super::action_core::action_channel_type(type_name, "GetResult");
1146        let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
1147        let get_result_info = Self::service_info(
1148            self.domain_id,
1149            &self.name,
1150            &self.namespace,
1151            &get_result_keyexpr,
1152            &get_result_type,
1153            type_hash,
1154        );
1155        let get_result_client = self
1156            .session
1157            .create_client(&get_result_info, QoSProfile::services_default())
1158            .map_err(|_| NodeError::ActionCreationFailed)?;
1159
1160        let feedback_type: heapless::String<256> =
1161            super::action_core::action_channel_type(type_name, "FeedbackMessage");
1162        let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
1163        let feedback_topic = Self::topic_info(
1164            self.domain_id,
1165            &self.name,
1166            &self.namespace,
1167            &feedback_keyexpr,
1168            &feedback_type,
1169            type_hash,
1170        );
1171        let feedback_subscriber = self
1172            .session
1173            .create_subscription(&feedback_topic, QoSProfile::BEST_EFFORT)
1174            .map_err(|_| NodeError::ActionCreationFailed)?;
1175
1176        Ok(super::action_core::ActionClientCore::new(
1177            send_goal_client,
1178            cancel_goal_client,
1179            get_result_client,
1180            feedback_subscriber,
1181        ))
1182    }
1183
1184    /// Create an action server.
1185    pub fn create_action_server<A: RosAction>(
1186        &mut self,
1187        action_name: &str,
1188    ) -> Result<ActionServer<A>, NodeError>
1189    where
1190        A::Goal: MessageForRmw,
1191        A::Result: MessageForRmw,
1192        A::Feedback: MessageForRmw,
1193        A::SendGoalRequest: MessageForRmw,
1194        A::SendGoalResponse: MessageForRmw,
1195        A::GetResultRequest: MessageForRmw,
1196        A::GetResultResponse: MessageForRmw,
1197        A::FeedbackMessage: MessageForRmw,
1198    {
1199        self.create_action_server_sized::<A, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, 4>(action_name)
1200    }
1201
1202    /// Create an action server with custom buffer sizes.
1203    pub fn create_action_server_sized<
1204        A: RosAction,
1205        const GOAL_BUF: usize,
1206        const RESULT_BUF: usize,
1207        const FEEDBACK_BUF: usize,
1208        const MAX_GOALS: usize,
1209    >(
1210        &mut self,
1211        action_name: &str,
1212    ) -> Result<ActionServer<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>, NodeError>
1213    where
1214        A::Goal: MessageForRmw,
1215        A::Result: MessageForRmw,
1216        A::Feedback: MessageForRmw,
1217        A::SendGoalRequest: MessageForRmw,
1218        A::SendGoalResponse: MessageForRmw,
1219        A::GetResultRequest: MessageForRmw,
1220        A::GetResultResponse: MessageForRmw,
1221        A::FeedbackMessage: MessageForRmw,
1222    {
1223        // Phase 212.K.7.6.b + K.7.7.c — register the three user-facing
1224        // message types AND the five action-protocol envelope types under
1225        // cyclonedds. No-op for other RMWs. The envelopes are needed
1226        // because the action service shapes (`*_SendGoal_Request`,
1227        // `*_GetResult_Response`, …) are the actual on-wire CDR types,
1228        // and the C++ Cyclone bridge auto-prepends a cdds_request_header_t
1229        // for any TYPE_NAME ending `_Request`/`_Response`/`_Reply`.
1230        register_type::<A::Goal>()?;
1231        register_type::<A::Result>()?;
1232        register_type::<A::Feedback>()?;
1233        register_type::<A::SendGoalRequest>()?;
1234        register_type::<A::SendGoalResponse>()?;
1235        register_type::<A::GetResultRequest>()?;
1236        register_type::<A::GetResultResponse>()?;
1237        register_type::<A::FeedbackMessage>()?;
1238        // issue #234 — also register the fixed `action_msgs` protocol types
1239        // (`CancelGoal_{Request,Response}`, `GoalStatusArray`) the cancel service
1240        // + status publisher created below serialize. They are not `RosAction`
1241        // associated types (they live in `action_msgs`, which `nros-core` cannot
1242        // name), so the generated `impl RosAction::register_protocol_types` — which
1243        // routes them through the generic `nros_rmw::register_type_descriptor` seam —
1244        // registers them. Without this the cancel_goal service + status publisher
1245        // have no Cyclone descriptor → `ActionCreationFailed`. The callback executor
1246        // path (`executor/action.rs`) already did this; this node.rs path — the one
1247        // `create_action_server` materialises through — did not.
1248        A::register_protocol_types().map_err(|()| NodeError::ActionCreationFailed)?;
1249        let remapped = self.remapped(action_name);
1250        let action_name = remapped.as_deref().unwrap_or(action_name);
1251        let action_info =
1252            Self::action_info(self.domain_id, action_name, A::ACTION_NAME, A::ACTION_HASH);
1253
1254        // Each underlying ServiceInfo / TopicInfo also carries the
1255        // node identity so the Zenoh shim declares a liveliness token
1256        // for it. Without `with_node_name` the shim's
1257        // `declare_entity_liveliness` short-circuits (`node_name.and_then`
1258        // → None) and `wait_for_action_server` has nothing to find.
1259        // Advertise the per-channel service / topic types ROS 2 matches on
1260        // (`<Action>_SendGoal` / `<Action>_GetResult` / `<Action>_FeedbackMessage`),
1261        // not the bare action type — see `action_core::action_service_base_type`.
1262        let send_goal_type = super::action_core::action_service_base_type(
1263            <A::SendGoalRequest as RosMessage>::TYPE_NAME,
1264            A::ACTION_NAME,
1265        );
1266        let get_result_type = super::action_core::action_service_base_type(
1267            <A::GetResultRequest as RosMessage>::TYPE_NAME,
1268            A::ACTION_NAME,
1269        );
1270        let feedback_type = <A::FeedbackMessage as RosMessage>::TYPE_NAME;
1271
1272        let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
1273        let send_goal_info = Self::service_info(
1274            self.domain_id,
1275            &self.name,
1276            &self.namespace,
1277            &send_goal_keyexpr,
1278            send_goal_type,
1279            A::SEND_GOAL_SERVICE_HASH,
1280        );
1281        let send_goal_server = self
1282            .session
1283            .create_service(&send_goal_info, QoSProfile::services_default())
1284            .map_err(|_| NodeError::ActionCreationFailed)?;
1285
1286        let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
1287        let cancel_goal_info = Self::service_info(
1288            self.domain_id,
1289            &self.name,
1290            &self.namespace,
1291            &cancel_goal_keyexpr,
1292            "action_msgs::srv::dds_::CancelGoal_",
1293            A::CANCEL_GOAL_SERVICE_HASH,
1294        );
1295        let cancel_goal_server = self
1296            .session
1297            .create_service(&cancel_goal_info, QoSProfile::services_default())
1298            .map_err(|_| NodeError::ActionCreationFailed)?;
1299
1300        let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
1301        let get_result_info = Self::service_info(
1302            self.domain_id,
1303            &self.name,
1304            &self.namespace,
1305            &get_result_keyexpr,
1306            get_result_type,
1307            A::GET_RESULT_SERVICE_HASH,
1308        );
1309        let get_result_server = self
1310            .session
1311            .create_service(&get_result_info, QoSProfile::services_default())
1312            .map_err(|_| NodeError::ActionCreationFailed)?;
1313
1314        let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
1315        let feedback_topic = Self::topic_info(
1316            self.domain_id,
1317            &self.name,
1318            &self.namespace,
1319            &feedback_keyexpr,
1320            feedback_type,
1321            <A::FeedbackMessage as RosMessage>::TYPE_HASH,
1322        );
1323        let feedback_publisher = self
1324            .session
1325            .create_publisher(&feedback_topic, QoSProfile::QOS_PROFILE_DEFAULT)
1326            .map_err(|_| NodeError::ActionCreationFailed)?;
1327
1328        let status_keyexpr: heapless::String<256> = action_info.status_key();
1329        let status_topic = Self::topic_info(
1330            self.domain_id,
1331            &self.name,
1332            &self.namespace,
1333            &status_keyexpr,
1334            "action_msgs::msg::dds_::GoalStatusArray_",
1335            A::STATUS_MESSAGE_HASH,
1336        );
1337        let status_publisher = self
1338            .session
1339            .create_publisher(&status_topic, QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT)
1340            .map_err(|_| NodeError::ActionCreationFailed)?;
1341
1342        Ok(ActionServer {
1343            core: super::action_core::ActionServerCore {
1344                send_goal_server,
1345                cancel_goal_server,
1346                get_result_server,
1347                feedback_publisher,
1348                status_publisher,
1349                active_goals: heapless::Vec::new(),
1350                completed_results: heapless::Vec::new(),
1351                pending_get_results: heapless::Vec::new(),
1352                result_slab: [0u8; RESULT_BUF],
1353                result_slab_used: 0,
1354                goal_buffer: [0u8; GOAL_BUF],
1355                feedback_buffer: [0u8; FEEDBACK_BUF],
1356                cancel_buffer: [0u8; 256],
1357            },
1358            typed_goals: heapless::Vec::new(),
1359            completed_goals: heapless::Vec::new(),
1360        })
1361    }
1362
1363    /// Create an action client.
1364    pub fn create_action_client<A: RosAction>(
1365        &mut self,
1366        action_name: &str,
1367    ) -> Result<ActionClient<A>, NodeError>
1368    where
1369        A::Goal: MessageForRmw,
1370        A::Result: MessageForRmw,
1371        A::Feedback: MessageForRmw,
1372        A::SendGoalRequest: MessageForRmw,
1373        A::SendGoalResponse: MessageForRmw,
1374        A::GetResultRequest: MessageForRmw,
1375        A::GetResultResponse: MessageForRmw,
1376        A::FeedbackMessage: MessageForRmw,
1377    {
1378        self.create_action_client_sized::<A, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }>(action_name)
1379    }
1380
1381    /// Create an action client with custom buffer sizes.
1382    pub fn create_action_client_sized<
1383        A: RosAction,
1384        const GOAL_BUF: usize,
1385        const RESULT_BUF: usize,
1386        const FEEDBACK_BUF: usize,
1387    >(
1388        &mut self,
1389        action_name: &str,
1390    ) -> Result<ActionClient<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>, NodeError>
1391    where
1392        A::Goal: MessageForRmw,
1393        A::Result: MessageForRmw,
1394        A::Feedback: MessageForRmw,
1395        A::SendGoalRequest: MessageForRmw,
1396        A::SendGoalResponse: MessageForRmw,
1397        A::GetResultRequest: MessageForRmw,
1398        A::GetResultResponse: MessageForRmw,
1399        A::FeedbackMessage: MessageForRmw,
1400    {
1401        // Phase 212.K.7.6.b + K.7.7.c — see `create_action_server_sized`.
1402        register_type::<A::Goal>()?;
1403        register_type::<A::Result>()?;
1404        register_type::<A::Feedback>()?;
1405        register_type::<A::SendGoalRequest>()?;
1406        register_type::<A::SendGoalResponse>()?;
1407        register_type::<A::GetResultRequest>()?;
1408        register_type::<A::GetResultResponse>()?;
1409        register_type::<A::FeedbackMessage>()?;
1410        // issue #234 — register the `action_msgs` protocol types the cancel-goal
1411        // service client below serializes (`CancelGoal_{Request,Response}`; the impl
1412        // also registers `GoalStatusArray`, harmlessly unused client-side) via the
1413        // generic seam. Without it the cancel_goal client has no Cyclone descriptor
1414        // → `ActionCreationFailed`. Mirrors the server path.
1415        A::register_protocol_types().map_err(|()| NodeError::ActionCreationFailed)?;
1416        let remapped = self.remapped(action_name);
1417        let action_name = remapped.as_deref().unwrap_or(action_name);
1418        let action_info =
1419            Self::action_info(self.domain_id, action_name, A::ACTION_NAME, A::ACTION_HASH);
1420
1421        // Mirror `create_action_server_sized`: thread node identity through
1422        // each underlying ServiceInfo / TopicInfo so the Zenoh shim
1423        // declares the matching client-side liveliness tokens (and so the
1424        // discovery wildcard built from `send_goal_info` ends up in the
1425        // same domain as the server's tokens).
1426        // Same per-channel typing as the server side so the client's requesters
1427        // and feedback reader match a real ROS 2 action server over DDS.
1428        let send_goal_type = super::action_core::action_service_base_type(
1429            <A::SendGoalRequest as RosMessage>::TYPE_NAME,
1430            A::ACTION_NAME,
1431        );
1432        let get_result_type = super::action_core::action_service_base_type(
1433            <A::GetResultRequest as RosMessage>::TYPE_NAME,
1434            A::ACTION_NAME,
1435        );
1436        let feedback_type = <A::FeedbackMessage as RosMessage>::TYPE_NAME;
1437
1438        let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
1439        let send_goal_info = Self::service_info(
1440            self.domain_id,
1441            &self.name,
1442            &self.namespace,
1443            &send_goal_keyexpr,
1444            send_goal_type,
1445            A::SEND_GOAL_SERVICE_HASH,
1446        );
1447        let send_goal_client = self
1448            .session
1449            .create_client(&send_goal_info, QoSProfile::services_default())
1450            .map_err(|_| NodeError::ActionCreationFailed)?;
1451
1452        let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
1453        let cancel_goal_info = Self::service_info(
1454            self.domain_id,
1455            &self.name,
1456            &self.namespace,
1457            &cancel_goal_keyexpr,
1458            "action_msgs::srv::dds_::CancelGoal_",
1459            A::CANCEL_GOAL_SERVICE_HASH,
1460        );
1461        let cancel_goal_client = self
1462            .session
1463            .create_client(&cancel_goal_info, QoSProfile::services_default())
1464            .map_err(|_| NodeError::ActionCreationFailed)?;
1465
1466        let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
1467        let get_result_info = Self::service_info(
1468            self.domain_id,
1469            &self.name,
1470            &self.namespace,
1471            &get_result_keyexpr,
1472            get_result_type,
1473            A::GET_RESULT_SERVICE_HASH,
1474        );
1475        let get_result_client = self
1476            .session
1477            .create_client(&get_result_info, QoSProfile::services_default())
1478            .map_err(|_| NodeError::ActionCreationFailed)?;
1479
1480        let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
1481        let feedback_topic = Self::topic_info(
1482            self.domain_id,
1483            &self.name,
1484            &self.namespace,
1485            &feedback_keyexpr,
1486            feedback_type,
1487            <A::FeedbackMessage as RosMessage>::TYPE_HASH,
1488        );
1489        let feedback_subscriber = self
1490            .session
1491            .create_subscription(&feedback_topic, QoSProfile::BEST_EFFORT)
1492            .map_err(|_| NodeError::ActionCreationFailed)?;
1493
1494        Ok(ActionClient {
1495            core: super::action_core::ActionClientCore {
1496                send_goal_client,
1497                cancel_goal_client,
1498                get_result_client,
1499                feedback_subscriber,
1500                goal_buffer: [0u8; GOAL_BUF],
1501                result_buffer: [0u8; RESULT_BUF],
1502                feedback_buffer: [0u8; FEEDBACK_BUF],
1503                goal_counter: 0,
1504                in_flight_send_goal: false,
1505                in_flight_cancel: false,
1506                in_flight_get_result: false,
1507                pending_send_goal: super::action_core::ActionRequests::new(),
1508                pending_cancel: super::action_core::ActionRequests::new(),
1509                pending_get_result: super::action_core::ActionRequests::new(),
1510            },
1511            _phantom: PhantomData,
1512        })
1513    }
1514}
1515
1516// ===================================================================
1517// Phase 189.M1 — entity builders (the `clone` tier)
1518// ===================================================================
1519
1520/// Publisher builder — `node.publisher(topic)`. Choose `.typed::<M>()` or
1521/// `.generic(type, hash)`, optionally `.qos(..)`, then `.build()`.
1522pub struct PublisherBuilder<'n, 'a, 't> {
1523    node: &'n mut NodeHandle<'a>,
1524    topic: &'t str,
1525    qos: QoSProfile,
1526}
1527
1528impl<'n, 'a, 't> PublisherBuilder<'n, 'a, 't> {
1529    /// Set the QoS (also settable on the typed/generic builder).
1530    pub fn qos(mut self, qos: QoSProfile) -> Self {
1531        self.qos = qos;
1532        self
1533    }
1534
1535    /// Mark this publisher "express": its samples bypass
1536    /// transport tx batching (sent immediately even when the batching knob is
1537    /// on). For control-tier / latency-sensitive topics.
1538    pub fn tx_express(mut self, express: bool) -> Self {
1539        self.qos.tx_express = express;
1540        self
1541    }
1542
1543    /// Typed publisher for a ROS message `M` (mirrors rclcpp/rclrs).
1544    pub fn typed<M: MessageForRmw>(self) -> TypedPublisherBuilder<'n, 'a, 't, M> {
1545        TypedPublisherBuilder {
1546            node: self.node,
1547            topic: self.topic,
1548            qos: self.qos,
1549            _phantom: PhantomData,
1550        }
1551    }
1552
1553    /// Generic (type-erased) publisher — the rclcpp `create_generic_publisher`
1554    /// form; raw CDR bytes via `publish_raw`.
1555    pub fn generic(
1556        self,
1557        type_name: &'t str,
1558        type_hash: &'t str,
1559    ) -> GenericPublisherBuilder<'n, 'a, 't> {
1560        GenericPublisherBuilder {
1561            node: self.node,
1562            topic: self.topic,
1563            type_name,
1564            type_hash,
1565            qos: self.qos,
1566        }
1567    }
1568}
1569
1570/// Typed publisher builder (`.typed::<M>()`).
1571pub struct TypedPublisherBuilder<'n, 'a, 't, M> {
1572    node: &'n mut NodeHandle<'a>,
1573    topic: &'t str,
1574    qos: QoSProfile,
1575    _phantom: PhantomData<M>,
1576}
1577
1578impl<'n, 'a, 't, M: MessageForRmw> TypedPublisherBuilder<'n, 'a, 't, M> {
1579    pub fn qos(mut self, qos: QoSProfile) -> Self {
1580        self.qos = qos;
1581        self
1582    }
1583
1584    /// See [`PublisherBuilder::tx_express`].
1585    pub fn tx_express(mut self, express: bool) -> Self {
1586        self.qos.tx_express = express;
1587        self
1588    }
1589
1590    pub fn build(self) -> Result<EmbeddedPublisher<M>, NodeError> {
1591        self.node
1592            .create_publisher_with_qos::<M>(self.topic, self.qos)
1593    }
1594}
1595
1596/// Generic (type-erased) publisher builder (`.generic(type, hash)`).
1597pub struct GenericPublisherBuilder<'n, 'a, 't> {
1598    node: &'n mut NodeHandle<'a>,
1599    topic: &'t str,
1600    type_name: &'t str,
1601    type_hash: &'t str,
1602    qos: QoSProfile,
1603}
1604
1605impl<'n, 'a, 't> GenericPublisherBuilder<'n, 'a, 't> {
1606    pub fn qos(mut self, qos: QoSProfile) -> Self {
1607        self.qos = qos;
1608        self
1609    }
1610
1611    /// See [`PublisherBuilder::tx_express`].
1612    pub fn tx_express(mut self, express: bool) -> Self {
1613        self.qos.tx_express = express;
1614        self
1615    }
1616
1617    pub fn build(self) -> Result<crate::executor::handles::EmbeddedRawPublisher, NodeError> {
1618        self.node.create_publisher_raw_with_qos(
1619            self.topic,
1620            self.type_name,
1621            self.type_hash,
1622            self.qos,
1623        )
1624    }
1625}
1626
1627// ============================================================================
1628// Phase 273 (RFC-0047) — CallbackGroup token (rclcpp/rclrs shape)
1629// ============================================================================
1630
1631/// A first-class callback group — a **name-only token** (rclcpp/rclrs shape).
1632///
1633/// Created via [`Node::create_callback_group`].  Passed to the `_in`
1634/// entity-create variants (`create_timer_in_group`, `create_subscription_in_group`,
1635/// `create_publisher_in_group`) to label entities with a group name.
1636///
1637/// The group is just a name — the actual `SchedContext` binding is seeded at
1638/// boot by `Executor::bind_group_sched` (from `system.toml group_tasks`, phase
1639/// 273 W2) and resolved at entity-registration time by
1640/// `apply_node_default_sched`.  No concurrency type (Mutually-
1641/// Exclusive vs Reentrant) is stored here — that is an open follow-up.
1642pub struct CallbackGroup {
1643    name: heapless::String<32>,
1644}
1645
1646impl CallbackGroup {
1647    /// The group name (e.g. `"ctrl"`, `"telem"`).
1648    pub fn name(&self) -> &str {
1649        &self.name
1650    }
1651}
1652
1653/// A ROS 2 node — rclrs's `Node`, and the ONE node type.
1654///
1655/// `Executor::create_node(name)` returns it, and so does
1656/// `Executor::node_mut(id)`; a component and a standalone program hold the
1657/// same type. It carries rclrs's methods — `create_publisher`,
1658/// `create_subscription(topic, callback)`, `create_service`, timers, the
1659/// clock, `name` / `namespace` / `logger`, the graph queries — plus RTOS
1660/// extensions with names of their own (`create_polling_*`, the `_sized` and
1661/// `_raw` constructors).
1662///
1663/// ADOPT-BOUNDED: a node is a short-lived `&mut Executor` borrow, not rclrs's `Arc<Node>`.
1664/// Create entities, then drop it before acquiring the next node handle; entity
1665/// handles (`HandleId`, publishers) are owned and outlive it (no allocator —
1666/// see `docs/design/0022-entity-api-tiers.md` §Borrow model).
1667pub struct Node<'e, 's> {
1668    executor: &'e mut super::spin::Executor<'s>,
1669    node_id: super::node_record::NodeId,
1670}
1671
1672// ============================================================================
1673// Parameters -- the node is the receiver (phase-515 R10)
1674// ============================================================================
1675//
1676// rclrs keeps parameter verbs on the node; ours were on the `Executor`, as a
1677// `_on(NodeId, ...)` form plus a bare form meaning the primary node, because
1678// the store is one table the executor owns (phase-426 W1). The store did not
1679// move -- these forward to the `_on` forms with this node's id -- but the
1680// RECEIVER a user writes is the node, as upstream's is, and the executor's
1681// bare forms are deprecated. Executor-wide verbs (`register_parameter_services`,
1682// `params`, `install_argv_params`, `flush_parameter_events`) stay there.
1683#[cfg(feature = "param-store")]
1684impl<'e, 's> Node<'e, 's> {
1685    /// rclrs's `Node::declare_parameter::<T>(name)`: a [`ParameterBuilder`]
1686    /// whose terminal (`mandatory` / `optional` / `read_only`) declares it.
1687    ///
1688    /// ADOPT-BOUNDED: returns `Result`, where rclrs's builder cannot fail. The
1689    /// store is created on first use; `Err(NodeError::NotInitialized)` means the
1690    /// platform heap refused it, which has to be reported.
1691    ///
1692    /// [`ParameterBuilder`]: nros_params::ParameterBuilder
1693    pub fn declare_parameter<'a, T: nros_params::ParameterVariant>(
1694        &'a mut self,
1695        name: &'a str,
1696    ) -> Result<nros_params::ParameterBuilder<'a, 's, T>, NodeError> {
1697        self.executor.parameter_on(self.node_id, name)
1698    }
1699
1700    /// rclrs's `Node::use_undeclared_parameters()`: read and write any name,
1701    /// declared or not.
1702    pub fn use_undeclared_parameters(
1703        &mut self,
1704    ) -> Result<nros_params::Parameters<'_, 's>, NodeError> {
1705        self.executor.use_undeclared_parameters_on(self.node_id)
1706    }
1707
1708    /// Declare `name` with `value` and a descriptor -- rclcpp's
1709    /// `declare_parameter(name, value, descriptor)`. `false` if it exists, the
1710    /// table is full, or the value is outside the descriptor's range.
1711    pub fn declare_parameter_with_descriptor(
1712        &mut self,
1713        name: &str,
1714        value: nros_params::ParameterValue,
1715        descriptor: nros_params::ParameterDescriptor,
1716    ) -> bool {
1717        // Issue 2670 -- this route is Rust code's own; the `_on` form below is
1718        // shared with the C++ shim, which records through its own hook.
1719        self.executor.observe_code_parameter_declare(
1720            self.node_id,
1721            name,
1722            Some(&value),
1723            value.param_type(),
1724        );
1725        self.executor
1726            .declare_parameter_with_descriptor_on(self.node_id, name, value, descriptor)
1727    }
1728
1729    /// The current value of `name`, if declared.
1730    pub fn get_parameter(&self, name: &str) -> Option<&nros_params::ParameterValue> {
1731        self.executor.get_parameter_on(self.node_id, name)
1732    }
1733
1734    /// Set `name`, through the same rules a remote set obeys.
1735    pub fn set_parameter(
1736        &mut self,
1737        name: &str,
1738        value: nros_params::ParameterValue,
1739    ) -> Result<(), nros_params::ParameterError> {
1740        self.executor.set_parameter_on(self.node_id, name, value)
1741    }
1742
1743    /// Set several parameters all-or-nothing -- rclcpp's
1744    /// `set_parameters_atomically`.
1745    pub fn set_parameters_atomically<'x, I>(
1746        &mut self,
1747        items: I,
1748    ) -> Result<(), nros_params::ParameterError>
1749    where
1750        I: Iterator<Item = Option<(&'x str, nros_params::ParameterValue)>> + Clone,
1751    {
1752        self.executor
1753            .set_parameters_atomically_on(self.node_id, items)
1754    }
1755
1756    /// Remove a declared parameter -- rclcpp's `undeclare_parameter`.
1757    pub fn undeclare_parameter(&mut self, name: &str) -> bool {
1758        self.executor.undeclare_parameter_on(self.node_id, name)
1759    }
1760
1761    /// Whether a REMOTE set may create a name that was never declared.
1762    pub fn allow_undeclared_parameters(&mut self, allow: bool) {
1763        self.executor
1764            .allow_undeclared_parameters_on(self.node_id, allow)
1765    }
1766
1767    /// The descriptor of `name` -- rclcpp's `describe_parameter`.
1768    pub fn describe_parameter(&self, name: &str) -> Option<&nros_params::ParameterDescriptor> {
1769        self.executor.describe_parameter_on(self.node_id, name)
1770    }
1771
1772    /// The type of `name` -- rclcpp's `get_parameter_type`.
1773    pub fn get_parameter_type(&self, name: &str) -> Option<nros_params::ParameterType> {
1774        self.executor.get_parameter_type_on(self.node_id, name)
1775    }
1776
1777    /// The names of this node's parameters under `prefix` -- rclcpp's
1778    /// `list_parameters`, as an iterator rather than an allocated list.
1779    pub fn list_parameters<'p>(&'p self, prefix: &'p str) -> impl Iterator<Item = &'p str> {
1780        self.executor.list_parameters_on(self.node_id, prefix)
1781    }
1782
1783    /// Set the descriptor's description and constraint text.
1784    pub fn set_parameter_description(
1785        &mut self,
1786        name: &str,
1787        description: &str,
1788        additional_constraints: &str,
1789    ) -> bool {
1790        self.executor.set_parameter_description_on(
1791            self.node_id,
1792            name,
1793            description,
1794            additional_constraints,
1795        )
1796    }
1797
1798    /// Make `name` read-only (or writable again).
1799    pub fn set_parameter_read_only(&mut self, name: &str, read_only: bool) -> bool {
1800        self.executor
1801            .set_parameter_read_only_on(self.node_id, name, read_only)
1802    }
1803
1804    /// Constrain an integer parameter to `[min, max]` in steps of `step`.
1805    pub fn set_parameter_integer_range(
1806        &mut self,
1807        name: &str,
1808        min: i64,
1809        max: i64,
1810        step: i64,
1811    ) -> bool {
1812        self.executor
1813            .set_parameter_integer_range_on(self.node_id, name, min, max, step)
1814    }
1815
1816    /// Constrain a floating-point parameter to `[min, max]` in steps of `step`.
1817    pub fn set_parameter_float_range(&mut self, name: &str, min: f64, max: f64, step: f64) -> bool {
1818        self.executor
1819            .set_parameter_float_range_on(self.node_id, name, min, max, step)
1820    }
1821
1822    /// rclcpp's `add_on_set_parameters_callback`: `callback` may refuse a write
1823    /// to this node's parameters.
1824    pub fn add_on_set_parameters_callback(
1825        &mut self,
1826        callback: nros_params::OnSetParameterFn,
1827        ctx: nros_params::OnSetContext,
1828    ) -> Option<nros_params::OnSetParameterHandle> {
1829        self.executor
1830            .add_on_set_parameters_callback_on(self.node_id, callback, ctx)
1831    }
1832
1833    /// rclcpp's `remove_on_set_parameters_callback`.
1834    pub fn remove_on_set_parameters_callback(
1835        &mut self,
1836        handle: nros_params::OnSetParameterHandle,
1837    ) -> bool {
1838        self.executor.remove_on_set_parameters_callback(handle)
1839    }
1840
1841    // phase-515 R10 stage 1b -- the rest of the per-node parameter surface,
1842    // which only the executor's node-id-keyed forms carried before those moved
1843    // behind `ExecutorFfi`.
1844
1845    /// The `-p` / `--params-file` overrides that apply to this node, one per
1846    /// name — rclcpp's `NodeParametersInterface::get_parameter_overrides()`.
1847    #[cfg(feature = "alloc")]
1848    pub fn argv_param_overrides(
1849        &self,
1850    ) -> impl Iterator<Item = (&str, nros_params::ParameterValue)> + '_ {
1851        self.executor.argv_param_overrides_on(self.node_id)
1852    }
1853
1854    /// [`argv_param_overrides`](Self::argv_param_overrides), one call of `f`
1855    /// per override with the value borrowed; returns how many there were.
1856    #[cfg(feature = "alloc")]
1857    pub fn for_each_argv_param_override(
1858        &self,
1859        f: impl FnMut(&str, &nros_params::ParameterValue),
1860    ) -> usize {
1861        self.executor
1862            .for_each_argv_param_override_on(self.node_id, f)
1863    }
1864
1865    /// rclc's LOCAL typed set: type and on-set hooks are checked, read-only
1866    /// and range are not (rclc's owner of a parameter is not bound by them).
1867    pub fn set_parameter_local(
1868        &mut self,
1869        name: &str,
1870        value: nros_params::ParameterValue,
1871    ) -> Result<(), nros_params::ParameterError> {
1872        self.executor
1873            .set_parameter_local_on(self.node_id, name, value)
1874    }
1875
1876    /// Publish no `/parameter_events` for this node (rclcpp's
1877    /// `start_parameter_event_publisher(false)`).
1878    #[cfg(feature = "param-services")]
1879    pub fn disable_parameter_events(&mut self) {
1880        self.executor.disable_parameter_events_on(self.node_id)
1881    }
1882
1883    /// Publish this node's parameter changes on `/parameter_events`.
1884    #[cfg(feature = "param-services")]
1885    pub fn enable_parameter_events(&mut self) -> Result<(), NodeError> {
1886        self.executor.enable_parameter_events_on(self.node_id)
1887    }
1888
1889    /// A remote `NOT_SET` deletes the parameter (rclc) instead of being
1890    /// refused (rclcpp).
1891    pub fn delete_parameters_on_not_set(&mut self, on: bool) {
1892        self.executor
1893            .delete_parameters_on_not_set_on(self.node_id, on)
1894    }
1895
1896    /// [`set_parameters_atomically`](Self::set_parameters_atomically) with
1897    /// element `i` filled into one scratch value by `fill(i, slot)`.
1898    pub fn set_parameters_atomically_with<'x>(
1899        &mut self,
1900        count: usize,
1901        fill: impl FnMut(usize, &mut nros_params::ParameterValue) -> Option<&'x str>,
1902    ) -> Result<(), nros_params::ParameterError> {
1903        self.executor
1904            .set_parameters_atomically_with_on(self.node_id, count, fill)
1905    }
1906}
1907
1908impl<'e, 's> Node<'e, 's> {
1909    pub(crate) fn new(
1910        executor: &'e mut super::spin::Executor<'s>,
1911        node_id: super::node_record::NodeId,
1912    ) -> Self {
1913        Self { executor, node_id }
1914    }
1915
1916    /// The node's name — rclrs's `Node::name()`.
1917    ///
1918    /// Read from the executor's node table, where the name the
1919    /// node was created with (or the launch file's override of it) lives.
1920    #[must_use]
1921    pub fn name(&self) -> &str {
1922        self.executor
1923            .node(self.node_id)
1924            .map(|r| r.name.as_str())
1925            .unwrap_or("")
1926    }
1927
1928    /// The node's namespace — rclrs's `Node::namespace()`. `""` is the root.
1929    #[must_use]
1930    pub fn namespace(&self) -> &str {
1931        self.executor
1932            .node(self.node_id)
1933            .map(|r| r.namespace.as_str())
1934            .unwrap_or("")
1935    }
1936
1937    /// `/<namespace>/<name>` — rclrs's `Node::fully_qualified_name()`.
1938    ///
1939    /// Bounded, where rclrs returns a `String`: no allocator here, and the
1940    /// two halves are each at most 64 bytes.
1941    pub fn fully_qualified_name(&self) -> Result<crate::names::ResolvedName, NodeError> {
1942        crate::names::fully_qualified_name(self.name(), self.namespace())
1943            .map_err(|()| NodeError::NameTooLong)
1944    }
1945
1946    /// The node's ROS domain — rclrs's `Node::domain_id()`. Every node of an
1947    /// executor shares its session, so this is the executor's domain.
1948    #[must_use]
1949    pub fn domain_id(&self) -> u32 {
1950        self.executor.domain_id
1951    }
1952
1953    /// The logger named for this node — rclrs's `Node::logger()`. See
1954    /// [`NodeHandle::logger`] for how the name is resolved.
1955    #[must_use]
1956    pub fn logger(&self) -> &'static nros_log::Logger {
1957        nros_log::resolve_node_logger(self.name())
1958    }
1959
1960    /// The executor this node borrows — for the `nros` facade's declarative
1961    /// constructors, which register into it. Not a user API.
1962    #[doc(hidden)]
1963    pub fn __executor(&mut self) -> &mut super::spin::Executor<'s> {
1964        self.executor
1965    }
1966
1967    /// This node's id in the executor's node table — an RTOS extension, for
1968    /// the APIs that address a node by id (`Executor::node_mut`, the
1969    /// per-node QoS override table).
1970    #[must_use]
1971    pub fn id(&self) -> super::node_record::NodeId {
1972        self.node_id
1973    }
1974
1975    /// The node's clock — rclrs's `Node::get_clock()`, and rclcpp's.
1976    ///
1977    /// `cpp:Node::get_clock` had shipped for a long time and
1978    /// only the Rust node lacked the accessor: a component reached the clock
1979    /// through the executor, or constructed one, and the ported line
1980    /// `node.get_clock().now()` had nothing to bind.
1981    ///
1982    /// **A delegation, not a second clock.** [`nros_core::clock::Clock`] is a
1983    /// one-field value naming a time SOURCE — it holds no state of its own, and
1984    /// `now()` on a ROS-time clock reads the process-global override that
1985    /// `install_ros_time_source` installs. So
1986    /// this returns the same answer as the executor's clock by construction
1987    /// rather than by agreement, which is the property the graph forwarders in
1988    /// this family are shaped for.
1989    ///
1990    /// ROS TIME, as rclcpp's and rclrs's node clocks are: with a `/clock`
1991    /// source installed it follows the simulator, and with none it reads the
1992    /// same wall clock `Clock::system()` does (the two share one
1993    /// expression). A component that specifically wants the monotonic source
1994    /// asks for `Clock::steady()`.
1995    ///
1996    /// By VALUE, where rclcpp hands back a `Clock::SharedPtr`: there is no
1997    /// allocator here and the type is `Copy`, so a handle would be
1998    /// a pointer to one `u8`.
1999    pub fn get_clock(&self) -> nros_core::clock::Clock {
2000        nros_core::clock::Clock::ros_time()
2001    }
2002
2003    /// Subscription builder (the `clone` tier). Pick a mode with `.typed::<M>()`
2004    /// or `.generic(type, hash)`, set knobs (`.qos`), then `.build(callback)`.
2005    pub fn subscription<'t>(&mut self, topic: &'t str) -> SubscriptionBuilder<'_, 'e, 't, 's> {
2006        SubscriptionBuilder {
2007            ctx: self,
2008            topic,
2009            qos: QoSProfile::default(),
2010        }
2011    }
2012
2013    /// Publisher builder (the `clone` tier), symmetric with
2014    /// [`subscription`](Self::subscription). Pick `.typed::<M>()` or
2015    /// `.generic(type, hash)`, set `.qos()`, then `.build()`. The returned
2016    /// publisher handle is owned and outlives this `Node` — the bridge
2017    /// builds the dest publisher on one ctx, drops it, then registers the
2018    /// source subscription on another (see `0022-entity-api-tiers.md`).
2019    pub fn publisher<'t>(&mut self, topic: &'t str) -> CtxPublisherBuilder<'_, 'e, 't, 's> {
2020        CtxPublisherBuilder {
2021            ctx: self,
2022            topic,
2023            qos: QoSProfile::default(),
2024        }
2025    }
2026
2027    /// Convenient typed publisher (the `fork` tier — rclcpp/rclrs shape).
2028    ///
2029    /// Takes rclrs's `impl IntoPrimitiveOptions`: a bare
2030    /// topic name (default QoS) or one with QoS steps chained on,
2031    /// `"chatter".keep_last(10).reliable()`.
2032    pub fn create_publisher<'o, M: MessageForRmw>(
2033        &mut self,
2034        options: impl crate::IntoPrimitiveOptions<'o>,
2035    ) -> Result<EmbeddedPublisher<M>, NodeError> {
2036        let options = options.into_primitive_options();
2037        self.create_publisher_with_qos::<M>(options.name, options.resolve(QoSProfile::default()))
2038    }
2039
2040    /// Convenient generic (type-erased) publisher — rclcpp `create_generic_*`.
2041    pub fn create_generic_publisher(
2042        &mut self,
2043        topic: &str,
2044        type_name: &str,
2045        type_hash: &str,
2046    ) -> Result<crate::executor::handles::EmbeddedRawPublisher, NodeError> {
2047        self.create_generic_publisher_with_qos(topic, type_name, type_hash, QoSProfile::default())
2048    }
2049
2050    /// The same, with an explicit profile. The declarative
2051    /// component path needs it: a node that declares
2052    /// `create_publisher_for_topic_with_qos(...)` carries its profile in
2053    /// `EntityMetadata::qos`, and the runtime used to drop it on the floor by
2054    /// calling the default-QoS constructor here.
2055    pub fn create_generic_publisher_with_qos(
2056        &mut self,
2057        topic: &str,
2058        type_name: &str,
2059        type_hash: &str,
2060        qos: QoSProfile,
2061    ) -> Result<crate::executor::handles::EmbeddedRawPublisher, NodeError> {
2062        self.executor
2063            .create_publisher_raw_on(self.node_id, topic, type_name, type_hash, qos)
2064    }
2065
2066    /// Convenient typed subscription (the `fork` tier — rclcpp/rclrs shape).
2067    /// Sugar over the builder with default QoS + buffer.
2068    ///
2069    /// `options` is rclrs's `impl IntoPrimitiveOptions`, as on
2070    /// [`create_publisher`](Self::create_publisher). ADOPT-BOUNDED (subscription):
2071    /// returns the entity's `HandleId`, not an owned rclrs `Subscription` — the
2072    /// entity lives in the executor's table, and the id is what cancels it.
2073    pub fn create_subscription<'o, M, F>(
2074        &mut self,
2075        options: impl crate::IntoPrimitiveOptions<'o>,
2076        callback: F,
2077    ) -> Result<super::types::HandleId, NodeError>
2078    where
2079        M: MessageForRmw + 'static,
2080        F: FnMut(&M) + 'static,
2081    {
2082        let options = options.into_primitive_options();
2083        self.executor
2084            .register_subscription_buffered_on::<M, F, { crate::config::DEFAULT_RX_BUF_SIZE }>(
2085                self.node_id,
2086                options.name,
2087                options.resolve(QoSProfile::default()),
2088                callback,
2089                None, // no group — node default
2090                None, // phase-403 W2: the configured default, unchanged
2091            )
2092    }
2093
2094    /// Subscribe `/clock` and install every sample as this image's ROS time —
2095    /// the thing `rclcpp`'s `use_sim_time` parameter switches on.
2096    ///
2097    /// After this, `Clock::ros_time().now()` is the simulator's or the bag
2098    /// player's time, and a timer registered with `TimerClockSource::Ros`
2099    /// follows it: it stops while the simulation is paused and tracks the replay
2100    /// rate. Nothing else changes — a wall timer on the same executor keeps its
2101    /// own cadence, which is what a watchdog needs.
2102    ///
2103    /// QoS is `QoSProfile::clock_default()`, i.e. `rclcpp::ClockQoS`: best
2104    /// effort, keep-last 1, volatile. A late subscriber wants the NEXT sample,
2105    /// not a replay of the simulation's history.
2106    ///
2107    /// Returns the subscription handle. Cancelling it stops the source but does
2108    /// NOT clear the override: a node that unsubscribes mid-run keeps the last
2109    /// simulated time rather than jumping back to the wall clock, which every
2110    /// ROS-time timer would otherwise have to absorb as a jump.
2111    ///
2112    /// The override is process-global — one simulated clock per image — so
2113    /// calling this on a second node in the same image adds a second subscriber
2114    /// to the same global, which is redundant rather than wrong.
2115    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
2116    pub fn install_ros_time_source(&mut self) -> Result<super::types::HandleId, NodeError> {
2117        self.install_ros_time_source_on(crate::time_source::CLOCK_TOPIC)
2118    }
2119
2120    /// [`install_ros_time_source`](Self::install_ros_time_source) against a
2121    /// topic other than `/clock` — a remapped or namespaced clock, which is what
2122    /// a launch file creates when two simulations share a graph.
2123    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
2124    pub fn install_ros_time_source_on(
2125        &mut self,
2126        topic: &str,
2127    ) -> Result<super::types::HandleId, NodeError> {
2128        // One spelling of the QoS and the sample conversion, on the executor:
2129        // the `use_sim_time` reconciliation (phase-425 W3b) installs the same
2130        // subscription, and two copies would be two places for the QoS to drift.
2131        self.executor.install_ros_time_source(self.node_id, topic)
2132    }
2133
2134    // -----------------------------------------------------------------------
2135    // Phase 273 (RFC-0047) — callback-group API (rclcpp/rclrs shape)
2136    // -----------------------------------------------------------------------
2137
2138    /// Create a named callback group — a thin token wrapping the group name.
2139    ///
2140    /// Pass the returned [`CallbackGroup`] to the `_in` create variants
2141    /// (`create_timer_in_group`, `create_subscription_in_group`, `create_publisher_in_group`)
2142    /// to label entities with this group. The executor binds the entity's
2143    /// callback to the `SchedContext` seeded via `bind_group_sched` for
2144    /// `(node_name, namespace, group_name)`.
2145    ///
2146    /// ```ignore
2147    /// let ctrl = node.create_callback_group("ctrl");
2148    /// node.create_timer_in_group(&ctrl, TimerDuration::from_millis(10), || { /* … */ })?;
2149    /// ```
2150    ///
2151    /// Names longer than 32 bytes are silently truncated.
2152    pub fn create_callback_group(&self, name: &str) -> CallbackGroup {
2153        let mut s = heapless::String::<32>::new();
2154        // Silently truncate if the name is too long (defensive; caller
2155        // should use short ASCII group names like "ctrl"/"telem").
2156        for ch in name.chars() {
2157            if s.push(ch).is_err() {
2158                break;
2159            }
2160        }
2161        CallbackGroup { name: s }
2162    }
2163
2164    /// Create a repeating timer **in** a callback group (rclcpp shape).
2165    ///
2166    /// The timer's callback is bound to the `SchedContext` associated with
2167    /// `group` in the executor's `group_sched_table` for this node. If no
2168    /// entry was seeded for the group, the node's default `SchedContext` applies
2169    /// (same as `register_timer`). `period` fires the callback repeatedly.
2170    pub fn create_timer_in_group<F>(
2171        &mut self,
2172        group: &CallbackGroup,
2173        period: crate::timer::TimerDuration,
2174        callback: F,
2175    ) -> Result<super::types::HandleId, NodeError>
2176    where
2177        F: FnMut() + 'static,
2178    {
2179        self.executor
2180            .register_timer_on(Some(self.node_id), period, callback, Some(group.name()))
2181    }
2182
2183    /// rclrs's `create_timer_repeating(period, callback)`.
2184    ///
2185    /// Fires `callback` every `period`, on this node's default `SchedContext`.
2186    /// rclrs 0.7.0 settled on the same three timer modes ours carries
2187    /// (repeating, one-shot, inert); these three verbs are its spelling of
2188    /// them. `period` is a [`TimerDuration`](crate::timer::TimerDuration) or a
2189    /// `core::time::Duration`.
2190    ///
2191    /// ADOPT-BOUNDED: returns the timer's [`HandleId`](super::types::HandleId),
2192    /// not an rclrs `Timer` object — the timer lives in the executor's static
2193    /// table, so `Executor::cancel_timer` / `reset_timer` / `timer_period_ms`
2194    /// take that id. No `IntoTimerOptions` (a clock choice is
2195    /// [`create_timer_on_clock`](Self::create_timer_on_clock)).
2196    pub fn create_timer_repeating<F>(
2197        &mut self,
2198        period: impl Into<crate::timer::TimerDuration>,
2199        callback: F,
2200    ) -> Result<super::types::HandleId, NodeError>
2201    where
2202        F: FnMut() + 'static,
2203    {
2204        self.executor.register_timer_entry(
2205            Some(self.node_id),
2206            period.into(),
2207            super::TimerClockSource::Steady,
2208            false,
2209            None,
2210            callback,
2211        )
2212    }
2213
2214    /// rclrs's `create_timer_oneshot(period, callback)`.
2215    ///
2216    /// Fires `callback` once, `period` after creation, then goes inert;
2217    /// `Executor::reset_timer` re-arms it for one more shot. Same envelope as
2218    /// [`create_timer_repeating`](Self::create_timer_repeating).
2219    pub fn create_timer_oneshot<F>(
2220        &mut self,
2221        period: impl Into<crate::timer::TimerDuration>,
2222        callback: F,
2223    ) -> Result<super::types::HandleId, NodeError>
2224    where
2225        F: FnMut() + 'static,
2226    {
2227        self.executor.register_timer_entry(
2228            Some(self.node_id),
2229            period.into(),
2230            super::TimerClockSource::Steady,
2231            true,
2232            None,
2233            callback,
2234        )
2235    }
2236
2237    /// rclrs's `create_timer_inert(period, callback)`.
2238    ///
2239    /// Creates the timer without starting it (rcl's `autostart = false`): it
2240    /// never fires until `Executor::reset_timer` starts it, after which it
2241    /// repeats every `period`. ADOPT-BOUNDED beyond
2242    /// [`create_timer_repeating`](Self::create_timer_repeating)'s envelope:
2243    /// rclrs can later switch an inert timer to one-shot; ours starts as a
2244    /// repeating timer, and a one-shot is created with
2245    /// [`create_timer_oneshot`](Self::create_timer_oneshot) instead.
2246    pub fn create_timer_inert<F>(
2247        &mut self,
2248        period: impl Into<crate::timer::TimerDuration>,
2249        callback: F,
2250    ) -> Result<super::types::HandleId, NodeError>
2251    where
2252        F: FnMut() + 'static,
2253    {
2254        let mut callback = callback;
2255        self.executor.register_timer_entry_with(
2256            Some(self.node_id),
2257            period.into(),
2258            super::TimerClockSource::Steady,
2259            false,
2260            false,
2261            None,
2262            None,
2263            core::ptr::null_mut(),
2264            move |_| move |_: &crate::timer::TimerCallInfo| callback(),
2265        )
2266    }
2267
2268    /// Create a guard condition on this node — the Rust half of
2269    /// the one creation shape.
2270    ///
2271    /// A guard condition is the cross-thread / ISR wake source: any thread may
2272    /// call [`GuardCondition::trigger`](super::types::GuardCondition::trigger)
2273    /// and the `callback` runs on the executor's next `spin_once`. The flag
2274    /// itself lives in the executor's arena, which is what makes the returned
2275    /// handle `Send + Sync` with no allocation — so the NODE is the owner a
2276    /// caller names and the EXECUTOR is where the entity lands, exactly as for
2277    /// a timer or a subscription.
2278    ///
2279    /// Until 2026-09-18 the only Rust spelling was
2280    /// [`Executor::register_guard_condition`](crate::Executor::register_guard_condition),
2281    /// while C++ created one on the node and C needed three calls. That was the
2282    /// three-owner state the adoption rule exists to remove; the executor form
2283    /// survives as the ours-only primitive this calls.
2284    ///
2285    /// The returned [`HandleId`](super::types::HandleId) is the slot, for
2286    /// `trigger_one` / `bind_handle_to_sched_context`; the
2287    /// [`GuardCondition`](super::types::GuardCondition) is the trigger handle to
2288    /// hand to the other thread.
2289    ///
2290    /// ```ignore
2291    /// let (_id, guard) = node.create_guard_condition(|| { /* woken */ })?;
2292    /// // from an ISR or another task:
2293    /// guard.trigger();
2294    /// ```
2295    pub fn create_guard_condition<F>(
2296        &mut self,
2297        callback: F,
2298    ) -> Result<(super::types::HandleId, super::types::GuardCondition<'s>), NodeError>
2299    where
2300        F: FnMut() + 'static,
2301    {
2302        self.executor
2303            .register_guard_condition_on(Some(self.node_id), callback)
2304    }
2305
2306    /// Create a repeating timer on a chosen CLOCK — the
2307    /// node-level spelling of
2308    /// [`Executor::register_timer_on_clock`](crate::Executor::register_timer_on_clock)
2309    /// and the Rust counterpart of C++'s `create_timer(clock, period, cb)`.
2310    ///
2311    /// [`create_timer_in_group`](Self::create_timer_in_group) and the executor's
2312    /// `register_timer` are the WALL case: they consume the spin delta the
2313    /// executor already measured, and no simulator can slow them down. A
2314    /// [`TimerClockSource::Ros`](crate::executor::TimerClockSource::Ros) timer instead follows `/clock`, so it stops
2315    /// while the simulator is paused and tracks a bag's replay rate; with no
2316    /// `/clock` source installed it reads system time, the same fallback
2317    /// `rclcpp::Clock` has.
2318    ///
2319    /// The timer is bound to this node, so the node's default `SchedContext`
2320    /// applies — [`create_timer_on_clock_in_group`](Self::create_timer_on_clock_in_group)
2321    /// is the callback-group form.
2322    ///
2323    /// ```ignore
2324    /// node.create_timer_on_clock(
2325    ///     TimerDuration::from_millis(100),
2326    ///     TimerClockSource::Ros,
2327    ///     || { /* fires once per 100 ms of SIMULATED time */ },
2328    /// )?;
2329    /// ```
2330    pub fn create_timer_on_clock<F>(
2331        &mut self,
2332        period: crate::timer::TimerDuration,
2333        source: crate::executor::TimerClockSource,
2334        callback: F,
2335    ) -> Result<super::types::HandleId, NodeError>
2336    where
2337        F: FnMut() + 'static,
2338    {
2339        self.executor.register_timer_entry(
2340            Some(self.node_id),
2341            period,
2342            source,
2343            false,
2344            None,
2345            callback,
2346        )
2347    }
2348
2349    /// [`create_timer_on_clock`](Self::create_timer_on_clock) **in** a callback
2350    /// group — the clock axis on [`create_timer_in_group`](Self::create_timer_in_group).
2351    /// The two axes are independent: the group decides which
2352    /// `SchedContext` the callback runs under, the clock decides what advances
2353    /// the timer towards its next activation.
2354    pub fn create_timer_on_clock_in_group<F>(
2355        &mut self,
2356        group: &CallbackGroup,
2357        period: crate::timer::TimerDuration,
2358        source: crate::executor::TimerClockSource,
2359        callback: F,
2360    ) -> Result<super::types::HandleId, NodeError>
2361    where
2362        F: FnMut() + 'static,
2363    {
2364        self.executor.register_timer_entry(
2365            Some(self.node_id),
2366            period,
2367            source,
2368            false,
2369            Some(group.name()),
2370            callback,
2371        )
2372    }
2373
2374    /// Create a repeating timer whose callback receives the activation's
2375    /// [`TimerCallInfo`](crate::TimerCallInfo) — the Rust
2376    /// counterpart of Jazzy's `rclcpp::TimerInfoCallbackType`.
2377    ///
2378    /// `info.expected_call_time` is the deadline the executor was serving and
2379    /// `info.actual_call_time` when the callback ran, both on `source`'s clock;
2380    /// `info.lateness_ns()` is the jitter a real-time node otherwise measures
2381    /// by hand. `autostart == false` creates the timer cancelled (rclcpp's
2382    /// `create_timer(..., autostart = false)`); `Executor::reset_timer` on the
2383    /// returned handle starts it.
2384    ///
2385    /// ```ignore
2386    /// node.create_timer_with_info(
2387    ///     TimerDuration::from_millis(10),
2388    ///     TimerClockSource::Steady,
2389    ///     true,
2390    ///     |info| worst = worst.max(info.lateness_ns()),
2391    /// )?;
2392    /// ```
2393    pub fn create_timer_with_info<F>(
2394        &mut self,
2395        period: crate::timer::TimerDuration,
2396        source: crate::executor::TimerClockSource,
2397        autostart: bool,
2398        callback: F,
2399    ) -> Result<super::types::HandleId, NodeError>
2400    where
2401        F: FnMut(&crate::TimerCallInfo) + 'static,
2402    {
2403        self.executor.register_timer_with_info_on(
2404            Some(self.node_id),
2405            period,
2406            source,
2407            autostart,
2408            None,
2409            callback,
2410        )
2411    }
2412
2413    /// Create a typed subscription **in** a callback group (rclcpp shape).
2414    ///
2415    /// The subscription's callback is bound to the `SchedContext` associated
2416    /// with `group` in the `group_sched_table` for this node. If no entry was
2417    /// seeded, the node default applies.
2418    pub fn create_subscription_in_group<M, F>(
2419        &mut self,
2420        group: &CallbackGroup,
2421        topic: &str,
2422        callback: F,
2423    ) -> Result<super::types::HandleId, NodeError>
2424    where
2425        M: MessageForRmw + 'static,
2426        F: FnMut(&M) + 'static,
2427    {
2428        self.executor
2429            .register_subscription_buffered_on::<M, F, { crate::config::DEFAULT_RX_BUF_SIZE }>(
2430                self.node_id,
2431                topic,
2432                QoSProfile::default(),
2433                callback,
2434                Some(group.name()),
2435                None, // phase-403 W2: the configured default, unchanged
2436            )
2437    }
2438
2439    /// Create a typed publisher **in** a callback group (rclcpp shape).
2440    ///
2441    /// Publishers do not have an executor-dispatched callback, so the group
2442    /// name has no scheduling effect today (publishers are explicitly driven by
2443    /// the user via `publish()`). The API is provided for symmetry and
2444    /// forward-compatibility (intra-process / loaned-message knobs may use
2445    /// it in the future).
2446    pub fn create_publisher_in_group<M: MessageForRmw>(
2447        &mut self,
2448        _group: &CallbackGroup,
2449        topic: &str,
2450    ) -> Result<EmbeddedPublisher<M>, NodeError> {
2451        // Publishers carry no executor callback slot; group is forward-compat.
2452        self.create_publisher::<M>(topic)
2453    }
2454
2455    /// Callback-based service client (rclcpp
2456    /// `async_send_request(req, cb)` analogue). The reply is delivered to
2457    /// `callback` at `spin_once` (no `Promise` poll). Returns a
2458    /// [`ServiceClientCallback`] send handle; dual-mode — the `Promise`-based
2459    /// `create_client` is unchanged.
2460    pub fn create_client_with_callback<Svc, F>(
2461        &mut self,
2462        service_name: &str,
2463        callback: F,
2464    ) -> Result<ServiceClientCallback<Svc>, NodeError>
2465    where
2466        Svc: RosService + 'static,
2467        Svc::Request: MessageForRmw,
2468        Svc::Reply: MessageForRmw,
2469        F: FnMut(&Svc::Reply) + 'static,
2470    {
2471        self.create_client_with_callback_sized::<
2472            Svc,
2473            F,
2474            { crate::config::DEFAULT_RX_BUF_SIZE },
2475            { crate::config::DEFAULT_RX_BUF_SIZE },
2476        >(service_name, callback)
2477    }
2478
2479    /// Callback-based service client with custom buffer sizes.
2480    pub fn create_client_with_callback_sized<Svc, F, const REQ_BUF: usize, const REPLY_BUF: usize>(
2481        &mut self,
2482        service_name: &str,
2483        callback: F,
2484    ) -> Result<ServiceClientCallback<Svc, REQ_BUF, REPLY_BUF>, NodeError>
2485    where
2486        Svc: RosService + 'static,
2487        Svc::Request: MessageForRmw,
2488        Svc::Reply: MessageForRmw,
2489        F: FnMut(&Svc::Reply) + 'static,
2490    {
2491        self.register_client_callback::<Svc, _, REQ_BUF, REPLY_BUF>(
2492            service_name,
2493            super::arena::ReplyOnly(callback),
2494        )
2495    }
2496
2497    /// [`create_client_with_callback`](Self::create_client_with_callback)
2498    /// whose closure also receives the reply's
2499    /// [`ServiceInfo`](nros_core::ServiceInfo) — the callback twin
2500    /// of [`Promise::take_with_info`](super::handles::Promise::take_with_info)
2501    /// and the client twin of
2502    /// [`create_service_with_info`](Self::create_service_with_info).
2503    ///
2504    /// rclrs's `(Response, ServiceInfo)` reply and upstream
2505    /// `rmw_take_response`'s `rmw_service_info_t`: `request_id` names the
2506    /// request this reply answers (this client's GID and the sequence number
2507    /// of its request), `source_timestamp` is when the SERVER sent the reply,
2508    /// on its clock, and `received_timestamp` is when this client received it.
2509    /// A field the backend cannot report is `None`, never a zero — see
2510    /// [`ServiceInfo`](nros_core::ServiceInfo).
2511    pub fn create_client_with_callback_with_info<Svc, F>(
2512        &mut self,
2513        service_name: &str,
2514        callback: F,
2515    ) -> Result<ServiceClientCallback<Svc>, NodeError>
2516    where
2517        Svc: RosService + 'static,
2518        Svc::Request: MessageForRmw,
2519        Svc::Reply: MessageForRmw,
2520        F: FnMut(&Svc::Reply, &nros_core::ServiceInfo) + 'static,
2521    {
2522        self.register_client_callback::<
2523            Svc,
2524            _,
2525            { crate::config::DEFAULT_RX_BUF_SIZE },
2526            { crate::config::DEFAULT_RX_BUF_SIZE },
2527        >(service_name, super::arena::ReplyWithInfo(callback))
2528    }
2529
2530    /// The one registration behind both callback-client shapes (issue 2148).
2531    fn register_client_callback<Svc, C, const REQ_BUF: usize, const REPLY_BUF: usize>(
2532        &mut self,
2533        service_name: &str,
2534        callback: C,
2535    ) -> Result<ServiceClientCallback<Svc, REQ_BUF, REPLY_BUF>, NodeError>
2536    where
2537        Svc: RosService + 'static,
2538        Svc::Request: MessageForRmw,
2539        Svc::Reply: MessageForRmw,
2540        C: super::arena::ClientReplyCallback<Svc::Reply> + 'static,
2541    {
2542        register_type::<Svc::Request>()?;
2543        register_type::<Svc::Reply>()?;
2544        let (_id, hdr) = self
2545            .executor
2546            .register_service_client_callback::<Svc, C, REPLY_BUF>(
2547                Some(self.node_id),
2548                service_name,
2549                Svc::SERVICE_NAME,
2550                Svc::SERVICE_HASH,
2551                QoSProfile::services_default(),
2552                callback,
2553            )?;
2554        Ok(ServiceClientCallback::new(hdr))
2555    }
2556
2557    /// Callback-based action client (rclcpp
2558    /// `SendGoalOptions{goal_response_callback, feedback_callback,
2559    /// result_callback}` analogue). Goal-response / feedback / result are
2560    /// delivered to the closures at `spin_once`. Returns an
2561    /// [`ActionClientCallback`] send handle (`send_goal` / `get_result`);
2562    /// dual-mode — the `Promise`-based `create_action_client`
2563    /// is unchanged.
2564    #[allow(clippy::type_complexity)]
2565    pub fn create_action_client_with_callbacks<A, GRespF, FbF, ResF>(
2566        &mut self,
2567        action_name: &str,
2568        on_goal_response: GRespF,
2569        on_feedback: FbF,
2570        on_result: ResF,
2571    ) -> Result<ActionClientCallback<A>, NodeError>
2572    where
2573        A: RosAction + 'static,
2574        A::Goal: MessageForRmw,
2575        A::Result: MessageForRmw,
2576        A::Feedback: MessageForRmw,
2577        GRespF: FnMut(&nros_core::GoalUuid, bool) + 'static,
2578        FbF: FnMut(&nros_core::GoalUuid, &A::Feedback) + 'static,
2579        ResF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode, &A::Result) + 'static,
2580    {
2581        self.create_action_client_with_callbacks_sized::<
2582            A,
2583            GRespF,
2584            FbF,
2585            ResF,
2586            { crate::config::DEFAULT_RX_BUF_SIZE },
2587            { crate::config::DEFAULT_RX_BUF_SIZE },
2588            { crate::config::DEFAULT_RX_BUF_SIZE },
2589        >(action_name, on_goal_response, on_feedback, on_result)
2590    }
2591
2592    /// Callback-based action client with custom buffer sizes.
2593    #[allow(clippy::type_complexity)]
2594    pub fn create_action_client_with_callbacks_sized<
2595        A,
2596        GRespF,
2597        FbF,
2598        ResF,
2599        const GOAL_BUF: usize,
2600        const RESULT_BUF: usize,
2601        const FEEDBACK_BUF: usize,
2602    >(
2603        &mut self,
2604        action_name: &str,
2605        on_goal_response: GRespF,
2606        on_feedback: FbF,
2607        on_result: ResF,
2608    ) -> Result<ActionClientCallback<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>, NodeError>
2609    where
2610        A: RosAction + 'static,
2611        A::Goal: MessageForRmw,
2612        A::Result: MessageForRmw,
2613        A::Feedback: MessageForRmw,
2614        GRespF: FnMut(&nros_core::GoalUuid, bool) + 'static,
2615        FbF: FnMut(&nros_core::GoalUuid, &A::Feedback) + 'static,
2616        ResF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode, &A::Result) + 'static,
2617    {
2618        register_type::<A::Goal>()?;
2619        register_type::<A::Result>()?;
2620        register_type::<A::Feedback>()?;
2621        let (_id, core) = self
2622            .executor
2623            .register_action_client_callback::<A, GRespF, FbF, ResF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>(
2624                Some(self.node_id),
2625                action_name,
2626                A::ACTION_NAME,
2627                A::ACTION_HASH,
2628                // Feedback is a stream → buffer a short QoS-depth history (Phase
2629                // 239.5). Goal-response / result are single-outstanding (gated).
2630                super::arena::DEFAULT_ACTION_FEEDBACK_DEPTH,
2631                on_goal_response,
2632                on_feedback,
2633                on_result,
2634            )?;
2635        Ok(ActionClientCallback::new(core))
2636    }
2637
2638    /// Convenient generic (type-erased) subscription — rclcpp `create_generic_*`.
2639    pub fn create_generic_subscription<F>(
2640        &mut self,
2641        topic: &str,
2642        type_name: &str,
2643        type_hash: &str,
2644        callback: F,
2645    ) -> Result<super::types::HandleId, NodeError>
2646    where
2647        F: FnMut(&[u8]) + 'static,
2648    {
2649        self.create_generic_subscription_with_qos(
2650            topic,
2651            type_name,
2652            type_hash,
2653            QoSProfile::default(),
2654            callback,
2655        )
2656    }
2657
2658    /// The same, with an explicit profile (see
2659    /// [`Self::create_generic_publisher_with_qos`] for why).
2660    pub fn create_generic_subscription_with_qos<F>(
2661        &mut self,
2662        topic: &str,
2663        type_name: &str,
2664        type_hash: &str,
2665        qos: QoSProfile,
2666        callback: F,
2667    ) -> Result<super::types::HandleId, NodeError>
2668    where
2669        F: FnMut(&[u8]) + 'static,
2670    {
2671        self.create_generic_subscription_with_qos_and_rx_hint(
2672            topic, type_name, type_hash, qos, None, callback,
2673        )
2674    }
2675
2676    /// [`Self::create_generic_subscription_with_qos`] for a
2677    /// caller that knows the message type's bound although it registers
2678    /// type-erased (the declarative runtime, which recorded it at
2679    /// declaration). `rx_hint` reaches the backend as `rx_buffer_hint`, which
2680    /// sizes zenoh-pico's receive class and, with a declared arrival curve, the
2681    /// XRCE agent's pace (see the ingress budget's XRCE notes). `None` states nothing.
2682    pub fn create_generic_subscription_with_qos_and_rx_hint<F>(
2683        &mut self,
2684        topic: &str,
2685        type_name: &str,
2686        type_hash: &str,
2687        qos: QoSProfile,
2688        rx_hint: Option<usize>,
2689        callback: F,
2690    ) -> Result<super::types::HandleId, NodeError>
2691    where
2692        F: FnMut(&[u8]) + 'static,
2693    {
2694        self.executor
2695            .register_subscription_buffered_raw_on::<F, { crate::config::DEFAULT_RX_BUF_SIZE }>(
2696                self.node_id,
2697                topic,
2698                type_name,
2699                type_hash,
2700                qos,
2701                rx_hint,
2702                callback,
2703            )
2704    }
2705
2706    // Issue 2349.
2707    /// Generic (type-erased) subscription whose callback also receives the
2708    /// sample's metadata (`FnMut(&[u8], Option<&MessageInfo>)`, `None` from a
2709    /// backend that reports none), with an explicit QoS and the type's bound
2710    /// as `rx_hint`. The declarative runtime's lowering for a component
2711    /// subscription that asked for `CallbackCtx::message_info`; the same
2712    /// executor path as C++'s `(msg, MessageInfo)` callback. It
2713    /// cannot dispatch in place, so it claims a receive region where a plain
2714    /// subscription would not. The node's baked QoS overrides for the topic
2715    /// are folded first, as the plain declared path does.
2716    pub fn create_generic_subscription_with_info_and_rx_hint<F>(
2717        &mut self,
2718        topic: &str,
2719        type_name: &str,
2720        type_hash: &str,
2721        qos: QoSProfile,
2722        rx_hint: Option<usize>,
2723        callback: F,
2724    ) -> Result<super::types::HandleId, NodeError>
2725    where
2726        F: FnMut(&[u8], Option<&nros_core::MessageInfo>) + 'static,
2727    {
2728        let qos = self
2729            .executor
2730            .fold_node_qos_overrides(self.node_id, topic, qos)?;
2731        self.executor
2732            .register_subscription_buffered_raw_msg_info_on(
2733                Some(self.node_id),
2734                topic,
2735                type_name,
2736                type_hash,
2737                qos,
2738                rx_hint.unwrap_or(0),
2739                core::ptr::null_mut(),
2740                None,
2741                move |_| callback,
2742            )
2743    }
2744
2745    /// Generic (type-erased) subscription that surfaces E2E
2746    /// [`IntegrityStatus`](nros_rmw::IntegrityStatus) (CRC + sequence gap/dup) to
2747    /// the callback (`FnMut(&[u8], &IntegrityStatus)`). The declarative-`Node`
2748    /// analog of the typed `.typed::<M>().safety()` builder: the validator lives
2749    /// in the `RmwSubscriber`, so the raw bytes + status arrive together without
2750    /// a typed `M`. Wired by the declarative runtime's `.safety()` opt-in.
2751    #[cfg(feature = "safety-e2e")]
2752    pub fn create_generic_subscription_with_integrity<F>(
2753        &mut self,
2754        topic: &str,
2755        type_name: &str,
2756        type_hash: &str,
2757        callback: F,
2758    ) -> Result<super::types::HandleId, NodeError>
2759    where
2760        F: FnMut(&[u8], &nros_rmw::IntegrityStatus) + 'static,
2761    {
2762        self.create_generic_subscription_with_integrity_and_rx_hint(
2763            topic, type_name, type_hash, None, callback,
2764        )
2765    }
2766
2767    /// [`Self::create_generic_subscription_with_integrity`]
2768    /// with the message type's bound, as
2769    /// [`Self::create_generic_subscription_with_qos_and_rx_hint`].
2770    #[cfg(feature = "safety-e2e")]
2771    pub fn create_generic_subscription_with_integrity_and_rx_hint<F>(
2772        &mut self,
2773        topic: &str,
2774        type_name: &str,
2775        type_hash: &str,
2776        rx_hint: Option<usize>,
2777        callback: F,
2778    ) -> Result<super::types::HandleId, NodeError>
2779    where
2780        F: FnMut(&[u8], &nros_rmw::IntegrityStatus) + 'static,
2781    {
2782        self.executor
2783            .register_subscription_buffered_raw_safety_on::<F, { crate::config::DEFAULT_RX_BUF_SIZE }>(
2784                self.node_id,
2785                topic,
2786                type_name,
2787                type_hash,
2788                QoSProfile::default(),
2789                rx_hint,
2790                callback,
2791            )
2792    }
2793
2794    /// Convenient zero-copy subscription (the
2795    /// `view` mode).
2796    ///
2797    /// `B` is the code-generated VIEWABLE marker (e.g. `ImageViewable`, emitted
2798    /// alongside the `inline` `Image` for a `.msg` with a `view`-mode field).
2799    /// The marker is zero-sized and carries NO lifetime, which is the whole
2800    /// reason it exists: `B::View<'a>` does, and a generic parameter cannot be
2801    /// the lifetime-carrying type itself. That is also why it could not
2802    /// simply rename it to `{Msg}View` — the view struct already owns that
2803    /// name, and the marker points AT it.
2804    ///
2805    /// The callback receives `&B::View<'a>` — a message whose unbounded
2806    /// sequence/string fields point directly into the receive buffer (no
2807    /// `heapless::Vec` copy); valid only for the callback's duration.
2808    ///
2809    /// Uses `KEEP_LAST(1)` QoS → triple buffer, as view subscriptions require
2810    /// (a single well-defined slot for the callback). For an explicit deeper
2811    /// queue use the `inline` [`create_subscription`](Self::create_subscription);
2812    /// a view subscription registered with `KEEP_LAST(N>1)` is rejected.
2813    pub fn create_subscription_viewable<B, F>(
2814        &mut self,
2815        topic: &str,
2816        callback: F,
2817    ) -> Result<super::types::HandleId, NodeError>
2818    where
2819        B: nros_core::ViewableMessage + 'static,
2820        F: for<'a> FnMut(&B::View<'a>) + 'static,
2821    {
2822        self.executor
2823            .register_subscription_buffered_borrowed_on::<B, F, { crate::config::DEFAULT_RX_BUF_SIZE }>(
2824                self.node_id,
2825                topic,
2826                QoSProfile::default().keep_last(1),
2827                callback,
2828            )
2829    }
2830
2831    /// Service-server builder (the `clone` tier) — `node.service(name)`.
2832    /// Set `.qos()` (defaults to the services profile = RELIABLE+VOLATILE+
2833    /// KEEP_LAST(10)), then `.build::<Svc, _>(callback)`.
2834    pub fn service<'t>(&mut self, name: &'t str) -> CtxServiceBuilder<'_, 'e, 't, 's> {
2835        CtxServiceBuilder {
2836            ctx: self,
2837            name,
2838            qos: QoSProfile::services_default(),
2839        }
2840    }
2841
2842    /// Convenient service server (the `fork` tier — rclrs/rclcpp shape), default
2843    /// services QoS. Mirror of `create_subscription`.
2844    ///
2845    /// `options` is rclrs's `impl IntoPrimitiveOptions`; a bare
2846    /// name keeps the services profile. ADOPT-BOUNDED (service): returns the
2847    /// entity's `HandleId`, not an owned rclrs `Service` — the entity lives in
2848    /// the executor's table.
2849    pub fn create_service<'o, Svc, F>(
2850        &mut self,
2851        options: impl crate::IntoPrimitiveOptions<'o>,
2852        callback: F,
2853    ) -> Result<super::types::HandleId, NodeError>
2854    where
2855        Svc: RosService + 'static,
2856        Svc::Request: crate::rmw_type_registry::MessageForRmw,
2857        Svc::Reply: crate::rmw_type_registry::MessageForRmw,
2858        F: FnMut(&Svc::Request) -> Svc::Reply + 'static,
2859    {
2860        let options = options.into_primitive_options();
2861        self.executor.register_service_sized_on::<
2862            Svc,
2863            F,
2864            { crate::config::DEFAULT_RX_BUF_SIZE },
2865            { crate::config::DEFAULT_RX_BUF_SIZE },
2866        >(
2867            self.node_id,
2868            options.name,
2869            options.resolve(QoSProfile::services_default()),
2870            callback,
2871        )
2872    }
2873
2874    /// [`create_service`](Self::create_service) whose callback also receives
2875    /// the request's [`ServiceInfo`](nros_core::ServiceInfo) — rclrs's
2876    /// `(request, ServiceInfo)` service callback.
2877    ///
2878    /// The info says who sent the request (client GID + the client's sequence
2879    /// number) and when. Which fields arrive depends on the backend; one it
2880    /// cannot report is `None`, never a zero — see
2881    /// [`ServiceInfo`](nros_core::ServiceInfo).
2882    pub fn create_service_with_info<Svc, F>(
2883        &mut self,
2884        name: &str,
2885        callback: F,
2886    ) -> Result<super::types::HandleId, NodeError>
2887    where
2888        Svc: RosService + 'static,
2889        Svc::Request: crate::rmw_type_registry::MessageForRmw,
2890        Svc::Reply: crate::rmw_type_registry::MessageForRmw,
2891        F: FnMut(&Svc::Request, &nros_core::ServiceInfo) -> Svc::Reply + 'static,
2892    {
2893        self.service(name).service_info().build::<Svc, F>(callback)
2894    }
2895
2896    // ====================================================================
2897    // Graph introspection — RFC-0036, phase-444.
2898    //
2899    // Upstream hangs the graph family off the NODE (`rclrs::Node::
2900    // get_node_names`, `rcl_get_node_names(node, ...)`). We open ONE transport
2901    // session per image and the Executor owns it, so the capability lives on
2902    // [`Executor`](super::spin::Executor) — see phase-381 W4. These are the
2903    // forwarders that let a ported node keep upstream's receiver and upstream's
2904    // verb, the same forwarders phase-417 stage 2b wrote for C++ `nros::Node`.
2905    //
2906    // They add no behaviour: each is a one-line delegation to the executor
2907    // this handle already borrows.
2908    //
2909    // THE CONTRACT EVERY ONE OF THEM KEEPS (RFC-0036 §"Static CONNECTION,
2910    // dynamic GRAPH"), stated once here and referenced from each:
2911    //
2912    //  * It reports what has been DISCOVERED, and NEVER BLOCKS. The backend
2913    //    keeps a standing view fed by `spin`, so a first call legitimately
2914    //    returns a partial graph and the view fills in over successive calls.
2915    //    Code waiting for a peer must poll, not call once and conclude.
2916    //  * An empty answer is "nobody seen yet", NEVER "nobody exists".
2917    //  * `Err(Transport(Unsupported))` — a backend that cannot tell you, such
2918    //    as XRCE — is a DIFFERENT answer from empty, and must not be collapsed
2919    //    into zero or into an empty enumeration.
2920    //
2921    // SHAPE DIVERGENCE from rclrs, and why: rclrs returns owned heap
2922    // containers (`Vec<NodeNameInfo>`, `TopicNamesAndTypes`). The graph has no
2923    // bound the caller can know, so a caller-sized buffer is an unanswerable
2924    // question and an owned container needs an allocator a 128 KiB target does
2925    // not have. We stream through a visitor instead, which costs one entry of
2926    // peak RAM. Every `&str` handed to a visitor is BORROWED for the duration
2927    // of that call — copy anything you keep. Returning `false` stops the walk.
2928    // ====================================================================
2929
2930    /// Every node on the graph, with its namespace — rclrs's
2931    /// `Node::get_node_names`.
2932    ///
2933    /// `visit(name, namespace)` once per node. For the enclave as well, use
2934    /// [`get_node_names_with_enclaves`](Self::get_node_names_with_enclaves):
2935    /// one backend slot answers both, exactly as `rmw_get_node_names` and
2936    /// `rmw_get_node_names_with_enclaves` are one query upstream.
2937    ///
2938    /// Reports what has been DISCOVERED and never blocks, so an empty
2939    /// enumeration means "nobody seen yet", not "nobody exists";
2940    /// `Err(Transport(Unsupported))` from a backend with no graph is a
2941    /// different answer from empty. See the module note above.
2942    pub fn get_node_names(
2943        &mut self,
2944        visit: &mut dyn FnMut(&str, &str) -> bool,
2945    ) -> Result<(), NodeError> {
2946        self.executor
2947            .get_node_names(&mut |name, ns, _enclave| visit(name, ns))
2948    }
2949
2950    /// Every node on the graph with its namespace AND its enclave — rclrs's
2951    /// `Node::get_node_names_with_enclaves`.
2952    ///
2953    /// `visit(name, namespace, enclave)`. `enclave` is `None` when the backend
2954    /// reports the node but not its enclave, which is a partial answer rather
2955    /// than an error — reporting the node without the enclave beats dropping
2956    /// it. Same discovery envelope as [`get_node_names`](Self::get_node_names).
2957    pub fn get_node_names_with_enclaves(
2958        &mut self,
2959        visit: &mut dyn FnMut(&str, &str, Option<&str>) -> bool,
2960    ) -> Result<(), NodeError> {
2961        self.executor.get_node_names(visit)
2962    }
2963
2964    /// Every topic on the graph, with the types on it — rclrs's
2965    /// `Node::get_topic_names_and_types`.
2966    ///
2967    /// `visit(topic_name, types)` once per distinct TOPIC: a topic carrying
2968    /// two types is one call with two entries, not two calls. `types` may
2969    /// legitimately be empty on a partially discovered graph. Same discovery
2970    /// envelope as [`get_node_names`](Self::get_node_names).
2971    pub fn get_topic_names_and_types(
2972        &mut self,
2973        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2974    ) -> Result<(), NodeError> {
2975        self.executor.get_topic_names_and_types(visit)
2976    }
2977
2978    /// Every service on the graph, with its types — rclrs's
2979    /// `Node::get_service_names_and_types`. As
2980    /// [`get_topic_names_and_types`](Self::get_topic_names_and_types), over
2981    /// servers and clients.
2982    pub fn get_service_names_and_types(
2983        &mut self,
2984        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2985    ) -> Result<(), NodeError> {
2986        self.executor.get_service_names_and_types(visit)
2987    }
2988
2989    /// How many publishers are visible on `topic_name` — rclrs's
2990    /// `Node::count_publishers`.
2991    ///
2992    /// **This is the GRAPH's count, not this node's.** The number of
2993    /// publishers this node itself DECLARED is
2994    /// [`StandaloneNode::publisher_count`](crate::StandaloneNode), a different
2995    /// question with a different answer.
2996    ///
2997    /// A count reflects what has been DISCOVERED, so it can be low right after
2998    /// startup and is never a proof of absence. See
2999    /// [`get_node_names`](Self::get_node_names).
3000    pub fn count_publishers(&mut self, topic_name: &str) -> Result<usize, NodeError> {
3001        self.executor.count_publishers(topic_name)
3002    }
3003
3004    /// How many subscriptions are visible on `topic_name` — rclrs's
3005    /// `Node::count_subscriptions`.
3006    ///
3007    /// **`subscriptions`, not `subscribers`** — this is rclrs's spelling, and
3008    /// the Rust surface takes its vocabulary from rclrs so a user porting Rust
3009    /// ROS 2 code types what they already know. The C surface says
3010    /// `subscribers` because rcl does, and the vtable slot says `subscribers`
3011    /// because upstream rmw does. Three layers, three upstreams, one word each
3012    /// — not drift.
3013    ///
3014    /// The graph's count, not this node's; see
3015    /// [`count_publishers`](Self::count_publishers) for that distinction and
3016    /// for the discovery caveats.
3017    pub fn count_subscriptions(&mut self, topic_name: &str) -> Result<usize, NodeError> {
3018        self.executor.count_subscribers(topic_name)
3019    }
3020
3021    /// How many service clients are visible on `service_name` — rclcpp's
3022    /// (Jazzy) `Node::count_clients`; rclrs has no counterpart.
3023    ///
3024    /// The graph's count, not this node's; see
3025    /// [`count_publishers`](Self::count_publishers) for that distinction and
3026    /// for the discovery caveats.
3027    pub fn count_clients(&mut self, service_name: &str) -> Result<usize, NodeError> {
3028        self.executor.count_clients(service_name)
3029    }
3030
3031    /// How many service servers are visible on `service_name` — rclcpp's
3032    /// (Jazzy) `Node::count_services`. See [`count_clients`](Self::count_clients).
3033    pub fn count_services(&mut self, service_name: &str) -> Result<usize, NodeError> {
3034        self.executor.count_services(service_name)
3035    }
3036
3037    /// What one named node PUBLISHES, with the types — rclrs's
3038    /// `Node::get_publisher_names_and_types_by_node`.
3039    ///
3040    /// A node the graph has not discovered yields no visits, which is not an
3041    /// error — see [`get_node_names`](Self::get_node_names) for why an empty
3042    /// answer means "not seen yet".
3043    pub fn get_publisher_names_and_types_by_node(
3044        &mut self,
3045        node_name: &str,
3046        node_namespace: &str,
3047        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
3048    ) -> Result<(), NodeError> {
3049        self.executor
3050            .get_publisher_names_and_types_by_node(node_name, node_namespace, visit)
3051    }
3052
3053    /// What one named node SUBSCRIBES to, with the types — rclrs's
3054    /// `Node::get_subscription_names_and_types_by_node`. See
3055    /// [`count_subscriptions`](Self::count_subscriptions) on the spelling.
3056    pub fn get_subscription_names_and_types_by_node(
3057        &mut self,
3058        node_name: &str,
3059        node_namespace: &str,
3060        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
3061    ) -> Result<(), NodeError> {
3062        self.executor
3063            .get_subscription_names_and_types_by_node(node_name, node_namespace, visit)
3064    }
3065
3066    /// What services one named node SERVES, with the types — rclrs's
3067    /// `Node::get_service_names_and_types_by_node`.
3068    pub fn get_service_names_and_types_by_node(
3069        &mut self,
3070        node_name: &str,
3071        node_namespace: &str,
3072        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
3073    ) -> Result<(), NodeError> {
3074        self.executor
3075            .get_service_names_and_types_by_node(node_name, node_namespace, visit)
3076    }
3077
3078    /// What services one named node CALLS, with the types — rclrs's
3079    /// `Node::get_client_names_and_types_by_node`.
3080    pub fn get_client_names_and_types_by_node(
3081        &mut self,
3082        node_name: &str,
3083        node_namespace: &str,
3084        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
3085    ) -> Result<(), NodeError> {
3086        self.executor
3087            .get_client_names_and_types_by_node(node_name, node_namespace, visit)
3088    }
3089
3090    /// The PUBLISHERS on `topic_name`, one visit each — rclrs's
3091    /// `Node::get_publishers_info_by_topic`.
3092    ///
3093    /// The last two members of the graph family to reach upstream's receiver.
3094    /// `visit(info)` per discovered endpoint; every `&str` on the
3095    /// [`GraphEndpointInfo`](nros_rmw::GraphEndpointInfo) is BORROWED for the
3096    /// duration of that call, so copy anything you keep, and returning `false`
3097    /// stops the walk.
3098    ///
3099    /// ADOPT-BOUNDED: rclrs returns an owned `Vec<TopicEndpointInfo>`; here the
3100    /// answer is STREAMED to `visit`, because the graph has no bound a caller could
3101    /// size a buffer to and there is no allocator for a `Vec`. It reports what has
3102    /// been DISCOVERED and never blocks, so an empty walk means "nobody seen yet";
3103    /// a backend with no graph answers `Err(Transport(Unsupported))`, never an
3104    /// empty `Ok`.
3105    ///
3106    /// It carries NO QoS, and that absence is the point: the GRANTED profile is
3107    /// what answers "why is nothing arriving", no backend can read a remote's
3108    /// back yet, and reporting the remote's DECLARED profile instead would be
3109    /// the confident wrong answer the field exists to avoid.
3110    pub fn get_publishers_info_by_topic(
3111        &mut self,
3112        topic_name: &str,
3113        visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
3114    ) -> Result<(), NodeError> {
3115        self.executor
3116            .get_publishers_info_by_topic(topic_name, visit)
3117    }
3118
3119    /// The SUBSCRIPTIONS on `topic_name`, one visit each — rclrs's
3120    /// `Node::get_subscriptions_info_by_topic`. See
3121    /// [`get_publishers_info_by_topic`](Self::get_publishers_info_by_topic).
3122    ///
3123    /// Same envelope: STREAMED to `visit` rather than returned as a `Vec`, every
3124    /// `&str` borrowed for the visit, discovered-only and non-blocking, and
3125    /// `Err(Transport(Unsupported))` from a backend with no graph.
3126    pub fn get_subscriptions_info_by_topic(
3127        &mut self,
3128        topic_name: &str,
3129        visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
3130    ) -> Result<(), NodeError> {
3131        self.executor
3132            .get_subscriptions_info_by_topic(topic_name, visit)
3133    }
3134
3135    // ------------------------------------------------------------------
3136    // phase-483 W2 — the constructors that only `NodeHandle` had. `Node`
3137    // is the ONE node type, so it carries them too; each forwards through
3138    // `Executor::with_node_try`, which opens a `NodeHandle` on this node's
3139    // session for the duration of the call. The polled subscription and
3140    // service constructors are `create_polling_*`: rclrs's
3141    // `create_subscription` / `create_service` take a callback, and this type
3142    // already has those under exactly those names.
3143    // ------------------------------------------------------------------
3144
3145    /// [`create_publisher`](Self::create_publisher) with an explicit profile.
3146    ///
3147    /// Through [`NodeHandle::create_publisher_with_qos`], so a publisher made
3148    /// here gets what one made on the handle `Executor::create_node` used to
3149    /// return: the node's remap rules (launch, then `--ros-args`), the plan's
3150    /// QoS overrides and the declared-QoS check. `Executor::create_publisher_on`
3151    /// takes a name its caller already resolved, which is right for the C and
3152    /// component roads and wrong for a user's source name.
3153    pub fn create_publisher_with_qos<M: MessageForRmw>(
3154        &mut self,
3155        topic_name: &str,
3156        qos: QoSProfile,
3157    ) -> Result<EmbeddedPublisher<M>, NodeError> {
3158        self.executor.with_node_try(self.node_id, |h| {
3159            h.create_publisher_with_qos::<M>(topic_name, qos)
3160        })
3161    }
3162
3163    /// [`NodeHandle::create_publisher_raw`] on this node.
3164    pub fn create_publisher_raw(
3165        &mut self,
3166        topic_name: &str,
3167        type_name: &str,
3168        type_hash: &str,
3169    ) -> Result<crate::executor::handles::EmbeddedRawPublisher, NodeError> {
3170        self.executor.with_node_try(self.node_id, |h| {
3171            h.create_publisher_raw(topic_name, type_name, type_hash)
3172        })
3173    }
3174
3175    /// [`NodeHandle::create_publisher_raw_with_qos`] on this node.
3176    pub fn create_publisher_raw_with_qos(
3177        &mut self,
3178        topic_name: &str,
3179        type_name: &str,
3180        type_hash: &str,
3181        qos: QoSProfile,
3182    ) -> Result<crate::executor::handles::EmbeddedRawPublisher, NodeError> {
3183        self.executor.with_node_try(self.node_id, |h| {
3184            h.create_publisher_raw_with_qos(topic_name, type_name, type_hash, qos)
3185        })
3186    }
3187
3188    /// The POLLED form of [`NodeHandle::create_subscription`]: the caller
3189    /// takes from it, where rclrs's `create_subscription` takes a callback.
3190    pub fn create_polling_subscription<M: MessageForRmw>(
3191        &mut self,
3192        topic_name: &str,
3193    ) -> Result<Subscription<M>, NodeError> {
3194        self.executor
3195            .with_node_try(self.node_id, |h| h.create_subscription::<M>(topic_name))
3196    }
3197
3198    /// The POLLED form of [`NodeHandle::create_subscription_sized`]: the caller
3199    /// takes from it, where rclrs's `create_subscription` takes a callback.
3200    pub fn create_polling_subscription_sized<M: MessageForRmw, const RX_BUF: usize>(
3201        &mut self,
3202        topic_name: &str,
3203    ) -> Result<Subscription<M, RX_BUF>, NodeError> {
3204        self.executor.with_node_try(self.node_id, |h| {
3205            h.create_subscription_sized::<M, RX_BUF>(topic_name)
3206        })
3207    }
3208
3209    /// The POLLED form of [`NodeHandle::create_subscription_with_qos`]: the caller
3210    /// takes from it, where rclrs's `create_subscription` takes a callback.
3211    pub fn create_polling_subscription_with_qos<M: MessageForRmw, const RX_BUF: usize>(
3212        &mut self,
3213        topic_name: &str,
3214        qos: QoSProfile,
3215    ) -> Result<Subscription<M, RX_BUF>, NodeError> {
3216        self.executor.with_node_try(self.node_id, |h| {
3217            h.create_subscription_with_qos::<M, RX_BUF>(topic_name, qos)
3218        })
3219    }
3220
3221    /// The POLLED form of [`NodeHandle::create_subscription_raw`]: the caller
3222    /// takes from it, where rclrs's `create_subscription` takes a callback.
3223    pub fn create_polling_subscription_raw(
3224        &mut self,
3225        topic_name: &str,
3226        type_name: &str,
3227        type_hash: &str,
3228    ) -> Result<crate::executor::handles::RawSubscription, NodeError> {
3229        self.executor.with_node_try(self.node_id, |h| {
3230            h.create_subscription_raw(topic_name, type_name, type_hash)
3231        })
3232    }
3233
3234    /// The POLLED form of [`NodeHandle::create_subscription_raw_sized`]: the caller
3235    /// takes from it, where rclrs's `create_subscription` takes a callback.
3236    pub fn create_polling_subscription_raw_sized<const RX_BUF: usize>(
3237        &mut self,
3238        topic_name: &str,
3239        type_name: &str,
3240        type_hash: &str,
3241    ) -> Result<crate::executor::handles::RawSubscription<RX_BUF>, NodeError> {
3242        self.executor.with_node_try(self.node_id, |h| {
3243            h.create_subscription_raw_sized::<RX_BUF>(topic_name, type_name, type_hash)
3244        })
3245    }
3246
3247    /// The POLLED form of [`NodeHandle::create_service`]: the caller
3248    /// takes from it, where rclrs's `create_service` takes a callback.
3249    pub fn create_polling_service<Svc: RosService>(
3250        &mut self,
3251        service_name: &str,
3252    ) -> Result<EmbeddedServiceServer<Svc>, NodeError>
3253    where
3254        Svc::Request: MessageForRmw,
3255        Svc::Reply: MessageForRmw,
3256    {
3257        self.executor
3258            .with_node_try(self.node_id, |h| h.create_service::<Svc>(service_name))
3259    }
3260
3261    /// The POLLED form of [`NodeHandle::create_service_with_qos`]: the caller
3262    /// takes from it, where rclrs's `create_service` takes a callback.
3263    pub fn create_polling_service_with_qos<Svc: RosService>(
3264        &mut self,
3265        service_name: &str,
3266        qos: QoSProfile,
3267    ) -> Result<EmbeddedServiceServer<Svc>, NodeError>
3268    where
3269        Svc::Request: MessageForRmw,
3270        Svc::Reply: MessageForRmw,
3271    {
3272        self.executor.with_node_try(self.node_id, |h| {
3273            h.create_service_with_qos::<Svc>(service_name, qos)
3274        })
3275    }
3276
3277    /// The POLLED form of [`NodeHandle::create_service_sized`]: the caller
3278    /// takes from it, where rclrs's `create_service` takes a callback.
3279    pub fn create_polling_service_sized<
3280        Svc: RosService,
3281        const REQ_BUF: usize,
3282        const REPLY_BUF: usize,
3283    >(
3284        &mut self,
3285        service_name: &str,
3286        qos: QoSProfile,
3287    ) -> Result<EmbeddedServiceServer<Svc, REQ_BUF, REPLY_BUF>, NodeError>
3288    where
3289        Svc::Request: MessageForRmw,
3290        Svc::Reply: MessageForRmw,
3291    {
3292        self.executor.with_node_try(self.node_id, |h| {
3293            h.create_service_sized::<Svc, REQ_BUF, REPLY_BUF>(service_name, qos)
3294        })
3295    }
3296
3297    /// [`NodeHandle::create_client`] on this node.
3298    ///
3299    /// `options` is rclrs's `impl IntoPrimitiveOptions`; a bare
3300    /// name keeps the services profile. ADOPT-BOUNDED (client): returns an
3301    /// `EmbeddedServiceClient`, the executor-table handle, where rclrs returns
3302    /// a reference-counted `Client`.
3303    pub fn create_client<'o, Svc: RosService>(
3304        &mut self,
3305        options: impl crate::IntoPrimitiveOptions<'o>,
3306    ) -> Result<EmbeddedServiceClient<Svc>, NodeError>
3307    where
3308        Svc::Request: MessageForRmw,
3309        Svc::Reply: MessageForRmw,
3310    {
3311        let options = options.into_primitive_options();
3312        let qos = options.resolve(QoSProfile::services_default());
3313        self.executor.with_node_try(self.node_id, |h| {
3314            h.create_client_with_qos::<Svc>(options.name, qos)
3315        })
3316    }
3317
3318    /// [`NodeHandle::create_client_with_qos`] on this node.
3319    pub fn create_client_with_qos<Svc: RosService>(
3320        &mut self,
3321        service_name: &str,
3322        qos: QoSProfile,
3323    ) -> Result<EmbeddedServiceClient<Svc>, NodeError>
3324    where
3325        Svc::Request: MessageForRmw,
3326        Svc::Reply: MessageForRmw,
3327    {
3328        self.executor.with_node_try(self.node_id, |h| {
3329            h.create_client_with_qos::<Svc>(service_name, qos)
3330        })
3331    }
3332
3333    /// [`NodeHandle::create_client_sized`] on this node.
3334    pub fn create_client_sized<Svc: RosService, const REQ_BUF: usize, const REPLY_BUF: usize>(
3335        &mut self,
3336        service_name: &str,
3337        qos: QoSProfile,
3338    ) -> Result<EmbeddedServiceClient<Svc, REQ_BUF, REPLY_BUF>, NodeError>
3339    where
3340        Svc::Request: MessageForRmw,
3341        Svc::Reply: MessageForRmw,
3342    {
3343        self.executor.with_node_try(self.node_id, |h| {
3344            h.create_client_sized::<Svc, REQ_BUF, REPLY_BUF>(service_name, qos)
3345        })
3346    }
3347
3348    /// The POLLED form of [`NodeHandle::create_service_raw`]: the caller
3349    /// takes from it, where rclrs's `create_service` takes a callback.
3350    pub fn create_polling_service_raw(
3351        &mut self,
3352        service_name: &str,
3353        type_name: &str,
3354        type_hash: &str,
3355    ) -> Result<crate::executor::handles::RawServiceServer, NodeError> {
3356        self.executor.with_node_try(self.node_id, |h| {
3357            h.create_service_raw(service_name, type_name, type_hash)
3358        })
3359    }
3360
3361    /// The POLLED form of [`NodeHandle::create_service_raw_sized`]: the caller
3362    /// takes from it, where rclrs's `create_service` takes a callback.
3363    pub fn create_polling_service_raw_sized<const REQ_BUF: usize, const RESP_BUF: usize>(
3364        &mut self,
3365        service_name: &str,
3366        type_name: &str,
3367        type_hash: &str,
3368    ) -> Result<crate::executor::handles::RawServiceServer<REQ_BUF, RESP_BUF>, NodeError> {
3369        self.executor.with_node_try(self.node_id, |h| {
3370            h.create_service_raw_sized::<REQ_BUF, RESP_BUF>(service_name, type_name, type_hash)
3371        })
3372    }
3373
3374    /// [`NodeHandle::create_client_raw`] on this node.
3375    pub fn create_client_raw(
3376        &mut self,
3377        service_name: &str,
3378        type_name: &str,
3379        type_hash: &str,
3380    ) -> Result<crate::executor::handles::RawServiceClient, NodeError> {
3381        self.executor.with_node_try(self.node_id, |h| {
3382            h.create_client_raw(service_name, type_name, type_hash)
3383        })
3384    }
3385
3386    /// [`NodeHandle::create_client_raw_sized`] on this node.
3387    pub fn create_client_raw_sized<const REQ_BUF: usize, const REPLY_BUF: usize>(
3388        &mut self,
3389        service_name: &str,
3390        type_name: &str,
3391        type_hash: &str,
3392    ) -> Result<crate::executor::handles::RawServiceClient<REQ_BUF, REPLY_BUF>, NodeError> {
3393        self.executor.with_node_try(self.node_id, |h| {
3394            h.create_client_raw_sized::<REQ_BUF, REPLY_BUF>(service_name, type_name, type_hash)
3395        })
3396    }
3397
3398    /// [`NodeHandle::create_action_server_raw`] on this node.
3399    pub fn create_action_server_raw(
3400        &mut self,
3401        action_name: &str,
3402        type_name: &str,
3403        type_hash: &str,
3404    ) -> Result<
3405        super::action_core::ActionServerCore<
3406            { crate::config::DEFAULT_RX_BUF_SIZE },
3407            { crate::config::DEFAULT_RX_BUF_SIZE },
3408            { crate::config::DEFAULT_RX_BUF_SIZE },
3409            4,
3410        >,
3411        NodeError,
3412    > {
3413        self.executor.with_node_try(self.node_id, |h| {
3414            h.create_action_server_raw(action_name, type_name, type_hash)
3415        })
3416    }
3417
3418    /// [`NodeHandle::create_action_server_raw_sized`] on this node.
3419    pub fn create_action_server_raw_sized<
3420        const GOAL_BUF: usize,
3421        const RESULT_BUF: usize,
3422        const FEEDBACK_BUF: usize,
3423        const MAX_GOALS: usize,
3424    >(
3425        &mut self,
3426        action_name: &str,
3427        type_name: &str,
3428        type_hash: &str,
3429    ) -> Result<
3430        super::action_core::ActionServerCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
3431        NodeError,
3432    > {
3433        self.executor.with_node_try(self.node_id, |h| {
3434            h.create_action_server_raw_sized::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>(
3435                action_name,
3436                type_name,
3437                type_hash,
3438            )
3439        })
3440    }
3441
3442    /// [`NodeHandle::create_action_client_raw`] on this node.
3443    pub fn create_action_client_raw(
3444        &mut self,
3445        action_name: &str,
3446        type_name: &str,
3447        type_hash: &str,
3448    ) -> Result<
3449        super::action_core::ActionClientCore<
3450            { crate::config::DEFAULT_RX_BUF_SIZE },
3451            { crate::config::DEFAULT_RX_BUF_SIZE },
3452            { crate::config::DEFAULT_RX_BUF_SIZE },
3453        >,
3454        NodeError,
3455    > {
3456        self.executor.with_node_try(self.node_id, |h| {
3457            h.create_action_client_raw(action_name, type_name, type_hash)
3458        })
3459    }
3460
3461    /// [`NodeHandle::create_action_client_raw_sized`] on this node.
3462    pub fn create_action_client_raw_sized<
3463        const GOAL_BUF: usize,
3464        const RESULT_BUF: usize,
3465        const FEEDBACK_BUF: usize,
3466    >(
3467        &mut self,
3468        action_name: &str,
3469        type_name: &str,
3470        type_hash: &str,
3471    ) -> Result<super::action_core::ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>, NodeError>
3472    {
3473        self.executor.with_node_try(self.node_id, |h| {
3474            h.create_action_client_raw_sized::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>(
3475                action_name,
3476                type_name,
3477                type_hash,
3478            )
3479        })
3480    }
3481
3482    /// [`NodeHandle::create_action_server`] on this node.
3483    pub fn create_action_server<A: RosAction>(
3484        &mut self,
3485        action_name: &str,
3486    ) -> Result<ActionServer<A>, NodeError>
3487    where
3488        A::Goal: MessageForRmw,
3489        A::Result: MessageForRmw,
3490        A::Feedback: MessageForRmw,
3491        A::SendGoalRequest: MessageForRmw,
3492        A::SendGoalResponse: MessageForRmw,
3493        A::GetResultRequest: MessageForRmw,
3494        A::GetResultResponse: MessageForRmw,
3495        A::FeedbackMessage: MessageForRmw,
3496    {
3497        self.executor
3498            .with_node_try(self.node_id, |h| h.create_action_server::<A>(action_name))
3499    }
3500
3501    /// [`NodeHandle::create_action_server_sized`] on this node.
3502    pub fn create_action_server_sized<
3503        A: RosAction,
3504        const GOAL_BUF: usize,
3505        const RESULT_BUF: usize,
3506        const FEEDBACK_BUF: usize,
3507        const MAX_GOALS: usize,
3508    >(
3509        &mut self,
3510        action_name: &str,
3511    ) -> Result<ActionServer<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>, NodeError>
3512    where
3513        A::Goal: MessageForRmw,
3514        A::Result: MessageForRmw,
3515        A::Feedback: MessageForRmw,
3516        A::SendGoalRequest: MessageForRmw,
3517        A::SendGoalResponse: MessageForRmw,
3518        A::GetResultRequest: MessageForRmw,
3519        A::GetResultResponse: MessageForRmw,
3520        A::FeedbackMessage: MessageForRmw,
3521    {
3522        self.executor.with_node_try(self.node_id, |h| {
3523            h.create_action_server_sized::<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>(
3524                action_name,
3525            )
3526        })
3527    }
3528
3529    /// [`NodeHandle::create_action_client`] on this node.
3530    pub fn create_action_client<A: RosAction>(
3531        &mut self,
3532        action_name: &str,
3533    ) -> Result<ActionClient<A>, NodeError>
3534    where
3535        A::Goal: MessageForRmw,
3536        A::Result: MessageForRmw,
3537        A::Feedback: MessageForRmw,
3538        A::SendGoalRequest: MessageForRmw,
3539        A::SendGoalResponse: MessageForRmw,
3540        A::GetResultRequest: MessageForRmw,
3541        A::GetResultResponse: MessageForRmw,
3542        A::FeedbackMessage: MessageForRmw,
3543    {
3544        self.executor
3545            .with_node_try(self.node_id, |h| h.create_action_client::<A>(action_name))
3546    }
3547
3548    /// [`NodeHandle::create_action_client_sized`] on this node.
3549    pub fn create_action_client_sized<
3550        A: RosAction,
3551        const GOAL_BUF: usize,
3552        const RESULT_BUF: usize,
3553        const FEEDBACK_BUF: usize,
3554    >(
3555        &mut self,
3556        action_name: &str,
3557    ) -> Result<ActionClient<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>, NodeError>
3558    where
3559        A::Goal: MessageForRmw,
3560        A::Result: MessageForRmw,
3561        A::Feedback: MessageForRmw,
3562        A::SendGoalRequest: MessageForRmw,
3563        A::SendGoalResponse: MessageForRmw,
3564        A::GetResultRequest: MessageForRmw,
3565        A::GetResultResponse: MessageForRmw,
3566        A::FeedbackMessage: MessageForRmw,
3567    {
3568        self.executor.with_node_try(self.node_id, |h| {
3569            h.create_action_client_sized::<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>(action_name)
3570        })
3571    }
3572}
3573
3574/// Service-server builder on a [`Node`] — `node.service(name)`.
3575pub struct CtxServiceBuilder<'c, 'e, 't, 's> {
3576    ctx: &'c mut Node<'e, 's>,
3577    name: &'t str,
3578    qos: QoSProfile,
3579}
3580
3581impl<'c, 'e, 't, 's> CtxServiceBuilder<'c, 'e, 't, 's> {
3582    /// Service QoS (applies to both the request + reply endpoints). Defaults to
3583    /// `QoSProfile::services_default()`.
3584    pub fn qos(mut self, qos: QoSProfile) -> Self {
3585        self.qos = qos;
3586        self
3587    }
3588
3589    /// Surface the request's [`ServiceInfo`](nros_core::ServiceInfo) to the
3590    /// callback — `FnMut(&Request, &ServiceInfo) -> Reply`. The
3591    /// service-side twin of the subscription builder's `.message_info()`.
3592    pub fn service_info(self) -> CtxServiceInfoBuilder<'c, 'e, 't, 's> {
3593        CtxServiceInfoBuilder {
3594            ctx: self.ctx,
3595            name: self.name,
3596            qos: self.qos,
3597        }
3598    }
3599
3600    pub fn build<Svc, F>(self, callback: F) -> Result<super::types::HandleId, NodeError>
3601    where
3602        Svc: RosService + 'static,
3603        Svc::Request: crate::rmw_type_registry::MessageForRmw,
3604        Svc::Reply: crate::rmw_type_registry::MessageForRmw,
3605        F: FnMut(&Svc::Request) -> Svc::Reply + 'static,
3606    {
3607        self.ctx.executor.register_service_sized_on::<
3608            Svc,
3609            F,
3610            { crate::config::DEFAULT_RX_BUF_SIZE },
3611            { crate::config::DEFAULT_RX_BUF_SIZE },
3612        >(self.ctx.node_id, self.name, self.qos, callback)
3613    }
3614}
3615
3616/// Service-server builder with [`ServiceInfo`](nros_core::ServiceInfo)
3617/// surfaced (`node.service(name).service_info()`). Callback is
3618/// `FnMut(&Svc::Request, &ServiceInfo) -> Svc::Reply`.
3619pub struct CtxServiceInfoBuilder<'c, 'e, 't, 's> {
3620    ctx: &'c mut Node<'e, 's>,
3621    name: &'t str,
3622    qos: QoSProfile,
3623}
3624
3625impl<'c, 'e, 't, 's> CtxServiceInfoBuilder<'c, 'e, 't, 's> {
3626    /// Service QoS (applies to both the request + reply endpoints). Defaults to
3627    /// `QoSProfile::services_default()`.
3628    pub fn qos(mut self, qos: QoSProfile) -> Self {
3629        self.qos = qos;
3630        self
3631    }
3632
3633    pub fn build<Svc, F>(self, callback: F) -> Result<super::types::HandleId, NodeError>
3634    where
3635        Svc: RosService + 'static,
3636        Svc::Request: crate::rmw_type_registry::MessageForRmw,
3637        Svc::Reply: crate::rmw_type_registry::MessageForRmw,
3638        F: FnMut(&Svc::Request, &nros_core::ServiceInfo) -> Svc::Reply + 'static,
3639    {
3640        self.ctx.executor.register_service_with_info_sized_on::<
3641            Svc,
3642            F,
3643            { crate::config::DEFAULT_RX_BUF_SIZE },
3644            { crate::config::DEFAULT_RX_BUF_SIZE },
3645        >(self.ctx.node_id, self.name, self.qos, callback)
3646    }
3647}
3648
3649/// Publisher builder on a [`Node`] — `node.publisher(topic)`.
3650pub struct CtxPublisherBuilder<'c, 'e, 't, 's> {
3651    ctx: &'c mut Node<'e, 's>,
3652    topic: &'t str,
3653    qos: QoSProfile,
3654}
3655
3656impl<'c, 'e, 't, 's> CtxPublisherBuilder<'c, 'e, 't, 's> {
3657    pub fn qos(mut self, qos: QoSProfile) -> Self {
3658        self.qos = qos;
3659        self
3660    }
3661
3662    /// Typed publisher for a ROS message `M`.
3663    pub fn typed<M: MessageForRmw>(self) -> CtxTypedPublisherBuilder<'c, 'e, 't, 's, M> {
3664        CtxTypedPublisherBuilder {
3665            ctx: self.ctx,
3666            topic: self.topic,
3667            qos: self.qos,
3668            _phantom: PhantomData,
3669        }
3670    }
3671
3672    /// Generic (type-erased) publisher.
3673    pub fn generic(
3674        self,
3675        type_name: &'t str,
3676        type_hash: &'t str,
3677    ) -> CtxGenericPublisherBuilder<'c, 'e, 't, 's> {
3678        CtxGenericPublisherBuilder {
3679            ctx: self.ctx,
3680            topic: self.topic,
3681            type_name,
3682            type_hash,
3683            qos: self.qos,
3684        }
3685    }
3686}
3687
3688/// Typed publisher builder on a `Node` (`.typed::<M>()`).
3689pub struct CtxTypedPublisherBuilder<'c, 'e, 't, 's, M> {
3690    ctx: &'c mut Node<'e, 's>,
3691    topic: &'t str,
3692    qos: QoSProfile,
3693    _phantom: PhantomData<M>,
3694}
3695
3696impl<'c, 'e, 't, 's, M: MessageForRmw> CtxTypedPublisherBuilder<'c, 'e, 't, 's, M> {
3697    pub fn qos(mut self, qos: QoSProfile) -> Self {
3698        self.qos = qos;
3699        self
3700    }
3701
3702    pub fn build(self) -> Result<EmbeddedPublisher<M>, NodeError> {
3703        self.ctx
3704            .executor
3705            .create_publisher_on::<M>(self.ctx.node_id, self.topic, self.qos)
3706    }
3707}
3708
3709/// Generic publisher builder on a `Node` (`.generic(type, hash)`).
3710pub struct CtxGenericPublisherBuilder<'c, 'e, 't, 's> {
3711    ctx: &'c mut Node<'e, 's>,
3712    topic: &'t str,
3713    type_name: &'t str,
3714    type_hash: &'t str,
3715    qos: QoSProfile,
3716}
3717
3718impl<'c, 'e, 't, 's> CtxGenericPublisherBuilder<'c, 'e, 't, 's> {
3719    pub fn qos(mut self, qos: QoSProfile) -> Self {
3720        self.qos = qos;
3721        self
3722    }
3723
3724    pub fn build(self) -> Result<crate::executor::handles::EmbeddedRawPublisher, NodeError> {
3725        self.ctx.executor.create_publisher_raw_on(
3726            self.ctx.node_id,
3727            self.topic,
3728            self.type_name,
3729            self.type_hash,
3730            self.qos,
3731        )
3732    }
3733}
3734
3735/// Subscription builder — `node.subscription(topic)`.
3736pub struct SubscriptionBuilder<'c, 'e, 't, 's> {
3737    ctx: &'c mut Node<'e, 's>,
3738    topic: &'t str,
3739    qos: QoSProfile,
3740}
3741
3742impl<'c, 'e, 't, 's> SubscriptionBuilder<'c, 'e, 't, 's> {
3743    pub fn qos(mut self, qos: QoSProfile) -> Self {
3744        self.qos = qos;
3745        self
3746    }
3747
3748    /// Typed subscription for a ROS message `M`.
3749    pub fn typed<M: MessageForRmw + 'static>(self) -> TypedSubscriptionBuilder<'c, 'e, 't, 's, M> {
3750        TypedSubscriptionBuilder {
3751            ctx: self.ctx,
3752            topic: self.topic,
3753            qos: self.qos,
3754            sched: None,
3755            rx_explicit: false,
3756            _phantom: PhantomData,
3757        }
3758    }
3759
3760    /// Generic (type-erased) subscription — raw CDR bytes to the callback.
3761    pub fn generic(
3762        self,
3763        type_name: &'t str,
3764        type_hash: &'t str,
3765    ) -> GenericSubscriptionBuilder<'c, 'e, 't, 's> {
3766        GenericSubscriptionBuilder {
3767            ctx: self.ctx,
3768            topic: self.topic,
3769            type_name,
3770            type_hash,
3771            qos: self.qos,
3772            sched: None,
3773        }
3774    }
3775}
3776
3777/// Typed subscription builder (`.typed::<M>()`). `RX` is the staging-buffer
3778/// size, set via `.rx_buffer::<N>()` (defaults to `DEFAULT_RX_BUF_SIZE`).
3779pub struct TypedSubscriptionBuilder<
3780    'c,
3781    'e,
3782    't,
3783    's,
3784    M,
3785    const RX: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3786> {
3787    ctx: &'c mut Node<'e, 's>,
3788    topic: &'t str,
3789    qos: QoSProfile,
3790    sched: Option<super::sched_context::SchedContextId>,
3791    /// phase-392 W3c -- did the CONSUMER name `RX`, or is it just the default?
3792    ///
3793    /// The two are the same const generic and mean opposite things now: an
3794    /// unnamed `RX` is a ceiling the derivation clamps to, a named one is the
3795    /// number the consumer asked for. `.rx_buffer::<N>()` is the only thing that
3796    /// sets this, so the flag cannot drift from "somebody wrote a number".
3797    rx_explicit: bool,
3798    _phantom: PhantomData<M>,
3799}
3800
3801impl<'c, 'e, 't, 's, M: MessageForRmw + 'static, const RX: usize>
3802    TypedSubscriptionBuilder<'c, 'e, 't, 's, M, RX>
3803{
3804    pub fn qos(mut self, qos: QoSProfile) -> Self {
3805        self.qos = qos;
3806        self
3807    }
3808
3809    /// Bind the subscription's callback to a scheduling context.
3810    pub fn sched_context(mut self, sc: super::sched_context::SchedContextId) -> Self {
3811        self.sched = Some(sc);
3812        self
3813    }
3814
3815    /// Set the staging-buffer size (const-generic).
3816    ///
3817    /// **this is the opt-out.** A subscription that does not
3818    /// call it is sized from `M`'s own serialized bound; calling it says "give
3819    /// me exactly `N` bytes per slot" and the derivation is skipped. Naming a
3820    /// number is the only way to spend more arena than the type needs, which is
3821    /// the direction that should require saying so.
3822    ///
3823    /// It stays the way to raise a buffer above the type's bound -- for a peer
3824    /// that pads, or a type whose `.msg` bound is looser than what it really
3825    /// sends -- and `.rx_buffer_from_type()` after it re-enters the derivation
3826    /// with `N` as the ceiling.
3827    pub fn rx_buffer<const N: usize>(self) -> TypedSubscriptionBuilder<'c, 'e, 't, 's, M, N> {
3828        TypedSubscriptionBuilder {
3829            ctx: self.ctx,
3830            topic: self.topic,
3831            qos: self.qos,
3832            sched: self.sched,
3833            rx_explicit: true,
3834            _phantom: PhantomData,
3835        }
3836    }
3837
3838    /// Size the receive buffer from `M`'s OWN serialized bound
3839    /// instead of the configured default.
3840    ///
3841    /// ```ignore
3842    /// node.subscription("/chatter")
3843    ///     .typed::<Int32>()
3844    ///     .rx_buffer_from_type()   // 12 bytes per slot, not 1024
3845    ///     .build(on_msg)?;
3846    /// ```
3847    ///
3848    /// **No longer the only way to get it.** This was opt-in,
3849    /// and its own doc said making it the default "would move every image's
3850    /// arena occupancy at once, which is a decision, not a refactor". W3c is
3851    /// that decision: a plain `.typed::<M>().build()` now derives too, wherever
3852    /// the bound is reachable, and `.rx_buffer::<N>()` is the opt-out.
3853    ///
3854    /// Two jobs are left, and they are why this method stays:
3855    ///
3856    /// * **It REFUSES an unbounded `M` at build time.** The default path cannot
3857    ///   -- erroring there would make a bound mandatory for every message type
3858    ///   in every image at once -- so it keeps `RX` for a type with no bound.
3859    ///   Calling this says the bound must exist, and the `const` assert below
3860    ///   is the error that says so.
3861    /// * **It reaches the derivation where `MessageForRmw` carries no schema.**
3862    ///   Only a backend declaring `type-descriptors` makes the type-erased
3863    ///   default site able to read a bound at all (see
3864    ///   [`default_subscription_rx_bytes`](crate::rmw_type_registry::default_subscription_rx_bytes));
3865    ///   this method names `M: nros_serdes::schema::Message` itself, so it works
3866    ///   on every backend.
3867    ///
3868    /// **What it costs and what it buys.** The buffered path stores `depth <= 1
3869    /// ? 3 : depth+1` slots of this size in the executor arena, so a bounded
3870    /// type recovers `slots * (default - bound)` bytes per subscription. The
3871    /// number is the LARGER of the type's XCDR1 and XCDR2 bounds, because the
3872    /// stack writes XCDR1 but a peer may send XCDR2 (see
3873    /// [`subscription_rx_bytes`](crate::rmw_type_registry::subscription_rx_bytes)).
3874    ///
3875    /// **An unbounded `M` fails the BUILD.** Every message type is required to
3876    /// carry a bound -- stated in the `.msg` (`string<=64`) or capped in
3877    /// `nros-codegen.toml` -- so "this type has no bound" is a defect to report,
3878    /// not a case to absorb. The alternative, quietly keeping the configured
3879    /// default, is precisely the substitution the sizing rules forbid: `None` means
3880    /// "no bound EXISTS", never "unknown", and a buffer sized from a fallback is
3881    /// the failure that rule was written to prevent. The C header already refuses
3882    /// the same thing the same way -- naming an unbounded type's
3883    /// `{PREFIX}_RX_MAX_SERIALIZED_SIZE` expands to a deliberate compile error
3884    /// carrying the member that costs the bound (`unbounded_token`) -- and this
3885    /// is that refusal on the Rust path. rustc names `M` in the instantiation
3886    /// note; the member comes from the codegen diagnostic for the same type.
3887    ///
3888    /// **The bound never GROWS the buffer.** A type larger than `RX` keeps `RX`;
3889    /// spending unbudgeted arena silently is the worse failure, and the
3890    /// too-small case already reports itself (`report_dropped_take`).
3891    ///
3892    /// Returns a builder without `.message_info()` / `.safety()` on purpose:
3893    /// those entries hold a real `[u8; RX]` array, so their size can only come
3894    /// from a const generic -- `nros::rx_buffer_for!(M)` at the call site -- and
3895    /// carrying the flag into them would silently drop it.
3896    pub fn rx_buffer_from_type(self) -> TypedSubBoundBuilder<'c, 'e, 't, 's, M, RX>
3897    where
3898        M: nros_serdes::schema::Message,
3899    {
3900        // The diagnostic lives HERE, at the opt-in, rather than in `build()`:
3901        // this is the call that asserts the type has a bound, so it is the call
3902        // the error should point at.
3903        const {
3904            assert!(
3905                crate::rmw_type_registry::subscription_rx_bytes::<M>(RX).is_some(),
3906                "this message type has NO maximum serialized size, so its receive \
3907                 buffer cannot be sized from it. Every message type must carry a \
3908                 bound: give the unbounded member one in the `.msg` \
3909                 (`string<=64`, `int32[<=8]`) or a `cap` in `nros-codegen.toml`. \
3910                 The generated C header for this type names the member that costs \
3911                 it the bound (`NROS_UNBOUNDED__<type>__field_<member>`)."
3912            )
3913        }
3914        TypedSubBoundBuilder {
3915            ctx: self.ctx,
3916            topic: self.topic,
3917            qos: self.qos,
3918            sched: self.sched,
3919            _phantom: PhantomData,
3920        }
3921    }
3922
3923    /// Surface per-message [`MessageInfo`](nros_core::MessageInfo) (seq,
3924    /// publisher GID, timestamps) to the callback — `FnMut(&M, Option<&MessageInfo>)`,
3925    /// the rclrs shape. Distinct from the generic builder's `.message_info()`
3926    /// (which yields a `RawMessageInfo` with the wire attachment).
3927    pub fn message_info(self) -> TypedSubInfoBuilder<'c, 'e, 't, 's, M, RX> {
3928        TypedSubInfoBuilder {
3929            ctx: self.ctx,
3930            topic: self.topic,
3931            qos: self.qos,
3932            sched: self.sched,
3933            rx_explicit: self.rx_explicit,
3934            _phantom: PhantomData,
3935        }
3936    }
3937
3938    /// Surface E2E-safety validation (CRC + sequence gap/duplicate) to the
3939    /// callback — `FnMut(&M, &IntegrityStatus)`.
3940    #[cfg(feature = "safety-e2e")]
3941    pub fn safety(self) -> TypedSubSafetyBuilder<'c, 'e, 't, 's, M, RX> {
3942        TypedSubSafetyBuilder {
3943            ctx: self.ctx,
3944            topic: self.topic,
3945            qos: self.qos,
3946            sched: self.sched,
3947            rx_explicit: self.rx_explicit,
3948            _phantom: PhantomData,
3949        }
3950    }
3951
3952    pub fn build<F: FnMut(&M) + 'static>(
3953        self,
3954        callback: F,
3955    ) -> Result<super::types::HandleId, NodeError> {
3956        let handle = self
3957            .ctx
3958            .executor
3959            .register_subscription_buffered_on::<M, F, RX>(
3960                self.ctx.node_id,
3961                self.topic,
3962                self.qos,
3963                callback,
3964                None, // group threaded via create_subscription_in_group; builder uses sched override
3965                // phase-392 W3c -- `None` asks the choke point to DERIVE from
3966                // `M`; `Some(RX)` is the consumer's own number, and only
3967                // `.rx_buffer::<N>()` sets that flag.
3968                if self.rx_explicit { Some(RX) } else { None },
3969            )?;
3970        if let Some(sc) = self.sched {
3971            self.ctx.executor.bind_handle_to_sched_context(handle, sc)?;
3972        }
3973        Ok(handle)
3974    }
3975}
3976
3977/// A typed subscription whose buffer is sized by `M`'s own
3978/// serialized bound (`.typed::<M>().rx_buffer_from_type()`).
3979///
3980/// Terminal by construction: `.message_info()` and `.safety()` are absent
3981/// because their entries store `[u8; RX]` and cannot take a runtime size. `RX`
3982/// survives as the CEILING -- an unbounded `M`, or one whose bound exceeds `RX`,
3983/// gets `RX` unchanged.
3984pub struct TypedSubBoundBuilder<
3985    'c,
3986    'e,
3987    't,
3988    's,
3989    M,
3990    const RX: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3991> {
3992    ctx: &'c mut Node<'e, 's>,
3993    topic: &'t str,
3994    qos: QoSProfile,
3995    sched: Option<super::sched_context::SchedContextId>,
3996    _phantom: PhantomData<M>,
3997}
3998
3999impl<'c, 'e, 't, 's, M: MessageForRmw + nros_serdes::schema::Message + 'static, const RX: usize>
4000    TypedSubBoundBuilder<'c, 'e, 't, 's, M, RX>
4001{
4002    pub fn qos(mut self, qos: QoSProfile) -> Self {
4003        self.qos = qos;
4004        self
4005    }
4006
4007    /// Bind the subscription's callback to a scheduling context.
4008    pub fn sched_context(mut self, sc: super::sched_context::SchedContextId) -> Self {
4009        self.sched = Some(sc);
4010        self
4011    }
4012
4013    pub fn build<F: FnMut(&M) + 'static>(
4014        self,
4015        callback: F,
4016    ) -> Result<super::types::HandleId, NodeError> {
4017        // Unreachable: `rx_buffer_from_type` is the only constructor of this
4018        // builder and its `const` assert already refused an unbounded `M`.
4019        let rx_bytes = crate::rmw_type_registry::subscription_rx_bytes::<M>(RX)
4020            .expect("rx_buffer_from_type asserts the bound exists at build time");
4021        let handle = self
4022            .ctx
4023            .executor
4024            .register_subscription_buffered_on::<M, F, RX>(
4025                self.ctx.node_id,
4026                self.topic,
4027                self.qos,
4028                callback,
4029                None,
4030                Some(rx_bytes),
4031            )?;
4032        if let Some(sc) = self.sched {
4033            self.ctx.executor.bind_handle_to_sched_context(handle, sc)?;
4034        }
4035        Ok(handle)
4036    }
4037}
4038
4039/// Typed subscription builder with `MessageInfo` (`.typed::<M>().message_info()`).
4040/// Callback is `FnMut(&M, Option<&MessageInfo>)`.
4041pub struct TypedSubInfoBuilder<
4042    'c,
4043    'e,
4044    't,
4045    's,
4046    M,
4047    const RX: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
4048> {
4049    ctx: &'c mut Node<'e, 's>,
4050    topic: &'t str,
4051    qos: QoSProfile,
4052    sched: Option<super::sched_context::SchedContextId>,
4053    /// Issue 1860 -- did the consumer NAME `RX` (`.rx_buffer::<N>()`), or is it
4054    /// the default the type's bound is clamped to? As `TypedSubscriptionBuilder`.
4055    rx_explicit: bool,
4056    _phantom: PhantomData<M>,
4057}
4058
4059impl<'c, 'e, 't, 's, M: MessageForRmw + 'static, const RX: usize>
4060    TypedSubInfoBuilder<'c, 'e, 't, 's, M, RX>
4061{
4062    pub fn qos(mut self, qos: QoSProfile) -> Self {
4063        self.qos = qos;
4064        self
4065    }
4066
4067    pub fn sched_context(mut self, sc: super::sched_context::SchedContextId) -> Self {
4068        self.sched = Some(sc);
4069        self
4070    }
4071
4072    pub fn rx_buffer<const N: usize>(self) -> TypedSubInfoBuilder<'c, 'e, 't, 's, M, N> {
4073        TypedSubInfoBuilder {
4074            ctx: self.ctx,
4075            topic: self.topic,
4076            qos: self.qos,
4077            sched: self.sched,
4078            rx_explicit: true,
4079            _phantom: PhantomData,
4080        }
4081    }
4082
4083    pub fn build<F: FnMut(&M, Option<&nros_core::MessageInfo>) + 'static>(
4084        self,
4085        callback: F,
4086    ) -> Result<super::types::HandleId, NodeError> {
4087        let handle = self
4088            .ctx
4089            .executor
4090            .register_subscription_with_info_sized_inner::<M, F, RX>(
4091                Some(self.ctx.node_id),
4092                self.topic,
4093                self.qos,
4094                callback,
4095                if self.rx_explicit { Some(RX) } else { None },
4096            )?;
4097        if let Some(sc) = self.sched {
4098            self.ctx.executor.bind_handle_to_sched_context(handle, sc)?;
4099        }
4100        Ok(handle)
4101    }
4102}
4103
4104/// Typed subscription builder with E2E-safety validation
4105/// (`.typed::<M>().safety()`). Callback is `FnMut(&M, &IntegrityStatus)`.
4106#[cfg(feature = "safety-e2e")]
4107pub struct TypedSubSafetyBuilder<
4108    'c,
4109    'e,
4110    't,
4111    's,
4112    M,
4113    const RX: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
4114> {
4115    ctx: &'c mut Node<'e, 's>,
4116    topic: &'t str,
4117    qos: QoSProfile,
4118    sched: Option<super::sched_context::SchedContextId>,
4119    /// Issue 1860 -- did the consumer NAME `RX` (`.rx_buffer::<N>()`), or is it
4120    /// the default the type's bound is clamped to? As `TypedSubscriptionBuilder`.
4121    rx_explicit: bool,
4122    _phantom: PhantomData<M>,
4123}
4124
4125#[cfg(feature = "safety-e2e")]
4126impl<'c, 'e, 't, 's, M: MessageForRmw + 'static, const RX: usize>
4127    TypedSubSafetyBuilder<'c, 'e, 't, 's, M, RX>
4128{
4129    pub fn qos(mut self, qos: QoSProfile) -> Self {
4130        self.qos = qos;
4131        self
4132    }
4133
4134    pub fn sched_context(mut self, sc: super::sched_context::SchedContextId) -> Self {
4135        self.sched = Some(sc);
4136        self
4137    }
4138
4139    pub fn rx_buffer<const N: usize>(self) -> TypedSubSafetyBuilder<'c, 'e, 't, 's, M, N> {
4140        TypedSubSafetyBuilder {
4141            ctx: self.ctx,
4142            topic: self.topic,
4143            qos: self.qos,
4144            sched: self.sched,
4145            rx_explicit: true,
4146            _phantom: PhantomData,
4147        }
4148    }
4149
4150    pub fn build<F: FnMut(&M, &nros_rmw::IntegrityStatus) + 'static>(
4151        self,
4152        callback: F,
4153    ) -> Result<super::types::HandleId, NodeError> {
4154        let handle = self
4155            .ctx
4156            .executor
4157            .register_subscription_with_safety_sized_inner::<M, F, RX>(
4158                Some(self.ctx.node_id),
4159                self.topic,
4160                self.qos,
4161                callback,
4162                if self.rx_explicit { Some(RX) } else { None },
4163            )?;
4164        if let Some(sc) = self.sched {
4165            self.ctx.executor.bind_handle_to_sched_context(handle, sc)?;
4166        }
4167        Ok(handle)
4168    }
4169}
4170
4171/// Generic (type-erased) subscription builder (`.generic(type, hash)`).
4172pub struct GenericSubscriptionBuilder<
4173    'c,
4174    'e,
4175    't,
4176    's,
4177    const RX: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
4178> {
4179    ctx: &'c mut Node<'e, 's>,
4180    topic: &'t str,
4181    type_name: &'t str,
4182    type_hash: &'t str,
4183    qos: QoSProfile,
4184    sched: Option<super::sched_context::SchedContextId>,
4185}
4186
4187impl<'c, 'e, 't, 's, const RX: usize> GenericSubscriptionBuilder<'c, 'e, 't, 's, RX> {
4188    pub fn qos(mut self, qos: QoSProfile) -> Self {
4189        self.qos = qos;
4190        self
4191    }
4192
4193    pub fn sched_context(mut self, sc: super::sched_context::SchedContextId) -> Self {
4194        self.sched = Some(sc);
4195        self
4196    }
4197
4198    pub fn rx_buffer<const N: usize>(self) -> GenericSubscriptionBuilder<'c, 'e, 't, 's, N> {
4199        GenericSubscriptionBuilder {
4200            ctx: self.ctx,
4201            topic: self.topic,
4202            type_name: self.type_name,
4203            type_hash: self.type_hash,
4204            qos: self.qos,
4205            sched: self.sched,
4206        }
4207    }
4208
4209    /// Surface the sample's wire attachment + metadata to the callback
4210    /// (`FnMut(&[u8], &RawMessageInfo)`). The cross-RMW bridge reads the
4211    /// bridge_origin tag from `info.attachment()` for echo suppression.
4212    pub fn message_info(self) -> GenericSubInfoBuilder<'c, 'e, 't, 's, RX> {
4213        GenericSubInfoBuilder {
4214            ctx: self.ctx,
4215            topic: self.topic,
4216            type_name: self.type_name,
4217            type_hash: self.type_hash,
4218            qos: self.qos,
4219            sched: self.sched,
4220        }
4221    }
4222
4223    pub fn build<F: FnMut(&[u8]) + 'static>(
4224        self,
4225        callback: F,
4226    ) -> Result<super::types::HandleId, NodeError> {
4227        let handle = self
4228            .ctx
4229            .executor
4230            .register_subscription_buffered_raw_on::<F, RX>(
4231                self.ctx.node_id,
4232                self.topic,
4233                self.type_name,
4234                self.type_hash,
4235                self.qos,
4236                None,
4237                callback,
4238            )?;
4239        if let Some(sc) = self.sched {
4240            self.ctx.executor.bind_handle_to_sched_context(handle, sc)?;
4241        }
4242        Ok(handle)
4243    }
4244}
4245
4246/// Generic subscription builder with `MessageInfo` surfaced
4247/// (`.message_info()`). Callback is `FnMut(&[u8], &RawMessageInfo)`.
4248pub struct GenericSubInfoBuilder<
4249    'c,
4250    'e,
4251    't,
4252    's,
4253    const RX: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
4254> {
4255    ctx: &'c mut Node<'e, 's>,
4256    topic: &'t str,
4257    type_name: &'t str,
4258    type_hash: &'t str,
4259    qos: QoSProfile,
4260    sched: Option<super::sched_context::SchedContextId>,
4261}
4262
4263impl<'c, 'e, 't, 's, const RX: usize> GenericSubInfoBuilder<'c, 'e, 't, 's, RX> {
4264    pub fn qos(mut self, qos: QoSProfile) -> Self {
4265        self.qos = qos;
4266        self
4267    }
4268
4269    pub fn sched_context(mut self, sc: super::sched_context::SchedContextId) -> Self {
4270        self.sched = Some(sc);
4271        self
4272    }
4273
4274    pub fn rx_buffer<const N: usize>(self) -> GenericSubInfoBuilder<'c, 'e, 't, 's, N> {
4275        GenericSubInfoBuilder {
4276            ctx: self.ctx,
4277            topic: self.topic,
4278            type_name: self.type_name,
4279            type_hash: self.type_hash,
4280            qos: self.qos,
4281            sched: self.sched,
4282        }
4283    }
4284
4285    pub fn build<F: FnMut(&[u8], &nros_core::RawMessageInfo) + 'static>(
4286        self,
4287        callback: F,
4288    ) -> Result<super::types::HandleId, NodeError> {
4289        let handle = self
4290            .ctx
4291            .executor
4292            .register_subscription_buffered_raw_info_on::<F, RX>(
4293                self.ctx.node_id,
4294                self.topic,
4295                self.type_name,
4296                self.type_hash,
4297                self.qos,
4298                callback,
4299            )?;
4300        if let Some(sc) = self.sched {
4301            self.ctx.executor.bind_handle_to_sched_context(handle, sc)?;
4302        }
4303        Ok(handle)
4304    }
4305}
4306
4307// `not(feature = "rmw-cffi")` — these tests use the `mock` backend
4308// (`crate::mock`, itself `cfg(all(test, not(rmw-cffi)))`); a workspace test
4309// build that unifies `rmw-cffi` on swaps `ConcreteSession` to the cffi session
4310// and drops `mock`, so the module must drop with it (matches the
4311// `mock_integration` gate in lifecycle_services.rs).
4312#[cfg(all(test, feature = "alloc", not(feature = "rmw-cffi")))]
4313mod builder_tests {
4314    use super::*;
4315    use crate::{executor::Executor, mock::MockSession};
4316    use nros_core::{CdrReader, CdrWriter, DeserError, Deserialize, SerError, Serialize};
4317
4318    struct TestMsg;
4319    impl RosMessage for TestMsg {
4320        const TYPE_NAME: &'static str = "test/msg/TestMsg";
4321        const TYPE_HASH: &'static str = "test_hash";
4322    }
4323    impl Serialize for TestMsg {
4324        fn serialize(&self, _w: &mut CdrWriter) -> Result<(), SerError> {
4325            Ok(())
4326        }
4327    }
4328    impl Deserialize for TestMsg {
4329        fn deserialize(_r: &mut CdrReader) -> Result<Self, DeserError> {
4330            Ok(Self)
4331        }
4332    }
4333    // Phase 212.K.7.6.b — minimal single-field `Message` impl so
4334    // `TypedPublisherBuilder::build` resolves under the cyclonedds-tightened
4335    // bound AND the runtime register call succeeds. `DescriptorBuilder`
4336    // rejects empty `FIELDS` with `BuildError::EmptySchema`; pretend
4337    // there's one byte so the bridge stub returns a non-NULL pointer.
4338    // phase-380 W4 — was `#[cfg(rmw_needs_type_descriptors)]`: the schema is
4339    // now required by `MessageForRmw` on EVERY backend, because that is where
4340    // a subscription's build-time size bound comes from.
4341    impl nros_serdes::schema::Message for TestMsg {
4342        const TYPE_NAME: &'static str = "test/msg/TestMsg";
4343        const FIELDS: &'static [nros_serdes::schema::Field] = &[nros_serdes::schema::Field {
4344            name: "data",
4345            ty: nros_serdes::schema::FieldType::Uint8,
4346            offset: 0,
4347        }];
4348    }
4349
4350    fn s(v: &str) -> heapless::String<64> {
4351        heapless::String::try_from(v).unwrap()
4352    }
4353
4354    #[test]
4355    fn publisher_builder_typed_and_generic() {
4356        let mut session = MockSession::new();
4357        let mut node = NodeHandle::new(
4358            s("n"),
4359            s("/"),
4360            &mut session,
4361            crate::executor::spin::RemapView {
4362                launch: &[],
4363                runtime: &[],
4364            },
4365            0,
4366        );
4367
4368        // typed: node.publisher(t).typed::<M>().qos(..).build()
4369        let _typed = node
4370            .publisher("/chatter")
4371            .typed::<TestMsg>()
4372            .qos(QoSProfile::default().keep_last(5))
4373            .build()
4374            .expect("typed publisher builds");
4375
4376        // generic: node.publisher(t).qos(..).generic(type, hash).build()
4377        let _generic = node
4378            .publisher("/chatter")
4379            .qos(QoSProfile::default())
4380            .generic("std_msgs/msg/Int32", "hash")
4381            .build()
4382            .expect("generic publisher builds");
4383    }
4384
4385    // The handle `Executor::create_node` returns resolves through the same two
4386    // tiers. Asserted on the name the BACKEND was handed (`MockPublisher`
4387    // records it), not on a helper's return value.
4388
4389    fn argv_rule(from: &'static str, to: &'static str) -> crate::ros_args::RemapArg<'static> {
4390        crate::ros_args::RemapArg {
4391            node: None,
4392            from,
4393            to,
4394        }
4395    }
4396
4397    #[test]
4398    fn create_node_handle_applies_an_argv_remap() {
4399        let mut exec: Executor = Executor::from_session(MockSession::new());
4400        crate::ros_args::install_argv_remaps(&mut exec, [argv_rule("chatter", "/from_argv")])
4401            .unwrap();
4402        let mut node = exec.create_node("talker").expect("node");
4403        let p = node
4404            .create_publisher::<TestMsg>("chatter")
4405            .expect("publisher");
4406        assert_eq!(p.handle.topic_name(), "/from_argv");
4407    }
4408
4409    #[test]
4410    fn create_node_handle_prefers_a_launch_rule_over_argv() {
4411        let mut exec: Executor = Executor::from_session(MockSession::new());
4412        crate::ros_args::install_argv_remaps(&mut exec, [argv_rule("chatter", "/from_argv")])
4413            .unwrap();
4414        exec.declare_remap("talker", "/", "chatter", "/from_launch")
4415            .unwrap();
4416        let mut node = exec.create_node("talker").expect("node");
4417        let p = node
4418            .create_publisher::<TestMsg>("chatter")
4419            .expect("publisher");
4420        assert_eq!(p.handle.topic_name(), "/from_launch");
4421    }
4422
4423    /// Issue 1971 -- the handle reads the flash launch table too, above argv.
4424    #[test]
4425    fn create_node_handle_prefers_a_flash_launch_rule_over_argv() {
4426        static LAUNCH: [crate::executor::LaunchRemap; 1] = [crate::executor::LaunchRemap::new(
4427            c"talker",
4428            c"/",
4429            c"chatter",
4430            c"/from_flash",
4431        )];
4432        let mut exec: Executor = Executor::from_session(MockSession::new());
4433        crate::ros_args::install_argv_remaps(&mut exec, [argv_rule("chatter", "/from_argv")])
4434            .unwrap();
4435        exec.set_launch_remaps(&LAUNCH);
4436        let mut node = exec.create_node("talker").expect("node");
4437        let p = node
4438            .create_publisher::<TestMsg>("chatter")
4439            .expect("publisher");
4440        assert_eq!(p.handle.topic_name(), "/from_flash");
4441    }
4442
4443    #[test]
4444    fn create_node_handle_passes_an_unmatched_name_through_unchanged() {
4445        // No rule matches, so the handle hands the backend exactly what it was
4446        // given — NOT the expanded `/talker_ns/chatter`. This handle has never
4447        // expanded names, and a remap that does not fire must not start.
4448        let mut exec: Executor = Executor::from_session(MockSession::new());
4449        crate::ros_args::install_argv_remaps(&mut exec, [argv_rule("other", "/x")]).unwrap();
4450        let mut node = exec.create_node("talker").expect("node");
4451        let p = node
4452            .create_publisher::<TestMsg>("chatter")
4453            .expect("publisher");
4454        assert_eq!(p.handle.topic_name(), "chatter");
4455    }
4456
4457    #[test]
4458    fn subscription_builder_and_convenient() {
4459        let mut exec: Executor = Executor::from_session(MockSession::new());
4460        let id = exec.node_builder("n").build().expect("node");
4461
4462        // builder: typed
4463        let _h = exec
4464            .node_mut(id)
4465            .subscription("/chatter")
4466            .typed::<TestMsg>()
4467            .qos(QoSProfile::default().keep_last(5))
4468            .build(|_m: &TestMsg| {})
4469            .expect("typed subscription builds");
4470
4471        // builder: generic (raw bytes)
4472        let _g = exec
4473            .node_mut(id)
4474            .subscription("/raw")
4475            .generic("std_msgs/msg/Int32", "hash")
4476            .build(|_b: &[u8]| {})
4477            .expect("generic subscription builds");
4478
4479        // builder: sized + sched-context (slice 3 knobs)
4480        let sc = exec.default_sched_context_id();
4481        let _s = exec
4482            .node_mut(id)
4483            .subscription("/sized")
4484            .typed::<TestMsg>()
4485            .rx_buffer::<64>()
4486            .sched_context(sc)
4487            .build(|_m: &TestMsg| {})
4488            .expect("sized + sched subscription builds");
4489
4490        // convenient (fork tier) — one node-ctx at a time, re-acquired
4491        let _c = exec
4492            .node_mut(id)
4493            .create_subscription::<TestMsg, _>("/conv", |_m: &TestMsg| {})
4494            .expect("convenient typed subscription builds");
4495    }
4496
4497    #[test]
4498    fn generic_message_info_builder() {
4499        // slice 3b — the bridge echo path: generic sub whose callback
4500        // receives the wire attachment via RawMessageInfo.
4501        let mut exec: Executor = Executor::from_session(MockSession::new());
4502        let id = exec.node_builder("n").build().expect("node");
4503
4504        let _i = exec
4505            .node_mut(id)
4506            .subscription("/info")
4507            .generic("std_msgs/msg/Int32", "hash")
4508            .message_info()
4509            .rx_buffer::<256>()
4510            .build(|_payload: &[u8], info: &nros_core::RawMessageInfo| {
4511                let _ = info.attachment();
4512            })
4513            .expect("generic + message_info subscription builds");
4514    }
4515
4516    #[test]
4517    fn typed_message_info_builder() {
4518        // M2.a — typed .message_info() (rclrs shape FnMut(&M, Option<&MessageInfo>)),
4519        // replacing register_subscription_with_info.
4520        let mut exec: Executor = Executor::from_session(MockSession::new());
4521        let id = exec.node_builder("n").build().expect("node");
4522        let _h = exec
4523            .node_mut(id)
4524            .subscription("/chatter")
4525            .typed::<TestMsg>()
4526            .qos(QoSProfile::default().keep_last(5))
4527            .message_info()
4528            .build(|_m: &TestMsg, _info: Option<&nros_core::MessageInfo>| {})
4529            .expect("typed + message_info subscription builds");
4530    }
4531
4532    #[cfg(feature = "safety-e2e")]
4533    #[test]
4534    fn typed_safety_builder() {
4535        // M2.a — typed .safety(), replacing register_subscription_with_safety.
4536        let mut exec: Executor = Executor::from_session(MockSession::new());
4537        let id = exec.node_builder("n").build().expect("node");
4538        let _h = exec
4539            .node_mut(id)
4540            .subscription("/chatter")
4541            .typed::<TestMsg>()
4542            .safety()
4543            .build(|_m: &TestMsg, _status: &nros_rmw::IntegrityStatus| {})
4544            .expect("typed + safety subscription builds");
4545    }
4546
4547    #[test]
4548    fn generator_emitted_chain_compiles() {
4549        // Locks the exact builder chain the orchestration generator emits
4550        // for a subscriber (replaces register_subscription_raw_with_qos_sized_on).
4551        let mut exec: Executor = Executor::from_session(MockSession::new());
4552        let id = exec.node_builder("n").build().expect("node");
4553        let _h = exec
4554            .node_mut(id)
4555            .subscription("/topic")
4556            .generic("std_msgs/msg/Int32", "hash")
4557            .qos(QoSProfile::default().keep_last(1))
4558            .rx_buffer::<1024>()
4559            .build(|_data: &[u8]| {})
4560            .expect("generator-shape subscription builds");
4561    }
4562
4563    #[test]
4564    fn nodectx_publisher_and_bridge_shape() {
4565        // Node publisher symmetry + the bridge two-ctx borrow pattern:
4566        // build the dest publisher on one Node (dropped), then register
4567        // the source subscription on another — the owned publisher outlives.
4568        let mut exec: Executor = Executor::from_session(MockSession::new());
4569        let id = exec.node_builder("n").build().expect("node");
4570
4571        // convenient + builder publisher on Node
4572        let _p = exec
4573            .node_mut(id)
4574            .create_publisher::<TestMsg>("/p")
4575            .expect("ctx convenient publisher");
4576        let dest_pub = exec
4577            .node_mut(id)
4578            .publisher("/fwd")
4579            .generic("std_msgs/msg/Int32", "hash")
4580            .build()
4581            .expect("ctx generic publisher builds"); // Node dropped here
4582
4583        // re-borrow exec for the source sub; closure owns dest_pub
4584        let _s = exec
4585            .node_mut(id)
4586            .subscription("/src")
4587            .generic("std_msgs/msg/Int32", "hash")
4588            .message_info()
4589            .build(move |payload: &[u8], _info: &nros_core::RawMessageInfo| {
4590                let _ = dest_pub.publish_serialized(payload);
4591            })
4592            .expect("bridge-shape source subscription builds");
4593    }
4594}