nros_rmw/traits.rs
1//! Transport abstraction traits.
2//!
3//! Defines the backend-agnostic interface that transport implementations
4//! (zenoh-pico, XRCE-DDS) must satisfy. The core trait hierarchy is:
5//!
6//! - [`Session`] — connection lifecycle and handle creation
7//! - [`Publisher`] / [`Subscription`] — pub/sub data transport
8//! - [`ServiceTrait`] / [`ClientTrait`] — request/reply
9//! - [`Rmw`] — top-level factory that creates sessions
10
11use crate::service_inbox::ServiceInboxSpec;
12use nros_core::{Deserialize, RosMessage, RosService, Serialize};
13
14/// Topic information for pub/sub
15#[derive(Debug, Clone)]
16pub struct TopicInfo<'a> {
17 /// Topic name (e.g., "/chatter")
18 pub name: &'a str,
19 /// ROS type name (e.g., "std_msgs::msg::dds_::String_")
20 pub type_name: &'a str,
21 /// Type hash for compatibility checking
22 pub type_hash: &'a str,
23 /// Domain ID (default: 0)
24 pub domain_id: u32,
25 /// Node name for liveliness token generation.
26 /// `None` means no node association — no liveliness token will be declared.
27 pub node_name: Option<&'a str>,
28 /// Node namespace for liveliness token generation (default: "/").
29 /// In ROS 2, "/" is the root namespace and the standard default.
30 pub namespace: &'a str,
31 /// Receive-buffer size hint, bytes. The executor sets
32 /// this from the subscription's `RX_BUF`; a backend may use it to route the
33 /// subscription to a size-class receive buffer (zenoh-pico: small vs large).
34 /// `0` = unset (backend picks its default). Ignored by backends that don't
35 /// size-class their receive storage.
36 pub rx_buffer_hint: usize,
37 /// The rate this subscription DECLARED it can
38 /// take (`arrival_curve.rate_hz`), in millihertz. `0` = undeclared. Carried to
39 /// the backend in `rmw_subscription_options_t::arrival_rate_mhz`; the XRCE
40 /// backend turns it into the agent's `max_bytes_per_second`, zenoh ignores
41 /// it (its enforcement point 1 is the router rule). Ignored by publishers.
42 pub arrival_rate_mhz: u32,
43 /// Publisher-side "express" hint: this topic's samples
44 /// bypass transport tx batching (zenoh: the wire EXPRESS flag; a batching
45 /// zenoh-pico session sends them immediately instead of queueing them for
46 /// the next flush). For control-tier / latency-sensitive topics. Ignored by
47 /// subscriptions and by backends without a batching concept.
48 pub tx_express: bool,
49}
50
51impl<'a> TopicInfo<'a> {
52 /// Create new topic info
53 pub const fn new(name: &'a str, type_name: &'a str, type_hash: &'a str) -> Self {
54 Self {
55 name,
56 type_name,
57 type_hash,
58 domain_id: 0,
59 node_name: None,
60 namespace: "/",
61 rx_buffer_hint: 0,
62 arrival_rate_mhz: 0,
63 tx_express: false,
64 }
65 }
66
67 /// Create topic info with custom domain ID
68 pub const fn with_domain(mut self, domain_id: u32) -> Self {
69 self.domain_id = domain_id;
70 self
71 }
72
73 /// Set the receive-buffer size hint (bytes) used by
74 /// size-classing backends (zenoh-pico) to route the subscription's receive
75 /// buffer to the small or large class.
76 pub const fn with_rx_buffer_hint(mut self, hint: usize) -> Self {
77 self.rx_buffer_hint = hint;
78 self
79 }
80
81 /// Set the declared arrival rate, millihertz
82 /// (`rate_hz x 1000`). `0` leaves it undeclared.
83 pub const fn with_arrival_rate_mhz(mut self, rate_mhz: u32) -> Self {
84 self.arrival_rate_mhz = rate_mhz;
85 self
86 }
87
88 /// Mark this publisher's samples express: they bypass
89 /// transport tx batching (sent immediately even when `ZPICO_TX_BATCH` is
90 /// on). For control-tier / latency-sensitive topics.
91 pub const fn with_tx_express(mut self, express: bool) -> Self {
92 self.tx_express = express;
93 self
94 }
95
96 /// Set the node name for liveliness token generation
97 pub const fn with_node_name(mut self, node_name: &'a str) -> Self {
98 self.node_name = Some(node_name);
99 self
100 }
101
102 /// Set the node namespace for liveliness token generation
103 pub const fn with_namespace(mut self, namespace: &'a str) -> Self {
104 self.namespace = namespace;
105 self
106 }
107}
108
109/// Service information for service client/server
110#[derive(Debug, Clone)]
111pub struct ServiceInfo<'a> {
112 /// Service name (e.g., "/add_two_ints")
113 pub name: &'a str,
114 /// ROS service type name (e.g., "example_interfaces::srv::dds_::AddTwoInts_")
115 pub type_name: &'a str,
116 /// Type hash for compatibility checking
117 pub type_hash: &'a str,
118 /// Domain ID (default: 0)
119 pub domain_id: u32,
120 /// Node name for liveliness token generation.
121 /// `None` means no node association — no liveliness token will be declared.
122 pub node_name: Option<&'a str>,
123 /// Node namespace for liveliness token generation (default: "/").
124 /// In ROS 2, "/" is the root namespace and the standard default.
125 pub namespace: &'a str,
126}
127
128/// The REP-2011 hash each of an action's five endpoints is keyed
129/// on. An Iron+ `rmw_zenoh_cpp` peer keys every endpoint on its OWN type: the
130/// `<Action>_SendGoal` / `<Action>_GetResult` services, the standard
131/// `action_msgs/srv/CancelGoal`, `<Action>_FeedbackMessage`, and the standard
132/// `action_msgs/msg/GoalStatusArray`. One hash for all five matched none of
133/// them, which is what every registration path carried until 1913.
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub struct ActionEndpointHashes<'a> {
136 pub send_goal: &'a str,
137 pub cancel_goal: &'a str,
138 pub get_result: &'a str,
139 pub feedback: &'a str,
140 pub status: &'a str,
141}
142
143impl<'a> ActionEndpointHashes<'a> {
144 /// Every endpoint on one value — Humble's `TypeHashNotSupported`, or a
145 /// caller that has nothing better (it will not match an Iron+ peer).
146 pub const fn uniform(hash: &'a str) -> Self {
147 Self {
148 send_goal: hash,
149 cancel_goal: hash,
150 get_result: hash,
151 feedback: hash,
152 status: hash,
153 }
154 }
155}
156
157impl ActionEndpointHashes<'static> {
158 /// The five hashes a typed action carries.
159 pub const fn of<A: nros_core::RosAction>() -> Self {
160 Self {
161 send_goal: A::SEND_GOAL_SERVICE_HASH,
162 cancel_goal: A::CANCEL_GOAL_SERVICE_HASH,
163 get_result: A::GET_RESULT_SERVICE_HASH,
164 feedback: <A::FeedbackMessage as nros_core::RosMessage>::TYPE_HASH,
165 status: A::STATUS_MESSAGE_HASH,
166 }
167 }
168}
169
170/// Action information for action client/server
171///
172/// Actions in ROS 2 use 5 communication channels:
173/// - `send_goal` service: `<action_name>/_action/send_goal`
174/// - `cancel_goal` service: `<action_name>/_action/cancel_goal`
175/// - `get_result` service: `<action_name>/_action/get_result`
176/// - `feedback` topic: `<action_name>/_action/feedback`
177/// - `status` topic: `<action_name>/_action/status`
178#[derive(Debug, Clone)]
179pub struct ActionInfo<'a> {
180 /// Action name (e.g., "/fibonacci")
181 pub name: &'a str,
182 /// ROS action type name (e.g., "example_interfaces::action::dds_::Fibonacci_")
183 pub type_name: &'a str,
184 /// Type hash for compatibility checking
185 pub type_hash: &'a str,
186 /// Domain ID (default: 0)
187 pub domain_id: u32,
188}
189
190impl<'a> ActionInfo<'a> {
191 /// Create new action info
192 pub const fn new(name: &'a str, type_name: &'a str, type_hash: &'a str) -> Self {
193 Self {
194 name,
195 type_name,
196 type_hash,
197 domain_id: 0,
198 }
199 }
200
201 /// Create action info with custom domain ID
202 pub const fn with_domain(mut self, domain_id: u32) -> Self {
203 self.domain_id = domain_id;
204 self
205 }
206
207 /// Generate the send_goal service name
208 /// Returns: `<action>/_action/send_goal`
209 pub fn send_goal_key<const N: usize>(&self) -> heapless::String<N> {
210 self.sub_name::<N>("send_goal")
211 }
212
213 /// Generate the cancel_goal service name
214 /// Returns: `<action>/_action/cancel_goal`
215 pub fn cancel_goal_key<const N: usize>(&self) -> heapless::String<N> {
216 self.sub_name::<N>("cancel_goal")
217 }
218
219 /// Generate the get_result service name
220 /// Returns: `<action>/_action/get_result`
221 pub fn get_result_key<const N: usize>(&self) -> heapless::String<N> {
222 self.sub_name::<N>("get_result")
223 }
224
225 /// Generate the feedback topic name
226 /// Returns: `<action>/_action/feedback`
227 pub fn feedback_key<const N: usize>(&self) -> heapless::String<N> {
228 self.sub_name::<N>("feedback")
229 }
230
231 /// Generate the status topic name
232 /// Returns: `<action>/_action/status`
233 pub fn status_key<const N: usize>(&self) -> heapless::String<N> {
234 self.sub_name::<N>("status")
235 }
236
237 /// Generate a sub-entity name for an action component
238 /// Returns: `<action>/_action/<suffix>` (e.g., `fibonacci/_action/send_goal`)
239 ///
240 /// The caller is responsible for constructing the full key expression
241 /// by wrapping this name in a `ServiceInfo` or `TopicInfo` with the
242 /// correct sub-service/sub-topic type name.
243 fn sub_name<const N: usize>(&self, suffix: &str) -> heapless::String<N> {
244 let mut name = heapless::String::new();
245 let action_stripped = self.name.trim_matches('/');
246 let _ = core::fmt::write(
247 &mut name,
248 format_args!("/{}/_action/{}", action_stripped, suffix),
249 );
250 name
251 }
252}
253
254impl<'a> ServiceInfo<'a> {
255 /// Create new service info
256 pub const fn new(name: &'a str, type_name: &'a str, type_hash: &'a str) -> Self {
257 Self {
258 name,
259 type_name,
260 type_hash,
261 domain_id: 0,
262 node_name: None,
263 namespace: "/",
264 }
265 }
266
267 /// Create service info with custom domain ID
268 pub const fn with_domain(mut self, domain_id: u32) -> Self {
269 self.domain_id = domain_id;
270 self
271 }
272
273 /// Set the node name for liveliness token generation
274 pub const fn with_node_name(mut self, node_name: &'a str) -> Self {
275 self.node_name = Some(node_name);
276 self
277 }
278
279 /// Set the node namespace for liveliness token generation
280 pub const fn with_namespace(mut self, namespace: &'a str) -> Self {
281 self.namespace = namespace;
282 self
283 }
284}
285
286/// Transport error types.
287///
288/// No longer `Copy` — the `Backend` / `BackendDynamic` variants carry a
289/// string diagnostic, which can't be `Copy`. Rust callers that used to
290/// copy a `TransportError` value repeatedly now need `.clone()` or
291/// `ref` in match arms. C/C++ callers are unaffected — both map
292/// `TransportError` to integer codes (`rcl_ret_t` / `ErrorCode`)
293/// before crossing the FFI boundary.
294#[derive(Debug, Clone, PartialEq, Eq)]
295pub enum TransportError {
296 /// Failed to connect to transport
297 ConnectionFailed,
298 /// Connection was closed
299 Disconnected,
300 /// Failed to create publisher
301 PublisherCreationFailed,
302 /// Failed to create subscriber
303 SubscriberCreationFailed,
304 /// Failed to create service server
305 ServiceServerCreationFailed,
306 /// Failed to create service client
307 ServiceClientCreationFailed,
308 /// Failed to publish message
309 PublishFailed,
310 /// Failed to send service request
311 ServiceRequestFailed,
312 /// Failed to send service reply
313 ServiceReplyFailed,
314 /// Serialization error
315 SerializationError,
316 /// Deserialization error
317 DeserializationError,
318 /// Buffer too small
319 BufferTooSmall,
320 /// A message larger than the buffer that holds it, or than the transport
321 /// can carry (an XRCE message states its length in 16 bits).
322 MessageTooLarge,
323 /// Timeout waiting for message
324 Timeout,
325 /// Invalid configuration
326 InvalidConfig,
327 /// Resource (slot, buffer, queue) momentarily unavailable. Retry.
328 /// Phase 99: returned by `try_loan` when arena slots are full and
329 /// by `try_borrow` when no message is ready (alternative to
330 /// `Ok(None)` for backends that prefer the error variant).
331 WouldBlock,
332 /// Requested allocation exceeds backend capacity. Phase 99:
333 /// `try_loan(len)` returns this when `len` > arena slot size.
334 TooLarge,
335 /// Failed to start background tasks
336 TaskStartFailed,
337 /// Failed to poll for incoming messages
338 PollFailed,
339 /// Failed to send keepalive
340 KeepaliveFailed,
341 /// Failed to send join message
342 JoinFailed,
343 /// Caller supplied a NULL pointer, an out-of-range value, or an
344 /// inconsistent argument combination. Phase 102.1.
345 InvalidArgument,
346 /// The backend does not implement this operation. Optional
347 /// callbacks return this; the runtime then falls back to a
348 /// default path. Phase 102.1.
349 Unsupported,
350 /// Memory allocation failed. Returned by backends on `std` /
351 /// `alloc`-equipped platforms when heap allocation fails.
352 /// Bare-metal backends generally do not produce this — they
353 /// preallocate at session-open time. Phase 102.1.
354 BadAlloc,
355 /// Publisher and subscriber QoS profiles do not match in a way
356 /// the backend cannot reconcile. Phase 102.1.
357 ///
358 /// **It NAMES the policy** — phase-417 G7. The payload is the single
359 /// [`QoSPolicyMask`] bit that was refused, so
360 /// `err.qos_policy_name()` (or `mask.policy_name()`) turns the refusal
361 /// into `"RELIABILITY"` without an allocator. Until this carried a
362 /// payload, [`QoSProfile::validate_against`] computed the offending bit
363 /// and threw it away, while `rmw_vtable.h`'s `supported_qos_policies`
364 /// block told the reader those creates fail "naming a policy". They did
365 /// not. Issue 1329's NONE-over-union choice rests on that sentence, so the
366 /// choice was right and its evidence was not yet true.
367 ///
368 /// [`QoSPolicyMask::NONE`] is the honest answer where the refusal crossed
369 /// a boundary that cannot carry one — a C backend returns
370 /// `NROS_RMW_RET_INCOMPATIBLE_QOS`, an `rmw_ret_t` with no room for a
371 /// mask — and `policy_name()` then answers `None` rather than naming a
372 /// policy nobody identified.
373 IncompatibleQos(QoSPolicyMask),
374 /// Topic, service, or action name failed validation. Phase 102.1.
375 TopicNameInvalid,
376 /// A request referenced a node that does not exist in this
377 /// session. Phase 102.1.
378 NodeNameNonExistent,
379 /// The backend does not support loaned messages on this entity,
380 /// or the loan slot is currently in use. Phase 102.1.
381 LoanNotSupported,
382 /// No data was available on a non-blocking receive. Distinct
383 /// from `Timeout`: fires immediately, not after a bounded wait.
384 /// Phase 102.1.
385 NoData,
386 /// Phase 115.A.2 — caller passed a versioned vtable struct
387 /// (e.g. `NrosTransportOps`) with an `abi_version` the runtime
388 /// doesn't know. Maps to `NROS_RMW_RET_INCOMPATIBLE_ABI` at
389 /// the C boundary.
390 IncompatibleAbi,
391 /// The peer is reachable and no longer holds this session: an XRCE
392 /// Agent that restarted answers a ping with "available, no session".
393 /// It does not clear itself; every later call on the session returns
394 /// it, and the remedy is to drop the executor and open a new one.
395 /// Distinct from [`Self::Timeout`] (no answer at all). Maps to
396 /// `NROS_RMW_RET_SESSION_LOST` at the C boundary.
397 SessionLost,
398 /// Backend-specific error with a `'static` diagnostic string.
399 ///
400 /// Useful for zenoh-pico / XRCE-DDS return codes that map to a
401 /// fixed set of known messages. `no_std`-compatible.
402 Backend(&'static str),
403 /// Backend-specific error with an owned diagnostic string.
404 ///
405 /// Available only with the `alloc` feature. Use this when the
406 /// diagnostic is formatted at runtime (e.g. from a C error code
407 /// plus a socket address).
408 #[cfg(feature = "alloc")]
409 BackendDynamic(alloc::string::String),
410}
411
412/// One line per variant, in the defining crate, so every consumer renders the
413/// same words (issue 0783: `NodeError` used to fall back to `{:?}` because
414/// this impl did not exist, and writing the prose there would have put a
415/// backend's wording in the wrong crate). `no_std`: no allocator, only
416/// `write_str` and the payloads the variants already carry.
417impl core::fmt::Display for TransportError {
418 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
419 let s = match self {
420 Self::ConnectionFailed => "failed to connect to the transport",
421 Self::Disconnected => "the transport connection was closed",
422 Self::PublisherCreationFailed => "failed to create a publisher",
423 Self::SubscriberCreationFailed => "failed to create a subscriber",
424 Self::ServiceServerCreationFailed => "failed to create a service server",
425 Self::ServiceClientCreationFailed => "failed to create a service client",
426 Self::PublishFailed => "failed to publish a message",
427 Self::ServiceRequestFailed => "failed to send a service request",
428 Self::ServiceReplyFailed => "failed to send a service reply",
429 Self::SerializationError => "serialization failed",
430 Self::DeserializationError => "deserialization failed",
431 Self::BufferTooSmall => "buffer too small",
432 Self::MessageTooLarge => "message is larger than the buffer or the transport can carry",
433 Self::Timeout => "timed out",
434 Self::InvalidConfig => "invalid configuration",
435 Self::WouldBlock => "resource momentarily unavailable; retry",
436 Self::TooLarge => "requested size exceeds the backend's capacity",
437 Self::TaskStartFailed => "failed to start a background task",
438 Self::PollFailed => "failed to poll for incoming messages",
439 Self::KeepaliveFailed => "failed to send a keepalive",
440 Self::JoinFailed => "failed to send a join message",
441 Self::InvalidArgument => "invalid argument",
442 Self::Unsupported => "operation not supported by this backend",
443 Self::BadAlloc => "memory allocation failed",
444 Self::IncompatibleQos(policy) => {
445 return match policy.policy_name() {
446 Some(name) => write!(f, "incompatible QoS: {name}"),
447 None => f.write_str("incompatible QoS"),
448 };
449 }
450 Self::TopicNameInvalid => "invalid topic, service or action name",
451 Self::NodeNameNonExistent => "no such node in this session",
452 Self::LoanNotSupported => "message loans unavailable on this entity",
453 Self::NoData => "no data available",
454 Self::IncompatibleAbi => "incompatible ABI version",
455 Self::SessionLost => "the session was lost: the peer no longer holds it; re-open",
456 Self::Backend(msg) => return write!(f, "backend error: {msg}"),
457 #[cfg(feature = "alloc")]
458 Self::BackendDynamic(msg) => return write!(f, "backend error: {msg}"),
459 };
460 f.write_str(s)
461 }
462}
463
464impl TransportError {
465 /// The QoS policy this error names, or `None`.
466 ///
467 /// The one accessor the three surfaces share. `Some` only
468 /// for [`Self::IncompatibleQos`] carrying exactly one
469 /// [`QoSPolicyMask`] bit; `None` for every other error, and for a
470 /// refusal that crossed a boundary with no room for the mask.
471 ///
472 /// The string is borrowed from [`QoSPolicyMask::NAMED`], so this costs no
473 /// allocator and no formatter and is available on a bare-metal target.
474 pub fn qos_policy_name(&self) -> Option<&'static str> {
475 match self {
476 Self::IncompatibleQos(policy) => policy.policy_name(),
477 _ => None,
478 }
479 }
480}
481
482/// QoS history policy
483#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
484pub enum QoSHistoryPolicy {
485 /// **The caller did not state a history policy** — the backend picks.
486 /// Upstream's `RMW_QOS_POLICY_HISTORY_SYSTEM_DEFAULT`; lowers to
487 /// `NROS_RMW_HISTORY_SYSTEM_DEFAULT` (0) across the C ABI.
488 ///
489 /// See [`QoSSystemDefaults`] for how a backend resolves it. Listed
490 /// first to match rclrs's enumerator order.
491 SystemDefault,
492 /// Keep last N messages (where N is defined in QoSProfile)
493 #[default]
494 KeepLast,
495 /// Keep all messages (up to resource limits)
496 KeepAll,
497 /// **The backend could not determine this policy.** Upstream's
498 /// `RMW_QOS_POLICY_HISTORY_UNKNOWN`; lowers to `NROS_RMW_HISTORY_UNKNOWN`
499 /// (3) across the C ABI.
500 ///
501 /// An ABSENCE, not a value: it is what a `*_get_actual_qos` read-back
502 /// writes for a policy it looked at and cannot report, and it is never a
503 /// request an application makes. Distinct from `SystemDefault`, which is
504 /// "nobody asked, so the middleware chooses" — see
505 /// [`QoSProfile::QOS_PROFILE_UNKNOWN`].
506 Unknown,
507}
508
509/// QoS reliability policy
510#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
511pub enum QoSReliabilityPolicy {
512 /// **The caller did not state a reliability policy** — the backend picks.
513 /// Upstream's `RMW_QOS_POLICY_RELIABILITY_SYSTEM_DEFAULT`; lowers to
514 /// `NROS_RMW_RELIABILITY_SYSTEM_DEFAULT` (0) across the C ABI.
515 ///
516 /// See [`QoSSystemDefaults`].
517 SystemDefault,
518 /// Reliable delivery (retransmit if needed).
519 ///
520 /// Default — matches ROS 2 `rmw_qos_profile_default` and the
521 /// `QoSProfile::default()` / `QOS_PROFILE_DEFAULT` aggregates.
522 #[default]
523 Reliable,
524 /// Best-effort delivery (no retransmits)
525 BestEffort,
526 /// **The backend could not determine this policy.** Upstream's
527 /// `RMW_QOS_POLICY_RELIABILITY_UNKNOWN`; lowers to `NROS_RMW_RELIABILITY_UNKNOWN`
528 /// (3) across the C ABI.
529 ///
530 /// An ABSENCE, not a value: it is what a `*_get_actual_qos` read-back
531 /// writes for a policy it looked at and cannot report, and it is never a
532 /// request an application makes. Distinct from `SystemDefault`, which is
533 /// "nobody asked, so the middleware chooses" — see
534 /// [`QoSProfile::QOS_PROFILE_UNKNOWN`].
535 Unknown,
536 /// **Resolve at creation against the discovered graph** (issue 1973).
537 /// Upstream's `RMW_QOS_POLICY_RELIABILITY_BEST_AVAILABLE` (Iron+); lowers
538 /// to `NROS_RMW_RELIABILITY_BEST_AVAILABLE` (4) across the C ABI.
539 ///
540 /// A REQUEST, never a grant: the runtime replaces it before the backend's
541 /// create slot runs ([`QoSProfile::resolve_best_available`]), so a
542 /// `*_get_actual_qos` read-back reports the concrete policy chosen.
543 BestAvailable,
544}
545
546/// QoS durability policy
547#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
548pub enum QoSDurabilityPolicy {
549 /// **The caller did not state a durability policy** — the backend picks.
550 /// Upstream's `RMW_QOS_POLICY_DURABILITY_SYSTEM_DEFAULT`; lowers to
551 /// `NROS_RMW_DURABILITY_SYSTEM_DEFAULT` (0) across the C ABI.
552 ///
553 /// See [`QoSSystemDefaults`].
554 SystemDefault,
555 /// Messages are discarded when subscriber disconnects
556 #[default]
557 Volatile,
558 /// Messages are persisted for late-joining subscribers
559 TransientLocal,
560 /// **The backend could not determine this policy.** Upstream's
561 /// `RMW_QOS_POLICY_DURABILITY_UNKNOWN`; lowers to `NROS_RMW_DURABILITY_UNKNOWN`
562 /// (3) across the C ABI.
563 ///
564 /// An ABSENCE, not a value: it is what a `*_get_actual_qos` read-back
565 /// writes for a policy it looked at and cannot report, and it is never a
566 /// request an application makes. Distinct from `SystemDefault`, which is
567 /// "nobody asked, so the middleware chooses" — see
568 /// [`QoSProfile::QOS_PROFILE_UNKNOWN`].
569 Unknown,
570 /// **Resolve at creation against the discovered graph** (issue 1973).
571 /// Upstream's `RMW_QOS_POLICY_DURABILITY_BEST_AVAILABLE` (Iron+); lowers
572 /// to `NROS_RMW_DURABILITY_BEST_AVAILABLE` (4) across the C ABI. A
573 /// request only — see [`QoSReliabilityPolicy::BestAvailable`].
574 BestAvailable,
575}
576
577/// QoS liveliness policy. Matches DDS `LIVELINESS` semantics.
578#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
579#[repr(u8)]
580pub enum QoSLivelinessPolicy {
581 /// Discriminant 0 — the same value the C ABI spells
582 /// `NROS_RMW_LIVELINESS_SYSTEM_DEFAULT` and upstream spells
583 /// `RMW_QOS_POLICY_LIVELINESS_SYSTEM_DEFAULT`.
584 ///
585 /// phase-428 W10 — the NAME diverges from both and the VALUE does not, so
586 /// this is what an upstream-mirroring profile carries. Read it as "the
587 /// middleware's choice", not as "liveliness is off": a backend that sees 0
588 /// omits the DDS call entirely and inherits the DDS default, which is
589 /// AUTOMATIC. `None` is our spelling, kept because it is the C ABI
590 /// discriminant three enums already agree on; renaming it is a separate
591 /// question from getting the value right, and only the value crosses.
592 ///
593 /// No liveliness assertion or tracking of our own.
594 #[default]
595 None = 0,
596 /// Backend's keepalive task asserts liveliness automatically.
597 Automatic = 1,
598 /// Application calls `assert_liveliness()` at the node level.
599 ///
600 /// Phase 376 W5/B2 — this was 3 and `ManualByTopic` was 2, the opposite of
601 /// upstream. The discriminant IS the C ABI value (`liveliness_kind` is
602 /// written with `as u8`), and the cyclonedds backend turns it into a real
603 /// DDS liveliness kind that a ROS peer matches on, so the swap was visible
604 /// on the wire and nowhere else.
605 ManualByNode = 2,
606 /// Application calls `assert_liveliness()` per topic explicitly.
607 ManualByTopic = 3,
608 /// **The backend could not determine this policy.** Discriminant 4, the
609 /// value the C ABI spells `NROS_RMW_LIVELINESS_UNKNOWN`.
610 ///
611 /// An ABSENCE, not a value — see [`QoSProfile::QOS_PROFILE_UNKNOWN`]. A
612 /// `*_get_actual_qos` read-back writes it for a policy it cannot report;
613 /// an application never requests it.
614 Unknown = 4,
615 /// **Resolve at creation against the discovered graph** (issue 1973).
616 /// Discriminant 5, upstream's `RMW_QOS_POLICY_LIVELINESS_BEST_AVAILABLE`
617 /// (Iron+) and the C ABI's `NROS_RMW_LIVELINESS_BEST_AVAILABLE`. A
618 /// request only — see [`QoSReliabilityPolicy::BestAvailable`]. Not manual:
619 /// it resolves to `Automatic` or `ManualByTopic` before anything asks.
620 BestAvailable = 5,
621}
622
623impl QoSLivelinessPolicy {
624 /// `true` for the two kinds under which the APPLICATION owns the
625 /// assertion — [`ManualByNode`](Self::ManualByNode) and
626 /// [`ManualByTopic`](Self::ManualByTopic).
627 ///
628 /// The ONE spelling of that test. It decides what
629 /// [`Publisher::assert_liveliness`] owes: under a manual kind the caller
630 /// asked for something a backend either performs or cannot, so a backend
631 /// that cannot must answer `Unsupported`; under `Automatic` / `None` there
632 /// is nothing to assert and `Ok(())` is the whole truth. `Unknown` is an
633 /// absence, never a request, so it is not manual.
634 #[must_use]
635 pub const fn is_manual(self) -> bool {
636 matches!(self, Self::ManualByNode | Self::ManualByTopic)
637 }
638}
639
640/// Which side of a topic a [`QoSOverride`] targets.
641/// Mirrors the `<role>` segment of a ROS 2
642/// `qos_overrides.<topic>.<role>.<policy>` launch parameter.
643#[derive(Debug, Clone, Copy, PartialEq, Eq)]
644pub enum QoSOverrideRole {
645 /// `qos_overrides.<topic>.publisher.*`
646 Publisher,
647 /// `qos_overrides.<topic>.subscription.*`
648 Subscription,
649}
650
651/// A single policy value a [`QoSOverride`] sets. A typed enum
652/// (not a string) so the codegen that bakes these from the plan catches an
653/// unknown policy / mistyped value at generation time rather than silently
654/// no-op-ing at runtime.
655#[derive(Debug, Clone, Copy, PartialEq, Eq)]
656pub enum QoSOverrideValue {
657 /// `.reliability` → Reliable / BestEffort.
658 Reliability(QoSReliabilityPolicy),
659 /// `.durability` → Volatile / TransientLocal.
660 Durability(QoSDurabilityPolicy),
661 /// `.history` → KeepLast / KeepAll.
662 History(QoSHistoryPolicy),
663 /// `.depth` → KeepLast depth.
664 Depth(u32),
665 /// Issue 0303 — `.deadline` → [`QoSProfile::deadline_ms`]. `0` /
666 /// [`DURATION_INFINITE_MS`] = no deadline check.
667 Deadline(u32),
668 /// Issue 0303 — `.lifespan` → [`QoSProfile::lifespan_ms`].
669 Lifespan(u32),
670 /// Issue 0303 — `.liveliness` → [`QoSProfile::liveliness_kind`].
671 Liveliness(QoSLivelinessPolicy),
672 /// Issue 0303 — `.liveliness_lease_duration` →
673 /// [`QoSProfile::liveliness_lease_ms`].
674 LivelinessLease(u32),
675}
676
677/// The wire form a baked QoS override travels in:
678/// `(topic, role, policy, value)`, all primitives.
679///
680/// One numbering for every language: `rclc_qos_override_t` (C),
681/// `nros_cpp_qos_override_t` (C++), `RuntimeCtx::qos_overrides` (the Rust
682/// entry bake) and `NodeRecord::qos_overrides` are all THIS tuple. Codes rather
683/// than [`QoSOverride`] because the table crosses the C ABI and rides
684/// `nros-platform`, which sits below this crate in the layer graph.
685///
686/// `topic` is `&'static` because every producer bakes a literal.
687pub type QoSOverrideCode = (&'static str, u8, u8, u32);
688
689/// `role` codes for [`QoSOverrideCode`].
690pub mod qos_override_role {
691 /// The override targets publishers on the topic.
692 pub const PUBLISHER: u8 = 0;
693 /// The override targets subscriptions on the topic.
694 pub const SUBSCRIPTION: u8 = 1;
695}
696
697/// `policy` codes for [`QoSOverrideCode`].
698///
699/// Append-only: these numbers are baked into shipped images and mirrored in
700/// two C headers. Never renumber — add.
701pub mod qos_override_policy {
702 /// value `0` = best_effort, `1` = reliable.
703 pub const RELIABILITY: u8 = 0;
704 /// value `0` = volatile, `1` = transient_local.
705 pub const DURABILITY: u8 = 1;
706 /// value `0` = keep_last, `1` = keep_all.
707 pub const HISTORY: u8 = 2;
708 /// value = the KeepLast depth.
709 pub const DEPTH: u8 = 3;
710 /// value = milliseconds.
711 pub const DEADLINE: u8 = 4;
712 /// value = milliseconds.
713 pub const LIFESPAN: u8 = 5;
714 /// value = [`super::QoSLivelinessPolicy`] discriminant.
715 pub const LIVELINESS: u8 = 6;
716 /// value = milliseconds.
717 pub const LIVELINESS_LEASE: u8 = 7;
718}
719
720/// Decode one [`QoSOverrideCode`] into a typed [`QoSOverride`].
721///
722/// `None` for an unrecognised role or policy code. THE one decoder: this
723/// match once existed four times (nros-node, nros-c, nros-cpp, and
724/// the executor's node record), each with a silent catch-all, so adding a
725/// policy meant finding all four — and the two FFI copies had already been
726/// forgotten once.
727pub fn decode_qos_override(code: &QoSOverrideCode) -> Option<QoSOverride> {
728 let (topic, role, policy, value) = *code;
729 decode_qos_override_parts(topic, role, policy, value)
730}
731
732/// [`decode_qos_override`] over loose parts — for the FFI paths, which read the
733/// fields out of a `#[repr(C)]` struct rather than a tuple.
734pub fn decode_qos_override_parts(
735 topic: &'static str,
736 role: u8,
737 policy: u8,
738 value: u32,
739) -> Option<QoSOverride> {
740 Some(QoSOverride {
741 topic,
742 role: decode_qos_override_role(role)?,
743 value: decode_qos_override_value(policy, value)?,
744 })
745}
746
747/// Decode a `role` code. `None` for an unrecognised one.
748pub fn decode_qos_override_role(role: u8) -> Option<QoSOverrideRole> {
749 match role {
750 qos_override_role::PUBLISHER => Some(QoSOverrideRole::Publisher),
751 qos_override_role::SUBSCRIPTION => Some(QoSOverrideRole::Subscription),
752 _ => None,
753 }
754}
755
756/// Decode a `(policy, value)` code pair. `None` for an unrecognised policy or
757/// an out-of-range enum value.
758///
759/// Split out from [`decode_qos_override`] for the FFI paths: they have already
760/// matched the topic against a `*const c_char`, so they need the VALUE without
761/// a `&'static str` to build a whole [`QoSOverride`] around.
762pub fn decode_qos_override_value(policy: u8, value: u32) -> Option<QoSOverrideValue> {
763 let out = match policy {
764 qos_override_policy::RELIABILITY => QoSOverrideValue::Reliability(if value == 0 {
765 QoSReliabilityPolicy::BestEffort
766 } else {
767 QoSReliabilityPolicy::Reliable
768 }),
769 qos_override_policy::DURABILITY => QoSOverrideValue::Durability(if value == 1 {
770 QoSDurabilityPolicy::TransientLocal
771 } else {
772 QoSDurabilityPolicy::Volatile
773 }),
774 qos_override_policy::HISTORY => QoSOverrideValue::History(if value == 1 {
775 QoSHistoryPolicy::KeepAll
776 } else {
777 QoSHistoryPolicy::KeepLast
778 }),
779 qos_override_policy::DEPTH => QoSOverrideValue::Depth(value),
780 qos_override_policy::DEADLINE => QoSOverrideValue::Deadline(value),
781 qos_override_policy::LIFESPAN => QoSOverrideValue::Lifespan(value),
782 // The encoder is `nros_orchestration_ir::qos_override`; both ends name
783 // the variant rather than its number, so W5/B2's renumbering moved them
784 // together instead of silently swapping two policies.
785 qos_override_policy::LIVELINESS => QoSOverrideValue::Liveliness(match value {
786 v if v == QoSLivelinessPolicy::None as u32 => QoSLivelinessPolicy::None,
787 v if v == QoSLivelinessPolicy::Automatic as u32 => QoSLivelinessPolicy::Automatic,
788 v if v == QoSLivelinessPolicy::ManualByNode as u32 => QoSLivelinessPolicy::ManualByNode,
789 v if v == QoSLivelinessPolicy::ManualByTopic as u32 => {
790 QoSLivelinessPolicy::ManualByTopic
791 }
792 _ => return None,
793 }),
794 qos_override_policy::LIVELINESS_LEASE => QoSOverrideValue::LivelinessLease(value),
795 _ => return None,
796 };
797 Some(out)
798}
799
800/// One per-topic QoS override, lowered from a ROS 2
801/// `qos_overrides.<topic>.<role>.<policy>` launch parameter by the planner and
802/// baked into a `&'static [QoSOverride]` table by the entry codegen. The node
803/// folds the matching entries into the entity's [`QoSProfile`] at
804/// `create_publisher` / `create_subscription` time (setup-time, single
805/// linear scan, no alloc), *before* the backend-compat `validate_against` —
806/// so an override the active RMW can't honour still errors loudly, never a
807/// silent downgrade.
808#[derive(Debug, Clone, Copy, PartialEq, Eq)]
809pub struct QoSOverride {
810 /// The resolved (remapped) topic name the override targets, e.g.
811 /// `"/chatter"`. Matched exactly against the entity's topic.
812 pub topic: &'static str,
813 /// Publisher or subscription side.
814 pub role: QoSOverrideRole,
815 /// The policy + value to set.
816 pub value: QoSOverrideValue,
817}
818
819/// Explicit "infinite" spelling for the u32
820/// millisecond QoS duration fields (`deadline_ms`, `lifespan_ms`,
821/// `liveliness_lease_ms`). Semantically identical to `0` (unset /
822/// no-check) at every check site; exists so a caller can distinguish
823/// "default" from "deliberately infinite". Mirrors the C header's
824/// `NROS_RMW_DURATION_INFINITE_MS`.
825pub const DURATION_INFINITE_MS: u32 = u32::MAX;
826
827/// The "best available" spelling for `deadline_ms` and
828/// `liveliness_lease_ms`: resolve at creation against the discovered graph.
829///
830/// Upstream spells it `RMW_QOS_DEADLINE_BEST_AVAILABLE` /
831/// `RMW_QOS_LIVELINESS_LEASE_DURATION_BEST_AVAILABLE`, both
832/// `RMW_DURATION_INFINITE - 1`; this is the same idea in our u32-millisecond
833/// fields: [`DURATION_INFINITE_MS`] minus one. A REQUEST only — the runtime
834/// replaces it before a backend sees the profile
835/// ([`QoSProfile::resolve_best_available`]). Mirrors the C header's
836/// `NROS_RMW_DURATION_BEST_AVAILABLE_MS`. Not meaningful for `lifespan_ms`,
837/// as upstream defines no best-available lifespan.
838pub const DURATION_BEST_AVAILABLE_MS: u32 = DURATION_INFINITE_MS - 1;
839
840/// Lower a [`core::time::Duration`] into a u32
841/// millisecond QoS field. Boundary contract:
842///
843/// - zero stays `0` (unset / no-check);
844/// - sub-millisecond remainders CEIL to the next ms (rounding down
845/// would silently turn a real deadline into "no deadline");
846/// - values at or past [`DURATION_INFINITE_MS`] ms are a create-time
847/// error, never a clamp (infinite is requested via the sentinel or
848/// `0`, not by a huge finite duration). The bound starts one below, at
849/// [`DURATION_BEST_AVAILABLE_MS`], so no finite duration can
850/// collide with that sentinel either.
851pub fn duration_to_qos_ms(d: core::time::Duration) -> Result<u32, TransportError> {
852 if d.is_zero() {
853 return Ok(0);
854 }
855 let mut ms = d.as_millis();
856 if !d.subsec_nanos().is_multiple_of(1_000_000) {
857 ms += 1;
858 }
859 if ms >= DURATION_BEST_AVAILABLE_MS as u128 {
860 return Err(TransportError::InvalidArgument);
861 }
862 Ok(ms as u32)
863}
864
865/// Full DDS-shaped QoS profile. Matches the field set of upstream
866/// `rmw_qos_profile_t`.
867///
868/// Backends advertise per-policy support via
869/// [`Session::supported_qos_policies`]; entities created with a
870/// profile the active backend can't honour return
871/// [`TransportError::IncompatibleQos`] synchronously at create time
872/// — no silent downgrade.
873///
874/// Zero-valued time-window fields ("off") mean infinite — the policy
875/// is effectively disabled for the entity.
876#[derive(Debug, Clone, Copy, PartialEq, Eq)]
877pub struct QoSProfile {
878 /// History policy
879 pub history: QoSHistoryPolicy,
880 /// Reliability policy
881 pub reliability: QoSReliabilityPolicy,
882 /// Durability policy
883 pub durability: QoSDurabilityPolicy,
884 /// Liveliness policy
885 pub liveliness_kind: QoSLivelinessPolicy,
886 /// History depth (only used if history is KeepLast)
887 pub depth: u32,
888 /// Subscription max-inter-arrival / publisher offered-rate, ms.
889 /// `0` = infinite (no deadline check).
890 pub deadline_ms: u32,
891 /// Sample expiry, ms. Subscribers filter samples older than this.
892 /// `0` = infinite (no expiry).
893 pub lifespan_ms: u32,
894 /// Liveliness lease, ms. `0` = infinite.
895 pub liveliness_lease_ms: u32,
896 /// If `true`, topic-name encoding skips the `/rt/` ROS prefix.
897 pub avoid_ros_namespace_conventions: bool,
898 /// Publisher-side "express" hint: this publisher's
899 /// samples bypass transport tx batching (zenoh: the wire EXPRESS flag; a
900 /// batching zenoh-pico session sends them immediately instead of queueing
901 /// them for the next flush). A transport hint, not a DDS policy — no RxO
902 /// matching, no backend-compat validation; ignored by subscriptions and by
903 /// backends without a batching concept.
904 pub tx_express: bool,
905}
906
907impl Default for QoSProfile {
908 fn default() -> Self {
909 Self::QOS_PROFILE_DEFAULT
910 }
911}
912
913/// The depth sentinel — "the caller did not state a queue depth".
914///
915/// Upstream spells it `RMW_QOS_POLICY_DEPTH_SYSTEM_DEFAULT = 0`
916/// (`rmw/include/rmw/types.h`); depth is `size_t` there and `uint16_t` in our
917/// C ABI, but 0 is 0 in both. The value was already free on every backend:
918/// Cyclone REJECTS `KEEP_LAST` with depth 0 outright
919/// (`validate_history_qospolicy`, `ddsi_plist.c:2603-2604`), the XRCE client
920/// already reads it as "unstated" and drops the field from the wire
921/// (`create_entities_bin.c:148`), and both `read_entity_qos`
922/// (`nros-rmw-cyclonedds/src/qos.cpp:138`) and `report_qos_downgrade`
923/// (`nros-rmw-cffi/src/lib.rs:1903`) already treat a 0 read-back as "no
924/// answer" rather than as an answer.
925pub const DEPTH_SYSTEM_DEFAULT: u32 = 0;
926
927/// What ONE backend resolves the `SYSTEM_DEFAULT` sentinel to.
928///
929/// `rmw_qos_profile_system_default` is an absence, and the RMW
930/// fills it — which means the answer is per backend and there is no constant
931/// this crate could bake. Each backend declares its own `QoSSystemDefaults`
932/// and applies it with [`QoSProfile::resolve_system_default`] at its create
933/// entry, **before anything is derived from the QoS**.
934///
935/// That ordering is load-bearing on the zenoh path: the profile is serialised
936/// into the liveliness-token keyexpr that a ROS `rmw_zenoh_cpp` peer parses
937/// out of the graph (`nros-rmw-zenoh/src/keyexpr.rs`). Upstream resolves in
938/// best_available_qos before the entity and its token exist, so its tokens
939/// never carry a sentinel; ours must not either, or we advertise `0:0:0,0` to
940/// peers as though it were a policy.
941///
942/// The values a backend picks should mirror **the corresponding upstream
943/// RMW**, not the raw middleware default — interop with a ROS peer is the
944/// requirement, and the two differ. Leaving `dds_qset_reliability` unset gives
945/// Cyclone's own reader default of BEST_EFFORT (`ddsi_plist.c:3470`), where
946/// `rmw_cyclonedds_cpp` deliberately picks RELIABLE.
947#[derive(Debug, Clone, Copy, PartialEq, Eq)]
948pub struct QoSSystemDefaults {
949 /// Concrete reliability. Must not itself be `SystemDefault`.
950 pub reliability: QoSReliabilityPolicy,
951 /// Concrete durability. Must not itself be `SystemDefault`.
952 pub durability: QoSDurabilityPolicy,
953 /// Concrete history. Must not itself be `SystemDefault`.
954 pub history: QoSHistoryPolicy,
955 /// Concrete queue depth. `0` means the backend genuinely has no answer and
956 /// defers further down the stack — the XRCE case, where the client encodes
957 /// exactly that (`optional_history_depth = false`) and the Agent's DDS
958 /// layer resolves it.
959 pub depth: u32,
960}
961
962impl QoSProfile {
963 /// Fold the plan's `qos_overrides` matching `topic` + `role`
964 /// into this profile, returning the overridden profile. Setup-time only
965 /// (called from `create_publisher`/`create_subscription`): a single linear
966 /// scan over the baked `&'static` table, no alloc, RT-safe. Later entries
967 /// win on a duplicate `(topic, role, policy)` (last-write), matching the
968 /// planner's sorted, de-conflicted emit. Non-matching entries are ignored,
969 /// so passing the whole node table to every entity is cheap + correct.
970 #[must_use]
971 pub fn apply_overrides(
972 mut self,
973 topic: &str,
974 role: QoSOverrideRole,
975 overrides: &[QoSOverride],
976 ) -> Self {
977 for ovr in overrides {
978 if ovr.topic == topic && ovr.role == role {
979 self.apply_override_value(ovr.value);
980 }
981 }
982 self
983 }
984
985 /// Apply ONE decoded override value. The single place a
986 /// policy maps to the field it sets; `apply_overrides` and the FFI folds
987 /// both go through it, so a new policy cannot reach some paths only.
988 pub fn apply_override_value(&mut self, value: QoSOverrideValue) {
989 match value {
990 QoSOverrideValue::Reliability(r) => self.reliability = r,
991 QoSOverrideValue::Durability(d) => self.durability = d,
992 QoSOverrideValue::History(h) => self.history = h,
993 QoSOverrideValue::Depth(d) => self.depth = d,
994 QoSOverrideValue::Deadline(ms) => self.deadline_ms = ms,
995 QoSOverrideValue::Lifespan(ms) => self.lifespan_ms = ms,
996 QoSOverrideValue::Liveliness(k) => self.liveliness_kind = k,
997 QoSOverrideValue::LivelinessLease(ms) => self.liveliness_lease_ms = ms,
998 }
999 }
1000
1001 /// Fold baked [`QoSOverrideCode`]s for one `(topic, role)`.
1002 /// Unrecognised codes are skipped; the producers reject them at BAKE time
1003 /// (`nros_orchestration_ir::qos_override`), so a code reaching here that
1004 /// this build does not know is an older image running newer data, not a
1005 /// user error to diagnose at runtime.
1006 pub fn apply_override_codes(
1007 self,
1008 topic: &str,
1009 role: QoSOverrideRole,
1010 codes: &[QoSOverrideCode],
1011 ) -> Self {
1012 let mut qos = self;
1013 for code in codes {
1014 if let Some(ovr) = decode_qos_override(code) {
1015 qos = qos.apply_overrides(topic, role, core::slice::from_ref(&ovr));
1016 }
1017 }
1018 qos
1019 }
1020}
1021
1022/// The ONE authoring site for every named [`QoSProfile`] preset — phase-428 W10.
1023///
1024/// Upstream's profiles were hand-transcribed here and in three other places
1025/// (`nros::qos`, `rclcpp/qos.hpp`, `rmw_entity.h`) with nothing binding them, and
1026/// they drifted exactly as every other hand-mirror in this tree has: issue 0793
1027/// caught `PARAMETERS` claiming TRANSIENT_LOCAL, fixed that one profile, and
1028/// left `PARAMETER_EVENTS` sitting at `KeepAll, depth 0` under a comment saying
1029/// *"matches rmw_qos_profile_parameter_events"* — where upstream is
1030/// `KEEP_LAST, 1000`. A RELIABLE writer with KEEP_ALL **blocks** when history
1031/// fills where KEEP_LAST(1000) overwrites, so that was an inverting difference,
1032/// not a weaker one, and the test beneath it asserted the wrong value.
1033///
1034/// Three properties are what make this a table rather than ten `const`s:
1035///
1036/// 1. **Every field is stated.** The `Self::build(...)` helper this replaces
1037/// supplied `liveliness_kind`, the three duration windows and both flags
1038/// silently, so five of ten fields per profile were invisible at the
1039/// authoring site and no reader could compare a row against upstream.
1040/// 2. **Every row declares its PROVENANCE** — the upstream symbol it mirrors,
1041/// or `nros: <why>` for a preset we invented. A profile cannot be added
1042/// without answering "whose constant is this?".
1043/// 3. **The field ORDER is upstream's** (`rmw_qos_profile_t` in
1044/// `rmw/include/rmw/types.h`: history, depth, reliability, durability,
1045/// deadline, lifespan, liveliness, lease, avoid-ns), so a row reads against
1046/// the header positionally.
1047///
1048/// Expansion is exactly the `pub const` items that were here before — no table
1049/// is materialised, nothing is `static`, and the crate stays `no_std` and
1050/// zero-cost on every target it reaches.
1051///
1052/// `scripts/check-qos-profile-ssot.py` parses this invocation and asserts every
1053/// upstream-mirroring row field-by-field against
1054/// `docs/reference/rmw-qos-profiles.txt`, which is itself extracted from a real
1055/// ROS install. The other three sites bind to this block.
1056macro_rules! qos_profiles {
1057 ($(
1058 $(#[$meta:meta])*
1059 $name:ident : $provenance:literal = {
1060 history: $history:ident,
1061 depth: $depth:expr,
1062 reliability: $reliability:ident,
1063 durability: $durability:ident,
1064 deadline_ms: $deadline_ms:expr,
1065 lifespan_ms: $lifespan_ms:expr,
1066 liveliness_kind: $liveliness_kind:ident,
1067 liveliness_lease_ms: $liveliness_lease_ms:expr,
1068 avoid_ros_namespace_conventions: $avoid:expr,
1069 tx_express: $tx_express:expr,
1070 };
1071 )+) => {
1072 impl QoSProfile {
1073 $(
1074 $(#[$meta])*
1075 ///
1076 #[doc = concat!("Provenance: `", $provenance, "`.")]
1077 pub const $name: Self = Self {
1078 history: QoSHistoryPolicy::$history,
1079 depth: $depth,
1080 reliability: QoSReliabilityPolicy::$reliability,
1081 durability: QoSDurabilityPolicy::$durability,
1082 deadline_ms: $deadline_ms,
1083 lifespan_ms: $lifespan_ms,
1084 liveliness_kind: QoSLivelinessPolicy::$liveliness_kind,
1085 liveliness_lease_ms: $liveliness_lease_ms,
1086 avoid_ros_namespace_conventions: $avoid,
1087 tx_express: $tx_express,
1088 };
1089 )+
1090 }
1091 };
1092}
1093
1094// nros-qos-table: BEGIN
1095// The SSoT. Everything between this marker and `nros-qos-table: END` is parsed
1096// by `scripts/check-qos-profile-ssot.py`; do not add a `QoSProfile` preset
1097// anywhere else in this crate — the gate refuses one.
1098qos_profiles! {
1099 /// Best-effort QoS (for real-time).
1100 BEST_EFFORT: "nros: best-effort keep-last(1); a shorthand, not an upstream constant" = {
1101 history: KeepLast,
1102 depth: 1,
1103 reliability: BestEffort,
1104 durability: Volatile,
1105 deadline_ms: 0,
1106 lifespan_ms: 0,
1107 liveliness_kind: Automatic,
1108 liveliness_lease_ms: 0,
1109 avoid_ros_namespace_conventions: false,
1110 tx_express: false,
1111 };
1112
1113 /// Reliable QoS.
1114 RELIABLE: "nros: reliable keep-last(10); a shorthand, not an upstream constant" = {
1115 history: KeepLast,
1116 depth: 10,
1117 reliability: Reliable,
1118 durability: Volatile,
1119 deadline_ms: 0,
1120 lifespan_ms: 0,
1121 liveliness_kind: Automatic,
1122 liveliness_lease_ms: 0,
1123 avoid_ros_namespace_conventions: false,
1124 tx_express: false,
1125 };
1126
1127 /// `rmw_qos_profile_system_default` — **an absence, not a profile.**
1128 ///
1129 /// issue 0829. Every field is the sentinel: upstream's constant names no
1130 /// concrete policy at all, and the two reference RMWs fill the absence with
1131 /// different numbers — `rmw_cyclonedds_cpp`'s `create_readwrite_qos` folds
1132 /// `RMW_QOS_POLICY_DEPTH_SYSTEM_DEFAULT` to `KEEP_LAST(1)`, while
1133 /// `rmw_zenoh_cpp`'s `QoS::QoS()` fills it from
1134 /// `RMW_ZENOH_DEFAULT_HISTORY_DEPTH`, which is 42, over a comment stating
1135 /// the contract outright: *"If the depth field in the qos profile is set to
1136 /// 0, the RMW implementation has the liberty to assign a default depth."*
1137 ///
1138 /// So no baked number can be right. This carried a concrete
1139 /// `Reliable / Volatile / KeepLast(1)` until 2026-09-03, and
1140 /// `nros::qos::SYSTEM_DEFAULT` carried a concrete depth **10**, which is how
1141 /// one name shipped two queue depths. Both are gone; the backend resolves
1142 /// this at its create entry via [`QoSProfile::resolve_system_default`].
1143 ///
1144 /// `liveliness_kind` is [`QoSLivelinessPolicy::None`], which IS the
1145 /// sentinel on that policy — it lowers to
1146 /// `NROS_RMW_LIVELINESS_SYSTEM_DEFAULT` (0), the two having collapsed onto
1147 /// one value in phase-376 W5/B2. This is therefore the ONE preset that
1148 /// matches upstream on all nine fields.
1149 QOS_PROFILE_SYSTEM_DEFAULT: "rmw_qos_profile_system_default" = {
1150 history: SystemDefault,
1151 depth: DEPTH_SYSTEM_DEFAULT,
1152 reliability: SystemDefault,
1153 durability: SystemDefault,
1154 deadline_ms: 0,
1155 lifespan_ms: 0,
1156 liveliness_kind: None,
1157 liveliness_lease_ms: 0,
1158 avoid_ros_namespace_conventions: false,
1159 tx_express: false,
1160 };
1161
1162 /// `rmw_qos_profile_unknown` — **"the backend could not determine this"**,
1163 /// and distinct from [`QOS_PROFILE_SYSTEM_DEFAULT`](Self::QOS_PROFILE_SYSTEM_DEFAULT).
1164 ///
1165 /// `SYSTEM_DEFAULT` means "nobody asked, so the middleware chooses";
1166 /// this means "we looked and cannot say", which is what a
1167 /// `*_get_actual_qos` read-back owes its caller for a policy it cannot
1168 /// report. It is the starting value the read-back helper pre-loads, so a
1169 /// field the backend does not overwrite reads as an ABSENCE rather than as
1170 /// a confident grant of whatever was asked.
1171 ///
1172 /// **Never a request.** No `create_*` accepts it — a backend's
1173 /// `qos_admit` refuses `UNKNOWN` on every policy, because an application
1174 /// asking for "I cannot say" is a bug, not a preference.
1175 ///
1176 /// The C ABI twin is `NROS_RMW_QOS_PROFILE_UNKNOWN` (`rmw_entity.h`),
1177 /// which existed from phase-428 W10 with no Rust counterpart: three of the
1178 /// four policy enums had no `Unknown` variant to build it from. They do
1179 /// now.
1180 QOS_PROFILE_UNKNOWN: "rmw_qos_profile_unknown" = {
1181 history: Unknown,
1182 depth: 0,
1183 reliability: Unknown,
1184 durability: Unknown,
1185 deadline_ms: 0,
1186 lifespan_ms: 0,
1187 liveliness_kind: Unknown,
1188 liveliness_lease_ms: 0,
1189 avoid_ros_namespace_conventions: false,
1190 tx_express: false,
1191 };
1192
1193 /// Default QoS profile — reliable, volatile, keep-last(10).
1194 QOS_PROFILE_DEFAULT: "rmw_qos_profile_default" = {
1195 history: KeepLast,
1196 depth: 10,
1197 reliability: Reliable,
1198 durability: Volatile,
1199 deadline_ms: 0,
1200 lifespan_ms: 0,
1201 liveliness_kind: None,
1202 liveliness_lease_ms: 0,
1203 avoid_ros_namespace_conventions: false,
1204 tx_express: false,
1205 };
1206
1207 /// Sensor data QoS profile — best-effort, volatile, keep-last(5).
1208 QOS_PROFILE_SENSOR_DATA: "rmw_qos_profile_sensor_data" = {
1209 history: KeepLast,
1210 depth: 5,
1211 reliability: BestEffort,
1212 durability: Volatile,
1213 deadline_ms: 0,
1214 lifespan_ms: 0,
1215 liveliness_kind: None,
1216 liveliness_lease_ms: 0,
1217 avoid_ros_namespace_conventions: false,
1218 tx_express: false,
1219 };
1220
1221 /// Services default QoS profile — reliable, volatile, keep-last(10).
1222 QOS_PROFILE_SERVICES_DEFAULT: "rmw_qos_profile_services_default" = {
1223 history: KeepLast,
1224 depth: 10,
1225 reliability: Reliable,
1226 durability: Volatile,
1227 deadline_ms: 0,
1228 lifespan_ms: 0,
1229 liveliness_kind: None,
1230 liveliness_lease_ms: 0,
1231 avoid_ros_namespace_conventions: false,
1232 tx_express: false,
1233 };
1234
1235 /// Parameters QoS profile — KEEP_LAST(1000), RELIABLE, **VOLATILE**.
1236 ///
1237 /// issue 0793 — this said `TransientLocal` until 2026-08-25, disagreeing
1238 /// both with upstream (`/opt/ros/<distro>/include/rmw/rmw/qos_profiles.h`)
1239 /// and with our own second copy of the same profile, `nros::qos::PARAMETERS`,
1240 /// which was already correct. Two copies of one profile that disagree is the
1241 /// defect; the wrong one being the one named after the upstream constant is
1242 /// what made it hard to see.
1243 QOS_PROFILE_PARAMETERS: "rmw_qos_profile_parameters" = {
1244 history: KeepLast,
1245 depth: 1000,
1246 reliability: Reliable,
1247 durability: Volatile,
1248 deadline_ms: 0,
1249 lifespan_ms: 0,
1250 liveliness_kind: None,
1251 liveliness_lease_ms: 0,
1252 avoid_ros_namespace_conventions: false,
1253 tx_express: false,
1254 };
1255
1256 /// Parameter events QoS profile — KEEP_LAST(1000), RELIABLE, VOLATILE.
1257 ///
1258 /// phase-428 W10 — this was `KeepAll, depth 0` until 2026-09-05, under a
1259 /// comment claiming it matched `rmw_qos_profile_parameter_events`. Upstream
1260 /// is `KEEP_LAST, 1000` (identical to `rmw_qos_profile_parameters`), and
1261 /// `rclcpp::ParameterEventsQoS` — which our own C++ surface mirrors — was
1262 /// already correct, so the two languages shipped different profiles under
1263 /// one name.
1264 ///
1265 /// The difference INVERTS behaviour rather than weakening it: both DDS
1266 /// backends map KEEP_ALL faithfully, and a RELIABLE writer with KEEP_ALL
1267 /// **blocks** once history fills, where KEEP_LAST(1000) overwrites. A
1268 /// parameter server whose events nobody is reading would stall the node
1269 /// instead of dropping the oldest event.
1270 QOS_PROFILE_PARAMETER_EVENTS: "rmw_qos_profile_parameter_events" = {
1271 history: KeepLast,
1272 depth: 1000,
1273 reliability: Reliable,
1274 durability: Volatile,
1275 deadline_ms: 0,
1276 lifespan_ms: 0,
1277 liveliness_kind: None,
1278 liveliness_lease_ms: 0,
1279 avoid_ros_namespace_conventions: false,
1280 tx_express: false,
1281 };
1282
1283 /// Action status default QoS profile — reliable, transient-local,
1284 /// keep-last(1). From `rcl_action`, not `rmw`.
1285 QOS_PROFILE_ACTION_STATUS_DEFAULT: "rcl_action_qos_profile_status_default" = {
1286 history: KeepLast,
1287 depth: 1,
1288 reliability: Reliable,
1289 durability: TransientLocal,
1290 deadline_ms: 0,
1291 lifespan_ms: 0,
1292 liveliness_kind: None,
1293 liveliness_lease_ms: 0,
1294 avoid_ros_namespace_conventions: false,
1295 tx_express: false,
1296 };
1297
1298 /// `rmw_qos_profile_best_available` (Iron+) — KEEP_LAST(10) with every
1299 /// policy that CAN be best-available set so (issue 1973).
1300 ///
1301 /// Reliability, durability, liveliness, deadline and lease are resolved at
1302 /// creation against the endpoints already discovered on the topic, by
1303 /// [`QoSProfile::resolve_best_available`]; history, depth and lifespan
1304 /// are stated, exactly as upstream states them. A request only: no
1305 /// backend is handed this profile unresolved.
1306 QOS_PROFILE_BEST_AVAILABLE: "rmw_qos_profile_best_available" = {
1307 history: KeepLast,
1308 depth: 10,
1309 reliability: BestAvailable,
1310 durability: BestAvailable,
1311 deadline_ms: DURATION_BEST_AVAILABLE_MS,
1312 lifespan_ms: 0,
1313 liveliness_kind: BestAvailable,
1314 liveliness_lease_ms: DURATION_BEST_AVAILABLE_MS,
1315 avoid_ros_namespace_conventions: false,
1316 tx_express: false,
1317 };
1318
1319 /// Clock QoS profile — sensor-data shaped with depth 1.
1320 // phase-428 W4 — the provenance string said "/clock has no rmw constant",
1321 // which is true and was read as "no upstream at all". `rclrs::QOS_PROFILE_CLOCK`
1322 // EXISTS under this exact name (`rclrs/src/qos.rs:598`, it is rclcpp's
1323 // `ClockQoS`), and Rust follows rclrs. So this row mirrors something after
1324 // all, and the gate — which only compares upstream-MIRRORING rows — could
1325 // not see it.
1326 //
1327 // That is why it kept `Automatic` when W10 moved the other five to the
1328 // sentinel: F2's fourth instance, sitting inside the fix for F2's third.
1329 // The one row the instrument does not reach is the one that kept the
1330 // defect.
1331 // The provenance renders as this const's rustdoc, so its id lives here:
1332 // phase-428 W4.
1333 QOS_PROFILE_CLOCK: "nros: mirrors rclrs::QOS_PROFILE_CLOCK; no rmw constant exists, so the gate cannot bind it" = {
1334 history: KeepLast,
1335 depth: 1,
1336 reliability: BestEffort,
1337 durability: Volatile,
1338 deadline_ms: 0,
1339 lifespan_ms: 0,
1340 liveliness_kind: None,
1341 liveliness_lease_ms: 0,
1342 avoid_ros_namespace_conventions: false,
1343 tx_express: false,
1344 };
1345
1346 /// PX4 companion QoS profile (Phase 233 / RFC-0039 Track B). Matches the
1347 /// QoS PX4's `uxrce_dds_client` uses on `/fmu/out/*` and `/fmu/in/*` —
1348 /// `BEST_EFFORT` + `VOLATILE` + `KEEP_LAST(1)`. A nano-ros node talking to
1349 /// the same `MicroXRCEAgent` must use this (a reliable or
1350 /// `TRANSIENT_LOCAL` reader will not match PX4's volatile best-effort
1351 /// writers). Verified against real PX4 SITL (`nros-px4-sitl-test`):
1352 /// `TRANSIENT_LOCAL` durability silently fails to match `/fmu/out/*`.
1353 /// Adjust depth via `.keep_last(n)` for higher-rate streams.
1354 ///
1355 /// Liveliness is the `None` sentinel, not `Automatic` (issue 2002): this
1356 /// profile exists for the XRCE backend, and `uxrQoS_t` carries no
1357 /// liveliness, so XRCE refuses a stated one (issue 1329). Stating it made
1358 /// every companion fail to advertise its first topic.
1359 QOS_PROFILE_PX4: "nros: PX4 uxrce_dds_client companion QoS; no upstream constant" = {
1360 history: KeepLast,
1361 depth: 1,
1362 reliability: BestEffort,
1363 durability: Volatile,
1364 deadline_ms: 0,
1365 lifespan_ms: 0,
1366 liveliness_kind: None,
1367 liveliness_lease_ms: 0,
1368 avoid_ros_namespace_conventions: false,
1369 tx_express: false,
1370 };
1371}
1372// nros-qos-table: END
1373
1374// Where we knowingly differ from upstream, and where we knowingly have no
1375// counterpart. phase-428 W10.
1376//
1377// These lines are DATA, not prose: `check-qos-profile-ssot.py` requires a
1378// deviation to name the field, BOTH values and a tracking reference, and it
1379// re-measures `ours=` and `upstream=` against the table and the extracted
1380// record on every run. So a deviation cannot survive either side changing —
1381// which is the failure mode the phase-428 sweep found in `ARG_DEVIATIONS`,
1382// where 42 values were reason strings against a membership test and nothing
1383// checked that the reason was still true.
1384//
1385// The liveliness deviation is CLOSED (issue 1329, 2026-09-12) and is
1386// recorded here because the reason it survived two phases is worth keeping.
1387//
1388// Every application-facing preset used to state AUTOMATIC where upstream
1389// states the SYSTEM_DEFAULT sentinel. W10 moved this table and
1390// `rmw_entity.h` onto the sentinel and could not move the remaining three —
1391// `nros-c`'s `NROS_QOS_*`, ~~`rclc_c_qos_default()`~~ and `nros::QoS`'s
1392// constructor — because `liveliness_kind` crosses the C ABI as its
1393// discriminant, so flipping one surface alone makes a C caller's default and
1394// a Rust caller's default differ in a field cyclonedds puts on the wire. All
1395// three moved together instead.
1396//
1397// MEASURED consequences of the move, 2026-09-05 and re-read 2026-09-12:
1398// - cyclonedds: wire-identical. `nros_rmw_cyclonedds::make_dds_qos`
1399// (`qos.cpp`; the name here read ~~`nros_rmw_cyclonedds_qos_apply`~~ until
1400// phase-428 W9 went looking for it — no such symbol has ever existed)
1401// calls `dds_qset_liveliness` only when the kind is
1402// NOT the sentinel, and Cyclone's own reader/writer default IS
1403// `DDS_LIVELINESS_AUTOMATIC` — so both spellings put AUTOMATIC on the
1404// wire.
1405// - zenoh: invisible. `QosKeyExpr::to_qos_string` (`keyexpr.rs`)
1406// elides fields equal to upstream's defaults (issue 1495), and both
1407// SYSTEM_DEFAULT and AUTOMATIC leave the liveliness kind position
1408// EMPTY (only a manual kind is stated, since phase-556 W6), so the two
1409// spellings read the same in a peer's graph parse.
1410// - xrce: invisible. `uxrQoS_t` has no liveliness field at all.
1411// The one live consequence was `required_policies()`, which set
1412// `LIVELINESS_AUTOMATIC` for presets upstream leaves unset — an over-demand,
1413// so it could only turn an acceptance into a rejection. It flipped no
1414// verdict while every `supported_qos_policies()` in the tree advertised the
1415// bit, and issue 1329 is exactly the change that stops them doing so: XRCE
1416// honours no liveliness and now says so, which would have refused every C
1417// application on that backend over a policy nobody asked for. The fix is to
1418// stop asking, not to let a backend claim what it does not implement.
1419//
1420// The `BEST_EFFORT` / `RELIABLE` shorthands still state AUTOMATIC. They
1421// mirror no upstream constant — their doc strings say so — so they are
1422// choices rather than deviations, and a caller picking one is asking for
1423// automatic liveliness on purpose. `QOS_PROFILE_PX4` stated it too, and was
1424// the counterexample to that reading (issue 2002): it is the profile FOR the
1425// XRCE backend, which honours no liveliness, so nobody picking it could have
1426// meant it. It carries the sentinel now.
1427//
1428// `rmw_qos_profile_unknown` HAS a counterpart now — `QOS_PROFILE_UNKNOWN` in the
1429// table below, added by this phase. The note that used to stand here declared it
1430// absent because three of our four policy enums had no `Unknown` variant to
1431// build it from; they have one now, which is what made the read-back able to
1432// say "I cannot report this policy" instead of echoing the request back as a
1433// grant.
1434
1435/// phase-515 R8 helper -- a QoS duration as the record's whole milliseconds:
1436/// saturating at `u32::MAX`, and a non-zero duration under 1 ms rounded UP to
1437/// 1, because `0` is "infinite" in the record.
1438const fn qos_duration_ms(d: core::time::Duration) -> u32 {
1439 let ms = d.as_millis();
1440 if ms == 0 && !d.is_zero() {
1441 1
1442 } else if ms > u32::MAX as u128 {
1443 u32::MAX
1444 } else {
1445 ms as u32
1446 }
1447}
1448
1449impl QoSProfile {
1450 /// Create new QoS settings with defaults (matches `QOS_PROFILE_DEFAULT`:
1451 /// Reliable, Volatile, KeepLast(10)).
1452 pub const fn new() -> Self {
1453 Self::QOS_PROFILE_DEFAULT
1454 }
1455
1456 // --- Static constructor methods (matching rclrs API) ---
1457
1458 /// Get the default QoS profile for ordinary topics
1459 pub const fn topics_default() -> Self {
1460 Self::QOS_PROFILE_DEFAULT
1461 }
1462
1463 /// The PX4 companion QoS profile ([`QOS_PROFILE_PX4`](Self::QOS_PROFILE_PX4))
1464 /// — use for `/fmu/out/*` subscriptions and `/fmu/in/*` publications against
1465 /// a `MicroXRCEAgent`.
1466 pub const fn px4() -> Self {
1467 Self::QOS_PROFILE_PX4
1468 }
1469
1470 /// Get the default QoS profile for sensor data topics
1471 pub const fn sensor_data_default() -> Self {
1472 Self::QOS_PROFILE_SENSOR_DATA
1473 }
1474
1475 /// Get the default QoS profile for services
1476 pub const fn services_default() -> Self {
1477 Self::QOS_PROFILE_SERVICES_DEFAULT
1478 }
1479
1480 /// The parameter services' profile — rclrs's
1481 /// `QoSProfile::parameter_services_default()`.
1482 ///
1483 /// `rmw_qos_profile_parameters`: KEEP_LAST(**1000**), RELIABLE, VOLATILE.
1484 /// The depth is the point — 1000 against the generic services profile's
1485 /// 10 — and it is what a tool setting many parameters at once depends on.
1486 ///
1487 /// **RENAMED, and the old spelling is GONE.** It was
1488 /// ~~`parameters_default`~~, an ours-only word for a name rclrs has; the
1489 /// ledger carried the pair as `rust:QoSProfile::parameters_default`
1490 /// (`rename` — ours is the one that should change) and
1491 /// `rust:QoSProfile::parameter_services_default` (`gap`). Adding the
1492 /// upstream name beside ours would have been a FOURTH spelling of one
1493 /// preset (`QOS_PROFILE_PARAMETERS` and `QosPresets::PARAMETERS` are the
1494 /// other two) and would have left the `rename` row open for good. No
1495 /// deprecated forwarder: a stale call should fail on the IDENTIFIER rather
1496 /// than on a deprecation, which is the rename rule and what the
1497 /// sibling `parameter_events_default` — already at rclrs's spelling —
1498 /// makes the pair consistent with.
1499 pub const fn parameter_services_default() -> Self {
1500 Self::QOS_PROFILE_PARAMETERS
1501 }
1502
1503 /// Get the default QoS profile for parameter events
1504 pub const fn parameter_events_default() -> Self {
1505 Self::QOS_PROFILE_PARAMETER_EVENTS
1506 }
1507
1508 /// Get the system default QoS profile
1509 pub const fn system_default() -> Self {
1510 Self::QOS_PROFILE_SYSTEM_DEFAULT
1511 }
1512
1513 /// Get the default QoS profile for action status topics
1514 pub const fn action_status_default() -> Self {
1515 Self::QOS_PROFILE_ACTION_STATUS_DEFAULT
1516 }
1517
1518 /// Get the default QoS profile for clock topics
1519 pub const fn clock_default() -> Self {
1520 Self::QOS_PROFILE_CLOCK
1521 }
1522
1523 /// rclrs's `QoSProfile::best_available()` — `rmw_qos_profile_best_available`
1524 /// ([`QOS_PROFILE_BEST_AVAILABLE`](Self::QOS_PROFILE_BEST_AVAILABLE)).
1525 ///
1526 /// Reliability, durability, liveliness, deadline and liveliness lease are
1527 /// chosen when the entity is created, from the endpoints the backend has
1528 /// already discovered on the topic ([`QoSProfile::resolve_best_available`]
1529 /// states the rule); read the outcome back with the entity's
1530 /// `actual_qos()`. Upstream's caveat holds: the choice is not revisited
1531 /// when endpoints appear later.
1532 pub const fn best_available() -> Self {
1533 Self::QOS_PROFILE_BEST_AVAILABLE
1534 }
1535
1536 // --- Builder methods ---
1537
1538 /// Set history to keep last N messages
1539 pub const fn keep_last(mut self, depth: u32) -> Self {
1540 self.history = QoSHistoryPolicy::KeepLast;
1541 self.depth = depth;
1542 self
1543 }
1544
1545 /// Set history to keep all messages
1546 pub const fn keep_all(mut self) -> Self {
1547 self.history = QoSHistoryPolicy::KeepAll;
1548 self
1549 }
1550
1551 /// Set reliability to reliable
1552 pub const fn reliable(mut self) -> Self {
1553 self.reliability = QoSReliabilityPolicy::Reliable;
1554 self
1555 }
1556
1557 /// Set reliability to best-effort
1558 pub const fn best_effort(mut self) -> Self {
1559 self.reliability = QoSReliabilityPolicy::BestEffort;
1560 self
1561 }
1562
1563 /// Set durability to volatile
1564 pub const fn volatile(mut self) -> Self {
1565 self.durability = QoSDurabilityPolicy::Volatile;
1566 self
1567 }
1568
1569 /// Set durability to transient local
1570 pub const fn transient_local(mut self) -> Self {
1571 self.durability = QoSDurabilityPolicy::TransientLocal;
1572 self
1573 }
1574
1575 /// Set reliability policy explicitly
1576 pub const fn reliability(mut self, policy: QoSReliabilityPolicy) -> Self {
1577 self.reliability = policy;
1578 self
1579 }
1580
1581 /// Set durability policy explicitly
1582 pub const fn durability(mut self, policy: QoSDurabilityPolicy) -> Self {
1583 self.durability = policy;
1584 self
1585 }
1586
1587 /// Set history policy explicitly
1588 pub const fn history(mut self, policy: QoSHistoryPolicy) -> Self {
1589 self.history = policy;
1590 self
1591 }
1592
1593 /// Set history depth explicitly
1594 pub const fn depth(mut self, depth: u32) -> Self {
1595 self.depth = depth;
1596 self
1597 }
1598
1599 /// rclrs's `QoSProfile::deadline_duration(deadline)`.
1600 ///
1601 /// ADOPT-BOUNDED: stored as whole MILLISECONDS in [`Self::deadline_ms`]
1602 /// (the repr(C) QoS record the C and C++ surfaces share), saturating at
1603 /// `u32::MAX`; a non-zero duration under 1 ms rounds UP to 1 ms, because
1604 /// `0` here means "infinite" and must not be reached by accident.
1605 pub const fn deadline_duration(mut self, deadline: core::time::Duration) -> Self {
1606 self.deadline_ms = qos_duration_ms(deadline);
1607 self
1608 }
1609
1610 /// rclrs's `QoSProfile::lifespan_duration(lifespan)`,
1611 /// stored in [`Self::lifespan_ms`] as `deadline_duration` stores its value.
1612 pub const fn lifespan_duration(mut self, lifespan: core::time::Duration) -> Self {
1613 self.lifespan_ms = qos_duration_ms(lifespan);
1614 self
1615 }
1616
1617 /// rclrs's `QoSProfile::liveliness_lease_duration(lease_duration)`,
1618 /// stored in [`Self::liveliness_lease_ms`] as `deadline_duration` stores
1619 /// its value.
1620 pub const fn liveliness_lease_duration(mut self, lease_duration: core::time::Duration) -> Self {
1621 self.liveliness_lease_ms = qos_duration_ms(lease_duration);
1622 self
1623 }
1624
1625 /// Mark this publisher's samples "express": they
1626 /// bypass transport tx batching (sent immediately even when the batching
1627 /// knob is on). A transport hint for control-sched-task / latency-sensitive
1628 /// topics; ignored on subscriptions and by backends without batching.
1629 pub const fn tx_express(mut self, express: bool) -> Self {
1630 self.tx_express = express;
1631 self
1632 }
1633
1634 /// Get history depth (for backwards compatibility)
1635 pub const fn history_depth(&self) -> u8 {
1636 if self.depth > 255 {
1637 255
1638 } else {
1639 self.depth as u8
1640 }
1641 }
1642}
1643
1644/// Transport session configuration
1645#[derive(Debug, Clone)]
1646pub struct TransportConfig<'a> {
1647 /// Peer locator (e.g., "tcp/192.168.1.1:7447" or "serial//dev/ttyUSB0#baudrate=115200")
1648 pub locator: Option<&'a str>,
1649 /// Session mode: client, peer, or router
1650 pub mode: SessionMode,
1651 /// Additional transport properties (key-value pairs)
1652 ///
1653 /// These are passed through to the underlying transport backend.
1654 /// For zenoh-pico, recognized keys include:
1655 /// - `"multicast_scouting"` - Enable/disable multicast scouting (`"true"` or `"false"`)
1656 /// - `"scouting_timeout_ms"` - Scouting timeout in milliseconds
1657 /// - `"multicast_locator"` - Multicast group address
1658 /// - `"listen"` - Listen endpoint (e.g., `"tcp/0.0.0.0:0"`)
1659 /// - `"add_timestamp"` - Add timestamps to messages (`"true"` or `"false"`)
1660 pub properties: &'a [(&'a str, &'a str)],
1661 /// Node name for ROS 2 graph discovery liveliness token.
1662 ///
1663 /// Empty string (`""`) means no node-liveliness token is declared.
1664 /// Non-empty causes the session to declare a
1665 /// `@ros2_lv/<domain>/<zid>/0/0/NN/%/<ns>/<node>` token on open.
1666 pub node_name: &'a str,
1667 /// Node namespace for the liveliness token (e.g., `""` or `"/ns1"`).
1668 ///
1669 /// Empty string is treated as root `"/"` by the keyexpr builder.
1670 pub namespace: &'a str,
1671 /// ROS 2 domain ID used in the liveliness token key expression.
1672 pub domain_id: u32,
1673}
1674
1675impl Default for TransportConfig<'_> {
1676 fn default() -> Self {
1677 Self {
1678 locator: None,
1679 mode: SessionMode::Client,
1680 properties: &[],
1681 node_name: "",
1682 namespace: "",
1683 domain_id: 0,
1684 }
1685 }
1686}
1687
1688/// Middleware-agnostic session configuration.
1689///
1690/// `RmwConfig` provides a uniform interface that any RMW backend can
1691/// interpret. Backends map the universal fields to their own connection
1692/// parameters and interpret `properties` for anything backend-specific.
1693///
1694/// # Examples
1695///
1696/// ```
1697/// use nros_rmw::{RmwConfig, SessionMode};
1698///
1699/// let config = RmwConfig {
1700/// locator: "tcp/192.168.1.1:7447",
1701/// mode: SessionMode::Client,
1702/// domain_id: 0,
1703/// node_name: "talker",
1704/// namespace: "",
1705/// properties: &[],
1706/// };
1707/// ```
1708#[derive(Debug, Clone, Copy)]
1709pub struct RmwConfig<'a> {
1710 /// Middleware-specific connection string.
1711 ///
1712 /// - zenoh: `"tcp/192.168.1.1:7447"` or `"udp/224.0.0.224:7447"`
1713 /// - XRCE-DDS: `"udp/192.168.1.1:2019"`
1714 pub locator: &'a str,
1715 /// Session mode (zenoh: client/peer; XRCE-DDS: always client)
1716 pub mode: SessionMode,
1717 /// ROS 2 domain ID (maps to DDS domain or zenoh key prefix)
1718 pub domain_id: u32,
1719 /// Node name (e.g., `"talker"`)
1720 pub node_name: &'a str,
1721 /// Node namespace (e.g., `""` or `"/ns1"`)
1722 pub namespace: &'a str,
1723 /// Backend-specific key/value properties.
1724 ///
1725 /// Uniform escape hatch for backend-specific tuning that doesn't fit
1726 /// the universal fields above. Each backend documents the keys it
1727 /// understands; unknown keys are ignored. Passing `&[]` is always
1728 /// valid.
1729 ///
1730 /// Examples:
1731 /// - zenoh: `"tls.root_ca"`, `"scouting.multicast.enabled"`
1732 /// - XRCE-DDS: `"agent_port"`, `"client_key"`
1733 pub properties: &'a [(&'a str, &'a str)],
1734}
1735
1736impl Default for RmwConfig<'_> {
1737 fn default() -> Self {
1738 Self {
1739 locator: "tcp/127.0.0.1:7447",
1740 mode: SessionMode::Client,
1741 domain_id: 0,
1742 node_name: "node",
1743 namespace: "",
1744 properties: &[],
1745 }
1746 }
1747}
1748
1749/// Locator transport protocol
1750#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1751pub enum LocatorProtocol {
1752 /// TCP transport (e.g., "tcp/127.0.0.1:7447")
1753 Tcp,
1754 /// UDP transport (e.g., "udp/192.168.1.50:2019" — common for XRCE-DDS)
1755 Udp,
1756 /// Serial/UART transport (e.g., "serial//dev/ttyUSB0#baudrate=115200")
1757 Serial,
1758 /// Unknown protocol
1759 Unknown,
1760}
1761
1762/// Parse the protocol from a locator string
1763pub fn locator_protocol(locator: &str) -> LocatorProtocol {
1764 if locator.starts_with("tcp/") {
1765 LocatorProtocol::Tcp
1766 } else if locator.starts_with("udp/") {
1767 LocatorProtocol::Udp
1768 } else if locator.starts_with("serial/") {
1769 LocatorProtocol::Serial
1770 } else {
1771 LocatorProtocol::Unknown
1772 }
1773}
1774
1775/// Validate a locator string format.
1776///
1777/// Returns `Ok(())` if the locator is well-formed, or an error message describing
1778/// the problem. This provides early feedback before zenoh-pico or XRCE-DDS rejects
1779/// a bad locator.
1780///
1781/// Supported formats:
1782/// - TCP: `tcp/<host>:<port>` (e.g., `tcp/127.0.0.1:7447`)
1783/// - UDP: `udp/<host>:<port>` (e.g., `udp/192.168.1.50:2019`)
1784/// - Serial: `serial/<device>#baudrate=<rate>` (e.g., `serial//dev/ttyUSB0#baudrate=115200`)
1785pub fn validate_locator(locator: &str) -> Result<(), &'static str> {
1786 match locator_protocol(locator) {
1787 LocatorProtocol::Tcp => {
1788 let rest = &locator[4..]; // skip "tcp/"
1789 if !rest.contains(':') {
1790 return Err("TCP locator must contain host:port (e.g., tcp/127.0.0.1:7447)");
1791 }
1792 Ok(())
1793 }
1794 LocatorProtocol::Udp => {
1795 let rest = &locator[4..]; // skip "udp/"
1796 if !rest.contains(':') {
1797 return Err("UDP locator must contain host:port (e.g., udp/192.168.1.50:2019)");
1798 }
1799 Ok(())
1800 }
1801 LocatorProtocol::Serial => {
1802 let rest = &locator[7..]; // skip "serial/"
1803 if rest.is_empty() {
1804 return Err(
1805 "serial locator must specify device (e.g., serial//dev/ttyUSB0#baudrate=115200)",
1806 );
1807 }
1808 if !rest.contains("#baudrate=") {
1809 return Err(
1810 "serial locator must include #baudrate=RATE (e.g., serial//dev/ttyUSB0#baudrate=115200)",
1811 );
1812 }
1813 // Validate baudrate is numeric
1814 if let Some(baud_str) = rest.split("#baudrate=").nth(1) {
1815 let baud_str = baud_str.split('#').next().unwrap_or(baud_str);
1816 if baud_str.parse::<u32>().is_err() {
1817 return Err("serial baudrate must be a number");
1818 }
1819 }
1820 Ok(())
1821 }
1822 LocatorProtocol::Unknown => {
1823 Err("unknown locator protocol (expected tcp/, udp/, or serial/)")
1824 }
1825 }
1826}
1827
1828/// How a session reports that data arrived.
1829///
1830/// The executor's park ends for exactly two reasons: the sched task's next deadline,
1831/// or readiness. This is the readiness half, in one of two forms, and the
1832/// executor picks its wait from it rather than blocking inside the transport.
1833#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1834pub enum ReadinessSource {
1835 /// Neither form: the executor can only learn of an arrival by blocking in
1836 /// [`Session::drive_io`]. RFC-0113 D5 refuses this once phase-521 W6
1837 /// lands.
1838 None,
1839 /// The backend calls the wake callback [`Session::set_wake_callback`]
1840 /// installed when data arrives (a transport thread, a listener, an RX
1841 /// interrupt).
1842 Notify,
1843 /// An OS handle that becomes readable when data arrives — a file
1844 /// descriptor on POSIX and NuttX. The executor multiplexes it with its own
1845 /// wake object and drives the session non-blockingly after the park. It
1846 /// must stay valid until the session closes.
1847 Waitable(i32),
1848}
1849
1850/// Session mode
1851#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1852pub enum SessionMode {
1853 /// Connect as client to a router
1854 #[default]
1855 Client,
1856 /// Connect as peer for peer-to-peer communication
1857 Peer,
1858}
1859
1860/// Transport session trait — the per-process anchor an RMW backend
1861/// gives to the executor.
1862///
1863/// # Threading
1864///
1865/// `&mut self` on every method means the executor serialises all
1866/// session calls onto a single thread. A backend may rely on this
1867/// — no internal locking is required for `create_*` / `close` /
1868/// `drive_io`. **Publisher / subscriber / service handles created
1869/// from the session, however, are typically used from worker
1870/// threads** and must carry their own synchronisation (see the
1871/// [`Publisher`] / [`Subscription`] trait docs).
1872///
1873/// # Calling pattern
1874///
1875/// 1. Open the session (backend-specific factory; not on this trait).
1876/// 2. `create_*` for every entity at startup. Creating entities mid-
1877/// flight after `drive_io` has run is allowed but not common.
1878/// 3. The executor calls `drive_io` periodically. Worker threads
1879/// publish / receive in parallel.
1880/// 4. `close` once at shutdown. Entities must be dropped first.
1881pub trait Session {
1882 /// RFC-0088 — the serialization format this backend speaks, as ROS 2's
1883 /// `rmw_get_serialization_format()` reports it ("One middleware can only
1884 /// have one encoding").
1885 ///
1886 /// Defaulted to CDR because every backend in tree except uORB speaks it,
1887 /// and a backend that speaks something else says so by overriding these
1888 /// two. They travel together: `SERIALIZATION_FORMAT` is the identity that
1889 /// crosses images (bridge config, tooling, the vtable slot) and
1890 /// `SERIALIZATION_FORMAT_ID` is the image-local discriminant used for the
1891 /// one-byte comparison a bridge makes at construction.
1892 const SERIALIZATION_FORMAT: &'static str =
1893 nros_serdes::format::SerializationFormatId::Cdr.as_str();
1894
1895 /// Image-local discriminant for [`Self::SERIALIZATION_FORMAT`]. Never
1896 /// persisted, never compared across images — see `nros_serdes::format`.
1897 const SERIALIZATION_FORMAT_ID: nros_serdes::format::SerializationFormatId =
1898 nros_serdes::format::SerializationFormatId::Cdr;
1899
1900 /// RFC-0088 — this session's serialization format, as ROS 2's
1901 /// `rmw_get_serialization_format()` reports it.
1902 ///
1903 /// **Per session, not per process.** ROS 2's function takes no handle
1904 /// because one process links one middleware; an `Executor::open_multi`
1905 /// image links two, so the answer must be asked of the session.
1906 ///
1907 /// **`None` means the backend has NOT SAID**, and that is not a synonym
1908 /// for `"cdr"`. The seam's contract is stated once, for the
1909 /// `get_serialization_format` slot in
1910 /// `packages/core/nros-rmw-abi/include/nros/rmw_vtable.h`: "NULL slot: the
1911 /// runtime answers NULL — it does NOT guess `cdr`." This method is the
1912 /// Rust face of that slot and carries the same absence. A `&'static str`
1913 /// could not: the only value it had to hand back was the literal `"cdr"`,
1914 /// indistinguishable at every call site from a backend that declared CDR.
1915 ///
1916 /// The default answers `Some(Self::SERIALIZATION_FORMAT)`, which is right
1917 /// for any backend whose format is a compile-time fact — it HAS said, in
1918 /// the const. A session that dispatches to a backend chosen at run time —
1919 /// the C-ABI adapter, whose vtable carries the answer — overrides this to
1920 /// ask the backend, and hands on the `None` a NULL slot gives it.
1921 fn serialization_format(&self) -> Option<&'static str> {
1922 Some(Self::SERIALIZATION_FORMAT)
1923 }
1924
1925 /// The backend's name, as ROS 2's `rmw_get_implementation_identifier()`
1926 /// reports it — the nano-ros name (`"zenoh"`, `"cyclonedds"`, `"xrce"`,
1927 /// `"uorb"`), never a stock `rmw_*_cpp` name, for the reason the
1928 /// `get_implementation_identifier` slot in
1929 /// `packages/core/nros-rmw-abi/include/nros/rmw_vtable.h` states.
1930 ///
1931 /// `None` = the backend has not said. A backend whose name is a
1932 /// compile-time fact states it here; it must be the same string it stamps
1933 /// into a gid, since gids are comparable only under one identifier.
1934 const IMPLEMENTATION_IDENTIFIER: Option<&'static str> = None;
1935
1936 /// This session's backend name — the per-session form of
1937 /// `rmw_get_implementation_identifier()`, for the same reason
1938 /// [`serialization_format`](Self::serialization_format) is per session: an
1939 /// `Executor::open_multi` image links two backends.
1940 ///
1941 /// The default answers [`Self::IMPLEMENTATION_IDENTIFIER`]. A session that
1942 /// dispatches to a backend chosen at run time (the C-ABI adapter) overrides
1943 /// this to ask the backend's vtable.
1944 fn implementation_identifier(&self) -> Option<&'static str> {
1945 Self::IMPLEMENTATION_IDENTIFIER
1946 }
1947
1948 /// Error type for this session
1949 type Error;
1950 /// Publisher handle type
1951 type PublisherHandle;
1952 /// Subscription handle type
1953 type SubscriptionHandle;
1954 /// Service server handle type
1955 type ServiceHandle;
1956 /// Service client handle type
1957 type ClientHandle;
1958
1959 /// Create a publisher bound to this session.
1960 ///
1961 /// May allocate transport resources (zenoh declarations, DDS
1962 /// writers). Returns a handle that outlives the call but not the
1963 /// session — drop the handle before `close()`.
1964 fn create_publisher(
1965 &mut self,
1966 topic: &TopicInfo,
1967 qos: QoSProfile,
1968 ) -> Result<Self::PublisherHandle, Self::Error>;
1969
1970 /// Create a subscriber bound to this session.
1971 ///
1972 /// Subscribers may start receiving immediately after creation if
1973 /// the transport supports late-joining publishers. Late messages
1974 /// are buffered up to the QoS depth.
1975 fn create_subscription(
1976 &mut self,
1977 topic: &TopicInfo,
1978 qos: QoSProfile,
1979 ) -> Result<Self::SubscriptionHandle, Self::Error>;
1980
1981 /// Create a service server bound to this session. Replies are
1982 /// matched to requests by the sequence number returned from
1983 /// [`ServiceTrait::take_request`].
1984 ///
1985 /// `qos` is applied to both the request and reply endpoints (a
1986 /// service is two DDS topics; rmw uses one profile for both). The
1987 /// default is [`QoSProfile::services_default`]
1988 /// (RELIABLE+VOLATILE+KEEP_LAST(10)).
1989 ///
1990 /// The server receives through the backend's own inbox. A builtin family
1991 /// that sizes its own ring calls [`create_service_with_inbox`] instead.
1992 ///
1993 /// [`create_service_with_inbox`]: Session::create_service_with_inbox
1994 fn create_service(
1995 &mut self,
1996 service: &ServiceInfo,
1997 qos: QoSProfile,
1998 ) -> Result<Self::ServiceHandle, Self::Error>;
1999
2000 /// phase-461 W2 -- does this backend accept a caller-owned request ring
2001 /// ([`ServiceInboxSpec::Caller`])?
2002 ///
2003 /// A `const`, so the family that would bring one picks at COMPILE time
2004 /// and a `Caller` spec never degrades silently into the backend's own
2005 /// geometry (RFC-0052: a knob that is dropped is a knob that lies). The
2006 /// caller reads this and passes [`ServiceInboxSpec::Backend`] where it is
2007 /// `false`, which is how a family refuses at BUILD time rather than
2008 /// discovering at boot that its ring went nowhere -- `nros-node`'s
2009 /// `PARAM_INBOX` is the worked example.
2010 ///
2011 /// `false` is the right default and every backend in tree states it
2012 /// explicitly with its own reason, because "this backend has no caller
2013 /// ring" and "nobody thought about it" are different facts.
2014 ///
2015 /// [`create_service_with_inbox`]: Session::create_service_with_inbox
2016 const SUPPORTS_CALLER_INBOX: bool = false;
2017
2018 /// Create a service server that receives through `inbox`.
2019 ///
2020 /// phase-461 W2 / issue 1352 -- the ROS parameter services are six
2021 /// queryables per node and the REP-2002 lifecycle services five, and on a
2022 /// board they are most of the image's queryables. Their requests are
2023 /// bounded by the contract's declared parameters and their clients are
2024 /// sequential, so they want one small slot where a user service wants four
2025 /// large ones. The family that knows that bound brings the ring; the
2026 /// backend keeps the per-queryable header.
2027 ///
2028 /// The default body is [`Self::SUPPORTS_CALLER_INBOX`] `= false` spelled
2029 /// out: it serves [`ServiceInboxSpec::Backend`] and nothing else. It can
2030 /// only be reached with a `Caller` spec by a caller that ignored the
2031 /// const, so the `debug_assert` names that -- the REFUSAL itself is the
2032 /// caller's, at compile time, because a runtime error here would be a
2033 /// boot failure where a build failure was available (`nros-node`'s
2034 /// `PARAM_INBOX` is the worked example).
2035 ///
2036 /// A backend that overrides this must also state the const `true`.
2037 fn create_service_with_inbox(
2038 &mut self,
2039 service: &ServiceInfo,
2040 qos: QoSProfile,
2041 inbox: ServiceInboxSpec,
2042 ) -> Result<Self::ServiceHandle, Self::Error> {
2043 debug_assert!(
2044 inbox.caller().is_none(),
2045 "a caller-owned service inbox reached a backend whose \
2046 SUPPORTS_CALLER_INBOX is false; the caller must read the const"
2047 );
2048 self.create_service(service, qos)
2049 }
2050
2051 /// Create a service client bound to this session.
2052 ///
2053 /// `qos` is applied to both the request and reply endpoints (a
2054 /// service is two DDS topics; rmw uses one profile for both). The
2055 /// default is [`QoSProfile::services_default`]
2056 /// (RELIABLE+VOLATILE+KEEP_LAST(10)).
2057 fn create_client(
2058 &mut self,
2059 service: &ServiceInfo,
2060 qos: QoSProfile,
2061 ) -> Result<Self::ClientHandle, Self::Error>;
2062
2063 /// Close the session, releasing transport resources. All entity
2064 /// handles created from this session must already be dropped.
2065 fn close(&mut self) -> Result<(), Self::Error>;
2066
2067 /// Drive transport I/O (poll network, dispatch callbacks).
2068 ///
2069 /// Both zenoh-pico and XRCE-DDS are pull-based: they require the
2070 /// application to periodically call this method to read from the
2071 /// network socket and dispatch incoming messages to subscriber
2072 /// buffers.
2073 ///
2074 /// `timeout_ms` is the maximum time to wait for data (0 = non-blocking;
2075 /// negative values mean "block indefinitely" — see Phase 84.D7 for the
2076 /// planned migration to `core::time::Duration`).
2077 ///
2078 /// **Required**. There is no default body — both shipped backends
2079 /// (zenoh and XRCE) must drive I/O, and a silent no-op default was a
2080 /// trap for third-party implementers. If your backend genuinely
2081 /// receives data via OS callbacks (push-based) and has nothing to do
2082 /// here, return `Ok(())` explicitly.
2083 fn drive_io(&mut self, timeout_ms: i32) -> Result<(), Self::Error>;
2084
2085 /// Phase 109 — report which QoS policies the active backend
2086 /// honours. The runtime validates requested QoS against this mask
2087 /// at entity-create time and returns
2088 /// [`TransportError::IncompatibleQos`] if the requested profile
2089 /// includes a policy the backend can't enforce. **No silent
2090 /// downgrade.**
2091 ///
2092 /// # The mask is DERIVED, not authored — phase-428 W9
2093 ///
2094 /// Every bit an implementation sets must be backed by a
2095 /// `nros-qos-honours:` claim sited on the code that honours the policy,
2096 /// and `check-qos-mask-derivation` re-measures those claims on every
2097 /// push. Deleting the code deletes the claim, which is the property this
2098 /// item exists to buy: before W9 this was a hand-written constant, so a
2099 /// backend could advertise a policy it had never implemented and nothing
2100 /// noticed. Three did — `LIVELINESS_MANUAL_BY_NODE` was advertised by
2101 /// every backend in the tree and implemented by none.
2102 ///
2103 /// "Honours" means the backend reads the field and either APPLIES it or
2104 /// REFUSES a value it cannot serve. Passing the field on to someone else
2105 /// (a discovery keyexpr, a lowered C struct) is not honouring it, and the
2106 /// gate does not count it: see `nros-qos-discovery-only`.
2107 ///
2108 /// # The default is EMPTY, deliberately
2109 ///
2110 /// It returned [`QoSPolicyMask::CORE`] until phase-428 W9 — four policies
2111 /// granted to any implementation that had written no code at all, which
2112 /// is precisely the lie above with the trait as its author. An
2113 /// implementation now states what it honours or is told it honours
2114 /// nothing; the failure is loud (`IncompatibleQos` at create) rather than
2115 /// a silent downgrade at runtime, which is the direction this trait has
2116 /// chosen everywhere else.
2117 ///
2118 /// # A C backend answers through the vtable — issue 1329
2119 ///
2120 /// `CffiSession` is the one implementation that cannot answer from
2121 /// compile-time knowledge: which backend registered is a run-time fact. It
2122 /// returned the UNION of what any C backend it routes to honours, which
2123 /// over-claims for each of them; it now asks the backend through
2124 /// `nros_rmw_vtable_t::supported_qos_policies` and returns what it said. A
2125 /// NULL slot there carries the same meaning as this default — the backend
2126 /// has not said, so it honours nothing — deliberately, so the ABI and the
2127 /// trait give one answer to one question.
2128 fn supported_qos_policies(&self) -> QoSPolicyMask {
2129 QoSPolicyMask::NONE
2130 }
2131
2132 /// Phase 110.0 — backend's next internal-event deadline in
2133 /// milliseconds from now (lease keepalive, heartbeat, reader
2134 /// ACK-NACK timeout, etc.).
2135 ///
2136 /// The executor caps its `drive_io` timeout against
2137 /// `min(user_timeout, timer_deadline, this)` so quiet links don't
2138 /// wake early, see no user-visible work, and round-trip back into
2139 /// `drive_io`. Returns `None` when the backend has no internal
2140 /// deadlines or chooses not to expose them.
2141 ///
2142 /// Default `None` keeps existing backends working unchanged; opt-in
2143 /// per backend.
2144 fn next_deadline_ms(&self) -> Option<u32> {
2145 None
2146 }
2147
2148 /// Phase 124.B.1 — install (or clear, when `cb.is_none()`) the
2149 /// executor wake callback. The runtime calls this once per
2150 /// session after `open` with `cb` pointing at a runtime-owned
2151 /// function and `ctx` pointing at the executor's wake state.
2152 /// The backend stores `(cb, ctx)` in its per-session state and
2153 /// calls `cb(ctx)` whenever its transport notification path
2154 /// fires (datagram arrival, condvar wake, etc.) — the runtime
2155 /// cb does flag-write + condvar-signal atomically, so a
2156 /// `spin_once` blocked on the wake condvar resumes immediately
2157 /// instead of waiting for the next poll iteration.
2158 ///
2159 /// # Safety
2160 ///
2161 /// When `cb` is `Some`, `ctx` must remain valid until the callback is
2162 /// cleared or the session is closed. The backend may invoke `cb(ctx)` from
2163 /// its transport notification path.
2164 ///
2165 /// Default body: ignore the call. Poll-only backends (XRCE,
2166 /// bare-metal) leave the default in place; the executor still
2167 /// drains them on its deadline-bound cv-wait boundary.
2168 unsafe fn set_wake_callback(
2169 &mut self,
2170 cb: Option<unsafe extern "C" fn(ctx: *mut core::ffi::c_void)>,
2171 ctx: *mut core::ffi::c_void,
2172 ) {
2173 let _ = (cb, ctx);
2174 }
2175
2176 /// Phase 130.4 — does this backend actually honour
2177 /// [`set_wake_callback`]?
2178 ///
2179 /// `true` means the backend installs the callback and will
2180 /// fire it from its async notify path (worker thread, ISR,
2181 /// signalfd, …). `false` (the default) means
2182 /// `set_wake_callback` was a no-op — the executor must drive
2183 /// I/O for the caller's full timeout because no async wake
2184 /// will pre-empt it.
2185 ///
2186 /// The executor uses this to choose between the wake-primitive
2187 /// wait (`NodeWake::wait_ms` / `std::Condvar::wait_timeout_while`)
2188 /// and a direct `drive_io(timeout_ms)`. Poll-only backends
2189 /// (XRCE-DDS-Client, bare-metal smoltcp) return `false`;
2190 /// event-driven backends (zenoh-pico with an RX task that
2191 /// invokes the callback on packet arrival) return `true`.
2192 ///
2193 /// [`set_wake_callback`]: Self::set_wake_callback
2194 fn supports_wake_callback(&self) -> bool {
2195 false
2196 }
2197
2198 /// phase-521 W3 (RFC-0113 D4) — which form of readiness this session has.
2199 ///
2200 /// Default: [`ReadinessSource::Notify`] when the backend honours
2201 /// [`set_wake_callback`](Self::set_wake_callback), else
2202 /// [`ReadinessSource::None`] — what the executor inferred before this
2203 /// method existed, so a backend that already delivers a wake callback
2204 /// needs no change. A backend with a waitable OS handle overrides it.
2205 fn readiness_source(&self) -> ReadinessSource {
2206 if self.supports_wake_callback() {
2207 ReadinessSource::Notify
2208 } else {
2209 ReadinessSource::None
2210 }
2211 }
2212
2213 /// Phase 124.F.1 — session-level connectivity probe.
2214 ///
2215 /// Sends a wire-level round-trip probe and waits up to
2216 /// `timeout_ms`. `Ok(())` on reply, `Err(TransportError::Timeout)`
2217 /// on no reply, `Err(TransportError::Unsupported)` when the
2218 /// backend can't probe (DDS without participant introspection).
2219 /// Lesson from micro-ROS's `rmw_uros_ping_agent`.
2220 ///
2221 /// Default body: `Err(Unsupported)`. Backends with a native
2222 /// ping API (XRCE: `uxr_ping_agent_session`; zenoh, which has no
2223 /// round-trip ping, sends one `zpico_send_keep_alive` frame) opt in by
2224 /// overriding.
2225 fn ping_session(&mut self, timeout_ms: i32) -> Result<(), Self::Error>
2226 where
2227 Self::Error: From<TransportError>,
2228 {
2229 let _ = timeout_ms;
2230 Err(TransportError::Unsupported.into())
2231 }
2232
2233 /// phase-381 W3 — enumerate the nodes this session can see.
2234 ///
2235 /// A VISITOR, not a returned collection, because upstream's
2236 /// `rcutils_string_array_t` allocates two levels deep and there is no
2237 /// allocator at this seam. A caller-provided buffer is worse than it looks:
2238 /// the graph has no bound the CALLER can know. So the backend streams from
2239 /// state it already holds, peak extra RAM is one entry, and a caller with a
2240 /// bound stops early by returning `false`.
2241 ///
2242 /// `namespace` and `name` are ROS names. `enclave` is `None` where the
2243 /// backend does not track one — which is what lets this one method answer
2244 /// both `rmw_get_node_names` and `rmw_get_node_names_with_enclaves`.
2245 ///
2246 /// Every string is BORROWED for the duration of the call.
2247 ///
2248 /// **Must not block on the wire, and takes no timeout.** It reports what has
2249 /// ALREADY arrived, so the first call after startup legitimately returns a
2250 /// partial graph — a backend feeds its view from `drive_io`. Letting this
2251 /// block was considered and rejected: it would stall the executor's only
2252 /// thread inside an introspection call, on a runtime whose premise is that
2253 /// there is no other thread to do the work.
2254 ///
2255 /// Default body: `Err(Unsupported)` — a backend with no graph (XRCE) says
2256 /// so, and the runtime can tell that from an empty graph.
2257 fn get_node_names(
2258 &mut self,
2259 visit: &mut dyn FnMut(&str, &str, Option<&str>) -> bool,
2260 ) -> Result<(), Self::Error>
2261 where
2262 Self::Error: From<TransportError>,
2263 {
2264 let _ = visit;
2265 Err(TransportError::Unsupported.into())
2266 }
2267
2268 /// phase-381 W3 — how many publishers this session can see on `topic_name`.
2269 ///
2270 /// `topic_name` is a ROS name (`/chatter`); the backend mangles as needed.
2271 /// Same warm-up caveat as [`Self::get_node_names`]: a count reflects what
2272 /// has already been discovered, so it can be low right after startup and is
2273 /// never a proof of absence.
2274 ///
2275 /// Default body: `Err(Unsupported)` — distinct from `Ok(0)`, which claims
2276 /// there are none.
2277 fn count_publishers(&mut self, topic_name: &str) -> Result<usize, Self::Error>
2278 where
2279 Self::Error: From<TransportError>,
2280 {
2281 let _ = topic_name;
2282 Err(TransportError::Unsupported.into())
2283 }
2284
2285 /// phase-381 W3 — how many subscribers this session can see on `topic_name`.
2286 /// See [`Self::count_publishers`] for the caveats.
2287 fn count_subscribers(&mut self, topic_name: &str) -> Result<usize, Self::Error>
2288 where
2289 Self::Error: From<TransportError>,
2290 {
2291 let _ = topic_name;
2292 Err(TransportError::Unsupported.into())
2293 }
2294
2295 /// Issue 1978 — how many service CLIENTS this session can see on
2296 /// `service_name`, upstream (Jazzy) `rmw_count_clients`. The service twin
2297 /// of [`Self::count_publishers`], with the same caveats: `service_name` is
2298 /// a ROS name the backend mangles, and a count reflects what has already
2299 /// been discovered.
2300 ///
2301 /// Default body: `Err(Unsupported)` — distinct from `Ok(0)`.
2302 fn count_clients(&mut self, service_name: &str) -> Result<usize, Self::Error>
2303 where
2304 Self::Error: From<TransportError>,
2305 {
2306 let _ = service_name;
2307 Err(TransportError::Unsupported.into())
2308 }
2309
2310 /// Issue 1978 — how many service SERVERS this session can see on
2311 /// `service_name`, upstream (Jazzy) `rmw_count_services`. See
2312 /// [`Self::count_clients`].
2313 fn count_services(&mut self, service_name: &str) -> Result<usize, Self::Error>
2314 where
2315 Self::Error: From<TransportError>,
2316 {
2317 let _ = service_name;
2318 Err(TransportError::Unsupported.into())
2319 }
2320
2321 /// Issue 1978 — upstream (Jazzy) `rmw_event_type_is_supported`: whether
2322 /// ANY entity of this backend can carry status event `kind`.
2323 ///
2324 /// STATIC, like [`Self::SERIALIZATION_FORMAT`]: upstream's signature
2325 /// takes no entity and no session, so the C-ABI adapter answers it from
2326 /// the backend TYPE. Per-entity registration
2327 /// ([`Publisher::supports_event`], [`Subscription::supports_event`]) stays
2328 /// the authority for one entity; a backend's per-entity answer must be a
2329 /// subset of this one, and the way to keep it so is to derive both from
2330 /// one helper in the backend (zenoh's `shim::events`).
2331 ///
2332 /// Default: `false` — the backend states no event support, the answer a
2333 /// NULL vtable slot carries.
2334 fn event_type_is_supported(kind: crate::event::EventKind) -> bool
2335 where
2336 Self: Sized,
2337 {
2338 let _ = kind;
2339 false
2340 }
2341
2342 /// phase-381 W3 — every topic, with the types published or subscribed on it.
2343 ///
2344 /// A visitor for the same reason as [`Self::get_node_names`], and one call
2345 /// per distinct NAME: the contract hands over a name and the types on it,
2346 /// so a topic carrying two types is one visit with two entries, not two
2347 /// visits.
2348 ///
2349 /// `types_count` may legitimately be 0 on a partially discovered graph —
2350 /// reporting the name without a type beats dropping it.
2351 ///
2352 /// Default body: `Err(Unsupported)`.
2353 fn get_topic_names_and_types(
2354 &mut self,
2355 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2356 ) -> Result<(), Self::Error>
2357 where
2358 Self::Error: From<TransportError>,
2359 {
2360 let _ = visit;
2361 Err(TransportError::Unsupported.into())
2362 }
2363
2364 /// phase-381 W3 — every service, with its types. As
2365 /// [`Self::get_topic_names_and_types`], over servers and clients.
2366 fn get_service_names_and_types(
2367 &mut self,
2368 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2369 ) -> Result<(), Self::Error>
2370 where
2371 Self::Error: From<TransportError>,
2372 {
2373 let _ = visit;
2374 Err(TransportError::Unsupported.into())
2375 }
2376
2377 /// phase-381 W3 — what ONE named node publishes / subscribes / serves /
2378 /// calls.
2379 ///
2380 /// `node_name` and `node_namespace` are ROS names; a node the graph has not
2381 /// discovered yields no visits, which is NOT an error — see
2382 /// [`Self::get_node_names`] for why an empty answer is "not seen yet".
2383 ///
2384 /// `kind` selects which of the four upstream `*_by_node` questions this
2385 /// answers. One method rather than four because the four differ ONLY by
2386 /// which entity kind they keep, and four trait methods would be four copies
2387 /// of one filter.
2388 ///
2389 /// The trait keeps the ABI's `subscriber` vocabulary because
2390 /// `rmw_get_subscriber_names_and_types_by_node` is what upstream rmw calls
2391 /// it and RFC-0054 makes the C headers the SSoT. The USER-facing spelling
2392 /// is per language and settled at that layer: rcl says `subscriber`, rclcpp
2393 /// and rclrs say `subscription`.
2394 ///
2395 /// Default body: `Err(Unsupported)`.
2396 fn get_names_and_types_by_node(
2397 &mut self,
2398 kind: GraphEntityKind,
2399 node_name: &str,
2400 node_namespace: &str,
2401 visit: &mut dyn FnMut(&str, &[&str]) -> bool,
2402 ) -> Result<(), Self::Error>
2403 where
2404 Self::Error: From<TransportError>,
2405 {
2406 let _ = (kind, node_name, node_namespace, visit);
2407 Err(TransportError::Unsupported.into())
2408 }
2409
2410 /// phase-381 W3 — the endpoints on one topic, with the QoS each GRANTED.
2411 ///
2412 /// `publishers` selects `rmw_get_publishers_info_by_topic` (`true`) or
2413 /// `rmw_get_subscriptions_info_by_topic` (`false`).
2414 ///
2415 /// The granted profile is the whole reason a consumer asks: "why is nothing
2416 /// arriving" is usually a QoS incompatibility, and the REQUESTED profile
2417 /// cannot answer it. A backend that cannot read a remote's granted QoS says
2418 /// so per field rather than echoing the request back — see
2419 /// `rmw_topic_endpoint_info_t`.
2420 ///
2421 /// Default body: `Err(Unsupported)`.
2422 fn get_endpoint_info_by_topic(
2423 &mut self,
2424 publishers: bool,
2425 topic_name: &str,
2426 visit: &mut dyn FnMut(&GraphEndpointInfo<'_>) -> bool,
2427 ) -> Result<(), Self::Error>
2428 where
2429 Self::Error: From<TransportError>,
2430 {
2431 let _ = (publishers, topic_name, visit);
2432 Err(TransportError::Unsupported.into())
2433 }
2434
2435 /// phase-467 Row 8 — install (or clear, when `callback` is `None`) the
2436 /// callback the backend fires when the ROS GRAPH changes.
2437 ///
2438 /// The Rust twin of `nros_rmw_vtable_t::node_get_graph_guard_condition`, which
2439 /// is upstream's `rmw_node_get_graph_guard_condition` under the
2440 /// `set_wake_callback` shape: upstream RETURNS a guard condition the caller
2441 /// adds to a wait set, we have no wait set, and a guard condition here is
2442 /// an executor concept the backend never hands out. So the edge is PUSHED,
2443 /// not polled — and the ABI slot has said so since phase-376 W4, while
2444 /// this is the trait twin it never had.
2445 ///
2446 /// The callback is an EDGE and carries no payload. `count` is how many
2447 /// changes the backend coalesced, never a description of WHAT changed:
2448 /// delivering that would mean buffering the graph, which is the cache a
2449 /// small target cannot afford.
2450 ///
2451 /// **A backend must not fire it for a no-op.** The contract is "the graph
2452 /// this session can SEE differs from what it saw", which both real
2453 /// backends already computed and threw away — zenoh in
2454 /// `zpico_graph_set_apply`'s return value, Cyclone in
2455 /// `on_data_available`'s first parameter.
2456 ///
2457 /// # Safety
2458 ///
2459 /// When `callback` is `Some`, `user_data` must remain valid until the
2460 /// callback is cleared or the session is closed; the backend may invoke it
2461 /// from a transport or worker thread. **The installer owes the clear** —
2462 /// see `Executor::clear_graph_change_signal`, which is issue 1385's lesson
2463 /// applied before the hazard rather than after it.
2464 ///
2465 /// Default body: `Err(Unsupported)` — a backend with no graph (XRCE, uORB)
2466 /// says "cannot tell you" rather than accepting a callback it will never
2467 /// fire. That answer is also the capability PROBE the runtime uses: a
2468 /// `None` clear on a graphless backend returns `Unsupported`, so nothing
2469 /// else has to be asked and no handle is consumed before the answer.
2470 unsafe fn set_graph_change_callback(
2471 &mut self,
2472 callback: Option<unsafe extern "C" fn(user_data: *const core::ffi::c_void, count: usize)>,
2473 user_data: *const core::ffi::c_void,
2474 ) -> Result<(), Self::Error>
2475 where
2476 Self::Error: From<TransportError>,
2477 {
2478 let _ = (callback, user_data);
2479 Err(TransportError::Unsupported.into())
2480 }
2481}
2482
2483/// Which entity kind a `*_by_node` graph query keeps.
2484///
2485/// Named for upstream rmw's four `*_by_node` slots. `Subscriber` carries rmw's
2486/// word, not rclcpp's `subscription`; the user-facing spelling is chosen per
2487/// language one layer up.
2488#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2489pub enum GraphEntityKind {
2490 Publisher,
2491 Subscriber,
2492 Service,
2493 Client,
2494}
2495
2496/// One discovered endpoint on a topic — the Rust view of
2497/// `rmw_topic_endpoint_info_t`.
2498///
2499/// Every string BORROWS from the backend's own state for the duration of the
2500/// visit. A caller that needs one afterwards copies it; that is what lets the
2501/// graph stream without an allocator.
2502#[derive(Debug, Clone)]
2503pub struct GraphEndpointInfo<'a> {
2504 /// Node that owns the endpoint.
2505 pub node_name: &'a str,
2506 /// That node's namespace.
2507 pub node_namespace: &'a str,
2508 /// Fully-qualified type on the wire, e.g. `"std_msgs/msg/Int32"`.
2509 pub topic_type: &'a str,
2510 /// `true` for a publisher, `false` for a subscription.
2511 pub is_publisher: bool,
2512 /// The endpoint's 24-byte identity; all-zero when the backend has none.
2513 pub endpoint_gid: [u8; 24],
2514 /// The profile the endpoint is known by — what the backend MATCHED on.
2515 ///
2516 /// [`QoSProfile::QOS_PROFILE_UNKNOWN`] (every policy `Unknown`, windows 0)
2517 /// when the backend cannot read it, which is the C seam's contract on
2518 /// `rmw_topic_endpoint_info_t::qos_profile` too.
2519 pub qos: QoSProfile,
2520}
2521
2522// The `qos` field arrived with issue 1973, because resolving a best-available
2523// profile needs every peer's profile and this is the seam that walks them.
2524//
2525// It was left out before on the reading that zenoh's liveliness token carries
2526// the DECLARING side's profile, not a negotiated grant. Measured against what
2527// the token actually holds, that distinction does not exist on zenoh: there is
2528// no negotiation, our token is written from `shim/qos.rs`'s GRANT
2529// (`keyexpr.rs`), and a stock `rmw_zenoh_cpp` peer writes its own resolved
2530// profile and reports the same string from `rmw_get_publishers_info_by_topic`.
2531// So the token is what the endpoint does, which is what the C seam's
2532// `qos_profile` promises ("reports what it MATCHED on"). Cyclone fills it from
2533// the discovered endpoint's DDS QoS (`graph_query.cpp`). A backend that cannot
2534// read one writes `QOS_PROFILE_UNKNOWN`, never the local request.
2535
2536/// Bitmask of QoS policies a backend can honour. See
2537/// [`Session::supported_qos_policies`].
2538///
2539/// One bit per value `QoSProfile::required_policies` can request, and that
2540/// function is the definition of what each bit MEANS — `check-qos-mask-
2541/// derivation` reads the bit->field mapping out of its body rather than
2542/// restating it, so a policy that gains a bit here and no arm there is a gate
2543/// failure instead of a bit nothing can ever ask for.
2544#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2545pub struct QoSPolicyMask(pub u32);
2546
2547impl QoSPolicyMask {
2548 pub const RELIABILITY: Self = Self(1 << 0);
2549 pub const DURABILITY_VOLATILE: Self = Self(1 << 1);
2550 pub const DURABILITY_TRANSIENT_LOCAL: Self = Self(1 << 2);
2551 pub const HISTORY: Self = Self(1 << 3);
2552 pub const DEPTH: Self = Self(1 << 4);
2553 pub const DEADLINE: Self = Self(1 << 5);
2554 pub const LIFESPAN: Self = Self(1 << 6);
2555 pub const LIVELINESS_AUTOMATIC: Self = Self(1 << 7);
2556 pub const LIVELINESS_MANUAL_BY_TOPIC: Self = Self(1 << 8);
2557 pub const LIVELINESS_MANUAL_BY_NODE: Self = Self(1 << 9);
2558 pub const LIVELINESS_LEASE: Self = Self(1 << 10);
2559 pub const AVOID_ROS_NAMESPACE_CONVENTIONS: Self = Self(1 << 11);
2560
2561 /// Honours nothing. The default answer for an implementation that has not
2562 /// said otherwise — see [`Session::supported_qos_policies`].
2563 pub const NONE: Self = Self(0);
2564
2565 /// The four policies every `QoSProfile` states a value for.
2566 ///
2567 /// NOT "policies every nano-ros backend implements", which is what this
2568 /// once said, until it was measured: the zenoh shim honoured exactly
2569 /// none of the four, serialising all four into a discovery keyexpr and
2570 /// enforcing a build-time ring depth. The name describes the SHAPE of a
2571 /// profile — a caller who states nothing else still states these — and a
2572 /// backend still has to earn each bit.
2573 pub const CORE: Self =
2574 Self(Self::RELIABILITY.0 | Self::DURABILITY_VOLATILE.0 | Self::HISTORY.0 | Self::DEPTH.0);
2575
2576 /// Every policy bit paired with the name it PRINTS — the vocabulary the
2577 /// three languages name a refused policy in (ledger row
2578 /// `cpp:qos_policy_kind_to_cstr`).
2579 ///
2580 /// The name of a bit is the CONSTANT'S OWN IDENTIFIER, never an
2581 /// independently chosen word. That is what keeps this from becoming the
2582 /// parallel table this campaign has paid for twice — the RMW parity map's
2583 /// 28 stale slots and the layout gate's three authored type names — and it
2584 /// is what `check-qos-mask-derivation`'s R8 measures: the entries here must
2585 /// be exactly the `pub const … = Self(1 << n)` bits above, each paired with
2586 /// its own spelling. A bit added above and not here is a gate failure, not
2587 /// a policy that silently prints as nothing.
2588 ///
2589 /// Uppercase because that is upstream's convention for the same strings:
2590 /// `rclcpp::qos_policy_kind_to_cstr` returns `"DURABILITY"`, `"DEADLINE"`,
2591 /// `"LIVELINESS"` and the rest.
2592 ///
2593 /// `NONE` and `CORE` are deliberately absent: they are not policies, they
2594 /// are the empty mask and a named union, and neither can be the answer to
2595 /// "which policy was refused".
2596 ///
2597 /// The name is stored as a [`core::ffi::CStr`] and not as a `&str`,
2598 /// because the C entry point (`rclc_qos_policy_kind_to_cstr`) needs the
2599 /// trailing NUL and a `&str` does not carry one. Storing the `&str` form
2600 /// and NUL-terminating it in `nros-c` was the first shape here, and it put
2601 /// the twelve identifiers in a second file — which is the drift this row
2602 /// exists to avoid. One table, two readings: `policy_name` slices the NUL
2603 /// off for Rust, the C entry point hands the pointer straight over.
2604 pub const NAMED: &'static [(Self, &'static core::ffi::CStr)] = &[
2605 (Self::RELIABILITY, c"RELIABILITY"),
2606 (Self::DURABILITY_VOLATILE, c"DURABILITY_VOLATILE"),
2607 (
2608 Self::DURABILITY_TRANSIENT_LOCAL,
2609 c"DURABILITY_TRANSIENT_LOCAL",
2610 ),
2611 (Self::HISTORY, c"HISTORY"),
2612 (Self::DEPTH, c"DEPTH"),
2613 (Self::DEADLINE, c"DEADLINE"),
2614 (Self::LIFESPAN, c"LIFESPAN"),
2615 (Self::LIVELINESS_AUTOMATIC, c"LIVELINESS_AUTOMATIC"),
2616 (
2617 Self::LIVELINESS_MANUAL_BY_TOPIC,
2618 c"LIVELINESS_MANUAL_BY_TOPIC",
2619 ),
2620 (
2621 Self::LIVELINESS_MANUAL_BY_NODE,
2622 c"LIVELINESS_MANUAL_BY_NODE",
2623 ),
2624 (Self::LIVELINESS_LEASE, c"LIVELINESS_LEASE"),
2625 (
2626 Self::AVOID_ROS_NAMESPACE_CONVENTIONS,
2627 c"AVOID_ROS_NAMESPACE_CONVENTIONS",
2628 ),
2629 ];
2630
2631 /// The name of the ONE policy this mask is, as a C string.
2632 ///
2633 /// `None` for the empty mask and for a mask carrying more than one bit:
2634 /// both are real answers a diagnostic must be able to give. "The backend
2635 /// did not say which" is not a policy name, and printing a neighbouring
2636 /// one would be the plausible wrong answer this whole family exists to
2637 /// refuse.
2638 ///
2639 /// Borrowed from a table in flash: no allocator, no formatting, reaches a
2640 /// bare-metal target, and these are the exact bytes the C and C++ entry
2641 /// points hand back.
2642 pub const fn policy_name_cstr(self) -> Option<&'static core::ffi::CStr> {
2643 let mut i = 0;
2644 while i < Self::NAMED.len() {
2645 if Self::NAMED[i].0.0 == self.0 {
2646 return Some(Self::NAMED[i].1);
2647 }
2648 i += 1;
2649 }
2650 None
2651 }
2652
2653 /// [`Self::policy_name_cstr`] as a Rust string — the same bytes without
2654 /// the terminator.
2655 pub fn policy_name(self) -> Option<&'static str> {
2656 // Every entry is an ASCII literal, so this cannot fail; `ok()` rather
2657 // than `expect()` because a panic in a diagnostic path is worse than
2658 // the diagnostic being absent.
2659 self.policy_name_cstr().and_then(|c| c.to_str().ok())
2660 }
2661
2662 /// The policies in `self` that `supported` does not carry.
2663 pub const fn missing_from(self, supported: Self) -> Self {
2664 Self(self.0 & !supported.0)
2665 }
2666
2667 /// The lowest-numbered policy bit set here, or [`Self::NONE`].
2668 ///
2669 /// Which single policy a multi-policy refusal REPORTS. Lowest bit rather
2670 /// than "any": a stable choice means the same profile against the same
2671 /// backend names the same policy on every run and in every language, so a
2672 /// test can assert it and two surfaces cannot disagree about which one to
2673 /// mention first.
2674 pub const fn lowest_policy(self) -> Self {
2675 Self(self.0 & self.0.wrapping_neg())
2676 }
2677
2678 /// `true` if `self` contains every policy in `other`.
2679 pub const fn contains(self, other: Self) -> bool {
2680 self.0 & other.0 == other.0
2681 }
2682
2683 /// Bitwise OR of two masks.
2684 pub const fn union(self, other: Self) -> Self {
2685 Self(self.0 | other.0)
2686 }
2687}
2688
2689impl core::ops::BitOr for QoSPolicyMask {
2690 type Output = Self;
2691 fn bitor(self, rhs: Self) -> Self {
2692 self.union(rhs)
2693 }
2694}
2695
2696impl core::ops::BitOrAssign for QoSPolicyMask {
2697 fn bitor_assign(&mut self, rhs: Self) {
2698 self.0 |= rhs.0;
2699 }
2700}
2701
2702impl QoSProfile {
2703 /// Does any policy in this profile carry its `Unknown` sentinel?
2704 ///
2705 /// True only for a profile that came out of a `*_get_actual_qos`
2706 /// read-back on a backend that could not report every policy — never for
2707 /// one an application built. [`validate_against`](Self::validate_against)
2708 /// refuses such a profile at create time, so "I cannot say" cannot be
2709 /// laundered into a request.
2710 pub const fn has_unknown(&self) -> bool {
2711 matches!(self.reliability, QoSReliabilityPolicy::Unknown)
2712 || matches!(self.durability, QoSDurabilityPolicy::Unknown)
2713 || matches!(self.history, QoSHistoryPolicy::Unknown)
2714 || matches!(self.liveliness_kind, QoSLivelinessPolicy::Unknown)
2715 }
2716
2717 /// Compute the set of QoS policies actually requested by this profile.
2718 ///
2719 /// Zero-valued time fields and `QoSLivelinessPolicy::None` count as "not
2720 /// requesting" the corresponding policy — the cheap default.
2721 ///
2722 /// The four `CORE` bits (reliability, durability, history,
2723 /// depth) used to be added UNCONDITIONALLY, on the reasoning that every
2724 /// nano-ros backend honours them. That is true and still not the right
2725 /// test: this function answers *what did the caller ASK FOR*, and a
2726 /// `SYSTEM_DEFAULT` policy asks for nothing. Starting from `CORE` made
2727 /// `QOS_PROFILE_SYSTEM_DEFAULT` demand all four, so a backend that could
2728 /// not honour one would reject the profile with `IncompatibleQos` — for
2729 /// requesting nothing. The pattern was already here for the extended
2730 /// policies three lines down (a zero `deadline_ms` declines its bit); it
2731 /// just never reached the four CORE ones.
2732 ///
2733 /// This RELAXES the mask, so it can only turn a rejection into an
2734 /// acceptance, never the reverse.
2735 ///
2736 /// It used to say it flipped no verdict "because every
2737 /// `supported_qos_policies` impl in the tree returns at least `CORE`".
2738 /// That stopped being true: the trait default is
2739 /// [`QoSPolicyMask::NONE`] now, so an implementation that claims nothing
2740 /// is refused on the first CORE bit a caller states — which is the whole
2741 /// point, and which makes THIS function's sentinel handling the thing
2742 /// standing between `QOS_PROFILE_SYSTEM_DEFAULT` and a hard refusal.
2743 pub fn required_policies(&self) -> QoSPolicyMask {
2744 let mut mask = QoSPolicyMask(0);
2745 if self.reliability != QoSReliabilityPolicy::SystemDefault
2746 && self.reliability != QoSReliabilityPolicy::BestAvailable
2747 {
2748 mask |= QoSPolicyMask::RELIABILITY;
2749 }
2750 if self.history != QoSHistoryPolicy::SystemDefault {
2751 mask |= QoSPolicyMask::HISTORY;
2752 }
2753 // Depth's sentinel is a VALUE, not a variant: `DEPTH_SYSTEM_DEFAULT`
2754 // is 0, the same 0 that a `KEEP_ALL` profile carries to mean "depth is
2755 // not used here" (`QoSProfile::keep_all()` leaves whatever depth the
2756 // profile had, and a caller building one from scratch leaves it 0).
2757 // Both mean the caller did not ask for a depth, so both decline the
2758 // bit. No NAMED preset is `KEEP_ALL` any more — phase-428 W10;
2759 // `QOS_PROFILE_PARAMETER_EVENTS` used to be the exemplar here and was
2760 // the defect, not the example.
2761 if self.depth != DEPTH_SYSTEM_DEFAULT {
2762 mask |= QoSPolicyMask::DEPTH;
2763 }
2764 match self.durability {
2765 QoSDurabilityPolicy::SystemDefault => {}
2766 QoSDurabilityPolicy::Volatile => mask |= QoSPolicyMask::DURABILITY_VOLATILE,
2767 QoSDurabilityPolicy::TransientLocal => {
2768 mask |= QoSPolicyMask::DURABILITY_TRANSIENT_LOCAL
2769 }
2770 // `Unknown` is a READ-BACK sentinel, never a request, so there is
2771 // no capability bit to demand for it — there is nothing a backend
2772 // could support. Refusing it belongs one level up, in
2773 // `validate_against`, where it is refused for every policy at once
2774 // rather than smuggled in as an unsatisfiable mask bit.
2775 QoSDurabilityPolicy::Unknown => {}
2776 // issue 1973 — a best-available field demands NOTHING: the
2777 // resolver clamps its choice to the backend's own mask
2778 // (`resolve_best_available`), so whatever it picks is honoured.
2779 QoSDurabilityPolicy::BestAvailable => {}
2780 }
2781 // Phase-301 (issue 0241): DURATION_INFINITE_MS reads the same as 0
2782 // (infinite = no check) at every duration check site. The
2783 // best-available sentinel demands nothing either (see above).
2784 if self.deadline_ms != 0
2785 && self.deadline_ms != DURATION_INFINITE_MS
2786 && self.deadline_ms != DURATION_BEST_AVAILABLE_MS
2787 {
2788 mask |= QoSPolicyMask::DEADLINE;
2789 }
2790 if self.lifespan_ms != 0 && self.lifespan_ms != DURATION_INFINITE_MS {
2791 mask |= QoSPolicyMask::LIFESPAN;
2792 }
2793 match self.liveliness_kind {
2794 QoSLivelinessPolicy::None => {}
2795 QoSLivelinessPolicy::Automatic => mask |= QoSPolicyMask::LIVELINESS_AUTOMATIC,
2796 QoSLivelinessPolicy::ManualByTopic => mask |= QoSPolicyMask::LIVELINESS_MANUAL_BY_TOPIC,
2797 QoSLivelinessPolicy::ManualByNode => mask |= QoSPolicyMask::LIVELINESS_MANUAL_BY_NODE,
2798 // See the durability arm.
2799 QoSLivelinessPolicy::Unknown => {}
2800 QoSLivelinessPolicy::BestAvailable => {}
2801 }
2802 if self.liveliness_lease_ms != 0
2803 && self.liveliness_lease_ms != DURATION_INFINITE_MS
2804 && self.liveliness_lease_ms != DURATION_BEST_AVAILABLE_MS
2805 {
2806 mask |= QoSPolicyMask::LIVELINESS_LEASE;
2807 }
2808 if self.avoid_ros_namespace_conventions {
2809 mask |= QoSPolicyMask::AVOID_ROS_NAMESPACE_CONVENTIONS;
2810 }
2811 mask
2812 }
2813
2814 /// Returns `Err(TransportError::IncompatibleQos(policy))` if any policy
2815 /// this profile requires is missing from the backend's `supported` mask.
2816 /// Used at entity-create time to enforce the **no silent
2817 /// degradation** contract.
2818 ///
2819 /// **The error NAMES the policy**. This once computed the
2820 /// offending bit and discarded it, returning a bare
2821 /// `IncompatibleQos` — so every one of the six `create_*` paths in
2822 /// `nros-node` refused with the one fact the caller needed missing, while
2823 /// `rmw_vtable.h` told the reader the opposite. Which bit is reported when
2824 /// several are missing is [`QoSPolicyMask::lowest_policy`]'s choice, and it
2825 /// is stable so a test can assert it.
2826 pub fn validate_against(&self, supported: QoSPolicyMask) -> Result<(), TransportError> {
2827 // issue 1437 — `UNKNOWN` is what a `*_get_actual_qos` read-back writes
2828 // for a policy it cannot report. It is an ABSENCE, so it is meaningless
2829 // as a REQUEST, and the way it reaches a create call is a caller
2830 // feeding a read-back profile straight back in — the exact round trip
2831 // that would otherwise turn "I cannot say" into a silently different
2832 // entity. Refused here, once, for all four policies.
2833 //
2834 // The refusal names NO policy, and that is not laziness: the mask's
2835 // bits are CAPABILITIES a backend declares, and no backend could ever
2836 // declare one that makes "I cannot say" servable — `required_policies`
2837 // has no bit to set, so there is none to report. `policy_name` already
2838 // answers `None` for the empty mask, which the diagnostic renders as
2839 // the honest "the profile is not a request", rather than naming
2840 // `DURABILITY_VOLATILE` for a durability that is not volatile.
2841 if self.has_unknown() {
2842 return Err(TransportError::IncompatibleQos(QoSPolicyMask::NONE));
2843 }
2844 let missing = self.required_policies().missing_from(supported);
2845 if missing.0 == 0 {
2846 Ok(())
2847 } else {
2848 Err(TransportError::IncompatibleQos(missing.lowest_policy()))
2849 }
2850 }
2851
2852 /// Replace every `SYSTEM_DEFAULT` field with the backend's own answer.
2853 ///
2854 /// A backend calls this at its create entry, **before**
2855 /// anything is derived from the profile (see [`QoSSystemDefaults`] for why
2856 /// the ordering matters on the zenoh path). Fields the caller DID state
2857 /// are left exactly as they are: this resolves an absence, it never
2858 /// overrides a request.
2859 ///
2860 /// Idempotent, and safe to call on a fully concrete profile — a profile
2861 /// with no sentinel in it is returned unchanged.
2862 #[must_use]
2863 pub const fn resolve_system_default(mut self, defaults: &QoSSystemDefaults) -> Self {
2864 if matches!(self.reliability, QoSReliabilityPolicy::SystemDefault) {
2865 self.reliability = defaults.reliability;
2866 }
2867 if matches!(self.durability, QoSDurabilityPolicy::SystemDefault) {
2868 self.durability = defaults.durability;
2869 }
2870 if matches!(self.history, QoSHistoryPolicy::SystemDefault) {
2871 self.history = defaults.history;
2872 }
2873 if self.depth == DEPTH_SYSTEM_DEFAULT {
2874 self.depth = defaults.depth;
2875 }
2876 self
2877 }
2878
2879 /// `true` if any field is still the `SYSTEM_DEFAULT` sentinel.
2880 ///
2881 /// Depth is deliberately NOT part of this test: a `KEEP_ALL` profile
2882 /// legitimately carries depth 0 forever (any profile a caller builds with
2883 /// [`QoSProfile::keep_all`] and never gave a depth to — no NAMED preset is
2884 /// `KEEP_ALL`), and a backend that resolves the
2885 /// sentinel depth to 0 — XRCE does, on purpose — leaves a resolved profile
2886 /// reading 0 here. This asks about the
2887 /// three POLICY fields, where the sentinel is a distinct variant and so
2888 /// cannot be confused with a stated value.
2889 #[must_use]
2890 pub const fn has_unresolved_system_default(&self) -> bool {
2891 matches!(self.reliability, QoSReliabilityPolicy::SystemDefault)
2892 || matches!(self.durability, QoSDurabilityPolicy::SystemDefault)
2893 || matches!(self.history, QoSHistoryPolicy::SystemDefault)
2894 }
2895
2896 /// `true` if any field still asks to be resolved best-available (issue
2897 /// 1973): one of the three policy variants, or the
2898 /// [`DURATION_BEST_AVAILABLE_MS`] sentinel in `deadline_ms` /
2899 /// `liveliness_lease_ms`.
2900 #[must_use]
2901 pub const fn has_best_available(&self) -> bool {
2902 matches!(self.reliability, QoSReliabilityPolicy::BestAvailable)
2903 || matches!(self.durability, QoSDurabilityPolicy::BestAvailable)
2904 || matches!(self.liveliness_kind, QoSLivelinessPolicy::BestAvailable)
2905 || self.deadline_ms == DURATION_BEST_AVAILABLE_MS
2906 || self.liveliness_lease_ms == DURATION_BEST_AVAILABLE_MS
2907 }
2908
2909 /// Replace every best-available field with a concrete value — the ONE
2910 /// resolution rule every backend reaches.
2911 ///
2912 /// The rule is upstream's, transcribed from `rmw_dds_common`'s
2913 /// `qos_profile_get_best_available_for_{subscription,publisher}` and
2914 /// `qos_profile_update_best_available_for_services` (jazzy):
2915 ///
2916 /// | policy | subscription (peers = publishers) | publisher (peers = subscriptions) |
2917 /// |-------------|----------------------------------------------------|------------------------------------------------|
2918 /// | reliability | RELIABLE iff ≥1 peer and every peer is RELIABLE, else BEST_EFFORT | RELIABLE |
2919 /// | durability | TRANSIENT_LOCAL iff ≥1 peer and all are, else VOLATILE | TRANSIENT_LOCAL |
2920 /// | liveliness | MANUAL_BY_TOPIC iff ≥1 peer and all are, else AUTOMATIC | MANUAL_BY_TOPIC iff any peer is, else AUTOMATIC |
2921 /// | deadline | largest finite peer deadline, else default (0) | smallest finite peer deadline, else default (0) |
2922 /// | lease | largest finite peer lease, else default (0) | smallest finite peer lease, else default (0) |
2923 ///
2924 /// A service or client ([`BestAvailableRole::Service`]) takes each field
2925 /// from `rmw_qos_profile_services_default`, as upstream does.
2926 ///
2927 /// **No peers is a real answer, not a failure.** It is what a backend with
2928 /// no graph (XRCE, uORB) always reports, and it yields upstream's own
2929 /// "nothing discovered yet" profile: BEST_EFFORT / VOLATILE / AUTOMATIC for
2930 /// a subscription, RELIABLE / TRANSIENT_LOCAL / AUTOMATIC for a publisher.
2931 ///
2932 /// **A peer whose profile the backend cannot read** (its fields are the
2933 /// `Unknown` sentinels, durations 0) contributes its LEAST demanding value:
2934 /// not reliable, not transient-local, not manual, no deadline. For a
2935 /// subscription that keeps the choice compatible with the peer whatever it
2936 /// really offers; a publisher cannot be protected the same way and offers
2937 /// what the readable peers ask for.
2938 ///
2939 /// **Last, the choice is clamped to what the backend honours**
2940 /// (`supported`, its [`Session::supported_qos_policies`]): a resolved value
2941 /// the backend could not grant steps down to the next one it can —
2942 /// TRANSIENT_LOCAL → VOLATILE, MANUAL_BY_TOPIC → AUTOMATIC, a finite
2943 /// deadline or lease → default — and to the `SYSTEM_DEFAULT` sentinel when
2944 /// the backend honours the policy not at all. "Best available" is then
2945 /// literally the best this backend has; the alternative, choosing a value
2946 /// the next line refuses with `IncompatibleQos`, would make the request
2947 /// fail for asking to be accommodated. Fields the caller stated are never
2948 /// touched.
2949 ///
2950 /// Idempotent: a profile with nothing best-available is returned as is.
2951 #[must_use]
2952 pub fn resolve_best_available(
2953 mut self,
2954 role: BestAvailableRole,
2955 peers: &BestAvailablePeers,
2956 supported: QoSPolicyMask,
2957 ) -> Self {
2958 let rel = matches!(self.reliability, QoSReliabilityPolicy::BestAvailable);
2959 let dur = matches!(self.durability, QoSDurabilityPolicy::BestAvailable);
2960 let liv = matches!(self.liveliness_kind, QoSLivelinessPolicy::BestAvailable);
2961 let dl = self.deadline_ms == DURATION_BEST_AVAILABLE_MS;
2962 let lease = self.liveliness_lease_ms == DURATION_BEST_AVAILABLE_MS;
2963 let any = peers.count > 0;
2964 match role {
2965 BestAvailableRole::Subscription => {
2966 if rel {
2967 self.reliability = if any && peers.reliable == peers.count {
2968 QoSReliabilityPolicy::Reliable
2969 } else {
2970 QoSReliabilityPolicy::BestEffort
2971 };
2972 }
2973 if dur {
2974 self.durability = if any && peers.transient_local == peers.count {
2975 QoSDurabilityPolicy::TransientLocal
2976 } else {
2977 QoSDurabilityPolicy::Volatile
2978 };
2979 }
2980 if liv {
2981 self.liveliness_kind = if any && peers.manual_by_topic == peers.count {
2982 QoSLivelinessPolicy::ManualByTopic
2983 } else {
2984 QoSLivelinessPolicy::Automatic
2985 };
2986 }
2987 if dl {
2988 self.deadline_ms = peers.deadline_max;
2989 }
2990 if lease {
2991 self.liveliness_lease_ms = peers.lease_max;
2992 }
2993 }
2994 BestAvailableRole::Publisher => {
2995 if rel {
2996 self.reliability = QoSReliabilityPolicy::Reliable;
2997 }
2998 if dur {
2999 self.durability = QoSDurabilityPolicy::TransientLocal;
3000 }
3001 if liv {
3002 self.liveliness_kind = if peers.manual_by_topic > 0 {
3003 QoSLivelinessPolicy::ManualByTopic
3004 } else {
3005 QoSLivelinessPolicy::Automatic
3006 };
3007 }
3008 if dl {
3009 self.deadline_ms = peers.deadline_min;
3010 }
3011 if lease {
3012 self.liveliness_lease_ms = peers.lease_min;
3013 }
3014 }
3015 BestAvailableRole::Service => {
3016 let svc = Self::QOS_PROFILE_SERVICES_DEFAULT;
3017 if rel {
3018 self.reliability = svc.reliability;
3019 }
3020 if dur {
3021 self.durability = svc.durability;
3022 }
3023 if liv {
3024 self.liveliness_kind = svc.liveliness_kind;
3025 }
3026 if dl {
3027 self.deadline_ms = svc.deadline_ms;
3028 }
3029 if lease {
3030 self.liveliness_lease_ms = svc.liveliness_lease_ms;
3031 }
3032 }
3033 }
3034
3035 // The clamp — only on fields that WERE best-available.
3036 self.step_down(
3037 StepDownFields {
3038 reliability: rel,
3039 durability: dur,
3040 liveliness: liv,
3041 deadline: dl,
3042 lease,
3043 lifespan: false,
3044 },
3045 supported,
3046 )
3047 }
3048
3049 /// Fit a profile the RUNTIME chose for one of its own endpoints to what
3050 /// the backend honours, and say what that dropped.
3051 ///
3052 /// The rule for a runtime-owned endpoint (`/rosout`, `/parameter_events`,
3053 /// the lifecycle services and `transition_event`): its profile is a
3054 /// preference, not a request. Every field the backend's `supported` mask
3055 /// lacks steps down by the same rule a best-available field is clamped
3056 /// with — TRANSIENT_LOCAL → VOLATILE, a manual liveliness → AUTOMATIC, a
3057 /// finite deadline, lease or lifespan → none, and a policy the backend
3058 /// honours not at all → `SYSTEM_DEFAULT` — so the endpoint exists on every
3059 /// backend instead of being refused for asking.
3060 ///
3061 /// A profile an APPLICATION supplies never comes here: it stays a
3062 /// requirement, and [`Self::validate_against`] refuses it naming the
3063 /// policy. So does anything folded onto a runtime profile afterwards (a
3064 /// per-topic override, a declared contract), because a person wrote that.
3065 ///
3066 /// Returns the fitted profile and the policies it no longer requires —
3067 /// [`QoSPolicyMask::NONE`] when the backend honours all of them, in which
3068 /// case the profile is unchanged. History, depth and the namespace
3069 /// convention have no weaker form and are not touched: a runtime profile
3070 /// that needs one the backend lacks is still refused.
3071 #[must_use]
3072 pub fn fit_to_supported(self, supported: QoSPolicyMask) -> (Self, QoSPolicyMask) {
3073 let dropped = self.required_policies().missing_from(supported);
3074 if dropped.0 == 0 {
3075 return (self, QoSPolicyMask::NONE);
3076 }
3077 let fitted = self.step_down(StepDownFields::ALL, supported);
3078 // Only what actually stopped being required: a policy with no weaker
3079 // form (history, depth) stays required and is refused downstream.
3080 let still = fitted.required_policies().missing_from(supported);
3081 (fitted, QoSPolicyMask(dropped.0 & !still.0))
3082 }
3083
3084 /// Step each field named in `fields` down to the strongest value the
3085 /// backend honours. The one spelling of the step-down rule, shared by the
3086 /// best-available clamp and [`Self::fit_to_supported`].
3087 fn step_down(mut self, fields: StepDownFields, supported: QoSPolicyMask) -> Self {
3088 if fields.reliability
3089 && !matches!(self.reliability, QoSReliabilityPolicy::SystemDefault)
3090 && !supported.contains(QoSPolicyMask::RELIABILITY)
3091 {
3092 self.reliability = QoSReliabilityPolicy::SystemDefault;
3093 }
3094 if fields.durability {
3095 if matches!(self.durability, QoSDurabilityPolicy::TransientLocal)
3096 && !supported.contains(QoSPolicyMask::DURABILITY_TRANSIENT_LOCAL)
3097 {
3098 self.durability = QoSDurabilityPolicy::Volatile;
3099 }
3100 if matches!(self.durability, QoSDurabilityPolicy::Volatile)
3101 && !supported.contains(QoSPolicyMask::DURABILITY_VOLATILE)
3102 {
3103 self.durability = QoSDurabilityPolicy::SystemDefault;
3104 }
3105 }
3106 if fields.liveliness {
3107 if matches!(
3108 self.liveliness_kind,
3109 QoSLivelinessPolicy::ManualByTopic | QoSLivelinessPolicy::ManualByNode
3110 ) && !supported.contains(match self.liveliness_kind {
3111 QoSLivelinessPolicy::ManualByNode => QoSPolicyMask::LIVELINESS_MANUAL_BY_NODE,
3112 _ => QoSPolicyMask::LIVELINESS_MANUAL_BY_TOPIC,
3113 }) {
3114 self.liveliness_kind = QoSLivelinessPolicy::Automatic;
3115 }
3116 if matches!(self.liveliness_kind, QoSLivelinessPolicy::Automatic)
3117 && !supported.contains(QoSPolicyMask::LIVELINESS_AUTOMATIC)
3118 {
3119 self.liveliness_kind = QoSLivelinessPolicy::None;
3120 }
3121 }
3122 if fields.deadline && self.deadline_ms != 0 && !supported.contains(QoSPolicyMask::DEADLINE)
3123 {
3124 self.deadline_ms = 0;
3125 }
3126 if fields.lease
3127 && self.liveliness_lease_ms != 0
3128 && !supported.contains(QoSPolicyMask::LIVELINESS_LEASE)
3129 {
3130 self.liveliness_lease_ms = 0;
3131 }
3132 if fields.lifespan && self.lifespan_ms != 0 && !supported.contains(QoSPolicyMask::LIFESPAN)
3133 {
3134 self.lifespan_ms = 0;
3135 }
3136 self
3137 }
3138}
3139
3140/// Which fields [`QoSProfile::step_down`] may touch.
3141#[derive(Debug, Clone, Copy)]
3142struct StepDownFields {
3143 reliability: bool,
3144 durability: bool,
3145 liveliness: bool,
3146 deadline: bool,
3147 lease: bool,
3148 lifespan: bool,
3149}
3150
3151impl StepDownFields {
3152 const ALL: Self = Self {
3153 reliability: true,
3154 durability: true,
3155 liveliness: true,
3156 deadline: true,
3157 lease: true,
3158 lifespan: true,
3159 };
3160}
3161
3162/// Which end of the graph a best-available profile is resolved for — issue
3163/// 1973. See [`QoSProfile::resolve_best_available`].
3164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3165pub enum BestAvailableRole {
3166 /// A publisher; resolved against the topic's discovered SUBSCRIPTIONS.
3167 Publisher,
3168 /// A subscription; resolved against the topic's discovered PUBLISHERS.
3169 Subscription,
3170 /// A service server or client; resolved to
3171 /// `rmw_qos_profile_services_default`, never against the graph.
3172 Service,
3173}
3174
3175/// The discovered peers of one topic, folded down to what
3176/// [`QoSProfile::resolve_best_available`] reads.
3177///
3178/// A fold rather than a list so a graph walk can feed it one endpoint at a
3179/// time, with no allocator and no bound on how many endpoints there are.
3180#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3181pub struct BestAvailablePeers {
3182 /// Peers observed.
3183 pub count: usize,
3184 /// …of which RELIABLE.
3185 pub reliable: usize,
3186 /// …of which TRANSIENT_LOCAL.
3187 pub transient_local: usize,
3188 /// …of which MANUAL_BY_TOPIC.
3189 pub manual_by_topic: usize,
3190 /// Smallest finite deadline seen, ms; `0` when none was finite.
3191 pub deadline_min: u32,
3192 /// Largest finite deadline seen, ms; `0` when none was finite.
3193 pub deadline_max: u32,
3194 /// Smallest finite liveliness lease seen, ms; `0` when none was finite.
3195 pub lease_min: u32,
3196 /// Largest finite liveliness lease seen, ms; `0` when none was finite.
3197 pub lease_max: u32,
3198}
3199
3200impl BestAvailablePeers {
3201 /// No peers — what a backend with no graph reports.
3202 pub const NONE: Self = Self {
3203 count: 0,
3204 reliable: 0,
3205 transient_local: 0,
3206 manual_by_topic: 0,
3207 deadline_min: 0,
3208 deadline_max: 0,
3209 lease_min: 0,
3210 lease_max: 0,
3211 };
3212
3213 /// Fold one discovered endpoint's profile in.
3214 ///
3215 /// `0`, [`DURATION_INFINITE_MS`] and the best-available sentinel all read
3216 /// as "no finite window" — upstream's `RMW_QOS_DEADLINE_DEFAULT`
3217 /// comparison, widened to our two spellings of infinite.
3218 pub fn observe(&mut self, peer: &QoSProfile) {
3219 self.count += 1;
3220 if matches!(peer.reliability, QoSReliabilityPolicy::Reliable) {
3221 self.reliable += 1;
3222 }
3223 if matches!(peer.durability, QoSDurabilityPolicy::TransientLocal) {
3224 self.transient_local += 1;
3225 }
3226 if matches!(peer.liveliness_kind, QoSLivelinessPolicy::ManualByTopic) {
3227 self.manual_by_topic += 1;
3228 }
3229 fn finite(ms: u32) -> Option<u32> {
3230 (ms != 0 && ms < DURATION_BEST_AVAILABLE_MS).then_some(ms)
3231 }
3232 fn fold(min: &mut u32, max: &mut u32, v: Option<u32>) {
3233 if let Some(v) = v {
3234 *min = if *min == 0 { v } else { (*min).min(v) };
3235 *max = (*max).max(v);
3236 }
3237 }
3238 fold(
3239 &mut self.deadline_min,
3240 &mut self.deadline_max,
3241 finite(peer.deadline_ms),
3242 );
3243 fold(
3244 &mut self.lease_min,
3245 &mut self.lease_max,
3246 finite(peer.liveliness_lease_ms),
3247 );
3248 }
3249}
3250
3251/// Resolve `qos`'s best-available fields against what `session` has
3252/// discovered on `topic_name`. The graph half of
3253/// [`QoSProfile::resolve_best_available`], shared by every create path.
3254///
3255/// Queries [`Session::get_endpoint_info_by_topic`] for the OTHER side of the
3256/// topic (subscriptions for a publisher, publishers for a subscription) and
3257/// folds each endpoint's [`GraphEndpointInfo::qos`]. A backend that cannot
3258/// answer — `Unsupported`, or any error from the walk — is treated as having
3259/// discovered nothing, which resolves to upstream's documented
3260/// nothing-discovered profile rather than to a guess. A
3261/// [`BestAvailableRole::Service`] never walks the graph.
3262///
3263/// Returns `qos` unchanged when nothing in it is best-available, so it is
3264/// free to call on every create.
3265pub fn resolve_best_available_on<S: Session + ?Sized>(
3266 session: &mut S,
3267 role: BestAvailableRole,
3268 topic_name: &str,
3269 qos: QoSProfile,
3270) -> QoSProfile
3271where
3272 S::Error: From<TransportError>,
3273{
3274 if !qos.has_best_available() {
3275 return qos;
3276 }
3277 let mut peers = BestAvailablePeers::NONE;
3278 let publishers = match role {
3279 BestAvailableRole::Publisher => Some(false),
3280 BestAvailableRole::Subscription => Some(true),
3281 BestAvailableRole::Service => None,
3282 };
3283 if let Some(publishers) = publishers {
3284 let mut walked = BestAvailablePeers::NONE;
3285 let ok = session
3286 .get_endpoint_info_by_topic(publishers, topic_name, &mut |info| {
3287 walked.observe(&info.qos);
3288 true
3289 })
3290 .is_ok();
3291 if ok {
3292 peers = walked;
3293 }
3294 }
3295 let supported = session.supported_qos_policies();
3296 qos.resolve_best_available(role, &peers, supported)
3297}
3298
3299/// Publisher trait for sending messages.
3300///
3301/// The name is rclrs's, the role is the backend seam: rclrs's `Publisher<T>` is a
3302/// typed, shared handle (`Arc<PublisherState<T>>`); this trait is what an RMW
3303/// backend implements, raw bytes in. The typed handle a node hands an application
3304/// is one type with no `Arc` (`nros::EmbeddedPublisher<M>`). Loaning exists:
3305/// `EmbeddedRawPublisher::try_loan` / `loan`, zero-copy through `SlotLending`
3306/// when the `lending` feature is on and the backend supports it.
3307///
3308/// # Threading
3309///
3310/// `&self` on `publish_raw` — implementors must allow concurrent
3311/// publishes from multiple threads. Internal locking (or lock-free
3312/// queues) is the backend's responsibility.
3313///
3314/// # Buffer ownership
3315///
3316/// `data` in `publish_raw` is borrowed for the duration of the call.
3317/// The backend must either send it inline or copy into its own
3318/// buffer before returning — the slice is invalid after the call.
3319///
3320/// # Blocking
3321///
3322/// `publish_raw` is expected to be non-blocking on best-effort QoS
3323/// and bounded-blocking on reliable QoS (waiting for outbound queue
3324/// space). Backends should *not* block waiting for ack from a
3325/// matched subscriber.
3326pub trait Publisher {
3327 /// Error type for publish operations
3328 type Error;
3329
3330 /// Publish a CDR-serialised message.
3331 ///
3332 /// Returns once the message has been handed to the transport
3333 /// (queued or fired-and-forgotten depending on QoS). Does **not**
3334 /// wait for delivery.
3335 fn publish_raw(&self, data: &[u8]) -> Result<(), Self::Error>;
3336
3337 /// Phase 128.F.4 — publish with an opaque attachment block.
3338 ///
3339 /// `attachment` rides alongside the payload at the wire layer.
3340 /// Receivers can read it back via
3341 /// [`Subscription::take_serialized_with_attachment`].
3342 ///
3343 /// Primary use case: cross-RMW bridges stamp a bridge_origin
3344 /// tag (the source backend's RMW name) so a paired return
3345 /// bridge can deterministically drop echoed frames.
3346 ///
3347 /// Default body delegates to [`publish_raw`](Self::publish_raw)
3348 /// and discards the attachment — backends that do not natively
3349 /// carry attachments (XRCE today, DDS without a user-data hook)
3350 /// see no change. Backends with native attachment support
3351 /// (zenoh-pico's `z_publisher_put_options::attachment`,
3352 /// Cyclone DDS user-data) override to write the bytes onto the
3353 /// wire.
3354 fn publish_raw_with_attachment(
3355 &self,
3356 data: &[u8],
3357 _attachment: &[u8],
3358 ) -> Result<(), Self::Error> {
3359 self.publish_raw(data)
3360 }
3361
3362 /// Phase 124.E.1 — streamed publish.
3363 ///
3364 /// `size_cb` reports the total payload length once; `chunk_cb`
3365 /// fills the slot in chunks. What it saves is the CALLER-side
3366 /// buffer holding a whole serialised message — which is STACK,
3367 /// not `.bss`: `EmbeddedPublisher::publish` serialises into a
3368 /// per-CALL array of `DEFAULT_TX_BUF`, and this trait's own
3369 /// fallback below stages on the caller's stack too. There is no
3370 /// per-publisher staging buffer and none of it is in `.bss`;
3371 /// issue 0782 corrected that fiction on the C slot and left this
3372 /// copy of it standing (phase-428 W12's F2, one layer over).
3373 ///
3374 /// Default body — the **staging-buffer fallback** (124.E.2).
3375 /// Asks `size_cb` for the total length, fills a stack-allocated
3376 /// `[u8; STAGE_CAP]` via `chunk_cb`, then forwards to
3377 /// `publish_raw`. `STAGE_CAP` is the 4096 constant declared in
3378 /// the body, not a knob: this said `NROS_MAX_STREAM_CHUNK` until
3379 /// 2026-09-12 and no such setting has ever existed in any form,
3380 /// so a reader looking for it found nothing and had no way to
3381 /// learn the limit. Returns `Err(BufferTooSmall)` if the total
3382 /// exceeds that cap so the caller can drop back to a regular
3383 /// `publish_raw` with a heap-sized buffer.
3384 ///
3385 /// Concrete backends opt in by overriding to stream straight
3386 /// into the network buffer (zenoh: write into the zenoh-pico
3387 /// outbound buffer; XRCE: micro-CDR streaming APIs).
3388 ///
3389 /// # Safety
3390 ///
3391 /// The caller must ensure `user_ctx` is valid for every invocation of
3392 /// `size_cb` and `chunk_cb` during this call, and that both callbacks obey
3393 /// their out-pointer contracts.
3394 ///
3395 /// `size_cb` and `chunk_cb` may be called from the same thread
3396 /// that called `publish_streamed`. Backends MUST NOT defer the
3397 /// calls past the function return; the caller's `user_ctx`
3398 /// pointer is only guaranteed valid for the duration of the
3399 /// call.
3400 unsafe fn publish_streamed(
3401 &self,
3402 size_cb: unsafe extern "C" fn(out_total_len: *mut usize, user_ctx: *mut core::ffi::c_void),
3403 chunk_cb: unsafe extern "C" fn(
3404 out_buf: *mut u8,
3405 cap: usize,
3406 out_written: *mut usize,
3407 user_ctx: *mut core::ffi::c_void,
3408 ),
3409 user_ctx: *mut core::ffi::c_void,
3410 ) -> Result<(), Self::Error>
3411 where
3412 Self::Error: From<TransportError>,
3413 {
3414 /// Default staging-buffer cap. Stack-allocated, so embedded
3415 /// callers don't pay for it unless they actually invoke this
3416 /// fallback. 4 KiB matches typical RTPS frag-size +
3417 /// micro-XRCE message ceilings.
3418 const STAGE_CAP: usize = 4096;
3419
3420 let mut total = 0usize;
3421 // SAFETY: caller's contract on `size_cb` matches our trait
3422 // doc — fire once with a writable `*mut usize` slot.
3423 unsafe { size_cb(&mut total as *mut usize, user_ctx) };
3424 if total > STAGE_CAP {
3425 return Err(TransportError::BufferTooSmall.into());
3426 }
3427 let mut stage = [0u8; STAGE_CAP];
3428 let mut written_so_far = 0usize;
3429 while written_so_far < total {
3430 let mut chunk_written = 0usize;
3431 let remaining = total - written_so_far;
3432 // SAFETY: `chunk_cb` writes ≤ `cap` bytes to
3433 // `out_buf` and reports the count via `out_written`.
3434 unsafe {
3435 chunk_cb(
3436 stage.as_mut_ptr().add(written_so_far),
3437 remaining,
3438 &mut chunk_written as *mut usize,
3439 user_ctx,
3440 );
3441 }
3442 if chunk_written == 0 {
3443 // Caller signalled EOF early — treat the partial
3444 // write as a malformed sequence; reporting it as
3445 // BufferTooSmall keeps the surface tight without
3446 // adding a new variant.
3447 return Err(TransportError::BufferTooSmall.into());
3448 }
3449 written_so_far += chunk_written;
3450 }
3451 self.publish_raw(&stage[..total])
3452 }
3453
3454 /// Publish a typed message (serializes automatically)
3455 fn publish<M: RosMessage>(&self, msg: &M, buf: &mut [u8]) -> Result<(), Self::Error> {
3456 use nros_core::CdrWriter;
3457
3458 let mut writer = CdrWriter::new_with_header(buf).map_err(|_| self.buffer_error())?;
3459 msg.serialize(&mut writer)
3460 .map_err(|_| self.serialization_error())?;
3461 let len = writer.position();
3462 self.publish_raw(&buf[..len])
3463 }
3464
3465 /// Return a buffer-too-small error (implementation specific)
3466 fn buffer_error(&self) -> Self::Error;
3467
3468 /// Return a serialization error (implementation specific)
3469 fn serialization_error(&self) -> Self::Error;
3470
3471 /// Phase 108 — `true` if the backend can generate this event for
3472 /// this publisher. Default returns `false`; backends override per
3473 /// supported event kind.
3474 ///
3475 /// Only [`EventKind::LivelinessLost`](crate::event::EventKind::LivelinessLost) and
3476 /// [`EventKind::OfferedDeadlineMissed`](crate::event::EventKind::OfferedDeadlineMissed) are publisher-side events;
3477 /// other kinds always return `false` here.
3478 fn supports_event(&self, _kind: crate::event::EventKind) -> bool {
3479 false
3480 }
3481
3482 /// Phase 108 — register a callback fired when the named status
3483 /// event occurs. `deadline_ms` applies to
3484 /// [`EventKind::OfferedDeadlineMissed`](crate::event::EventKind::OfferedDeadlineMissed) only; ignored otherwise.
3485 /// Default impl returns the backend's "unsupported"-shaped error.
3486 ///
3487 /// # Safety
3488 ///
3489 /// `cb` and `user_ctx` must remain valid for the entity's
3490 /// lifetime. Caller (typically `nros-node`'s typed wrapper) is
3491 /// responsible for keeping the closure / context arena alive.
3492 unsafe fn register_event_callback(
3493 &mut self,
3494 _kind: crate::event::EventKind,
3495 _deadline_ms: u32,
3496 _cb: crate::event::EventCallback,
3497 _user_ctx: *mut core::ffi::c_void,
3498 ) -> Result<(), Self::Error> {
3499 Err(self.unsupported_event_error())
3500 }
3501
3502 /// Phase 108 — backend's error variant for "this event kind is
3503 /// not supported." Default impl reuses `serialization_error()`
3504 /// since most backends share an `Unsupported` variant; backends
3505 /// override if they have a distinct `Unsupported` mapping.
3506 fn unsupported_event_error(&self) -> Self::Error {
3507 self.serialization_error()
3508 }
3509
3510 /// Phase 109 — assert this publisher's liveliness manually.
3511 /// Required for publishers configured with
3512 /// [`QoSLivelinessPolicy::ManualByTopic`] / [`ManualByNode`](QoSLivelinessPolicy::ManualByNode);
3513 /// nothing to do for the other kinds.
3514 ///
3515 /// **`Ok(())` MEANS THE ASSERTION REACHED THE WIRE, or that there was
3516 /// nothing to assert** (the phase-467 RMW gap-closure design study's
3517 /// Row 7). Under a kind for which [`QoSLivelinessPolicy::is_manual`]
3518 /// holds, a backend that cannot renew a lease a PEER can observe must
3519 /// answer `Unsupported` — an `Ok(())` from a call that sent nothing is
3520 /// the silently-wrong shape RFC-0089 Part I refuses, and it is what the
3521 /// zenoh shim answered until this study. A backend is free to keep a
3522 /// LOCAL record of the call (zenoh drives its own `LivelinessLost`
3523 /// watchdog off one) and still report `Unsupported`; the return value is
3524 /// about what a peer can see, not about what we noted down.
3525 ///
3526 /// The default body is `Ok(())`, which is correct only for a publisher
3527 /// whose kind is not manual — a backend that can be created with a manual
3528 /// kind must override.
3529 fn assert_liveliness(&self) -> Result<(), Self::Error> {
3530 Ok(())
3531 }
3532
3533 /// This publisher's own global identifier — upstream
3534 /// `rmw_get_gid_for_publisher`, the vtable's `get_gid_for_publisher`.
3535 ///
3536 /// The phase-467 RMW gap-closure design study's Q1. **Not the same
3537 /// question as [`MessageInfo::publisher_gid`](nros_core::MessageInfo::publisher_gid)**,
3538 /// which is the identity of whoever sent a message we RECEIVED. Since
3539 /// that study's Q1(a) the two are one TYPE — both
3540 /// [`PUBLISHER_GID_SIZE`](nros_core::PUBLISHER_GID_SIZE) wide, nothing
3541 /// truncated, no mapping — and since issue 1495 they are one VALUE on
3542 /// zenoh and Cyclone: a take reports the gid this publisher's own
3543 /// `get_gid` reports, so the two compare. (XRCE answers `get_gid` — the
3544 /// DDS GID its graph derives, issue 2110 — but reports no take-side gid;
3545 /// uORB answers neither.)
3546 ///
3547 /// **How many of the 24 bytes MEAN anything is a backend property.** A
3548 /// backend whose identity is narrower zero-extends through
3549 /// [`pad_publisher_gid`](nros_core::pad_publisher_gid) rather than
3550 /// leaving the tail undefined, so two gids naming one entity compare
3551 /// equal. Gids from DIFFERENT backends are never comparable.
3552 ///
3553 /// The default is `Err(Unsupported)`, never a fabricated or all-zero id:
3554 /// an all-zero gid is what an unwritten buffer holds, so handing one back
3555 /// would make "this backend has no identity for this publisher"
3556 /// indistinguishable from an answer. That is the same NULL-slot
3557 /// discipline the ABI header states for `get_serialization_format`.
3558 fn get_gid(&self) -> Result<[u8; nros_core::PUBLISHER_GID_SIZE], Self::Error>
3559 where
3560 Self::Error: From<TransportError>,
3561 {
3562 Err(TransportError::Unsupported.into())
3563 }
3564
3565 /// How many subscriptions are MATCHED to this publisher — upstream
3566 /// `rmw_publisher_count_matched_subscriptions`, the vtable's
3567 /// `publisher_count_matched_subscriptions`. Issue 1643.
3568 ///
3569 /// Matched means QoS-compatible with THIS publisher, which is upstream's
3570 /// question and a stronger one than "how many subscriptions are on the
3571 /// topic" (the graph's `count_subscribers`): an incompatible peer is on
3572 /// the topic and not matched.
3573 ///
3574 /// The default is `Err(Unsupported)`, never `Ok(0)` — `0` means "nobody
3575 /// is listening", and a backend that cannot tell must not say that. A
3576 /// caller with a weaker fallback (the node API's topic-wide graph count)
3577 /// takes it on `Unsupported`.
3578 fn count_matched_subscriptions(&self) -> Result<usize, Self::Error>
3579 where
3580 Self::Error: From<TransportError>,
3581 {
3582 Err(TransportError::Unsupported.into())
3583 }
3584
3585 /// The profile this entity is ACTUALLY running — what the backend GRANTED,
3586 /// not what the call site requested.
3587 ///
3588 /// Upstream's `rmw_publisher_get_actual_qos`. The two differ whenever a
3589 /// backend serves something other than what it was asked for, and the
3590 /// difference is exactly what answers "why is nothing arriving": a
3591 /// RELIABLE reader does not match a BEST_EFFORT writer, and a clamped
3592 /// history depth drops samples the caller believed were kept.
3593 ///
3594 /// **Per-field, and an unreportable field is an ABSENCE.** A backend that
3595 /// determines four policies and not the fifth returns the four and leaves
3596 /// the fifth at its `Unknown` variant. Never echo the request into a field
3597 /// you did not read back — that is the inverse of this method's meaning,
3598 /// and it is what the six C-ABI slots did until this phase.
3599 ///
3600 /// The default is [`QoSProfile::QOS_PROFILE_UNKNOWN`] — every field an
3601 /// absence — which is the honest answer for a backend with no read-back at
3602 /// all (XRCE has none; zenoh-pico's QoS is per-message flags). It is NOT
3603 /// the request, and it is NOT `QOS_PROFILE_DEFAULT`.
3604 fn actual_qos(&self) -> QoSProfile {
3605 QoSProfile::QOS_PROFILE_UNKNOWN
3606 }
3607}
3608
3609/// Subscription trait for receiving messages.
3610///
3611/// # Threading
3612///
3613/// `&mut self` on `take_serialized` — the executor takes exclusive
3614/// ownership of the subscriber for the duration of a receive. A
3615/// backend that wants to allow concurrent receives must split into
3616/// per-thread sub-handles internally.
3617///
3618/// # Buffer ownership
3619///
3620/// `buf` is caller-owned. The implementation copies the next ready
3621/// message into `buf` and returns the byte count. The caller may
3622/// re-use or drop `buf` immediately after the call.
3623///
3624/// # Blocking
3625///
3626/// `take_serialized` is **non-blocking**: returns `Ok(None)` (or
3627/// equivalent for backends that map empty into a zero-length read)
3628/// when no message is ready. Use [`Session::drive_io`] to wait for
3629/// data; never sleep inside `take_serialized`.
3630/// What [`Subscription::take_serialized_with_info_and_attachment`] returns
3631/// for one sample: `(payload_len, info, attachment_len)`.
3632pub type TakenWithInfoAndAttachment = (usize, Option<nros_core::MessageInfo>, usize);
3633
3634pub trait Subscription {
3635 /// Error type for receive operations
3636 type Error;
3637
3638 /// Check if data is available without consuming it.
3639 ///
3640 /// Non-destructive — does not advance the receive cursor.
3641 /// Conservative default returns `true` (always assume data may
3642 /// be available); backends should override with a real check
3643 /// to avoid spurious receive attempts.
3644 fn has_data(&self) -> bool {
3645 true
3646 }
3647
3648 /// Try to receive one message into `buf`.
3649 ///
3650 /// Non-blocking. On success returns `Ok(Some(len))` where `len`
3651 /// is the byte count written into `buf[..len]`. Returns
3652 /// `Ok(None)` if no message is ready. If `buf` is too small the
3653 /// backend may either truncate (and document it) or return an
3654 /// error (preferred).
3655 fn take_serialized(&mut self, buf: &mut [u8]) -> Result<Option<usize>, Self::Error>;
3656
3657 /// Issue 1612 — how many bytes the sample the most recent take REFUSED
3658 /// as too big for the caller's buffer needed.
3659 ///
3660 /// Read it right after a take returns `BufferTooSmall`; a later take may
3661 /// overwrite it. `None` means the backend does not know the size (the
3662 /// default, and the honest answer for one that never measured it), never
3663 /// "zero bytes" — a zero-byte sample fits every buffer, so no refusal can
3664 /// need zero.
3665 ///
3666 /// A query beside the error rather than a payload on
3667 /// `TransportError::BufferTooSmall`: that variant is the same word a dozen
3668 /// unrelated paths return (arena exhaustion, a short reply buffer), so
3669 /// giving it a field would make every one of them invent a size. Only a
3670 /// take ever has one, and only a take is asked.
3671 fn refused_sample_len(&self) -> Option<usize> {
3672 None
3673 }
3674
3675 /// Phase 128.F.4 — receive with attachment bytes alongside the
3676 /// payload.
3677 ///
3678 /// On success returns `Ok(Some((payload_len, attachment_len)))`
3679 /// with the payload written into `buf[..payload_len]` and the
3680 /// attachment (if any) written into
3681 /// `att_buf[..attachment_len]`. `attachment_len == 0` means the
3682 /// incoming sample carried no attachment.
3683 ///
3684 /// Default body falls back to [`take_serialized`](Self::take_serialized)
3685 /// and reports a 0-length attachment. Backends with native
3686 /// attachment support override to populate `att_buf`. Cross-RMW
3687 /// bridges use the attachment to read the bridge_origin tag
3688 /// stamped by the sending side.
3689 fn take_serialized_with_attachment(
3690 &mut self,
3691 buf: &mut [u8],
3692 _att_buf: &mut [u8],
3693 ) -> Result<Option<(usize, usize)>, Self::Error> {
3694 match self.take_serialized(buf)? {
3695 Some(len) => Ok(Some((len, 0))),
3696 None => Ok(None),
3697 }
3698 }
3699
3700 /// Receive one sample with BOTH its metadata and its attachment.
3701 ///
3702 /// On success returns `Ok(Some((payload_len, info, attachment_len)))`:
3703 /// the payload in `buf[..payload_len]`, the attachment in
3704 /// `att_buf[..attachment_len]` (`0` = none), and `info` as
3705 /// [`take_serialized_with_info`](Self::take_serialized_with_info) reports
3706 /// it (`None` from a backend that reports no metadata).
3707 ///
3708 /// One take, so the metadata and the attachment describe the same
3709 /// sample. Two separate takes would consume two samples.
3710 ///
3711 /// The default makes the metadata take and reports no attachment. That
3712 /// loses nothing today: no backend delivers an attachment (none overrides
3713 /// [`take_serialized_with_attachment`](Self::take_serialized_with_attachment),
3714 /// and the C vtable has no attachment slot), while every backend that
3715 /// reports metadata implements `take_serialized_with_info`. A backend that
3716 /// carries both overrides this. Issue 2712: the attachment-only take this
3717 /// replaces on the generic `.message_info()` path left every metadata
3718 /// field at zero.
3719 fn take_serialized_with_info_and_attachment(
3720 &mut self,
3721 buf: &mut [u8],
3722 _att_buf: &mut [u8],
3723 ) -> Result<Option<TakenWithInfoAndAttachment>, Self::Error> {
3724 self.take_serialized_with_info(buf)
3725 .map(|opt| opt.map(|(len, info)| (len, info, 0)))
3726 }
3727
3728 /// Phase 124.D.1 — burst-take.
3729 ///
3730 /// Drain up to `max_msgs` queued samples into the contiguous
3731 /// `buf` block in one call, with the i-th sample at
3732 /// `buf[i * per_msg_cap .. i * per_msg_cap + out_lens[i]]`.
3733 /// Returns the number of messages actually delivered. Partial
3734 /// drains MUST report the count, not error out.
3735 ///
3736 /// Default body loop-drives `take_serialized` so callers can
3737 /// commit to the batched API regardless of backend support.
3738 /// Concrete backends opt in by overriding with a native batch
3739 /// take (zenoh queue drain, `dds_take(max_samples)`).
3740 fn take_sequence(
3741 &mut self,
3742 buf: &mut [u8],
3743 per_msg_cap: usize,
3744 max_msgs: usize,
3745 out_lens: &mut [usize],
3746 ) -> Result<usize, Self::Error> {
3747 if per_msg_cap == 0 || max_msgs == 0 {
3748 return Ok(0);
3749 }
3750 let limit = max_msgs.min(out_lens.len());
3751 let mut count = 0;
3752 for i in 0..limit {
3753 let slot = &mut buf[i * per_msg_cap..(i + 1) * per_msg_cap];
3754 // Issue 0971 — NOT `take_serialized(slot)?`. The `?` propagates the
3755 // error and DISCARDS `count`, which is precisely what the doc
3756 // comment above forbids ("Partial drains MUST report the count, not
3757 // error out") and what `c3af8c1d1` removed from the two concrete
3758 // implementations. A backend that does not override this body got
3759 // the original defect back through the default.
3760 //
3761 // The shape is the one that fix established: a drain that has
3762 // already taken messages reports the COUNT, and the error is
3763 // delivered by the NEXT call — the caller sees every message it was
3764 // handed, then the reason the drain stopped. With nothing taken
3765 // there is no count to protect, so the error goes out immediately.
3766 //
3767 // Parking is per-implementation state, which a default body has no
3768 // place to keep. So it does the half it can do correctly: it
3769 // returns the partial count and lets the error surface on the
3770 // caller's next `take_serialized`, which is where an unconsumed
3771 // backend error still sits.
3772 match self.take_serialized(slot) {
3773 Ok(Some(len)) => {
3774 out_lens[i] = len;
3775 count += 1;
3776 }
3777 Ok(None) => break,
3778 Err(e) => {
3779 if count == 0 {
3780 return Err(e);
3781 }
3782 break;
3783 }
3784 }
3785 }
3786 Ok(count)
3787 }
3788
3789 /// Try to receive a typed message (non-blocking)
3790 fn take<M: RosMessage>(&mut self, buf: &mut [u8]) -> Result<Option<M>, Self::Error> {
3791 use nros_core::CdrReader;
3792
3793 match self.take_serialized(buf)? {
3794 Some(len) => {
3795 let mut reader = CdrReader::new_with_header(&buf[..len])
3796 .map_err(|_| self.deserialization_error())?;
3797 let msg = M::deserialize(&mut reader).map_err(|_| self.deserialization_error())?;
3798 Ok(Some(msg))
3799 }
3800 None => Ok(None),
3801 }
3802 }
3803
3804 /// Process the received message in-place without copying.
3805 ///
3806 /// Calls `f` with a reference to the raw CDR bytes in the subscriber's
3807 /// internal receive buffer, avoiding a copy into a caller-provided buffer.
3808 /// While `f` executes the buffer is exclusively borrowed — any messages
3809 /// arriving from the transport during that time are dropped to prevent
3810 /// data races.
3811 ///
3812 /// Returns `Ok(true)` if a message was available and `f` was called,
3813 /// `Ok(false)` if no message was available.
3814 ///
3815 /// **Default body**: returns `Err(MessageTooLarge)` — the old default
3816 /// silently truncated anything larger than 1 KB into a stack buffer,
3817 /// which broke large messages with no diagnostic. Backends must
3818 /// override this with a real zero-copy path if they advertise support
3819 /// for `process_raw_in_place`; callers that hit the default should
3820 /// use `take_serialized` with a caller-sized buffer instead.
3821 fn process_raw_in_place(&mut self, f: impl FnOnce(&[u8])) -> Result<bool, Self::Error>
3822 where
3823 Self::Error: From<TransportError>,
3824 {
3825 let _ = f;
3826 Err(TransportError::MessageTooLarge.into())
3827 }
3828
3829 /// Whether this backend implements the in-place dispatch methods
3830 /// ([`process_raw_in_place`](Subscription::process_raw_in_place) /
3831 /// [`process_raw_in_place_with_info`](Subscription::process_raw_in_place_with_info))
3832 /// with a real zero-copy borrow.
3833 ///
3834 /// The executor consults this at subscription registration to choose the
3835 /// **in-place** arena dispatch (borrow + deserialize from the backend slot, no
3836 /// arena buffer) over the **buffered** dispatch (copy into an arena buffer
3837 /// first). Backends that leave the in-place methods at their unsupported
3838 /// default return `false` (the default) and keep the buffered path. (RFC-0038,
3839 /// Phase 231 Wave 0.2.)
3840 fn supports_process_in_place(&self) -> bool {
3841 false
3842 }
3843
3844 /// In-place processing variant that also surfaces publisher metadata.
3845 ///
3846 /// Same borrow contract as
3847 /// [`process_raw_in_place`](Subscription::process_raw_in_place): `f` receives
3848 /// the raw CDR bytes plus the parsed [`MessageInfo`](nros_core::MessageInfo)
3849 /// — the co-located attachment (publisher GID / sequence / source timestamp),
3850 /// or `None` when no attachment was present — for the duration of the call;
3851 /// the slot is released after `f` returns. `Ok(true)` = a message was
3852 /// available and `f` was called; `Ok(false)` = none ready.
3853 ///
3854 /// **Default body**: returns the unsupported error (mirrors
3855 /// `process_raw_in_place`). Backends that advertise in-place support override
3856 /// this with a real zero-copy path; callers that hit the default should use
3857 /// the buffered [`take_serialized_with_info`](Subscription::take_serialized_with_info)
3858 /// path instead. (RFC-0038, Phase 231 Wave 0.1.)
3859 fn process_raw_in_place_with_info(
3860 &mut self,
3861 f: impl FnOnce(&[u8], Option<nros_core::MessageInfo>),
3862 ) -> Result<bool, Self::Error>
3863 where
3864 Self::Error: From<TransportError>,
3865 {
3866 let _ = f;
3867 Err(TransportError::MessageTooLarge.into())
3868 }
3869
3870 /// Try to receive raw data along with publisher metadata.
3871 ///
3872 /// When available, [`MessageInfo`](nros_core::MessageInfo) contains
3873 /// the publisher's GID (Global Identifier) and source timestamp,
3874 /// extracted from a transport-level attachment on the incoming message.
3875 ///
3876 /// Returns `Ok(Some((len, info)))` if data is available, where:
3877 /// - `len` is the number of bytes written to the buffer
3878 /// - `info` is the parsed publisher metadata (if attachment was present)
3879 ///
3880 /// Default: delegates to [`take_serialized`](Subscription::take_serialized) with no info.
3881 fn take_serialized_with_info(
3882 &mut self,
3883 buf: &mut [u8],
3884 ) -> Result<Option<(usize, Option<nros_core::MessageInfo>)>, Self::Error> {
3885 self.take_serialized(buf)
3886 .map(|opt| opt.map(|len| (len, None)))
3887 }
3888
3889 /// Try to receive raw data with E2E safety validation (CRC + sequence tracking).
3890 ///
3891 /// Returns `Ok(Some((len, status)))` if data is available, where:
3892 /// - `len` is the number of bytes written to the buffer
3893 /// - `status` is the integrity validation result
3894 ///
3895 /// Default: delegates to `take_serialized` with no CRC info.
3896 #[cfg(feature = "safety-e2e")]
3897 fn take_validated(
3898 &mut self,
3899 buf: &mut [u8],
3900 ) -> Result<Option<(usize, crate::IntegrityStatus)>, Self::Error> {
3901 self.take_serialized(buf).map(|opt| {
3902 opt.map(|len| {
3903 (
3904 len,
3905 crate::IntegrityStatus {
3906 gap: 0,
3907 duplicate: false,
3908 crc_valid: None,
3909 },
3910 )
3911 })
3912 })
3913 }
3914
3915 /// Register an async waker to be notified when data arrives.
3916 ///
3917 /// Called from `Future::poll()` implementations to store the waker.
3918 /// The transport backend calls `waker.wake()` from its receive callback
3919 /// when new data is available, enabling event-driven async without
3920 /// busy-polling.
3921 ///
3922 /// Returns `true` when the backend will wake `waker` on an arrival, and
3923 /// `false` when it cannot (issue 1940): the caller must then poll, or
3924 /// rely on the session-wide wake, and a C caller reports
3925 /// `RCL_RET_UNSUPPORTED` rather than `OK`.
3926 ///
3927 /// Default: `false` — a backend that writes no code cannot wake anyone.
3928 fn register_waker(&self, _waker: &core::task::Waker) -> bool {
3929 false
3930 }
3931
3932 /// Return a deserialization error (implementation specific)
3933 fn deserialization_error(&self) -> Self::Error;
3934
3935 /// Phase 108 — `true` if the backend can generate this event for
3936 /// this subscriber. Default returns `false`; backends override per
3937 /// supported event kind.
3938 ///
3939 /// Subscription-side event kinds:
3940 /// [`EventKind::LivelinessChanged`](crate::event::EventKind::LivelinessChanged),
3941 /// [`EventKind::RequestedDeadlineMissed`](crate::event::EventKind::RequestedDeadlineMissed),
3942 /// [`EventKind::MessageLost`](crate::event::EventKind::MessageLost).
3943 /// Publisher kinds always return `false` here.
3944 fn supports_event(&self, _kind: crate::event::EventKind) -> bool {
3945 false
3946 }
3947
3948 /// Phase 108 — register a callback fired when the named status
3949 /// event occurs. `deadline_ms` applies to
3950 /// [`EventKind::RequestedDeadlineMissed`](crate::event::EventKind::RequestedDeadlineMissed) only; ignored otherwise.
3951 /// Default impl returns the backend's "unsupported"-shaped error.
3952 ///
3953 /// # Safety
3954 ///
3955 /// `cb` and `user_ctx` must remain valid for the entity's
3956 /// lifetime. Caller (typically `nros-node`'s typed wrapper) is
3957 /// responsible for keeping the closure / context arena alive.
3958 unsafe fn register_event_callback(
3959 &mut self,
3960 _kind: crate::event::EventKind,
3961 _deadline_ms: u32,
3962 _cb: crate::event::EventCallback,
3963 _user_ctx: *mut core::ffi::c_void,
3964 ) -> Result<(), Self::Error> {
3965 Err(self.unsupported_event_error())
3966 }
3967
3968 /// Phase 108 — backend's error variant for "this event kind is
3969 /// not supported." Default reuses `deserialization_error()` for
3970 /// backends that don't have a distinct `Unsupported` mapping.
3971 fn unsupported_event_error(&self) -> Self::Error {
3972 self.deserialization_error()
3973 }
3974 /// The profile this entity is ACTUALLY running — what the backend GRANTED,
3975 /// not what the call site requested.
3976 ///
3977 /// Upstream's `rmw_subscription_get_actual_qos`. The two differ whenever a
3978 /// backend serves something other than what it was asked for, and the
3979 /// difference is exactly what answers "why is nothing arriving": a
3980 /// RELIABLE reader does not match a BEST_EFFORT writer, and a clamped
3981 /// history depth drops samples the caller believed were kept.
3982 ///
3983 /// **Per-field, and an unreportable field is an ABSENCE.** A backend that
3984 /// determines four policies and not the fifth returns the four and leaves
3985 /// the fifth at its `Unknown` variant. Never echo the request into a field
3986 /// you did not read back — that is the inverse of this method's meaning,
3987 /// and it is what the six C-ABI slots did until this phase.
3988 ///
3989 /// The default is [`QoSProfile::QOS_PROFILE_UNKNOWN`] — every field an
3990 /// absence — which is the honest answer for a backend with no read-back at
3991 /// all (XRCE has none; zenoh-pico's QoS is per-message flags). It is NOT
3992 /// the request, and it is NOT `QOS_PROFILE_DEFAULT`.
3993 fn actual_qos(&self) -> QoSProfile {
3994 QoSProfile::QOS_PROFILE_UNKNOWN
3995 }
3996
3997 /// How many publishers are MATCHED to this subscription — upstream
3998 /// `rmw_subscription_count_matched_publishers`, the vtable's
3999 /// `subscription_count_matched_publishers`. Issue 1643.
4000 ///
4001 /// The subscription half of
4002 /// [`Publisher::count_matched_subscriptions`], which states the contract:
4003 /// matched, not merely discovered; `Err(Unsupported)` by default, never a
4004 /// fabricated `0`.
4005 fn count_matched_publishers(&self) -> Result<usize, Self::Error>
4006 where
4007 Self::Error: From<TransportError>,
4008 {
4009 Err(TransportError::Unsupported.into())
4010 }
4011}
4012
4013/// Service request from a client
4014pub struct ServiceRequest<'a> {
4015 /// Raw request data (CDR encoded)
4016 pub data: &'a [u8],
4017 /// Sequence number for request/response matching
4018 pub sequence_number: i64,
4019}
4020
4021// ============================================================================
4022// Phase 99 — zero-copy raw API: SlotLending / SlotBorrowing
4023// ============================================================================
4024//
4025// Backends that can lend a slot directly into their outbound buffer
4026// (zenoh-pico w/ unstable-zenoh-api, XRCE-DDS via uxr_prepare_output_stream,
4027// full DDS w/ SHM transport) implement these traits. Backends that cannot
4028// (uORB, default zenoh-pico) do NOT impl them — `EmbeddedRawPublisher` then
4029// falls back to its per-publisher arena and memcpys at commit time. Both
4030// paths land at `Publisher::publish_raw` for the actual wire write; only
4031// the user-side copy is eliminated when lending is available.
4032//
4033// Selection is **compile-time** via the `lending` Cargo feature. Each
4034// backend crate forwards its own `lending` feature to `nros-rmw/lending`
4035// when it can satisfy the trait. nros-node's `rmw-lending` aggregates.
4036// User opting `nros/rmw-lending` w/ a non-lending backend (e.g. uORB)
4037// gets a clear compile error from the unsatisfied trait bound on the
4038// concrete `RmwPublisher`.
4039
4040/// Backend can lend a writable slot into its outbound buffer.
4041///
4042/// The returned slot's lifetime is tied to `&self`; user fills it in
4043/// place, then calls [`commit_slot`](Self::commit_slot) to publish.
4044/// Dropping the slot without commit is a no-op (slot returned to free
4045/// pool); concurrent loan attempts that would exceed backend capacity
4046/// return [`TransportError::WouldBlock`] — never block.
4047#[cfg(feature = "lending")]
4048pub trait SlotLending: Publisher {
4049 /// Backend-owned writable slot. Holds a `&'a mut [u8]` and any
4050 /// state needed for commit_slot.
4051 type Slot<'a>: AsMut<[u8]> + 'a
4052 where
4053 Self: 'a;
4054
4055 /// Reserve a writable slot of `len` bytes from the backend's
4056 /// outbound buffer. Returns `Ok(None)` if the backend has no slot
4057 /// available (full); never blocks.
4058 fn try_lend_slot(&self, len: usize) -> Result<Option<Self::Slot<'_>>, Self::Error>;
4059
4060 /// Commit a previously-lent slot. Consumes the slot and triggers
4061 /// the actual wire write. Returns `Err` on backend send failure;
4062 /// the slot's bytes are lost in that case (caller must re-lend +
4063 /// re-fill to retry).
4064 fn commit_slot(&self, slot: Self::Slot<'_>) -> Result<(), Self::Error>;
4065}
4066
4067/// Backend can lend a read-only view into its receive buffer.
4068///
4069/// The returned view's lifetime is tied to `&mut self` (subscriber-
4070/// exclusive); dropping the view releases any backend lock and lets
4071/// the next message advance into the buffer.
4072#[cfg(feature = "lending")]
4073pub trait SlotBorrowing: Subscription {
4074 /// Backend-owned read-only view. Holds a `&'a [u8]` and any state
4075 /// needed to release the borrow on Drop.
4076 type View<'a>: AsRef<[u8]> + 'a
4077 where
4078 Self: 'a;
4079
4080 /// Try to borrow the next available message in place. Returns
4081 /// `Ok(None)` if no message is ready; never blocks.
4082 fn try_borrow(&mut self) -> Result<Option<Self::View<'_>>, Self::Error>;
4083}
4084
4085/// The size a refused take needed, as a drop log prints
4086/// it: the number, or `?` when unknown. No allocator.
4087///
4088/// [`RefusedLen::for_error`] is the one rule for WHICH refusal may carry a
4089/// size: only `BufferTooSmall`, the caller's-buffer refusal a take measures.
4090/// `MessageTooLarge` is the backend's own staging buffer refusing before any
4091/// take saw a length, so a size recorded by an earlier `BufferTooSmall` must
4092/// not be printed beside it. The C++ subscription drop log and `nros-node`'s
4093/// arena drop log both read it from here, so the two cannot disagree.
4094#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4095pub struct RefusedLen(pub Option<usize>);
4096
4097impl RefusedLen {
4098 /// The size `recorded` (a `refused_*_len()` reading) for `err`, or
4099 /// unknown when `err` is not a refusal a take measured.
4100 pub fn for_error(err: &TransportError, recorded: Option<usize>) -> Self {
4101 Self(match err {
4102 TransportError::BufferTooSmall => recorded,
4103 _ => None,
4104 })
4105 }
4106}
4107
4108impl core::fmt::Display for RefusedLen {
4109 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
4110 match self.0 {
4111 Some(n) => write!(f, "{n}"),
4112 None => f.write_str("?"),
4113 }
4114 }
4115}
4116
4117/// Service server trait for handling requests.
4118///
4119/// # Threading
4120///
4121/// `&mut self` on `take_request` and `send_response` — the executor
4122/// owns the server while a request is being handled. Handler bodies
4123/// run synchronously on the executor thread; long handlers should
4124/// dispatch work to a worker queue and reply later via the recorded
4125/// `sequence_number`.
4126///
4127/// # Calling pattern
4128///
4129/// 1. Executor calls `take_request(buf)`.
4130/// 2. If `Some(req)` returned, decode, run handler, encode reply.
4131/// 3. `send_response(req.sequence_number, &reply_buf)`.
4132///
4133/// `sequence_number` is the canonical request → reply correlation
4134/// token; backends derive it from the wire-level metadata (zenoh
4135/// query id, DDS sample identity).
4136pub trait ServiceTrait {
4137 /// Error type for service operations
4138 type Error;
4139
4140 /// Check if a request is available without consuming it.
4141 ///
4142 /// Non-destructive. Default returns `true` (always assume one
4143 /// may be available); backends should override with a real
4144 /// check.
4145 fn has_request(&self) -> bool {
4146 true
4147 }
4148
4149 /// Phase 122.3.c.6.e — register a `Waker` for event-driven
4150 /// service servers. Mirrors the matching method on
4151 /// `SubscriberTrait` / `ClientTrait`. Backends that
4152 /// surface incoming-request notifications wake `waker` when
4153 /// `has_request()` flips true. Returns `false` when the backend cannot
4154 /// (issue 1940); the caller then falls back to polling. Default: `false`.
4155 fn register_waker(&self, _waker: &core::task::Waker) -> bool {
4156 false
4157 }
4158
4159 /// Try to receive a service request into `buf` (non-blocking).
4160 ///
4161 /// On success returns a `ServiceRequest` that borrows from
4162 /// `buf`. The borrow is released when the returned struct is
4163 /// dropped — typically before `send_response` is called, since
4164 /// `send_response` takes `&mut self`.
4165 fn take_request<'a>(
4166 &mut self,
4167 buf: &'a mut [u8],
4168 ) -> Result<Option<ServiceRequest<'a>>, Self::Error>;
4169
4170 /// Issue 1632 — how many bytes the request the most recent
4171 /// [`take_request`](Self::take_request) REFUSED as too big for the
4172 /// caller's buffer needed.
4173 ///
4174 /// [`Subscription::refused_sample_len`]'s contract, for the service
4175 /// server: read it right after a take returns `BufferTooSmall`; `None`
4176 /// means the backend does not know (the default), never "zero bytes".
4177 fn refused_request_len(&self) -> Option<usize> {
4178 None
4179 }
4180
4181 /// Send a reply for the given sequence number. Non-blocking
4182 /// from the application's perspective; the backend may queue
4183 /// the reply for transport-level transmission.
4184 fn send_response(&mut self, sequence_number: i64, data: &[u8]) -> Result<(), Self::Error>;
4185
4186 /// Issue 1942 — the per-request metadata of the request the most recent
4187 /// successful [`take_request`](Self::take_request) returned: client GID +
4188 /// client sequence number, and the timestamps the backend can supply.
4189 ///
4190 /// rclrs's `ServiceInfo`. Read it after a take and before the next one.
4191 /// **A field the backend cannot report is `None`**, and the default — for
4192 /// a backend with no per-request metadata at all — is
4193 /// [`ServiceInfo::NOT_REPORTED`](nros_core::ServiceInfo::NOT_REPORTED),
4194 /// never a zeroed or invented value (the `MessageInfo` precedent).
4195 ///
4196 /// Not [`ServiceRequest::sequence_number`]: that is the token this backend
4197 /// replies against, which on zenoh is a local reply-slot index, while
4198 /// `request_id.sequence_number` is the number the CLIENT assigned.
4199 fn request_info(&self) -> nros_core::ServiceInfo {
4200 nros_core::ServiceInfo::NOT_REPORTED
4201 }
4202
4203 /// Handle a service request with typed messages
4204 fn handle_request<S: RosService>(
4205 &mut self,
4206 req_buf: &mut [u8],
4207 reply_buf: &mut [u8],
4208 handler: impl FnOnce(&S::Request) -> S::Reply,
4209 ) -> Result<bool, Self::Error>
4210 where
4211 Self::Error: From<TransportError>,
4212 {
4213 self.handle_request_with_info::<S>(req_buf, reply_buf, |req, _info| handler(req))
4214 }
4215
4216 /// Issue 1942 — [`handle_request`](Self::handle_request), with the
4217 /// request's [`ServiceInfo`](nros_core::ServiceInfo) (read through
4218 /// [`request_info`](Self::request_info) right after the take) handed to
4219 /// the handler beside it. rclrs's `(request, ServiceInfo)` callback.
4220 fn handle_request_with_info<S: RosService>(
4221 &mut self,
4222 req_buf: &mut [u8],
4223 reply_buf: &mut [u8],
4224 handler: impl FnOnce(&S::Request, &nros_core::ServiceInfo) -> S::Reply,
4225 ) -> Result<bool, Self::Error>
4226 where
4227 Self::Error: From<TransportError>,
4228 {
4229 use nros_core::{CdrReader, CdrWriter};
4230
4231 // First, try to receive a request and extract necessary data.
4232 // Capture the data slice's offset within `req_buf` so we can
4233 // re-borrow it after the `ServiceRequest` (which holds a
4234 // borrow into `req_buf`) is dropped. Some backends prepend a
4235 // header (DDS: 8-byte sequence number) and place the CDR
4236 // payload at a non-zero offset in the buffer; others (zenoh)
4237 // put it at offset 0. Reading from offset 0 unconditionally
4238 // would feed the prefix bytes to the CDR deserializer and
4239 // silently corrupt the request.
4240 let buf_start = req_buf.as_ptr() as usize;
4241 let (data_offset, data_len, sequence_number) = match self.take_request(req_buf)? {
4242 Some(request) => {
4243 let offset = (request.data.as_ptr() as usize).saturating_sub(buf_start);
4244 (offset, request.data.len(), request.sequence_number)
4245 }
4246 None => return Ok(false),
4247 };
4248
4249 // Issue 1942 — the take that just succeeded is the one this describes.
4250 let info = self.request_info();
4251
4252 // Deserialize request from the captured offset.
4253 let mut reader = CdrReader::new_with_header(&req_buf[data_offset..data_offset + data_len])
4254 .map_err(|_| TransportError::DeserializationError)?;
4255 let req = S::Request::deserialize(&mut reader)
4256 .map_err(|_| TransportError::DeserializationError)?;
4257
4258 // Call handler
4259 let reply = handler(&req, &info);
4260
4261 // Serialize reply
4262 let mut writer =
4263 CdrWriter::new_with_header(reply_buf).map_err(|_| TransportError::BufferTooSmall)?;
4264 reply
4265 .serialize(&mut writer)
4266 .map_err(|_| TransportError::SerializationError)?;
4267 let len = writer.position();
4268
4269 // Send reply (now we can borrow self mutably again)
4270 self.send_response(sequence_number, &reply_buf[..len])?;
4271 Ok(true)
4272 }
4273
4274 /// Handle a service request where the handler returns `Box<S::Reply>`
4275 ///
4276 /// Identical to `handle_request` but the handler returns a heap-allocated reply.
4277 /// This is needed for services with large response types (e.g., parameter services
4278 /// where `Vec<ParameterValue, 64>` is ~1MB+) that would overflow the stack.
4279 #[cfg(feature = "alloc")]
4280 fn handle_request_boxed<S: RosService>(
4281 &mut self,
4282 req_buf: &mut [u8],
4283 reply_buf: &mut [u8],
4284 handler: impl FnOnce(&S::Request) -> alloc::boxed::Box<S::Reply>,
4285 ) -> Result<bool, Self::Error>
4286 where
4287 Self::Error: From<TransportError>,
4288 {
4289 use nros_core::{CdrReader, CdrWriter};
4290
4291 let buf_start = req_buf.as_ptr() as usize;
4292 let (data_offset, data_len, sequence_number) = match self.take_request(req_buf)? {
4293 Some(request) => {
4294 let offset = (request.data.as_ptr() as usize).saturating_sub(buf_start);
4295 (offset, request.data.len(), request.sequence_number)
4296 }
4297 None => return Ok(false),
4298 };
4299
4300 let mut reader = CdrReader::new_with_header(&req_buf[data_offset..data_offset + data_len])
4301 .map_err(|_| TransportError::DeserializationError)?;
4302 let req = S::Request::deserialize(&mut reader)
4303 .map_err(|_| TransportError::DeserializationError)?;
4304
4305 let reply = handler(&req);
4306
4307 let mut writer =
4308 CdrWriter::new_with_header(reply_buf).map_err(|_| TransportError::BufferTooSmall)?;
4309 reply
4310 .serialize(&mut writer)
4311 .map_err(|_| TransportError::SerializationError)?;
4312 let len = writer.position();
4313
4314 self.send_response(sequence_number, &reply_buf[..len])?;
4315 Ok(true)
4316 }
4317
4318 /// Handle one request by STREAMING: the handler reads fields off the wire
4319 /// and writes the reply's fields straight back, so neither the request nor
4320 /// the reply is ever materialised as a value.
4321 ///
4322 /// phase-382 W1'. `handle_request_boxed` above boxes the REPLY because the
4323 /// parameter responses are enormous — `GetParametersResponse` measures
4324 /// 1,176,072 bytes. It does not box the REQUEST, which is deserialized by
4325 /// value into a stack local one line above the handler, and
4326 /// `SetParametersRequest` measures **1,192,968 bytes**. So every
4327 /// `ros2 param set` against a node put a 1.19 MB local on the calling
4328 /// task's stack — larger than the reply the boxing exists for, on every
4329 /// platform, with `param-services` live on Zephyr.
4330 ///
4331 /// Streaming removes both, and removes the `alloc` requirement with them:
4332 /// the whole value is never needed, because serialisation happens on the
4333 /// line after construction. Three things make it safe rather than clever:
4334 ///
4335 /// * **No `rcl_interfaces` message uses a DHEADER** — every `Serialize` impl
4336 /// is plain sequential CDR, so hand-written field writes are byte-identical
4337 /// to the generated ones. (If a future message gains XCDR2 extensibility
4338 /// this stops being true for THAT message; see RFC-0055.)
4339 /// * `req_buf` and `reply_buf` are disjoint, so a handler can hold the
4340 /// reader and the writer at once.
4341 /// * `CdrReader::read_string` borrows out of `req_buf` rather than copying,
4342 /// so a handler can look a name up without a buffer of its own.
4343 ///
4344 /// The cost is that the hand-written writes can drift from the generated
4345 /// `Serialize`. Guard it with a round-trip test that deserialises the
4346 /// streamed bytes back into the generated type — the by-value handler makes
4347 /// a good test-only oracle.
4348 ///
4349 /// No `alloc`, deliberately: this is the seam that lets `param-services` and
4350 /// `lifecycle-services` build without it.
4351 fn handle_request_raw(
4352 &mut self,
4353 req_buf: &mut [u8],
4354 reply_buf: &mut [u8],
4355 handler: impl FnOnce(
4356 &mut nros_core::CdrReader<'_>,
4357 &mut nros_core::CdrWriter<'_>,
4358 ) -> Result<(), TransportError>,
4359 ) -> Result<bool, Self::Error>
4360 where
4361 Self::Error: From<TransportError>,
4362 {
4363 use nros_core::{CdrReader, CdrWriter};
4364
4365 let buf_start = req_buf.as_ptr() as usize;
4366 let (data_offset, data_len, sequence_number) = match self.take_request(req_buf)? {
4367 Some(request) => {
4368 let offset = (request.data.as_ptr() as usize).saturating_sub(buf_start);
4369 (offset, request.data.len(), request.sequence_number)
4370 }
4371 None => return Ok(false),
4372 };
4373
4374 // Split the borrow so the reader (over `req_buf`) and the writer (over
4375 // `reply_buf`) can be live at the same time. They are separate
4376 // parameters, so this is disjoint by construction.
4377 let mut reader = CdrReader::new_with_header(&req_buf[data_offset..data_offset + data_len])
4378 .map_err(|_| TransportError::DeserializationError)?;
4379 let mut writer =
4380 CdrWriter::new_with_header(reply_buf).map_err(|_| TransportError::BufferTooSmall)?;
4381
4382 handler(&mut reader, &mut writer)?;
4383 let len = writer.position();
4384
4385 self.send_response(sequence_number, &reply_buf[..len])?;
4386 Ok(true)
4387 }
4388 /// The profile this entity is ACTUALLY running — what the backend GRANTED,
4389 /// not what the call site requested.
4390 ///
4391 /// Upstream's `rmw_service_request_subscription_get_actual_qos`. The two differ whenever a
4392 /// backend serves something other than what it was asked for, and the
4393 /// difference is exactly what answers "why is nothing arriving": a
4394 /// RELIABLE reader does not match a BEST_EFFORT writer, and a clamped
4395 /// history depth drops samples the caller believed were kept.
4396 ///
4397 /// **Per-field, and an unreportable field is an ABSENCE.** A backend that
4398 /// determines four policies and not the fifth returns the four and leaves
4399 /// the fifth at its `Unknown` variant. Never echo the request into a field
4400 /// you did not read back — that is the inverse of this method's meaning,
4401 /// and it is what the six C-ABI slots did until this phase.
4402 ///
4403 /// The default is [`QoSProfile::QOS_PROFILE_UNKNOWN`] — every field an
4404 /// absence — which is the honest answer for a backend with no read-back at
4405 /// all (XRCE has none; zenoh-pico's QoS is per-message flags). It is NOT
4406 /// the request, and it is NOT `QOS_PROFILE_DEFAULT`.
4407 fn request_subscription_actual_qos(&self) -> QoSProfile {
4408 QoSProfile::QOS_PROFILE_UNKNOWN
4409 }
4410
4411 /// The profile this entity is ACTUALLY running — what the backend GRANTED,
4412 /// not what the call site requested.
4413 ///
4414 /// Upstream's `rmw_service_response_publisher_get_actual_qos`. The two differ whenever a
4415 /// backend serves something other than what it was asked for, and the
4416 /// difference is exactly what answers "why is nothing arriving": a
4417 /// RELIABLE reader does not match a BEST_EFFORT writer, and a clamped
4418 /// history depth drops samples the caller believed were kept.
4419 ///
4420 /// **Per-field, and an unreportable field is an ABSENCE.** A backend that
4421 /// determines four policies and not the fifth returns the four and leaves
4422 /// the fifth at its `Unknown` variant. Never echo the request into a field
4423 /// you did not read back — that is the inverse of this method's meaning,
4424 /// and it is what the six C-ABI slots did until this phase.
4425 ///
4426 /// The default is [`QoSProfile::QOS_PROFILE_UNKNOWN`] — every field an
4427 /// absence — which is the honest answer for a backend with no read-back at
4428 /// all (XRCE has none; zenoh-pico's QoS is per-message flags). It is NOT
4429 /// the request, and it is NOT `QOS_PROFILE_DEFAULT`.
4430 fn response_publisher_actual_qos(&self) -> QoSProfile {
4431 QoSProfile::QOS_PROFILE_UNKNOWN
4432 }
4433}
4434
4435/// Decode a CDR service reply (encapsulation header included) — the typed
4436/// half [`ClientTrait::take_response`] and [`ClientTrait::take_response_for`]
4437/// share.
4438fn decode_reply<S: RosService>(bytes: &[u8]) -> Result<S::Reply, TransportError> {
4439 use nros_core::CdrReader;
4440
4441 let mut reader =
4442 CdrReader::new_with_header(bytes).map_err(|_| TransportError::DeserializationError)?;
4443 S::Reply::deserialize(&mut reader).map_err(|_| TransportError::DeserializationError)
4444}
4445
4446/// Service client trait for sending requests.
4447///
4448/// # Threading
4449///
4450/// `&mut self` on every method — the client is single-owner. For
4451/// fan-out request patterns, create one client per worker thread.
4452///
4453/// # Calling pattern
4454///
4455/// All in-tree backends route blocking waits through the executor:
4456///
4457/// 1. `send_request_raw(buf)` — non-blocking; returns once the
4458/// request is queued for transmission.
4459/// 2. The executor's `drive_io` runs.
4460/// 3. `take_response_raw(buf)` — non-blocking; returns
4461/// `Ok(Some(len))` when the reply is back.
4462///
4463/// The deprecated blocking `call_raw` path is
4464/// DELETED — `send_request_raw` + `take_response_raw` is the one
4465/// request/reply path, and both are required for service-capable
4466/// backends.
4467pub trait ClientTrait {
4468 /// Error type for service operations
4469 type Error;
4470
4471 /// Send a service request without waiting for a reply (non-blocking).
4472 ///
4473 /// Returns the SEQUENCE ID the backend assigned. The caller must
4474 /// subsequently poll [`take_response_raw`](Self::take_response_raw) and
4475 /// match that id against the one the reply carries.
4476 ///
4477 /// Issue 0778 — this returned `()` until 2026-08-25, and every backend
4478 /// computed an id and discarded it. With nothing to correlate by, a client
4479 /// with two calls outstanding could not tell the replies apart, so each
4480 /// backend picked a policy: cyclonedds abandoned the older request, zenoh
4481 /// took the first reply. Both are wrong for `send_goal` and
4482 /// `SetParameters`, which travel this path and are not idempotent.
4483 fn send_request_raw(&mut self, request: &[u8]) -> Result<i64, Self::Error>;
4484
4485 /// Poll for a reply (non-blocking).
4486 ///
4487 /// Returns `Ok(Some((len, sequence_id)))` when a reply has arrived,
4488 /// `Ok(None)` if not yet available, or `Err` on failure. The
4489 /// `sequence_id` is the one [`send_request_raw`](Self::send_request_raw)
4490 /// returned for the request this answers.
4491 ///
4492 /// It used to say "a reply to the MOST RECENTLY sent request", which was
4493 /// the single-outstanding-call assumption written into the contract.
4494 fn take_response_raw(
4495 &mut self,
4496 reply_buf: &mut [u8],
4497 ) -> Result<Option<(usize, i64)>, Self::Error>;
4498
4499 /// Issue 1632 — how many bytes the reply the most recent
4500 /// [`take_response_raw`](Self::take_response_raw) REFUSED as too big for
4501 /// the caller's buffer needed. [`Subscription::refused_sample_len`]'s
4502 /// contract, for the client: `None` is "the backend does not know".
4503 fn refused_response_len(&self) -> Option<usize> {
4504 None
4505 }
4506
4507 /// Issue 2136 — the metadata of the reply the most recent successful
4508 /// [`take_response_raw`](Self::take_response_raw) returned: upstream
4509 /// `rmw_take_response`'s `rmw_service_info_t`, the client twin of
4510 /// [`ServiceTrait::request_info`].
4511 ///
4512 /// - `request_id` — the request this reply answers: this client's own GID
4513 /// and the sequence number of its request;
4514 /// - `source_timestamp` — when the SERVER sent the reply, on its clock;
4515 /// - `received_timestamp` — when this client received it, on its clock.
4516 ///
4517 /// Read it after a take and before the next one. **A field the backend
4518 /// cannot report is `None`**, and the default — for a backend with no
4519 /// per-reply metadata at all — is
4520 /// [`ServiceInfo::NOT_REPORTED`](nros_core::ServiceInfo::NOT_REPORTED).
4521 fn response_info(&self) -> nros_core::ServiceInfo {
4522 nros_core::ServiceInfo::NOT_REPORTED
4523 }
4524
4525 /// Send a typed service request without waiting for a reply (non-blocking).
4526 ///
4527 /// Serializes the request into `req_buf` and calls
4528 /// [`send_request_raw`](Self::send_request_raw), returning the SEQUENCE ID
4529 /// the backend assigned — [`crate::SEQUENCE_ID_UNKNOWN`] on a backend that
4530 /// cannot assign one. Hand it to
4531 /// [`take_response_for`](Self::take_response_for) so this call takes only
4532 /// its own reply.
4533 ///
4534 /// Issue 2033 — this returned `()` after issue 2009, discarding the id the
4535 /// raw path had carried since issue 0778, so a typed caller had nothing to
4536 /// correlate by.
4537 fn send_request<S: RosService>(
4538 &mut self,
4539 request: &S::Request,
4540 req_buf: &mut [u8],
4541 ) -> Result<i64, Self::Error>
4542 where
4543 Self::Error: From<TransportError>,
4544 {
4545 use nros_core::CdrWriter;
4546
4547 let mut writer =
4548 CdrWriter::new_with_header(req_buf).map_err(|_| TransportError::BufferTooSmall)?;
4549 request
4550 .serialize(&mut writer)
4551 .map_err(|_| TransportError::SerializationError)?;
4552 let req_len = writer.position();
4553
4554 self.send_request_raw(&req_buf[..req_len])
4555 }
4556
4557 /// Poll for the next typed reply (non-blocking), WHICHEVER request it
4558 /// answers.
4559 ///
4560 /// Returns `Ok(Some((reply, sequence_id)))`: `sequence_id` is the id
4561 /// [`send_request`](Self::send_request) returned for the request this
4562 /// reply answers, and the caller decides whom it belongs to — upstream's
4563 /// `rcl_take_response` request header. A caller with ONE request in mind
4564 /// wants [`take_response_for`](Self::take_response_for), which drops the
4565 /// replies of requests it abandoned.
4566 ///
4567 /// Issue 2033 — this used to return the reply alone and was documented as
4568 /// "the reply to the most recently sent request", which it never checked:
4569 /// after a resend or a timeout, the abandoned request's late reply was
4570 /// handed to the new one.
4571 fn take_response<S: RosService>(
4572 &mut self,
4573 reply_buf: &mut [u8],
4574 ) -> Result<Option<(S::Reply, i64)>, Self::Error>
4575 where
4576 Self::Error: From<TransportError>,
4577 {
4578 match self.take_response_raw(reply_buf)? {
4579 Some((len, seq)) => Ok(Some((decode_reply::<S>(&reply_buf[..len])?, seq))),
4580 None => Ok(None),
4581 }
4582 }
4583
4584 /// Poll for the typed reply to the request `sequence_id` names
4585 /// (non-blocking), dropping any reply that answers a different one.
4586 ///
4587 /// `sequence_id` is what [`send_request`](Self::send_request) returned.
4588 /// The rule is [`crate::correlation`]'s, the one every other client
4589 /// surface applies (issue 2009): a reply is delivered only to the request
4590 /// whose id it carries, a stale reply is DROPPED (at most
4591 /// [`crate::MAX_STALE_DRAIN_PER_POLL`] per call), and an id-less reply or
4592 /// request ([`crate::SEQUENCE_ID_UNKNOWN`]) matches the sole request in
4593 /// mind. `Ok(None)` — nothing for this request yet.
4594 fn take_response_for<S: RosService>(
4595 &mut self,
4596 sequence_id: i64,
4597 reply_buf: &mut [u8],
4598 ) -> Result<Option<S::Reply>, Self::Error>
4599 where
4600 Self::Error: From<TransportError>,
4601 {
4602 let mut pending = crate::RequestCorrelator::<(), 1>::new();
4603 // A one-entry table cannot be full on its first insert.
4604 let _ = pending.insert(sequence_id, ());
4605 match crate::take_correlated(self, reply_buf, &mut pending)? {
4606 Some((len, _seq, ())) => Ok(Some(decode_reply::<S>(&reply_buf[..len])?)),
4607 None => Ok(None),
4608 }
4609 }
4610
4611 /// Register an async waker to be notified when a reply arrives.
4612 ///
4613 /// Called from `Future::poll()` implementations to store the waker.
4614 /// The transport backend calls `waker.wake()` from its reply callback
4615 /// when a response is available, enabling event-driven async without
4616 /// busy-polling.
4617 ///
4618 /// Returns `false` when the backend cannot wake `waker` (issue 1940);
4619 /// the caller then polls. Default: `false`.
4620 fn register_waker(&self, _waker: &core::task::Waker) -> bool {
4621 false
4622 }
4623
4624 // phase-428 W13 — the ~~`start_server_discovery`~~ / ~~`poll_server_discovery`~~
4625 // pair was DELETED here. It existed because the only zenoh backend could
4626 // answer "is a server up?" only by issuing a `z_liveliness_get`, which is
4627 // start-then-poll, so the synchronous `service_is_ready` below had nothing
4628 // to return but a latch (issue 1087). The pair had no vtable slot, so every
4629 // C-ABI backend inherited its default and `wait_for_service` answered
4630 // without asking. The zenoh backend now keeps a matched-server SET fed by
4631 // its liveliness subscriber — the state upstream's DDS discovery cache
4632 // keeps — and `service_is_ready` reads it synchronously; the wait loops
4633 // spin on that one query, and nothing needs the pair.
4634
4635 /// Whether a matching service server is currently discoverable.
4636 ///
4637 /// Mirrors `rclcpp::ClientBase::service_is_ready` — the NAME is upstream's.
4638 /// The SHAPE is `rcl`'s: `rcl_service_server_is_available(node, client,
4639 /// bool *is_available)` returns `RCL_RET_OK` "if the check was made
4640 /// successfully (regardless of the service readiness)", i.e. the return
4641 /// code says whether the CHECK worked and the out-param carries the ANSWER.
4642 /// rclcpp collapses that to a bare `bool` and moves the error to
4643 /// exceptions; RFC-0018 forbids exceptions, so `Result<bool, _>` is how the
4644 /// same contract is expressed here (phase-379 W6, RFC-0036).
4645 ///
4646 /// Returns `Ok(true)` if at least one matching server is CURRENTLY
4647 /// discoverable, `Ok(false)` if none is, or `Err(_)` if the backend
4648 /// cannot answer (e.g. XRCE — micro-XRCE-DDS-Client has no participant
4649 /// enumeration).
4650 ///
4651 /// CURRENT, not latched: upstream `rmw.h` says the outcome reflects a
4652 /// change in either direction, and `rclcpp::ClientBase::service_is_ready`
4653 /// calls `rcl_service_server_is_available` on every invocation. A backend
4654 /// answers from the discovery state it maintains — the DDS built-in
4655 /// topics, or the zenoh matched-server set fed by liveliness PUT/DELETE
4656 /// (phase-428 W13) — so a server that goes away reads unavailable again.
4657 /// Every wait loop in the tree (`wait_for_service`,
4658 /// `wait_for_action_server`, their C and C++ bindings) is a spin on this
4659 /// one method; there is no separate asynchronous probe (issue 1087).
4660 ///
4661 /// Those are three answers, not two, and keeping them apart is the whole
4662 /// point: `is_server_ready` used to sit beside this method collapsing
4663 /// "don't know" and "no server" into one `false`, its trait default was
4664 /// `true`, and only zenoh overrode it — so on every other image
4665 /// `wait_for_service` returned success without probing anything. Issue
4666 /// 1008 deleted it rather than fixing it, because a caller cannot recover
4667 /// from an answer that does not distinguish the two.
4668 ///
4669 /// User-facing surface: `Client<S>::server_available()` in Rust,
4670 /// `rclc_client_server_available()` in C/C++. Clients use this
4671 /// to gate the first request so a startup-ordering race
4672 /// (client opens before server's discovery announcement lands)
4673 /// doesn't surface as a request-side timeout.
4674 ///
4675 /// Default impl: `Err(TransportError::Unsupported)` — backends
4676 /// that support graph introspection (zenoh queryable interest,
4677 /// DDS built-in topic readers) opt in by overriding.
4678 fn service_is_ready(&self) -> Result<bool, Self::Error>
4679 where
4680 Self::Error: From<TransportError>,
4681 {
4682 Err(TransportError::Unsupported.into())
4683 }
4684
4685 /// This client's own global identifier — upstream (Jazzy)
4686 /// `rmw_get_gid_for_client`, the vtable's `get_gid_for_client`. Issue
4687 /// 1978.
4688 ///
4689 /// The client twin of [`Publisher::get_gid`]: the identity a server keys
4690 /// a request id on (zenoh: the gid stamped into every request
4691 /// attachment; Cyclone: the request writer's GUID), zero-extended to
4692 /// [`PUBLISHER_GID_SIZE`](nros_core::PUBLISHER_GID_SIZE) by
4693 /// [`pad_publisher_gid`](nros_core::pad_publisher_gid).
4694 ///
4695 /// The default is `Err(Unsupported)`, never an all-zero id — the same
4696 /// discipline, for the same reason, as `Publisher::get_gid`.
4697 fn get_gid(&self) -> Result<[u8; nros_core::PUBLISHER_GID_SIZE], Self::Error>
4698 where
4699 Self::Error: From<TransportError>,
4700 {
4701 Err(TransportError::Unsupported.into())
4702 }
4703
4704 /// The profile this entity is ACTUALLY running — what the backend GRANTED,
4705 /// not what the call site requested.
4706 ///
4707 /// Upstream's `rmw_client_request_publisher_get_actual_qos`. The two differ whenever a
4708 /// backend serves something other than what it was asked for, and the
4709 /// difference is exactly what answers "why is nothing arriving": a
4710 /// RELIABLE reader does not match a BEST_EFFORT writer, and a clamped
4711 /// history depth drops samples the caller believed were kept.
4712 ///
4713 /// **Per-field, and an unreportable field is an ABSENCE.** A backend that
4714 /// determines four policies and not the fifth returns the four and leaves
4715 /// the fifth at its `Unknown` variant. Never echo the request into a field
4716 /// you did not read back — that is the inverse of this method's meaning,
4717 /// and it is what the six C-ABI slots did until this phase.
4718 ///
4719 /// The default is [`QoSProfile::QOS_PROFILE_UNKNOWN`] — every field an
4720 /// absence — which is the honest answer for a backend with no read-back at
4721 /// all (XRCE has none; zenoh-pico's QoS is per-message flags). It is NOT
4722 /// the request, and it is NOT `QOS_PROFILE_DEFAULT`.
4723 fn request_publisher_actual_qos(&self) -> QoSProfile {
4724 QoSProfile::QOS_PROFILE_UNKNOWN
4725 }
4726
4727 /// The profile this entity is ACTUALLY running — what the backend GRANTED,
4728 /// not what the call site requested.
4729 ///
4730 /// Upstream's `rmw_client_response_subscription_get_actual_qos`. The two differ whenever a
4731 /// backend serves something other than what it was asked for, and the
4732 /// difference is exactly what answers "why is nothing arriving": a
4733 /// RELIABLE reader does not match a BEST_EFFORT writer, and a clamped
4734 /// history depth drops samples the caller believed were kept.
4735 ///
4736 /// **Per-field, and an unreportable field is an ABSENCE.** A backend that
4737 /// determines four policies and not the fifth returns the four and leaves
4738 /// the fifth at its `Unknown` variant. Never echo the request into a field
4739 /// you did not read back — that is the inverse of this method's meaning,
4740 /// and it is what the six C-ABI slots did until this phase.
4741 ///
4742 /// The default is [`QoSProfile::QOS_PROFILE_UNKNOWN`] — every field an
4743 /// absence — which is the honest answer for a backend with no read-back at
4744 /// all (XRCE has none; zenoh-pico's QoS is per-message flags). It is NOT
4745 /// the request, and it is NOT `QOS_PROFILE_DEFAULT`.
4746 fn response_subscription_actual_qos(&self) -> QoSProfile {
4747 QoSProfile::QOS_PROFILE_UNKNOWN
4748 }
4749}
4750
4751/// Transport backend trait (legacy).
4752///
4753/// Use [`Rmw`] for new code. This trait is retained for backward compatibility
4754/// with existing code that uses [`TransportConfig`] directly.
4755pub trait Transport {
4756 /// Error type for this transport
4757 type Error;
4758 /// Session type for this transport
4759 type Session: Session;
4760
4761 /// Open a new session with the given configuration
4762 fn open(config: &TransportConfig) -> Result<Self::Session, Self::Error>;
4763}
4764
4765/// Factory trait for compile-time middleware selection.
4766///
4767/// Embedded crates select a backend via feature flag:
4768/// ```rust,ignore
4769/// #[cfg(feature = "rmw-cffi")]
4770/// type DefaultRmw = nros_rmw_cffi::CffiRmw;
4771/// ```
4772///
4773/// Each backend provides its own `Rmw` implementation that bridges
4774/// from the middleware-agnostic [`RmwConfig`] to backend-specific
4775/// initialization.
4776///
4777/// `open` consumes `self`. Backends carry their own
4778/// configuration (agent addresses, serial ports, TLS CA slots)
4779/// inside the factory value and hand that over to the session at
4780/// `open` time. In-tree, every backend sits behind the C vtable, so the one
4781/// production impl is `CffiRmw`, spelled `CffiRmw::default().open(&config)`.
4782pub trait Rmw {
4783 /// Session type returned by [`open`](Rmw::open)
4784 type Session: Session;
4785 /// Error type for session creation
4786 type Error: core::fmt::Debug;
4787
4788 /// Open a new middleware session with the given configuration.
4789 ///
4790 /// The backend maps [`RmwConfig`] fields to its own connection
4791 /// parameters (e.g., zenoh locator and session mode, XRCE-DDS
4792 /// agent address). Any backend-specific pre-open state stored
4793 /// on `self` (e.g. configured agent IP / port) is moved into the
4794 /// returned `Session`.
4795 fn open(self, config: &RmwConfig) -> Result<Self::Session, Self::Error>;
4796}
4797
4798#[cfg(test)]
4799mod tests {
4800 use super::*;
4801
4802 /// phase-515 R8 -- rclrs's `*_duration` QoS builders, in the record's ms.
4803 #[test]
4804 fn qos_duration_builders_store_whole_milliseconds() {
4805 use core::time::Duration;
4806 let q = QoSProfile::new()
4807 .deadline_duration(Duration::from_millis(250))
4808 .lifespan_duration(Duration::from_secs(2))
4809 .liveliness_lease_duration(Duration::from_micros(1500));
4810 assert_eq!(q.deadline_ms, 250);
4811 assert_eq!(q.lifespan_ms, 2000);
4812 assert_eq!(q.liveliness_lease_ms, 1, "1.5 ms truncates to whole ms");
4813 // Sub-millisecond is never "infinite" (0) by accident.
4814 assert_eq!(
4815 QoSProfile::new()
4816 .deadline_duration(Duration::from_nanos(1))
4817 .deadline_ms,
4818 1
4819 );
4820 assert_eq!(
4821 QoSProfile::new()
4822 .deadline_duration(Duration::ZERO)
4823 .deadline_ms,
4824 0
4825 );
4826 assert_eq!(
4827 QoSProfile::new()
4828 .lifespan_duration(Duration::from_secs(u64::MAX))
4829 .lifespan_ms,
4830 u32::MAX,
4831 "saturates"
4832 );
4833 }
4834
4835 /// issue 0783 -- the variants with a payload render it; the rest render
4836 /// their fixed line. `heapless`, so the check runs without `alloc`.
4837 #[test]
4838 fn transport_error_display_renders_payloads() {
4839 use core::fmt::Write;
4840 fn show(e: &TransportError) -> heapless::String<64> {
4841 let mut s = heapless::String::new();
4842 write!(s, "{e}").unwrap();
4843 s
4844 }
4845 assert_eq!(show(&TransportError::Timeout).as_str(), "timed out");
4846 assert_eq!(
4847 show(&TransportError::IncompatibleQos(QoSPolicyMask::RELIABILITY)).as_str(),
4848 "incompatible QoS: RELIABILITY"
4849 );
4850 assert_eq!(
4851 show(&TransportError::IncompatibleQos(QoSPolicyMask::NONE)).as_str(),
4852 "incompatible QoS"
4853 );
4854 assert_eq!(
4855 show(&TransportError::Backend("z_open refused")).as_str(),
4856 "backend error: z_open refused"
4857 );
4858 }
4859
4860 /// Issue 0971 — the DEFAULT `take_sequence` body must report a partial
4861 /// count rather than discard it, which is what its own doc comment says and
4862 /// what `?` did not do.
4863 ///
4864 /// This is the default's negative control: a backend that takes two
4865 /// messages and then errors must hand the caller those two. Before the fix
4866 /// the `?` threw them away and the caller could not tell two messages had
4867 /// been consumed — they were gone from the queue and absent from the
4868 /// result.
4869 mod take_sequence_default {
4870 use super::*;
4871
4872 #[derive(Debug, PartialEq)]
4873 struct Boom;
4874
4875 /// Yields `n` one-byte messages, then errors forever.
4876 struct ThenErrors {
4877 left: usize,
4878 }
4879
4880 impl Subscription for ThenErrors {
4881 type Error = Boom;
4882
4883 fn take_serialized(&mut self, buf: &mut [u8]) -> Result<Option<usize>, Self::Error> {
4884 if self.left == 0 {
4885 return Err(Boom);
4886 }
4887 self.left -= 1;
4888 buf[0] = 0xAB;
4889 Ok(Some(1))
4890 }
4891
4892 fn deserialization_error(&self) -> Self::Error {
4893 Boom
4894 }
4895 }
4896
4897 #[test]
4898 fn a_partial_drain_reports_its_count_instead_of_the_error() {
4899 let mut sub = ThenErrors { left: 2 };
4900 let mut buf = [0u8; 4 * 8];
4901 let mut lens = [0usize; 4];
4902
4903 // Two messages are available, the third call errors.
4904 let got = sub.take_sequence(&mut buf, 8, 4, &mut lens);
4905
4906 assert_eq!(
4907 got,
4908 Ok(2),
4909 "a drain that took messages must report them; `?` discarded the \
4910 count and the caller lost two consumed messages"
4911 );
4912 assert_eq!(&lens[..2], &[1, 1]);
4913 }
4914
4915 #[test]
4916 fn an_error_with_nothing_taken_is_returned_immediately() {
4917 let mut sub = ThenErrors { left: 0 };
4918 let mut buf = [0u8; 4 * 8];
4919 let mut lens = [0usize; 4];
4920
4921 // No count to protect, so the caller should see the error itself
4922 // rather than an ambiguous `Ok(0)`.
4923 assert_eq!(sub.take_sequence(&mut buf, 8, 4, &mut lens), Err(Boom));
4924 }
4925 }
4926
4927 #[test]
4928 fn test_topic_info() {
4929 let topic = TopicInfo::new("/chatter", "std_msgs::msg::dds_::String_", "abc123");
4930 assert_eq!(topic.name, "/chatter");
4931 assert_eq!(topic.domain_id, 0);
4932 }
4933
4934 #[test]
4935 fn qos_apply_overrides_matches_topic_and_role() {
4936 // Default is Reliable / Volatile / KeepLast(10).
4937 static OVERRIDES: &[QoSOverride] = &[
4938 QoSOverride {
4939 topic: "/chatter",
4940 role: QoSOverrideRole::Publisher,
4941 value: QoSOverrideValue::Reliability(QoSReliabilityPolicy::BestEffort),
4942 },
4943 QoSOverride {
4944 topic: "/chatter",
4945 role: QoSOverrideRole::Publisher,
4946 value: QoSOverrideValue::Depth(5),
4947 },
4948 QoSOverride {
4949 topic: "/scan",
4950 role: QoSOverrideRole::Subscription,
4951 value: QoSOverrideValue::Durability(QoSDurabilityPolicy::TransientLocal),
4952 },
4953 ];
4954
4955 // Matching topic + publisher role → reliability + depth applied.
4956 let pub_qos = QoSProfile::default().apply_overrides(
4957 "/chatter",
4958 QoSOverrideRole::Publisher,
4959 OVERRIDES,
4960 );
4961 assert_eq!(pub_qos.reliability, QoSReliabilityPolicy::BestEffort);
4962 assert_eq!(pub_qos.depth, 5);
4963 assert_eq!(pub_qos.durability, QoSDurabilityPolicy::Volatile); // untouched
4964
4965 // Same topic but subscription role → publisher overrides DON'T apply;
4966 // the /scan override is for a different topic → also no change.
4967 let sub_qos = QoSProfile::default().apply_overrides(
4968 "/chatter",
4969 QoSOverrideRole::Subscription,
4970 OVERRIDES,
4971 );
4972 assert_eq!(sub_qos, QoSProfile::default());
4973
4974 // The /scan subscription override applies only to /scan+subscription.
4975 let scan_qos = QoSProfile::default().apply_overrides(
4976 "/scan",
4977 QoSOverrideRole::Subscription,
4978 OVERRIDES,
4979 );
4980 assert_eq!(scan_qos.durability, QoSDurabilityPolicy::TransientLocal);
4981
4982 // Empty table → identity (the zero-override fast path).
4983 assert_eq!(
4984 QoSProfile::default().apply_overrides("/x", QoSOverrideRole::Publisher, &[]),
4985 QoSProfile::default()
4986 );
4987 }
4988
4989 #[test]
4990 fn test_qos_defaults() {
4991 let qos = QoSProfile::default();
4992 assert_eq!(qos.reliability, QoSReliabilityPolicy::Reliable);
4993 }
4994
4995 #[test]
4996 fn test_action_info() {
4997 let action = ActionInfo::new(
4998 "/fibonacci",
4999 "example_interfaces::action::dds_::Fibonacci_",
5000 "abc123",
5001 );
5002 assert_eq!(action.name, "/fibonacci");
5003 assert_eq!(action.domain_id, 0);
5004 }
5005
5006 #[test]
5007 fn test_action_info_with_domain() {
5008 let action = ActionInfo::new(
5009 "/fibonacci",
5010 "example_interfaces::action::dds_::Fibonacci_",
5011 "abc123",
5012 )
5013 .with_domain(42);
5014 assert_eq!(action.domain_id, 42);
5015 }
5016
5017 #[test]
5018 fn test_action_send_goal_key() {
5019 let action = ActionInfo::new(
5020 "/fibonacci",
5021 "example_interfaces::action::dds_::Fibonacci_",
5022 "abc123",
5023 )
5024 .with_domain(0);
5025
5026 let key: heapless::String<256> = action.send_goal_key();
5027 // ActionInfo returns the sub-entity name with leading slash for ROS 2 compatibility
5028 assert_eq!(key.as_str(), "/fibonacci/_action/send_goal");
5029 }
5030
5031 #[test]
5032 fn test_action_feedback_key() {
5033 let action = ActionInfo::new(
5034 "/fibonacci",
5035 "example_interfaces::action::dds_::Fibonacci_",
5036 "abc123",
5037 )
5038 .with_domain(0);
5039
5040 let key: heapless::String<256> = action.feedback_key();
5041 assert_eq!(key.as_str(), "/fibonacci/_action/feedback");
5042 }
5043
5044 #[test]
5045 fn test_action_all_sub_names() {
5046 let action = ActionInfo::new(
5047 "/fibonacci",
5048 "example_interfaces::action::dds_::Fibonacci_",
5049 "abc123",
5050 )
5051 .with_domain(0);
5052
5053 let cancel: heapless::String<256> = action.cancel_goal_key();
5054 assert_eq!(cancel.as_str(), "/fibonacci/_action/cancel_goal");
5055
5056 let result: heapless::String<256> = action.get_result_key();
5057 assert_eq!(result.as_str(), "/fibonacci/_action/get_result");
5058
5059 let status: heapless::String<256> = action.status_key();
5060 assert_eq!(status.as_str(), "/fibonacci/_action/status");
5061 }
5062
5063 // --- QoS Profile Tests ---
5064
5065 #[test]
5066 fn test_qos_profile_sensor_data() {
5067 let qos = QoSProfile::QOS_PROFILE_SENSOR_DATA;
5068 assert_eq!(qos.reliability, QoSReliabilityPolicy::BestEffort);
5069 assert_eq!(qos.durability, QoSDurabilityPolicy::Volatile);
5070 assert_eq!(qos.history, QoSHistoryPolicy::KeepLast);
5071 assert_eq!(qos.depth, 5);
5072 }
5073
5074 #[test]
5075 fn test_qos_profile_default() {
5076 let qos = QoSProfile::QOS_PROFILE_DEFAULT;
5077 assert_eq!(qos.reliability, QoSReliabilityPolicy::Reliable);
5078 assert_eq!(qos.durability, QoSDurabilityPolicy::Volatile);
5079 assert_eq!(qos.depth, 10);
5080 }
5081
5082 #[test]
5083 fn test_qos_profile_services_default() {
5084 let qos = QoSProfile::QOS_PROFILE_SERVICES_DEFAULT;
5085 assert_eq!(qos.reliability, QoSReliabilityPolicy::Reliable);
5086 assert_eq!(qos.durability, QoSDurabilityPolicy::Volatile);
5087 }
5088
5089 /// issue 0829 — `SYSTEM_DEFAULT` asks for NOTHING, so it demands no policy.
5090 ///
5091 /// `required_policies` started from `QoSPolicyMask::CORE` unconditionally,
5092 /// which made the sentinel profile demand reliability, durability, history
5093 /// AND depth — so a backend that could not honour one would answer
5094 /// `IncompatibleQos` to a profile that requested none of them.
5095 #[test]
5096 fn system_default_profile_requires_no_policy() {
5097 let required = QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT.required_policies();
5098 assert_eq!(required.0, 0, "SYSTEM_DEFAULT demanded {required:?}");
5099 // Therefore it is admissible against a backend that advertises nothing.
5100 assert!(
5101 QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT
5102 .validate_against(QoSPolicyMask(0))
5103 .is_ok()
5104 );
5105 }
5106
5107 /// phase-428 W9 — the roadmap predicted that deriving zenoh's mask would
5108 /// drop `DEPTH` and that "nothing that works today breaks". The second
5109 /// half is FALSE, and this is the measurement that says so.
5110 ///
5111 /// `QOS_PROFILE_DEFAULT` states `depth: 10`, so it REQUIRES `DEPTH`; a
5112 /// mask without that bit refuses it, and that profile is what every
5113 /// `create_publisher` / `create_subscription` with no explicit QoS passes
5114 /// (`nros-node/src/executor/node.rs:238,372`). Withdrawing the bit would
5115 /// therefore refuse every default entity on the backend, not just the ones
5116 /// asking for more depth than the ring holds.
5117 ///
5118 /// So the zenoh shim EARNS the bit instead of withdrawing it (phase-428
5119 /// W9: `shim/qos.rs` reads the depth, grants what the ring can hold, and
5120 /// publishes the GRANTED value to the graph). Which is the honest reading
5121 /// of the mask anyway: the bit says "I will not silently ignore this
5122 /// policy", and a depth lie lives in the VALUE, not in the bit.
5123 #[test]
5124 fn withdrawing_depth_would_refuse_the_default_profile() {
5125 let without_depth = QoSPolicyMask(!QoSPolicyMask::DEPTH.0);
5126 assert!(
5127 QoSProfile::QOS_PROFILE_DEFAULT
5128 .validate_against(without_depth)
5129 .is_err(),
5130 "QOS_PROFILE_DEFAULT states depth 10; a mask without DEPTH must refuse it"
5131 );
5132 // And the same for the two other presets a default caller reaches.
5133 for qos in [
5134 QoSProfile::QOS_PROFILE_SERVICES_DEFAULT,
5135 QoSProfile::QOS_PROFILE_SENSOR_DATA,
5136 ] {
5137 assert!(qos.validate_against(without_depth).is_err());
5138 }
5139 // The sentinel profile is the one that survives, because it states no
5140 // depth at all.
5141 assert!(
5142 QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT
5143 .validate_against(without_depth)
5144 .is_ok()
5145 );
5146 }
5147
5148 /// phase-428 W9 — the trait default advertises NOTHING, so an
5149 /// implementation that has written no QoS code refuses any stated policy.
5150 ///
5151 /// The default was `CORE` until W9: four policies granted to a backend
5152 /// that had implemented none of them, by the trait itself.
5153 #[test]
5154 fn the_empty_mask_refuses_every_stated_policy_and_nothing_else() {
5155 assert_eq!(QoSPolicyMask::NONE.0, 0);
5156 assert!(
5157 QoSProfile::QOS_PROFILE_DEFAULT
5158 .validate_against(QoSPolicyMask::NONE)
5159 .is_err()
5160 );
5161 assert!(
5162 QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT
5163 .validate_against(QoSPolicyMask::NONE)
5164 .is_ok(),
5165 "an absence demands nothing, so it is admissible anywhere"
5166 );
5167 }
5168
5169 // ------------------------------------------------------------------
5170 // phase-417 G7 — the refusal NAMES the policy, and the vocabulary it
5171 // names it in is `QoSPolicyMask`'s own constants.
5172 // ------------------------------------------------------------------
5173
5174 /// The table is the twelve bits and nothing else, and a name is never a
5175 /// second authoring of the constant it belongs to.
5176 ///
5177 /// The buildless half of this lives in `check-qos-mask-derivation` (R8),
5178 /// which reads the `pub const` block and compares it against `NAMED`
5179 /// entry for entry. This is the half a `no_std` unit run can assert: every
5180 /// entry is one bit, the bits are distinct, and every name is distinct.
5181 /// A bit added above with no entry here would leave a policy that refuses
5182 /// a create and prints nothing.
5183 #[test]
5184 fn every_named_policy_is_one_distinct_bit_with_one_distinct_name() {
5185 assert_eq!(QoSPolicyMask::NAMED.len(), 12);
5186 let mut seen_bits = 0u32;
5187 for (bit, cstr) in QoSPolicyMask::NAMED {
5188 let name = cstr.to_str().expect("every entry is an ASCII literal");
5189 assert_eq!(
5190 bit.0.count_ones(),
5191 1,
5192 "{name} is not a single policy bit ({:#x})",
5193 bit.0
5194 );
5195 assert_eq!(seen_bits & bit.0, 0, "{name} repeats a bit already named");
5196 seen_bits |= bit.0;
5197 assert_eq!(
5198 bit.policy_name(),
5199 Some(name),
5200 "{name} does not name itself back"
5201 );
5202 // The C entry points hand this pointer straight over, so the NUL
5203 // is load-bearing and the byte before it must be the last of the
5204 // name — a `&str` view that silently dropped a byte would be a
5205 // truncated C string.
5206 assert_eq!(cstr.to_bytes().len(), name.len());
5207 }
5208 // The twelve bits are contiguous from 0, which is what
5209 // `rmw_entity.h`'s `NROS_RMW_QOS_POLICY_*` mirrors.
5210 assert_eq!(seen_bits, (1 << 12) - 1);
5211 }
5212
5213 /// `None` is a real answer in both directions — neither the empty mask nor
5214 /// a union is a policy, so neither may borrow a neighbour's name.
5215 #[test]
5216 fn neither_the_empty_mask_nor_a_union_names_a_policy() {
5217 assert_eq!(QoSPolicyMask::NONE.policy_name(), None);
5218 assert_eq!(QoSPolicyMask::CORE.policy_name(), None);
5219 assert_eq!(
5220 (QoSPolicyMask::DEADLINE | QoSPolicyMask::LIFESPAN).policy_name(),
5221 None
5222 );
5223 // And an error that is not a QoS refusal names no policy either.
5224 assert_eq!(TransportError::Timeout.qos_policy_name(), None);
5225 assert_eq!(
5226 TransportError::IncompatibleQos(QoSPolicyMask::NONE).qos_policy_name(),
5227 None,
5228 "a refusal relayed across `rmw_ret_t` identified no policy"
5229 );
5230 }
5231
5232 /// Several missing policies still produce ONE name, the same one every
5233 /// time — otherwise two surfaces could report different policies for the
5234 /// same refusal and a test could not assert either.
5235 #[test]
5236 fn a_refusal_missing_several_policies_names_the_lowest_one() {
5237 // DEFAULT states reliability, durability(volatile), history and depth.
5238 let qos = QoSProfile::QOS_PROFILE_DEFAULT;
5239 assert_eq!(
5240 qos.validate_against(QoSPolicyMask::NONE),
5241 Err(TransportError::IncompatibleQos(QoSPolicyMask::RELIABILITY)),
5242 "RELIABILITY is bit 0, so it is the reported one"
5243 );
5244 // Grant reliability and the next-lowest missing policy is reported.
5245 assert_eq!(
5246 qos.validate_against(QoSPolicyMask::RELIABILITY)
5247 .unwrap_err()
5248 .qos_policy_name(),
5249 Some("DURABILITY_VOLATILE")
5250 );
5251 // Grant everything the profile states and it is admitted.
5252 assert!(qos.validate_against(qos.required_policies()).is_ok());
5253 }
5254
5255 /// The policy a caller stated is the policy the refusal names — not a
5256 /// policy the profile never asked for. `DEADLINE` is the interesting one
5257 /// because it is stated by a VALUE rather than by a variant.
5258 #[test]
5259 fn the_refusal_names_the_policy_the_caller_actually_stated() {
5260 let qos = QoSProfile {
5261 deadline_ms: 250,
5262 ..QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT
5263 };
5264 assert_eq!(qos.required_policies(), QoSPolicyMask::DEADLINE);
5265 assert_eq!(
5266 qos.validate_against(QoSPolicyMask::NONE)
5267 .unwrap_err()
5268 .qos_policy_name(),
5269 Some("DEADLINE")
5270 );
5271 }
5272
5273 /// The relaxation is per FIELD, not all-or-nothing: a profile that states
5274 /// SOME policies still demands exactly those.
5275 #[test]
5276 fn a_partly_stated_profile_demands_only_what_it_states() {
5277 let qos = QoSProfile {
5278 reliability: QoSReliabilityPolicy::BestEffort,
5279 ..QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT
5280 };
5281 let required = qos.required_policies();
5282 assert!(required.contains(QoSPolicyMask::RELIABILITY));
5283 assert!(!required.contains(QoSPolicyMask::HISTORY));
5284 assert!(!required.contains(QoSPolicyMask::DEPTH));
5285 assert!(!required.contains(QoSPolicyMask::DURABILITY_VOLATILE));
5286 assert!(!required.contains(QoSPolicyMask::DURABILITY_TRANSIENT_LOCAL));
5287 }
5288
5289 /// A fully concrete profile is unaffected by the relaxation — this is the
5290 /// guard on "do not silently stop demanding what the caller asked for".
5291 #[test]
5292 fn concrete_profiles_still_demand_their_core_policies() {
5293 let required = QoSProfile::QOS_PROFILE_DEFAULT.required_policies();
5294 assert!(required.contains(QoSPolicyMask::RELIABILITY));
5295 assert!(required.contains(QoSPolicyMask::DURABILITY_VOLATILE));
5296 assert!(required.contains(QoSPolicyMask::HISTORY));
5297 assert!(required.contains(QoSPolicyMask::DEPTH));
5298 // And a backend missing one still rejects it.
5299 let missing = QoSPolicyMask(required.0 & !QoSPolicyMask::DEPTH.0);
5300 // phase-417 G7 — and it says WHICH policy. `DEPTH` is the only bit
5301 // dropped, so there is exactly one right answer here.
5302 assert_eq!(
5303 QoSProfile::QOS_PROFILE_DEFAULT.validate_against(missing),
5304 Err(TransportError::IncompatibleQos(QoSPolicyMask::DEPTH))
5305 );
5306 }
5307
5308 /// issue 0829 — resolution replaces ONLY the sentinel fields, and the
5309 /// answer is the backend's, not a constant this crate bakes.
5310 #[test]
5311 fn resolve_system_default_fills_absences_and_touches_nothing_else() {
5312 // Two backends, two different answers to the SAME sentinel — the whole
5313 // reason no concrete `QOS_PROFILE_SYSTEM_DEFAULT` could be right.
5314 const CYCLONE: QoSSystemDefaults = QoSSystemDefaults {
5315 reliability: QoSReliabilityPolicy::Reliable,
5316 durability: QoSDurabilityPolicy::Volatile,
5317 history: QoSHistoryPolicy::KeepLast,
5318 depth: 1,
5319 };
5320 const ZENOH: QoSSystemDefaults = QoSSystemDefaults {
5321 depth: 4,
5322 ..CYCLONE
5323 };
5324
5325 let a = QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT.resolve_system_default(&CYCLONE);
5326 let b = QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT.resolve_system_default(&ZENOH);
5327 assert_eq!(a.reliability, QoSReliabilityPolicy::Reliable);
5328 assert_eq!(a.history, QoSHistoryPolicy::KeepLast);
5329 assert_eq!(a.durability, QoSDurabilityPolicy::Volatile);
5330 assert_eq!(a.depth, 1);
5331 assert_eq!(b.depth, 4);
5332 assert!(!a.has_unresolved_system_default());
5333 assert!(!b.has_unresolved_system_default());
5334
5335 // A STATED policy is never overridden — resolution fills an absence.
5336 let stated = QoSProfile {
5337 reliability: QoSReliabilityPolicy::BestEffort,
5338 history: QoSHistoryPolicy::KeepAll,
5339 durability: QoSDurabilityPolicy::TransientLocal,
5340 depth: 7,
5341 ..QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT
5342 };
5343 let resolved = stated.resolve_system_default(&CYCLONE);
5344 assert_eq!(resolved, stated, "resolution overrode a stated policy");
5345
5346 // Idempotent.
5347 assert_eq!(a.resolve_system_default(&ZENOH), a);
5348 }
5349
5350 #[test]
5351 fn services_default_validates_and_rejects_missing_policy() {
5352 // Phase 193.5 — the service-create path (node `create_service*_sized` +
5353 // the typed-arena `register_service*_on`) runs `validate_against` on the
5354 // caller's profile, exactly like pub/sub. A backend advertising the
5355 // profile's required policies admits it; dropping any required bit (here
5356 // RELIABILITY) rejects it with `IncompatibleQos` — no silent downgrade.
5357 let qos = QoSProfile::services_default();
5358 let required = qos.required_policies();
5359 assert!(qos.validate_against(required).is_ok());
5360 assert!(qos.validate_against(QoSPolicyMask(u32::MAX)).is_ok());
5361 let missing = QoSPolicyMask(required.0 & !QoSPolicyMask::RELIABILITY.0);
5362 // phase-417 G7 — RELIABILITY is the bit dropped and RELIABILITY is
5363 // what the refusal has to name.
5364 assert_eq!(
5365 qos.validate_against(missing),
5366 Err(TransportError::IncompatibleQos(QoSPolicyMask::RELIABILITY))
5367 );
5368 assert_eq!(
5369 qos.validate_against(missing).unwrap_err().qos_policy_name(),
5370 Some("RELIABILITY")
5371 );
5372 }
5373
5374 /// issue 0793 — this asserted `TransientLocal`, which PINNED THE DEFECT:
5375 /// upstream `rmw_qos_profile_parameters` is KEEP_LAST(1000) + RELIABLE +
5376 /// **VOLATILE** (`/opt/ros/<distro>/include/rmw/rmw/qos_profiles.h`), and
5377 /// our own second copy of the profile, `nros::qos::PARAMETERS`, was already
5378 /// correct. The test agreed with the wrong copy, so the disagreement between
5379 /// the two survived every run.
5380 #[test]
5381 fn test_qos_profile_parameters() {
5382 let qos = QoSProfile::QOS_PROFILE_PARAMETERS;
5383 assert_eq!(qos.reliability, QoSReliabilityPolicy::Reliable);
5384 assert_eq!(
5385 qos.durability,
5386 QoSDurabilityPolicy::Volatile,
5387 "rmw_qos_profile_parameters is VOLATILE; transient-local would make \
5388 every parameter server retain for late joiners, which ROS 2 does not do"
5389 );
5390 assert_eq!(qos.depth, 1000);
5391 }
5392
5393 #[test]
5394 fn test_qos_profile_clock() {
5395 let qos = QoSProfile::QOS_PROFILE_CLOCK;
5396 assert_eq!(qos.reliability, QoSReliabilityPolicy::BestEffort);
5397 assert_eq!(qos.depth, 1);
5398 }
5399
5400 /// phase-428 W10 — this asserted `KeepAll`, which PINNED THE DEFECT, in
5401 /// exactly the shape issue 0793 had already been caught in one profile
5402 /// over: upstream `rmw_qos_profile_parameter_events` is KEEP_LAST(1000) +
5403 /// RELIABLE + VOLATILE, byte-identical to `rmw_qos_profile_parameters`, and
5404 /// our C++ surface (`rclcpp::ParameterEventsQoS`) was already correct — so
5405 /// the two languages shipped different profiles under one name while this
5406 /// test reported green.
5407 ///
5408 /// The old value inverted behaviour rather than weakening it: a RELIABLE
5409 /// writer with KEEP_ALL blocks once history fills, where KEEP_LAST(1000)
5410 /// overwrites.
5411 #[test]
5412 fn test_qos_profile_parameter_events() {
5413 let qos = QoSProfile::QOS_PROFILE_PARAMETER_EVENTS;
5414 assert_eq!(qos.reliability, QoSReliabilityPolicy::Reliable);
5415 assert_eq!(qos.durability, QoSDurabilityPolicy::Volatile);
5416 assert_eq!(
5417 qos.history,
5418 QoSHistoryPolicy::KeepLast,
5419 "rmw_qos_profile_parameter_events is KEEP_LAST; KEEP_ALL makes a \
5420 reliable parameter-event writer BLOCK where upstream overwrites"
5421 );
5422 assert_eq!(qos.depth, 1000);
5423
5424 // Upstream defines the two constants with identical field values.
5425 assert_eq!(qos, QoSProfile::QOS_PROFILE_PARAMETERS);
5426 }
5427
5428 /// phase-428 W10 — the class behind the `PARAMETER_EVENTS` defect, not just
5429 /// the instance. `KEEP_ALL` under RELIABLE is a blocking configuration, and
5430 /// no upstream `rmw_qos_profile_*` nor `rcl_action_qos_profile_*` uses it;
5431 /// every one of them is `KEEP_LAST` or the SYSTEM_DEFAULT sentinel. A NAMED
5432 /// preset that is `KeepAll` is therefore a transcription error by
5433 /// construction — a caller who genuinely wants it says
5434 /// [`QoSProfile::keep_all`].
5435 #[test]
5436 fn no_named_preset_is_keep_all() {
5437 for (name, qos) in [
5438 ("BEST_EFFORT", QoSProfile::BEST_EFFORT),
5439 ("RELIABLE", QoSProfile::RELIABLE),
5440 ("SYSTEM_DEFAULT", QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT),
5441 ("DEFAULT", QoSProfile::QOS_PROFILE_DEFAULT),
5442 ("SENSOR_DATA", QoSProfile::QOS_PROFILE_SENSOR_DATA),
5443 ("SERVICES_DEFAULT", QoSProfile::QOS_PROFILE_SERVICES_DEFAULT),
5444 ("PARAMETERS", QoSProfile::QOS_PROFILE_PARAMETERS),
5445 ("PARAMETER_EVENTS", QoSProfile::QOS_PROFILE_PARAMETER_EVENTS),
5446 (
5447 "ACTION_STATUS_DEFAULT",
5448 QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT,
5449 ),
5450 ("CLOCK", QoSProfile::QOS_PROFILE_CLOCK),
5451 ("PX4", QoSProfile::QOS_PROFILE_PX4),
5452 ] {
5453 assert_ne!(
5454 qos.history,
5455 QoSHistoryPolicy::KeepAll,
5456 "preset {name} is KEEP_ALL; no upstream profile is"
5457 );
5458 }
5459 }
5460
5461 #[test]
5462 fn test_qos_profile_action_status() {
5463 let qos = QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT;
5464 assert_eq!(qos.reliability, QoSReliabilityPolicy::Reliable);
5465 assert_eq!(qos.durability, QoSDurabilityPolicy::TransientLocal);
5466 assert_eq!(qos.depth, 1);
5467 }
5468
5469 #[test]
5470 fn test_qos_static_constructors() {
5471 assert_eq!(
5472 QoSProfile::topics_default(),
5473 QoSProfile::QOS_PROFILE_DEFAULT
5474 );
5475 assert_eq!(
5476 QoSProfile::sensor_data_default(),
5477 QoSProfile::QOS_PROFILE_SENSOR_DATA
5478 );
5479 assert_eq!(
5480 QoSProfile::services_default(),
5481 QoSProfile::QOS_PROFILE_SERVICES_DEFAULT
5482 );
5483 assert_eq!(
5484 QoSProfile::parameter_services_default(),
5485 QoSProfile::QOS_PROFILE_PARAMETERS
5486 );
5487 assert_eq!(
5488 QoSProfile::action_status_default(),
5489 QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT
5490 );
5491 }
5492
5493 #[test]
5494 fn test_qos_builder_explicit_setters() {
5495 let qos = QoSProfile::new()
5496 .reliability(QoSReliabilityPolicy::Reliable)
5497 .durability(QoSDurabilityPolicy::TransientLocal)
5498 .history(QoSHistoryPolicy::KeepAll)
5499 .depth(100);
5500
5501 assert_eq!(qos.reliability, QoSReliabilityPolicy::Reliable);
5502 assert_eq!(qos.durability, QoSDurabilityPolicy::TransientLocal);
5503 assert_eq!(qos.history, QoSHistoryPolicy::KeepAll);
5504 assert_eq!(qos.depth, 100);
5505 }
5506
5507 #[test]
5508 fn test_qos_builder_chaining() {
5509 // Test that builder methods can be chained in any order
5510 let qos = QoSProfile::sensor_data_default()
5511 .reliable()
5512 .transient_local()
5513 .keep_last(20);
5514
5515 assert_eq!(qos.reliability, QoSReliabilityPolicy::Reliable);
5516 assert_eq!(qos.durability, QoSDurabilityPolicy::TransientLocal);
5517 assert_eq!(qos.history, QoSHistoryPolicy::KeepLast);
5518 assert_eq!(qos.depth, 20);
5519 }
5520
5521 #[test]
5522 fn test_qos_eq_impl() {
5523 // Verify that PartialEq works correctly via derive on QoSProfile
5524 let qos1 = QoSProfile::QOS_PROFILE_DEFAULT;
5525 let qos2 = QoSProfile::topics_default();
5526 // Both should have same values - verify field by field
5527 assert_eq!(qos1.reliability, qos2.reliability);
5528 assert_eq!(qos1.durability, qos2.durability);
5529 assert_eq!(qos1.history, qos2.history);
5530 assert_eq!(qos1.depth, qos2.depth);
5531 }
5532
5533 // --- Locator validation tests ---
5534
5535 #[test]
5536 fn test_locator_protocol_tcp() {
5537 assert_eq!(locator_protocol("tcp/127.0.0.1:7447"), LocatorProtocol::Tcp);
5538 }
5539
5540 #[test]
5541 fn test_locator_protocol_serial() {
5542 assert_eq!(
5543 locator_protocol("serial//dev/ttyUSB0#baudrate=115200"),
5544 LocatorProtocol::Serial
5545 );
5546 }
5547
5548 #[test]
5549 fn test_locator_protocol_unknown() {
5550 assert_eq!(locator_protocol(""), LocatorProtocol::Unknown);
5551 assert_eq!(locator_protocol("http://foo"), LocatorProtocol::Unknown);
5552 assert_eq!(locator_protocol("tls/host:port"), LocatorProtocol::Unknown);
5553 }
5554
5555 #[test]
5556 fn test_locator_protocol_udp() {
5557 assert_eq!(locator_protocol("udp/127.0.0.1:7447"), LocatorProtocol::Udp);
5558 assert_eq!(
5559 locator_protocol("udp/192.168.1.50:2019"),
5560 LocatorProtocol::Udp
5561 );
5562 }
5563
5564 #[test]
5565 fn test_validate_tcp_locator_ok() {
5566 assert!(validate_locator("tcp/127.0.0.1:7447").is_ok());
5567 assert!(validate_locator("tcp/192.168.1.1:7447").is_ok());
5568 }
5569
5570 #[test]
5571 fn test_validate_tcp_locator_missing_port() {
5572 assert!(validate_locator("tcp/127.0.0.1").is_err());
5573 }
5574
5575 #[test]
5576 fn test_validate_serial_locator_ok() {
5577 assert!(validate_locator("serial//dev/ttyUSB0#baudrate=115200").is_ok());
5578 assert!(validate_locator("serial//dev/ttyACM0#baudrate=9600").is_ok());
5579 assert!(validate_locator("serial/uart1#baudrate=921600").is_ok());
5580 }
5581
5582 #[test]
5583 fn test_validate_serial_locator_empty_device() {
5584 assert!(validate_locator("serial/").is_err());
5585 }
5586
5587 #[test]
5588 fn test_validate_serial_locator_missing_baudrate() {
5589 assert!(validate_locator("serial//dev/ttyUSB0").is_err());
5590 }
5591
5592 #[test]
5593 fn test_validate_serial_locator_invalid_baudrate() {
5594 assert!(validate_locator("serial//dev/ttyUSB0#baudrate=abc").is_err());
5595 }
5596
5597 #[test]
5598 fn test_validate_unknown_protocol() {
5599 assert!(validate_locator("http://foo").is_err());
5600 assert!(validate_locator("tls/host:port").is_err());
5601 }
5602
5603 #[test]
5604 fn test_validate_udp_locator_ok() {
5605 assert!(validate_locator("udp/127.0.0.1:7447").is_ok());
5606 assert!(validate_locator("udp/192.168.1.50:2019").is_ok());
5607 }
5608
5609 #[test]
5610 fn test_validate_udp_locator_missing_port() {
5611 assert!(validate_locator("udp/127.0.0.1").is_err());
5612 }
5613
5614 // Phase 233.2 — the PX4 companion QoS profile must be BEST_EFFORT +
5615 // TRANSIENT_LOCAL + KEEP_LAST so it matches PX4's uxrce_dds_client endpoints.
5616 #[test]
5617 fn px4_qos_profile_matches_uxrce_dds_client() {
5618 let q = QoSProfile::px4();
5619 assert_eq!(q.reliability, QoSReliabilityPolicy::BestEffort);
5620 // VOLATILE — PX4's /fmu/out writers are volatile; a TRANSIENT_LOCAL
5621 // reader silently fails to match (verified against real PX4 SITL).
5622 assert_eq!(q.durability, QoSDurabilityPolicy::Volatile);
5623 assert_eq!(q.history, QoSHistoryPolicy::KeepLast);
5624 assert_eq!(q, QoSProfile::QOS_PROFILE_PX4);
5625 // Depth is tunable via the builder without losing the PX4 policies.
5626 let deep = QoSProfile::px4().keep_last(5);
5627 assert_eq!(deep.depth, 5);
5628 assert_eq!(deep.reliability, QoSReliabilityPolicy::BestEffort);
5629 assert_eq!(deep.durability, QoSDurabilityPolicy::Volatile);
5630 }
5631
5632 // --- RmwConfig Tests ---
5633
5634 #[test]
5635 fn test_rmw_config_default() {
5636 let config = RmwConfig::default();
5637 assert_eq!(config.locator, "tcp/127.0.0.1:7447");
5638 assert_eq!(config.mode, SessionMode::Client);
5639 assert_eq!(config.domain_id, 0);
5640 assert_eq!(config.node_name, "node");
5641 assert_eq!(config.namespace, "");
5642 }
5643
5644 #[test]
5645 fn test_rmw_config_custom() {
5646 let config = RmwConfig {
5647 locator: "tcp/192.168.1.1:7447",
5648 mode: SessionMode::Peer,
5649 domain_id: 42,
5650 node_name: "talker",
5651 namespace: "/ns1",
5652 properties: &[("agent_port", "2019")],
5653 };
5654 assert_eq!(config.locator, "tcp/192.168.1.1:7447");
5655 assert_eq!(config.mode, SessionMode::Peer);
5656 assert_eq!(config.domain_id, 42);
5657 assert_eq!(config.node_name, "talker");
5658 assert_eq!(config.namespace, "/ns1");
5659 assert_eq!(config.properties.len(), 1);
5660 assert_eq!(config.properties[0].0, "agent_port");
5661 }
5662
5663 #[test]
5664 fn test_rmw_config_is_copy() {
5665 let config = RmwConfig::default();
5666 let config2 = config; // Copy
5667 assert_eq!(config.locator, config2.locator);
5668 assert_eq!(config.domain_id, config2.domain_id);
5669 }
5670
5671 #[test]
5672 fn test_rmw_config_clone() {
5673 let config = RmwConfig::default();
5674 let cloned = RmwConfig { ..config };
5675 assert_eq!(cloned.locator, config.locator);
5676 assert_eq!(cloned.node_name, config.node_name);
5677 }
5678}
5679
5680#[cfg(test)]
5681mod rx_buffer_hint_tests {
5682 use super::*;
5683
5684 /// issue 0896 / phase-402 — the hint must SURVIVE being set on `TopicInfo`.
5685 ///
5686 /// This is the seam every path funnels through: the C register writes it
5687 /// here, `nros-rmw-cffi` reads `topic.rx_buffer_hint` back out when
5688 /// building `rmw_subscription_options_t`, and a size-classing backend
5689 /// routes on it. A default that silently stayed 0 is the original defect,
5690 /// so the round trip is worth an assertion rather than an assumption.
5691 #[test]
5692 fn a_hint_set_on_topic_info_is_readable_back() {
5693 let t = TopicInfo::new("/chatter", "std_msgs/msg/Int32", "").with_rx_buffer_hint(4096);
5694 assert_eq!(t.rx_buffer_hint, 4096);
5695 }
5696
5697 /// Zero is "no opinion", not "zero bytes". The C options struct uses 0 as
5698 /// its unset sentinel and the executor only calls the setter when the
5699 /// caller stated something, so the default must stay 0 for the
5700 /// backend-default path to remain reachable.
5701 #[test]
5702 fn the_default_hint_is_zero_meaning_no_opinion() {
5703 let t = TopicInfo::new("/chatter", "std_msgs/msg/Int32", "");
5704 assert_eq!(t.rx_buffer_hint, 0);
5705 }
5706
5707 /// The builder must not disturb the rest of the descriptor — it is applied
5708 /// AFTER domain/namespace/node in the C path, so a setter that reset a
5709 /// field would drop identity that discovery depends on.
5710 #[test]
5711 fn setting_the_hint_preserves_the_rest_of_the_descriptor() {
5712 let make = || {
5713 TopicInfo::new("/chatter", "std_msgs/msg/Int32", "hash")
5714 .with_domain(7)
5715 .with_namespace("/ns")
5716 };
5717 let base = make();
5718 let hinted = make().with_rx_buffer_hint(1234);
5719 assert_eq!(hinted.name, base.name);
5720 assert_eq!(hinted.type_name, base.type_name);
5721 assert_eq!(hinted.type_hash, base.type_hash);
5722 assert_eq!(hinted.domain_id, base.domain_id);
5723 assert_eq!(hinted.namespace, base.namespace);
5724 assert_eq!(hinted.rx_buffer_hint, 1234);
5725 }
5726}
5727
5728#[cfg(test)]
5729mod granted_qos_tests {
5730 use super::*;
5731
5732 /// A backend with no read-back answers an ABSENCE, and the trait default
5733 /// is where that is decided for every backend that does not override it.
5734 ///
5735 /// The tempting defaults are both wrong and both silent: the REQUEST
5736 /// ("you got what you asked for", which is the claim this accessor exists
5737 /// to stop being made for free) and `QOS_PROFILE_DEFAULT` ("RELIABLE
5738 /// KEEP_LAST(10)", a profile nobody chose).
5739 struct Mute;
5740
5741 impl Publisher for Mute {
5742 type Error = TransportError;
5743 fn publish_raw(&self, _data: &[u8]) -> Result<(), TransportError> {
5744 Ok(())
5745 }
5746 fn buffer_error(&self) -> TransportError {
5747 TransportError::BufferTooSmall
5748 }
5749 fn serialization_error(&self) -> TransportError {
5750 TransportError::SerializationError
5751 }
5752 }
5753
5754 #[test]
5755 fn the_default_read_back_is_an_absence_not_the_request() {
5756 let answered = Publisher::actual_qos(&Mute);
5757 assert_eq!(answered, QoSProfile::QOS_PROFILE_UNKNOWN);
5758 assert!(answered.has_unknown());
5759 assert_ne!(
5760 answered,
5761 QoSProfile::QOS_PROFILE_DEFAULT,
5762 "a backend that cannot say must not answer a profile nobody chose"
5763 );
5764 }
5765
5766 /// The phase-467 RMW gap-closure design study's Q1 — the trait default is
5767 /// a REFUSAL, never a gid.
5768 ///
5769 /// `Mute` overrides nothing, so it stands for every backend that has not
5770 /// implemented the accessor. The tempting default is `Ok([0u8; 24])`: it
5771 /// compiles, it needs no error plumbing, and it is indistinguishable from
5772 /// a real gid a backend zero-padded — which is the RFC-0089 Part I shape
5773 /// this method exists on the loud side of.
5774 #[test]
5775 fn the_default_gid_is_a_refusal_not_zeros() {
5776 let answered = Publisher::get_gid(&Mute);
5777 assert_eq!(answered, Err(TransportError::Unsupported));
5778 assert_ne!(answered, Ok([0u8; nros_core::PUBLISHER_GID_SIZE]));
5779 }
5780
5781 /// Row 7 of the same study — the ONE spelling of "the application owns
5782 /// the assertion", which two backends had written out by hand.
5783 ///
5784 /// `Unknown` is deliberately not manual: it is what a `*_get_actual_qos`
5785 /// read-back writes for a policy the backend could not report, and an
5786 /// absence is not a request. Reading it as manual would make a backend
5787 /// with no read-back refuse an assertion nobody asked for.
5788 #[test]
5789 fn only_the_two_manual_kinds_are_manual() {
5790 assert!(QoSLivelinessPolicy::ManualByNode.is_manual());
5791 assert!(QoSLivelinessPolicy::ManualByTopic.is_manual());
5792 assert!(!QoSLivelinessPolicy::Automatic.is_manual());
5793 assert!(!QoSLivelinessPolicy::None.is_manual());
5794 assert!(!QoSLivelinessPolicy::Unknown.is_manual());
5795 }
5796
5797 /// `UNKNOWN` and `SYSTEM_DEFAULT` are DIFFERENT absences and the ABI keeps
5798 /// them apart: "nobody asked" is resolvable by the backend, "I cannot say"
5799 /// is not. A profile that confused them would let a read-back round-trip
5800 /// into a create call and silently pick policies.
5801 #[test]
5802 fn unknown_is_not_the_system_default_sentinel() {
5803 assert_ne!(
5804 QoSProfile::QOS_PROFILE_UNKNOWN,
5805 QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT
5806 );
5807 assert!(QoSProfile::QOS_PROFILE_UNKNOWN.has_unknown());
5808 assert!(!QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT.has_unknown());
5809 }
5810
5811 /// The round trip is REFUSED. Feeding a read-back straight back into a
5812 /// create is the one way `UNKNOWN` reaches a request, and it must fail
5813 /// loudly rather than resolve to whatever the backend picks.
5814 #[test]
5815 fn a_read_back_profile_cannot_be_used_as_a_request() {
5816 // A mask that supports everything, so the refusal cannot be an
5817 // accident of a narrow backend.
5818 let everything = QoSPolicyMask(u32::MAX);
5819 assert_eq!(
5820 QoSProfile::QOS_PROFILE_UNKNOWN.validate_against(everything),
5821 Err(TransportError::IncompatibleQos(QoSPolicyMask::NONE)),
5822 "UNKNOWN is an absence; nothing can grant it, so no policy is named"
5823 );
5824 // And exactly one unknown policy is enough — a partial read-back is
5825 // the common case, not the exotic one.
5826 let mut partial = QoSProfile::QOS_PROFILE_DEFAULT;
5827 partial.durability = QoSDurabilityPolicy::Unknown;
5828 assert_eq!(
5829 partial.validate_against(everything),
5830 Err(TransportError::IncompatibleQos(QoSPolicyMask::NONE))
5831 );
5832 // The same profile without the sentinel is admitted, so the refusal
5833 // above is about `UNKNOWN` and not about the mask.
5834 assert_eq!(
5835 QoSProfile::QOS_PROFILE_DEFAULT.validate_against(everything),
5836 Ok(())
5837 );
5838 }
5839
5840 /// `required_policies` cannot express `UNKNOWN`, which is why the refusal
5841 /// lives one level up. Asserted so that a future attempt to smuggle it in
5842 /// as an unsatisfiable mask bit has to change a test that says why not.
5843 #[test]
5844 fn unknown_demands_no_capability_bit() {
5845 let mut p = QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT;
5846 p.durability = QoSDurabilityPolicy::Unknown;
5847 p.liveliness_kind = QoSLivelinessPolicy::Unknown;
5848 assert_eq!(p.required_policies().0, QoSPolicyMask(0).0);
5849 }
5850}
5851
5852#[cfg(test)]
5853mod best_available_tests {
5854 //! The ONE best-available rule, asserted against upstream's
5855 //! `rmw_dds_common` behaviour case by case.
5856 use super::*;
5857
5858 const ALL: QoSPolicyMask = QoSPolicyMask(u32::MAX);
5859
5860 fn peer(
5861 rel: QoSReliabilityPolicy,
5862 dur: QoSDurabilityPolicy,
5863 liv: QoSLivelinessPolicy,
5864 deadline_ms: u32,
5865 lease_ms: u32,
5866 ) -> QoSProfile {
5867 let mut q = QoSProfile::QOS_PROFILE_DEFAULT;
5868 q.reliability = rel;
5869 q.durability = dur;
5870 q.liveliness_kind = liv;
5871 q.deadline_ms = deadline_ms;
5872 q.liveliness_lease_ms = lease_ms;
5873 q
5874 }
5875
5876 fn fold(peers: &[QoSProfile]) -> BestAvailablePeers {
5877 let mut f = BestAvailablePeers::NONE;
5878 for p in peers {
5879 f.observe(p);
5880 }
5881 f
5882 }
5883
5884 #[test]
5885 fn the_profile_matches_upstream_and_asks_for_resolution() {
5886 let q = QoSProfile::best_available();
5887 assert_eq!(q, QoSProfile::QOS_PROFILE_BEST_AVAILABLE);
5888 assert!(q.has_best_available());
5889 assert_eq!((q.history, q.depth), (QoSHistoryPolicy::KeepLast, 10));
5890 assert_eq!(q.lifespan_ms, 0, "lifespan has no best-available spelling");
5891 assert!(!QoSProfile::QOS_PROFILE_DEFAULT.has_best_available());
5892 }
5893
5894 /// A best-available field demands nothing of the backend: the resolver
5895 /// clamps to the backend's mask, so validation of the REQUEST cannot fail
5896 /// on it.
5897 #[test]
5898 fn a_best_available_request_requires_no_policy_bit() {
5899 let q = QoSProfile::best_available();
5900 assert_eq!(
5901 q.required_policies(),
5902 QoSPolicyMask::HISTORY | QoSPolicyMask::DEPTH
5903 );
5904 assert!(
5905 q.validate_against(QoSPolicyMask::HISTORY | QoSPolicyMask::DEPTH)
5906 .is_ok()
5907 );
5908 }
5909
5910 #[test]
5911 fn subscription_with_no_publishers_gets_upstreams_nothing_discovered_answer() {
5912 let q = QoSProfile::best_available().resolve_best_available(
5913 BestAvailableRole::Subscription,
5914 &BestAvailablePeers::NONE,
5915 ALL,
5916 );
5917 assert_eq!(q.reliability, QoSReliabilityPolicy::BestEffort);
5918 assert_eq!(q.durability, QoSDurabilityPolicy::Volatile);
5919 assert_eq!(q.liveliness_kind, QoSLivelinessPolicy::Automatic);
5920 assert_eq!((q.deadline_ms, q.liveliness_lease_ms), (0, 0));
5921 assert!(!q.has_best_available());
5922 }
5923
5924 #[test]
5925 fn publisher_with_no_subscriptions_gets_the_highest_service() {
5926 let q = QoSProfile::best_available().resolve_best_available(
5927 BestAvailableRole::Publisher,
5928 &BestAvailablePeers::NONE,
5929 ALL,
5930 );
5931 assert_eq!(q.reliability, QoSReliabilityPolicy::Reliable);
5932 assert_eq!(q.durability, QoSDurabilityPolicy::TransientLocal);
5933 assert_eq!(q.liveliness_kind, QoSLivelinessPolicy::Automatic);
5934 assert_eq!((q.deadline_ms, q.liveliness_lease_ms), (0, 0));
5935 }
5936
5937 #[test]
5938 fn subscription_takes_the_strictest_value_every_publisher_offers() {
5939 use QoSDurabilityPolicy as D;
5940 use QoSLivelinessPolicy as L;
5941 use QoSReliabilityPolicy as R;
5942 // All reliable + transient-local + manual: the subscription may ask
5943 // for all three; largest finite deadline / lease.
5944 let all = fold(&[
5945 peer(R::Reliable, D::TransientLocal, L::ManualByTopic, 100, 10),
5946 peer(R::Reliable, D::TransientLocal, L::ManualByTopic, 300, 30),
5947 ]);
5948 let q = QoSProfile::best_available().resolve_best_available(
5949 BestAvailableRole::Subscription,
5950 &all,
5951 ALL,
5952 );
5953 assert_eq!(q.reliability, R::Reliable);
5954 assert_eq!(q.durability, D::TransientLocal);
5955 assert_eq!(q.liveliness_kind, L::ManualByTopic);
5956 assert_eq!((q.deadline_ms, q.liveliness_lease_ms), (300, 30));
5957
5958 // One best-effort volatile automatic publisher with no deadline drags
5959 // each policy down — and an infinite window makes the deadline default.
5960 let mixed = fold(&[
5961 peer(R::Reliable, D::TransientLocal, L::ManualByTopic, 100, 0),
5962 peer(
5963 R::BestEffort,
5964 D::Volatile,
5965 L::Automatic,
5966 DURATION_INFINITE_MS,
5967 0,
5968 ),
5969 ]);
5970 let q = QoSProfile::best_available().resolve_best_available(
5971 BestAvailableRole::Subscription,
5972 &mixed,
5973 ALL,
5974 );
5975 assert_eq!(q.reliability, R::BestEffort);
5976 assert_eq!(q.durability, D::Volatile);
5977 assert_eq!(q.liveliness_kind, L::Automatic);
5978 assert_eq!(
5979 q.deadline_ms, 100,
5980 "infinite reads as no finite window, like upstream's DEFAULT"
5981 );
5982 }
5983
5984 #[test]
5985 fn publisher_follows_any_manual_subscription_and_the_smallest_window() {
5986 use QoSDurabilityPolicy as D;
5987 use QoSLivelinessPolicy as L;
5988 use QoSReliabilityPolicy as R;
5989 let subs = fold(&[
5990 peer(R::BestEffort, D::Volatile, L::Automatic, 300, 0),
5991 peer(R::BestEffort, D::Volatile, L::ManualByTopic, 100, 40),
5992 ]);
5993 let q = QoSProfile::best_available().resolve_best_available(
5994 BestAvailableRole::Publisher,
5995 &subs,
5996 ALL,
5997 );
5998 assert_eq!(
5999 q.reliability,
6000 R::Reliable,
6001 "reliable serves every subscription"
6002 );
6003 assert_eq!(
6004 q.durability,
6005 D::TransientLocal,
6006 "transient-local serves every subscription"
6007 );
6008 assert_eq!(q.liveliness_kind, L::ManualByTopic);
6009 assert_eq!((q.deadline_ms, q.liveliness_lease_ms), (100, 40));
6010 }
6011
6012 /// A peer the backend could not read contributes its least demanding
6013 /// value — never counted reliable — so a subscription stays compatible.
6014 #[test]
6015 fn an_unreadable_peer_counts_as_least_demanding() {
6016 let unknown = fold(&[QoSProfile::QOS_PROFILE_UNKNOWN]);
6017 let q = QoSProfile::best_available().resolve_best_available(
6018 BestAvailableRole::Subscription,
6019 &unknown,
6020 ALL,
6021 );
6022 assert_eq!(q.reliability, QoSReliabilityPolicy::BestEffort);
6023 assert_eq!(q.durability, QoSDurabilityPolicy::Volatile);
6024 }
6025
6026 #[test]
6027 fn services_take_the_services_default_profile() {
6028 let q = QoSProfile::best_available().resolve_best_available(
6029 BestAvailableRole::Service,
6030 &BestAvailablePeers::NONE,
6031 ALL,
6032 );
6033 let svc = QoSProfile::QOS_PROFILE_SERVICES_DEFAULT;
6034 assert_eq!(q.reliability, svc.reliability);
6035 assert_eq!(q.durability, svc.durability);
6036 assert_eq!(q.liveliness_kind, svc.liveliness_kind);
6037 assert_eq!((q.deadline_ms, q.liveliness_lease_ms), (0, 0));
6038 }
6039
6040 /// The choice never lands on a value the backend would refuse: it steps
6041 /// down to the next one the mask honours, and to the sentinel when the
6042 /// policy is not honoured at all.
6043 #[test]
6044 fn the_choice_is_clamped_to_what_the_backend_honours() {
6045 let mask = QoSPolicyMask::RELIABILITY
6046 | QoSPolicyMask::DURABILITY_VOLATILE
6047 | QoSPolicyMask::LIVELINESS_AUTOMATIC;
6048 let subs = fold(&[peer(
6049 QoSReliabilityPolicy::Reliable,
6050 QoSDurabilityPolicy::TransientLocal,
6051 QoSLivelinessPolicy::ManualByTopic,
6052 100,
6053 40,
6054 )]);
6055 let q = QoSProfile::best_available().resolve_best_available(
6056 BestAvailableRole::Publisher,
6057 &subs,
6058 mask,
6059 );
6060 assert_eq!(q.durability, QoSDurabilityPolicy::Volatile);
6061 assert_eq!(q.liveliness_kind, QoSLivelinessPolicy::Automatic);
6062 assert_eq!((q.deadline_ms, q.liveliness_lease_ms), (0, 0));
6063 assert!(
6064 q.validate_against(mask | QoSPolicyMask::HISTORY | QoSPolicyMask::DEPTH)
6065 .is_ok()
6066 );
6067
6068 let q = QoSProfile::best_available().resolve_best_available(
6069 BestAvailableRole::Publisher,
6070 &subs,
6071 QoSPolicyMask::NONE,
6072 );
6073 assert_eq!(q.reliability, QoSReliabilityPolicy::SystemDefault);
6074 assert_eq!(q.durability, QoSDurabilityPolicy::SystemDefault);
6075 assert_eq!(q.liveliness_kind, QoSLivelinessPolicy::None);
6076 }
6077
6078 /// Fields the caller STATED are never touched — only the best-available
6079 /// ones resolve.
6080 #[test]
6081 fn stated_fields_are_left_alone() {
6082 let q = QoSProfile::best_available().best_effort();
6083 let r =
6084 q.resolve_best_available(BestAvailableRole::Publisher, &BestAvailablePeers::NONE, ALL);
6085 assert_eq!(r.reliability, QoSReliabilityPolicy::BestEffort);
6086 assert_eq!(r.durability, QoSDurabilityPolicy::TransientLocal);
6087 let plain = QoSProfile::QOS_PROFILE_SENSOR_DATA;
6088 assert_eq!(
6089 plain.resolve_best_available(
6090 BestAvailableRole::Subscription,
6091 &BestAvailablePeers::NONE,
6092 ALL
6093 ),
6094 plain
6095 );
6096 }
6097
6098 /// No finite duration lowers onto the best-available sentinel.
6099 #[test]
6100 fn a_finite_duration_cannot_collide_with_the_sentinel() {
6101 use core::time::Duration;
6102 assert_eq!(
6103 duration_to_qos_ms(Duration::from_millis(DURATION_BEST_AVAILABLE_MS as u64)),
6104 Err(TransportError::InvalidArgument)
6105 );
6106 assert_eq!(
6107 duration_to_qos_ms(Duration::from_millis(DURATION_BEST_AVAILABLE_MS as u64 - 1)),
6108 Ok(DURATION_BEST_AVAILABLE_MS - 1)
6109 );
6110 }
6111}
6112
6113#[cfg(test)]
6114mod runtime_profile_tests {
6115 //! `fit_to_supported`: a runtime-owned endpoint's profile steps down to
6116 //! what the backend honours instead of being refused.
6117 use super::*;
6118
6119 /// XRCE's mask: no lifespan, no liveliness.
6120 const XRCE: QoSPolicyMask = QoSPolicyMask(
6121 QoSPolicyMask::RELIABILITY.0
6122 | QoSPolicyMask::DURABILITY_VOLATILE.0
6123 | QoSPolicyMask::DURABILITY_TRANSIENT_LOCAL.0
6124 | QoSPolicyMask::HISTORY.0
6125 | QoSPolicyMask::DEPTH.0
6126 | QoSPolicyMask::AVOID_ROS_NAMESPACE_CONVENTIONS.0
6127 | QoSPolicyMask::DEADLINE.0,
6128 );
6129
6130 fn rosout_like() -> QoSProfile {
6131 QoSProfile {
6132 history: QoSHistoryPolicy::KeepLast,
6133 depth: 10,
6134 reliability: QoSReliabilityPolicy::Reliable,
6135 durability: QoSDurabilityPolicy::Volatile,
6136 lifespan_ms: 10_000,
6137 ..QoSProfile::default()
6138 }
6139 }
6140
6141 /// The case that removed `/rosout` from every XRCE image: a 10 s
6142 /// lifespan the backend does not carry. Refused as a request, fitted as
6143 /// a preference, and the fit then validates.
6144 #[test]
6145 fn an_unsupported_lifespan_is_dropped_and_named() {
6146 let q = rosout_like();
6147 assert_eq!(
6148 q.validate_against(XRCE),
6149 Err(TransportError::IncompatibleQos(QoSPolicyMask::LIFESPAN))
6150 );
6151 let (fitted, dropped) = q.fit_to_supported(XRCE);
6152 assert_eq!(dropped, QoSPolicyMask::LIFESPAN);
6153 assert_eq!(fitted.lifespan_ms, 0);
6154 assert_eq!(fitted.reliability, q.reliability);
6155 assert_eq!(fitted.durability, q.durability);
6156 assert_eq!(fitted.depth, q.depth);
6157 assert!(fitted.validate_against(XRCE).is_ok());
6158 }
6159
6160 /// A backend that honours everything changes nothing.
6161 #[test]
6162 fn a_supported_profile_is_returned_unchanged() {
6163 let q = rosout_like();
6164 let (fitted, dropped) = q.fit_to_supported(QoSPolicyMask(u32::MAX));
6165 assert_eq!(fitted, q);
6166 assert_eq!(dropped, QoSPolicyMask::NONE);
6167 }
6168
6169 /// The same step-down as a best-available field: TRANSIENT_LOCAL to
6170 /// VOLATILE, a manual liveliness to AUTOMATIC, then to none.
6171 #[test]
6172 fn every_policy_steps_down_by_the_best_available_rule() {
6173 let q = QoSProfile {
6174 durability: QoSDurabilityPolicy::TransientLocal,
6175 liveliness_kind: QoSLivelinessPolicy::ManualByNode,
6176 liveliness_lease_ms: 500,
6177 deadline_ms: 100,
6178 ..rosout_like()
6179 };
6180 let mask = QoSPolicyMask::RELIABILITY
6181 | QoSPolicyMask::DURABILITY_VOLATILE
6182 | QoSPolicyMask::HISTORY
6183 | QoSPolicyMask::DEPTH
6184 | QoSPolicyMask::LIVELINESS_AUTOMATIC;
6185 let (fitted, dropped) = q.fit_to_supported(mask);
6186 assert_eq!(fitted.durability, QoSDurabilityPolicy::Volatile);
6187 assert_eq!(fitted.liveliness_kind, QoSLivelinessPolicy::Automatic);
6188 assert_eq!(
6189 (
6190 fitted.deadline_ms,
6191 fitted.liveliness_lease_ms,
6192 fitted.lifespan_ms
6193 ),
6194 (0, 0, 0)
6195 );
6196 assert!(fitted.validate_against(mask).is_ok());
6197 assert!(dropped.contains(QoSPolicyMask::DURABILITY_TRANSIENT_LOCAL));
6198 assert!(dropped.contains(QoSPolicyMask::LIFESPAN));
6199 assert!(dropped.contains(QoSPolicyMask::DEADLINE));
6200 }
6201
6202 /// History and depth have no weaker form: a runtime profile that needs
6203 /// one the backend lacks keeps it, is not reported as dropped, and is
6204 /// still refused.
6205 #[test]
6206 fn a_policy_with_no_weaker_form_is_still_refused() {
6207 let q = rosout_like();
6208 let mask = QoSPolicyMask::RELIABILITY | QoSPolicyMask::DURABILITY_VOLATILE;
6209 let (fitted, dropped) = q.fit_to_supported(mask);
6210 assert!(!dropped.contains(QoSPolicyMask::HISTORY));
6211 assert!(!dropped.contains(QoSPolicyMask::DEPTH));
6212 assert!(fitted.validate_against(mask).is_err());
6213 }
6214}