1
//! Framework diagnostics: warnings the engine emits about the app's own DOM,
2
//! recorded in-process so a test can assert on them.
3
//!
4
//! Lints like `image-churn` and `text-without-block` exist to tell a developer
5
//! that something they built will misbehave. Printing to stderr makes them
6
//! visible to a human and invisible to everything else: an e2e scenario cannot
7
//! assert that a warning fired, and — more useful — cannot assert that one did
8
//! NOT fire after a fix.
9
//!
10
//! So every diagnostic goes to BOTH places: a bounded in-process ring, where
11
//! `assert_stderr` in the e2e harness can read it, and an installable SINK.
12
//!
13
//! The sink exists because `eprintln!` is not something an application can
14
//! control. A shipped app wants these on its own logger — with levels, with a
15
//! category, and in production or QA forwarded to a remote store (Loki,
16
//! Prometheus) rather than dumped on a stderr nobody reads. [`set_sink`]
17
//! replaces the default, so the engine keeps ONE place that decides where a
18
//! diagnostic goes and every lint keeps using [`emit`].
19
//!
20
//! The ring is capped. A lint that fires every frame must not turn into an
21
//! unbounded allocation in a long-running app — the point is to catch churn,
22
//! not to become it.
23

            
24
#[cfg(feature = "std")]
25
use std::{
26
    collections::VecDeque,
27
    sync::{Mutex, OnceLock},
28
};
29

            
30
/// Most diagnostics retained. Older ones are dropped.
31
#[cfg(feature = "std")]
32
const CAPACITY: usize = 256;
33

            
34
#[cfg(feature = "std")]
35
16075
fn ring() -> &'static Mutex<VecDeque<String>> {
36
    static RING: OnceLock<Mutex<VecDeque<String>>> = OnceLock::new();
37
16075
    RING.get_or_init(|| Mutex::new(VecDeque::with_capacity(CAPACITY)))
38
16075
}
39

            
40
/// Where diagnostics go, besides the ring.
41
///
42
/// Default writes to stderr so a developer running the app sees warnings with
43
/// no setup. An application replaces it with [`set_sink`] to route through its
44
/// own logger — and from there to a remote store.
45
#[cfg(feature = "std")]
46
pub type DiagnosticSink = fn(&str);
47

            
48
/// Write one diagnostic line, tolerating a destination that has gone away.
49
///
50
/// `eprintln!` PANICS when the write fails, and a closed stderr is not exotic:
51
/// piping a running app into `head` closes the pipe as soon as `head` has its
52
/// lines, and the very next diagnostic kills the app. Observed exactly that
53
/// way on 2026-09-04 while capturing a log:
54
///
55
/// ```text
56
/// failed printing to stderr: Broken pipe (os error 32)
57
///   std::io::stdio::_eprint
58
///   azul_core::diagnostics::default_sink        @ diagnostics.rs:50
59
///   azul_core::diagnostics::emit                @ diagnostics.rs:116
60
///   azul_layout::widgets::warn_widget_needs_a_name
61
///   ...
62
///   azul::desktop::app::App::run
63
/// ```
64
///
65
/// A framework warning about a missing accessible name took the whole window
66
/// down. The ring below already refuses to do that ("a poisoned diagnostics
67
/// ring must never take the app down"); the printing half never got the same
68
/// rule. Diagnostics are advisory by definition - failing to deliver one is
69
/// never worth the process.
70
#[cfg(feature = "std")]
71
15569
fn write_diagnostic(mut out: impl std::io::Write, message: &str) {
72
    use std::io::Write as _;
73
    // `drop`, not `let _ =`: this crate denies `let_underscore_drop`, and
74
    // `io::Result` owns a boxed error. Discarding it is the POINT here - see
75
    // above - so say so explicitly.
76
15569
    drop(writeln!(out, "{message}"));
77
15569
}
78

            
79
#[cfg(feature = "std")]
80
15568
fn default_sink(message: &str) {
81
15568
    write_diagnostic(std::io::stderr().lock(), message);
82
15568
}
83

            
84
#[cfg(feature = "std")]
85
15568
fn sink() -> &'static Mutex<DiagnosticSink> {
86
    static SINK: OnceLock<Mutex<DiagnosticSink>> = OnceLock::new();
87
15568
    SINK.get_or_init(|| Mutex::new(default_sink))
88
15568
}
89

            
90
/// Route framework diagnostics somewhere other than stderr.
91
///
92
/// Call once at startup. Passing a sink that does nothing silences them
93
/// entirely while STILL recording to the ring, so tests keep working when an
94
/// app has muted its output.
95
#[cfg(feature = "std")]
96
pub fn set_sink(new_sink: DiagnosticSink) {
97
    if let Ok(mut s) = sink().lock() {
98
        *s = new_sink;
99
    }
100
}
101

            
102
/// The scenario currently running, attached to every diagnostic emitted while
103
/// it is set.
104
///
105
/// This is the label that makes a Grafana view legible. Without it the ring and
106
/// the log stream are one flat sequence and a failure cannot be attributed to
107
/// the test that provoked it; with it, filtering by `test="scroll_momentum"`
108
/// gives that scenario's whole story — the lints it tripped, in order, and the
109
/// assertion that finally failed.
110
///
111
/// Deliberately ONE string, not a stack: e2e scenarios run serially precisely
112
/// so their output can be read in order, and a nested notion of "current test"
113
/// would be a cardinality problem in the metric store for no benefit.
114
#[cfg(feature = "std")]
115
15700
fn scope() -> &'static Mutex<Option<String>> {
116
    static SCOPE: OnceLock<Mutex<Option<String>>> = OnceLock::new();
