nros_node/executor/node_record.rs
1//! Multi-Node-per-Executor storage.
2//!
3//! Mirrors the `rclcpp` pattern where a single `Executor` holds N
4//! `Node`s via `add_node(...)`. Each Node carries its own
5//! name/namespace + a reference to the Session that backs it +
6//! a default `SchedContext` handles inherit unless
7//! overridden.
8//!
9//! For now this is the *storage scaffold* + the builder
10//! API. Multi-Session-per-Executor dispatch is a follow-up
11//! — today every Node in this list resolves to the
12//! Executor's primary session, which means `node_builder.rmw(name)`
13//! only accepts the same backend the Executor was opened against.
14//! Bridge use cases (two RMW backends concurrent in one Executor)
15//! light up when 104.C.3 adds the per-Node session ref.
16
17use super::{sched_context::SchedContextId, types::NodeError};
18
19/// Opaque handle returned by `Executor::node_builder(...).build()`.
20/// Used in 104.C.3+ to disambiguate handle ownership when multiple
21/// Nodes coexist in one Executor.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23pub struct NodeId(pub(crate) u8);
24
25impl NodeId {
26 /// Reserved id for the implicit "primary" Node that mirrors the
27 /// original single-Node Executor identity.
28 pub const PRIMARY: NodeId = NodeId(0);
29
30 /// Numeric index into the Executor's node table.
31 pub fn index(self) -> usize {
32 self.0 as usize
33 }
34
35 /// Build a `NodeId` from a raw `u8` for
36 /// FFI consumers that store the index in their own struct
37 /// (`rcl_node_t.node_id`, `nros_cpp_node_t.node_id`). The value
38 /// is not validated against the executor's `nodes` table — the
39 /// caller is responsible for only constructing ids that
40 /// `node_builder(...).build()` previously returned. Out-of-range
41 /// ids fail loudly at the next `with_node` / `_on(...)` call.
42 pub const fn from_raw(raw: u8) -> NodeId {
43 NodeId(raw)
44 }
45
46 /// Raw u8 form for FFI persistence.
47 pub const fn raw(self) -> u8 {
48 self.0
49 }
50}
51
52/// phase-426 W1 — the parameter store's node key IS this index.
53///
54/// `nros-params` sits below `nros-node` in the layer graph, so it cannot name
55/// `NodeId`; it defines the same one-byte index as
56/// [`nros_params::NodeKey`] and this is the one conversion between them. One
57/// spelling, so a store lookup can never be keyed on a number derived some
58/// other way.
59impl From<NodeId> for nros_params::NodeKey {
60 fn from(id: NodeId) -> Self {
61 nros_params::NodeKey::new(id.raw())
62 }
63}
64
65/// Per-Node metadata stored inside the Executor.
66///
67/// The shape is minimal — name, namespace,
68/// default SchedContext, optional rmw-name for diagnostics. Future
69/// items: per-Node session reference, per-Node liveliness
70/// state, per-Node parameter overrides.
71pub struct NodeRecord {
72 pub name: heapless::String<64>,
73 pub namespace: heapless::String<64>,
74 /// RMW backend the Node was created against. `None` for the
75 /// implicit primary Node populated from `Executor::open`.
76 pub rmw_name: Option<heapless::String<32>>,
77 /// Per-Node locator override. `None` = use the Executor's
78 /// session-level locator.
79 pub locator: Option<heapless::String<128>>,
80 /// Default `SchedContext` for handles created via this Node.
81 /// Handles may override per-call. `SchedContextId::default()` =
82 /// the executor's auto-created Fifo slot (slot 0).
83 pub default_sched: SchedContextId,
84 /// Session-slot index. `0` resolves to the
85 /// Executor's primary `session` field; `N >= 1` resolves to
86 /// `extra_sessions[N-1]`. Each Node may bind to a different
87 /// session, enabling multi-RMW bridges in one Executor.
88 pub session_idx: u8,
89 /// The node's contract rank, 0 = most
90 /// urgent, seeded by `Executor::bind_node_rank` before the node is built.
91 /// Every callback the node registers dispatches at it. 0 when unseeded.
92 pub rank: u8,
93 /// Per-node QoS-override table, in the
94 /// SAME primitive `(topic, role, policy, value)` code form the C and C++
95 /// ABIs use (`rclc_qos_override_t` / `nros_cpp_qos_override_t`).
96 ///
97 /// Codes rather than [`nros_rmw::QoSOverride`] because the entry codegen
98 /// bakes this through `RuntimeCtx`, and `nros-platform` sits BELOW
99 /// `nros-rmw` in the layer graph — a typed field there would invert it.
100 /// Decoded at entity-create time by [`decode_qos_override`](nros_rmw::decode_qos_override).
101 ///
102 /// Empty by default: a system with no overrides pays nothing.
103 pub qos_overrides: &'static [QoSOverrideCode],
104 /// phase-556 W13 -- this node's `/rosout` writer, which the executor owns.
105 /// Created on the spin after the node is built (see
106 /// `Executor::reconcile_rosout`) and dropped with the record, by
107 /// `Executor::disable_rosout_on`, or at `close()`.
108 #[cfg(feature = "rosout")]
109 pub(crate) rosout: RosoutWriter,
110 /// Whether this node's publishers may send. A managed node's
111 /// lifecycle machine writes it on every transition; every publisher the
112 /// node creates reads it. Lives in the record because the node table is
113 /// carved from the executor's backing and never moves.
114 pub(crate) publish_gate: PublishGate,
115}
116
117pub use crate::lifecycle::PublishGate;
118
119/// phase-556 W13 -- the state of one node's runtime-owned `/rosout` writer.
120// `Up` holds the backend's publisher inline: 648 bytes with the C-vtable
121// backend (`rmw-cffi`), where clippy's `large_enum_variant` fires. Boxing it
122// is not available: `rosout` does not require `alloc`, and the node table
123// lives in the executor's caller-supplied arena. Nor would it save anything:
124// a node's writer is created on the first spin after the node is built, so
125// `Up` is the state every record spends its life in, and the dataless
126// variants are the short-lived ones.
127#[allow(clippy::large_enum_variant)]
128#[cfg(feature = "rosout")]
129pub(crate) enum RosoutWriter {
130 /// Not created yet; the next spin creates it.
131 Pending,
132 /// Up: the pump routes this node's records here.
133 Up(crate::session::RmwPublisher),
134 /// Creation failed with an error a retry cannot change; reported once.
135 Refused,
136 /// Turned off for this node (`Executor::disable_rosout_on`).
137 Off,
138}
139
140#[cfg(feature = "rosout")]
141impl RosoutWriter {
142 pub(crate) fn publisher(&self) -> Option<&crate::session::RmwPublisher> {
143 match self {
144 Self::Up(p) => Some(p),
145 _ => None,
146 }
147 }
148}
149
150/// Issue #52 / 0303 — one baked QoS override, re-exported from `nros-rmw`
151/// where the single decoder lives. Kept as a name here because `NodeRecord`
152/// and the entry bake spell it.
153pub use nros_rmw::QoSOverrideCode;
154
155/// Fold a node's baked override codes into `qos` for one `(topic, role)`.
156/// Thin alias over [`nros_rmw::QoSProfile::apply_override_codes`], which
157/// collapsed four copies of this match into one.
158pub fn apply_qos_override_codes(
159 qos: nros_rmw::QoSProfile,
160 topic: &str,
161 role: nros_rmw::QoSOverrideRole,
162 codes: &[QoSOverrideCode],
163) -> nros_rmw::QoSProfile {
164 qos.apply_override_codes(topic, role, codes)
165}
166
167impl NodeRecord {
168 /// Construct the implicit "primary" NodeRecord that mirrors the
169 /// Executor's pre-104.C.2 single-Node identity. Currently unused
170 /// (the primary Node is implicit until 104.C.3 wires per-Node
171 /// dispatch); kept here for the upcoming migration where every
172 /// Executor will have an explicit entry at slot 0.
173 #[allow(dead_code)]
174 pub(crate) fn new_primary(name: heapless::String<64>, namespace: heapless::String<64>) -> Self {
175 Self {
176 name,
177 namespace,
178 rmw_name: None,
179 locator: None,
180 default_sched: SchedContextId(0),
181 session_idx: 0,
182 rank: 0,
183 qos_overrides: &[],
184 #[cfg(feature = "rosout")]
185 rosout: RosoutWriter::Pending,
186 publish_gate: PublishGate::unmanaged(),
187 }
188 }
189}
190
191/// Builder returned by `Executor::node_builder(name)`. Chainable
192/// configuration; `.build()` registers the Node with the Executor
193/// and returns a [`NodeId`].
194///
195/// rclcpp-aligned API. Mirrors:
196///
197/// ```ignore
198/// rclcpp::Node::make_shared("my_node",
199/// rclcpp::NodeOptions().use_intra_process_comms(true))
200/// ```
201///
202/// Where rclcpp uses a single `NodeOptions` struct, we expose the
203/// individual setters directly on the builder — fewer cycles when
204/// the user only needs one option.
205pub struct NodeBuilder<'a, 'cfg, 's> {
206 pub(crate) executor: &'a mut super::spin::Executor<'s>,
207 pub(crate) name: &'cfg str,
208 pub(crate) namespace: Option<&'cfg str>,
209 pub(crate) rmw_name: Option<&'cfg str>,
210 pub(crate) locator: Option<&'cfg str>,
211 pub(crate) domain_id: Option<u32>,
212 pub(crate) sched: Option<SchedContextId>,
213 /// Phase 172.K.5 — explicit session slot (index into the sessions opened
214 /// by `open_multi`: 0 = primary, N = `extra_sessions[N-1]`). When set,
215 /// `build()` binds the Node directly to this session and **bypasses** the
216 /// rmw-based `resolve_session_slot` — the planner/generator already knows
217 /// which `SESSION_SPECS` slot each node belongs to (e.g. its domain group),
218 /// so no rmw/domain inference is needed. `None` ⇒ the legacy rmw-resolved
219 /// slot.
220 pub(crate) session_idx: Option<u8>,
221}
222
223impl<'a, 'cfg, 's> NodeBuilder<'a, 'cfg, 's> {
224 /// Select an RMW backend by name. `name` must match a backend
225 /// registered via `nros_rmw_cffi_register_named`.
226 ///
227 /// For now, the name must match the backend
228 /// the Executor was opened against — bridge mode lands
229 /// when per-Node sessions are wired. Passing a name
230 /// that doesn't match the Executor's session returns
231 /// `Err(NodeError::BackendMismatch)` from `.build()`.
232 pub fn rmw(mut self, name: &'cfg str) -> Self {
233 self.rmw_name = Some(name);
234 self
235 }
236
237 /// Override the locator for this Node's session. Empty / unset =
238 /// use the Executor's locator.
239 pub fn locator(mut self, locator: &'cfg str) -> Self {
240 self.locator = Some(locator);
241 self
242 }
243
244 /// Override the domain id for this Node's session.
245 pub fn domain_id(mut self, domain_id: u32) -> Self {
246 self.domain_id = Some(domain_id);
247 self
248 }
249
250 /// Bind this Node to an explicit session slot (index into
251 /// the sessions opened by [`Executor::open_multi`](crate::executor::Executor::open_multi): `0` = primary,
252 /// `N` = `extra_sessions[N-1]`). Bypasses the rmw-based session resolution
253 /// — the caller (generated multi-domain wiring) already knows the slot.
254 pub fn session_idx(mut self, idx: u8) -> Self {
255 self.session_idx = Some(idx);
256 self
257 }
258
259 /// Namespace for handles created via this Node. Empty = "/".
260 pub fn namespace(mut self, namespace: &'cfg str) -> Self {
261 self.namespace = Some(namespace);
262 self
263 }
264
265 /// Default [`SchedContext`](super::sched_context::SchedContext) for
266 /// handles registered via this Node.
267 /// handles inherit this unless they pass their own SchedContext
268 /// at registration time.
269 pub fn sched(mut self, sched: SchedContextId) -> Self {
270 self.sched = Some(sched);
271 self
272 }
273
274 /// Phase 104.C.3 — pick a session slot for the Node being
275 /// built. Returns `0` for the primary session (no rmw override
276 /// or rmw matches existing) and `N >= 1` for an extra session
277 /// just opened via `CffiRmw::open_with_rmw`.
278 #[cfg(feature = "rmw-cffi")]
279 fn resolve_session_slot(&mut self) -> Result<u8, NodeError> {
280 let Some(rmw) = self.rmw_name else {
281 return Ok(0);
282 };
283
284 // Phase 156 — check primary FIRST. Executor::open* records
285 // `primary_rmw_name` + `primary_locator` so we can detect
286 // when a `.rmw(name)` matches the primary session and
287 // return slot 0 instead of opening a SECOND backend
288 // session against the same singleton (which zenoh-pico's
289 // global g_session forbids). Locator-None means "inherit
290 // primary"; locator-Some must match primary's exactly.
291 // Empty `primary_rmw_name` → constructed via
292 // `from_session(_ptr)` without `open*` recording — fall
293 // through to extras cache + new-session path.
294 if !self.executor.primary_rmw_name.is_empty()
295 && self.executor.primary_rmw_name.as_str() == rmw
296 {
297 let locator_matches = match self.locator {
298 None => true,
299 Some(loc) => self.executor.primary_locator.as_str() == loc,
300 };
301 if locator_matches {
302 return Ok(0);
303 }
304 }
305
306 // Reuse an extra session if one already opened against the
307 // same rmw + locator. Slot 0 (primary) handled by the
308 // primary-identity check above.
309 // Issue 0436 — match the extras' RECORDED identity (rmw + locator). This
310 // is what lets a Node bind to a session `open_multi` opened: previously the
311 // only signal was a prior NodeRecord bound to that slot, so the FIRST node
312 // naming a backend always missed and fell through to opening a SECOND
313 // session against it (which fails — the backend's global state is a
314 // process singleton).
315 for (i, id) in self.executor.extra_session_ids.iter().enumerate() {
316 let (sess_rmw, sess_loc) = id;
317 if sess_rmw.as_str() == rmw {
318 let locator_matches = match self.locator {
319 // No locator requested → inherit whatever this session opened with.
320 None => true,
321 Some(loc) => sess_loc.as_str() == loc,
322 };
323 if locator_matches {
324 return Ok((i + 1) as u8);
325 }
326 }
327 }
328
329 for (i, sess) in self.executor.extra_sessions.iter().enumerate() {
330 let _ = sess;
331 // Phase 104.C.3 doesn't yet store rmw-name per session;
332 // dedupe by NodeRecord's stored rmw_name + locator.
333 if let Some(prev) = self.executor.nodes.iter().find(|n| {
334 n.session_idx as usize == i + 1
335 && n.rmw_name.as_deref() == Some(rmw)
336 && n.locator.as_deref() == self.locator
337 }) {
338 let _ = prev;
339 return Ok((i + 1) as u8);
340 }
341 }
342
343 // First Node naming this rmw → open a new session.
344 let mode = nros_rmw::SessionMode::Client;
345 let locator = self.locator.unwrap_or("");
346 let domain_id = self.domain_id.unwrap_or(0);
347 let cfg = nros_rmw::RmwConfig {
348 locator,
349 mode,
350 domain_id,
351 node_name: self.name,
352 namespace: self.namespace.unwrap_or(""),
353 properties: &[],
354 };
355 let session = nros_rmw_cffi::CffiRmw::open_with_rmw(rmw, &cfg)
356 .map_err(crate::executor::types::NodeError::Transport)?;
357 self.executor
358 .extra_sessions
359 .push(session)
360 .map_err(|_| NodeError::NodeTableFull)?;
361 // Issue 0436 — record identity here too, so the NEXT node naming this
362 // backend reuses the session instead of opening another.
363 {
364 let mut rmw_s = heapless::String::<32>::new();
365 let _ = rmw_s.push_str(rmw);
366 let mut loc_s = heapless::String::<128>::new();
367 let _ = loc_s.push_str(locator);
368 let _ = self.executor.extra_session_ids.push((rmw_s, loc_s));
369 }
370 let idx = self.executor.extra_sessions.len();
371 if idx > u8::MAX as usize {
372 return Err(NodeError::NodeTableFull);
373 }
374 // Phase 104.C.6.b — install the shared wake flag on the
375 // freshly opened extra session so its backend notifications
376 // can short-circuit `spin_once`.
377 //
378 // BOTH flavours, mirroring the construction path in
379 // `Executor::open_in`. Until now only the `std` arm was here, so a
380 // no_std build opening an extra session through THIS path (the
381 // dynamic one — a node naming a second RMW) never installed the
382 // wake callback: arrivals on that session could not short-circuit
383 // `spin_once`, and its traffic waited up to the full spin timeout
384 // instead of waking on arrival. Silent, latency-only, and no_std-only.
385 // The installer already existed; it simply was not called here.
386 //
387 // phase-359 W10 — one call. These were two arms naming two functions,
388 // `install_wake_signal_on_extra` and its `_alloc` mirror; the mirror is
389 // gone, so what was left was the same call written twice under
390 // complementary gates.
391 #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
392 self.executor.install_wake_signal_on_extra(idx - 1);
393 Ok(idx as u8)
394 }
395
396 #[cfg(not(feature = "rmw-cffi"))]
397 fn resolve_session_slot(&mut self) -> Result<u8, NodeError> {
398 // Without `rmw-cffi`, only the primary session exists. An
399 // rmw-name override is meaningless; treat as the primary.
400 Ok(0)
401 }
402
403 /// Register the Node with the Executor and return its
404 /// [`NodeId`]. Bumps `Executor.nodes.len()`; fails if the table
405 /// is full (`NROS_EXECUTOR_MAX_NODES` reached) or the name is
406 /// too long.
407 pub fn build(mut self) -> Result<NodeId, NodeError> {
408 if self.name.len() > 64 {
409 return Err(NodeError::NameTooLong);
410 }
411
412 // Phase 104.C.2 — single-session check. rmw mismatch is an
413 // error today; 104.C.3 will accept and open a new session
414 // via the session cache.
415 if let Some(_requested) = self.rmw_name {
416 // No accessor for the current session's rmw name yet —
417 // the registry first-registered slot drives the
418 // singleton. We accept any rmw name in C.2 (no
419 // validation) so consumer code is forward-compatible.
420 // C.3 adds the mismatch check + session-cache lookup.
421 }
422
423 let mut name_buf = heapless::String::<64>::new();
424 name_buf
425 .push_str(self.name)
426 .map_err(|_| NodeError::NameTooLong)?;
427
428 let mut ns_buf = heapless::String::<64>::new();
429 if let Some(ns) = self.namespace {
430 ns_buf.push_str(ns).map_err(|_| NodeError::NameTooLong)?;
431 } else {
432 ns_buf
433 .push_str(self.executor.namespace.as_str())
434 .map_err(|_| NodeError::NameTooLong)?;
435 }
436
437 let mut rmw_buf = None;
438 if let Some(rmw) = self.rmw_name {
439 let mut s = heapless::String::<32>::new();
440 s.push_str(rmw).map_err(|_| NodeError::NameTooLong)?;
441 rmw_buf = Some(s);
442 }
443
444 let mut loc_buf = None;
445 if let Some(loc) = self.locator {
446 let mut s = heapless::String::<128>::new();
447 s.push_str(loc).map_err(|_| NodeError::NameTooLong)?;
448 loc_buf = Some(s);
449 }
450
451 // Phase 172.K.5 — an explicit `.session_idx(n)` binds the Node to a
452 // pre-opened `open_multi` session directly (validated against the
453 // opened set), bypassing rmw resolution. Otherwise (Phase 104.C.3)
454 // resolve by rmw: slot 0 for no/primary-matching rmw, else open/reuse
455 // an extra session.
456 let session_idx = match self.session_idx {
457 Some(idx) => {
458 if idx as usize > self.executor.extra_sessions.len() {
459 return Err(NodeError::NodeTableFull);
460 }
461 idx
462 }
463 None => self.resolve_session_slot()?,
464 };
465
466 // Phase 272 (RFC-0047) — resolve default_sched with precedence:
467 // explicit .sched() > table lookup > SchedContextId(0)
468 //
469 // The lookup borrows `self.executor` immutably and returns a Copy
470 // value, so the borrow ends before the mutable `nodes.push` below.
471 let default_sched = match self.sched {
472 Some(id) => id,
473 None => self
474 .executor
475 .lookup_node_sched(name_buf.as_str(), ns_buf.as_str())
476 .unwrap_or(SchedContextId(0)),
477 };
478
479 // phase-509 P2 -- the rank codegen seeded for this node, 0 if none.
480 let rank = self
481 .executor
482 .lookup_node_rank(name_buf.as_str(), ns_buf.as_str());
483
484 let record = NodeRecord {
485 name: name_buf,
486 namespace: ns_buf,
487 rmw_name: rmw_buf,
488 locator: loc_buf,
489 default_sched,
490 session_idx,
491 rank,
492 // Installed after creation by `Executor::set_node_qos_overrides`
493 // (the entry codegen's bake) — a builder never carries them.
494 qos_overrides: &[],
495 #[cfg(feature = "rosout")]
496 rosout: RosoutWriter::Pending,
497 publish_gate: PublishGate::unmanaged(),
498 };
499
500 // Issue 2681 -- the census hears every node this builder creates, the
501 // imperative Rust routes included, BEFORE the table answers. Behind the
502 // feature only a metadata probe turns on, like every observer.
503 #[cfg(feature = "registration-observer")]
504 crate::executor::registration_observer::observe_node_create(
505 crate::executor::registration_observer::ObservedNodeCreate {
506 name: record.name.as_str(),
507 namespace: record.namespace.as_str(),
508 },
509 );
510 self.executor
511 .nodes
512 .push(record)
513 .map_err(|_| NodeError::NodeTableFull)?;
514 let idx = self.executor.nodes.len() - 1;
515 if idx > u8::MAX as usize {
516 // The carved table's capacity (`ExecutorSizing::nodes`) is far
517 // below u8::MAX; defensive only.
518 return Err(NodeError::NodeTableFull);
519 }
520 // phase-556 W13 -- start queueing for `/rosout` as soon as a node
521 // exists, so records logged before the first spin (the boot story)
522 // are published when that spin creates the node's writer. Idempotent.
523 // A sink table that is full is reported by the reconcile, which
524 // asks again.
525 #[cfg(feature = "rosout")]
526 let _ = crate::rosout::enable();
527 // RFC-0128 D8 (phase-554 W3 slice B) -- the primary node now exists,
528 // so an executor-level entity waiting for it (the `/diagnostics`
529 // reporter) opens on it here, before any spin. Its failure is this
530 // registration's: the node is taken back out so no half-registered
531 // primary is left behind.
532 if idx == NodeId::PRIMARY.index() {
533 if let Err(e) = self.executor.run_primary_node_hook() {
534 // The primary is the only record (`idx == 0`), so this is
535 // exactly that one.
536 self.executor.nodes.clear();
537 return Err(e);
538 }
539 }
540 Ok(NodeId(idx as u8))
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547 use nros_rmw::{
548 QoSDurabilityPolicy, QoSHistoryPolicy, QoSOverrideRole, QoSProfile, QoSReliabilityPolicy,
549 };
550
551 /// Issue #52 — the primitive codes decode to the same overrides the C and
552 /// C++ ABIs spell, and fold only into the matching `(topic, role)`.
553 #[test]
554 fn codes_fold_into_the_matching_topic_and_role() {
555 const CODES: &[QoSOverrideCode] = &[
556 // /chatter publisher reliability = best_effort
557 ("/chatter", 0, 0, 0),
558 // /chatter subscription depth = 7
559 ("/chatter", 1, 3, 7),
560 // /other publisher durability = transient_local
561 ("/other", 0, 1, 1),
562 ];
563
564 let pub_qos = apply_qos_override_codes(
565 QoSProfile::default(),
566 "/chatter",
567 QoSOverrideRole::Publisher,
568 CODES,
569 );
570 assert_eq!(pub_qos.reliability, QoSReliabilityPolicy::BestEffort);
571 // The subscription-side depth entry must NOT leak onto the publisher.
572 assert_eq!(pub_qos.depth, QoSProfile::default().depth);
573 // Nor the other topic's durability.
574 assert_eq!(pub_qos.durability, QoSProfile::default().durability);
575
576 let sub_qos = apply_qos_override_codes(
577 QoSProfile::default(),
578 "/chatter",
579 QoSOverrideRole::Subscription,
580 CODES,
581 );
582 assert_eq!(sub_qos.depth, 7);
583 assert_eq!(sub_qos.reliability, QoSProfile::default().reliability);
584
585 let other = apply_qos_override_codes(
586 QoSProfile::default(),
587 "/other",
588 QoSOverrideRole::Publisher,
589 CODES,
590 );
591 assert_eq!(other.durability, QoSDurabilityPolicy::TransientLocal);
592 }
593
594 /// An unrecognised role or policy code is SKIPPED, never applied as a
595 /// silently wrong override.
596 #[test]
597 fn unknown_codes_are_skipped_not_guessed() {
598 const BAD: &[QoSOverrideCode] = &[("/t", 9, 0, 1), ("/t", 0, 9, 1)];
599 assert!(nros_rmw::decode_qos_override(&BAD[0]).is_none());
600 assert!(nros_rmw::decode_qos_override(&BAD[1]).is_none());
601 let qos =
602 apply_qos_override_codes(QoSProfile::default(), "/t", QoSOverrideRole::Publisher, BAD);
603 assert_eq!(qos, QoSProfile::default());
604 }
605
606 /// History `keep_all` and reliability `reliable` are the non-default arms —
607 /// pin them so a code-table renumbering cannot pass silently.
608 #[test]
609 fn history_and_reliability_arms_decode() {
610 let qos = apply_qos_override_codes(
611 QoSProfile::default(),
612 "/t",
613 QoSOverrideRole::Subscription,
614 &[("/t", 1, 2, 1), ("/t", 1, 0, 1)],
615 );
616 assert_eq!(qos.history, QoSHistoryPolicy::KeepAll);
617 assert_eq!(qos.reliability, QoSReliabilityPolicy::Reliable);
618 }
619
620 /// An empty table leaves QoS untouched — the common case pays nothing.
621 #[test]
622 fn empty_table_is_a_no_op() {
623 let qos =
624 apply_qos_override_codes(QoSProfile::default(), "/t", QoSOverrideRole::Publisher, &[]);
625 assert_eq!(qos, QoSProfile::default());
626 }
627}