Skip to main content

bitwarden_logging/
sink.rs

1//! Destinations for captured Flight Recorder events.
2
3use std::sync::{Arc, RwLock};
4
5use crate::{CircularBuffer, FlightRecorderEvent};
6
7/// Destination for events captured by the Flight Recorder.
8///
9/// Both the tracing layer and externally written events (e.g. from TypeScript) push through the
10/// active sink, so a sink sees every captured event regardless of where it came from.
11pub trait FlightRecorderSink: Send + Sync {
12    /// Accept one captured event.
13    fn push(&self, event: FlightRecorderEvent);
14}
15
16/// Sink that stores events in an in-memory [`CircularBuffer`].
17pub struct LocalBufferSink {
18    buffer: Arc<CircularBuffer<FlightRecorderEvent>>,
19}
20
21impl LocalBufferSink {
22    /// Create a sink that pushes into `buffer`.
23    pub fn new(buffer: Arc<CircularBuffer<FlightRecorderEvent>>) -> Self {
24        Self { buffer }
25    }
26}
27
28impl FlightRecorderSink for LocalBufferSink {
29    fn push(&self, event: FlightRecorderEvent) {
30        self.buffer.push(event);
31    }
32}
33
34/// Swappable slot holding the active sink, shared by the layer and the global write path.
35#[derive(Clone)]
36pub(crate) struct SinkSlot(Arc<RwLock<Arc<dyn FlightRecorderSink>>>);
37
38impl SinkSlot {
39    pub(crate) fn new(sink: Arc<dyn FlightRecorderSink>) -> Self {
40        Self(Arc::new(RwLock::new(sink)))
41    }
42
43    pub(crate) fn push(&self, event: FlightRecorderEvent) {
44        self.0
45            .read()
46            .expect("FlightRecorder sink lock poisoned")
47            .push(event);
48    }
49
50    pub(crate) fn set(&self, sink: Arc<dyn FlightRecorderSink>) {
51        *self.0.write().expect("FlightRecorder sink lock poisoned") = sink;
52    }
53}
54
55impl std::fmt::Debug for SinkSlot {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.debug_struct("SinkSlot").finish_non_exhaustive()
58    }
59}