Skip to main content

bitwarden_logging/
global.rs

1//! Global Flight Recorder buffer and convenience accessors.
2
3use std::sync::{Arc, OnceLock};
4
5use crate::{
6    CircularBuffer, FlightRecorderConfig, FlightRecorderEvent, FlightRecorderLayer,
7    FlightRecorderSink, sink::SinkSlot, suppress::is_suppressed,
8};
9
10/// Global Flight Recorder buffer, initialized during `init_sdk()`.
11static FLIGHT_RECORDER_BUFFER: OnceLock<Arc<CircularBuffer<FlightRecorderEvent>>> = OnceLock::new();
12
13/// Active sink of the global Flight Recorder, shared with its layer.
14static FLIGHT_RECORDER_SINK: OnceLock<SinkSlot> = OnceLock::new();
15
16/// Configured level floor for the global Flight Recorder, initialized during
17/// `init_sdk()`. Mirrors [`FlightRecorderLayer`]'s level so that direct writes
18/// via [`write_flight_recorder`] honor the same filter as the tracing layer.
19static FLIGHT_RECORDER_LEVEL: OnceLock<tracing::Level> = OnceLock::new();
20
21/// Initialize the global Flight Recorder.
22///
23/// Creates a [`FlightRecorderLayer`] and stores the buffer in a global
24/// [`OnceLock`] so it can be read from anywhere via [`read_flight_recorder`].
25/// Returns the layer to add to a tracing subscriber.
26///
27/// If called more than once, the second call's buffer is **not** stored
28/// globally (the `OnceLock` is already set), but the returned layer is
29/// still independently functional.
30#[must_use]
31pub fn init_flight_recorder(config: FlightRecorderConfig) -> FlightRecorderLayer {
32    let _ = FLIGHT_RECORDER_LEVEL.set(config.level);
33    let layer = FlightRecorderLayer::new(config);
34    let _ = FLIGHT_RECORDER_BUFFER.set(layer.buffer());
35    let _ = FLIGHT_RECORDER_SINK.set(layer.sink());
36    layer
37}
38
39/// Replace the global Flight Recorder's active sink. Events already in the local buffer stay
40/// there. No-op if [`init_flight_recorder`] has not been called.
41pub fn set_flight_recorder_sink(sink: Arc<dyn FlightRecorderSink>) {
42    if let Some(slot) = FLIGHT_RECORDER_SINK.get() {
43        slot.set(sink);
44    }
45}
46
47/// Write a single externally-sourced event (e.g. from TypeScript) into the global
48/// Flight Recorder's active sink, honoring the configured level floor.
49///
50/// This mirrors [`FlightRecorderLayer`]'s filter so that events routed around
51/// the tracing pipeline are subject to the same level check. Events more verbose
52/// than the configured floor are dropped. No-op if [`init_flight_recorder`] has
53/// not been called.
54pub fn write_flight_recorder(event: FlightRecorderEvent, level: tracing::Level) {
55    // Mirrors the layer's check: skip events more verbose than the configured level.
56    if let Some(floor) = FLIGHT_RECORDER_LEVEL.get()
57        && level > *floor
58    {
59        return;
60    }
61    if is_suppressed() {
62        return;
63    }
64    if let Some(slot) = FLIGHT_RECORDER_SINK.get() {
65        slot.push(event);
66    }
67}
68
69/// Get the global Flight Recorder buffer.
70///
71/// Returns `None` if [`init_flight_recorder`] has not been called.
72pub fn get_flight_recorder_buffer() -> Option<Arc<CircularBuffer<FlightRecorderEvent>>> {
73    FLIGHT_RECORDER_BUFFER.get().cloned()
74}
75
76/// Read all events from the global Flight Recorder buffer.
77///
78/// Returns an empty `Vec` if [`init_flight_recorder`] has not been called.
79#[must_use]
80pub fn read_flight_recorder() -> Vec<FlightRecorderEvent> {
81    get_flight_recorder_buffer()
82        .map(|buffer| buffer.read())
83        .unwrap_or_default()
84}
85
86/// Get the current event count without reading event contents.
87///
88/// Returns `0` if [`init_flight_recorder`] has not been called.
89#[must_use]
90pub fn flight_recorder_count() -> usize {
91    get_flight_recorder_buffer()
92        .map(|buffer| buffer.len())
93        .unwrap_or(0)
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn test_config_default_values() {
102        let config = FlightRecorderConfig::default();
103        assert_eq!(config.buffer_size.get(), 1000);
104        assert_eq!(config.level, tracing::Level::DEBUG);
105    }
106
107    #[test]
108    fn test_read_before_init_returns_empty() {
109        // A fresh OnceLock (not the global one, which may already be set
110        // by other tests) would return None. We can at least verify the
111        // convenience functions don't panic.
112        let events = read_flight_recorder();
113        // Either empty (not initialized) or non-empty (another test initialized it)
114        let _ = events;
115    }
116
117    fn event(marker: &str, level: &str) -> FlightRecorderEvent {
118        FlightRecorderEvent {
119            timestamp: 0,
120            level: level.to_string(),
121            target: "test::module".to_string(),
122            message: marker.to_string(),
123            fields: std::collections::HashMap::new(),
124            process: None,
125        }
126    }
127
128    #[test]
129    fn test_write_flight_recorder_respects_level_floor() {
130        // This is the only test in the crate that initializes the global
131        // recorder, so it controls the shared level/buffer for this binary.
132        let config = FlightRecorderConfig::new(
133            std::num::NonZeroUsize::new(100).expect("non-zero"),
134            tracing::Level::INFO,
135        );
136        let _ = init_flight_recorder(config);
137
138        // Below the floor (more verbose than INFO) is dropped.
139        write_flight_recorder(event("fr-drop-debug", "DEBUG"), tracing::Level::DEBUG);
140        // At or above the floor is captured.
141        write_flight_recorder(event("fr-keep-info", "INFO"), tracing::Level::INFO);
142        write_flight_recorder(event("fr-keep-error", "ERROR"), tracing::Level::ERROR);
143
144        let messages: Vec<String> = read_flight_recorder()
145            .into_iter()
146            .map(|e| e.message)
147            .collect();
148        assert!(messages.contains(&"fr-keep-info".to_string()));
149        assert!(messages.contains(&"fr-keep-error".to_string()));
150        assert!(!messages.contains(&"fr-drop-debug".to_string()));
151    }
152}