nros/contract.rs
1//! Contract monitors on target, and the `/diagnostics` reporter they publish
2//! through — ONE implementation for every language.
3//!
4//! A contracted image bakes monitor tables
5//! (`min_rate_hz` / `max_latency_ms` per publisher, `max_age_ms` per
6//! subscriber), the executor checks them every spin and logs each violation at
7//! detection (the floor every image keeps). A C or C++ image can also
8//! PUBLISH each one as a `DiagnosticArray` on `/diagnostics`, through a
9//! reporter `nros-cpp` armed when the tables were installed. The Rust entry
10//! (`nros::main!`) installed no table at all, so it neither
11//! monitored nor reported.
12//!
13//! This module is that reporter, moved up to the umbrella so the three
14//! languages share it: [`DiagSink`] (one `/diagnostics` publisher and its two
15//! counters) and its violation sink, used by `nros-cpp`'s
16//! `nros_cpp_install_monitors` and by [`install_contract_monitors`], which the
17//! `nros::main!` expansion calls before the first node is created. The mapping
18//! from a violation to a report is `nros-diagnostics`'
19//! (`DiagnosticReporter::report_violation`, streamed by
20//! `write_violation_reports` so the report never sits on the spin thread's
21//! stack as a value), so a violation reads the same from every road. The
22//! executor hands the reporter its queued verdicts off the judged dispatch,
23//! and one report carries as many as fit one message.
24
25use core::{cell::UnsafeCell, ffi::c_void};
26
27use nros_core::RosMessage;
28use nros_diagnostics::DiagnosticArray;
29use nros_node::executor::{
30 Executor, NodeError,
31 monitor::{AgeMonitorSpec, MonitorSpec, Violation},
32};
33use nros_rmw::Publisher as _;
34
35use crate::internals::RmwPublisher;
36
37/// The topic ROS 2's diagnostics tooling reads.
38pub const DIAG_TOPIC: &str = "/diagnostics";
39
40/// One report's CDR: one `DiagnosticStatus` (name <= 64, message <= 128,
41/// hardware id <= 96) with one key/value (<= 32 + 64) and the array's header.
42/// 512 covers that with room; a report that does not fit is counted, not sent
43/// truncated.
44const REPORT_BUF: usize = 512;
45
46/// One executor's `/diagnostics` reporter: the publisher and two counters.
47///
48/// No rate-limit state: the rules are windowed and fire on transitions, so the
49/// reporter is built per call with no interval (and this struct's size, which
50/// `nros-build-helpers` adds to `CPP_EXECUTOR_OPAQUE_U64S`, stays the
51/// publisher plus two words).
52pub struct DiagSink {
53 publisher: RmwPublisher,
54 /// Reports published.
55 pub published: u32,
56 /// Reports that could not be (serialise or publish failed).
57 pub failed: u32,
58}
59
60impl DiagSink {
61 /// Create the `/diagnostics` publisher on `executor`'s PRIMARY node, in
62 /// `domain_id` (the executor's own for a Rust entry; the C++ context
63 /// keeps its domain beside the executor).
64 ///
65 /// An executor-level entity, so it is announced under the primary node
66 /// (`Executor::create_executor_publisher`), as a stock ROS 2 node publishes its own diagnostics. It used to be a
67 /// session publisher with no node, filed under the session's own name.
68 pub fn create(executor: &mut Executor<'_>, domain_id: u32) -> Result<Self, NodeError> {
69 let publisher = executor.create_executor_publisher(
70 DIAG_TOPIC,
71 <DiagnosticArray as RosMessage>::TYPE_NAME,
72 <DiagnosticArray as RosMessage>::TYPE_HASH,
73 nros_rmw::QoSProfile::default(),
74 domain_id,
75 )?;
76 Ok(Self {
77 publisher,
78 published: 0,
79 failed: 0,
80 })
81 }
82
83 /// Point `executor`'s violation sink at this reporter.
84 ///
85 /// # Safety
86 /// `self` must not move, and must outlive every spin of `executor`, until
87 /// the sink is removed (`set_violation_sink(None)`) or the executor is
88 /// dropped — the executor keeps its address.
89 pub unsafe fn hook(&mut self, executor: &mut Executor<'_>) {
90 let ctx = self as *mut DiagSink as *mut c_void;
91 unsafe { executor.set_violation_sink(Some((publish_violations as _, ctx))) };
92 }
93}
94
95/// The executor's violation sink: the pending violations, coalesced into one
96/// `DiagnosticArray` -- as many of them, oldest first, as fit [`REPORT_BUF`].
97/// Returns how many it took (0 when even one could not be sent, which it
98/// counts in `failed`).
99///
100/// phase-474 I7 -- the executor calls this off the judged dispatch, at the end
101/// of a spin with slack, with every verdict queued since the last call. Each
102/// status is the one a single report would carry; on the safety island's
103/// 921,600-baud serial link one report cost 15-20 ms of spin, so one message
104/// for several verdicts is the difference between one tick and several.
105///
106/// # Safety
107/// `ctx` is the [`DiagSink`] [`DiagSink::hook`] installed.
108unsafe fn publish_violations(ctx: *mut c_void, pending: &[Violation]) -> usize {
109 let sink = unsafe { &mut *(ctx as *mut DiagSink) };
110 // No rate limit: the rules themselves are windowed and fire on
111 // transitions. phase-474 I7 -- the report is STREAMED into the buffer
112 // (`write_violation_reports`, byte-identical to serializing the value
113 // form). The value is a 5 KB `DiagnosticArray`, and building it on the
114 // spin thread ran the safety island's 16 KiB main stack into the idle
115 // thread's on its first stored violation. What stays on this frame is the
116 // 512 B buffer and four borrowed tuples.
117 let mut buf = [0u8; REPORT_BUF];
118 let mut rows: [(&str, &str, u32, u32, &str); nros_node::executor::monitor::REPORT_QUEUE] =
119 [("", "", 0, 0, ""); nros_node::executor::monitor::REPORT_QUEUE];
120 let n_max = pending.len().min(rows.len());
121 for (row, v) in rows.iter_mut().zip(pending.iter()) {
122 *row = (v.rule, v.fqn, v.measured, v.declared, v.level);
123 }
124 // The most that fit one buffer: a status is 100-300 B, so two or three
125 // usually do; whatever does not fit waits for the next slot.
126 let mut n = n_max;
127 while n > 0 {
128 let Ok(mut w) = nros_core::CdrWriter::new_with_header(&mut buf) else {
129 break;
130 };
131 if nros_diagnostics::write_violation_reports(&mut w, &rows[..n]).is_ok() {
132 let len = w.position();
133 return match sink.publisher.publish_raw(&buf[..len]) {
134 Ok(()) => {
135 sink.published = sink.published.saturating_add(1);
136 n
137 }
138 Err(_) => {
139 sink.failed = sink.failed.saturating_add(1);
140 0
141 }
142 };
143 }
144 n -= 1;
145 }
146 sink.failed = sink.failed.saturating_add(1);
147 0
148}
149
150/// Static storage for one executor's [`DiagSink`] — what a Rust entry owns in
151/// place of the C++ context's `diag` field.
152///
153/// `nros::main!` emits one per executor that installs a non-empty table, as a
154/// `static`. Filled once, by [`install_contract_monitors`], on the thread that
155/// registers that executor's nodes; read afterwards only through the
156/// executor's sink, on the thread that spins it.
157pub struct ContractReporter {
158 sink: UnsafeCell<Option<DiagSink>>,
159}
160
161// SAFETY: one `ContractReporter` serves one executor. It is written once,
162// before that executor spins, and afterwards reached only from that
163// executor's spin (through the sink pointer) — never from two threads at once.
164unsafe impl Sync for ContractReporter {}
165
166impl ContractReporter {
167 /// An empty reporter.
168 #[must_use]
169 pub const fn new() -> Self {
170 Self {
171 sink: UnsafeCell::new(None),
172 }
173 }
174}
175
176impl Default for ContractReporter {
177 fn default() -> Self {
178 Self::new()
179 }
180}
181
182/// Install a contracted Rust image's monitor tables on one executor, and arm
183/// its `/diagnostics` reporter.
184///
185/// The Rust spelling of `nros_cpp_install_monitors`. Call BEFORE any node is
186/// created on the executor: a publisher attaches its counter cell by exact
187/// topic match at create time, so a table installed later monitors nothing.
188/// `nros::main!` emits this ahead of the parameter services and the node
189/// registrations on every executor it builds (the single one, and each
190/// sched task's).
191///
192/// The tables are refused, not truncated, when they exceed the executor's
193/// `MAX_MONITORS` / `MAX_AGE_MONITORS` (the baked tables also carry a
194/// compile-time assert naming the knob). Empty tables install nothing and arm
195/// no reporter — an uncontracted image carries none of this. A reporter is
196/// armed once per `reporter`; a second install keeps the first.
197///
198/// The `/diagnostics` publisher opens on the primary node when that node is
199/// registered, and a failure to open it fails that registration (both roads,
200/// through [`arm_reporter`]; a census run arms none). Returns `Err` only for
201/// a refused table.
202///
203/// # Safety
204/// `executor` must be the live `*mut Executor<'static>` handle a
205/// `RuntimeCtx` hands out (`runtime.executor_handle()`), or NULL, and nothing
206/// else may hold a reference into that executor for the call.
207pub unsafe fn install_contract_monitors(
208 executor: *mut c_void,
209 monitors: &'static [MonitorSpec],
210 ages: &'static [AgeMonitorSpec],
211 reporter: &'static ContractReporter,
212) -> Result<(), &'static str> {
213 // Issue 1535 — the one handle check every seam in this crate makes.
214 let executor = match unsafe {
215 crate::executor_handle::executor_from_handle(executor, "install_contract_monitors")
216 } {
217 Ok(executor) => executor,
218 Err(crate::executor_handle::HandleRefusal::Null) => {
219 return Err("the runtime hands out no executor to install the contract monitors on");
220 }
221 Err(crate::executor_handle::HandleRefusal::CppContext) => {
222 return Err("the contract monitors were handed an nros-cpp context, not an executor");
223 }
224 };
225 if let Err(full) = executor.try_set_monitor_tables(monitors, ages) {
226 nros_log::log_error!(
227 nros_log::get_logger("nros.contract"),
228 "install_contract_monitors: {}",
229 full
230 );
231 return Err("the contract's monitor tables exceed the executor's monitor capacity");
232 }
233 if monitors.is_empty() && ages.is_empty() {
234 return Ok(());
235 }
236 // SAFETY: see `ContractReporter`'s `Sync` — this is the one write, made
237 // before the executor spins.
238 let slot = unsafe { &mut *reporter.sink.get() };
239 let domain_id = executor.domain_id();
240 // SAFETY: `slot` lives in a `'static` reporter and never moves.
241 unsafe { arm_reporter(executor, domain_id, slot) };
242 Ok(())
243}
244
245/// Install a contracted Rust image's hazard table on one
246/// executor, after [`install_contract_monitors`] (each hazard's guards index
247/// the two tables that call installs). `nros::main!` emits this only for an
248/// executor whose tables observe a hazard; the observer then reports
249/// `hazard-detected`, `hazard-reaction` and `hazard-recovered` through the
250/// reporter that call armed.
251///
252/// A NULL or non-executor handle installs nothing: the monitor install it
253/// follows has already refused that handle, and said so.
254///
255/// # Safety
256/// As for [`install_contract_monitors`].
257pub unsafe fn install_contract_hazards(
258 executor: *mut c_void,
259 hazards: &'static [nros_node::executor::monitor::HazardSpec],
260) {
261 if let Ok(executor) = unsafe {
262 crate::executor_handle::executor_from_handle(executor, "install_contract_hazards")
263 } {
264 executor.set_hazard_table(hazards);
265 }
266}
267
268/// Install a contracted Rust image's MODE variants of the two
269/// monitor tables on one executor, after [`install_contract_monitors`] (entry
270/// 0 of `modes` is that call's base tables). `nros::main!` emits this only
271/// for a model that declares modes; `nros::monitor::request_mode` then
272/// switches every executor at its next spin.
273///
274/// # Errors
275///
276/// A variant whose tables are not the base's length, which the bake already
277/// refuses, so this is a corrupted image; a NULL or non-executor handle, as
278/// [`install_contract_monitors`] reports it.
279///
280/// # Safety
281/// As for [`install_contract_monitors`].
282pub unsafe fn install_contract_modes(
283 executor: *mut c_void,
284 modes: &'static [nros_node::executor::monitor::ModeTables],
285) -> Result<(), &'static str> {
286 let executor =
287 unsafe { crate::executor_handle::executor_from_handle(executor, "install_contract_modes") }
288 .map_err(|_| "install_contract_modes: not an executor handle")?;
289 executor
290 .set_mode_tables(modes)
291 .map_err(|_| "a contract mode's tables are not the base tables' shape (re-run the bake)")
292}
293
294/// Arm one executor's `/diagnostics` reporter in `slot`, and point the
295/// executor's violation sink at it — THE arming step, shared by
296/// [`install_contract_monitors`] (Rust) and `nros-cpp`'s
297/// `nros_cpp_install_monitors` (C and C++).
298///
299/// * Idempotent: a slot already holding a reporter keeps it.
300/// * A CENSUS run arms nothing ([`crate::census_hooks::recording_run`]): it
301/// never spins, so the reporter could never publish, and the recorder has no
302/// node open yet to attribute it to — it refused the publisher, and the
303/// C/C++ road turned that refusal into a failed setup that recorded nothing.
304/// * The publisher opens on the image's PRIMARY node. Armed
305/// before any node exists -- the usual case, since the tables must precede
306/// every entity -- it opens when the primary node is registered, and a
307/// failure then fails that registration (the node's `build()` returns it).
308/// An image that registers no node opens it at its first spin instead, and
309/// `spin` returns the failure (a temporary path; see
310/// `Executor::open_pending_on_configured_name`).
311/// * Armed after a node exists, it opens now, and a publisher that cannot be
312/// created is REPORTED here, not fatal: the tables stay installed and every
313/// violation still reaches the log (the floor).
314///
315/// Returns whether a reporter is armed (or waiting for the primary node)
316/// after the call.
317///
318/// # Safety
319/// `slot` must not move, and must outlive every spin of `executor`, until the
320/// sink is removed (`set_violation_sink(None)`) or the executor is dropped —
321/// [`DiagSink::hook`]'s contract.
322pub unsafe fn arm_reporter(
323 executor: &mut Executor<'_>,
324 domain_id: u32,
325 slot: &mut Option<DiagSink>,
326) -> bool {
327 if slot.is_some() || executor.primary_node_open_pending() {
328 return true;
329 }
330 if crate::census_hooks::recording_run() {
331 return false;
332 }
333 // RFC-0128 D8 (phase-554 W3 slice B) -- the publisher belongs to the
334 // primary node, and the reporter is armed BEFORE any node exists (the
335 // tables must precede every entity). So the open is handed to the
336 // executor, which runs it the moment the primary node is registered: a
337 // failure then fails that node's registration, loudly. When a node is
338 // already registered it runs now, and a failure is reported here.
339 let ctx = slot as *mut Option<DiagSink> as *mut c_void;
340 // SAFETY: `slot` outlives the executor's spins (this fn's contract), so
341 // it is valid when the hook runs.
342 match unsafe { executor.open_on_primary_node(open_reporter, ctx, domain_id) } {
343 Ok(()) => true,
344 Err(e) => {
345 // issues 1635/1676
346 nros_log::log_error!(
347 nros_log::get_logger("nros.contract"),
348 "contract monitors installed, but the {} publisher could not be created \
349 ({:?}); violations stay in the log only",
350 DIAG_TOPIC,
351 e
352 );
353 false
354 }
355 }
356}
357
358/// The executor-run half of [`arm_reporter`]: open the publisher on the
359/// primary node, fill `slot`, and point the violation sink at it.
360///
361/// # Safety
362/// `ctx` is the `*mut Option<DiagSink>` [`arm_reporter`] installed, under its
363/// contract.
364unsafe fn open_reporter(
365 ctx: *mut c_void,
366 domain_id: u32,
367 executor: &mut Executor<'_>,
368) -> Result<(), NodeError> {
369 let slot = unsafe { &mut *(ctx as *mut Option<DiagSink>) };
370 if slot.is_some() {
371 return Ok(());
372 }
373 let sink = slot.insert(DiagSink::create(executor, domain_id)?);
374 // SAFETY: `slot` does not move and outlives the executor's spins
375 // (`arm_reporter`'s contract).
376 unsafe { sink.hook(executor) };
377 Ok(())
378}