Skip to main content

nros/
lib.rs

1//! # nros
2//!
3//! A lightweight ROS 2 client library for embedded systems.
4//!
5//! This crate provides a unified API for building ROS 2 nodes in Rust,
6//! with support for `no_std` environments and embedded targets.
7//!
8//! ## Features
9//!
10//! - **no_std compatible**: Works on bare-metal and RTOS targets
11//! - **Zero-copy where possible**: Minimizes memory allocations
12//! - **Type-safe**: Compile-time verification of message types
13//! - **ROS 2 compatible**: Interoperates with standard ROS 2 nodes via rmw_zenoh
14//!
15//! ## Quick Start
16//!
17//! ```ignore
18//! use nros::prelude::*;
19//! use std_msgs::msg::Int32;
20//!
21//! let config = ExecutorConfig::from_env().node_name("my_node");
22//! let mut executor = Executor::open(&config)?;
23//!
24//! let node = executor.node_builder("my_node").build()?;
25//! let publisher = executor.node_mut(node).create_publisher::<Int32>("/my_topic")?;
26//! publisher.publish(&Int32 { data: 42 })?;
27//!
28//! executor.node_mut(node).create_subscription::<Int32, _>("/topic", |msg: &Int32| {
29//!     println!("Received: {}", msg.data);
30//! })?;
31//!
32//! executor.spin(SpinOptions::default());
33//! ```
34//!
35//! ## Executor Sizing
36//!
37//! The executor's static memory layout is controlled via environment variables
38//! at build time:
39//!
40//! - **`NROS_EXECUTOR_MAX_CBS`** (default 4) — maximum number of registered
41//!   callbacks (subscriptions + timers + services + guard conditions).
42//! - **`NROS_EXECUTOR_ARENA_BYTES`** (default 4096) — byte budget for storing
43//!   callback closures inline.
44//!
45//! A subscription's arena receive buffer is sized from the MESSAGE TYPE's own
46//! serialized bound, not from that knob, wherever the bound is
47//! reachable. `.rx_buffer::<N>()` is the opt-out: it says "give me exactly `N`
48//! bytes per slot" and skips the derivation, which is what a peer that pads or
49//! a `.msg` bound looser than the traffic needs (e.g.
50//! `node_mut(id).subscription(t).typed::<M>().rx_buffer::<4096>().build(cb)`).
51//!
52//! ## Transport Backends
53//!
54//! `nros` is RMW- and platform-AGNOSTIC. It carries only the
55//! `rmw-cffi` vtable; the concrete backend (zenoh / xrce / cyclonedds) enters
56//! the link graph via the board crate (embedded), the board-less app's own
57//! `nros-rmw-*` dep (native), or the `nros-c`/`nros-cpp` staticlib root (D3),
58//! and self-registers — before `main` on a hosted target (an `.init_array`
59//! ctor; the ~~`RMW_INIT_ENTRIES`~~ walker at `Executor::open`
60//! before that), or through the board's explicit `<backend>::register()`.
61//! The concrete session type is resolved automatically; advanced users can
62//! access it via `nros::internals::RmwSession`.
63//!
64//! ## Crate Features
65//!
66//! `nros` exposes only FUNCTIONAL features — `std`/`alloc`, the `rmw-cffi`
67//! vtable, `lending`, `bridge`/`config`, `param-services`,
68//! `lifecycle-services`, `safety-e2e`, `stream`, and the ROS
69//! edition (`ros-humble`/`ros-iron`). There are NO `platform-*` or concrete
70//! `rmw-*` selector features. Platform + RMW are selected by the
71//! board / staticlib root via dependencies, not `nros` features. The
72//! `zephyr_component_main!` entry macro is gated only on `rmw-cffi` (it's
73//! framework entry codegen, like `nros::main!`), not a platform feature.
74//!
75//! **ROS edition** (select one; the per-distro interop profile):
76//! - `ros-humble` - ROS 2 Humble (default; `TypeHashNotSupported`, XCDR1)
77//! - `ros-iron` - ROS 2 Iron (RIHS01 type hash)
78//! - `ros-jazzy` - ROS 2 Jazzy (RIHS01; XCDR2/appendable interop is parked)
79//!
80//! **Other**:
81//! - `std` (default) - Enable standard library support
82//! - `alloc` - Enable heap allocation without full std
83//!
84//! ## Further Reading
85//!
86//! - [`guide`] — tutorials: getting started, services, configuration,
87//!   ROS 2 interop, and troubleshooting
88//! - [Message Generation](https://github.com/jerry73204/nano-ros/blob/main/docs/guides/message-generation.md)
89//!   — codegen reference (all options, output structure, bundled interfaces)
90//! - [Environment Variables](https://github.com/jerry73204/nano-ros/blob/main/docs/reference/environment-variables.md)
91//!   — complete buffer tuning reference
92//! - [ROS 2 Interop](https://github.com/jerry73204/nano-ros/blob/main/docs/reference/rmw_zenoh_interop.md)
93//!   — protocol details (key expressions, liveliness, attachments)
94//! - [Examples](https://github.com/jerry73204/nano-ros/tree/main/examples)
95//!   — working examples by platform (native, QEMU, ESP32, Zephyr)
96
97#![no_std]
98
99// ── Feature validation (mutual exclusivity) ─────────────────────────────
100// Phase 248 C5c/C7 — `nros` carries NO `platform-*` selector features, so the
101// platform mutual-exclusion `compile_error!` is gone. The platform is selected
102// by the board / staticlib root via an `nros-platform` dep, and nros-node picks
103// the kernel primitive at runtime (C2 wake-probe).
104// Only `rmw-cffi` is exposed at this layer; the cffi shim selects the
105// concrete backend at the C ABI level from its registry (filled by each
106// backend's self-registration; the ~~`RMW_INIT_ENTRIES`~~ walker once).
107
108// At most one ROS edition (RFC-0056 — the axis is compile-time exclusive).
109#[cfg(any(
110    all(
111        feature = "ros-humble",
112        any(feature = "ros-iron", feature = "ros-jazzy")
113    ),
114    all(feature = "ros-iron", feature = "ros-jazzy"),
115))]
116compile_error!("`ros-{humble,iron,jazzy}` are mutually exclusive — select one ROS edition.");
117
118// phase-359 W10 stage B — no `std` feature. The hosted edge (`env`) reads
119// through the C library; only the test harness links `std`.
120#[cfg(test)]
121extern crate std;
122
123#[cfg(feature = "alloc")]
124extern crate alloc;
125
126// Phase 216.A.5 — the `nros::node!()` proc-macro emits absolute paths
127// under `::nros::*` (so downstream Node pkgs only need a single `nros`
128// dep). For the in-crate macro-expansion test in `node.rs`, alias the
129// `nros` crate name to itself so those absolute paths resolve. Gated on
130// `cfg(test)` to keep the alias out of normal builds.
131#[cfg(test)]
132extern crate self as nros;
133
134// Phase 248 C5c — the umbrella's force-link statics
135// (`__FORCE_LINK_{PLATFORM_CFFI,ZENOH,XRCE,CYCLONEDDS_SYS}`) are REMOVED along
136// with `nros`'s concrete-backend deps. `nros` no longer references any concrete
137// RMW or platform crate, so it has nothing to force-link. Registration + the
138// `nros_platform_*` link anchor now live with whoever owns the concrete crate:
139//   * embedded   — the BOARD crate force-links its backend + calls
140//     `<backend>::register()` in its boot path (C5a);
141//   * board-less native — the APP owns `nros-rmw-*` + a `#[used]` force-link in
142//     its `main.rs`, and `nros-platform-cffi[posix-c-port]` anchors the C symbols;
143//   * C/C++ staticlib — `nros-c`/`nros-cpp` bundle one backend (D3) and anchor
144//     `nros-platform` themselves.
145
146// Phase 249 P1 — `__register_linked_rmw()` (a Phase 248 C5c no-op kept only so the
147// `nros::main!` framework's call sites compiled) is REMOVED along with those call
148// sites. Backend registration never routed through the backend-agnostic `nros` crate:
149// hosted auto-registers before `main` (an `.init_array` ctor, phase-249 P4b.1; the
150// ~~`RMW_INIT_ENTRIES`~~ walk at `Executor::open` before that); embedded
151// boards perform the explicit `<backend>::register()` in their boot path (C5a). One
152// Rust trigger = the board/app explicit register (phase-249).
153
154// phase-391 W5 — build-time knobs (`MAX_COMPONENTS`, `COMPONENT_SLOT_BYTES`).
155// Ungated: they are plain consts, useful to size caller-supplied storage
156// whether or not the runtime module that consumes them is compiled in.
157pub mod config;
158
159// phase-391 W5 — caller-supplied component-pool storage sizing. Ungated for the
160// same reason `config` is: plain arithmetic, useful to size a `static` whether
161// or not `node_runtime` is compiled in.
162// Issue 1419 / issue 1556 item 1 — the census hooks every language's node API
163// calls (unconditionally; the bodies exist only under `metadata-mode`).
164#[doc(hidden)]
165pub mod census_hooks;
166pub mod dispatch_tag;
167pub mod guide;
168#[cfg(feature = "metadata-mode")]
169pub mod metadata_mode;
170/// The host profile (`nros_node::executor::profile`), for the
171/// hosted edges that read `$NROS_PROFILE_OUT` (`nros-cpp`, `nros-board-linux`).
172#[cfg(all(feature = "profile-mode", feature = "rmw-cffi"))]
173pub use nros_node::executor::profile;
174// phase-562 W10.
175/// The run-to-completion level runner's deadlines.
176pub mod level_wake;
177/// The Rust sched task runners' level core: one
178/// executor per core, a worker per level.
179#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
180pub mod levels;
181pub mod node;
182pub mod node_metadata;
183/// Executor-backed component runtime.
184///
185/// Binds [`Node`] / [`ExecutableNode`] to a live
186/// [`Executor`] so a Node pkg can actually run (versus
187/// [`MetadataRecorder`] which
188/// is the planner-side metadata sink).
189///
190/// Gated on `rmw-cffi`; the underlying [`Executor`] is only present
191/// when an RMW backend is linked. The MACRO install
192/// path (per-class static storage, placed cells, slabbed ctxs) is alloc-free,
193/// so the module no longer demands `alloc` — only the dynamic
194/// `ExecutorNodeRuntime` half does, item-gated inside.
195#[cfg(feature = "rmw-cffi")]
196pub mod node_runtime;
197pub mod runtime_storage;
198
199/// What a `void*` executor handle crossing the language seam is,
200/// and the one check every seam in this crate makes before treating it as an
201/// `Executor` (a C/C++ entry's handle is an nros-cpp context, not one).
202pub mod executor_handle;
203
204/// Top-level init API, on every target.
205///
206/// Re-exported flat at the crate root: `nros::Context` (`alloc`),
207/// `nros::ContextSource`, `nros::InitError`, `nros::InitOptions` (every
208/// target); `nros::init()`, `nros::init_with_args(args)` (`env`).
209/// The `env` feature gates only the process-environment reader and the
210/// argv entry; freestanding, `Context::default_from_env()` is the
211/// bake (`Context::baked()`).
212pub mod init;
213
214/// The hosted edge of configuration: every env var nano-ros
215/// honours is read here, and the core takes values.
216///
217/// Read through the C library's `getenv`, so it needs
218/// a C library and not `std`: `target_os = "linux"` is "a C library is linked"
219/// on this tree. It exists on every Linux build, `env` or not, because the
220/// C / C++ entries of a `#![no_std]` image inside a host process
221/// (threadx-linux, freertos-posix) resolve their boot config
222/// through it. The `env` FEATURE is the user-facing half: `from_env`, `init*`,
223/// `Context::new`.
224#[cfg(target_os = "linux")]
225pub mod env;
226
227/// The boot task census of a Linux process (`/proc/self/task`), one reader
228/// for both Linux runners. Linux only, as [`mod@env`] is.
229#[cfg(target_os = "linux")]
230pub mod task_census;
231/// Where a hosted POSIX runner places zenoh-pico's transport tasks, one
232/// decision for both Linux runners.
233#[cfg(unix)]
234pub mod transport_band;
235
236/// The retired env aliases the hosted reader refuses.
237pub mod retired_env;
238/// What a sched task's thread is called (`nros-<label>`).
239pub mod thread_name;
240pub use retired_env::RETIRED_ENV_VARS;
241
242#[cfg(feature = "env")]
243pub use env::ExecutorConfigEnvExt;
244#[cfg(target_os = "linux")]
245pub use env::rmw_selector;
246
247pub use init::{ContextSource, InitError, InitOptions};
248
249#[cfg(feature = "alloc")]
250pub use init::Context;
251
252#[cfg(feature = "env")]
253pub use init::{init, init_with_args};
254
255/// Compile-time opaque storage sizes for FFI consumers.
256///
257/// See [`sizes`] for the `export_size!` pattern used to expose these values
258/// to `nros-c` / `nros-cpp` at build time.
259pub mod sizes;
260
261/// Monotonic time for portable node code.
262///
263/// `rmw-cffi`, not `any(std, rmw-cffi)`: the clock is the
264/// platform port's, and a build with no port has none to offer.
265#[cfg(feature = "rmw-cffi")]
266pub mod time;
267
268/// CDR encapsulation constants and helpers for FFI layers that handle raw
269/// CDR bytes (e.g. nros-c, nros-cpp action and service paths).
270pub mod cdr {
271    pub use nros_serdes::{
272        CDR_BE_HEADER, CDR_HEADER_LEN, CDR_LE_HEADER, strip_cdr_header, write_cdr_le_header,
273    };
274}
275
276// Re-export core types
277pub use nros_core::{
278    CdrReader, CdrWriter, Clock, ClockType, DeserError, Deserialize, Duration, MessageInfo,
279    PUBLISHER_GID_SIZE, REQUEST_WRITER_GUID_SIZE, RawMessageInfo, RequestId, RosMessage,
280    RosService, SecNanosecMsg, SerError, Serialize, ServiceInfo, Time,
281};
282
283// RFC-0141 — what the wall-clock stamps mean right now (synced, which source
284// answers), beside `Clock::system()` whose reading it qualifies. The C and C++
285// surfaces have it as `rclc_wall_clock_state()` / `rclcpp::Clock::wall_clock_state()`.
286pub use nros_core::{WallClockSource, WallClockState, wall_clock_state};
287
288// -----------------------------------------------------------------------------
289// Logging (phase-417 W4.d, issue 0589).
290//
291// `nros_log` was in this crate's dependency graph and reachable from NONE of
292// its surface: no `pub use`, nothing in the prelude. So from the façade the
293// shortest path to "print something" was `std::println!` — which is FATAL on
294// Zephyr `native_sim`: `zvfs_write(1, …)` dispatches to
295// `stdinout_write_vmeth`, which calls `zvfs_write(1, …)` again, and because
296// `k_mutex` is recursive it exhausts the stack instead of deadlocking. The
297// image dies with no message. A logging facade nobody can reach from the
298// umbrella is not a facade.
299//
300// `nros::Logger` IS RE-BOUND, and that is the point rather than a side effect.
301// It used to name `nros_core::logger::Logger`, which formats through the `log`
302// crate: on a target with no `log` backend installed — every embedded one —
303// the record is constructed and dropped, and it NEVER reaches
304// `nros_platform_log_write`. The type the C and C++ FFI hands out, the type
305// the `nros_*!` macros dispatch through, and the type the platform sink
306// receives is `nros_log::Logger`. One name, one meaning.
307//
308// Migration: the two types share `new` and `name` and NOTHING else — the old
309// one has inherent `.info(&str)` / `.warn(&str)` / `*_once` / `*_throttle`
310// methods, the new one is driven by the `nros_*!` macros. So every call site
311// that used the old surface FAILS TO COMPILE against the new binding rather
312// than silently changing where its records go. That is the RFC-0089 rule
313// applied to our own rename, and it is why this is a re-binding with a named
314// escape hatch instead of a quiet swap. The escape hatch was ~~`LogCrateLogger`~~,
315// deprecated on arrival and deleted by phase-482 W6.
316pub use nros_log::{
317    DEFAULT_LOGGER, LogSink, Logger, MAX_LOGGERS, Record as LogRecord, Severity, ThrottleState,
318    get_logger, get_or_create_logger, register_logger,
319};
320// The emission macros, at the crate root, because a user who has
321// `use nros::prelude::*` should not have to learn a second crate name to log a
322// line. `#[macro_export]` puts them at `nros_log`'s root; this puts them at
323// ours.
324//
325// NAMES (phase-417, RFC-0089 "each language follows ITS OWN upstream",
326// settled 2026-09-04). The three ROS 2 client libraries disagree about how to
327// spell a log line — `rclrs::log_info!`, `RCLCPP_INFO`,
328// `RCUTILS_LOG_INFO_NAMED` — so there is no one "ROS 2 spelling" to match.
329// Rust follows rclrs, because a node ported from rclrs is read beside rclrs.
330// Hence the five severity macros below carry rclrs's names.
331//
332// Two families keep OUR prefix, and that is a decision rather than an
333// oversight: a name takes rclrs's spelling exactly when rclrs HAS that name.
334//
335//   * `nros_trace!` — rclrs stops at `debug`. TRACE has no upstream twin, so
336//     giving it one would claim a correspondence that does not exist.
337//   * `nros_*_throttle!` / `nros_*_throttle_at!` — rclrs throttles with a
338//     MODIFIER on one macro (`log_info!(logger.throttle(d), "…")` via
339//     `LogParams` / `ToLogParams`), not a macro per severity. Adopting that is
340//     a shape change, not a rename; see `nros-log/src/macros.rs`'s throttle
341//     note for the three ledger rows it would have to reverse.
342pub use nros_log::{
343    log_debug, log_error, log_fatal, log_info, log_warn, nros_debug_throttle,
344    nros_debug_throttle_at, nros_error_throttle, nros_error_throttle_at, nros_fatal_throttle,
345    nros_fatal_throttle_at, nros_info_throttle, nros_info_throttle_at, nros_trace,
346    nros_trace_throttle, nros_trace_throttle_at, nros_warn_throttle, nros_warn_throttle_at,
347};
348/// The whole logging facade — sinks, the early-record ring, the throttle
349/// primitives, `init`/`flush`/`add_sink`.
350///
351/// The root re-exports above are the surface a node author needs; this is
352/// everything, for a board or a bridge composing its own delivery.
353pub mod logging {
354    pub use nros_log::*;
355}
356
357// Re-export heapless for generated message types and examples
358pub use nros_core::heapless;
359
360// phase-515 R1 — rclrs's per-entity options, beside R2's node options.
361pub use nros_node::{IntoPrimitiveOptions, PrimitiveOptions};
362
363// Phase 212.M.5.a.2 — executor-backed runtime entry points.
364// (~~`component_register_symbol`~~ retired in the Phase 212.N.7 closing
365// sweep — the helper had no live callers after the BSP baker + macro
366// extern emit were deleted.)
367pub use node::{
368    Callback, CallbackCtx, EntityBounds, IntoNodeOptions, NodeActionClient, NodeActionServer,
369    NodeDeclError, NodeOptions, NodeParameter, NodePublisher, NodeResult, NodeRuntime,
370    NodeServiceClient, NodeServiceServer, NodeSubscription, NodeTimer, TickCtx,
371};
372// phase-483 W3 — the component API registers into a live executor, so it
373// exists where the executor does.
374#[cfg(feature = "rmw-cffi")]
375pub use node::{CallbackEffects, Component, DeclarativeNode, ExecutableNode, NodeContext};
376// Issue 0784 — the macro and codegen PLUMBING, out of the documented surface.
377// `nros::` publishes three audiences under one namespace; these six are for the
378// `nros::node!` expansion and the generated metadata probe
379// (`nros-cli-core/src/orchestration/metadata_build.rs`), never for a node
380// author, and none is named by any hand-written file in `examples/` or
381// `packages/`. Hidden, not deleted: the generated code reaches them by path.
382// phase-359 W8 — follows `node_metadata`'s re-gate: the type needs `alloc`,
383// not `std`.
384#[cfg(feature = "alloc")]
385pub use node_metadata::SourceMetadataExport;
386/// The node-FQN join, at the crate root because that is
387/// where a user looks after `Executor::get_node_names` hands them the two
388/// halves. `nros_node::names` also has `expand_name` / `resolve_name`, which
389/// stay behind `node_metadata` — they are the entity-name seam, not this.
390pub use node_metadata::fully_qualified_name;
391pub use node_metadata::{
392    CallbackEffectKind, CallbackEffectMetadata, EntityKind, EntityMetadata, MetadataRecorder,
393    MetadataString, NodeMetadata, NodeMetadataError, ParameterDefault, SourceLocationMetadata,
394    SourceNameKind,
395};
396#[doc(hidden)]
397pub use node_metadata::{CallbackId, EntityId, NodeId};
398// Phase 216.A.4 — opaque tag types Node authors hold on `Self::State`
399// and match against the `Callback<'_>` delivered to
400// `ExecutableNode::on_callback`.
401pub use dispatch_tag::{ActionTag, ServiceTag, SubscriptionTag};
402// W5-endgame (issue 0843) — the alloc-free half of the seam: per-class static
403// storage. The `_in` installs the macro emits live in `__macro`.
404#[cfg(feature = "rmw-cffi")]
405pub use node_runtime::ComponentSlotStorage;
406// The dynamic runtime still needs `alloc`.
407#[cfg(all(feature = "rmw-cffi", feature = "alloc"))]
408pub use node_runtime::{ExecutorError, RegisteredNode};
409
410/// What `nros::node!`, `nros::main!`, the generated entry points and the board
411/// entry glue expand into — never what a node author writes.
412///
413/// These sat at the top of `nros::`
414/// beside the user API, public only because generated code resolves them
415/// through `::nros::`. Gathering them here keeps every path reachable for
416/// generated code and takes them off the surface a porting user browses.
417#[doc(hidden)]
418pub mod __macro {
419    // Issue 2590.
420    /// The type of `__nros_component_<pkg>_install`, the C-ABI
421    /// install symbol `nros::node!` emits: `(node, executor, self, params,
422    /// n_params, name, namespace, remaps, n_remaps)`. ONE spelling: the macro
423    /// re-exports it per crate as `__NrosComponentInstallFn`, and a consumer
424    /// that anchors the symbol by type (`NanoRosRuntimeCrate.cmake`) names
425    /// that alias instead of writing the signature again.
426    pub type ComponentInstallFn = unsafe extern "C" fn(
427        *const core::ffi::c_void,
428        *mut core::ffi::c_void,
429        *mut core::ffi::c_void,
430        *const *const core::ffi::c_char,
431        usize,
432        *const core::ffi::c_char,
433        *const core::ffi::c_char,
434        *const *const core::ffi::c_char,
435        usize,
436    ) -> i32;
437
438    #[cfg(all(feature = "rmw-cffi", feature = "probe-descriptor-text"))]
439    pub use crate::node::record_node_metadata_watching_prose;
440    #[cfg(feature = "rmw-cffi")]
441    pub use crate::node::{__record_with_context, record_node_metadata, register_node};
442    pub use crate::node::{ActionExecutor, ClientDispatch, GraphQuery, PublisherResolver, TimerOp};
443    // Phase 257 (W0-B) / phase-305 W3 — the uniform cross-language
444    // component-install seam backing `__nros_component_<pkg>_install`.
445    #[cfg(all(feature = "rmw-cffi", feature = "alloc"))]
446    pub use crate::node_runtime::{
447        ExecutorNodeRuntime, install_node_typed, install_node_typed_with_launch,
448        install_node_typed_with_node_identity, install_node_typed_with_params,
449    };
450    #[cfg(feature = "rmw-cffi")]
451    pub use crate::node_runtime::{
452        install_node_typed_in, install_node_typed_with_c_params_in,
453        install_node_typed_with_launch_in,
454    };
455    // phase-509 P5 -- a ranked node's rank, seeded before its `register`.
456    #[cfg(feature = "rmw-cffi")]
457    pub use crate::node_runtime::seed_node_rank;
458}
459
460// phase-483 W3 — the `install_node_typed*` STUBS for builds without
461// `rmw-cffi` are gone. They existed so a `nros::node!()` package compiled
462// without the executor stayed linkable; a component now registers into a live
463// executor (`NodeContext::create_node` returns a `Node`), so a component
464// package without `rmw-cffi` has nothing to register into and does not build.
465// Phase 212.N.12 — canonical `nros::node!()` macro. Replaces the legacy
466// `nros::node!()` macro (retired in the N.12 hard rename — both the
467// proc-macro forwarder and the Cargo metadata key are gone).
468#[cfg(feature = "macros")]
469pub use nros_macros::node;
470// Phase 212.N.9 — `nros::main!()` proc-macro family. One-line Entry-pkg
471// `main.rs` (replaces the legacy `build.rs + include!()` shape). See
472// `docs/design/0024-multi-node-workspace-layout.md` §11.6.
473#[cfg(feature = "macros")]
474pub use nros_macros::main;
475
476/// Route this image's panics to its platform — phase-366 W5.c / RFC-0077.
477///
478/// Emits the `#[panic_handler]` for an embedded image, forwarding the message
479/// to `nros_platform_panic` so a Rust panic ends the same way a C precondition
480/// failure or a C++ terminate does. What that ending IS belongs to the port:
481/// `k_panic()` on Zephyr, `esp_system_abort()` on ESP-IDF, UART-then-exit-QEMU
482/// on the ThreadX RV64 board.
483///
484/// # Why this is a macro you INVOKE, not something `nros::main!` emits
485///
486/// `#[panic_handler]` is a singleton of the final artifact, and the image owns
487/// it. Emitting one silently from `nros::main!()` would collide with every image
488/// that already declares its own — `examples/esp32-c3-baremetal` writes
489/// `use esp_backtrace as _;`, and `logging-smoke-freertos-mps2` uses
490/// `panic-semihosting` with `features = ["exit"]` so a panic exits QEMU instead
491/// of hanging the test harness. Those images are RIGHT, and an invisible default
492/// would fight them.
493///
494/// So the line is written in the entry, where it can be read, swapped for
495/// `use panic_halt as _;`, or replaced by a hand-written handler that logs to
496/// NVM and reboots. A default you cannot see is a constraint, not a default.
497///
498/// # Use — `main!(panic = …)` is the normal way; this is the escape hatch
499///
500/// phase-366 R3. An entry that goes through `nros::main!()` should say
501/// `panic = "platform"` (or nothing — that is the default since M5) and let the
502/// macro emit this body. One line, and the build can check it.
503///
504/// ```ignore
505/// #![no_std]
506/// nros::main!();            // ends through `nros_platform_panic`
507/// ```
508///
509/// Invoke this macro directly only where no `main!()` expansion can carry the
510/// item — a hand-rolled `no_std` binary, or the lib side of a crate whose
511/// `crate-type` includes `staticlib` and whose entry macro is
512/// `zephyr_component_main!` / a board `app_main!`. It is kept for exactly those:
513/// deleting it would strand the images that cannot use the macro replacing it.
514///
515/// ```ignore
516/// // src/app_main.rs — the .a is a final artifact to rustc, and `main!()` in
517/// // the bin target never reaches it.
518/// nros::panic_to_platform!();
519/// ```
520///
521/// Do NOT invoke it in a `std` image: libstd supplies the lang item there and a
522/// second one does not compile. Do not invoke it alongside `use panic_halt as _`
523/// or any other provider, for the same reason — that is the duplicate
524/// `check-archive-lang-items` exists to catch.
525/// Park the core on panic — the `halt` value of `nros::main!(panic = …)`.
526///
527/// For an image that must not print: no formatting, no allocation, no call out
528/// to the platform. Interrupts are masked first so the parked core cannot be
529/// woken back into a half-dead system by a timer or a driver ISR still armed
530/// from before the panic.
531///
532/// This is a body rather than a re-export of the `panic-halt` crate so that
533/// choosing it costs the entry no new dependency — `main!(panic = "halt")` is a
534/// word in a macro the crate already calls, which is the point of the surface.
535/// The behaviour is the same: mask, then spin forever.
536///
537/// Prefer `panic = "platform"`. Halting discards the diagnosis, and every port
538/// implements `nros_platform_panic` precisely so a dying image can say why.
539/// Phase 392 W3b — the receive-buffer size for a message type, as a constant
540/// that cannot drift from the type.
541///
542/// ```ignore
543/// node.subscription::<PointCloud2>("points")
544///     .rx_buffer::<{ nros::rx_buffer_for!(PointCloud2) }>()
545///     .build(on_cloud)?;
546/// ```
547///
548/// `.rx_buffer::<N>()` has always accepted a number. The problem is where the
549/// number comes from: a literal is correct until someone appends a field to the
550/// message, and then it is silently too small — the sample is received, ACKed
551/// and dropped at the transport, which needs a packet capture to attribute
552/// (`report_dropped_take`, and the 13.4 KiB Autoware trajectory case). This
553/// expands to the type's own bound, computed from its schema by phase 380, so
554/// appending a field moves the buffer with it.
555///
556/// **phase-392 W3c narrowed what this is FOR.** A plain
557/// `.typed::<M>().build()` now derives its arena receive buffer from `M` on its
558/// own, and `.rx_buffer::<N>()` is the opt-out, so the macro is no longer how a
559/// buffered subscription gets a type-sized buffer. What still needs it is the
560/// entry shapes whose buffer is a real inline `[u8; RX]` and therefore a
561/// const-generic argument: `.message_info()` and `.safety()`. Those are the
562/// call sites this expands for.
563///
564/// **Why a macro and not a method.** The builder cannot do this for you:
565/// inside `impl<M> TypedSubscriptionBuilder<M>` the type is a generic
566/// parameter, and on stable Rust a generic parameter may not appear in a const
567/// operation — `error: generic parameters may not be used in const operations`.
568/// At a call site the type is CONCRETE, which is legal, so the size has to be
569/// named where the type is. That constraint is also why phase-392's size
570/// classes were "decoupled from codegen" in the first place.
571///
572/// **Unbounded types are a BUILD ERROR** (phase-403 W0). A type with an
573/// unbounded `string`/`wstring`/`sequence` has no bound, and this refuses to
574/// invent one. It used to expand to `DEFAULT_RX_BUF_SIZE`; it now fails to
575/// compile, naming both remedies.
576///
577/// Every message type is REQUIRED to carry a derived upper bound, stated in the
578/// `.msg` (`string<=64`) or capped in `nros-codegen.toml`. Phase 380 is explicit
579/// that `None` means "no bound EXISTS", never "unknown", and that a buffer must
580/// not be sized from a fallback. Substituting the configured default was the
581/// violation of that rule; refusing is what it licenses. `report_dropped_take`
582/// is a backstop for a buffer that is too small, not a licence to pick one.
583///
584/// ```compile_fail
585/// use nros_serdes::schema::{Field, FieldType, Message};
586/// struct Unbounded;
587/// impl Message for Unbounded {
588///     const TYPE_NAME: &'static str = "test/msg/Unbounded";
589///     const FIELDS: &'static [Field] = &[Field {
590///         name: "s",
591///         ty: FieldType::String,
592///         offset: 0,
593///     }];
594/// }
595/// let _n: usize = nros::rx_buffer_for!(Unbounded);
596/// ```
597///
598/// The positive control for that `compile_fail`, so it cannot pass because the
599/// fixture stopped compiling for an unrelated reason:
600///
601/// ```
602/// use nros_serdes::schema::{Field, FieldType, Message};
603/// struct Bounded;
604/// impl Message for Bounded {
605///     const TYPE_NAME: &'static str = "test/msg/Bounded";
606///     const FIELDS: &'static [Field] = &[Field {
607///         name: "a",
608///         ty: FieldType::Uint64,
609///         offset: 0,
610///     }];
611/// }
612/// let n: usize = nros::rx_buffer_for!(Bounded);
613/// assert!(n > 0);
614/// ```
615///
616/// **Why the `const` block.** The macro is used in two positions: as a
617/// const-generic argument (`.rx_buffer::<{ rx_buffer_for!(M) }>()`) and as a
618/// plain expression (`let n = rx_buffer_for!(M);`). A bare `panic!` is a build
619/// error in the first and a RUNTIME panic in the second, which would make the
620/// rule depend on where the macro appears. Wrapping the whole match in an inline
621/// `const` block forces compile-time evaluation in BOTH, so an unbounded type
622/// can never reach a running image.
623///
624/// **What the error names.** rustc points at this macro invocation, where the
625/// type is written literally, so the TYPE is named. The MEMBER that costs the
626/// bound cannot be in the message: const evaluation does not format, so a
627/// `panic!` there takes a literal only. The member is named by the codegen
628/// diagnostic for the same type -- `unbounded_reason` in the generated C header
629/// (`packs/c/message.h.jinja`), which names EVERY member that costs the bound in
630/// one build (phase-403 W0), or `nros_serdes::size::visit_unbounded` over its
631/// `FIELDS`.
632#[macro_export]
633macro_rules! rx_buffer_for {
634    ($msg:ty) => {
635        // The `const` block is load-bearing; see "Why the `const` block" above.
636        const {
637            match $crate::__rx_bound::<$msg>() {
638                ::core::option::Option::Some(n) => n,
639                // RFC-0033 (cap kinds); Phase 380 (no fallback bound)
640                ::core::option::Option::None => ::core::panic!(
641                    "nros: this message type has NO serialized-size bound, so no \
642                     receive buffer can be sized from it.\n\
643                     Every message type must carry a derived upper bound. Bound the \
644                     member that costs it, either:\n\
645                     \x20 - in the `.msg`: `string<=64`, `wstring<=64`, \
646                     `sequence<T, N>`, `T[<=N]`; or\n\
647                     \x20 - as an INLINE `cap` in `nros-codegen.toml`: under \
648                     `[fields]`, `\"pkg/Msg.field\" = 64`. A `heap` or `view` cap \
649                     is a sizing hint that nothing enforces, so it \
650                     deliberately does NOT bound.\n\
651                     WHICH members cost the bound -- all of them, not just the \
652                     first -- are named by the codegen diagnostic for this same \
653                     type: `unbounded_reason` in the generated C header, or \
654                     `nros_serdes::size::visit_unbounded` over its `FIELDS`. The type itself is named by the \
655                     `rx_buffer_for!` invocation rustc points at.\n\
656                     `None` means no bound EXISTS, never \"unknown\", and \
657                     a buffer sized from a fallback is the failure that rule was \
658                     written to prevent. Erroring honours it; defaulting to \
659                     `DEFAULT_RX_BUF_SIZE` did not."
660                ),
661            }
662        }
663    };
664}
665
666#[macro_export]
667macro_rules! panic_halt {
668    () => {
669        #[panic_handler]
670        fn __nros_panic_halt(_info: &::core::panic::PanicInfo) -> ! {
671            // Mask interrupts through the platform's critical section, which is
672            // the one IRQ primitive that is portable across the ports (the
673            // `cortex_m`/`riscv` intrinsics are not). Entering and never
674            // leaving is deliberate.
675            unsafe extern "C" {
676                fn nros_platform_critical_section_acquire() -> u32;
677            }
678            // SAFETY: the ABI's acquire takes no argument and returns a restore
679            // token we deliberately drop — nothing after this point runs.
680            unsafe {
681                let _ = nros_platform_critical_section_acquire();
682            }
683            loop {
684                ::core::hint::spin_loop();
685            }
686        }
687    };
688}
689
690#[macro_export]
691macro_rules! panic_to_platform {
692    () => {
693        #[panic_handler]
694        fn __nros_panic(info: &::core::panic::PanicInfo) -> ! {
695            use ::core::fmt::Write as _;
696
697            // Fixed buffer, never the heap: this runs when the allocator may be
698            // exactly what failed. Truncation is deliberate — a short panic line
699            // still diagnoses; a missing one does not.
700            struct Buf {
701                bytes: [u8; 192],
702                used: usize,
703            }
704            impl ::core::fmt::Write for Buf {
705                fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
706                    let room = self.bytes.len() - self.used;
707                    let n = s.len().min(room);
708                    self.bytes[self.used..self.used + n].copy_from_slice(&s.as_bytes()[..n]);
709                    self.used += n;
710                    Ok(())
711                }
712            }
713
714            let mut buf = Buf {
715                bytes: [0u8; 192],
716                used: 0,
717            };
718            let _ = write!(buf, "{info}");
719
720            unsafe extern "C" {
721                fn nros_platform_panic(msg: *const u8, len: usize) -> !;
722            }
723            // SAFETY: `buf.bytes[..used]` is initialised and outlives the
724            // diverging call; the ABI takes a length-delimited diagnostic, not
725            // a C string.
726            unsafe { nros_platform_panic(buf.bytes.as_ptr(), buf.used) }
727        }
728    };
729}
730
731/// Define Zephyr's `rust_main` for a self-bringup Rust component package.
732///
733/// The macro is intended for `rust_cargo_application()` apps whose crate
734/// already invokes `nros::node!()`. It opens a Zephyr executor, registers
735/// the supplied component through `nros::node_runtime::ExecutorNodeRuntime`, and spins forever.
736/// Issue 0330 — force-link an RMW backend crate into a pure-Rust staticlib.
737///
738/// On a Rust-only image (Zephyr and friends) the Zephyr module emits a weak
739/// `nros_rmw_<name>_register` and calls it only if it resolves. The strong
740/// definition is the backend crate's `#[no_mangle]` export — and rustc's
741/// staticlib DCE drops it unless something in the crate being compiled into the
742/// staticlib references that crate. The symbol is then present in the rlib and
743/// absent from the `.a`, the weak call sees NULL, and the image comes up with no
744/// backend registered (issues 0155 / 0163).
745///
746/// This emits the reference, without naming any backend in nano-ros' own
747/// RMW-agnostic layers — the app crate names it, because the app crate is what
748/// selects an RMW:
749///
750/// ```ignore
751/// #[cfg(feature = "rmw-zenoh")]
752/// nros::force_link_backend!(nros_rmw_zenoh);
753/// #[cfg(feature = "rmw-xrce")]
754/// nros::force_link_backend!(nros_rmw_xrce_cffi);
755/// ```
756///
757/// It is an ANCHOR, not a registration call — the static is never executed
758/// (same class as `nros-c`'s `FORCE_LINK` and `nros-rmw-cffi`'s section anchor).
759/// Registration happens through `nros_app_register_backends`. Backends whose
760/// register entry lives in a C/C++ library the image already links (cyclonedds
761/// on Zephyr) need no anchor at all.
762///
763/// Invoke at module scope. Multiple invocations in one crate are fine — each
764/// expands inside its own anonymous const, so the static names cannot collide.
765#[macro_export]
766macro_rules! force_link_backend {
767    // `ident`, not `path`: a `path` fragment may not be followed by `::`, so
768    // `$backend::register()` fails to parse at the CALL site with a misleading
769    // "expected an operator". Backend crate names are single idents anyway.
770    ($backend:ident) => {
771        const _: () = {
772            #[used]
773            static __NROS_FORCE_LINK_BACKEND: fn() = || {
774                let _ = $backend::register();
775            };
776        };
777    };
778}
779
780// Phase 248 C7 (Method A) — gated on `rmw-cffi` only (needs `Executor`), NOT a
781// `platform-*` feature. This is a framework ENTRY macro (same category as
782// `nros::main!`'s zephyr `rust_main` codegen) — `#[macro_export]` so it emits
783// nothing unless a Zephyr example invokes it; the body's `::zephyr::*` /
784// `::nros_platform::zephyr::wait_network` resolve only in that zephyr-build
785// context (the example deps the `zephyr` crate + `nros-platform[platform-zephyr]`).
786#[cfg(feature = "rmw-cffi")]
787#[macro_export]
788macro_rules! zephyr_component_main {
789    ($node:ty) => {
790        #[unsafe(no_mangle)]
791        pub extern "C" fn rust_main() {
792            // issue 1123 — publish an `nros_log` sink list. The `log` FACADE
793            // (what an example body writes) is bridged into it just below
794            // (issue 1324 retired `zephyr::set_logger`); the sink list is what
795            // `nros_log` needs, which is what the
796            // FRAMEWORK writes (nros-node's executor, nros-rmw-zenoh's session
797            // and pool diagnostics, nros-rmw-cffi). With no sink list
798            // `nros_log::dispatch_to_sinks` holds each record in the bounded
799            // `nros_log::early` ring — issue 0710 deliberately removed the
800            // implicit platform fallback — so on a pure-Rust Zephyr image every
801            // framework record was constructed, dispatched and never seen.
802            //
803            // This is the funnel: a pure-Rust Zephyr image has no
804            // `libnros_c.a` (issue 0163), so `rclc_log_init` / `rclc_log_emit`'s
805            // lazy `ensure_default_sinks()` never run, and `nros-board-zephyr`
806            // covers only `run_sched_tasks`. Reached through `nros_platform` because
807            // the example leaves dep that and not `nros-platform-cffi`.
808            //
809            // FIRST, before `wait_network`: `init` DRAINS the early ring, and
810            // anything raised during bringup is exactly what the ring exists to
811            // serve (the esp32 half of this class, issue 1048, got this order
812            // backwards and drained into a writer that was still `None`). The
813            // Zephyr writer is `nros_platform_log_write`, defined
814            // unconditionally by the C port, so there is no such window here.
815            ::nros_platform::log::init_default();
816            // issue 1324 — the `log` facade into the same sinks. This was
817            // `zephyr::set_logger()`, whose full-`CONFIG_LOG` arm exists only
818            // under `CONFIG_RUST_ALLOC`, the allocator this image no longer links.
819            ::nros_platform::log::install_log_crate_bridge();
820            // Phase 248 C7 step 1 — relocated helper (was `$crate::platform::zephyr`).
821            let _ = ::nros_platform::zephyr::wait_network(2000);
822            // Phase 249 P1 — RMW register is board/platform-owned (Phase 248 C5a);
823            // the backend-agnostic `nros` crate cannot register (no backend dep).
824            // Issue 0155 — the "board/platform boot path" that was supposed to
825            // register never fired for pure-Rust Zephyr images: the zephyr
826            // module emits a STRONG `nros_app_register_backends` stub for the
827            // Kconfig-selected RMW (zephyr/CMakeLists.txt Phase 160.A), but
828            // only the C/C++ `nros_cpp_init` path ever CALLED it — a Rust-only
829            // image reached `Executor::open` with no backend registered and
830            // died with Transport(ConnectionFailed) (silently, pre-0155).
831            // Call the hook explicitly, exactly like the C++ init path.
832            unsafe extern "C" {
833                fn nros_app_register_backends();
834            }
835            unsafe { nros_app_register_backends() };
836            // Issue 2051 (RFC-0109 D8) — the session properties the bringup's
837            // RMW file lowers to, baked by this crate's build from the table
838            // the west lane names, installed before any session opens. The
839            // baked Kconfig locator yields to them below (RFC-0109 D9), so the
840            // file is the wiring here as on every road.
841            if !$crate::__macro_support::baked_session::SESSION_PROPERTIES.is_empty()
842                && $crate::__macro_support::set_session_properties(
843                    &$crate::__macro_support::baked_session::SESSION_PROPERTIES,
844                )
845                .is_err()
846            {
847                ::core::panic!(
848                    "the bringup's RMW file lowers to more session properties than the executor holds"
849                );
850            }
851            // Issue 0163 — a pure-Rust image has no `libnros_c.a`, so the
852            // backend must ride in THIS staticlib and be referenced from the
853            // app crate, or rustc's staticlib DCE drops the whole backend
854            // closure (the `#[no_mangle]` C export included), leaving the
855            // module's weak `nros_rmw_<x>_register` resolving to NULL and the
856            // hook above registering nothing.
857            //
858            // Issue 0330 — that reference used to be a pair of hardcoded
859            // `::nros_rmw_zenoh::register()` / `::nros_rmw_xrce_cffi::register()`
860            // calls emitted RIGHT HERE, which named two concrete backends in
861            // the RMW-agnostic facade (and left cyclonedds handled asymmetrically
862            // through the C hook). It also forced every consumer to carry
863            // `rmw-zenoh` / `rmw-xrce` feature rows purely so these `cfg`s would
864            // resolve — the cyclonedds-only example carried both as inert
865            // placeholders. The anchor now lives in the app crate, which is the
866            // layer that legitimately selects an RMW: see
867            // [`nros::force_link_backend!`]. Registration itself is unchanged —
868            // the `nros_app_register_backends` hook above does it.
869            // phase-427 W9 — the baked identity has ONE source. This block
870            // used to read `option_env!("NROS_LOCATOR")` / `NROS_DOMAIN_ID`
871            // itself and assemble an `ExecutorConfig` by hand (a copy
872            // `nros::main!`'s Zephyr arm carried too, minus the domain — issue
873            // 0161's class); `Context::baked()` is where that lives now, and
874            // `default_from_env()` resolves to it on a freestanding build.
875            // `nros`'s own `build.rs` re-exports the Kconfig values into that
876            // crate's build (`nros_zephyr_build::bake_nros_config`), the same
877            // channel the leaf's `build.rs` uses for itself.
878            //
879            // #166 / phase-286 W1 — native_sim test parallelism. The test
880            // harness launches the image with `-testargs --nros-locator=<loc>`
881            // and starts a per-test zenohd on that (ephemeral) port; preferring
882            // it over the build-time bake lets every test dial a DISTINCT router,
883            // retiring the shared-baked-port serialization of the zenoh e2e
884            // lanes. Provided by `nros-platform-zephyr` (argv-backed, process
885            // lifetime); returns NULL on real embedded → the bake stands. The
886            // hook is an `extern "C"` only a Zephyr image defines, so it is
887            // resolved HERE, in the entry, and handed to the context.
888            unsafe extern "C" {
889                fn nros_runtime_locator_override() -> *const ::core::ffi::c_char;
890            }
891            let runtime_locator: ::core::option::Option<&str> = {
892                let p = unsafe { nros_runtime_locator_override() };
893                if p.is_null() {
894                    ::core::option::Option::None
895                } else {
896                    unsafe { ::core::ffi::CStr::from_ptr(p) }.to_str().ok()
897                }
898            };
899            let ctx = match $crate::Context::default_from_env() {
900                ::core::result::Result::Ok(ctx) => ctx
901                    .yield_locator_to_session_properties(
902                        &$crate::__macro_support::baked_session::SESSION_PROPERTIES,
903                    )
904                    .with_locator_override(runtime_locator),
905                ::core::result::Result::Err(e) => {
906                    panic!("nros zephyr entry: baked Context is invalid: {e:?}")
907                }
908            };
909            let config = ctx.config(<$node as $crate::Component>::NAME);
910            // Issue 0155 — fail LOUD (repo rule: panic, not silent
911            // early-return). A silent `return` here idles the image with zero
912            // output; the zephyr-cyclonedds rust lane was undiagnosable until
913            // this printed the real error.
914            let executor = match $crate::Executor::open(&config) {
915                Ok(executor) => executor,
916                Err(e) => {
917                    panic!("nros zephyr entry: Executor::open failed: {e:?}");
918                }
919            };
920            let mut runtime = $crate::__macro::ExecutorNodeRuntime::from_executor(executor);
921            // phase-436 — Zephyr's microsecond park, which the sched task runners
922            // install on every sched task and this single-executor entry did not.
923            // Zephyr's `platform.c` always defines both symbols, and this macro
924            // only expands in a Zephyr image, so they are plain references.
925            {
926                unsafe extern "C" {
927                    fn nros_platform_wake_park_until_us(
928                        w: *mut ::core::ffi::c_void,
929                        deadline_us: u64,
930                    ) -> i8;
931                    fn nros_platform_wake_park_granularity_us() -> u64;
932                }
933                // SAFETY: a pure query of the linked port, no arguments.
934                let granularity = unsafe { nros_platform_wake_park_granularity_us() };
935                let _ = $crate::port_park::install_port_park(
936                    runtime.executor_mut(),
937                    nros_platform_wake_park_until_us,
938                    granularity,
939                );
940            }
941            if let Err(e) = runtime.register_node::<$node>() {
942                panic!("nros zephyr entry: register_node failed: {e:?}");
943            }
944            // Readiness marker. The C/C++ Zephyr listeners print
945            // "Waiting for messages..." from their `main()` before the spin
946            // loop; the e2e harness polls for that substring to know the
947            // subscriber has declared before starting the talker (Phase 89.12).
948            // The Rust path's spin loop lives in this macro (the node only owns
949            // callbacks), so emit the same canonical marker here — without it a
950            // fully-working Rust listener never signals readiness and the e2e
951            // times out at 30 s (issue #35: the zenoh native_sim rust pubsub /
952            // service / action failures were this missing marker, not a
953            // transport fault — `Executor::open` + `register_node` had already
954            // succeeded).
955            ::log::info!("Waiting for messages");
956            // RFC-0141 D1 — the wall clock resolves after registration and
957            // before the first spin (as in the generated entries), then the
958            // timing restarts so the wait is owed to no timer. After the
959            // readiness marker on purpose: a peer that waits for it may start
960            // publishing while a zenoh-hlc source listens.
961            {
962                unsafe extern "C" {
963                    fn nros_clock_resolve_configured();
964                }
965                // SAFETY: the Zephyr module's shim; no arguments, once.
966                unsafe { nros_clock_resolve_configured() };
967            }
968            runtime.executor_mut().restart_timing();
969            loop {
970                // phase-521 W6 (RFC-0113 D2) — park until the next deadline when
971                // every source of work can end the park, else the 10 ms slice.
972                let budget = runtime.entry_spin_budget();
973                let _ = runtime.spin_once(budget);
974            }
975        }
976    };
977}
978
979// phase-483 W4 (issue 0784) — `StandaloneNode` (the transport-less
980// pre-component node) and its `NodeConfig` / `PublisherHandle` /
981// `SubscriptionHandle` are no longer re-exported. `nros::Node` is THE node,
982// and these have no rclrs counterpart; the two bench programs that use them
983// import `nros_node` directly.
984
985// Re-export publisher/subscriber options (topic + QoS; always available).
986pub use nros_node::{PublisherOptions, SubscriptionOptions};
987
988// Re-export timer types
989pub use nros_node::{TimerCallbackFn, TimerDuration, TimerHandle, TimerMode, TimerState};
990// phase-425 W4/W5 — which clock advances a timer. Re-exported here for the
991// reason `sim-time` is a feature here: an application deps `nros`, not
992// `nros-node`, so a capability that stops at the core crate is one no
993// application can name. W4 added the type and the registrar and stopped at the
994// core, which the `/clock` fixture found the moment it tried to use them.
995// UNGATED since phase-430 W4, and the enum moved to `nros_node::timer` to make
996// that possible. The `rmw-cffi` gate was right while the only way to name a
997// clock was `Executor::register_timer_on_clock`; W4 put the axis on the
998// DECLARATIVE surface too (`DeclaredNode::create_timer_on_clock`), which a
999// metadata-mode build compiles with no transport linked. A type the metadata
1000// layer cannot name is a type the metadata layer re-invents.
1001pub use nros_node::timer::TimerClockSource;
1002// Issue 2038 — what a declared timer's callback reads through
1003// `CallbackCtx::timer_info` (issue 1974's call info). Ungated for the reason
1004// `TimerClockSource` is: the declarative surface compiles in metadata mode.
1005pub use nros_node::timer::TimerCallInfo;
1006
1007/// Ledger row `c:logging_rosout_enabled` — the `/rosout` log
1008/// bridge. A module re-export rather than a flat one: the names a caller
1009/// needs (`enable`, `pump`, `qos`, `qos_bounded`, `TOPIC`) are generic words
1010/// that only read correctly under the `rosout::` prefix.
1011/// Gated like the module it comes from: `nros_node::rosout` is
1012/// `#[cfg(all(feature = "rosout", any(has_rmw, test)))]` there, and `has_rmw`
1013/// is `nros-node`'s own build-script cfg — this crate spells the same
1014/// condition as `feature = "rmw-cffi"`, exactly as the `parameter_services`
1015/// re-export below does.
1016#[cfg(all(feature = "rosout", feature = "rmw-cffi"))]
1017pub use nros_node::rosout;
1018
1019// The QoS vocabulary a node author states. RFC-0071 D12 (phase-506 W1, issue
1020// 1789): the RMW SEAM — `Session`, `Rmw`, `Transport`, `TopicInfo`, the
1021// `Publisher` / `Subscription` / `ClientTrait` / `ServiceTrait` entity traits
1022// and their config types — is NOT re-exported here. It is what a backend
1023// implements, and every in-tree backend already imports it from `nros-rmw`
1024// directly; beside the user API it was the "three audiences" problem issue
1025// 0784 was named for.
1026pub use nros_rmw::{
1027    QoSDurabilityPolicy, QoSHistoryPolicy, QoSLivelinessPolicy, QoSOverride, QoSOverrideRole,
1028    QoSOverrideValue, QoSPolicyMask, QoSProfile, QoSReliabilityPolicy,
1029};
1030// `SessionMode` is the type of `ExecutorConfig`'s `mode`, so it is user
1031// configuration even though it is defined beside the seam.
1032pub use nros_rmw::SessionMode;
1033
1034/// Standard ROS-2-equivalent QoS profiles. Match
1035/// upstream `rmw_qos_profile_default` etc. field-by-field. Backends
1036/// validate against these synchronously at create time; no silent
1037/// downgrade.
1038// phase-379 W5 — rclrs exports the eight QoS presets as CRATE-LEVEL consts
1039// (`rclrs::QOS_PROFILE_DEFAULT`); ours were associated consts on `QoSProfile`
1040// and nothing re-exported them, so `use rclrs::QOS_PROFILE_DEFAULT` had no
1041// counterpart to port to. The NAMES already matched exactly — only the path
1042// did not, which is why the ledger filed these as a re-export and not a
1043// rename.
1044//
1045// These ALIAS the associated consts rather than restating them. `nros::qos`
1046// below is a second, hand-written copy of the same presets that predates them;
1047// ~~`qos_presets_agree`~~ in the test module asserts the two never drift, which is
1048// the hand-mirror class (issues 0088/0160/0245) one layer up.
1049/// `rmw_qos_profile_default` — reliable, volatile, keep-last(10).
1050pub const QOS_PROFILE_DEFAULT: QoSProfile = QoSProfile::QOS_PROFILE_DEFAULT;
1051/// `rmw_qos_profile_system_default` — the RMW implementation's own defaults.
1052pub const QOS_PROFILE_SYSTEM_DEFAULT: QoSProfile = QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT;
1053/// `rmw_qos_profile_sensor_data` — best-effort, keep-last(5).
1054pub const QOS_PROFILE_SENSOR_DATA: QoSProfile = QoSProfile::QOS_PROFILE_SENSOR_DATA;
1055/// `rmw_qos_profile_services_default`.
1056pub const QOS_PROFILE_SERVICES_DEFAULT: QoSProfile = QoSProfile::QOS_PROFILE_SERVICES_DEFAULT;
1057/// `rmw_qos_profile_parameters` — reliable, depth 1000.
1058pub const QOS_PROFILE_PARAMETERS: QoSProfile = QoSProfile::QOS_PROFILE_PARAMETERS;
1059/// `rmw_qos_profile_parameter_events`.
1060pub const QOS_PROFILE_PARAMETER_EVENTS: QoSProfile = QoSProfile::QOS_PROFILE_PARAMETER_EVENTS;
1061/// The clock preset — sensor-data shaped with depth 1.
1062pub const QOS_PROFILE_CLOCK: QoSProfile = QoSProfile::QOS_PROFILE_CLOCK;
1063/// The action-status preset — reliable + transient-local, depth 1.
1064pub const QOS_PROFILE_ACTION_STATUS_DEFAULT: QoSProfile =
1065    QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT;
1066
1067/// The five presets under their older, shorter names.
1068///
1069/// **Every one of these is an ALIAS.** This module used to
1070/// RESTATE four of the five as struct literals: `DEFAULT` spelled all ten fields
1071/// out, `SENSOR_DATA` and `PARAMETERS` were `..DEFAULT` updates of it, and
1072/// `SERVICES_DEFAULT` was `= DEFAULT` — a second, independent transcription of
1073/// upstream's table living 40 lines below the first. Only `SYSTEM_DEFAULT` was a
1074/// real alias, and the comment that made it one claimed it was joining "the
1075/// other four", which was not true of any of them.
1076///
1077/// That is the mirror this work item removes: upstream's 7 profiles were
1078/// hand-written in four places across the repo — here, the crate-level
1079/// `QOS_PROFILE_*` consts above, `nros-rmw/src/traits.rs`, and
1080/// `nros-rmw-abi/include/nros/rmw_entity.h` — about 26 constants for a 7-row
1081/// table, with no gate binding them. `QOS_PROFILE_PARAMETER_EVENTS` is the proof
1082/// that the arrangement does not hold: it is `KeepAll, 0` in `traits.rs` under a
1083/// comment claiming it matched `rmw_qos_profile_parameter_events`, which is
1084/// `KEEP_LAST, 1000`.
1085///
1086/// So this module now declares no values at all. The SSoT is
1087/// [`QoSProfile`]'s associated consts, and a correction there — including the
1088/// `PARAMETER_EVENTS` one — reaches these names without anyone remembering to
1089/// come here. Note that the alias set is a SUBSET: `CLOCK`,
1090/// `PARAMETER_EVENTS`, `ACTION_STATUS_DEFAULT` and `PX4` have no short spelling
1091/// and are reached as `nros::QOS_PROFILE_*` or `QoSProfile::QOS_PROFILE_*`.
1092pub mod qos {
1093    use crate::QoSProfile;
1094
1095    /// `rmw_qos_profile_default` — reliable + volatile + keep-last(10),
1096    /// automatic liveliness, no deadline / lifespan.
1097    pub const DEFAULT: QoSProfile = QoSProfile::QOS_PROFILE_DEFAULT;
1098
1099    /// `rmw_qos_profile_sensor_data` — best-effort + volatile + keep-last(5).
1100    pub const SENSOR_DATA: QoSProfile = QoSProfile::QOS_PROFILE_SENSOR_DATA;
1101
1102    /// `rmw_qos_profile_services_default` — reliable + volatile +
1103    /// keep-last(10).
1104    ///
1105    /// It aliases its OWN associated const, not `DEFAULT`. The two profiles
1106    /// hold the same values upstream and are two upstream constants; writing
1107    /// this one as `= DEFAULT`, which is what it said before W10, would make a
1108    /// future divergence between them invisible here.
1109    pub const SERVICES_DEFAULT: QoSProfile = QoSProfile::QOS_PROFILE_SERVICES_DEFAULT;
1110
1111    /// `rmw_qos_profile_parameters` — reliable + volatile + keep-last(**1000**).
1112    pub const PARAMETERS: QoSProfile = QoSProfile::QOS_PROFILE_PARAMETERS;
1113
1114    /// `rmw_qos_profile_system_default` — **an absence, not a profile**: every
1115    /// policy is the SYSTEM_DEFAULT sentinel and the depth is the depth
1116    /// sentinel, resolved by whichever backend is linked.
1117    ///
1118    /// This said `= DEFAULT` (depth 10) while
1119    /// `QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT` said depth 1, so one name
1120    /// shipped two queue depths depending on which spelling a caller reached.
1121    /// It was the first of these to become an alias, and since W10 it is no
1122    /// longer the only one: see `QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT`.
1123    pub const SYSTEM_DEFAULT: QoSProfile = QoSProfile::QOS_PROFILE_SYSTEM_DEFAULT;
1124}
1125
1126// Re-export safety types when feature is enabled
1127#[cfg(feature = "safety-e2e")]
1128pub use nros_rmw::{IntegrityStatus, SafetyValidator, crc32};
1129
1130// Phase 248 C7 step 1 — the `nros::platform::zephyr` module (the
1131// ~~`wait_for_network`~~ FFI wrapper) RELOCATED to `nros-platform`
1132// (`nros_platform::zephyr::wait_network`); callers reference it via
1133// `::nros_platform::zephyr::wait_network`. nros no longer hosts a platform
1134// helper module. (The `zephyr_component_main!` macro relocation is C7 step 2.)
1135//
1136/// Backend-specific internal types.
1137///
1138/// These types are implementation details of the transport backends.
1139/// Most users should use the high-level APIs (`Executor`, etc.)
1140/// instead of these types directly.
1141///
1142/// The `Rmw*` type aliases resolve to whichever backend is active at compile time,
1143/// providing a backend-agnostic way to reference concrete transport types.
1144pub mod internals {
1145    // RFC-0071 D12 (phase-506 W1, issue 1789) — the untyped action machinery the
1146    // C and C++ shims drive, out of the top-level user API.
1147    #[cfg(feature = "rmw-cffi")]
1148    pub use nros_node::{
1149        ActionClientCore, ActionServerCore, ActionServerRawHandle, RawActionClientSpec,
1150        RawActionServerSpec,
1151    };
1152
1153    // ── Backend-agnostic type aliases ────────────────────────────────────
1154    // These resolve to the concrete types of the active RMW backend.
1155    // Today the only exposed backend at this layer is the cffi shim.
1156
1157    #[cfg(feature = "rmw-cffi")]
1158    pub type RmwSession = nros_rmw_cffi::CffiSession;
1159    #[cfg(feature = "rmw-cffi")]
1160    pub type RmwPublisher = nros_rmw_cffi::CffiPublisher;
1161    #[cfg(feature = "rmw-cffi")]
1162    pub type RmwSubscriber = nros_rmw_cffi::CffiSubscription;
1163    #[cfg(feature = "rmw-cffi")]
1164    pub type RmwServiceServer = nros_rmw_cffi::CffiService;
1165    #[cfg(feature = "rmw-cffi")]
1166    pub type RmwServiceClient = nros_rmw_cffi::CffiClient;
1167
1168    /// Zero-copy publisher slot type. Lives in the
1169    /// `internals` module so `nros-c` can construct + transmute the
1170    /// lifetime when boxing the slot for the C-side `_loan` /
1171    /// `_commit` / `_discard` token plumbing.
1172    #[cfg(all(feature = "rmw-cffi", feature = "lending"))]
1173    pub type RmwSlot<'a> = nros_rmw_cffi::CffiSlot<'a>;
1174
1175    /// Zero-copy subscriber view type.
1176    #[cfg(all(feature = "rmw-cffi", feature = "lending"))]
1177    pub type RmwView<'a> = nros_rmw_cffi::CffiView<'a>;
1178
1179    /// Open a new middleware session.
1180    ///
1181    /// Wraps the backend-specific session constructor behind a common signature.
1182    /// Used by the C API (`nros-c`); Rust users should prefer `Executor::open()`.
1183    ///
1184    /// Takes an explicit primary backend by name, mirroring what
1185    /// `Executor::open` does for Rust callers. Without it, C bridges built with
1186    /// two linked backends (e.g. xrce + dds) get whichever ctor fires first —
1187    /// non-deterministic across link orderings, and often the wrong backend for
1188    /// the bridge's intended primary.
1189    ///
1190    /// `rmw` is the RESOLVED selector, not a second
1191    /// reading of the environment. This function used to consult
1192    /// `rmw_selector()` itself, which made it the tree's second answer to "which
1193    /// backend?" and blind to every rung but the environment: a C image with a
1194    /// BAKED selector had it discarded here. The caller resolves the whole
1195    /// ladder (`env > baked > none`) through `ExecutorConfig` and passes the
1196    /// result; `None` means the registry must hold exactly one backend, which
1197    /// `nros_rmw_cffi::get_vtable` now enforces rather than assumes.
1198    #[cfg(feature = "rmw-cffi")]
1199    pub fn open_session(
1200        locator: &str,
1201        mode: nros_rmw::SessionMode,
1202        domain_id: u32,
1203        node_name: &str,
1204        rmw: Option<&str>,
1205    ) -> Result<RmwSession, nros_rmw::TransportError> {
1206        // Phase 249 P4b.1 — every linked backend self-registered via
1207        // its `.init_array` ctor before `main` (RFC-0042 §D3.3); no
1208        // runtime section walk.
1209
1210        // RFC-0109 D8 — the image's baked session properties, as
1211        // `Executor::open` hands them (`nros_node::with_session_properties`).
1212        nros_node::with_session_properties(&[], |properties| {
1213            let config = nros_rmw::RmwConfig {
1214                locator,
1215                mode,
1216                domain_id,
1217                node_name,
1218                namespace: "",
1219                properties,
1220            };
1221            open_with(rmw, &config)
1222        })
1223    }
1224
1225    #[cfg(feature = "rmw-cffi")]
1226    fn open_with(
1227        rmw: Option<&str>,
1228        config: &nros_rmw::RmwConfig<'_>,
1229    ) -> Result<RmwSession, nros_rmw::TransportError> {
1230        use nros_rmw::Rmw;
1231        // Phase 155.B — propagate the real `TransportError` instead of
1232        // collapsing every backend failure to `ConnectionFailed`. The
1233        // C-side `rclc_support_init` decodes the variant into a
1234        // specific `RCLC_RET_*` code so "init -> -X" tells the user
1235        // which precondition the backend rejected.
1236        // issue 1050 defect (3) — the selector ARRIVES here now. It used to be
1237        // read from `$NROS_RMW` on the spot, which is why a baked one could not
1238        // reach this path: the reader knew about one rung and the resolver knew
1239        // about two. The environment still wins; it wins in `ExecutorConfig`,
1240        // where every other field's precedence is decided, instead of here.
1241        if let Some(name) = rmw {
1242            return nros_rmw_cffi::CffiRmw::open_with_rmw(name, config);
1243        }
1244        nros_rmw_cffi::CffiRmw.open(config)
1245    }
1246
1247    /// Drive middleware I/O for pull-based backends.
1248    ///
1249    /// Delegates to [`Session::drive_io()`](nros_rmw::Session::drive_io),
1250    /// which each backend implements appropriately (no-op for push-based,
1251    /// poll for pull-based).
1252    ///
1253    /// Used by the C API executor before polling handles.
1254    #[cfg(feature = "rmw-cffi")]
1255    pub fn drive_session_io(session: &mut RmwSession, timeout_ms: i32) {
1256        use nros_rmw::Session;
1257        let _ = session.drive_io(timeout_ms);
1258    }
1259}
1260
1261// Re-export types that don't depend on RMW (always available)
1262pub use nros_node::{
1263    BOOT_SET_DOMAIN, BOOT_SET_LOCATOR, BOOT_SET_NAMESPACE, BOOT_SET_NODE_NAME, BakedBootConfig,
1264    BootConfig, BootConfigError, DOMAIN_ID_EXPLICIT_ZERO_C_ABI, DOMAIN_ID_MAX, DeferNotify,
1265    ExecutorConfig, ExecutorSemantics, GuardCondition, HandleId, HandleSet, InvocationMode,
1266    NROS_BOOT_CONFIG_MAGIC, NROS_BOOT_CONFIG_VERSION, RawCancelCallback, RawGoalCallback,
1267    RawServiceCallback, RawSubscriptionCallback, ReadinessSnapshot, ShutdownCallbackFn,
1268    ShutdownCallbackHandle, ShutdownPhase, SpinOnceResult, SpinOptions, SpinPeriodPollingResult,
1269    Trigger, baked_domain_from_c_abi,
1270};
1271
1272// ---------------------------------------------------------------------------
1273// The error vocabulary (issue 0783). Both re-exports are unconditional.
1274//
1275// Every fallible call in the Rust user API returns `NodeError`, and
1276// `NodeError::Transport(TransportError)` is its most common variant — so
1277// handling one means naming both. They used to be exported from two unrelated
1278// blocks (`NodeError` with the boot/executor types, `TransportError` with the
1279// transport traits), which is a discoverability nit rather than a capability
1280// gap: both were always reachable, and `prelude` already listed them together.
1281// Nothing here changes what `nros::` exports.
1282//
1283// There is deliberately NO numeric code type beside them. A Rust caller matches
1284// a flat enum; the numeric vocabulary is the C ABI's `rcl_ret_t` /
1285// `RCLC_RET_*` (0, -1..-16), which is its own space and not `rcl_ret_t`'s.
1286// nros-core carried an `rcl_ret_t` mirror (`RclReturnCode`) and an error that
1287// wrapped it (~~`NanoRosError`~~); neither was ever reachable from this facade and
1288// neither had a producer, so issue 0783 deleted them rather than exporting a
1289// type a user could name and never receive. RFC-0036's Errors row now describes
1290// what these two are.
1291// ---------------------------------------------------------------------------
1292/// Installing a port's park primitive, with the wake-object
1293/// constraint stated once. Board entries reach it through this facade because
1294/// that is the dependency they already carry.
1295///
1296/// Gated like every other `executor::` re-export here, and it has to be: the
1297/// module itself is `#[cfg(any(has_rmw, test))]`, and `has_rmw` is emitted by
1298/// `nros-node`'s build script exactly when `CARGO_FEATURE_RMW_CFFI` is set. An
1299/// ungated `pub use` therefore names a module that does not exist wherever no
1300/// RMW seam is compiled in — which is not a hypothetical configuration but the
1301/// one `nros build --metadata-mode` uses, where it is `error[E0432]:
1302/// unresolved import` before the harness reaches a single component.
1303#[cfg(feature = "rmw-cffi")]
1304pub use nros_node::executor::port_park;
1305
1306// issue 2641 -- the application's trace markers. Ungated like the module it
1307// re-exports: the id check runs in every build, the emission needs
1308// `trace-callbacks` and an installed sink.
1309pub use nros_node::executor::trace_marker;
1310
1311/// The other half of the seam, for the boards that now use it.
1312///
1313/// `port_park` above is what a port hands the executor to WAIT with;
1314/// these are what it hands the executor to be told WHEN. A board registering
1315/// a deadline source receives a [`WakeSourceId`] and reads it back out of
1316/// `Executor::last_park()`, so without this re-export it could match on
1317/// neither.
1318#[cfg(feature = "rmw-cffi")]
1319pub use nros_node::executor::{MAX_WAKE_SOURCES, NextDeadlineFn, WakeSourceId};
1320
1321/// The spawned sched tasks' executor backing. `nros::main!` emits one
1322/// `SchedTaskExecutorBacking` static per sched-task entry and hands its slots to the
1323/// board's `run_sched_tasks`, which refuses a short block through
1324/// `check_sched_task_executor_backing` and opens each spawned sched task with
1325/// `Executor::open_with_session_slot`. Gated like the module it names
1326/// (`has_rmw` + `alloc` in nros-node).
1327#[cfg(all(feature = "rmw-cffi", feature = "alloc"))]
1328pub use nros_node::executor::{
1329    EXECUTOR_BACKING_DEFAULT_U64S, SchedTaskBackingShort, SchedTaskExecutorBacking,
1330    SchedTaskExecutorBackingSlot, SchedTaskSetupGate, SchedTaskSetupGuard,
1331    check_sched_task_executor_backing,
1332};
1333/// Each spawned sched task's TASK memory (stack + control block):
1334/// `nros::main!` emits one `SchedTaskMemory` static per spawned sched task, sized from
1335/// its `stack_bytes`, and hands the `SchedTaskMemorySet` rows to a board whose
1336/// sched task runner creates the task over them (FreeRTOS `xTaskCreateStatic`).
1337#[cfg(all(feature = "rmw-cffi", feature = "alloc"))]
1338pub use nros_node::executor::{
1339    SCHED_TASK_TCB_U64S, SchedTaskMemory, SchedTaskMemoryRaw, SchedTaskMemorySet,
1340};
1341
1342/// Which level an executor is, and whether every
1343/// level of the image is alive: what a supervisor that owns a route per level
1344/// or feeds a watchdog reads, and what a board's sched task runner states (the level
1345/// count, and each sched task's level by [`sched_task_level_by`]). Plain atomics in
1346/// nros-node, so ungated.
1347pub use nros_node::executor::{
1348    MAX_LEVELS, every_level_alive, level_count, level_last_spin_us, level_spins, sched_task_level,
1349    sched_task_level_by, set_level_count, take_every_level_alive,
1350};
1351
1352pub use nros_node::NodeError;
1353pub use nros_rmw::TransportError;
1354
1355// RFC-0052 / phase-296 W3b — on-target contract-monitor types. Baked
1356// `system_monitors.rs` uses the fully-qualified `::nros_node::executor::
1357// monitor::*` path; this re-export lets hand-written entries and fixtures
1358// reach the same types through the `nros` umbrella (they install the
1359// tables via `Executor::set_monitor_table` / `set_age_table` and drain
1360// with `drain_violations`). The monitor module is `has_rmw`-gated in
1361// nros-node (it names entity types), so mirror that with `rmw-cffi`.
1362#[cfg(feature = "rmw-cffi")]
1363pub mod monitor {
1364    pub use nros_node::executor::monitor::{
1365        AgeMonitorSpec, HazardCell, HazardMonitorRef, HazardMonitorSpec, HazardSpec,
1366        MAX_AGE_MONITORS, MAX_MONITORS, MAX_VIOLATIONS, MECHANISM_EXECUTOR, MECHANISM_TIMER,
1367        ModeDeadline, ModeTables, ModeTablesMismatch, MonitorArming, MonitorSpec, MonitorTableFull,
1368        NO_MODE, NO_SINK, PubMonitorCell, REACTION_NONE, RULE_IDS, RUNG_ROLE_FLOOR, RUNG_ROLE_RUNG,
1369        RUNG_ROLE_WINDOW, ReactionEvent, ReactionHookFn, RouteWatch, RungSpec, SubMonitorCell,
1370        Violation, check_table_capacity, fqn_hash, request_mode, request_monitor_arming,
1371        requested_mode, route_next_due_us, rule_code, rule_name,
1372    };
1373}
1374
1375// Issues 1635 / 1676 — the contract-monitor install and the `/diagnostics`
1376// reporter, ONE implementation: `nros::main!` calls `install_contract_monitors`
1377// on every executor it builds, and `nros-cpp`'s `nros_cpp_install_monitors`
1378// arms the same `DiagSink`.
1379#[cfg(feature = "rmw-cffi")]
1380pub mod contract;
1381
1382// Re-export RMW-dependent types (require an active transport backend)
1383#[cfg(feature = "rmw-cffi")]
1384pub use nros_node::{
1385    ActionClient, ActionServer, ActionServerHandle, ActiveGoal, CompletedGoal, EmbeddedPublisher,
1386    EmbeddedRawPublisher, EmbeddedServiceClient, EmbeddedServiceServer, Executor, ExecutorSizing,
1387    FeedbackStream, GoalFeedbackStream, LoanError, Node, Promise, PublishLoan, RawActiveGoal,
1388    RawSubscription, RecvView, SessionHandle, SessionSpec, Subscription, action_channel_type,
1389};
1390
1391// phase-271 (issue #110) — per-entry executor sizing helper: the orchestration
1392// codegen's ~~`build_executor`~~ sizes its backing to the system's callback count
1393// via `nros::arena_size_for(CALLBACK_COUNT)` + `ExecutorSizing`, replacing the
1394// workspace-global `NROS_EXECUTOR_MAX_CBS`.
1395#[cfg(feature = "rmw-cffi")]
1396pub use nros_node::config::arena_size_for;
1397
1398/// The configured default receive-buffer size (`NROS_EXECUTOR_SUBSCRIPTION_BUFFER_BYTES`).
1399///
1400/// NOT a fallback for a missing bound any more: [`rx_buffer_for!`]
1401/// used to expand to this for an unbounded type and now refuses to compile
1402/// instead. It stays public, and stays the default, for the paths that have no
1403/// `M` to ask rather than a bound they declined to use -- `create_subscription_raw`
1404/// and the type-name-string subscriptions, the service / action / TX
1405/// buffer defaults, the `pubsub_entry` term of the arena derivation in
1406/// `nros-node/build.rs`, and its weld to the C API's `MESSAGE_BUFFER_SIZE`.
1407/// Whether the arena derivation should stop leaning on it is a separate
1408/// question.
1409///
1410/// Re-exported here (rather than reached through `nros_node`) because a macro
1411/// expands at the CALLER, where `nros_node` may not be a dependency at all.
1412pub use nros_node::config::DEFAULT_RX_BUF_SIZE;
1413
1414/// The bound behind [`rx_buffer_for!`]. Not part of the stable
1415/// surface; call the macro.
1416///
1417/// Public only because a `macro_rules!` body is expanded in the caller's crate
1418/// and can reach nothing private. `#[doc(hidden)]` and `__`-prefixed for the
1419/// same reason every other macro-support item in this crate is.
1420#[doc(hidden)]
1421pub const fn __rx_bound<M: nros_serdes::schema::Message>() -> Option<usize> {
1422    nros_serdes::size::max_serialized_bound::<M>()
1423}
1424
1425// Phase 173.5 — board config traits. `BoardConfig` (read locator /
1426// domain). ~~`BoardTransportConfig`~~ was removed with its dead
1427// setters (issue 1064); the live path is the deploy overlay.
1428pub use nros_platform::BoardConfig;
1429
1430// Phase 216.A.1 — `DispatchStrategy` enum. User-visible at
1431// `nros::DispatchStrategy`; the canonical home is `nros_platform::
1432// board::dispatch` so the C ABI symbol the `nros::node!()` macro emits
1433// (`__nros_node_<pkg>_dispatch_strategy() -> u8`) lives next to the
1434// other board-side trampolines.
1435pub use nros_platform::DispatchStrategy;
1436
1437/// Implementation detail — used by `nros::node!()` macro expansion.
1438///
1439/// Re-exports `nros_platform` so the macro's emitted trampoline can
1440/// reference `RuntimeCtx` / `RuntimeError` / the `Node*Fn`
1441/// fn-pointer aliases without forcing every consumer Node pkg's
1442/// `Cargo.toml` to carry an explicit `nros-platform` dep on top of
1443/// `nros`.
1444///
1445/// Not part of the public API — paths under this module may change at
1446/// any time. End users should depend on `nros` alone and invoke
1447/// `nros::node!()`; the macro routes through here automatically.
1448#[doc(hidden)]
1449pub mod __macro_support {
1450    /// The baked `rmw/zenoh.json5` session-property table.
1451    pub use ::nros_node::{SessionProperty, set_session_properties};
1452
1453    /// The table `nros build` rendered for a Zephyr Rust west
1454    /// application (`NROS_SESSION_PROPERTIES_RS`), for the entry macro that
1455    /// cannot read the text at expansion ([`crate::zephyr_component_main!`]).
1456    /// Empty when the build names none.
1457    pub mod baked_session {
1458        include!(concat!(env!("OUT_DIR"), "/baked_session_properties.rs"));
1459    }
1460    pub use ::nros_platform;
1461
1462    /// Whether THIS `nros` build carries the parameter services.
1463    ///
1464    /// The `nros::main!` expansion const-asserts it when the system declares
1465    /// `[param_services]`. A cfg in the entry crate cannot see this: the
1466    /// feature belongs to `nros`, and the entry enables it through its
1467    /// dependency, so only `nros` itself can report the answer.
1468    ///
1469    /// Without the assert the mismatch is SILENT — `apply_param_services` is a
1470    /// no-op, the build succeeds, the image boots, and `ros2 param list`
1471    /// returns nothing.
1472    pub const PARAM_SERVICES_ENABLED: bool = cfg!(feature = "param-services");
1473
1474    /// Whether THIS `nros` build carries the parameter STORE
1475    /// (`param-store`, which `param-services` implies). A system declaring the
1476    /// `params` axis const-asserts it, for the reason above: without the
1477    /// feature `apply_param_store` is a no-op and every `declare_parameter`
1478    /// is refused at boot instead of at compile time.
1479    pub const PARAM_STORE_ENABLED: bool = cfg!(feature = "param-store");
1480
1481    /// How many parameter-store slots this build carves from the executor
1482    /// backing (`nros_params::IMPLIED_STORE_SLOTS`), 0 when it carves none.
1483    ///
1484    /// The `nros::main!` expansion const-asserts it is non-zero wherever the
1485    /// image serves the parameter services. Zero there means no road told
1486    /// `nros-params` the image has a store, and the runtime would ask the heap
1487    /// for the whole crate-default store in one allocation instead: 283,392 B
1488    /// on a ThreadX-linux image, which its pool refused, and the image exited
1489    /// at boot. Refused at build, naming the knob, instead.
1490    // Issue 2777.
1491    pub const PARAM_STORE_CARVED_SLOTS: usize = ::nros_params::IMPLIED_STORE_SLOTS;
1492    /// The refusal text for [`PARAM_STORE_CARVED_SLOTS`] being 0.
1493    pub use ::nros_params::STORE_NOT_CARVED as PARAM_STORE_NOT_CARVED;
1494
1495    /// The same answer for the other capability axes a leaf
1496    /// can declare in `[system] features`. A Form-1 `nros::main!()`
1497    /// const-asserts the flag of every declared axis
1498    /// (`nros_orchestration_ir::leaf_capabilities::LeafAxis::compiled_flag`),
1499    /// because without the feature the axis is compiled out and the
1500    /// declaration would be dropped in silence.
1501    pub const LIFECYCLE_SERVICES_ENABLED: bool = cfg!(feature = "lifecycle-services");
1502    /// See [`LIFECYCLE_SERVICES_ENABLED`].
1503    pub const SAFETY_E2E_ENABLED: bool = cfg!(feature = "safety-e2e");
1504    /// See [`LIFECYCLE_SERVICES_ENABLED`].
1505    pub const ROSOUT_ENABLED: bool = cfg!(feature = "rosout");
1506    /// See [`LIFECYCLE_SERVICES_ENABLED`].
1507    pub const SIM_TIME_ENABLED: bool = cfg!(feature = "sim-time");
1508
1509    /// The build-time executor callback-table size
1510    /// (`NROS_EXECUTOR_MAX_CBS`, default 4). Re-exported so the `nros::main!`
1511    /// expansion can `const`-assert the model's entity count against the
1512    /// capacity that ACTUALLY compiles in, instead of letting the image boot
1513    /// and die on `create_timer (code=-6 Full)`.
1514    pub use ::nros_node::config::MAX_CBS as EXECUTOR_MAX_CBS;
1515}
1516
1517// Phase 110.B / 110.G — scheduling-context API surface. Consumers
1518// of the Phase 110 cyclic / TT scheduler need these types to
1519// describe schedules and bind handles; re-exporting them here
1520// keeps user code free of `nros_node::executor::sched_context`
1521// path noise. Gated on `rmw-cffi`: the source module is
1522// `#[cfg(any(has_rmw, test))]` in nros-node, so it only exists once
1523// an RMW backend is linked (matches the re-export block above).
1524#[cfg(feature = "rmw-cffi")]
1525pub use nros_node::executor::sched_context::{
1526    DeadlineAction, DeadlinePolicy, OptUs, Priority, SchedClass, SchedContext, SchedContextId,
1527    TimeTriggeredSchedule, TimeTriggeredScheduleError, TimeTriggeredWindow,
1528};
1529
1530#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
1531pub use nros_node::SpinPeriodResult;
1532
1533// Re-export service types
1534pub use nros_core::{ServiceClient, ServiceServer};
1535
1536// Re-export action types.
1537//
1538// issue 0796 — `CancelResponse` (the per-goal Reject/Accept decision) and
1539// `CancelResponseCode` (the `action_msgs/srv/CancelGoal` RPC status) are two
1540// concepts that shared one name until the split. Both are exported: without
1541// `CancelResponseCode` here, `ActionClient::cancel_goal`'s `Promise<CancelResponseCode>`
1542// could not be NAMED from `nros::` alone.
1543pub use nros_core::{
1544    CancelResponse, CancelResponseCode, GoalInfo, GoalResponse, GoalStatusCode, GoalStatusStamped,
1545    GoalUuid, RosAction,
1546};
1547// phase-515 R8 -- the pre-rename names, deprecated for one release.
1548#[allow(deprecated)]
1549pub use nros_core::{CancelReturnCode, GoalId, GoalStatus};
1550
1551// Re-export lifecycle types (always available, no_std compatible)
1552pub use nros_core::{LifecycleState, LifecycleTransition, TransitionResult};
1553pub use nros_node::{LifecycleCallbackFn, LifecycleError, LifecyclePollingNode};
1554
1555/// Re-export of the full lifecycle module so examples can reach
1556/// `LifecycleCallbackSlot`, `LifecyclePollingNodeCtx`, etc.
1557pub mod lifecycle {
1558    pub use nros_core::lifecycle::{LifecycleState, LifecycleTransition, TransitionResult};
1559    pub use nros_node::lifecycle::*;
1560}
1561
1562// Phase 128.G — bridge surface re-exports. Gated behind the
1563// `bridge` / `config` umbrella features so single-backend builds
1564// don't pull in `nros-bridge` (or, for `config`, the TOML stack).
1565#[cfg(feature = "bridge")]
1566pub use nros_bridge as bridge;
1567
1568#[cfg(feature = "config")]
1569pub use nros_bridge::run_from_config;
1570
1571// Re-export parameter types.
1572//
1573// phase-382 W2' — `ParameterStorage` / `ParameterTable` are here because the
1574// store's slots are CALLER-OWNED: anyone constructing a `ParameterServer`
1575// outside an executor has to place the storage and lend it.
1576// phase-426 W1 — `NodeKey` is here because every per-parameter call names the
1577// node it is about; a consumer holding a `ParameterServer` needs it to say so.
1578// phase-417 W4.a — the rest of the parameter vocabulary. Five ledger rows
1579// (`rust:ParameterRange`, `rust:ParameterRanges`, `rust:Parameters`,
1580// `rust:Node::use_undeclared_parameters`, `rust:RmwParameterConversionError`)
1581// were not missing capabilities: `nros_params` had every one of them and this
1582// list stopped at ten names, so a user of the facade could build a range
1583// through the builder's scalar arguments and never NAME the type it produced.
1584// An unexported type is a capability a user cannot write down.
1585/// Deprecated: the store answers `Result<(), ParameterError>`.
1586#[allow(deprecated)]
1587pub use nros_params::SetParameterResult;
1588#[allow(deprecated)]
1589pub use nros_params::UndeclaredParameters;
1590pub use nros_params::{
1591    DeclarationError, FloatingPointRange, IntegerRange, MAX_ON_SET_CALLBACKS, MandatoryParameter,
1592    NodeKey, OnSetContext, OnSetParameterFn, OnSetParameterHandle, OptionalParameter, Parameter,
1593    ParameterBuilder, ParameterDescriptor, ParameterError, ParameterRange, ParameterServer,
1594    ParameterStorage, ParameterTable, ParameterType, ParameterValue, ParameterVariant, Parameters,
1595    ReadOnlyParameter,
1596};
1597// Issue 2768 -- the two lines every full-store report ends with, so a refusal
1598// raised outside the executor (the C server's `max_params` check) names the
1599// knob in the same words as `Executor::report_parameter_refused`.
1600pub use nros_params::{STORE_SIZE_DERIVED, STORE_SIZE_KNOB};
1601// The wire-side half: why an `rcl_interfaces` parameter value could not be
1602// turned into a native one. The `~/set_parameters` handler already puts
1603// `reason()` into the `SetParametersResult`; without the type a user could read
1604// the sentence and not match on the cause.
1605// Gated like the module it comes from: `parameter_services` is the six
1606// `rcl_interfaces/srv/*` servers, and an image without them has no wire side
1607// for this error to describe.
1608// Gated like the module it comes from: `parameter_services` is
1609// `#[cfg(all(feature = "param-services", any(has_rmw, test)))]` in nros-node,
1610// so it exists only once an RMW backend is linked — the same pairing the
1611// `sched_context` re-export above uses.
1612#[cfg(all(feature = "param-services", feature = "rmw-cffi"))]
1613pub use nros_node::parameter_services::RmwParameterConversionError;
1614#[cfg(all(feature = "param-services", feature = "rmw-cffi"))]
1615#[allow(deprecated)]
1616pub use nros_node::parameter_services::ValueConversionError;
1617/// Prelude module for convenient imports
1618///
1619/// Import everything you need with a single statement:
1620/// ```
1621/// use nros::prelude::*;
1622/// ```
1623/// The RTOS machinery, named explicitly.
1624///
1625/// The second tier of the two-tier surface. `nros::prelude` is the API a ported
1626/// ROS 2 node uses; everything here exists because the target is an RTOS, has no
1627/// correspondent in rclrs/rclcpp/rclc, and a ROS 2 developer reading a node
1628/// should not have to step over it.
1629///
1630/// Nothing moved out of `nros::` — these are re-exports, and every name is still
1631/// reachable at its old path. What changed is that they are no longer dragged in
1632/// by `use nros::prelude::*`.
1633///
1634/// The membership rule is mechanical rather than taste: a name belongs in the
1635/// PRELUDE iff the parity ledger gives it a non-`extension` verdict — i.e. it
1636/// corresponds to something in rclrs, rclcpp or rclc. Names with no
1637/// correspondent belong here, unless they are load-bearing for startup
1638/// (`ExecutorConfig`, `SpinOptions`), which is an argued allow-list rather than
1639/// an exception anyone may grow.
1640pub mod embedded {
1641    // Wire encoding. A node publishes typed messages; these are for code that
1642    // handles bytes, which upstream hides entirely.
1643    pub use crate::{CdrReader, CdrWriter};
1644
1645    // Handle bookkeeping — the static tables that replace an allocator.
1646    #[cfg(feature = "rmw-cffi")]
1647    pub use crate::{HandleId, HandleSet, InvocationMode};
1648
1649    // Component/runtime plumbing, and the source-metadata capture the
1650    // orchestration layer records. None of it appears in a ported node.
1651    pub use crate::MetadataRecorder;
1652
1653    // Entity REGISTRATION vocabulary. A ported node writes
1654    // `create_publisher(...)`; these are what the declaration macros and the
1655    // orchestration layer use to describe what was created.
1656    #[cfg(feature = "rmw-cffi")]
1657    pub use crate::__macro::{record_node_metadata, register_node};
1658    #[cfg(feature = "rmw-cffi")]
1659    pub use crate::CallbackEffects;
1660    pub use crate::{
1661        ActionTag, Callback, CallbackEffectKind, EntityKind, NodeRuntime, ServiceTag,
1662        SourceLocationMetadata, SourceNameKind, SubscriptionTag,
1663    };
1664    // Gated where the root gates it — the export follows the capability, not
1665    // the sched task.
1666    #[cfg(feature = "alloc")]
1667    pub use crate::SourceMetadataExport;
1668}
1669
1670pub mod prelude {
1671    // phase-379 W5 — the RTOS machinery moved to `nros::embedded`. Removed
1672    // here rather than re-exported from both: a two-tier surface that still
1673    // drags tier two in through the glob is one tier with extra words.
1674
1675    pub use crate::{
1676        Deserialize, Logger, MessageInfo, QoSDurabilityPolicy, QoSHistoryPolicy, QoSProfile,
1677        QoSReliabilityPolicy, RosMessage, RosService, Serialize, ServiceInfo,
1678    };
1679
1680    // phase-417 / issue 0589 — logging, in the glob a node author already
1681    // writes. `Logger` above now means `nros_log::Logger`; these are what
1682    // drives it. Without them the shortest path from `use nros::prelude::*` to
1683    // a printed line was `std::println!`, which kills a Zephyr `native_sim`
1684    // image outright.
1685    //
1686    // The five severity macros now carry rclrs's OWN names (RFC-0089, settled
1687    // 2026-09-04), so a ROS 2 developer meeting one through the glob meets the
1688    // exact spelling their client library has, not a near-miss of it. That is
1689    // the property `check-prelude-tiers` enforces mechanically: a ledger
1690    // `extension` may not sit in the glob.
1691    //
1692    // `Severity`, `get_logger`, `get_or_create_logger`, `register_logger` and
1693    // `nros_trace` are ledger `extension`s -- rclrs has no correspondent for a
1694    // free logger lookup, a registry, or a TRACE severity (it stops at debug).
1695    // They stay behind `nros::logging::` / the crate root, where reaching for
1696    // one is a decision. phase-379 W5's rule, applied to this phase's own work.
1697    //
1698    // The throttle macros ARE here: they are ledger `divergence`s, not
1699    // extensions -- rclrs has the capability under a different decomposition
1700    // (`log_info!(logger.throttle(d), "…")`), so the glob is not introducing a
1701    // name with no upstream counterpart.
1702    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
1703    pub use crate::{Component, DeclarativeNode, NodeContext};
1704    #[cfg(feature = "alloc")]
1705    pub use crate::{
1706        NodeActionClient, NodeActionServer, NodeDeclError, NodeParameter, NodePublisher,
1707        NodeResult, NodeServiceClient, NodeServiceServer, NodeSubscription, NodeTimer,
1708        ParameterDefault, node,
1709    };
1710    pub use crate::{
1711        log_debug, log_error, log_fatal, log_info, log_warn, nros_debug_throttle,
1712        nros_debug_throttle_at, nros_error_throttle, nros_error_throttle_at, nros_fatal_throttle,
1713        nros_fatal_throttle_at, nros_info_throttle, nros_info_throttle_at, nros_warn_throttle,
1714        nros_warn_throttle_at,
1715    };
1716
1717    // phase-515 R2 -- `executor.create_node("talker".namespace("/ns"))`.
1718    pub use crate::{IntoNodeOptions, NodeOptions};
1719    // phase-515 R1 -- `node.create_publisher::<M>("chatter".keep_last(10))`.
1720    pub use crate::{IntoPrimitiveOptions, PrimitiveOptions};
1721
1722    // Re-export lifecycle types
1723    pub use crate::{
1724        LifecycleCallbackFn, LifecycleError, LifecyclePollingNode, LifecycleState,
1725        LifecycleTransition, TransitionResult,
1726    };
1727
1728    // Re-export executor config + handle types (always available)
1729    pub use crate::{
1730        ExecutorConfig, GuardCondition, NodeError, SessionMode, SpinOnceResult, SpinOptions,
1731        SpinPeriodPollingResult, TransportError, Trigger,
1732    };
1733
1734    // issue 0687 — `ExecutorConfig::from_env()` is an extension trait now (the
1735    // environment is read at this crate's edge, not in the core), so the
1736    // spelling only works where the trait is in scope. It is in the prelude
1737    // precisely so that the consumers written against the inherent method —
1738    // the native examples, the benches — keep compiling unchanged.
1739    #[cfg(feature = "env")]
1740    pub use crate::ExecutorConfigEnvExt;
1741
1742    // Re-export RMW-dependent executor + handle types
1743    #[cfg(feature = "rmw-cffi")]
1744    pub use crate::{
1745        EmbeddedPublisher, EmbeddedServiceClient, Executor, FeedbackStream, Node, Promise,
1746        Subscription,
1747    };
1748
1749    // Publisher/Subscriber options (topic + QoS).
1750    pub use crate::{PublisherOptions, SubscriptionOptions};
1751
1752    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
1753    pub use crate::SpinPeriodResult;
1754
1755    // Re-export parameter types
1756    pub use crate::{ParameterServer, ParameterStorage, ParameterType, ParameterValue};
1757
1758    // Re-export typed parameter API (rclrs-compatible builder pattern)
1759    pub use crate::{
1760        MandatoryParameter, OptionalParameter, ParameterBuilder, ParameterError, ParameterVariant,
1761        ReadOnlyParameter,
1762    };
1763
1764    // Re-export action types
1765    #[allow(deprecated)]
1766    pub use crate::{GoalId, GoalStatus};
1767    pub use crate::{
1768        GoalInfo, GoalResponse, GoalStatusCode, GoalStatusStamped, GoalUuid, RosAction,
1769    };
1770
1771    // Re-export Time, Duration, Clock from core
1772    pub use nros_core::{Clock, ClockType, Duration, Time};
1773
1774    // Re-export timer types
1775    pub use crate::{TimerCallbackFn, TimerDuration, TimerHandle, TimerMode};
1776}
1777
1778/// Derive macros for message types
1779///
1780/// Use these macros to generate message serialization code.
1781/// These macros help you create custom message types that are compatible
1782/// with ROS 2's CDR serialization format.
1783pub mod derive {
1784    #[cfg(feature = "macros")]
1785    pub use nros_macros::RosMessage;
1786}
1787
1788#[cfg(test)]
1789mod tests {
1790    #[test]
1791    fn test_prelude_imports() {
1792        // This test just verifies that the prelude compiles
1793        use crate::prelude::*;
1794
1795        let _ = QoSProfile::BEST_EFFORT;
1796    }
1797
1798    /// The component trait, its registration context and the result type
1799    /// resolve under the names phase-483 W2/W3 gave them: `Component` (the
1800    /// trait, which phase-212 had named `Node`) and a `NodeContext` with no
1801    /// runtime parameter.
1802    #[cfg(feature = "rmw-cffi")]
1803    #[test]
1804    fn node_context_types_resolve() {
1805        fn _take_node_ctx<N: crate::Component>(_: &mut crate::NodeContext<'_>) {}
1806        let _: crate::NodeResult<()> = Ok(());
1807    }
1808}
1809
1810// ---------------------------------------------------------------------------
1811// phase-361 W8.e / issue 0594 — capabilities REQUIRE the heap / the standard
1812// library, they do not enable it. Turning `alloc` or `std` on for the user
1813// silently changes what their firmware image is; naming the feature they must
1814// add does not.
1815// ---------------------------------------------------------------------------
1816// issue 0687 follow-up — `alloc`, not `std`. The reason recorded here ("writes
1817// a file and exits") was never this crate's: the file write is `nros-cpp`'s
1818// `metadata_hooks`. What `metadata_mode.rs` actually needed was a `Sync`
1819// global, and it named `std::sync::Mutex` for it; on the portable mutex the
1820// capability is `String` + `format!` + a lock, i.e. the heap and nothing more.
1821#[cfg(all(feature = "metadata-mode", not(feature = "alloc")))]
1822compile_error!(
1823    "`metadata-mode` records into a heap-allocated global: add \"alloc\" to this crate's features"
1824);
1825// phase-359 W10 stage B — `env` needs a PROCESS, not the standard library:
1826// its reader is the C library's `getenv` (`src/env.rs`). It needs the heap
1827// for `Context`'s owned strings and the `--params-file` read.
1828#[cfg(all(feature = "env", not(target_os = "linux")))]
1829compile_error!(
1830    "`env` reads the process environment through the C library, which this target does not have: a target image takes its boot config from `system.toml` (baked), so drop \"env\""
1831);
1832#[cfg(all(feature = "env", not(feature = "alloc")))]
1833compile_error!("`env` builds an owned `Context`: add \"alloc\" to this crate's features");
1834
1835// phase-379 W5, revised by phase-428 W10 — the crate-level `QOS_PROFILE_*`
1836// presets (rclrs parity) and the older `nros::qos::*` module are two spellings
1837// of the same profiles. BOTH now alias `QoSProfile`'s associated consts; until
1838// W10 the second restated them as struct literals, and these tests were the only
1839// thing holding the two copies together.
1840//
1841// They are kept, and what they assert has changed meaning. They no longer catch
1842// a hand-mirror drifting (there is no longer a hand mirror to drift — issues
1843// 0088 / 0160 / 0245). They catch a REINTRODUCTION: the moment someone writes a
1844// literal into either surface instead of aliasing, a value can differ and one of
1845// these fails. That is cheap enough to keep and is the only mechanism standing
1846// between this crate and the arrangement W10 removed.
1847//
1848// What they do NOT check, deliberately, is whether the SSoT matches UPSTREAM.
1849// Two aliases of a wrong constant agree perfectly — which is exactly the state
1850// `QOS_PROFILE_PARAMETER_EVENTS` was in (`KeepAll, 0` against upstream's
1851// `KEEP_LAST, 1000`). That assertion belongs beside the associated consts in
1852// `nros-rmw/src/traits.rs`, not here.
1853#[cfg(test)]
1854mod qos_preset_parity {
1855    use super::*;
1856
1857    #[test]
1858    fn crate_level_presets_alias_the_associated_consts() {
1859        assert_eq!(QOS_PROFILE_DEFAULT, QoSProfile::QOS_PROFILE_DEFAULT);
1860        assert_eq!(QOS_PROFILE_SENSOR_DATA, QoSProfile::QOS_PROFILE_SENSOR_DATA);
1861        assert_eq!(QOS_PROFILE_PARAMETERS, QoSProfile::QOS_PROFILE_PARAMETERS);
1862        assert_eq!(
1863            QOS_PROFILE_ACTION_STATUS_DEFAULT,
1864            QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT
1865        );
1866    }
1867
1868    /// `qos::*` was a SEPARATE hand-written copy until phase-428 W10; all five
1869    /// names alias the associated consts now, so this passes by construction.
1870    /// It stays as the tripwire for re-introducing a literal — see the module
1871    /// comment above.
1872    #[test]
1873    fn qos_module_agrees_with_the_presets() {
1874        // issue 0829 FIXED — SYSTEM_DEFAULT was the first to become an alias.
1875        // It is here rather than in its own pinned test because the two copies
1876        // no longer say anything a copy could get wrong: both alias the one
1877        // associated const, which is all sentinel.
1878        assert_eq!(
1879            qos::SYSTEM_DEFAULT,
1880            QOS_PROFILE_SYSTEM_DEFAULT,
1881            "qos::SYSTEM_DEFAULT drifted"
1882        );
1883        assert_eq!(qos::DEFAULT, QOS_PROFILE_DEFAULT, "qos::DEFAULT drifted");
1884        assert_eq!(
1885            qos::SENSOR_DATA,
1886            QOS_PROFILE_SENSOR_DATA,
1887            "qos::SENSOR_DATA drifted"
1888        );
1889        assert_eq!(
1890            qos::SERVICES_DEFAULT,
1891            QOS_PROFILE_SERVICES_DEFAULT,
1892            "qos::SERVICES_DEFAULT drifted"
1893        );
1894        assert_eq!(
1895            qos::PARAMETERS,
1896            QOS_PROFILE_PARAMETERS,
1897            "qos::PARAMETERS drifted"
1898        );
1899    }
1900
1901    /// issue 0829, RESOLVED — this test used to PIN the divergence, asserting
1902    /// depth 10 on the façade side and depth 1 on the `nros-rmw` side because
1903    /// neither was obviously the live one. Both numbers are gone, and the
1904    /// replacement is not "we picked one": no concrete depth can be right,
1905    /// because the two reference RMWs resolve the same sentinel differently
1906    /// (`rmw_cyclonedds_cpp` → `KEEP_LAST, 1`; `rmw_zenoh_cpp` →
1907    /// `RMW_ZENOH_DEFAULT_HISTORY_DEPTH`, 42).
1908    ///
1909    /// So what is asserted now is the SHAPE: `SYSTEM_DEFAULT` states nothing,
1910    /// on every field. That is what makes it different from `DEFAULT` — the
1911    /// two being byte-identical was the older defect, and asserting they
1912    /// DIFFER is what keeps anyone from quietly aliasing them again.
1913    #[test]
1914    fn system_default_states_nothing_on_every_field() {
1915        use nros_rmw::{
1916            DEPTH_SYSTEM_DEFAULT, QoSDurabilityPolicy, QoSHistoryPolicy, QoSLivelinessPolicy,
1917            QoSReliabilityPolicy,
1918        };
1919        let sd = QOS_PROFILE_SYSTEM_DEFAULT;
1920        assert_eq!(sd.reliability, QoSReliabilityPolicy::SystemDefault);
1921        assert_eq!(sd.durability, QoSDurabilityPolicy::SystemDefault);
1922        assert_eq!(sd.history, QoSHistoryPolicy::SystemDefault);
1923        assert_eq!(sd.depth, DEPTH_SYSTEM_DEFAULT);
1924        // `None` IS the liveliness sentinel — it lowers to
1925        // `NROS_RMW_LIVELINESS_SYSTEM_DEFAULT` (0), the two having collapsed
1926        // onto one value in phase-376 W5/B2.
1927        assert_eq!(sd.liveliness_kind, QoSLivelinessPolicy::None);
1928        assert!(sd.has_unresolved_system_default());
1929
1930        // The whole point of the name: it is NOT a synonym for DEFAULT.
1931        assert_ne!(
1932            sd, QOS_PROFILE_DEFAULT,
1933            "SYSTEM_DEFAULT aliased DEFAULT again — see issue 0829"
1934        );
1935        assert!(!QOS_PROFILE_DEFAULT.has_unresolved_system_default());
1936    }
1937}