Skip to main content

nros_log/
early.rs

1//! Records that could not be delivered when they were raised: before any sink
2//! was installed, or while another thread was inside a sink.
3//!
4//! ## The problem this exists for
5//!
6//! [`crate::init`] publishes the sink list. A record raised before that call
7//! has nowhere to go, and for most of this crate's life it was constructed,
8//! dispatched and DROPPED — silently, and invisibly to its author, who cannot
9//! know what the board did before reaching their code.
10//!
11//! The first answer required every board boot funnel to call
12//! `init_default()`, gated on funnels spelled `pub fn run*`. That is a SEARCH
13//! for boot paths and it kept losing: NuttX's funnel is `pub extern "C" fn
14//! nsh_main`, and three board crates did not link `nros-log` in the
15//! configuration holding the funnel at all.
16//!
17//! The second answer had dispatch install the platform sink itself.
18//! That removed the search — but it put `nros_platform_log_write` on a path
19//! EVERY binary executes, which turned a pluggable delivery into a LINK-TIME
20//! requirement. Seven test targets in `nros-rmw-cffi` and most of `nros-tests`
21//! stopped linking under `check-workspace-features`, and no Cargo feature can
22//! fix that: `nros-platform-cffi` and `nros-rmw-bridge` enable
23//! `nros-node/rmw-cffi` unconditionally, so feature unification turns any
24//! forwarded gate back ON for every member of a workspace build. A feature is a
25//! property of the BUILD; what the question needs is a property of the BINARY.
26//!
27//! ## A funnel is not always a board method
28//!
29//! The search above kept losing for one more reason, and it is worth naming
30//! because it defeats the obvious grep: **not every boot funnel lives in a
31//! board crate.** `nros::main!` emits a different entry shape per framework,
32//! and two of them reach no `BoardEntry` method at all —
33//!
34//! * `Framework::Zephyr` (and its single-node sibling
35//!   `nros::zephyr_component_main!`) emits `rust_main` directly, because Zephyr
36//!   owns the C `main` and a Rust staticlib cannot take it over. That is why
37//!   `nros-board-zephyr` has only `run_sched_tasks` to install from, and why a
38//!   single-sched-task pure-Rust Zephyr image once published no sink list
39//!   while its `log::info!`s worked fine.
40//! * a `[[bridge]]` system replaces the register/spin body with
41//!   `nros_bridge::run_from_config_str`, so it reaches no board either.
42//!
43//! Both now call `nros_platform::log::init_default()` — reached through
44//! `nros-platform` (which re-exports `nros_platform_cffi::log`) because that is
45//! the crate a generated Entry and the Zephyr example leaves already declare;
46//! giving each leaf a `nros-platform-cffi` dep of its own is the link-time
47//! requirement 0710 rejected.
48//!
49//! So the enumeration is **board crates PLUS the framework arms of
50//! `nros-macros`' `main_macro.rs` PLUS `nros`' entry macros**. Sweep it with:
51//!
52//! ```text
53//! grep -rn 'Framework::[A-Za-z]* => ' packages/core/nros-macros/src/main_macro.rs
54//! grep -rn 'init_default()' packages/boards packages/core/nros-macros packages/api/nros
55//! ```
56//!
57//! ## What this does instead
58//!
59//! Hold the records. A record raised with no sinks installed is copied into a
60//! bounded static ring here; [`crate::init`] drains it into whatever sinks the
61//! board actually chose. Nothing is dropped, no board can forget, and this
62//! crate touches no platform symbol to do it — the facade stays a facade.
63//!
64//! It is also STRICTLY better than installing a default sink was: the early
65//! records land in the sink the board picked, rather than in whichever one
66//! dispatch guessed before the board had spoken.
67//!
68//! ## Cost, and how to decline it
69//!
70//! EARLY_DEPTH * (format buffer + name + header) of static RAM, all of it in
71//! `.bss`. The depth is the `NROS_LOG_EARLY_RECORDS` knob (builtin 4,
72//! resolved by `build.rs` on the env > board > builtin ladder — it replaced the
73//! `early-records-<N>` features), because a 64 KB MCU and a Linux host do not
74//! want the same number. `0` declines the buffer entirely and restores the
75//! old behaviour of dropping, with the count below still kept so the loss
76//! is at least reportable.
77//!
78//! Overflow is counted, never silently absorbed: [`overflowed`] returns how
79//! many records did not fit, and the next delivery reports the count through
80//! the sinks (`nros_log` logger, at `warn`).
81//!
82//! ## The same queue holds records that met a BUSY dispatcher
83//!
84//! Dispatch runs one record at a time: a flag is held across every
85//! `sink.log()`, so a sink that logs cannot recurse into itself, and two
86//! threads never write to a sink at once. A record that found the flag held
87//! used to be DROPPED, which was right for the recursion it was written
88//! for and wrong for everything else: a record from ANOTHER thread vanished
89//! whenever any thread was mid-delivery. `nros-log` cannot tell the two apart
90//! without a thread identity, which no `no_std` target here gives it for free.
91//!
92//! So such a record is held here instead, and the thread holding the flag
93//! delivers it before letting go. Nobody waits and nothing interleaves inside
94//! a sink. Two properties follow, both bounded on purpose:
95//!
96//! * **A sink that logs is not refused, it is postponed.** The holder makes at
97//!   most [`DRAIN_PASSES`] passes, each over the records already held when the
98//!   pass began, so a sink that logs on every write adds a bounded number of
99//!   lines per dispatch and can never loop or grow the stack. What is left
100//!   waits for the next dispatch or [`crate::flush`].
101//! * **A record cannot be stranded by the hand-off.** The raiser publishes the
102//!   record, then tries the flag once more; the holder releases the flag, then
103//!   looks for held records once more. Under `SeqCst` one of the two always
104//!   sees the other, so either the raiser delivers it or the holder does. The
105//!   only record left behind is one raised during the holder's LAST pass, which
106//!   the next dispatch or `flush` delivers.
107//!
108//! The knob sizes both uses, because they are one question: how many records
109//! may be waiting for a sink at once.
110
111use core::cell::UnsafeCell;
112
113use portable_atomic::{AtomicU8, AtomicUsize, Ordering};
114
115use crate::{Record, Severity, buffer::format_buffer_capacity};
116
117/// Records held at once. See the module docs for the trade.
118#[must_use]
119pub const fn early_depth() -> usize {
120    crate::config::EARLY_RECORDS
121}
122
123/// Passes a dispatcher makes over the held records before it lets go. See the
124/// module docs: this is what bounds a sink that logs.
125pub const DRAIN_PASSES: usize = 2;
126
127const DEPTH: usize = early_depth();
128const MSG_CAP: usize = format_buffer_capacity();
129/// A logger name is an identifier, not prose — `nros-node`'s longest is 20.
130const NAME_CAP: usize = 48;
131
132/// Slot states. A slot cycles `EMPTY -> WRITING -> READY -> READING -> EMPTY`,
133/// and each arrow is taken by exactly one thread (a CAS for the two claims).
134const EMPTY: u8 = 0;
135const WRITING: u8 = 1;
136const READY: u8 = 2;
137const READING: u8 = 3;
138
139/// Which sinks a held record is still owed to -- issue 2762.
140///
141/// A record that found a sink installed has ALREADY reached every
142/// re-entrant sink in its own context; it is held only for the others, and
143/// the drain must not hand it to a re-entrant sink a second time.
144#[derive(Clone, Copy, PartialEq, Eq, Debug)]
145pub(crate) enum Owed {
146    /// Every sink: no sink was installed yet, or the record took the
147    /// guarded path for all of them (the re-entrant depth was spent).
148    All,
149    /// Only the sinks that are not re-entrant.
150    Serialised,
151}
152
153struct Pending {
154    owed: Owed,
155    severity: Severity,
156    logger_name: heapless::String<NAME_CAP>,
157    message: heapless::String<MSG_CAP>,
158    file: &'static str,
159    line: u32,
160    timestamp_ns: u64,
161}
162
163impl Pending {
164    const fn new() -> Self {
165        Self {
166            owed: Owed::All,
167            severity: Severity::Info,
168            logger_name: heapless::String::new(),
169            message: heapless::String::new(),
170            file: "",
171            line: 0,
172            timestamp_ns: 0,
173        }
174    }
175}
176
177struct Slot {
178    /// Written only by the thread that moved `state` EMPTY -> WRITING, read
179    /// only by the one that moved it READY -> READING.
180    cell: UnsafeCell<Pending>,
181    state: AtomicU8,
182    /// Raise order, so a drain replays in the order records were raised.
183    seq: AtomicUsize,
184}
185
186// SAFETY: `cell` has one owner at a time, handed over by `state`: a writer owns
187// it from its EMPTY -> WRITING CAS to its `Release` store of READY, a reader
188// from its READY -> READING CAS (`Acquire`) to its `Release` store of EMPTY.
189unsafe impl Sync for Slot {}
190
191impl Slot {
192    const fn new() -> Self {
193        Self {
194            cell: UnsafeCell::new(Pending::new()),
195            state: AtomicU8::new(EMPTY),
196            seq: AtomicUsize::new(0),
197        }
198    }
199}
200
201#[allow(clippy::declare_interior_mutable_const)]
202const EMPTY_SLOT: Slot = Slot::new();
203static SLOTS: [Slot; DEPTH] = [EMPTY_SLOT; DEPTH];
204
205/// Next raise-order number.
206static NEXT_SEQ: AtomicUsize = AtomicUsize::new(0);
207/// READY slots. `SeqCst` on both sides: it is half of the hand-off in the
208/// module docs, paired with the dispatch flag.
209static PENDING: AtomicUsize = AtomicUsize::new(0);
210/// Records that found every slot taken. Never reset.
211static LOST: AtomicUsize = AtomicUsize::new(0);
212
213/// How many records did not fit and were lost, since the program started.
214#[must_use]
215pub fn overflowed() -> usize {
216    LOST.load(Ordering::Relaxed)
217}
218
219/// Raise a record with `emit` until `delivered()` sees it, re-raising it
220/// whenever [`overflowed`] counts a loss, for as long as `keep_waiting()`
221/// says to. Returns whether `delivered()` saw it.
222///
223/// For a caller that must OBSERVE a record it raised — a test asserting on
224/// what reached its sink. A record raised while another thread is delivering
225/// is held, and one that does not fit is dropped and counted, so in a
226/// multi-threaded test binary a record can be lost outright and no amount of
227/// waiting or [`crate::flush`] delivers it. Measured on `nros-node`'s lib
228/// tests: 8 copies at `--test-threads=64` failed 1 run in 48, with 16 records
229/// counted lost, the asserted ones among them.
230///
231/// A counted loss may have been a sibling's record while the caller's was
232/// still held, so a re-raise can deliver the record TWICE: assert on every
233/// copy, never on a count. `emit` must therefore be safe to repeat — a
234/// one-shot report (a latch it trips) has to reset its latch inside `emit`.
235///
236/// `keep_waiting` is the caller's budget and back-off, since this crate has
237/// no clock: a hosted test passes a deadline that yields,
238/// `|| { std::thread::yield_now(); Instant::now() < deadline }`.
239pub fn emit_until_delivered(
240    emit: impl Fn(),
241    delivered: impl Fn() -> bool,
242    mut keep_waiting: impl FnMut() -> bool,
243) -> bool {
244    loop {
245        let lost = overflowed();
246        emit();
247        loop {
248            crate::flush();
249            if delivered() {
250                return true;
251            }
252            if overflowed() != lost {
253                break;
254            }
255            if !keep_waiting() {
256                return delivered();
257            }
258        }
259        if !keep_waiting() {
260            return delivered();
261        }
262    }
263}
264
265/// Hold `record` until a dispatcher delivers it.
266///
267/// Returns `false` when it did not fit — the caller has nothing further to do,
268/// but [`overflowed`] counts it and the next delivery reports it.
269pub(crate) fn hold(record: &Record<'_>, owed: Owed) -> bool {
270    for slot in &SLOTS {
271        if slot
272            .state
273            .compare_exchange(EMPTY, WRITING, Ordering::Acquire, Ordering::Relaxed)
274            .is_err()
275        {
276            continue;
277        }
278        slot.seq
279            .store(NEXT_SEQ.fetch_add(1, Ordering::Relaxed), Ordering::Relaxed);
280        // SAFETY: the CAS above made this thread the slot's only owner until
281        // the `Release` store of READY below.
282        let pending = unsafe { &mut *slot.cell.get() };
283        pending.owed = owed;
284        pending.severity = record.severity;
285        // Truncating rather than refusing: a clipped record is worth more than
286        // none, and the alternative is deciding that a long logger name loses
287        // the whole line.
288        pending.logger_name.clear();
289        let _ = pending
290            .logger_name
291            .push_str(clip(record.logger_name, NAME_CAP));
292        pending.message.clear();
293        let _ = pending.message.push_str(clip(record.message, MSG_CAP));
294        pending.file = record.file;
295        pending.line = record.line;
296        pending.timestamp_ns = record.timestamp_ns;
297        slot.state.store(READY, Ordering::Release);
298        PENDING.fetch_add(1, Ordering::SeqCst);
299        return true;
300    }
301    LOST.fetch_add(1, Ordering::Relaxed);
302    false
303}
304
305/// Whether any record is waiting.
306pub(crate) fn pending() -> bool {
307    PENDING.load(Ordering::SeqCst) > 0
308}
309
310/// Longest prefix of `s` that fits `cap` bytes without splitting a character.
311fn clip(s: &str, cap: usize) -> &str {
312    if s.len() <= cap {
313        return s;
314    }
315    let mut end = cap;
316    while end > 0 && !s.is_char_boundary(end) {
317        end -= 1;
318    }
319    &s[..end]
320}
321
322/// One pass: deliver every record held when the pass began, oldest first.
323///
324/// A record held DURING the pass waits for the next one — that is what bounds
325/// a sink that logs (module docs). Safe to run concurrently with `hold` and
326/// with another pass: a slot is claimed READY -> READING by one reader only.
327pub(crate) fn drain_with(deliver: &mut dyn FnMut(&Record<'_>, Owed)) {
328    let bound = NEXT_SEQ.load(Ordering::Acquire);
329    loop {
330        // Oldest READY slot raised before the pass began. DEPTH is a handful,
331        // so a scan per record is cheaper than any ordered structure.
332        let mut oldest: Option<(&Slot, usize)> = None;
333        for slot in &SLOTS {
334            if slot.state.load(Ordering::Acquire) != READY {
335                continue;
336            }
337            let seq = slot.seq.load(Ordering::Relaxed);
338            if seq >= bound {
339                continue;
340            }
341            if oldest.is_none_or(|(_, best)| seq < best) {
342                oldest = Some((slot, seq));
343            }
344        }
345        let Some((slot, _)) = oldest else { break };
346        if slot
347            .state
348            .compare_exchange(READY, READING, Ordering::Acquire, Ordering::Relaxed)
349            .is_err()
350        {
351            // Another pass took it first.
352            continue;
353        }
354        // SAFETY: the CAS above made this the slot's only reader, and its
355        // `Acquire` pairs with the writer's `Release` store of READY.
356        let pending = unsafe { &*slot.cell.get() };
357        let record = Record {
358            severity: pending.severity,
359            logger_name: pending.logger_name.as_str(),
360            message: pending.message.as_str(),
361            file: pending.file,
362            line: pending.line,
363            timestamp_ns: pending.timestamp_ns,
364        };
365        deliver(&record, pending.owed);
366        slot.state.store(EMPTY, Ordering::Release);
367        PENDING.fetch_sub(1, Ordering::SeqCst);
368    }
369}