117
15700
    SCOPE.get_or_init(|| Mutex::new(None))
118
15700
}
119

            
120
/// Name the scenario now running. Pass `None` when it ends.
121
#[cfg(feature = "std")]
122
132
pub fn set_scope(name: Option<String>) {
123
132
    if let Ok(mut sc) = scope().lock() {
124
132
        *sc = name;
125
132
    }
126
132
}
127

            
128
/// The scenario now running, if any.
129
#[cfg(feature = "std")]
130
#[must_use]
131
15568
pub fn current_scope() -> Option<String> {
132
15568
    scope().lock().ok().and_then(|sc| sc.clone())
133
15568
}
134

            
135
/// Emit a framework diagnostic: send it to the sink AND record it.
136
///
137
/// Callers pass the fully-formatted message, tag included, exactly as it should
138
/// appear in a log.
139
#[cfg(feature = "std")]
140
15568
pub fn emit(message: String) {
141
    // Tag with the running scenario so a Grafana query can follow ONE test.
142
15568
    let tagged = match current_scope() {
143
154
        Some(test) => format!("[test={test}] {message}"),
144
15414
        None => message,
145
    };
146
15568
    let f = sink().lock().map(|s| *s).unwrap_or(default_sink);
147
15568
    f(&tagged);
148
15568
    record(tagged);
149
15568
}
150

            
151
/// Record without printing — for the rare diagnostic that has already been
152
/// printed by other means but should still be assertable.
153
#[cfg(feature = "std")]
154
15874
pub fn record(message: String) {
155
15874
    let Ok(mut r) = ring().lock() else {
156
        return; // a poisoned diagnostics ring must never take the app down
157
    };
158
15874
    if r.len() == CAPACITY {
159
8630
        r.pop_front();
160
8996
    }
161
15874
    r.push_back(message);
162
15874
}
163

            
164
/// Every diagnostic recorded so far, oldest first.
165
#[cfg(feature = "std")]
166
#[must_use]
167
1
pub fn recorded() -> Vec<String> {
168
1
    ring()
169
1
        .lock()
170
1
        .map(|r| r.iter().cloned().collect())
171
1
        .unwrap_or_default()
172
1
}
173

            
174
/// Does any recorded diagnostic contain `needle`?
175
#[cfg(feature = "std")]
176
#[must_use]
177
76
pub fn any_contains(needle: &str) -> bool {
178
76
    ring()
179
76
        .lock()
180
330
        .map(|r| r.iter().any(|m| m.contains(needle)))
181
76
        .unwrap_or(false)
182
76
}
183

            
184
/// One lock for the one shared ring, for tests ANYWHERE in the workspace.
185
///
186
/// The ring is global, so tests that touch it must not run concurrently. Two
187
/// modules each having their own private lock does NOT achieve that — it was
188
/// tried, and `dom_lint`'s tests and the e2e `assert_stderr` tests promptly
189
/// raced, passing alone and failing together. A shared resource needs a shared
190
/// lock, and the honest place for it is beside the resource.
191
#[cfg(feature = "std")]
192
#[must_use]
193
62
pub fn test_lock() -> &'static Mutex<()> {
194
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
195
62
    LOCK.get_or_init(|| Mutex::new(()))
196
62
}
197

            
198
/// Drop everything recorded so far.
199
///
200
/// An e2e scenario clears before the step it means to observe, so a warning
201
/// emitted during startup cannot satisfy — or spoil — a later assertion.
202
#[cfg(feature = "std")]
203
124
pub fn clear() {
204
124
    if let Ok(mut r) = ring().lock() {
205
124
        r.clear();
206
124
    }
207
124
}
208

            
209
#[cfg(not(feature = "std"))]
210
pub fn emit(_message: alloc::string::String) {}
211
#[cfg(not(feature = "std"))]
212
pub fn record(_message: alloc::string::String) {}
213
#[cfg(not(feature = "std"))]
214
#[must_use]
215
pub fn recorded() -> alloc::vec::Vec<alloc::string::String> {
216
    alloc::vec::Vec::new()
217
}
218
#[cfg(not(feature = "std"))]
219
#[must_use]
220
pub fn any_contains(_needle: &str) -> bool {
221
    false
222
}
223
#[cfg(not(feature = "std"))]
224
pub fn clear() {}
225

            
226
#[cfg(test)]
227
#[path = "diagnostics_test.rs"]
228
mod diagnostics_test;