Skip to main content

nros_node/executor/
handles.rs

1//! Entity wrapper types for the embedded executor.
2
3use core::marker::PhantomData;
4
5use nros_core::{CdrReader, CdrWriter, Deserialize, RosAction, RosMessage, RosService, Serialize};
6use nros_rmw::{ClientTrait, Publisher, ServiceTrait, Subscription as _, TransportError};
7
8use crate::session;
9
10use super::types::{DEFAULT_TX_BUF, NodeError};
11
12/// Default polling interval (ms) for sync wait loops.
13pub(super) const DEFAULT_SPIN_INTERVAL_MS: u64 = 10;
14
15/// Check whether the given budget has been exhausted.
16///
17/// `std` builds measure wall-clock against `Instant::now()`; `no_std`
18/// builds count iterations and exhaust after `max_iterations` calls.
19///
20/// **Phase 89.8**: the plain `max_iters` approach is insufficient on
21/// multi-threaded zpico backends (POSIX/Zephyr/NuttX). There,
22/// `executor.spin_once(10ms)` waits on a condvar that zenoh-pico's
23/// background tasks signal on any inbound frame (keep-alives,
24/// discovery gossip, interest messages). Each signal returns the
25/// spin well before the 10 ms budget, so a nominal
26/// `1000 × 10 ms = 10 s` iteration count collapses to milliseconds
27/// of real time and the wait returns `Timeout` long before the
28/// awaited reply can arrive.
29///
30/// Same class of bug 89.2 fixed in `nros-c`'s blocking service call
31/// and 89.3 fixed in `nros-cpp`'s action-client helpers. The
32/// maintainer explicitly flagged this `Promise::wait` / `wait_next`
33/// path in the 89.2 commit: *"Promise::wait in nros-node has the
34/// same structural bug but currently passes all tests. Left on
35/// max_spins until a test surfaces it."* The NuttX Rust action
36/// E2E is that test.
37pub(super) struct WaitBudget {
38    /// The clock this budget is counting against, when the build has one.
39    ///
40    /// phase-359 W10 — this used to be a `std`/`no_std` PAIR: a
41    /// `std::time::Instant` deadline on one side, an iteration count on the
42    /// other. Which one a build got was decided by whether some crate in the
43    /// graph named `std`, so dropping that feature from a hosted consumer
44    /// silently converted every timeout in this file into "N spins" — a
45    /// different quantity wearing the same name.
46    ///
47    /// The choice is now made on what the build can actually DO. Any build with
48    /// a clock — every platform port exports one — gets a real deadline. The
49    /// iteration count survives as the honest fallback for a build with no
50    /// clock at all, which is what it always was.
51    clock: Option<fn() -> u64>,
52    /// Absolute deadline in `clock`'s µs, meaningful when `clock` is `Some`.
53    deadline_us: u64,
54    /// Iterations left, meaningful when `clock` is `None`.
55    remaining: u64,
56    /// The TOTAL the caller allowed, in µs. Kept for the no-clock build: it
57    /// cannot measure elapsed time, but it still knows that a single spin must
58    /// never exceed the whole budget (phase-436 W4).
59    timeout_us: u64,
60}
61
62impl WaitBudget {
63    pub(super) fn new(max_iterations: u64, timeout: core::time::Duration) -> Self {
64        let clock = super::spin::default_clock_us_fn();
65        let timeout_us = timeout.as_micros().min(u64::MAX as u128) as u64;
66        Self {
67            clock,
68            deadline_us: clock.map(|c| c().saturating_add(timeout_us)).unwrap_or(0),
69            remaining: max_iterations,
70            timeout_us,
71        }
72    }
73
74    /// phase-436 W4 (issue 1195) — how long the next poll may spin without
75    /// overshooting the caller's deadline.
76    ///
77    /// These loops used a FIXED `DEFAULT_SPIN_INTERVAL_MS` and consulted the
78    /// budget only afterwards, so the last iteration always overshot: with
79    /// `max_spins` flooring at 1, `wait(1ms)` ran a full `spin_once(10ms)`.
80    /// The deadline was already in hand — it was simply checked one spin too
81    /// late.
82    ///
83    /// With no clock the build has no deadline to measure against, so the
84    /// caller's interval stands; that is the same honest fallback `tick`
85    /// makes.
86    pub(super) fn next_spin_interval(&self, default: core::time::Duration) -> core::time::Duration {
87        let Some(clock) = self.clock else {
88            // No clock: elapsed is unknowable, but the TOTAL budget is not, and
89            // one spin may never exceed it.
90            let whole = core::time::Duration::from_micros(self.timeout_us);
91            return if whole < default { whole } else { default };
92        };
93        let now = clock();
94        if now >= self.deadline_us {
95            return core::time::Duration::ZERO;
96        }
97        let remaining = core::time::Duration::from_micros(self.deadline_us - now);
98        if remaining < default {
99            remaining
100        } else {
101            default
102        }
103    }
104
105    pub(super) fn tick(&mut self) -> bool {
106        match self.clock {
107            Some(clock) => clock() < self.deadline_us,
108            None => {
109                if self.remaining == 0 {
110                    false
111                } else {
112                    self.remaining -= 1;
113                    true
114                }
115            }
116        }
117    }
118}
119
120/// UUID byte count in a ROS 2 GoalUuid.
121///
122/// CDR encoding: a fixed `uint8[16]` array — ROS 2 `unique_identifier_msgs/UUID`
123/// — with **no** length prefix (fixed arrays are unprefixed in CDR).
124const GOAL_UUID_SIZE: usize = 16;
125
126// ============================================================================
127// EmbeddedPublisher
128// ============================================================================
129
130/// Typed publisher handle.
131///
132/// Two methods, both byte-oriented at the wire:
133///
134/// - [`publish`](Self::publish) / [`publish_with_buffer`](Self::publish_with_buffer)
135///   — accept `&M: RosMessage`, CDR-encode into a stack buffer, then
136///   call [`Publisher::publish_raw`](nros_rmw::Publisher::publish_raw).
137/// - [`publish_serialized`](Self::publish_serialized) — accepts pre-encoded CDR bytes
138///   for callers that already produced the wire payload.
139///
140/// **No typed `loan()` exists.** Loan/borrow live exclusively on
141/// [`EmbeddedRawPublisher`] / [`RawSubscription`]. `try_loan(len)`
142/// requires the byte length up front, which CDR ser/de can only
143/// discover after encoding — the two APIs are incompatible by
144/// construction. See `docs/design/0010-zero-copy-raw-api.md` decision D7.
145pub struct EmbeddedPublisher<M> {
146    pub(crate) handle: session::RmwPublisher,
147    /// Whether the creating node's lifecycle state lets this publisher send.
148    pub(crate) gate: crate::lifecycle::PublisherGate,
149    /// Phase 108 — registered event closures kept alive for the
150    /// publisher's lifetime; freed in `Drop`.
151    pub(crate) event_regs: EventRegs,
152    /// RFC-0052 W3b.4 — contracted endpoint's publish counter (`None`
153    /// for uncontracted publishers; one relaxed atomic bump when set).
154    pub(crate) monitor: Option<&'static crate::executor::monitor::PubMonitorCell>,
155    /// Epoch clock for the publish-stamp observation, paired with `monitor`
156    /// the way the subscriber's `AgeMon` pairs cell and clock. Separate
157    /// field rather than a tuple so an uncontracted publisher costs nothing
158    /// and the existing `monitor` construction sites keep their shape.
159    pub(crate) epoch: Option<fn() -> u64>,
160    pub(crate) _phantom: PhantomData<M>,
161}
162
163impl<M> Drop for EmbeddedPublisher<M> {
164    fn drop(&mut self) {
165        drop_event_regs(&mut self.event_regs);
166    }
167}
168
169impl<M: RosMessage> EmbeddedPublisher<M> {
170    /// Publish a message using the default buffer size.
171    ///
172    /// Takes the message borrowed (`publish(&msg)`) or owned
173    /// (`publish(msg)`), as rclrs's `publish(impl MessageCow)` does. Both
174    /// serialise immediately into the stack buffer, so owning buys no deferred
175    /// path; it only lets an rclrs call site that hands its message over
176    /// compile unchanged. `core::borrow::Borrow` is the one trait, so no
177    /// `MessageCow` type is added.
178    pub fn publish(&self, msg: impl core::borrow::Borrow<M>) -> Result<(), NodeError> {
179        self.publish_with_buffer::<DEFAULT_TX_BUF>(msg.borrow())
180    }
181
182    /// Publish a message with a custom buffer size.
183    pub fn publish_with_buffer<const BUF: usize>(&self, msg: &M) -> Result<(), NodeError> {
184        if self.gate.drops(self.handle.topic_name()) {
185            return Ok(());
186        }
187        let mut buffer = [0u8; BUF];
188        let mut writer = crate::tx_writer(&mut buffer).map_err(|_| NodeError::BufferTooSmall)?;
189        msg.serialize(&mut writer)
190            .map_err(|_| NodeError::Serialization)?;
191        let len = writer.position();
192        self.bump_monitor();
193        self.observe_publish_stamp(&buffer[..len]);
194        self.handle
195            .publish_raw(&buffer[..len])
196            // Issue 2978 -- the backend's own refusal (MessageTooLarge, WouldBlock,
197            // SessionLost ...), not a flattened PublishFailed.
198            .map_err(NodeError::Transport)
199    }
200
201    /// RFC-0052 W3b.4 — one relaxed bump per publish on contracted
202    /// endpoints; a predictable no-op otherwise.
203    /// Record how old the data we just put on the wire was.
204    ///
205    /// Folds away completely for a type with no `STAMP_OFFSET`, an
206    /// uncontracted publisher, or a build with no epoch source -- the same
207    /// three exits as the subscriber's `observe_age`.
208    #[inline]
209    fn observe_publish_stamp(&self, raw: &[u8]) {
210        if let (Some(cell), Some(epoch), Some(off)) =
211            (self.monitor, self.epoch, <M as RosMessage>::STAMP_OFFSET)
212        {
213            crate::executor::monitor::observe_publish_stamp(cell, raw, off, epoch());
214        }
215    }
216
217    #[inline]
218    fn bump_monitor(&self) {
219        if let Some(cell) = self.monitor {
220            cell.count
221                .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
222        }
223        // phase-463 W7 — every publish path passes here, so this is where the
224        // host profile learns which topics the dispatching callback published.
225        #[cfg(all(feature = "profile-mode", feature = "rmw-cffi"))]
226        crate::executor::profile::on_publish(self.handle.topic_name());
227    }
228
229    /// Publish CDR-encoded data (must include the CDR header) — rcl's
230    /// `rcl_publish_serialized_message`, rclcpp's `publish(SerializedMessage)`.
231    pub fn publish_serialized(&self, data: &[u8]) -> Result<(), NodeError> {
232        if self.gate.drops(self.handle.topic_name()) {
233            return Ok(());
234        }
235        self.bump_monitor();
236        self.handle
237            .publish_raw(data)
238            // Issue 2978 -- the backend's own refusal (MessageTooLarge, WouldBlock,
239            // SessionLost ...), not a flattened PublishFailed.
240            .map_err(NodeError::Transport)
241    }
242
243    /// Renamed to [`publish_serialized`](Self::publish_serialized),
244    /// the transmit word of the receive side's `take_serialized`.
245    // phase-515 C8 renamed it.
246    #[deprecated(
247        since = "0.6.0",
248        note = "renamed to `publish_serialized`; call it instead"
249    )]
250    pub fn publish_raw(&self, data: &[u8]) -> Result<(), NodeError> {
251        self.publish_serialized(data)
252    }
253
254    /// Streamed publish. Use a closure-driven writer
255    /// to serialise straight into the backend's outbound buffer
256    /// without a per-publisher staging copy. Saves on RAM-constrained
257    /// nodes that publish multi-KB payloads.
258    ///
259    /// `total_len` declares the payload length up front, and the backend
260    /// reserves that many bytes in its outbound buffer before any chunk
261    /// lands. The `writer` closure is then handed the slot one chunk
262    /// (`&mut [u8]`) at a time and returns how many bytes it wrote. (It
263    /// was handed a ~~`StreamWriter`~~ with `write` / `extend` /
264    /// ~~`reserve_total`~~ before.)
265    ///
266    /// Backends without a native stream slot fall through to a
267    /// stack-allocated staging buffer (capped at 4 KiB) + a single
268    /// `publish_raw` — same observable result, just no zero-staging
269    /// win for the big-message case.
270    pub fn publish_streamed<F>(&self, total_len: usize, writer: F) -> Result<(), NodeError>
271    where
272        F: FnMut(&mut [u8]) -> usize,
273    {
274        if self.gate.drops(self.handle.topic_name()) {
275            return Ok(());
276        }
277        // Wrap the closure in a `*mut c_void` so it survives the
278        // crossing into the C callback contract the vtable expects.
279        // The closure is consumed by reference, so the lifetime is
280        // bounded by this function's frame — no escape.
281        use nros_rmw::Publisher;
282        struct Ctx<W> {
283            writer: W,
284            total: usize,
285        }
286        unsafe extern "C" fn size_cb<W>(
287            out_total_len: *mut usize,
288            user_ctx: *mut core::ffi::c_void,
289        ) {
290            unsafe {
291                let ctx = &*(user_ctx as *const Ctx<W>);
292                *out_total_len = ctx.total;
293            }
294        }
295        unsafe extern "C" fn chunk_cb<W: FnMut(&mut [u8]) -> usize>(
296            out_buf: *mut u8,
297            cap: usize,
298            out_written: *mut usize,
299            user_ctx: *mut core::ffi::c_void,
300        ) {
301            unsafe {
302                let ctx = &mut *(user_ctx as *mut Ctx<W>);
303                let slot = core::slice::from_raw_parts_mut(out_buf, cap);
304                let n = (ctx.writer)(slot);
305                *out_written = n;
306            }
307        }
308        let mut ctx = Ctx {
309            writer,
310            total: total_len,
311        };
312        let ctx_ptr = &mut ctx as *mut Ctx<F> as *mut core::ffi::c_void;
313        // SAFETY: `ctx` lives until this call returns, and both callbacks
314        // only cast `user_ctx` back to that stack-local `Ctx<F>`.
315        unsafe {
316            self.handle
317                .publish_streamed(size_cb::<F>, chunk_cb::<F>, ctx_ptr)
318        }
319        .map_err(NodeError::Transport)
320    }
321
322    /// Manually assert this publisher's liveliness.
323    /// Required for publishers configured with
324    /// [`QoSLivelinessPolicy::ManualByTopic`](nros_rmw::QoSLivelinessPolicy::ManualByTopic) /
325    /// [`QoSLivelinessPolicy::ManualByNode`](nros_rmw::QoSLivelinessPolicy::ManualByNode). No-op for AUTOMATIC /
326    /// NONE kinds. Returns `Err(Unsupported)` if the backend doesn't
327    /// implement manual liveliness — which, after the RMW
328    /// gap-closure design study, includes **zenoh under a manual
329    /// kind**: its liveliness is a session keepalive, and a `Ok(())` from a
330    /// call that put nothing on the wire was the wrong answer. Cyclone
331    /// performs the assertion for real.
332    pub fn assert_liveliness(&self) -> Result<(), NodeError> {
333        use nros_rmw::Publisher as _;
334        self.handle
335            .assert_liveliness()
336            .map_err(NodeError::Transport)
337    }
338
339    /// This publisher's own global identifier — upstream
340    /// `rmw_get_gid_for_publisher` / `rclcpp::PublisherBase::get_gid`.
341    ///
342    /// From the RMW gap-closure design study. 24 bytes,
343    /// [`nros_rmw::PUBLISHER_GID_SIZE`], the width upstream's
344    /// `RMW_GID_STORAGE_SIZE` uses.
345    ///
346    /// **Three bounds, each of which a caller will otherwise assume away:**
347    ///
348    /// * **How many of the 24 bytes mean anything is a BACKEND property.**
349    ///   zenoh fills 16 and zero-extends the rest; Cyclone fills a 16-byte
350    ///   DDS writer GUID the same way, and XRCE the 16-byte DDS GUID its
351    ///   graph derives for the Agent-side writer. The padding has one spelling
352    ///   ([`nros_rmw::pad_publisher_gid`]) so two gids naming one entity
353    ///   compare equal.
354    /// * **Comparable with a gid from a TAKE** on zenoh and Cyclone. A
355    ///   received sample's
356    ///   [`MessageInfo::publisher_gid`](nros_core::MessageInfo::publisher_gid)
357    ///   is produced from the same source as this: zenoh's
358    ///   XXH3-128 of the publisher's liveliness keyexpr, Cyclone's writer
359    ///   GUID — the same gid `ros2 topic info --verbose` prints.
360    /// * **`Err(Unsupported)` is a real answer, and it is not zero.** A
361    ///   backend with no identity for this publisher (uORB; XRCE when its
362    ///   GUID probe went unanswered) says so;
363    ///   nothing here ever hands back an all-zero gid, because that is what
364    ///   an unwritten buffer holds.
365    pub fn get_gid(&self) -> Result<[u8; nros_rmw::PUBLISHER_GID_SIZE], NodeError> {
366        use nros_rmw::Publisher as _;
367        self.handle.get_gid().map_err(NodeError::Transport)
368    }
369
370    // ====================================================================
371    // Phase 108 — status events
372    // ====================================================================
373    //
374    // Publisher-side: `LivelinessLost` and `OfferedDeadlineMissed`.
375    // Returns `NodeError::Transport(TransportError::Unsupported)` if
376    // the active backend doesn't generate the event for this entity.
377
378    /// `true` if the active backend can fire the named event for this
379    /// publisher.
380    #[cfg(feature = "alloc")]
381    pub fn supports_event(&self, kind: nros_rmw::EventKind) -> bool {
382        use nros_rmw::Publisher as _;
383        self.handle.supports_event(kind)
384    }
385
386    /// Register a callback for `LivelinessLost`. Fires when this
387    /// publisher misses its own liveliness assertion deadline.
388    #[cfg(feature = "alloc")]
389    pub fn on_liveliness_lost<F>(&mut self, cb: F) -> Result<(), NodeError>
390    where
391        F: FnMut(nros_rmw::CountStatus) + Send + 'static,
392    {
393        register_pub_event::<F, _>(
394            &mut self.handle,
395            &mut self.event_regs,
396            nros_rmw::EventKind::LivelinessLost,
397            0,
398            cb,
399            |payload, f| {
400                if let nros_rmw::EventPayload::LivelinessLost(s) = payload {
401                    f(*s);
402                }
403            },
404        )
405    }
406
407    /// Register a callback for `OfferedDeadlineMissed`. Fires when
408    /// this publisher promised `deadline` and falls behind.
409    #[cfg(feature = "alloc")]
410    pub fn on_offered_deadline_missed<F>(
411        &mut self,
412        deadline: core::time::Duration,
413        cb: F,
414    ) -> Result<(), NodeError>
415    where
416        F: FnMut(nros_rmw::CountStatus) + Send + 'static,
417    {
418        register_pub_event::<F, _>(
419            &mut self.handle,
420            &mut self.event_regs,
421            nros_rmw::EventKind::OfferedDeadlineMissed,
422            deadline.as_millis().min(u32::MAX as u128) as u32,
423            cb,
424            |payload, f| {
425                if let nros_rmw::EventPayload::OfferedDeadlineMissed(s) = payload {
426                    f(*s);
427                }
428            },
429        )
430    }
431
432    /// Register a callback for `PublicationMatched` — upstream
433    /// `RMW_EVENT_PUBLICATION_MATCHED` / rclcpp's
434    /// `PublisherEventCallbacks::matched_callback`. Fires when a subscription
435    /// starts or stops matching this publisher; `current_count` is how many
436    /// match now.
437    ///
438    /// **When it is observed is a backend property.** Both backends that
439    /// carry it (Cyclone DDS, zenoh) poll it from the publisher's own data
440    /// path — `publish` and [`assert_liveliness`](Self::assert_liveliness) —
441    /// so a publisher that waits for a listener before its first publish
442    /// calls `assert_liveliness()` in its wait loop to give it a poll point.
443    #[cfg(feature = "alloc")]
444    pub fn on_matched<F>(&mut self, cb: F) -> Result<(), NodeError>
445    where
446        F: FnMut(nros_rmw::MatchedStatus) + Send + 'static,
447    {
448        register_pub_event::<F, _>(
449            &mut self.handle,
450            &mut self.event_regs,
451            nros_rmw::EventKind::PublicationMatched,
452            0,
453            cb,
454            |payload, f| {
455                if let nros_rmw::EventPayload::PublicationMatched(s) = payload {
456                    f(*s);
457                }
458            },
459        )
460    }
461
462    /// Register a callback for `PublisherIncompatibleType` —
463    /// upstream `RMW_EVENT_PUBLISHER_INCOMPATIBLE_TYPE` / rclcpp's
464    /// `PublisherEventCallbacks::incompatible_type_callback`. Fires when a
465    /// subscription on this topic NAME with a different type is seen.
466    #[cfg(feature = "alloc")]
467    pub fn on_incompatible_type<F>(&mut self, cb: F) -> Result<(), NodeError>
468    where
469        F: FnMut(nros_rmw::IncompatibleTypeStatus) + Send + 'static,
470    {
471        register_pub_event::<F, _>(
472            &mut self.handle,
473            &mut self.event_regs,
474            nros_rmw::EventKind::PublisherIncompatibleType,
475            0,
476            cb,
477            |payload, f| {
478                if let nros_rmw::EventPayload::PublisherIncompatibleType(s) = payload {
479                    f(*s);
480                }
481            },
482        )
483    }
484
485    /// The topic this publisher was created on — rclrs's
486    /// `PublisherState::topic_name`, C's `rcl_publisher_get_topic_name`,
487    /// C++'s `Publisher::get_topic_name`.
488    ///
489    /// **`&self`, which is upstream's own signature.** The ledger row this
490    /// closes (`rust:Publisher::topic_name`) argued the accessor had to take
491    /// the node or the executor as well, because "our Rust entity handle is a
492    /// bare arena index with no back-reference — `PublisherHandle { index,
493    /// _marker }`". Measured, that is a DIFFERENT type:
494    /// [`Node::create_publisher`](super::node::Node::create_publisher)
495    /// hands back an `EmbeddedPublisher`, which OWNS its backend handle, and
496    /// that handle has retained the name since creation
497    /// (`CffiPublisher::topic_name`, written from the caller's string at
498    /// `publisher_create`). Nothing is indexed and nothing is re-resolved.
499    ///
500    /// BORROWED, never owned: rclrs returns `String`, which needs an allocator
501    /// a 128 KiB target does not have. The bytes live in the backend handle for
502    /// as long as the publisher does, so a caller that wants an owned copy can
503    /// make one and a caller that does not pays nothing.
504    ///
505    /// **Not on the [`nros_rmw::Publisher`] trait, deliberately.** The C-ABI
506    /// shim above every backend already retains the name, so a trait method
507    /// would make each backend keep a SECOND copy of a 256-byte string for a
508    /// call that never reaches it. Contrast `actual_qos`, which IS on the trait
509    /// because only the backend can answer it.
510    pub fn topic_name(&self) -> &str {
511        self.handle.topic_name()
512    }
513
514    /// How many subscriptions this publisher reaches, RIGHT NOW —
515    /// rclcpp's `Publisher::get_subscription_count`, rcl's
516    /// `rclc_publisher_get_subscription_count`.
517    ///
518    /// **Upstream's question where the backend can answer it, a weaker one
519    /// where it cannot — and the difference belongs here rather than in a
520    /// surprise.** Upstream counts the subscriptions MATCHED to THIS
521    /// publisher — peers whose QoS is compatible with it — through
522    /// `rmw_publisher_count_matched_subscriptions`. A backend that fills that
523    /// slot (Cyclone) is asked first and its answer is upstream's exactly.
524    /// Only when it answers `Unsupported` does this fall back to the graph:
525    /// every subscription DISCOVERED on the topic, matched or not, because
526    /// that is what the graph can answer and a backend with no QoS
527    /// negotiation cannot tell the two apart at all.
528    ///
529    /// The fallback is non-inverting, and in the safe direction: a topic
530    /// nobody subscribes to still reads `0`, so the use this exists for —
531    /// skip the work when nobody is listening — is answered exactly. An
532    /// INCOMPATIBLE peer makes it read `1` where upstream reads `0`, i.e. you
533    /// do work nobody receives. Never the reverse.
534    ///
535    /// **Takes the executor**, which upstream does not, and that is forced: we
536    /// open ONE transport session per image and the [`Executor`] owns it, so
537    /// the graph is the executor's to read — the same receiver difference as
538    /// every other graph verb. The compiler demands the
539    /// argument, which is the adoption rule's mechanical-edit test.
540    ///
541    /// Reports what has been DISCOVERED and never blocks, so a small answer
542    /// right after startup is "not seen yet", never "not there"; and
543    /// `Err(Transport(Unsupported))` from a backend with no graph is a
544    /// DIFFERENT answer from `0`, which must not be collapsed into one.
545    ///
546    /// [`Executor`]: super::spin::Executor
547    pub fn get_subscription_count(
548        &self,
549        executor: &mut super::spin::Executor<'_>,
550    ) -> Result<usize, NodeError> {
551        match nros_rmw::Publisher::count_matched_subscriptions(&self.handle) {
552            Err(nros_rmw::TransportError::Unsupported) => {
553                executor.count_subscribers(self.handle.topic_name())
554            }
555            other => other.map_err(NodeError::Transport),
556        }
557    }
558}
559
560/// Cap on registered event callbacks per entity. Subscribers can hold
561/// up to 5 (LivelinessChanged + RequestedDeadlineMissed + MessageLost +
562/// SubscriptionMatched + SubscriptionIncompatibleType); publishers up to 4
563/// (LivelinessLost + OfferedDeadlineMissed + PublicationMatched +
564/// PublisherIncompatibleType, issue 1972). One vec type fits both — the
565/// extra slot is unused on publishers.
566#[cfg(feature = "alloc")]
567pub(crate) const MAX_EVENTS_PER_ENTITY: usize = 5;
568
569/// One row of the per-entity event-callback registry. Stores enough to
570/// type-erase the boxed closure for `Drop`-time deallocation.
571#[cfg(feature = "alloc")]
572#[derive(Clone, Copy)]
573pub(crate) struct EventReg {
574    /// `Box::into_raw`-derived pointer; valid for the entity's lifetime.
575    pub(crate) ctx: *mut core::ffi::c_void,
576    /// Type-erased destructor. Calls `Box::from_raw` w/ the originating
577    /// monomorphic type, dropping the closure + freeing the heap slot.
578    pub(crate) drop_fn: unsafe fn(*mut core::ffi::c_void),
579}
580
581#[cfg(feature = "alloc")]
582pub(crate) type EventRegs = heapless::Vec<EventReg, MAX_EVENTS_PER_ENTITY>;
583
584/// Empty placeholder for no-alloc builds — keeps struct layout stable
585/// across feature combinations without paying any space.
586#[cfg(not(feature = "alloc"))]
587#[derive(Default, Clone, Copy)]
588pub(crate) struct EventRegs;
589
590/// Empty initial value for the `event_regs` field. Selected at compile
591/// time so call sites are uniform across feature combinations
592/// (`heapless::Vec::new()` for `alloc`; unit-struct constructor
593/// otherwise — clippy's `default_constructed_unit_structs` lint
594/// rejects the `EventRegs::default()` form on the unit-struct branch).
595#[cfg(feature = "alloc")]
596#[inline]
597pub(crate) fn empty_event_regs() -> EventRegs {
598    heapless::Vec::new()
599}
600#[cfg(not(feature = "alloc"))]
601#[inline]
602pub(crate) fn empty_event_regs() -> EventRegs {
603    EventRegs
604}
605
606#[cfg(feature = "alloc")]
607pub(crate) fn drop_event_regs(regs: &mut EventRegs) {
608    while let Some(reg) = regs.pop() {
609        // SAFETY: `reg.ctx` was obtained from `Box::into_raw` of the
610        // monomorphic type that `reg.drop_fn` knows about. Each reg is
611        // visited exactly once because we drain via `pop`.
612        unsafe { (reg.drop_fn)(reg.ctx) };
613    }
614}
615
616#[cfg(not(feature = "alloc"))]
617#[inline]
618pub(crate) fn drop_event_regs(_regs: &mut EventRegs) {}
619
620#[cfg(feature = "alloc")]
621fn register_pub_event<F, D>(
622    handle: &mut session::RmwPublisher,
623    regs: &mut EventRegs,
624    kind: nros_rmw::EventKind,
625    deadline_ms: u32,
626    user_cb: F,
627    dispatch: D,
628) -> Result<(), NodeError>
629where
630    F: Send + 'static,
631    D: Fn(nros_rmw::EventPayload<'_>, &mut F) + 'static,
632{
633    use nros_rmw::Publisher as _;
634    if regs.is_full() {
635        return Err(NodeError::Transport(TransportError::Unsupported));
636    }
637    // issue 1551 — fallible: this runs from a C/C++ `*_event_init` that has an
638    // error return, and an infallible `Box::new` on an exhausted heap is
639    // libstd's OOM hook (0589's stdio recursion on Zephyr native_sim).
640    let Ok(state) = nros_rmw::fallible::try_box(EventClosureState { user_cb, dispatch }) else {
641        return Err(NodeError::Transport(TransportError::BadAlloc));
642    };
643    let user_ctx = alloc::boxed::Box::into_raw(state) as *mut core::ffi::c_void;
644    // SAFETY: trampoline downcasts `user_ctx` back to the boxed
645    // EventClosureState. Box ownership is recorded in `regs`; entity
646    // Drop walks the registry and frees via `drop_event_state::<F, D>`.
647    let res = unsafe {
648        handle.register_event_callback(kind, deadline_ms, event_trampoline::<F, D>, user_ctx)
649    };
650    match res {
651        Ok(()) => {
652            // is_full check above guarantees push() succeeds.
653            let _ = regs.push(EventReg {
654                ctx: user_ctx,
655                drop_fn: drop_event_state::<F, D>,
656            });
657            Ok(())
658        }
659        Err(e) => {
660            // SAFETY: backend rejected the registration; reclaim the
661            // box we just leaked into raw form.
662            unsafe {
663                drop(alloc::boxed::Box::from_raw(
664                    user_ctx as *mut EventClosureState<F, D>,
665                ));
666            }
667            Err(NodeError::Transport(e))
668        }
669    }
670}
671
672#[cfg(feature = "alloc")]
673struct EventClosureState<F, D> {
674    user_cb: F,
675    dispatch: D,
676}
677
678#[cfg(feature = "alloc")]
679unsafe extern "C" fn event_trampoline<F, D>(
680    kind: nros_rmw::EventKind,
681    payload_ptr: *const core::ffi::c_void,
682    user_ctx: *mut core::ffi::c_void,
683) where
684    F: Send + 'static,
685    D: Fn(nros_rmw::EventPayload<'_>, &mut F) + 'static,
686{
687    let state = unsafe { &mut *(user_ctx as *mut EventClosureState<F, D>) };
688    let payload = unsafe { nros_rmw::payload_from_raw(kind, payload_ptr) };
689    (state.dispatch)(payload, &mut state.user_cb);
690}
691
692#[cfg(feature = "alloc")]
693unsafe fn drop_event_state<F, D>(ctx: *mut core::ffi::c_void)
694where
695    F: Send + 'static,
696    D: Fn(nros_rmw::EventPayload<'_>, &mut F) + 'static,
697{
698    // SAFETY: caller guarantees `ctx` was obtained from
699    // `Box::into_raw::<EventClosureState<F, D>>` and not yet freed.
700    unsafe {
701        drop(alloc::boxed::Box::from_raw(
702            ctx as *mut EventClosureState<F, D>,
703        ));
704    }
705}
706
707#[cfg(feature = "alloc")]
708fn register_sub_event_count<F, D>(
709    handle: &mut session::RmwSubscriber,
710    regs: &mut EventRegs,
711    kind: nros_rmw::EventKind,
712    deadline_ms: u32,
713    user_cb: F,
714    dispatch: D,
715) -> Result<(), NodeError>
716where
717    F: Send + 'static,
718    D: Fn(nros_rmw::EventPayload<'_>, &mut F) + 'static,
719{
720    use nros_rmw::Subscription as _;
721    if regs.is_full() {
722        return Err(NodeError::Transport(TransportError::Unsupported));
723    }
724    // issue 1551 — fallible: this runs from a C/C++ `*_event_init` that has an
725    // error return, and an infallible `Box::new` on an exhausted heap is
726    // libstd's OOM hook (0589's stdio recursion on Zephyr native_sim).
727    let Ok(state) = nros_rmw::fallible::try_box(EventClosureState { user_cb, dispatch }) else {
728        return Err(NodeError::Transport(TransportError::BadAlloc));
729    };
730    let user_ctx = alloc::boxed::Box::into_raw(state) as *mut core::ffi::c_void;
731    let res = unsafe {
732        handle.register_event_callback(kind, deadline_ms, event_trampoline::<F, D>, user_ctx)
733    };
734    match res {
735        Ok(()) => {
736            let _ = regs.push(EventReg {
737                ctx: user_ctx,
738                drop_fn: drop_event_state::<F, D>,
739            });
740            Ok(())
741        }
742        Err(e) => {
743            unsafe {
744                drop(alloc::boxed::Box::from_raw(
745                    user_ctx as *mut EventClosureState<F, D>,
746                ));
747            }
748            Err(NodeError::Transport(e))
749        }
750    }
751}
752
753#[cfg(feature = "alloc")]
754fn register_sub_event_liveliness<F>(
755    handle: &mut session::RmwSubscriber,
756    regs: &mut EventRegs,
757    user_cb: F,
758) -> Result<(), NodeError>
759where
760    F: FnMut(nros_rmw::LivelinessChangedStatus) + Send + 'static,
761{
762    use nros_rmw::Subscription as _;
763    if regs.is_full() {
764        return Err(NodeError::Transport(TransportError::Unsupported));
765    }
766    // issue 1551 — fallible: this runs from a C/C++ `*_event_init` that has an
767    // error return, and an infallible `Box::new` on an exhausted heap is
768    // libstd's OOM hook (0589's stdio recursion on Zephyr native_sim).
769    let Ok(state) = nros_rmw::fallible::try_box(LivelinessClosureState { user_cb }) else {
770        return Err(NodeError::Transport(TransportError::BadAlloc));
771    };
772    let user_ctx = alloc::boxed::Box::into_raw(state) as *mut core::ffi::c_void;
773    let res = unsafe {
774        handle.register_event_callback(
775            nros_rmw::EventKind::LivelinessChanged,
776            0,
777            liveliness_trampoline::<F>,
778            user_ctx,
779        )
780    };
781    match res {
782        Ok(()) => {
783            let _ = regs.push(EventReg {
784                ctx: user_ctx,
785                drop_fn: drop_liveliness_state::<F>,
786            });
787            Ok(())
788        }
789        Err(e) => {
790            unsafe {
791                drop(alloc::boxed::Box::from_raw(
792                    user_ctx as *mut LivelinessClosureState<F>,
793                ));
794            }
795            Err(NodeError::Transport(e))
796        }
797    }
798}
799
800#[cfg(feature = "alloc")]
801unsafe fn drop_liveliness_state<F>(ctx: *mut core::ffi::c_void)
802where
803    F: FnMut(nros_rmw::LivelinessChangedStatus) + Send + 'static,
804{
805    unsafe {
806        drop(alloc::boxed::Box::from_raw(
807            ctx as *mut LivelinessClosureState<F>,
808        ));
809    }
810}
811
812#[cfg(feature = "alloc")]
813struct LivelinessClosureState<F> {
814    user_cb: F,
815}
816
817#[cfg(feature = "alloc")]
818unsafe extern "C" fn liveliness_trampoline<F>(
819    kind: nros_rmw::EventKind,
820    payload_ptr: *const core::ffi::c_void,
821    user_ctx: *mut core::ffi::c_void,
822) where
823    F: FnMut(nros_rmw::LivelinessChangedStatus) + Send + 'static,
824{
825    let state = unsafe { &mut *(user_ctx as *mut LivelinessClosureState<F>) };
826    let payload = unsafe { nros_rmw::payload_from_raw(kind, payload_ptr) };
827    if let nros_rmw::EventPayload::LivelinessChanged(s) = payload {
828        (state.user_cb)(*s);
829    }
830}
831
832// ============================================================================
833// EmbeddedRawPublisher — typeless publisher for non-ROS message wire formats
834// ============================================================================
835
836/// Default size of each per-publisher arena slot, in bytes.
837pub const DEFAULT_LOAN_BUF: usize = 1024;
838
839use core::cell::UnsafeCell;
840// portable-atomic AtomicBool — resolves to native on targets that support it,
841// software fallback on those that don't (e.g. some Xtensa ESP32 SoCs). Use
842// portable-atomic's Ordering too so the type sees the matching trait
843// implementation across all targets.
844use portable_atomic::{AtomicBool, Ordering};
845
846/// Typeless publisher handle. Use when the wire format is not ROS CDR
847/// (e.g. PX4 uORB raw POD bytes, custom binary protocols).
848///
849/// Two publish paths:
850///
851/// - [`publish_serialized`](Self::publish_serialized): user supplies a `&[u8]`, backend
852///   memcpys into its outbound buffer. One copy.
853/// - [`try_loan`](Self::try_loan): backend (or, without `rmw-lending`, a
854///   per-publisher arena) hands user a `&mut [u8]` slice. User writes in
855///   place. [`PublishLoan::commit`] triggers the wire write. With
856///   `rmw-lending` it is zero-copy where the backend lends — zenoh, the only
857///   one that fills the loan slots (no payload copy, measured)
858///   — and REFUSED where it does not (Cyclone, XRCE, uORB):
859///   `LoanError::Backend(Unsupported)`, permanent, the same in every build.
860///   The arena path is one copy, the same as `publish_serialized`.
861///
862/// The const-generic `TX_BUF` sizes the inline arena slot (default
863/// [`DEFAULT_LOAN_BUF`]). Loans larger than `TX_BUF` return
864/// `LoanError::TooLarge`.
865pub struct EmbeddedRawPublisher<const TX_BUF: usize = DEFAULT_LOAN_BUF> {
866    pub(crate) handle: session::RmwPublisher,
867    /// Whether the creating node's lifecycle state lets this publisher send.
868    pub(crate) gate: crate::lifecycle::PublisherGate,
869    /// Single-slot arena: writable buffer + busy flag. SLOTS=1 in v1
870    /// (concurrent loans on the same publisher return WouldBlock).
871    /// Unused when the `rmw-lending` feature is on — `try_loan`
872    /// dispatches to the backend's `SlotLending` instead.
873    #[allow(dead_code)]
874    pub(crate) arena: TxArena<TX_BUF>,
875    /// Phase 108 — registered event closures.
876    pub(crate) event_regs: EventRegs,
877    /// Issue 1676 — the contracted endpoint's publish counter, as
878    /// [`EmbeddedPublisher::monitor`] carries it. The Rust component road
879    /// (`nros::main!`, `create_publisher_for_topic`) publishes through THIS
880    /// type, so without it a contracted Rust publisher was measured at 0 Hz
881    /// while publishing at 1 Hz. `None` for an uncontracted publisher.
882    pub(crate) monitor: Option<&'static crate::executor::monitor::PubMonitorCell>,
883}
884
885impl<const TX_BUF: usize> Drop for EmbeddedRawPublisher<TX_BUF> {
886    fn drop(&mut self) {
887        drop_event_regs(&mut self.event_regs);
888    }
889}
890
891/// Single-slot per-publisher arena. Concurrent `try_loan` calls on the
892/// same publisher race on the busy flag; loser gets `WouldBlock`.
893#[allow(dead_code)]
894pub(crate) struct TxArena<const TX_BUF: usize> {
895    busy: AtomicBool,
896    buf: UnsafeCell<[u8; TX_BUF]>,
897}
898
899// SAFETY: Sync-ness of the arena is enforced by the `busy` flag — only
900// the thread that won the CAS may access `buf`, and only until commit/
901// discard releases the slot.
902unsafe impl<const TX_BUF: usize> Sync for TxArena<TX_BUF> {}
903
904#[allow(dead_code)] // unused when `rmw-lending` is on
905impl<const TX_BUF: usize> TxArena<TX_BUF> {
906    pub(crate) const fn new() -> Self {
907        Self {
908            busy: AtomicBool::new(false),
909            buf: UnsafeCell::new([0u8; TX_BUF]),
910        }
911    }
912
913    /// Try to claim the arena slot. Returns a raw pointer + len pair on
914    /// success; caller wraps it in a `PublishLoan`. Returns `false` if
915    /// the slot is already loaned.
916    ///
917    /// `&self` returning `&mut` is sound because the `busy` flag
918    /// gates exclusivity at runtime — the CAS in this function is
919    /// the only writer, and `release()` is only callable through the
920    /// loan's `Drop`.
921    #[allow(clippy::mut_from_ref)]
922    fn try_claim(&self, len: usize) -> Result<&mut [u8], LoanError> {
923        if len > TX_BUF {
924            return Err(LoanError::TooLarge);
925        }
926        if self
927            .busy
928            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
929            .is_err()
930        {
931            return Err(LoanError::WouldBlock);
932        }
933        // SAFETY: we just won the busy CAS; we hold exclusive access
934        // until release(). Lifetime is tied to `&self` for the loan.
935        let buf_ref: &mut [u8; TX_BUF] = unsafe { &mut *self.buf.get() };
936        Ok(&mut buf_ref[..len])
937    }
938
939    fn release(&self) {
940        self.busy.store(false, Ordering::Release);
941    }
942}
943
944impl<const TX_BUF: usize> EmbeddedRawPublisher<TX_BUF> {
945    /// The serialization format this publisher expects its raw
946    /// bytes to already be in. Counterpart to [`RawSubscription::format`].
947    pub const fn format(&self) -> nros_serdes::format::SerializationFormatId {
948        crate::session::IMAGE_SERIALIZATION_FORMAT_ID
949    }
950
951    /// Construct an [`EmbeddedRawPublisher`] from a backend-allocated
952    /// `RmwPublisher` handle. Public so external extension crates
953    /// (e.g. `nros-px4` for typed uORB wrappers) can wrap a handle
954    /// they obtained directly from the active session via
955    /// [`NodeHandle::session_mut`](crate::executor::NodeHandle::session_mut) + a backend-specific create method.
956    ///
957    /// Most users should not call this — use [`NodeHandle::create_publisher`](crate::executor::NodeHandle::create_publisher)
958    /// or [`NodeHandle::create_publisher_raw`](crate::executor::NodeHandle::create_publisher_raw) instead.
959    pub fn new(handle: session::RmwPublisher) -> Self {
960        Self {
961            handle,
962            // A handle obtained outside a node: nothing to follow.
963            gate: crate::lifecycle::PublisherGate::none(),
964            arena: TxArena::new(),
965            event_regs: empty_event_regs(),
966            monitor: None,
967        }
968    }
969
970    /// Issue 1676 — one relaxed bump per publish on a contracted endpoint;
971    /// a predictable no-op otherwise. Every publish route below calls it,
972    /// the loans' commits included.
973    #[inline]
974    fn bump_monitor(&self) {
975        if let Some(cell) = self.monitor {
976            cell.count
977                .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
978        }
979        // phase-463 W7 — every publish path passes here, so this is where the
980        // host profile learns which topics the dispatching callback published.
981        #[cfg(all(feature = "profile-mode", feature = "rmw-cffi"))]
982        crate::executor::profile::on_publish(self.handle.topic_name());
983    }
984
985    /// `true` if the active backend can fire the named
986    /// event for this raw publisher.
987    #[cfg(feature = "alloc")]
988    pub fn supports_event(&self, kind: nros_rmw::EventKind) -> bool {
989        use nros_rmw::Publisher as _;
990        self.handle.supports_event(kind)
991    }
992
993    /// Publish a pre-encoded byte slice. The byte format depends entirely
994    /// on the active RMW backend:
995    ///
996    /// - **zenoh / XRCE-DDS / DDS**: CDR-encoded payload including the
997    ///   4-byte CDR header.
998    /// - **uORB**: raw POD struct bytes (no header). Length must equal
999    ///   `size_of::<T::Msg>()` for the registered topic.
1000    pub fn publish_serialized(&self, data: &[u8]) -> Result<(), NodeError> {
1001        if self.gate.drops(self.handle.topic_name()) {
1002            return Ok(());
1003        }
1004        self.bump_monitor();
1005        self.handle
1006            .publish_raw(data)
1007            // Issue 2978 -- the backend's own refusal (MessageTooLarge, WouldBlock,
1008            // SessionLost ...), not a flattened PublishFailed.
1009            .map_err(NodeError::Transport)
1010    }
1011
1012    /// Renamed to [`publish_serialized`](Self::publish_serialized),
1013    /// the transmit word of the receive side's `take_serialized`.
1014    // phase-515 C8 renamed it.
1015    #[deprecated(
1016        since = "0.6.0",
1017        note = "renamed to `publish_serialized`; call it instead"
1018    )]
1019    pub fn publish_raw(&self, data: &[u8]) -> Result<(), NodeError> {
1020        self.publish_serialized(data)
1021    }
1022
1023    /// Raw publish with a wire-level attachment block.
1024    ///
1025    /// `attachment` rides alongside the payload on backends that
1026    /// natively support it (zenoh-pico, Cyclone DDS). Backends without
1027    /// native support silently discard `attachment` and fall back to
1028    /// the regular [`publish_serialized`](Self::publish_serialized) path — the
1029    /// default `Publisher::publish_raw_with_attachment` body in
1030    /// `nros-rmw` does this delegation.
1031    ///
1032    /// Primary use case: cross-RMW bridges stamp the source backend's
1033    /// RMW name as bridge_origin so a paired return bridge can drop
1034    /// echoed frames deterministically.
1035    pub fn publish_serialized_with_attachment(
1036        &self,
1037        data: &[u8],
1038        attachment: &[u8],
1039    ) -> Result<(), NodeError> {
1040        if self.gate.drops(self.handle.topic_name()) {
1041            return Ok(());
1042        }
1043        self.bump_monitor();
1044        self.handle
1045            .publish_raw_with_attachment(data, attachment)
1046            // Issue 2978 -- the backend's own refusal (MessageTooLarge, WouldBlock,
1047            // SessionLost ...), not a flattened PublishFailed.
1048            .map_err(NodeError::Transport)
1049    }
1050
1051    /// Renamed to
1052    /// [`publish_serialized_with_attachment`](Self::publish_serialized_with_attachment).
1053    // phase-515 C8 renamed it.
1054    #[deprecated(
1055        since = "0.6.0",
1056        note = "renamed to `publish_serialized_with_attachment`; call it instead"
1057    )]
1058    pub fn publish_raw_with_attachment(
1059        &self,
1060        data: &[u8],
1061        attachment: &[u8],
1062    ) -> Result<(), NodeError> {
1063        self.publish_serialized_with_attachment(data, attachment)
1064    }
1065
1066    /// Manually assert this publisher's liveliness.
1067    /// Required for `QoSLivelinessPolicy::ManualByTopic` /
1068    /// `ManualByNode`. No-op for AUTOMATIC / NONE. See
1069    /// [`EmbeddedPublisher::assert_liveliness`] for what `Err(Unsupported)`
1070    /// means per backend.
1071    pub fn assert_liveliness(&self) -> Result<(), NodeError> {
1072        use nros_rmw::Publisher as _;
1073        self.handle
1074            .assert_liveliness()
1075            .map_err(NodeError::Transport)
1076    }
1077
1078    /// This publisher's own global identifier — upstream
1079    /// `rmw_get_gid_for_publisher`. See [`EmbeddedPublisher::get_gid`] for
1080    /// the three bounds on what the bytes mean.
1081    pub fn get_gid(&self) -> Result<[u8; nros_rmw::PUBLISHER_GID_SIZE], NodeError> {
1082        use nros_rmw::Publisher as _;
1083        self.handle.get_gid().map_err(NodeError::Transport)
1084    }
1085
1086    /// Reserve a writable slot of `len` bytes. Caller writes into the
1087    /// returned [`PublishLoan`] and calls [`PublishLoan::commit`] to
1088    /// publish. Never blocks; returns [`LoanError::WouldBlock`] when the
1089    /// slot is already in use (arena fallback) or the backend's outbound
1090    /// stream is full (lending path), and [`LoanError::TooLarge`] when
1091    /// `len` exceeds the publisher's slot capacity.
1092    ///
1093    /// With the `rmw-lending` cargo feature on, this dispatches to the
1094    /// active backend's `SlotLending::try_lend_slot` — zero-copy on zenoh
1095    /// (`z_bytes_from_static_buf`), the only backend that lends; on
1096    /// Cyclone, XRCE and uORB it returns `LoanError::Backend(Unsupported)`,
1097    /// a permanent answer: use `publish_raw` there.
1098    /// Without `rmw-lending`, the arena fallback is used: caller fills a
1099    /// per-publisher inline slot, [`commit`](PublishLoan::commit) calls
1100    /// the backend's `publish_raw` (single memcpy into the backend's
1101    /// outbound buffer, same as `publish_raw` directly).
1102    #[cfg(not(feature = "rmw-lending"))]
1103    pub fn try_loan(&self, len: usize) -> Result<PublishLoan<'_, TX_BUF>, LoanError> {
1104        let slice = self.arena.try_claim(len)?;
1105        Ok(PublishLoan {
1106            publisher: self,
1107            slice,
1108            committed: false,
1109        })
1110    }
1111
1112    /// `rmw-lending` variant — see the no-lending [`try_loan`] for the docs.
1113    #[cfg(feature = "rmw-lending")]
1114    pub fn try_loan(&self, len: usize) -> Result<PublishLoan<'_, TX_BUF>, LoanError> {
1115        use nros_rmw::SlotLending;
1116        match self.handle.try_lend_slot(len) {
1117            Ok(Some(slot)) => Ok(PublishLoan {
1118                publisher: self,
1119                backend_slot: Some(slot),
1120                committed: false,
1121            }),
1122            Ok(None) => Err(LoanError::WouldBlock),
1123            Err(e) => Err(LoanError::Backend(e)),
1124        }
1125    }
1126
1127    /// Sync blocking loan with timeout. Spins the executor until the
1128    /// arena slot is free or `timeout` elapses.
1129    ///
1130    /// Useful when you publish from a sync context that owns the
1131    /// executor and want to block on a busy arena (rare — single-slot
1132    /// arena means contention only when concurrent task tries the same
1133    /// publisher, in which case the offending other task should have
1134    /// committed promptly).
1135    pub fn loan_with_timeout(
1136        &self,
1137        len: usize,
1138        executor: &mut super::Executor,
1139        timeout: core::time::Duration,
1140    ) -> Result<PublishLoan<'_, TX_BUF>, LoanError> {
1141        if len > TX_BUF {
1142            return Err(LoanError::TooLarge);
1143        }
1144        let spin_interval = core::time::Duration::from_millis(DEFAULT_SPIN_INTERVAL_MS);
1145        let timeout_ms = timeout.as_millis().min(u64::MAX as u128) as u64;
1146        let max_spins = (timeout_ms / DEFAULT_SPIN_INTERVAL_MS).max(1);
1147        let mut budget = WaitBudget::new(max_spins, timeout);
1148        loop {
1149            match self.try_loan(len) {
1150                Ok(loan) => return Ok(loan),
1151                Err(LoanError::WouldBlock) => {
1152                    executor.spin_once(budget.next_spin_interval(spin_interval));
1153                    if !budget.tick() {
1154                        return Err(LoanError::WouldBlock);
1155                    }
1156                }
1157                Err(other) => return Err(other),
1158            }
1159        }
1160    }
1161
1162    /// The topic this publisher was created on — see
1163    /// [`EmbeddedPublisher::topic_name`] for the contract and for why the
1164    /// accessor is here rather than on the RMW trait.
1165    pub fn topic_name(&self) -> &str {
1166        self.handle.topic_name()
1167    }
1168}
1169
1170/// Error type for [`EmbeddedRawPublisher::try_loan`].
1171#[derive(Debug, Clone, PartialEq, Eq)]
1172pub enum LoanError {
1173    /// Requested length exceeds the publisher's arena slot capacity.
1174    TooLarge,
1175    /// Arena slot already in use; another publish is in flight on this
1176    /// publisher. Retry after the other loan commits or discards.
1177    WouldBlock,
1178    /// Backend rejected the publish at commit time.
1179    Backend(TransportError),
1180}
1181
1182impl From<TransportError> for LoanError {
1183    fn from(e: TransportError) -> Self {
1184        LoanError::Backend(e)
1185    }
1186}
1187
1188/// Writable loan into a [`EmbeddedRawPublisher`]'s slot.
1189///
1190/// User fills `as_mut()` then calls [`commit`](Self::commit) to publish,
1191/// or [`discard`](Self::discard) to release the slot without publishing.
1192/// Dropping without either silently discards (slot freed); a
1193/// `#[must_use]` warning catches accidental drops at compile time.
1194///
1195/// Two backings, selected at compile time by the `rmw-lending` feature:
1196///
1197/// - **Arena (default)**: per-publisher inline `[u8; TX_BUF]` slot. On
1198///   commit, `publish_raw` memcpys into the backend's outbound buffer.
1199/// - **Backend lending (`rmw-lending`)**: slot owned by the backend —
1200///   zenoh-pico's static buffer aliased via `z_bytes_from_static_buf`, the
1201///   only backend that lends. True zero-copy publish there; the other
1202///   backends refuse the loan.
1203#[must_use = "PublishLoan must be committed or discarded; dropping silently rolls back"]
1204#[cfg(not(feature = "rmw-lending"))]
1205pub struct PublishLoan<'a, const TX_BUF: usize> {
1206    publisher: &'a EmbeddedRawPublisher<TX_BUF>,
1207    slice: &'a mut [u8],
1208    committed: bool,
1209}
1210
1211#[must_use = "PublishLoan must be committed or discarded; dropping silently rolls back"]
1212#[cfg(feature = "rmw-lending")]
1213pub struct PublishLoan<'a, const TX_BUF: usize> {
1214    publisher: &'a EmbeddedRawPublisher<TX_BUF>,
1215    /// `Option` so `commit` can move the slot out via `take()` without
1216    /// triggering Drop's release path. Always `Some(_)` until `commit`
1217    /// or `discard` runs.
1218    backend_slot: Option<<session::RmwPublisher as nros_rmw::SlotLending>::Slot<'a>>,
1219    committed: bool,
1220}
1221
1222#[cfg(not(feature = "rmw-lending"))]
1223impl<'a, const TX_BUF: usize> PublishLoan<'a, TX_BUF> {
1224    /// Mutable view into the loaned bytes. Caller writes message data here.
1225    #[allow(clippy::should_implement_trait)]
1226    pub fn as_mut(&mut self) -> &mut [u8] {
1227        self.slice
1228    }
1229
1230    /// Commit the loan: hand the bytes to the backend's `publish_raw`,
1231    /// then release the arena slot. Returns the backend's publish error
1232    /// if any (slot is released regardless).
1233    pub fn commit(mut self) -> Result<(), LoanError> {
1234        if self
1235            .publisher
1236            .gate
1237            .drops(self.publisher.handle.topic_name())
1238        {
1239            self.committed = true;
1240            return Ok(());
1241        }
1242        self.publisher.bump_monitor();
1243        let res = self
1244            .publisher
1245            .handle
1246            .publish_raw(self.slice)
1247            .map_err(LoanError::Backend); // issue 2978
1248        self.committed = true;
1249        // Drop runs and releases the slot.
1250        res
1251    }
1252
1253    /// Discard the loan without publishing. Equivalent to dropping, but
1254    /// explicit (no `#[must_use]` warning).
1255    pub fn discard(mut self) {
1256        self.committed = true; // Suppress Drop's "discard" log if any.
1257        drop(self);
1258    }
1259}
1260
1261#[cfg(feature = "rmw-lending")]
1262impl<'a, const TX_BUF: usize> PublishLoan<'a, TX_BUF> {
1263    /// Mutable view into the backend-lent bytes.
1264    #[allow(clippy::should_implement_trait)]
1265    pub fn as_mut(&mut self) -> &mut [u8] {
1266        // SAFETY-invariant: `backend_slot` is `Some` for the whole life of
1267        // a `PublishLoan` — only `commit`/`discard` take it, and both
1268        // consume `self` by value, so no `&mut self` method can observe
1269        // `None`.
1270        self.backend_slot
1271            .as_mut()
1272            .expect("PublishLoan slot already consumed")
1273            .as_mut()
1274    }
1275
1276    /// Commit the loan: hand the slot to the backend's `commit_slot` for
1277    /// flushing. The slot's bytes are written to the wire without an
1278    /// extra user-side memcpy.
1279    pub fn commit(mut self) -> Result<(), LoanError> {
1280        use nros_rmw::SlotLending;
1281        // SAFETY-invariant: first and only `take` — `commit` consumes
1282        // `self`, so the slot is still `Some` here.
1283        let slot = self
1284            .backend_slot
1285            .take()
1286            .expect("PublishLoan slot already consumed");
1287        self.committed = true;
1288        if self
1289            .publisher
1290            .gate
1291            .drops(self.publisher.handle.topic_name())
1292        {
1293            // Dropping the slot releases it unsent. A backend's slot releases
1294            // in its Drop; the test mock's slot has none, which is what the
1295            // lint sees in that build.
1296            #[allow(clippy::drop_non_drop)]
1297            drop(slot);
1298            return Ok(());
1299        }
1300        self.publisher.bump_monitor();
1301        self.publisher
1302            .handle
1303            .commit_slot(slot)
1304            .map_err(LoanError::Backend)
1305    }
1306
1307    /// Discard the loan without publishing. The backend-owned slot is
1308    /// released by its own Drop when this `PublishLoan` is dropped.
1309    pub fn discard(mut self) {
1310        self.committed = true;
1311        // Overwriting drops the backend's slot here, which releases it.
1312        self.backend_slot = None;
1313    }
1314}
1315
1316#[cfg(not(feature = "rmw-lending"))]
1317impl<'a, const TX_BUF: usize> Drop for PublishLoan<'a, TX_BUF> {
1318    fn drop(&mut self) {
1319        // Slot always returned to the free pool; whether the bytes were
1320        // actually published is encoded in `committed`. Future telemetry
1321        // hook could log uncommitted drops in debug builds.
1322        self.publisher.arena.release();
1323    }
1324}
1325
1326// rmw-lending variant relies on the backend's `Slot` Drop impl to release
1327// the underlying buffer/stream slot. No explicit nros-side Drop needed.
1328
1329// ============================================================================
1330// Subscription
1331// ============================================================================
1332
1333/// Typed subscription handle with internal receive buffer.
1334///
1335/// ADOPT-BOUNDED against rclrs's `Subscription`, whose callback is set on it
1336/// AFTER construction (`set_callback`, `set_async_callback`, ...). This handle is
1337/// POLL-style and has no callback; a callback subscription takes its closure at
1338/// DECLARATION (`create_subscription(topic, callback)`), because with no allocator
1339/// the entity set is fixed when `register` runs. There is no setter to call later.
1340///
1341/// Two methods, both byte-oriented at the wire:
1342///
1343/// - [`take`](Self::take) / [`wait_next`](Self::wait_next) — pull bytes
1344///   from the backend, CDR-decode into `M: RosMessage`, hand back
1345///   ownership of the typed message.
1346/// - [`take_serialized`](Self::take_serialized) — copy bytes into the
1347///   subscription's internal buffer and return the length, leaving CDR
1348///   decoding to the caller.
1349///
1350/// **No typed `borrow()` exists.** Borrow lives exclusively on
1351/// [`RawSubscription`]. `RecvView` is `&[u8]` semantics; CDR decoding
1352/// into a typed `M` requires owning the bytes (or running the decoder
1353/// in place), which the borrow contract doesn't fit. See
1354/// `docs/design/0010-zero-copy-raw-api.md` decision D7.
1355pub struct Subscription<M, const RX_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE }> {
1356    pub(crate) handle: session::RmwSubscriber,
1357    pub(crate) buffer: [u8; RX_BUF],
1358    /// Phase 108 — registered event closures.
1359    pub(crate) event_regs: EventRegs,
1360    /// W3b.5 — contracted-endpoint age hook (cell + epoch clock);
1361    /// `None` = uncontracted.
1362    pub(crate) age_mon: Option<crate::executor::arena::AgeMon>,
1363    pub(crate) _phantom: PhantomData<M>,
1364}
1365
1366impl<M, const RX_BUF: usize> Drop for Subscription<M, RX_BUF> {
1367    fn drop(&mut self) {
1368        drop_event_regs(&mut self.event_regs);
1369    }
1370}
1371
1372impl<M: RosMessage, const RX_BUF: usize> Subscription<M, RX_BUF> {
1373    /// Try to receive a typed message (non-blocking).
1374    /// Take one message if the middleware has one.
1375    ///
1376    /// Named `take` after rcl (`rcl_take`) and rclcpp (`Subscription::take`),
1377    /// which spell the non-blocking receive that way — as does our own C
1378    /// surface. NOT after rclrs: its subscription API is callback/worker-driven
1379    /// and has no public polling counterpart at all (its `take_*` methods are
1380    /// private), which is why the ledger records this as an `extension` against
1381    /// the Rust reference rather than a match. `take` was Rust
1382    /// channel vocabulary that reads as a different contract to a ROS 2 user:
1383    /// both are non-blocking and both report emptiness without failing, so
1384    /// nothing asked for the other word. Renamed as a clean break, no shim.
1385    pub fn take(&mut self) -> Result<Option<M>, NodeError> {
1386        match self
1387            .handle
1388            .take_serialized(&mut self.buffer)
1389            .map_err(NodeError::Transport)?
1390        {
1391            Some(len) => {
1392                // W3b.5 — record take-age for contracted endpoints.
1393                crate::executor::arena::observe_age::<M>(&self.buffer[..len], &self.age_mon);
1394                let mut reader = CdrReader::new_with_header(&self.buffer[..len])
1395                    .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
1396                let msg = M::deserialize(&mut reader)
1397                    .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
1398                Ok(Some(msg))
1399            }
1400            None => Ok(None),
1401        }
1402    }
1403
1404    /// Try to receive raw CDR-encoded data (non-blocking).
1405    pub fn take_serialized(&mut self) -> Result<Option<usize>, NodeError> {
1406        self.handle
1407            .take_serialized(&mut self.buffer)
1408            .map_err(NodeError::Transport)
1409    }
1410
1411    /// Get the receive buffer (valid after `take_serialized`).
1412    pub fn buffer(&self) -> &[u8] {
1413        &self.buffer
1414    }
1415
1416    // ====================================================================
1417    // Phase 108 — status events
1418    // ====================================================================
1419    //
1420    // Subscriber-side: `LivelinessChanged`, `RequestedDeadlineMissed`,
1421    // `MessageLost`. Returns
1422    // `NodeError::Transport(TransportError::Unsupported)` if the
1423    // active backend doesn't generate the event for this entity.
1424
1425    /// `true` if the active backend can fire the named event for this
1426    /// subscriber.
1427    #[cfg(feature = "alloc")]
1428    pub fn supports_event(&self, kind: nros_rmw::EventKind) -> bool {
1429        use nros_rmw::Subscription as _;
1430        self.handle.supports_event(kind)
1431    }
1432
1433    /// Register a callback for `LivelinessChanged`. Fires when a
1434    /// tracked publisher's liveliness state changes.
1435    #[cfg(feature = "alloc")]
1436    pub fn on_liveliness_changed<F>(&mut self, cb: F) -> Result<(), NodeError>
1437    where
1438        F: FnMut(nros_rmw::LivelinessChangedStatus) + Send + 'static,
1439    {
1440        register_sub_event_liveliness::<F>(&mut self.handle, &mut self.event_regs, cb)
1441    }
1442
1443    /// Register a callback for `RequestedDeadlineMissed`. Fires when
1444    /// an expected sample doesn't arrive within `deadline`.
1445    #[cfg(feature = "alloc")]
1446    pub fn on_requested_deadline_missed<F>(
1447        &mut self,
1448        deadline: core::time::Duration,
1449        cb: F,
1450    ) -> Result<(), NodeError>
1451    where
1452        F: FnMut(nros_rmw::CountStatus) + Send + 'static,
1453    {
1454        register_sub_event_count::<F, _>(
1455            &mut self.handle,
1456            &mut self.event_regs,
1457            nros_rmw::EventKind::RequestedDeadlineMissed,
1458            deadline.as_millis().min(u32::MAX as u128) as u32,
1459            cb,
1460            |payload, f| {
1461                if let nros_rmw::EventPayload::RequestedDeadlineMissed(s) = payload {
1462                    f(*s);
1463                }
1464            },
1465        )
1466    }
1467
1468    /// Register a callback for `MessageLost`. Fires when the backend
1469    /// drops a sample (overflow, etc.).
1470    #[cfg(feature = "alloc")]
1471    pub fn on_message_lost<F>(&mut self, cb: F) -> Result<(), NodeError>
1472    where
1473        F: FnMut(nros_rmw::CountStatus) + Send + 'static,
1474    {
1475        register_sub_event_count::<F, _>(
1476            &mut self.handle,
1477            &mut self.event_regs,
1478            nros_rmw::EventKind::MessageLost,
1479            0,
1480            cb,
1481            |payload, f| {
1482                if let nros_rmw::EventPayload::MessageLost(s) = payload {
1483                    f(*s);
1484                }
1485            },
1486        )
1487    }
1488
1489    /// Register a callback for `SubscriptionMatched` — upstream
1490    /// `RMW_EVENT_SUBSCRIPTION_MATCHED` / rclcpp's
1491    /// `SubscriptionEventCallbacks::matched_callback`. Fires when a publisher
1492    /// starts or stops matching this subscription; `current_count` is how
1493    /// many match now. Polled from the subscription's data path, like the
1494    /// other status events.
1495    #[cfg(feature = "alloc")]
1496    pub fn on_matched<F>(&mut self, cb: F) -> Result<(), NodeError>
1497    where
1498        F: FnMut(nros_rmw::MatchedStatus) + Send + 'static,
1499    {
1500        register_sub_event_count::<F, _>(
1501            &mut self.handle,
1502            &mut self.event_regs,
1503            nros_rmw::EventKind::SubscriptionMatched,
1504            0,
1505            cb,
1506            |payload, f| {
1507                if let nros_rmw::EventPayload::SubscriptionMatched(s) = payload {
1508                    f(*s);
1509                }
1510            },
1511        )
1512    }
1513
1514    /// Register a callback for `SubscriptionIncompatibleType` —
1515    /// upstream `RMW_EVENT_SUBSCRIPTION_INCOMPATIBLE_TYPE` / rclcpp's
1516    /// `SubscriptionEventCallbacks::incompatible_type_callback`. Fires when a
1517    /// publisher on this topic NAME with a different type is seen.
1518    #[cfg(feature = "alloc")]
1519    pub fn on_incompatible_type<F>(&mut self, cb: F) -> Result<(), NodeError>
1520    where
1521        F: FnMut(nros_rmw::IncompatibleTypeStatus) + Send + 'static,
1522    {
1523        register_sub_event_count::<F, _>(
1524            &mut self.handle,
1525            &mut self.event_regs,
1526            nros_rmw::EventKind::SubscriptionIncompatibleType,
1527            0,
1528            cb,
1529            |payload, f| {
1530                if let nros_rmw::EventPayload::SubscriptionIncompatibleType(s) = payload {
1531                    f(*s);
1532                }
1533            },
1534        )
1535    }
1536
1537    /// Check if data is available without consuming it.
1538    pub fn has_data(&self) -> bool {
1539        self.handle.has_data()
1540    }
1541
1542    /// Process the received message in-place without copying.
1543    pub fn process_in_place(&mut self, f: impl FnOnce(&M)) -> Result<bool, NodeError> {
1544        let mut deser_err = false;
1545        let processed = self
1546            .handle
1547            .process_raw_in_place(|raw| {
1548                match CdrReader::new_with_header(raw).and_then(|mut r| M::deserialize(&mut r)) {
1549                    Ok(msg) => f(&msg),
1550                    Err(_) => deser_err = true,
1551                }
1552            })
1553            .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
1554
1555        if deser_err {
1556            return Err(NodeError::Transport(TransportError::DeserializationError));
1557        }
1558        Ok(processed)
1559    }
1560
1561    /// Sync: wait for the next message, spinning the executor.
1562    ///
1563    /// Returns `Ok(Some(msg))` if a message arrives within `timeout_ms`,
1564    /// or `Ok(None)` on timeout. Unlike [`Promise::wait()`], timeout is
1565    /// not an error — the caller typically retries in a loop.
1566    ///
1567    /// # Example
1568    ///
1569    /// ```ignore
1570    /// while let Some(msg) = sub.wait_next(&mut executor, core::time::Duration::from_millis(1000))? {
1571    ///     /* handle msg */
1572    /// }
1573    /// ```
1574    pub fn wait_next(
1575        &mut self,
1576        executor: &mut super::Executor,
1577        timeout: core::time::Duration,
1578    ) -> Result<Option<M>, NodeError> {
1579        let spin_interval = core::time::Duration::from_millis(DEFAULT_SPIN_INTERVAL_MS);
1580        let timeout_ms = timeout.as_millis().min(u64::MAX as u128) as u64;
1581        let max_spins = (timeout_ms / DEFAULT_SPIN_INTERVAL_MS).max(1);
1582        let mut budget = WaitBudget::new(max_spins, timeout);
1583        loop {
1584            executor.spin_once(budget.next_spin_interval(spin_interval));
1585            if let Some(msg) = self.take()? {
1586                return Ok(Some(msg));
1587            }
1588            if !budget.tick() {
1589                return Ok(None);
1590            }
1591        }
1592    }
1593    /// The QoS profile this subscription is ACTUALLY running.
1594    ///
1595    /// rclrs's `SubscriptionState::qos`, and the answer is a step better than
1596    /// its own: rclrs returns the profile the subscription was CREATED with,
1597    /// because it never reads one back. This returns what the backend
1598    /// GRANTED — `rmw_subscription_get_actual_qos`, in other words, which is
1599    /// the same question with the answer measured instead of assumed. The two
1600    /// differ whenever a backend serves something other than it was asked
1601    /// (zenoh clamps depth to its receive ring; DDS negotiates), and that
1602    /// difference is what answers "why is nothing arriving".
1603    ///
1604    /// **A policy the backend could not report reads back as its `Unknown`
1605    /// variant**, never as the request — upstream's contract for this call.
1606    /// A backend with no read-back at all (XRCE) answers
1607    /// [`QoSProfile::QOS_PROFILE_UNKNOWN`](nros_rmw::QoSProfile::QOS_PROFILE_UNKNOWN), every field an absence.
1608    ///
1609    /// Free: read once at create and retained on the handle, so this never
1610    /// re-enters the transport.
1611    pub fn qos(&self) -> nros_rmw::QoSProfile {
1612        nros_rmw::Subscription::actual_qos(&self.handle)
1613    }
1614
1615    /// The topic this subscription was created on — rclrs's
1616    /// `SubscriptionState::topic_name`. See
1617    /// [`EmbeddedPublisher::topic_name`] for the contract and for why the
1618    /// accessor is here rather than on the RMW trait.
1619    pub fn topic_name(&self) -> &str {
1620        self.handle.topic_name()
1621    }
1622
1623    /// How many publishers are on this subscription's topic, RIGHT NOW —
1624    /// rclcpp's `Subscription::get_publisher_count`, rcl's
1625    /// `rclc_subscription_get_publisher_count`.
1626    ///
1627    /// The subscription half of
1628    /// [`EmbeddedPublisher::get_subscription_count`], which states the
1629    /// order (the matched count — upstream's
1630    /// `rmw_subscription_count_matched_publishers` — where the backend fills
1631    /// it, else the topic-wide graph count), why the executor is an argument,
1632    /// and why `Unsupported` is not `0`.
1633    pub fn get_publisher_count(
1634        &self,
1635        executor: &mut super::spin::Executor<'_>,
1636    ) -> Result<usize, NodeError> {
1637        match nros_rmw::Subscription::count_matched_publishers(&self.handle) {
1638            Err(nros_rmw::TransportError::Unsupported) => {
1639                executor.count_publishers(self.handle.topic_name())
1640            }
1641            other => other.map_err(NodeError::Transport),
1642        }
1643    }
1644}
1645
1646// ============================================================================
1647// RawSubscription — typeless subscription for non-ROS message wire formats
1648// ============================================================================
1649
1650/// Typeless subscription handle. Counterpart of [`EmbeddedRawPublisher`].
1651///
1652/// The user owns the decoding step: call [`take_serialized`](Self::take_serialized)
1653/// to fill an internal buffer with bytes whose format depends on the active
1654/// RMW backend, then interpret them however is appropriate (memcpy, custom
1655/// parser, …).
1656pub struct RawSubscription<const RX_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE }> {
1657    pub(crate) handle: session::RmwSubscriber,
1658    pub(crate) buffer: [u8; RX_BUF],
1659    /// Phase 108 — registered event closures.
1660    pub(crate) event_regs: EventRegs,
1661}
1662
1663impl<const RX_BUF: usize> Drop for RawSubscription<RX_BUF> {
1664    fn drop(&mut self) {
1665        drop_event_regs(&mut self.event_regs);
1666    }
1667}
1668
1669impl<const RX_BUF: usize> RawSubscription<RX_BUF> {
1670    /// The serialization format of the bytes this subscription
1671    /// yields, as an image-local discriminant.
1672    ///
1673    /// A single-backend image knows this at compile time; the accessor exists
1674    /// for the case that does not, a bridge image built with
1675    /// `Executor::open_multi`, where two sessions speak two formats and the
1676    /// answer is per session rather than per image.
1677    pub const fn format(&self) -> nros_serdes::format::SerializationFormatId {
1678        crate::session::IMAGE_SERIALIZATION_FORMAT_ID
1679    }
1680
1681    /// Construct a [`RawSubscription`] from a backend-allocated
1682    /// `RmwSubscriber` handle. Public so external extension crates
1683    /// (e.g. `nros-px4` for typed uORB wrappers) can wrap a handle
1684    /// they obtained directly from the active session via
1685    /// [`NodeHandle::session_mut`](crate::executor::NodeHandle::session_mut) + a backend-specific create method.
1686    ///
1687    /// Most users should not call this — use
1688    /// [`NodeHandle::create_subscription`](crate::executor::NodeHandle::create_subscription) or
1689    /// [`NodeHandle::create_subscription_raw`](crate::executor::NodeHandle::create_subscription_raw) instead.
1690    pub fn new(handle: session::RmwSubscriber) -> Self {
1691        Self {
1692            handle,
1693            buffer: [0u8; RX_BUF],
1694            event_regs: empty_event_regs(),
1695        }
1696    }
1697
1698    /// Try to receive raw bytes (non-blocking). Returns `Ok(Some(len))`
1699    /// with the message length on success; the bytes live in
1700    /// [`buffer`](Self::buffer) until the next call.
1701    pub fn take_serialized(&mut self) -> Result<Option<usize>, NodeError> {
1702        self.handle
1703            .take_serialized(&mut self.buffer)
1704            .map_err(NodeError::Transport)
1705    }
1706
1707    /// Raw receive that also surfaces the incoming
1708    /// sample's wire-level attachment block.
1709    ///
1710    /// Returns `Ok(Some((payload_len, attachment_len)))`. The payload
1711    /// lives in [`buffer`](Self::buffer); the attachment is written
1712    /// into caller-supplied `att_buf`. `attachment_len == 0` means
1713    /// the incoming sample carried no attachment.
1714    ///
1715    /// Backends without native attachment support delegate to
1716    /// [`take_serialized`](Self::take_serialized) and always report
1717    /// `attachment_len == 0` (default `Subscriber` trait body in
1718    /// `nros-rmw`).
1719    pub fn take_serialized_with_attachment(
1720        &mut self,
1721        att_buf: &mut [u8],
1722    ) -> Result<Option<(usize, usize)>, NodeError> {
1723        self.handle
1724            .take_serialized_with_attachment(&mut self.buffer, att_buf)
1725            .map_err(NodeError::Transport)
1726    }
1727
1728    /// Raw receive that also returns the E2E
1729    /// [`IntegrityStatus`](nros_rmw::IntegrityStatus) (CRC + sequence gap/dup) for
1730    /// the C/C++ `rclc_polling_subscription_take_validated` path. The validator lives
1731    /// in the backend handle (`take_validated`), so no typed message is needed;
1732    /// the payload lives in [`buffer`](Self::buffer). `crc_valid == None` when the
1733    /// wire sample carried no CRC (e.g. a publisher built without `safety-e2e`).
1734    #[cfg(feature = "safety-e2e")]
1735    pub fn take_validated(
1736        &mut self,
1737    ) -> Result<Option<(usize, nros_rmw::IntegrityStatus)>, NodeError> {
1738        use nros_rmw::Subscription as _;
1739        self.handle
1740            .take_validated(&mut self.buffer)
1741            .map_err(NodeError::Transport)
1742    }
1743
1744    /// Burst-take. Drain up to `max_msgs` queued
1745    /// samples into the caller-supplied contiguous block in one
1746    /// call, with the i-th sample at
1747    /// `buf[i * per_msg_cap .. i * per_msg_cap + out_lens[i]]`.
1748    /// Returns the number of messages delivered.
1749    ///
1750    /// Backends without a native batch take inherit the
1751    /// `Subscriber::take_sequence` default body which loop-drives
1752    /// `take_serialized` — same shape, same observable result; the
1753    /// batched API just lets sensor loops commit to the call shape
1754    /// regardless of backend support.
1755    pub fn take_sequence(
1756        &mut self,
1757        buf: &mut [u8],
1758        per_msg_cap: usize,
1759        max_msgs: usize,
1760        out_lens: &mut [usize],
1761    ) -> Result<usize, NodeError> {
1762        use nros_rmw::Subscription as _;
1763        self.handle
1764            .take_sequence(buf, per_msg_cap, max_msgs, out_lens)
1765            .map_err(NodeError::Transport)
1766    }
1767
1768    /// Register a `Waker` that fires when a new
1769    /// message arrives. Mirror of the existing service-server /
1770    /// service-client wake plumbing. Returns `false` on a backend that
1771    /// cannot wake — the caller falls back to polling.
1772    pub fn register_waker(&self, waker: &core::task::Waker) -> bool {
1773        use nros_rmw::Subscription as _;
1774        self.handle.register_waker(waker)
1775    }
1776
1777    /// `true` if the active backend can fire the named
1778    /// event for this raw subscription.
1779    #[cfg(feature = "alloc")]
1780    pub fn supports_event(&self, kind: nros_rmw::EventKind) -> bool {
1781        use nros_rmw::Subscription as _;
1782        self.handle.supports_event(kind)
1783    }
1784
1785    /// Register a callback for `LivelinessChanged`.
1786    #[cfg(feature = "alloc")]
1787    pub fn on_liveliness_changed<F>(&mut self, cb: F) -> Result<(), NodeError>
1788    where
1789        F: FnMut(nros_rmw::LivelinessChangedStatus) + Send + 'static,
1790    {
1791        register_sub_event_liveliness::<F>(&mut self.handle, &mut self.event_regs, cb)
1792    }
1793
1794    /// Register a callback for `RequestedDeadlineMissed`.
1795    #[cfg(feature = "alloc")]
1796    pub fn on_requested_deadline_missed<F>(
1797        &mut self,
1798        deadline: core::time::Duration,
1799        cb: F,
1800    ) -> Result<(), NodeError>
1801    where
1802        F: FnMut(nros_rmw::CountStatus) + Send + 'static,
1803    {
1804        register_sub_event_count::<F, _>(
1805            &mut self.handle,
1806            &mut self.event_regs,
1807            nros_rmw::EventKind::RequestedDeadlineMissed,
1808            deadline.as_millis().min(u32::MAX as u128) as u32,
1809            cb,
1810            |payload, f| {
1811                if let nros_rmw::EventPayload::RequestedDeadlineMissed(s) = payload {
1812                    f(*s);
1813                }
1814            },
1815        )
1816    }
1817
1818    /// Register a callback for `MessageLost`.
1819    #[cfg(feature = "alloc")]
1820    pub fn on_message_lost<F>(&mut self, cb: F) -> Result<(), NodeError>
1821    where
1822        F: FnMut(nros_rmw::CountStatus) + Send + 'static,
1823    {
1824        register_sub_event_count::<F, _>(
1825            &mut self.handle,
1826            &mut self.event_regs,
1827            nros_rmw::EventKind::MessageLost,
1828            0,
1829            cb,
1830            |payload, f| {
1831                if let nros_rmw::EventPayload::MessageLost(s) = payload {
1832                    f(*s);
1833                }
1834            },
1835        )
1836    }
1837
1838    /// Register a callback for `SubscriptionMatched` — upstream
1839    /// `RMW_EVENT_SUBSCRIPTION_MATCHED` / rclcpp's
1840    /// `SubscriptionEventCallbacks::matched_callback`. Fires when a publisher
1841    /// starts or stops matching this subscription; `current_count` is how
1842    /// many match now. Polled from the subscription's data path, like the
1843    /// other status events.
1844    #[cfg(feature = "alloc")]
1845    pub fn on_matched<F>(&mut self, cb: F) -> Result<(), NodeError>
1846    where
1847        F: FnMut(nros_rmw::MatchedStatus) + Send + 'static,
1848    {
1849        register_sub_event_count::<F, _>(
1850            &mut self.handle,
1851            &mut self.event_regs,
1852            nros_rmw::EventKind::SubscriptionMatched,
1853            0,
1854            cb,
1855            |payload, f| {
1856                if let nros_rmw::EventPayload::SubscriptionMatched(s) = payload {
1857                    f(*s);
1858                }
1859            },
1860        )
1861    }
1862
1863    /// Register a callback for `SubscriptionIncompatibleType` —
1864    /// upstream `RMW_EVENT_SUBSCRIPTION_INCOMPATIBLE_TYPE` / rclcpp's
1865    /// `SubscriptionEventCallbacks::incompatible_type_callback`. Fires when a
1866    /// publisher on this topic NAME with a different type is seen.
1867    #[cfg(feature = "alloc")]
1868    pub fn on_incompatible_type<F>(&mut self, cb: F) -> Result<(), NodeError>
1869    where
1870        F: FnMut(nros_rmw::IncompatibleTypeStatus) + Send + 'static,
1871    {
1872        register_sub_event_count::<F, _>(
1873            &mut self.handle,
1874            &mut self.event_regs,
1875            nros_rmw::EventKind::SubscriptionIncompatibleType,
1876            0,
1877            cb,
1878            |payload, f| {
1879                if let nros_rmw::EventPayload::SubscriptionIncompatibleType(s) = payload {
1880                    f(*s);
1881                }
1882            },
1883        )
1884    }
1885
1886    /// Get the receive buffer (valid after [`take_serialized`](Self::take_serialized)).
1887    pub fn buffer(&self) -> &[u8] {
1888        &self.buffer
1889    }
1890
1891    /// Check if data is available without consuming it.
1892    pub fn has_data(&self) -> bool {
1893        self.handle.has_data()
1894    }
1895
1896    /// Try to borrow the next available message in place. Returns
1897    /// `Ok(None)` if no message is ready; never blocks.
1898    ///
1899    /// The returned [`RecvView`] borrows the subscriber's internal
1900    /// receive buffer. Lifetime is tied to `&mut self` — only one view
1901    /// can be live at a time, and the next `try_borrow` / `take_serialized`
1902    /// call invalidates the previous view's bytes.
1903    ///
1904    /// View is `!Send + !Sync` to discourage holding it across `.await`
1905    /// or thread boundaries (would block subsequent receives on the
1906    /// same subscriber).
1907    #[cfg(not(feature = "rmw-lending"))]
1908    pub fn try_borrow(&mut self) -> Result<Option<RecvView<'_>>, NodeError> {
1909        match self.take_serialized()? {
1910            Some(len) => Ok(Some(RecvView {
1911                bytes: &self.buffer[..len],
1912                _marker: core::marker::PhantomData,
1913            })),
1914            None => Ok(None),
1915        }
1916    }
1917
1918    /// `rmw-lending` variant — dispatches to the backend's
1919    /// [`SlotBorrowing::try_borrow`](nros_rmw::SlotBorrowing::try_borrow)
1920    /// for true zero-copy receive (zenoh-pico's static buffer borrowed
1921    /// directly via `z_bytes_get_contiguous_view`, XRCE's slot borrowed
1922    /// in place). The bytes never touch `self.buffer`.
1923    #[cfg(feature = "rmw-lending")]
1924    pub fn try_borrow(&mut self) -> Result<Option<RecvView<'_>>, NodeError> {
1925        use nros_rmw::SlotBorrowing;
1926        match self.handle.try_borrow() {
1927            Ok(Some(view)) => Ok(Some(RecvView {
1928                view: Some(view),
1929                _marker: core::marker::PhantomData,
1930            })),
1931            Ok(None) => Ok(None),
1932            Err(e) => Err(NodeError::Transport(e)),
1933        }
1934    }
1935
1936    /// Sync blocking borrow with timeout. Spins the executor until a
1937    /// message is available or `timeout` elapses.
1938    ///
1939    /// Returns `Ok(Some(view))` on success, `Ok(None)` on timeout.
1940    /// The view's lifetime is tied to `&mut self`.
1941    pub fn borrow_with_timeout(
1942        &mut self,
1943        executor: &mut super::Executor,
1944        timeout: core::time::Duration,
1945    ) -> Result<Option<RecvView<'_>>, NodeError> {
1946        let spin_interval = core::time::Duration::from_millis(DEFAULT_SPIN_INTERVAL_MS);
1947        let timeout_ms = timeout.as_millis().min(u64::MAX as u128) as u64;
1948        let max_spins = (timeout_ms / DEFAULT_SPIN_INTERVAL_MS).max(1);
1949        let mut budget = WaitBudget::new(max_spins, timeout);
1950        loop {
1951            executor.spin_once(budget.next_spin_interval(spin_interval));
1952            if self.has_data() {
1953                return self.try_borrow();
1954            }
1955            if !budget.tick() {
1956                return Ok(None);
1957            }
1958        }
1959    }
1960    /// The QoS profile this subscription is ACTUALLY running.
1961    ///
1962    /// rclrs's `SubscriptionState::qos`, and the answer is a step better than
1963    /// its own: rclrs returns the profile the subscription was CREATED with,
1964    /// because it never reads one back. This returns what the backend
1965    /// GRANTED — `rmw_subscription_get_actual_qos`, in other words, which is
1966    /// the same question with the answer measured instead of assumed. The two
1967    /// differ whenever a backend serves something other than it was asked
1968    /// (zenoh clamps depth to its receive ring; DDS negotiates), and that
1969    /// difference is what answers "why is nothing arriving".
1970    ///
1971    /// **A policy the backend could not report reads back as its `Unknown`
1972    /// variant**, never as the request — upstream's contract for this call.
1973    /// A backend with no read-back at all (XRCE) answers
1974    /// [`QoSProfile::QOS_PROFILE_UNKNOWN`](nros_rmw::QoSProfile::QOS_PROFILE_UNKNOWN), every field an absence.
1975    ///
1976    /// Free: read once at create and retained on the handle, so this never
1977    /// re-enters the transport.
1978    pub fn qos(&self) -> nros_rmw::QoSProfile {
1979        nros_rmw::Subscription::actual_qos(&self.handle)
1980    }
1981
1982    /// The topic this subscription was created on — see
1983    /// [`EmbeddedPublisher::topic_name`].
1984    pub fn topic_name(&self) -> &str {
1985        self.handle.topic_name()
1986    }
1987}
1988
1989// ============================================================================
1990// RawServiceServer / RawServiceClient (Phase 122.3.c — L1 polling, typeless)
1991// ============================================================================
1992
1993/// Typeless service-server handle. L1 counterpart of
1994/// [`EmbeddedServiceServer`] for callers that own their own scheduler
1995/// (RTIC, embassy, FreeRTOS-task-per-entity) and the C / C++ FFI
1996/// shims.
1997///
1998/// Holds the transport handle plus an inline request buffer. The
1999/// caller polls [`take_request_raw`](Self::take_request_raw)
2000/// and sends replies via [`send_response_raw`](Self::send_response_raw)
2001/// with raw CDR bytes.
2002pub struct RawServiceServer<
2003    const REQ_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2004    const RESP_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2005> {
2006    pub(crate) handle: session::RmwServiceServer,
2007    pub(crate) req_buffer: [u8; REQ_BUF],
2008    pub(crate) _phantom_resp: PhantomData<[u8; RESP_BUF]>,
2009}
2010
2011impl<const REQ_BUF: usize, const RESP_BUF: usize> RawServiceServer<REQ_BUF, RESP_BUF> {
2012    /// Register a `Waker` that fires when a new
2013    /// request arrives. Mirror of the existing subscriber /
2014    /// service-client wake plumbing. Returns `false` on a backend that
2015    /// cannot wake — the caller falls back to polling.
2016    pub fn register_waker(&self, waker: &core::task::Waker) -> bool {
2017        use nros_rmw::ServiceTrait;
2018        self.handle.register_waker(waker)
2019    }
2020
2021    /// Construct a [`RawServiceServer`] from a backend-allocated
2022    /// `RmwServiceServer` handle. Public so external crates and the
2023    /// C / C++ FFI shims can wrap a handle obtained directly from
2024    /// [`NodeHandle::session_mut`](crate::executor::NodeHandle::session_mut).
2025    pub fn new(handle: session::RmwServiceServer) -> Self {
2026        Self {
2027            handle,
2028            req_buffer: [0u8; REQ_BUF],
2029            _phantom_resp: PhantomData,
2030        }
2031    }
2032
2033    /// Try to receive a service request (non-blocking).
2034    ///
2035    /// Returns `Ok(Some((len, sequence_number)))` when a request is
2036    /// available — the raw CDR bytes live in
2037    /// [`req_buffer`](Self::req_buffer) at `&req_buffer()[..len]`
2038    /// until the next call. The sequence number is required by
2039    /// [`send_response_raw`](Self::send_response_raw).
2040    pub fn take_request_raw(&mut self) -> Result<Option<(usize, i64)>, NodeError> {
2041        match self.handle.take_request(&mut self.req_buffer) {
2042            Ok(Some(req)) => Ok(Some((req.data.len(), req.sequence_number))),
2043            Ok(None) => Ok(None),
2044            // issue 1088 — a request is pending and every reply slot is held by
2045            // one not yet answered. Distinct from `Ok(None)` (nothing pending)
2046            // and from a failure: answer something, then take again.
2047            Err(TransportError::WouldBlock) => {
2048                Err(NodeError::Transport(TransportError::WouldBlock))
2049            }
2050            Err(_) => Err(NodeError::Transport(TransportError::ServiceRequestFailed)),
2051        }
2052    }
2053
2054    /// Borrow the inline request buffer. Valid after a successful
2055    /// [`take_request_raw`](Self::take_request_raw) call.
2056    pub fn req_buffer(&self) -> &[u8] {
2057        &self.req_buffer
2058    }
2059
2060    /// Send a reply with raw CDR bytes. `sequence_number` must match
2061    /// the value returned by the most recent
2062    /// [`take_request_raw`](Self::take_request_raw).
2063    pub fn send_response_raw(
2064        &mut self,
2065        sequence_number: i64,
2066        data: &[u8],
2067    ) -> Result<(), NodeError> {
2068        self.handle
2069            .send_response(sequence_number, data)
2070            .map_err(|_| NodeError::ServiceReplyFailed)
2071    }
2072
2073    /// The service this server was created on — see
2074    /// [`EmbeddedPublisher::topic_name`].
2075    pub fn service_name(&self) -> &str {
2076        self.handle.service_name()
2077    }
2078
2079    /// The QoS the backend GRANTED this service's REQUEST endpoint — issue
2080    /// 1437.
2081    ///
2082    /// `rmw_service_request_subscription_get_actual_qos`. One `create` builds
2083    /// TWO endpoints that negotiate against different peers, so the two
2084    /// directions are two answers and neither stands for the other; a
2085    /// reliable reply path over a best-effort request path is a working
2086    /// service that drops calls.
2087    ///
2088    /// **A policy the backend could not report reads back as its `Unknown`
2089    /// variant**, never as the request. A backend with no read-back at all
2090    /// answers [`QoSProfile::QOS_PROFILE_UNKNOWN`](nros_rmw::QoSProfile::QOS_PROFILE_UNKNOWN),
2091    /// every field an absence.
2092    ///
2093    /// Free: read once at create and retained, so this never re-enters the
2094    /// transport.
2095    pub fn request_subscription_actual_qos(&self) -> nros_rmw::QoSProfile {
2096        nros_rmw::ServiceTrait::request_subscription_actual_qos(&self.handle)
2097    }
2098
2099    /// The QoS the backend GRANTED this service's RESPONSE endpoint — issue
2100    /// 1437. See [`request_subscription_actual_qos`](Self::request_subscription_actual_qos).
2101    pub fn response_publisher_actual_qos(&self) -> nros_rmw::QoSProfile {
2102        nros_rmw::ServiceTrait::response_publisher_actual_qos(&self.handle)
2103    }
2104}
2105
2106/// Typeless service-client handle. L1 counterpart of
2107/// [`EmbeddedServiceClient`] for the same audience as
2108/// [`RawServiceServer`].
2109pub struct RawServiceClient<
2110    const REQ_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2111    const REPLY_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2112> {
2113    pub(crate) handle: session::RmwServiceClient,
2114    pub(crate) reply_buffer: [u8; REPLY_BUF],
2115    pub(crate) _phantom_req: PhantomData<[u8; REQ_BUF]>,
2116}
2117
2118impl<const REQ_BUF: usize, const REPLY_BUF: usize> RawServiceClient<REQ_BUF, REPLY_BUF> {
2119    /// Register a `Waker` that fires when the
2120    /// reply to a previously-sent request lands. Returns `false` on a
2121    /// backend that cannot wake.
2122    pub fn register_waker(&self, waker: &core::task::Waker) -> bool {
2123        use nros_rmw::ClientTrait;
2124        self.handle.register_waker(waker)
2125    }
2126
2127    /// Construct from a backend-allocated handle. Same audience as
2128    /// [`RawServiceServer::new`].
2129    pub fn new(handle: session::RmwServiceClient) -> Self {
2130        Self {
2131            handle,
2132            reply_buffer: [0u8; REPLY_BUF],
2133            _phantom_req: PhantomData,
2134        }
2135    }
2136
2137    /// The QoS the backend GRANTED this client's REQUEST endpoint — issue
2138    /// 1437. The client-side mirror of
2139    /// [`RawServiceServer::request_subscription_actual_qos`]: same topic pair,
2140    /// the other end of it, and the two need not agree.
2141    pub fn request_publisher_actual_qos(&self) -> nros_rmw::QoSProfile {
2142        nros_rmw::ClientTrait::request_publisher_actual_qos(&self.handle)
2143    }
2144
2145    /// The QoS the backend GRANTED this client's RESPONSE endpoint — issue
2146    /// 1437. See [`request_publisher_actual_qos`](Self::request_publisher_actual_qos).
2147    pub fn response_subscription_actual_qos(&self) -> nros_rmw::QoSProfile {
2148        nros_rmw::ClientTrait::response_subscription_actual_qos(&self.handle)
2149    }
2150
2151    /// Send a raw CDR request. Non-blocking; the reply arrives via
2152    /// [`take_response_raw`](Self::take_response_raw).
2153    ///
2154    /// Returns the SEQUENCE ID the backend assigned, which the
2155    /// reply carries back. This handle keeps no table: a caller with more than
2156    /// one request outstanding matches the id itself — the shape of upstream's
2157    /// `rcl_send_request(client, req, &sequence_number)`. It is
2158    /// [`nros_rmw::SEQUENCE_ID_UNKNOWN`] on a backend that cannot assign ids.
2159    pub fn send_request_raw(&mut self, request: &[u8]) -> Result<i64, NodeError> {
2160        self.handle
2161            .send_request_raw(request)
2162            .map_err(|_| NodeError::ServiceRequestFailed)
2163    }
2164
2165    /// Graph-aware "is the matching server up?"
2166    /// probe. Mirrors [`EmbeddedServiceClient::service_is_ready`](crate::executor::EmbeddedServiceClient::service_is_ready) for the raw API.
2167    pub fn service_is_ready(&self) -> Result<bool, NodeError> {
2168        use nros_rmw::ClientTrait;
2169        self.handle.service_is_ready().map_err(NodeError::Transport)
2170    }
2171
2172    /// Try to receive a reply (non-blocking). Returns
2173    /// `Ok(Some((len, sequence_id)))` on success; bytes live in
2174    /// [`reply_buffer`](Self::reply_buffer) until the next call, and
2175    /// `sequence_id` is the one [`send_request_raw`](Self::send_request_raw)
2176    /// returned for the request this answers — upstream's
2177    /// `rcl_take_response` request header.
2178    pub fn take_response_raw(&mut self) -> Result<Option<(usize, i64)>, NodeError> {
2179        self.handle
2180            .take_response_raw(&mut self.reply_buffer)
2181            .map_err(|_| NodeError::Transport(TransportError::ServiceRequestFailed))
2182    }
2183
2184    /// Borrow the inline reply buffer. Valid after a successful
2185    /// [`take_response_raw`](Self::take_response_raw) call.
2186    pub fn reply_buffer(&self) -> &[u8] {
2187        &self.reply_buffer
2188    }
2189
2190    /// The service this client was created on — see
2191    /// [`EmbeddedPublisher::topic_name`].
2192    pub fn service_name(&self) -> &str {
2193        self.handle.service_name()
2194    }
2195}
2196
2197/// Read-only view into a [`RawSubscription`]'s receive buffer.
2198///
2199/// `!Send + !Sync`: cannot cross `.await` or threads. Drop releases
2200/// any backend lock + lets the next message advance.
2201///
2202/// Two backings, selected at compile time by the `rmw-lending` feature:
2203/// the no-lending variant points at `RawSubscription::buffer` (filled by
2204/// `take_serialized`'s memcpy); the lending variant holds the backend's
2205/// own `SlotBorrowing::View` — zero
2206/// copies on the receive path, with the backend's Drop taking care of
2207/// releasing the buffer lock.
2208#[cfg(not(feature = "rmw-lending"))]
2209pub struct RecvView<'a> {
2210    bytes: &'a [u8],
2211    _marker: core::marker::PhantomData<*const ()>,
2212}
2213
2214#[cfg(feature = "rmw-lending")]
2215pub struct RecvView<'a> {
2216    /// `Option` for symmetry with `PublishLoan::backend_slot`. Always
2217    /// `Some(_)` until the view is dropped.
2218    view: Option<<session::RmwSubscriber as nros_rmw::SlotBorrowing>::View<'a>>,
2219    _marker: core::marker::PhantomData<*const ()>,
2220}
2221
2222#[cfg(not(feature = "rmw-lending"))]
2223impl<'a> core::ops::Deref for RecvView<'a> {
2224    type Target = [u8];
2225    fn deref(&self) -> &[u8] {
2226        self.bytes
2227    }
2228}
2229
2230#[cfg(feature = "rmw-lending")]
2231impl<'a> core::ops::Deref for RecvView<'a> {
2232    type Target = [u8];
2233    fn deref(&self) -> &[u8] {
2234        // SAFETY-invariant: `view` is `Some` for the whole life of a
2235        // `RecvView` — only `Drop` takes it, after which no method (incl.
2236        // this `deref`) is reachable.
2237        self.view
2238            .as_ref()
2239            .expect("RecvView accessed after drop")
2240            .as_ref()
2241    }
2242}
2243
2244#[cfg(not(feature = "rmw-lending"))]
2245impl<'a> AsRef<[u8]> for RecvView<'a> {
2246    fn as_ref(&self) -> &[u8] {
2247        self.bytes
2248    }
2249}
2250
2251#[cfg(feature = "rmw-lending")]
2252impl<'a> AsRef<[u8]> for RecvView<'a> {
2253    fn as_ref(&self) -> &[u8] {
2254        // SAFETY-invariant: `view` is `Some` until `Drop`; see the `Deref`
2255        // impl above.
2256        self.view
2257            .as_ref()
2258            .expect("RecvView accessed after drop")
2259            .as_ref()
2260    }
2261}
2262
2263// ============================================================================
2264// EmbeddedServiceServer
2265// ============================================================================
2266
2267/// Typed service server handle with internal buffers.
2268pub struct EmbeddedServiceServer<
2269    Svc: RosService,
2270    const REQ_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2271    const REPLY_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2272> {
2273    pub(crate) handle: session::RmwServiceServer,
2274    pub(crate) req_buffer: [u8; REQ_BUF],
2275    pub(crate) reply_buffer: [u8; REPLY_BUF],
2276    pub(crate) _phantom: PhantomData<Svc>,
2277}
2278
2279impl<Svc: RosService, const REQ_BUF: usize, const REPLY_BUF: usize>
2280    EmbeddedServiceServer<Svc, REQ_BUF, REPLY_BUF>
2281{
2282    /// Handle an incoming service request.
2283    ///
2284    /// Returns `Ok(true)` if a request was handled, `Ok(false)` if none available.
2285    pub fn handle_request(
2286        &mut self,
2287        handler: impl FnOnce(&Svc::Request) -> Svc::Reply,
2288    ) -> Result<bool, NodeError> {
2289        self.handle
2290            .handle_request::<Svc>(&mut self.req_buffer, &mut self.reply_buffer, handler)
2291            .map_err(|_| NodeError::ServiceReplyFailed)
2292    }
2293
2294    /// Handle a request with a heap-allocated reply (for large response types).
2295    ///
2296    /// Used by parameter services and lifecycle services (large response structs
2297    /// that overflow the stack). Returns `Ok(true)` if a request was handled,
2298    /// `Ok(false)` if none available.
2299    #[cfg(all(
2300        any(feature = "param-services", feature = "lifecycle-services"),
2301        feature = "alloc"
2302    ))]
2303    pub fn handle_request_boxed(
2304        &mut self,
2305        handler: impl FnOnce(&Svc::Request) -> alloc::boxed::Box<Svc::Reply>,
2306    ) -> Result<bool, NodeError> {
2307        self.handle
2308            .handle_request_boxed::<Svc>(&mut self.req_buffer, &mut self.reply_buffer, handler)
2309            .map_err(|_| NodeError::ServiceReplyFailed)
2310    }
2311
2312    /// Handle a request by STREAMING it — the handler reads the request's fields
2313    /// off the wire and writes the reply's fields straight back, so neither is
2314    /// ever materialised as a value.
2315    ///
2316    /// This is what `handle_request_boxed` should have been: that
2317    /// one boxes the reply and leaves the REQUEST as a stack local, which is how
2318    /// `ros2 param set` came to put 1.19 MB on the calling task's stack. Streaming
2319    /// removes both, and needs no allocator — see
2320    /// `ServiceTrait::handle_request_raw` for why it is byte-identical to the
2321    /// generated `Serialize` impls, and for the drift risk it carries.
2322    #[cfg(any(feature = "param-services", feature = "lifecycle-services"))]
2323    pub fn handle_request_raw(
2324        &mut self,
2325        handler: impl FnOnce(
2326            &mut nros_core::CdrReader<'_>,
2327            &mut nros_core::CdrWriter<'_>,
2328        ) -> Result<(), nros_rmw::TransportError>,
2329    ) -> Result<bool, NodeError> {
2330        self.handle
2331            .handle_request_raw(&mut self.req_buffer, &mut self.reply_buffer, handler)
2332            .map_err(|_| NodeError::ServiceReplyFailed)
2333    }
2334
2335    /// Check if a request is available.
2336    pub fn has_request(&self) -> bool {
2337        self.handle.has_request()
2338    }
2339
2340    /// The service this server was created on — rclrs's
2341    /// `ServiceState::service_name`, C's `rcl_service_get_service_name`,
2342    /// C++'s `Service::get_service_name`. See
2343    /// [`EmbeddedPublisher::topic_name`] for the contract and for why the
2344    /// accessor is here rather than on the RMW trait.
2345    ///
2346    /// Bounded against rclrs: the name is a `&str` BORROWED from this handle where
2347    /// rclrs returns an owned `String` (no allocator), and the receiver is this live
2348    /// handle — no type here is called `Service` (the declared entity is
2349    /// `ServiceServer`, the RMW seam `ServiceTrait`).
2350    pub fn service_name(&self) -> &str {
2351        self.handle.service_name()
2352    }
2353}
2354
2355// ============================================================================
2356// ServiceClientCallback (RFC-0041, Phase 239.1)
2357// ============================================================================
2358
2359/// Send handle for a **callback-based** typed service client.
2360///
2361/// Returned by `create_client_with_callback`: the reply is delivered to the
2362/// registered closure at `spin_once` (no `Promise` poll). This handle only
2363/// **sends** — it holds a `*mut` to the arena entry's
2364/// `ServiceClientSendHeader` (pinned in
2365/// the executor arena, like a guard-condition flag), so a single outstanding
2366/// request is gated by `hdr.pending`.
2367///
2368/// # Safety / lifetime
2369/// Valid only while the owning executor lives (the arena backs the header). Do
2370/// not use after the executor is dropped.
2371pub struct ServiceClientCallback<
2372    Svc: RosService,
2373    const REQ_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2374    const REPLY_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2375> {
2376    hdr: *mut super::arena::ServiceClientSendHeader<REPLY_BUF>,
2377    _phantom: PhantomData<Svc>,
2378}
2379
2380impl<Svc: RosService, const REQ_BUF: usize, const REPLY_BUF: usize>
2381    ServiceClientCallback<Svc, REQ_BUF, REPLY_BUF>
2382{
2383    /// Wrap an arena-resident send header. `hdr` must point at a live
2384    /// `ServiceClientCallbackEntry`'s header for the executor's lifetime.
2385    pub(crate) fn new(hdr: *mut super::arena::ServiceClientSendHeader<REPLY_BUF>) -> Self {
2386        Self {
2387            hdr,
2388            _phantom: PhantomData,
2389        }
2390    }
2391
2392    /// Send a typed request. The reply is delivered to the registered callback
2393    /// at a later `spin_once`. Returns `RequestInFlight` if a prior request has
2394    /// not yet been answered (single outstanding request).
2395    pub fn call(&mut self, request: &Svc::Request) -> Result<(), NodeError> {
2396        let hdr = unsafe { &mut *self.hdr };
2397        if hdr.pending {
2398            return Err(NodeError::RequestInFlight);
2399        }
2400        let mut buf = [0u8; REQ_BUF];
2401        let mut writer = crate::tx_writer(&mut buf).map_err(|_| NodeError::BufferTooSmall)?;
2402        request
2403            .serialize(&mut writer)
2404            .map_err(|_| NodeError::Serialization)?;
2405        let req_len = writer.position();
2406        let seq = hdr
2407            .handle
2408            .send_request_raw(&buf[..req_len])
2409            .map_err(|_| NodeError::ServiceRequestFailed)?;
2410        // Issue 2009 — the dispatcher delivers only the reply naming this id.
2411        super::arena::record_client_send(&mut hdr.sequences, seq, false);
2412        hdr.pending = true;
2413        Ok(())
2414    }
2415}
2416
2417// ============================================================================
2418// ActionClientCallback (RFC-0041, Phase 239.2)
2419// ============================================================================
2420
2421/// Send handle for a **callback-based** typed action client.
2422///
2423/// Returned by `create_action_client_with_callbacks`: goal-response, feedback,
2424/// and result are delivered to the registered closures at `spin_once` (no
2425/// `Promise` poll). This handle only **sends** — it holds a `*mut` to the arena
2426/// entry's [`ActionClientCore`](super::action_core::ActionClientCore) (offset 0,
2427/// pinned in the executor arena, like a guard-condition flag).
2428///
2429/// # Safety / lifetime
2430/// Valid only while the owning executor lives.
2431pub struct ActionClientCallback<
2432    A: RosAction,
2433    const GOAL_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2434    const RESULT_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2435    const FEEDBACK_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2436> {
2437    core: *mut super::action_core::ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
2438    _phantom: PhantomData<A>,
2439}
2440
2441impl<A: RosAction, const GOAL_BUF: usize, const RESULT_BUF: usize, const FEEDBACK_BUF: usize>
2442    ActionClientCallback<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>
2443{
2444    /// Wrap an arena-resident core. `core` must point at a live
2445    /// `ActionClientCallbackEntry`'s core for the executor's lifetime.
2446    pub(crate) fn new(
2447        core: *mut super::action_core::ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
2448    ) -> Self {
2449        Self {
2450            core,
2451            _phantom: PhantomData,
2452        }
2453    }
2454
2455    /// Send a typed goal. Returns its `GoalUuid`; acceptance arrives via the
2456    /// registered goal-response callback.
2457    pub fn send_goal(&mut self, goal: &A::Goal) -> Result<nros_core::GoalUuid, NodeError> {
2458        let core = unsafe { &mut *self.core };
2459        let mut buf = [0u8; GOAL_BUF];
2460        let mut writer = crate::tx_writer(&mut buf).map_err(|_| NodeError::BufferTooSmall)?;
2461        goal.serialize(&mut writer)
2462            .map_err(|_| NodeError::Serialization)?;
2463        let len = writer.position();
2464        core.send_goal_raw(&buf[..len])
2465    }
2466
2467    /// Request the result for `goal_id`; the result arrives via the registered
2468    /// result callback.
2469    pub fn get_result(&mut self, goal_id: &nros_core::GoalUuid) -> Result<(), NodeError> {
2470        let core = unsafe { &mut *self.core };
2471        core.send_get_result_request(goal_id)
2472    }
2473}
2474
2475// ============================================================================
2476// EmbeddedServiceClient
2477// ============================================================================
2478
2479/// Typed service client handle with internal buffers.
2480pub struct EmbeddedServiceClient<
2481    Svc: RosService,
2482    const REQ_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2483    const REPLY_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2484> {
2485    pub(crate) handle: session::RmwServiceClient,
2486    pub(crate) req_buffer: [u8; REQ_BUF],
2487    pub(crate) reply_buffer: [u8; REPLY_BUF],
2488    /// Phase 84.D3: set after a successful `send_request`, cleared on a
2489    /// successful `Promise::take`. Guards against "drop Promise
2490    /// without awaiting, then `call()` again" which would otherwise
2491    /// deliver the stale reply to the new caller.
2492    pub(crate) in_flight: bool,
2493    /// Issue 2009 — the id of the request in flight. The `Promise` accepts
2494    /// only the reply naming it, so a reply to a call abandoned with
2495    /// [`reset_in_flight`](Self::reset_in_flight) is dropped rather than
2496    /// delivered to the next call.
2497    pub(crate) pending: nros_rmw::RequestCorrelator<(), 1>,
2498    pub(crate) _phantom: PhantomData<Svc>,
2499}
2500
2501/// What a server-readiness probe answered, read the way a WAIT
2502/// loop must read it.
2503///
2504/// `ClientTrait::service_is_ready` has three answers, and every
2505/// wait loop in the tree — Rust's `wait_for_service` /
2506/// `wait_for_action_server` and the four C / C++ bindings — classifies the
2507/// probe through [`Self::of`], so the six loops cannot come to disagree.
2508///
2509/// The third answer is the one the loops used to drop. A backend that has no
2510/// discovery (XRCE: the Agent owns the DDS participant, `vtable.c` keeps the
2511/// slot NULL) answers `Err(Unsupported)` on EVERY probe, so waiting can never
2512/// change it. An older version folded it into "keep waiting", which spent the whole
2513/// budget and then reported TIMEOUT — and every C / C++ client example treats
2514/// TIMEOUT as "no server" and exits. So the C and C++ XRCE action and service
2515/// clients could not complete a single round-trip against a server that was
2516/// up and serving (measured: `Action server did not appear within 10s: -2`
2517/// with the server running beside it). rcl reports this case as an ERROR from
2518/// `rcl_service_server_is_available`, not as "no"; the loops now return it
2519/// at once as `Unsupported`, and the caller — which knows whether it may send
2520/// blind — decides. The Rust service-client examples already did exactly
2521/// that with the raw probe (`Err` ⇒ send anyway).
2522#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2523pub enum ServerVisibility {
2524    /// A matching server is visible now.
2525    Visible,
2526    /// The backend can answer, and has not seen one yet — keep waiting.
2527    NotYet,
2528    /// The backend cannot answer this question at all; waiting will not
2529    /// change that.
2530    Unknowable,
2531}
2532
2533impl ServerVisibility {
2534    /// Classify one readiness probe.
2535    ///
2536    /// Only `Unsupported` is [`Self::Unknowable`]. Any other `Err` is a probe
2537    /// that failed THIS time, so the loop keeps waiting rather than giving up
2538    /// on a backend that does answer.
2539    pub fn of(probe: Result<bool, TransportError>) -> Self {
2540        match probe {
2541            Ok(true) => Self::Visible,
2542            Ok(false) => Self::NotYet,
2543            Err(TransportError::Unsupported) => Self::Unknowable,
2544            Err(_) => Self::NotYet,
2545        }
2546    }
2547}
2548
2549/// The shared body of the two Rust wait loops. `probe` is re-run after every
2550/// `spin_once`; see [`ServerVisibility`].
2551pub(crate) fn wait_for_server_visible(
2552    executor: &mut super::Executor,
2553    timeout: core::time::Duration,
2554    mut probe: impl FnMut() -> Result<bool, TransportError>,
2555) -> Result<bool, NodeError> {
2556    match ServerVisibility::of(probe()) {
2557        ServerVisibility::Visible => return Ok(true),
2558        ServerVisibility::Unknowable => {
2559            return Err(NodeError::Transport(TransportError::Unsupported));
2560        }
2561        ServerVisibility::NotYet => {}
2562    }
2563    let spin_interval = core::time::Duration::from_millis(DEFAULT_SPIN_INTERVAL_MS);
2564    let max_spins = (timeout.as_millis() as u64 / DEFAULT_SPIN_INTERVAL_MS).max(1);
2565    let mut budget = WaitBudget::new(max_spins, timeout);
2566    // phase-428 W13 — spin, then ask again. The liveliness subscriber that
2567    // feeds the zenoh set runs on the executor's read path, so each
2568    // `spin_once` is what lets a freshly declared token land in the set.
2569    loop {
2570        executor.spin_once(budget.next_spin_interval(spin_interval));
2571        match ServerVisibility::of(probe()) {
2572            ServerVisibility::Visible => return Ok(true),
2573            ServerVisibility::Unknowable => {
2574                return Err(NodeError::Transport(TransportError::Unsupported));
2575            }
2576            ServerVisibility::NotYet => {}
2577        }
2578        if !budget.tick() {
2579            return Ok(false);
2580        }
2581    }
2582}
2583
2584impl<Svc: RosService, const REQ_BUF: usize, const REPLY_BUF: usize>
2585    EmbeddedServiceClient<Svc, REQ_BUF, REPLY_BUF>
2586{
2587    /// Call the service (non-blocking). Returns a [`Promise`] that can be polled.
2588    ///
2589    /// Use with `Executor::spin_once()` to drive I/O while waiting:
2590    ///
2591    /// ```ignore
2592    /// let mut promise = client.call(&request)?;
2593    /// loop {
2594    ///     executor.spin_once(core::time::Duration::from_millis(10));
2595    ///     if let Some(reply) = promise.take()? {
2596    ///         break;
2597    ///     }
2598    /// }
2599    /// ```
2600    ///
2601    /// # Errors
2602    ///
2603    /// Returns [`NodeError::RequestInFlight`] if a previous call's reply
2604    /// has not been received. This prevents the old hazard where dropping
2605    /// a [`Promise`] without awaiting its reply left the stale reply
2606    /// queued to land on the next [`call`](Self::call). Resolve by
2607    /// polling the existing promise to completion or calling
2608    /// [`reset_in_flight`](Self::reset_in_flight).
2609    pub fn call(&mut self, request: &Svc::Request) -> Result<Promise<'_, Svc::Reply>, NodeError> {
2610        if self.in_flight {
2611            return Err(NodeError::RequestInFlight);
2612        }
2613
2614        // Serialize request into req_buffer
2615        let mut writer =
2616            crate::tx_writer(&mut self.req_buffer).map_err(|_| NodeError::BufferTooSmall)?;
2617        request
2618            .serialize(&mut writer)
2619            .map_err(|_| NodeError::Serialization)?;
2620        let req_len = writer.position();
2621
2622        // Send the request (non-blocking)
2623        let seq = self
2624            .handle
2625            .send_request_raw(&self.req_buffer[..req_len])
2626            .map_err(|_| NodeError::ServiceRequestFailed)?;
2627
2628        // Issue 2009 — the promise accepts only the reply naming `seq`.
2629        self.pending.clear();
2630        let _ = self.pending.insert(seq, ());
2631        self.in_flight = true;
2632
2633        Ok(Promise {
2634            handle: &mut self.handle,
2635            reply_buffer: &mut self.reply_buffer,
2636            parse: cdr_deserialize_reply::<Svc>,
2637            in_flight_flag: &mut self.in_flight,
2638            pending: &mut self.pending,
2639        })
2640    }
2641
2642    /// Explicitly clear the in-flight flag.
2643    ///
2644    /// Call this if a previous [`Promise`] was dropped without completing
2645    /// and you want to abandon the pending reply. The next
2646    /// [`call`](Self::call) proceeds, and the abandoned call's reply — if it
2647    /// still arrives — is DROPPED: the next promise accepts only the reply
2648    /// naming its own request's id. It used to be delivered to
2649    /// the next call.
2650    pub fn reset_in_flight(&mut self) {
2651        self.in_flight = false;
2652        self.pending.clear();
2653    }
2654
2655    /// Block until at least one matching service server is discoverable on
2656    /// the network, or `timeout` elapses.
2657    ///
2658    /// Returns `Ok(true)` if a matching server reported back inside the
2659    /// budget; `Ok(false)` on timeout (no server visible). Mirrors
2660    /// `rclcpp::ClientBase::wait_for_service` and
2661    /// `rclpy.client.Client.wait_for_service`.
2662    ///
2663    /// A spin on [`service_is_ready`](Self::service_is_ready): the executor
2664    /// is spun cooperatively between checks so other subscribers / timers
2665    /// continue to make progress, and the check itself is a synchronous read
2666    /// of the discovery state the backend maintains (on zenoh, the
2667    /// matched-server set fed by liveliness PUT/DELETE). No
2668    /// query is issued at call time, which is also how upstream answers.
2669    ///
2670    /// A backend that cannot answer (`Err`, e.g. XRCE) is
2671    /// "cannot say", NOT "yes". It used to be yes, so this returned
2672    /// immediately on cyclone, XRCE and uORB without probing anything.
2673    ///
2674    /// And "cannot say" is not "no" either: such a backend
2675    /// returns `Err(NodeError::Transport(TransportError::Unsupported))` at
2676    /// once, rather than waiting out a budget no answer can arrive in and
2677    /// reporting `Ok(false)`. See [`ServerVisibility`]. A caller that may send
2678    /// blind (the request's own timeout is then the probe) matches that
2679    /// error and proceeds.
2680    ///
2681    /// Recommended usage — gate the first `call()` on this:
2682    ///
2683    /// ```ignore
2684    /// let mut client = node.create_client::<AddTwoInts>("/add_two_ints")?;
2685    /// if !client.wait_for_service(&mut executor, Duration::from_secs(5))? {
2686    ///     return Err(NodeError::Timeout);
2687    /// }
2688    /// let mut promise = client.call(&request)?;
2689    /// ```
2690    ///
2691    /// Nothing is latched. `service_is_ready` reads the CURRENT state, so a
2692    /// server that goes away after this returned `true` reads unavailable
2693    /// again — which is what `rclcpp` does too (`ClientBase::service_is_ready`
2694    /// calls `rcl_service_server_is_available` on every invocation; there is
2695    /// no snapshot semantic, whatever an earlier comment here claimed).
2696    pub fn wait_for_service(
2697        &mut self,
2698        executor: &mut super::Executor,
2699        timeout: core::time::Duration,
2700    ) -> Result<bool, NodeError> {
2701        // `Ok(true)` only means visible (issue 1008); `Unsupported` returns at
2702        // once (issue 1686) — see `ServerVisibility`.
2703        let handle = &self.handle;
2704        wait_for_server_visible(executor, timeout, || handle.service_is_ready())
2705    }
2706
2707    // phase-379 W6 decision 2 — the bool-returning `service_is_ready` was
2708    // DELETED here. It forwarded to `ClientTrait::is_server_ready`, whose trait
2709    // default is `true` and which only zenoh overrode, so on every cffi-backed
2710    // image (cyclonedds, XRCE, uORB) it answered "ready" without asking anything
2711    // — issue 1008. The `Result` form below is the same query with rcl's two
2712    // channels kept, and it is now the only one.
2713
2714    /// Graph-aware server-availability probe.
2715    ///
2716    /// Returns `Ok(true)` / `Ok(false)` when the backend can answer
2717    /// (zenoh queryable interest, DDS built-in topic reader), or
2718    /// `Err(NodeError::Transport(Unsupported))` when it can't (XRCE
2719    /// agent without participant enumeration). Distinct from
2720    /// rclcpp collapses this to a bare `bool` and throws on error;
2721    /// The C++ API design forbids exceptions, so the `Result` carries what the
2722    /// exception would have.
2723    ///
2724    /// Used to gate the first request so a startup-ordering race
2725    /// (client opens before server's discovery announcement lands)
2726    /// doesn't surface as a request-side timeout.
2727    pub fn service_is_ready(&self) -> Result<bool, NodeError> {
2728        use nros_rmw::ClientTrait;
2729        self.handle.service_is_ready().map_err(NodeError::Transport)
2730    }
2731
2732    /// The service this client was created on — rclrs's
2733    /// `ClientState::service_name`, C's `rcl_client_get_service_name`,
2734    /// C++'s `Client::get_service_name`. See
2735    /// [`EmbeddedPublisher::topic_name`] for the contract and for why the
2736    /// accessor is here rather than on the RMW trait.
2737    ///
2738    /// Bounded against rclrs: the name is a `&str` BORROWED from this handle where
2739    /// rclrs returns an owned `String` (no allocator), and the receiver is this live
2740    /// handle — no type here is called `Client` (the declared entity is
2741    /// `ServiceClient`, the RMW seam `ClientTrait`).
2742    pub fn service_name(&self) -> &str {
2743        self.handle.service_name()
2744    }
2745}
2746
2747// ============================================================================
2748// Promise
2749// ============================================================================
2750
2751/// A pending reply from a non-blocking service or action call.
2752///
2753/// Poll with [`take()`](Promise::take) to check for the reply.
2754/// Implements [`Future`](core::future::Future) for use with async executors.
2755pub struct Promise<'a, T> {
2756    pub(crate) handle: &'a mut session::RmwServiceClient,
2757    pub(crate) reply_buffer: &'a mut [u8],
2758    pub(crate) parse: fn(&[u8]) -> Result<T, NodeError>,
2759    /// Phase 84.D3: cleared on a successful `take` so the client's
2760    /// next `call()` can proceed. If the `Promise` is dropped before the
2761    /// reply is consumed, the flag stays set — forcing the user to
2762    /// explicitly acknowledge the abandoned call via
2763    /// `reset_in_flight()`.
2764    pub(crate) in_flight_flag: &'a mut bool,
2765    /// Issue 2009 — the ids this promise's request may come back under. A
2766    /// reply naming any other id is stale (an abandoned call's) and dropped.
2767    pub(crate) pending: &'a mut dyn nros_rmw::ReplyMatcher,
2768}
2769
2770impl<T> Promise<'_, T> {
2771    /// Try to receive the reply (non-blocking).
2772    ///
2773    /// Returns `Ok(Some(reply))` if the reply has arrived,
2774    /// `Ok(None)` if still pending.
2775    /// Take one message if the middleware has one.
2776    ///
2777    /// Named `take` after rcl (`rcl_take`) and rclcpp (`Subscription::take`),
2778    /// which spell the non-blocking receive that way — as does our own C
2779    /// surface. NOT after rclrs: its subscription API is callback/worker-driven
2780    /// and has no public polling counterpart at all (its `take_*` methods are
2781    /// private), which is why the ledger records this as an `extension` against
2782    /// the Rust reference rather than a match. `take` was Rust
2783    /// channel vocabulary that reads as a different contract to a ROS 2 user:
2784    /// both are non-blocking and both report emptiness without failing, so
2785    /// nothing asked for the other word. Renamed as a clean break, no shim.
2786    pub fn take(&mut self) -> Result<Option<T>, NodeError> {
2787        Ok(self.take_with_info()?.map(|(reply, _info)| reply))
2788    }
2789
2790    /// [`take`](Self::take), plus the reply's [`ServiceInfo`](nros_core::ServiceInfo).
2791    ///
2792    /// rclrs's `client.call::<_, (Response, ServiceInfo)>(..)`, and upstream
2793    /// `rmw_take_response`'s `rmw_service_info_t`: `request_id` is the
2794    /// request this reply answers (this client's GID and the sequence number
2795    /// of its request), `source_timestamp` is when the SERVER sent the reply,
2796    /// on its clock, and `received_timestamp` is when this client received
2797    /// it. As for a service callback's info, a field the backend cannot report
2798    /// is `None` — see [`nros_core::ServiceInfo`] for which backend fills
2799    /// which.
2800    pub fn take_with_info(&mut self) -> Result<Option<(T, nros_core::ServiceInfo)>, NodeError> {
2801        // Phase 120: NoData (no reply yet) is the steady-state polling
2802        // condition — map to Ok(None) instead of ServiceRequestFailed.
2803        // Issue 2009 — only the reply naming this promise's request; stale
2804        // replies met on the way are dropped.
2805        match match nros_rmw::take_matched(&mut *self.handle, self.reply_buffer, self.pending) {
2806            Ok(opt) => opt,
2807            Err(TransportError::NoData) => return Ok(None),
2808            Err(e) => return Err(NodeError::Transport(e)),
2809        } {
2810            Some((len, _seq)) => {
2811                // Issue 2136 — read before anything else can take on this
2812                // handle: the info describes the reply just matched.
2813                let info = nros_rmw::ClientTrait::response_info(&*self.handle);
2814                let reply = (self.parse)(&self.reply_buffer[..len])?;
2815                // Reply consumed — allow the client to issue another call.
2816                *self.in_flight_flag = false;
2817                Ok(Some((reply, info)))
2818            }
2819            None => Ok(None),
2820        }
2821    }
2822}
2823
2824impl<T> Promise<'_, T> {
2825    /// Block until the reply arrives, spinning the executor.
2826    ///
2827    /// Internally calls `executor.spin_once()` in a loop until the reply
2828    /// arrives or `timeout_ms` is exhausted. This is equivalent to the
2829    /// manual spin+poll loop pattern but more ergonomic for simple use cases.
2830    ///
2831    /// No borrow conflict: `executor` and `self` (which borrows the standalone
2832    /// client) are disjoint objects.
2833    ///
2834    /// # Errors
2835    ///
2836    /// Returns [`NodeError::Timeout`] if the reply does not arrive within
2837    /// `timeout_ms` milliseconds.
2838    pub fn wait(
2839        &mut self,
2840        executor: &mut super::Executor,
2841        timeout: core::time::Duration,
2842    ) -> Result<T, NodeError> {
2843        Ok(self.wait_with_info(executor, timeout)?.0)
2844    }
2845
2846    /// [`wait`](Self::wait), plus the reply's
2847    /// [`ServiceInfo`](nros_core::ServiceInfo). See
2848    /// [`take_with_info`](Self::take_with_info).
2849    pub fn wait_with_info(
2850        &mut self,
2851        executor: &mut super::Executor,
2852        timeout: core::time::Duration,
2853    ) -> Result<(T, nros_core::ServiceInfo), NodeError> {
2854        let spin_interval = core::time::Duration::from_millis(DEFAULT_SPIN_INTERVAL_MS);
2855        let timeout_ms = timeout.as_millis().min(u64::MAX as u128) as u64;
2856        let max_spins = (timeout_ms / DEFAULT_SPIN_INTERVAL_MS).max(1);
2857        let mut budget = WaitBudget::new(max_spins, timeout);
2858        // Always spin at least once so a zero-timeout still polls.
2859        loop {
2860            executor.spin_once(budget.next_spin_interval(spin_interval));
2861            if let Some(result) = self.take_with_info()? {
2862                return Ok(result);
2863            }
2864            if !budget.tick() {
2865                return Err(NodeError::Timeout);
2866            }
2867        }
2868    }
2869}
2870
2871/// Deserialize a CDR-encoded service reply.
2872fn cdr_deserialize_reply<Svc: RosService>(data: &[u8]) -> Result<Svc::Reply, NodeError> {
2873    let mut reader = CdrReader::new_with_header(data).map_err(|_| NodeError::Deserialization)?;
2874    Svc::Reply::deserialize(&mut reader).map_err(|_| NodeError::Deserialization)
2875}
2876
2877// ============================================================================
2878// Action types
2879// ============================================================================
2880
2881/// Active goal tracking for action server.
2882#[derive(Clone)]
2883pub struct ActiveGoal<A: RosAction> {
2884    /// Goal ID.
2885    pub goal_id: nros_core::GoalUuid,
2886    /// Current status.
2887    pub status: nros_core::GoalStatusCode,
2888    /// The goal data.
2889    pub goal: A::Goal,
2890}
2891
2892/// Completed goal with result.
2893pub struct CompletedGoal<A: RosAction> {
2894    /// Goal ID.
2895    pub goal_id: nros_core::GoalUuid,
2896    /// Final status.
2897    pub status: nros_core::GoalStatusCode,
2898    /// The result data.
2899    pub result: A::Result,
2900}
2901
2902// ============================================================================
2903// ActionServer
2904// ============================================================================
2905
2906/// Typed action server with goal state management.
2907///
2908/// Wraps [`ActionServerCore`](super::action_core::ActionServerCore) for
2909/// raw-bytes protocol handling, adding typed goal/feedback/result
2910/// serialization at the boundary.
2911///
2912/// The name is rclrs's and the contract is bounded: rclrs's `ActionServer<A>`
2913/// is an `Arc<ActionServerState<A>>` with async goal handling, while this one
2914/// is fixed-size, sized by const generics, and driven from the executor
2915/// (the blocking-API rules), so no goal lives on a heap and nothing needs an async runtime.
2916pub struct ActionServer<
2917    A: RosAction,
2918    const GOAL_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2919    const RESULT_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2920    const FEEDBACK_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
2921    const MAX_GOALS: usize = 4,
2922> {
2923    pub(crate) core:
2924        super::action_core::ActionServerCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
2925    /// Typed goal data parallel to `core.active_goals`.
2926    pub(crate) typed_goals: heapless::Vec<A::Goal, MAX_GOALS>,
2927    /// Completed goals with typed results.
2928    pub(crate) completed_goals: heapless::Vec<CompletedGoal<A>, MAX_GOALS>,
2929}
2930
2931impl<
2932    A: RosAction,
2933    const GOAL_BUF: usize,
2934    const RESULT_BUF: usize,
2935    const FEEDBACK_BUF: usize,
2936    const MAX_GOALS: usize,
2937> ActionServer<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>
2938{
2939    /// Try to accept a new goal.
2940    ///
2941    /// Checks for incoming send_goal requests. If one is available, calls the
2942    /// handler to decide acceptance. Returns the goal ID if accepted.
2943    pub fn try_accept_goal(
2944        &mut self,
2945        goal_handler: impl FnOnce(&nros_core::GoalUuid, &A::Goal) -> nros_core::GoalResponse,
2946    ) -> Result<Option<nros_core::GoalUuid>, NodeError>
2947    where
2948        A::Goal: Clone,
2949    {
2950        let Some((raw_req, goal)) = self.recv_goal()? else {
2951            return Ok(None);
2952        };
2953        let response = goal_handler(&raw_req.goal_id, &goal);
2954        self.finish_goal(raw_req, goal, response.is_accepted())
2955    }
2956
2957    /// The first half of [`try_accept_goal`](Self::try_accept_goal): take one
2958    /// pending `send_goal` request and decode its goal, without asking anyone
2959    /// about it. The goal is an owned value, so the caller can run its handler
2960    /// with no borrow of this server held (phase-573 W2b).
2961    pub(crate) fn recv_goal(
2962        &mut self,
2963    ) -> Result<Option<(super::action_core::RawGoalRequest, A::Goal)>, NodeError> {
2964        let Some(raw_req) = self.core.try_recv_goal_request()? else {
2965            return Ok(None);
2966        };
2967
2968        // Deserialize the goal from the buffer at the offset captured
2969        // by the core (DDS prepends an 8-byte seq prefix; zenoh uses 0).
2970        let buf = self.core.goal_buffer();
2971        let start = raw_req.data_offset;
2972        let end = start + raw_req.data_len;
2973        let mut reader = CdrReader::new_with_header(&buf[start..end])
2974            .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
2975        // Skip past the GoalUuid — a fixed `uint8[16]` UUID, no length prefix
2976        // (ROS 2 `unique_identifier_msgs/UUID`; see action_core::read_goal_id).
2977        for _ in 0..GOAL_UUID_SIZE {
2978            let _ = reader.read_u8();
2979        }
2980        let goal = A::Goal::deserialize(&mut reader)
2981            .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
2982        Ok(Some((raw_req, goal)))
2983    }
2984
2985    /// The second half of [`try_accept_goal`](Self::try_accept_goal): answer
2986    /// the request [`recv_goal`](Self::recv_goal) took, as the handler decided.
2987    pub(crate) fn finish_goal(
2988        &mut self,
2989        raw_req: super::action_core::RawGoalRequest,
2990        goal: A::Goal,
2991        accepted: bool,
2992    ) -> Result<Option<nros_core::GoalUuid>, NodeError> {
2993        if accepted {
2994            self.core
2995                .accept_goal(raw_req.goal_id, raw_req.sequence_number)?;
2996            let _ = self.typed_goals.push(goal);
2997            Ok(Some(raw_req.goal_id))
2998        } else {
2999            self.core.reject_goal(raw_req.sequence_number)?;
3000            Ok(None)
3001        }
3002    }
3003
3004    /// Publish feedback for a goal.
3005    pub fn publish_feedback(
3006        &mut self,
3007        goal_id: &nros_core::GoalUuid,
3008        feedback: &A::Feedback,
3009    ) -> Result<(), NodeError> {
3010        // Serialize feedback into a temp buffer (without CDR header or GoalUuid)
3011        let mut tmp = [0u8; FEEDBACK_BUF];
3012        let mut writer = CdrWriter::new(&mut tmp);
3013        feedback
3014            .serialize(&mut writer)
3015            .map_err(|_| NodeError::Serialization)?;
3016        let feedback_len = writer.position();
3017
3018        self.core
3019            .publish_feedback_raw(goal_id, &tmp[..feedback_len])
3020    }
3021
3022    /// Set a goal's status.
3023    ///
3024    /// Also publishes the updated `GoalStatusArray` on the status topic.
3025    pub fn set_goal_status(
3026        &mut self,
3027        goal_id: &nros_core::GoalUuid,
3028        status: nros_core::GoalStatusCode,
3029    ) {
3030        self.core.set_goal_status(goal_id, status);
3031    }
3032
3033    /// Complete a goal and store the result.
3034    ///
3035    /// Also publishes the updated `GoalStatusArray` on the status topic.
3036    ///
3037    /// # Errors
3038    ///
3039    /// `NodeError::Serialization` if `result` does not serialize, or
3040    /// `NodeError::BufferTooSmall` if the serialized result exceeds
3041    /// `RESULT_BUF` and so cannot be retained for a later `get_result`.
3042    /// This returned `()`, so both failures were invisible — and
3043    /// the second one used to strand every client waiting on the result.
3044    pub fn complete_goal(
3045        &mut self,
3046        goal_id: &nros_core::GoalUuid,
3047        status: nros_core::GoalStatusCode,
3048        result: A::Result,
3049    ) -> Result<(), NodeError> {
3050        // Serialize result for the core slab. Issue 0796: a serialization
3051        // failure used to degrade to a zero-length result stored as if it were
3052        // the real one; it is now reported.
3053        let mut tmp = [0u8; RESULT_BUF];
3054        let mut writer = CdrWriter::new(&mut tmp);
3055        let serialized = result.serialize(&mut writer);
3056        let result_len = writer.position();
3057
3058        // Remove typed goal parallel to core's active_goals removal
3059        if let Some(pos) = self
3060            .core
3061            .active_goals()
3062            .iter()
3063            .position(|g| g.goal_id.uuid == goal_id.uuid)
3064        {
3065            self.typed_goals.swap_remove(pos);
3066        }
3067
3068        let stored = match serialized {
3069            Ok(()) => self
3070                .core
3071                .complete_goal_raw(goal_id, status, &tmp[..result_len]),
3072            Err(_) => {
3073                // Still retire the goal (terminal status, waiting requesters)
3074                // with an empty payload, then report the failure.
3075                let _ = self.core.complete_goal_raw(goal_id, status, &[]);
3076                Err(NodeError::Serialization)
3077            }
3078        };
3079
3080        // Issue 0796 — the typed mirror is reclaimed with the core it mirrors.
3081        // `completed_goals` was push-only: after MAX_GOALS completions every
3082        // later push was silently dropped, so the table said "the last four
3083        // goals" while actually holding "the first four, forever".
3084        self.completed_goals
3085            .retain(|c| self.core.has_completed_result(&c.goal_id));
3086        if self.core.has_completed_result(goal_id) {
3087            let _ = self.completed_goals.push(CompletedGoal {
3088                goal_id: *goal_id,
3089                status,
3090                result,
3091            });
3092        }
3093
3094        stored
3095    }
3096
3097    /// Try to handle a cancel_goal request. `cancel_handler` is asked once
3098    /// per goal the request selects — a cancel-all or cancel-before request
3099    /// selects several (see
3100    /// [`ActionServerCore::try_handle_cancel`](crate::executor::ffi::ActionServerCoreFfi::try_handle_cancel)).
3101    pub fn try_handle_cancel(
3102        &mut self,
3103        cancel_handler: impl FnMut(
3104            &nros_core::GoalUuid,
3105            nros_core::GoalStatusCode,
3106        ) -> nros_core::CancelResponse,
3107    ) -> Result<Option<(nros_core::GoalUuid, nros_core::CancelResponse)>, NodeError> {
3108        self.core.try_handle_cancel(cancel_handler)
3109    }
3110
3111    /// Try to handle a get_result request.
3112    pub fn try_handle_get_result(&mut self) -> Result<Option<nros_core::GoalUuid>, NodeError>
3113    where
3114        A::Result: Clone + Default,
3115    {
3116        // Serialize default result for non-completed goals
3117        let mut default_buf = [0u8; RESULT_BUF];
3118        let mut writer = CdrWriter::new(&mut default_buf);
3119        let default_len = match A::Result::default().serialize(&mut writer) {
3120            Ok(()) => writer.position(),
3121            Err(_) => 0,
3122        };
3123
3124        self.core
3125            .try_handle_get_result_raw(&default_buf[..default_len])
3126    }
3127
3128    /// Drain all pending server-side work in one call.
3129    ///
3130    /// Calls `try_accept_goal`, `try_handle_cancel`, and
3131    /// `try_handle_get_result` in sequence. Invoke this on every
3132    /// `spin_once` iteration in manual-poll code — otherwise clients
3133    /// will hang on `get_result` because `create_action_server()`
3134    /// servers are not arena-registered.
3135    ///
3136    /// The two callbacks may be called zero or more times per `poll()`:
3137    ///   * `on_goal` fires when a new goal arrives.
3138    ///   * `on_cancel` fires once per goal a cancel request selects — one
3139    ///     for a request naming a goal, one per cancelable goal for a
3140    ///     cancel-all / cancel-before request.
3141    ///
3142    /// Get-result requests are drained unconditionally (no callback
3143    /// needed — the result is pulled from the goal's stored state).
3144    ///
3145    /// # Example
3146    /// ```ignore
3147    /// let mut server = node.create_action_server::<Fibonacci>("/fibonacci")?;
3148    /// loop {
3149    ///     executor.spin_once(Duration::from_millis(10));
3150    ///     server.poll(
3151    ///         |id, goal| {
3152    ///             /* accept or reject based on `goal` */
3153    ///             GoalResponse::AcceptAndExecute
3154    ///         },
3155    ///         |_id, _status| CancelResponse::Accept,
3156    ///     )?;
3157    /// }
3158    /// ```
3159    pub fn poll<GF, CF>(&mut self, mut on_goal: GF, mut on_cancel: CF) -> Result<(), NodeError>
3160    where
3161        GF: FnMut(&nros_core::GoalUuid, &A::Goal) -> nros_core::GoalResponse,
3162        CF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode) -> nros_core::CancelResponse,
3163        A::Goal: Clone,
3164        A::Result: Clone + Default,
3165    {
3166        let _ = self.try_accept_goal(|id, goal| on_goal(id, goal))?;
3167        let _ = self.try_handle_cancel(|id, status| on_cancel(id, status))?;
3168        let _ = self.try_handle_get_result()?;
3169        Ok(())
3170    }
3171
3172    /// Get a reference to an active goal.
3173    pub fn get_goal(&self, goal_id: &nros_core::GoalUuid) -> Option<ActiveGoal<A>>
3174    where
3175        A::Goal: Clone,
3176    {
3177        self.core
3178            .active_goals()
3179            .iter()
3180            .enumerate()
3181            .find(|(_, g)| g.goal_id.uuid == goal_id.uuid)
3182            .map(|(i, raw)| ActiveGoal {
3183                goal_id: raw.goal_id,
3184                status: raw.status,
3185                goal: self.typed_goals[i].clone(),
3186            })
3187    }
3188
3189    /// Get the number of active goals.
3190    pub fn active_goal_count(&self) -> usize {
3191        self.core.active_goal_count()
3192    }
3193
3194    /// Is `goal_id` a goal this server still knows about?
3195    ///
3196    /// See
3197    /// [`ActionServerCore::goal_exists`](crate::executor::ffi::ActionServerCoreFfi::goal_exists)
3198    /// for why the completed-result slab counts as well as the active set.
3199    pub fn goal_exists(&self, goal_id: &nros_core::GoalUuid) -> bool {
3200        self.core.goal_exists(goal_id)
3201    }
3202
3203    /// Eagerly reclaim every completed result already delivered.
3204    ///
3205    /// rcl's `rcl_action_expire_goals`, C's `rclc_action_expire_goals` and
3206    /// `ActionServerHandle::expire_goals` are the same call; ONE vocabulary
3207    /// across the three languages, which is what stage 4 is for. The core's own
3208    /// spelling stays `expire_completed_results` because down there the
3209    /// completed-result slab is the only thing that can be reclaimed, and no
3210    /// clock is in sight — see
3211    /// [`ActionServerCore::expire_completed_results`](crate::executor::ffi::ActionServerCoreFfi::expire_completed_results)
3212    /// for the envelope rcl's timeout leaves behind.
3213    pub fn expire_goals(&mut self) -> usize {
3214        self.core.expire_completed_results()
3215    }
3216}
3217
3218// ============================================================================
3219// ActionClient
3220// ============================================================================
3221
3222/// Typed action client handle.
3223///
3224/// Wraps [`ActionClientCore`](super::action_core::ActionClientCore) for
3225/// raw-bytes protocol handling, adding typed goal/feedback/result
3226/// serialization at the boundary.
3227///
3228/// The name is rclrs's and the contract is bounded: rclrs's `ActionClient<A>`
3229/// is an `Arc<ActionClientState<A>>` whose requests are async futures, while
3230/// this one's verbs return a `Promise` the caller drives with the executor
3231/// (the blocking-API rules), because there is no async runtime to await a future on.
3232pub struct ActionClient<
3233    A: RosAction,
3234    const GOAL_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3235    const RESULT_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3236    const FEEDBACK_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3237> {
3238    pub(crate) core: super::action_core::ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
3239    pub(crate) _phantom: PhantomData<A>,
3240}
3241
3242impl<A: RosAction, const GOAL_BUF: usize, const RESULT_BUF: usize, const FEEDBACK_BUF: usize>
3243    ActionClient<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>
3244{
3245    /// Send a goal (non-blocking). Returns the goal ID and a [`Promise`] for acceptance.
3246    ///
3247    /// The promise resolves to `true` if accepted, `false` if rejected.
3248    pub fn send_goal(
3249        &mut self,
3250        goal: &A::Goal,
3251    ) -> Result<(nros_core::GoalUuid, Promise<'_, bool>), NodeError> {
3252        if self.core.in_flight_send_goal {
3253            return Err(NodeError::RequestInFlight);
3254        }
3255
3256        // Serialize goal into a temp buffer (without CDR header or GoalUuid)
3257        let mut tmp = [0u8; GOAL_BUF];
3258        let mut writer = CdrWriter::new(&mut tmp);
3259        goal.serialize(&mut writer)
3260            .map_err(|_| NodeError::Serialization)?;
3261        let goal_len = writer.position();
3262
3263        let goal_id = self.core.send_goal_raw(&tmp[..goal_len])?;
3264        self.core.in_flight_send_goal = true;
3265
3266        Ok((
3267            goal_id,
3268            Promise {
3269                handle: &mut self.core.send_goal_client,
3270                reply_buffer: &mut self.core.result_buffer,
3271                parse: parse_goal_accepted,
3272                in_flight_flag: &mut self.core.in_flight_send_goal,
3273                pending: &mut self.core.pending_send_goal,
3274            },
3275        ))
3276    }
3277
3278    /// Try to receive feedback (non-blocking).
3279    pub fn try_recv_feedback(
3280        &mut self,
3281    ) -> Result<Option<(nros_core::GoalUuid, A::Feedback)>, NodeError> {
3282        let (goal_id, len) = match self.core.try_recv_feedback_raw()? {
3283            Some(v) => v,
3284            None => return Ok(None),
3285        };
3286
3287        // Deserialize feedback from the core's feedback buffer (after GoalUuid)
3288        let mut reader = CdrReader::new_with_header(&self.core.feedback_buffer[..len])
3289            .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
3290        // Skip GoalUuid — a fixed `uint8[16]` UUID, no length prefix
3291        // (ROS 2 `unique_identifier_msgs/UUID`; see action_core::read_goal_id).
3292        for _ in 0..GOAL_UUID_SIZE {
3293            let _ = reader.read_u8();
3294        }
3295
3296        let feedback = A::Feedback::deserialize(&mut reader)
3297            .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
3298
3299        Ok(Some((goal_id, feedback)))
3300    }
3301
3302    /// Cancel a goal (non-blocking). Returns a [`Promise`] for the
3303    /// `action_msgs/srv/CancelGoal` return code.
3304    ///
3305    /// The promise resolves to a
3306    /// [`nros_core::CancelResponseCode`], the RPC-level outcome. The per-goal
3307    /// accept/reject decision a SERVER's cancel callback returns is the
3308    /// separate [`nros_core::CancelResponse`]; both were spelled
3309    /// `CancelResponse` until the two were split.
3310    pub fn cancel_goal(
3311        &mut self,
3312        goal_id: &nros_core::GoalUuid,
3313    ) -> Result<Promise<'_, nros_core::CancelResponseCode>, NodeError> {
3314        if self.core.in_flight_cancel {
3315            return Err(NodeError::RequestInFlight);
3316        }
3317        self.core.send_cancel_request(goal_id)?;
3318        self.core.in_flight_cancel = true;
3319
3320        Ok(Promise {
3321            handle: &mut self.core.cancel_goal_client,
3322            reply_buffer: &mut self.core.result_buffer,
3323            parse: parse_cancel_response,
3324            in_flight_flag: &mut self.core.in_flight_cancel,
3325            pending: &mut self.core.pending_cancel,
3326        })
3327    }
3328
3329    /// Get the result of a completed goal (non-blocking). Returns a [`Promise`].
3330    pub fn get_result(
3331        &mut self,
3332        goal_id: &nros_core::GoalUuid,
3333    ) -> Result<Promise<'_, (nros_core::GoalStatusCode, A::Result)>, NodeError> {
3334        if self.core.in_flight_get_result {
3335            return Err(NodeError::RequestInFlight);
3336        }
3337        self.core.send_get_result_request(goal_id)?;
3338        self.core.in_flight_get_result = true;
3339
3340        Ok(Promise {
3341            handle: &mut self.core.get_result_client,
3342            reply_buffer: &mut self.core.result_buffer,
3343            parse: parse_result_response::<A>,
3344            in_flight_flag: &mut self.core.in_flight_get_result,
3345            pending: &mut self.core.pending_get_result,
3346        })
3347    }
3348
3349    /// Explicitly clear the "send_goal reply in flight" flag.
3350    ///
3351    /// The abandoned request's reply, if it still comes, is
3352    /// dropped rather than delivered to the next `send_goal`.
3353    pub fn reset_send_goal_in_flight(&mut self) {
3354        self.core.in_flight_send_goal = false;
3355        self.core.pending_send_goal.clear();
3356    }
3357
3358    /// Block until the action server's send-goal queryable is discoverable
3359    /// on the network, or `timeout` elapses.
3360    ///
3361    /// Returns `Ok(true)` on discovery, `Ok(false)` on timeout. Mirrors
3362    /// `rclcpp_action::Client::wait_for_action_server`.
3363    ///
3364    /// Implementation: spins on the `send_goal` service client's
3365    /// `service_is_ready`, the same primitive as
3366    /// [`EmbeddedServiceClient::wait_for_service`](crate::executor::EmbeddedServiceClient::wait_for_service). Once that service is reachable the
3367    /// remaining four action entities (cancel queryable + feedback /
3368    /// status / result publishers) are also reachable in practice — they
3369    /// were declared by the same server in one batch.
3370    ///
3371    /// A backend that cannot answer returns
3372    /// `Err(NodeError::Transport(TransportError::Unsupported))` at once
3373    /// — see [`ServerVisibility`].
3374    pub fn wait_for_action_server(
3375        &mut self,
3376        executor: &mut super::Executor,
3377        timeout: core::time::Duration,
3378    ) -> Result<bool, NodeError> {
3379        let core = &self.core;
3380        wait_for_server_visible(executor, timeout, || core.server_readiness())
3381    }
3382
3383    /// Snapshot whether the action server is currently visible.
3384    /// Mirrors `rclcpp_action::Client::action_server_is_ready`.
3385    pub fn action_server_is_ready(&self) -> bool {
3386        matches!(self.core.send_goal_client.service_is_ready(), Ok(true))
3387    }
3388
3389    /// Explicitly clear the "cancel reply in flight" flag.
3390    ///
3391    /// The abandoned request's reply, if it still comes, is
3392    /// dropped rather than delivered to the next `cancel_goal`.
3393    pub fn reset_cancel_in_flight(&mut self) {
3394        self.core.in_flight_cancel = false;
3395        self.core.pending_cancel.clear();
3396    }
3397
3398    /// Explicitly clear the "get_result reply in flight" flag.
3399    ///
3400    /// The abandoned request's reply, if it still comes, is
3401    /// dropped rather than delivered as the next goal's result.
3402    pub fn reset_get_result_in_flight(&mut self) {
3403        self.core.in_flight_get_result = false;
3404        self.core.pending_get_result.clear();
3405    }
3406
3407    /// Create a feedback stream (receives feedback for all goals).
3408    ///
3409    /// The stream borrows `&mut self` exclusively. Drop it before calling
3410    /// `get_result()` or `cancel_goal()`.
3411    pub fn feedback_stream(&mut self) -> FeedbackStream<'_, A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF> {
3412        FeedbackStream { client: self }
3413    }
3414
3415    /// Create a goal-filtered feedback stream.
3416    ///
3417    /// Only yields feedback for the given `goal_id`, returning `A::Feedback`
3418    /// directly (without the `GoalUuid` wrapper).
3419    pub fn feedback_stream_for(
3420        &mut self,
3421        goal_id: nros_core::GoalUuid,
3422    ) -> GoalFeedbackStream<'_, A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF> {
3423        GoalFeedbackStream {
3424            client: self,
3425            goal_id,
3426        }
3427    }
3428}
3429
3430// ============================================================================
3431// FeedbackStream
3432// ============================================================================
3433
3434/// A stream of feedback messages from an action server.
3435///
3436/// Created by [`ActionClient::feedback_stream()`]. Receives feedback for
3437/// all active goals. The stream never self-terminates — use combinators
3438/// like `take_while` or `break` to stop.
3439///
3440/// Read it with [`wait_next()`](FeedbackStream::wait_next), which drives
3441/// the executor; the async `recv()` and the `stream` feature's `Stream`
3442/// impl are retired.
3443pub struct FeedbackStream<
3444    'a,
3445    A: RosAction,
3446    const GOAL_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3447    const RESULT_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3448    const FEEDBACK_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3449> {
3450    client: &'a mut ActionClient<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
3451}
3452
3453impl<A: RosAction, const GOAL_BUF: usize, const RESULT_BUF: usize, const FEEDBACK_BUF: usize>
3454    FeedbackStream<'_, A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>
3455{
3456    /// Sync: wait for the next feedback message, spinning the executor.
3457    ///
3458    /// Returns `Ok(Some(feedback))` if a message arrives within `timeout_ms`,
3459    /// or `Ok(None)` on timeout. Unlike [`Promise::wait()`], timeout is not
3460    /// an error — the caller typically retries in a loop.
3461    pub fn wait_next(
3462        &mut self,
3463        executor: &mut super::Executor,
3464        timeout: core::time::Duration,
3465    ) -> Result<Option<(nros_core::GoalUuid, A::Feedback)>, NodeError> {
3466        let spin_interval = core::time::Duration::from_millis(DEFAULT_SPIN_INTERVAL_MS);
3467        let timeout_ms = timeout.as_millis().min(u64::MAX as u128) as u64;
3468        let max_spins = (timeout_ms / DEFAULT_SPIN_INTERVAL_MS).max(1);
3469        let mut budget = WaitBudget::new(max_spins, timeout);
3470        loop {
3471            executor.spin_once(budget.next_spin_interval(spin_interval));
3472            if let Some(item) = self.client.try_recv_feedback()? {
3473                return Ok(Some(item));
3474            }
3475            if !budget.tick() {
3476                return Ok(None);
3477            }
3478        }
3479    }
3480}
3481
3482// ============================================================================
3483// GoalFeedbackStream
3484// ============================================================================
3485
3486/// A goal-filtered feedback stream.
3487///
3488/// Created by [`ActionClient::feedback_stream_for()`]. Only yields feedback
3489/// messages matching the specified goal ID.
3490pub struct GoalFeedbackStream<
3491    'a,
3492    A: RosAction,
3493    const GOAL_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3494    const RESULT_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3495    const FEEDBACK_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
3496> {
3497    client: &'a mut ActionClient<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
3498    goal_id: nros_core::GoalUuid,
3499}
3500
3501impl<A: RosAction, const GOAL_BUF: usize, const RESULT_BUF: usize, const FEEDBACK_BUF: usize>
3502    GoalFeedbackStream<'_, A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>
3503{
3504    /// Sync: wait for the next feedback message for this goal, spinning the executor.
3505    pub fn wait_next(
3506        &mut self,
3507        executor: &mut super::Executor,
3508        timeout: core::time::Duration,
3509    ) -> Result<Option<A::Feedback>, NodeError> {
3510        let spin_interval = core::time::Duration::from_millis(DEFAULT_SPIN_INTERVAL_MS);
3511        let timeout_ms = timeout.as_millis().min(u64::MAX as u128) as u64;
3512        let max_spins = (timeout_ms / DEFAULT_SPIN_INTERVAL_MS).max(1);
3513        let mut budget = WaitBudget::new(max_spins, timeout);
3514        loop {
3515            executor.spin_once(budget.next_spin_interval(spin_interval));
3516            if let Some((id, feedback)) = self.client.try_recv_feedback()?
3517                && id.uuid == self.goal_id.uuid
3518            {
3519                return Ok(Some(feedback));
3520            }
3521            if !budget.tick() {
3522                return Ok(None);
3523            }
3524        }
3525    }
3526}
3527
3528/// Parse a goal acceptance response (bool).
3529///
3530/// Issue #223 — CDR read failures PROPAGATE: a truncated/corrupt frame used
3531/// to collapse to `accepted = false` via `unwrap_or(0)`, silently reporting
3532/// "goal rejected" for a wire error. Same rule in the two parsers below.
3533fn parse_goal_accepted(data: &[u8]) -> Result<bool, NodeError> {
3534    let mut reader =
3535        CdrReader::new_with_header(data).map_err(|_| NodeError::ServiceRequestFailed)?;
3536    let accepted = reader
3537        .read_u8()
3538        .map_err(|_| NodeError::ServiceRequestFailed)?
3539        != 0;
3540    Ok(accepted)
3541}
3542
3543/// Parse a cancel response (issue #223 — read errors propagate; an
3544/// out-of-range enum value is still mapped through `from_i8`'s default,
3545/// which is a PROTOCOL value question, not a truncation).
3546fn parse_cancel_response(data: &[u8]) -> Result<nros_core::CancelResponseCode, NodeError> {
3547    let mut reader =
3548        CdrReader::new_with_header(data).map_err(|_| NodeError::ServiceRequestFailed)?;
3549    let return_code = reader
3550        .read_i8()
3551        .map_err(|_| NodeError::ServiceRequestFailed)?;
3552    Ok(nros_core::CancelResponseCode::from_i8(return_code).unwrap_or_default())
3553}
3554
3555/// Parse an action result response (status + result; issue #223 — read
3556/// errors propagate).
3557fn parse_result_response<A: RosAction>(
3558    data: &[u8],
3559) -> Result<(nros_core::GoalStatusCode, A::Result), NodeError> {
3560    let mut reader =
3561        CdrReader::new_with_header(data).map_err(|_| NodeError::ServiceRequestFailed)?;
3562    let status_code = reader
3563        .read_i8()
3564        .map_err(|_| NodeError::ServiceRequestFailed)?;
3565    let status = nros_core::GoalStatusCode::from_i8(status_code).unwrap_or_default();
3566    let result =
3567        A::Result::deserialize(&mut reader).map_err(|_| NodeError::ServiceRequestFailed)?;
3568    Ok((status, result))
3569}
3570
3571#[cfg(test)]
3572mod parse_response_tests {
3573    // Issue #223 — truncated action-response frames must ERROR, not collapse
3574    // to plausible defaults ("goal rejected" / CancelResponseCode::default()).
3575    use super::{parse_cancel_response, parse_goal_accepted};
3576
3577    /// A valid 4-byte CDR encapsulation header with NO payload — the
3578    /// truncation case the pre-#223 parsers silently defaulted on.
3579    const HEADER_ONLY: &[u8] = &[0x00, 0x01, 0x00, 0x00];
3580
3581    #[test]
3582    fn truncated_goal_accepted_errors() {
3583        assert!(parse_goal_accepted(HEADER_ONLY).is_err());
3584    }
3585
3586    #[test]
3587    fn truncated_cancel_response_errors() {
3588        assert!(parse_cancel_response(HEADER_ONLY).is_err());
3589    }
3590
3591    #[test]
3592    fn valid_goal_accepted_still_parses() {
3593        let frame = [0x00, 0x01, 0x00, 0x00, 0x01];
3594        assert!(parse_goal_accepted(&frame).unwrap());
3595        let frame0 = [0x00, 0x01, 0x00, 0x00, 0x00];
3596        assert!(!parse_goal_accepted(&frame0).unwrap());
3597    }
3598}
3599
3600// ===========================================================================
3601// phase-436 W4 (issue 1195) — the poll interval never overshoots the caller's
3602// deadline.
3603// ===========================================================================
3604#[cfg(test)]
3605mod wait_budget_tests {
3606    use super::{DEFAULT_SPIN_INTERVAL_MS, WaitBudget};
3607    use core::time::Duration;
3608
3609    const DEFAULT: Duration = Duration::from_millis(DEFAULT_SPIN_INTERVAL_MS);
3610
3611    /// A timeout shorter than one poll interval must not be rounded up to one.
3612    /// `max_spins` floors at 1, so `wait(1ms)` ran a full `spin_once(10ms)` —
3613    /// the caller's deadline exceeded tenfold before the budget was consulted.
3614    #[test]
3615    fn a_budget_shorter_than_the_interval_shortens_the_spin() {
3616        let budget = WaitBudget::new(1, Duration::from_millis(1));
3617        let interval = budget.next_spin_interval(DEFAULT);
3618        assert!(
3619            interval <= Duration::from_millis(1),
3620            "a 1 ms budget must not spin for {interval:?}"
3621        );
3622    }
3623
3624    /// A budget longer than the interval keeps the interval: this is a cap on
3625    /// the last iteration, not a change to the polling cadence.
3626    #[test]
3627    fn a_longer_budget_keeps_the_default_interval() {
3628        let budget = WaitBudget::new(10, Duration::from_millis(100));
3629        assert_eq!(budget.next_spin_interval(DEFAULT), DEFAULT);
3630    }
3631
3632    /// An exhausted budget asks for no wait at all rather than one more
3633    /// interval — the caller is about to give up, and sleeping first would be
3634    /// pure overshoot.
3635    #[test]
3636    fn an_exhausted_budget_asks_for_a_zero_spin() {
3637        let budget = WaitBudget::new(1, Duration::ZERO);
3638        assert_eq!(budget.next_spin_interval(DEFAULT), Duration::ZERO);
3639    }
3640}