Skip to main content

yse_model/
diagnostics.rs

1//! Structured logging and reactive-graph diagnostics.
2//!
3//! Diagnostics answer "why did this change?": every transaction reports which
4//! nodes were processed, which observers fired, whether writes were deferred,
5//! and whether a cycle was rejected. Events are buffered during propagation
6//! (so they never re-enter the graph mid-transaction) and flushed as a stream
7//! when the transaction completes.
8
9use crate::{EventStream, Sink};
10use std::cell::{Cell, RefCell};
11use std::rc::Rc;
12
13/// A transactional graph event.
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub enum DiagnosticEvent {
16    /// A transaction began.
17    TransactionStarted {
18        /// Monotonically increasing transaction identifier.
19        id: u64,
20    },
21    /// A node was recomputed / processed.
22    NodeProcessed {
23        /// Identifier of the processed graph node.
24        node: u64,
25        /// Topological rank used to schedule the node.
26        rank: usize,
27        /// Whether the node represents state rather than events.
28        signal: bool,
29    },
30    /// An observer callback was delivered a value.
31    ObserverFired {
32        /// Identifier of the observer that received a value.
33        observer: u64,
34    },
35    /// A write performed during propagation was queued for the next pass.
36    DeferredWriteQueued {
37        /// Transaction during which the write was queued.
38        transaction: u64,
39    },
40    /// A reactive cycle was detected and rejected.
41    CycleRejected,
42    /// A transaction finished, with summary counts.
43    TransactionEnded {
44        /// Identifier matching the corresponding start event.
45        id: u64,
46        /// Number of graph nodes processed.
47        processed: usize,
48        /// Number of observer callbacks delivered.
49        fired: usize,
50        /// Number of re-entrant writes deferred.
51        deferred: usize,
52    },
53}
54
55thread_local! {
56    static DIAGNOSTICS: RefCell<Option<Rc<Diagnostics>>> = const { RefCell::new(None) };
57    static FLUSHING: Cell<bool> = const { Cell::new(false) };
58}
59
60/// Installed diagnostics for the current thread.
61pub struct Diagnostics {
62    buffer: RefCell<Vec<DiagnosticEvent>>,
63    sink: Sink<DiagnosticEvent>,
64}
65
66impl Diagnostics {
67    /// Install diagnostics for the current thread. Panics if already
68    /// installed.
69    pub fn install() -> Rc<Self> {
70        assert!(
71            DIAGNOSTICS.with(|d| d.borrow().is_none()),
72            "diagnostics already installed on this thread"
73        );
74        let diagnostics = Rc::new(Self {
75            buffer: RefCell::new(Vec::new()),
76            sink: Sink::new(),
77        });
78        DIAGNOSTICS.with(|d| *d.borrow_mut() = Some(diagnostics.clone()));
79        diagnostics
80    }
81
82    /// Remove this installation from the thread, if it is the current one.
83    pub fn uninstall(&self) {
84        let is_current = DIAGNOSTICS.with(|d| {
85            d.borrow()
86                .as_ref()
87                .is_some_and(|current| std::ptr::eq(Rc::as_ptr(current), self))
88        });
89        if is_current {
90            DIAGNOSTICS.with(|d| *d.borrow_mut() = None);
91        }
92    }
93
94    /// A stream of diagnostic events, flushed after each transaction.
95    pub fn events(&self) -> EventStream<DiagnosticEvent> {
96        self.sink.stream()
97    }
98
99    /// Deliver any buffered events now (also done automatically at the end of
100    /// every transaction).
101    pub fn flush(&self) {
102        if FLUSHING.get() {
103            return;
104        }
105        FLUSHING.set(true);
106        let events: Vec<DiagnosticEvent> = std::mem::take(&mut *self.buffer.borrow_mut());
107        for event in events {
108            self.sink.send(event);
109        }
110        FLUSHING.set(false);
111    }
112
113    pub(crate) fn emit(event: DiagnosticEvent) {
114        if FLUSHING.get() {
115            return;
116        }
117        DIAGNOSTICS.with(|d| {
118            if let Some(diagnostics) = d.borrow().as_ref() {
119                diagnostics.buffer.borrow_mut().push(event);
120            }
121        });
122    }
123
124    pub(crate) fn flush_global() {
125        DIAGNOSTICS.with(|d| {
126            if let Some(diagnostics) = d.borrow().as_ref() {
127                diagnostics.flush();
128            }
129        });
130    }
131}
132
133/// Severity of a log record.
134#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
135pub enum LogLevel {
136    /// An operation failed and needs attention.
137    Error,
138    /// A potentially harmful condition occurred.
139    Warn,
140    /// A normal operational message.
141    Info,
142    /// Detailed diagnostic information.
143    Debug,
144}
145
146/// A structured log record.
147#[derive(Clone, Debug, PartialEq, Eq)]
148pub struct LogRecord {
149    /// Severity assigned to the record.
150    pub level: LogLevel,
151    /// Human-readable log message.
152    pub message: String,
153}
154
155thread_local! {
156    static LOGGER: RefCell<Option<Rc<Logger>>> = const { RefCell::new(None) };
157}
158
159/// A leveled logger whose records are observable as a stream.
160pub struct Logger {
161    min_level: Cell<LogLevel>,
162    sink: Sink<LogRecord>,
163}
164
165impl Logger {
166    /// Install a logger for the current thread. Panics if already installed.
167    pub fn install(min_level: LogLevel) -> Rc<Self> {
168        assert!(
169            LOGGER.with(|l| l.borrow().is_none()),
170            "logger already installed on this thread"
171        );
172        let logger = Rc::new(Self {
173            min_level: Cell::new(min_level),
174            sink: Sink::new(),
175        });
176        LOGGER.with(|l| *l.borrow_mut() = Some(logger.clone()));
177        logger
178    }
179
180    /// Remove this installation from the thread, if it is the current one.
181    pub fn uninstall(&self) {
182        let is_current = LOGGER.with(|l| {
183            l.borrow()
184                .as_ref()
185                .is_some_and(|current| std::ptr::eq(Rc::as_ptr(current), self))
186        });
187        if is_current {
188            LOGGER.with(|l| *l.borrow_mut() = None);
189        }
190    }
191
192    /// A stream of log records at or above the current minimum level.
193    pub fn records(&self) -> EventStream<LogRecord> {
194        self.sink.stream()
195    }
196
197    /// Set the minimum level that is emitted.
198    pub fn set_min_level(&self, level: LogLevel) {
199        self.min_level.set(level);
200    }
201
202    /// Log `message` at `level` if it meets the minimum level.
203    pub fn log(&self, level: LogLevel, message: impl Into<String>) {
204        if level <= self.min_level.get() {
205            self.sink.send(LogRecord {
206                level,
207                message: message.into(),
208            });
209        }
210    }
211
212    /// Emit a debug record.
213    pub fn debug(&self, message: impl Into<String>) {
214        self.log(LogLevel::Debug, message);
215    }
216
217    /// Emit an informational record.
218    pub fn info(&self, message: impl Into<String>) {
219        self.log(LogLevel::Info, message);
220    }
221
222    /// Emit a warning record.
223    pub fn warn(&self, message: impl Into<String>) {
224        self.log(LogLevel::Warn, message);
225    }
226
227    /// Emit an error record.
228    pub fn error(&self, message: impl Into<String>) {
229        self.log(LogLevel::Error, message);
230    }
231}
232
233/// Log through the thread's installed logger; no-op when none is installed.
234pub fn log(level: LogLevel, message: impl Into<String>) {
235    LOGGER.with(|l| {
236        if let Some(logger) = l.borrow().as_ref() {
237            logger.log(level, message);
238        }
239    });
240}
241
242/// Emit a debug record through the thread's installed logger.
243pub fn log_debug(message: impl Into<String>) {
244    log(LogLevel::Debug, message);
245}
246
247/// Emit an informational record through the thread's installed logger.
248pub fn log_info(message: impl Into<String>) {
249    log(LogLevel::Info, message);
250}
251
252/// Emit a warning record through the thread's installed logger.
253pub fn log_warn(message: impl Into<String>) {
254    log(LogLevel::Warn, message);
255}
256
257/// Emit an error record through the thread's installed logger.
258pub fn log_error(message: impl Into<String>) {
259    log(LogLevel::Error, message);
260}