Skip to main content

bitwarden_logging/
suppress.rs

1//! Suppression of Flight Recorder capture while a future is polled.
2
3use std::{
4    cell::Cell,
5    future::Future,
6    pin::Pin,
7    task::{Context, Poll},
8};
9
10thread_local! {
11    static SUPPRESSED: Cell<bool> = const { Cell::new(false) };
12}
13
14/// Whether capture is suppressed on the current thread.
15pub(crate) fn is_suppressed() -> bool {
16    SUPPRESSED.with(Cell::get)
17}
18
19/// Runs `future` without recording any events it emits while being polled, from any crate or
20/// target. Work the future hands to other spawned tasks is not covered.
21///
22/// Used by code that sends Flight Recorder events, so that events produced by the sending itself
23/// are not captured and sent again.
24pub fn without_flight_recorder<F: Future>(future: F) -> impl Future<Output = F::Output> {
25    Suppressed {
26        inner: Box::pin(future),
27    }
28}
29
30struct Suppressed<F> {
31    inner: Pin<Box<F>>,
32}
33
34impl<F: Future> Future for Suppressed<F> {
35    type Output = F::Output;
36
37    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
38        let previous = SUPPRESSED.with(|s| s.replace(true));
39        let result = self.inner.as_mut().poll(cx);
40        SUPPRESSED.with(|s| s.set(previous));
41        result
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[tokio::test]
50    async fn test_suppressed_only_while_polled() {
51        assert!(!is_suppressed());
52        let inside = without_flight_recorder(async { is_suppressed() }).await;
53        assert!(inside);
54        assert!(!is_suppressed());
55    }
56}