Skip to main content

troupekit_trace/
span.rs

1use crate::category::Trace;
2use crate::record;
3use crate::redact::FIELDS_MAX;
4use crate::tracer::{current, Ctx};
5use crate::value::Value;
6use std::future::{poll_fn, Future};
7use std::pin::pin;
8use std::sync::atomic::Ordering;
9use std::time::Instant;
10
11/// A span guard: writes a `start` record when opened and an `end` record
12/// when dropped. A span opened outside any scope, or for a category that
13/// is off, is disabled and every method on it does nothing.
14#[must_use = "a span ends when it is dropped"]
15pub struct Span {
16    open: Option<Open>,
17}
18
19pub(crate) struct Open {
20    pub(crate) ctx: Ctx,
21    pub(crate) parent: u64,
22    pub(crate) started: Instant,
23    pub(crate) fields: Vec<(String, Value)>,
24    pub(crate) err: Option<String>,
25}
26
27impl Span {
28    /// Opens a span of category `cat` under the current span.
29    /// Called by `trace_span!` after `enabled`; not meant to be called directly.
30    #[doc(hidden)]
31    pub fn open(cat: Trace, name: &'static str, fields: Vec<(&'static str, Value)>) -> Span {
32        let Some(scope) = current() else {
33            return Span::none();
34        };
35        let id = scope.alloc_span();
36        let line = record::start(&scope, id, cat, name, fields);
37        scope.emit(&line);
38        let ctx = scope.child(id);
39        assert_eq!(ctx.span_id(), id);
40        let open = Open {
41            ctx,
42            parent: scope.span_id(),
43            started: Instant::now(),
44            fields: Vec::new(),
45            err: None,
46        };
47        Span { open: Some(open) }
48    }
49
50    /// Returns a disabled span. Input: none. Output: a span that records nothing.
51    pub fn none() -> Span {
52        Span { open: None }
53    }
54
55    /// Returns whether this span records. Input: none. Output: the flag.
56    pub fn is_enabled(&self) -> bool {
57        self.open.is_some()
58    }
59
60    /// Returns the span id, or 0 when disabled. Input: none. Output: the id.
61    pub fn id(&self) -> u64 {
62        self.open.as_ref().map_or(0, |open| open.ctx.span_id())
63    }
64
65    /// Adds a field written in the `end` record.
66    /// Input: the key and value. Output: none.
67    pub fn record(&mut self, key: &str, value: impl Into<Value>) {
68        let Some(open) = self.open.as_mut() else {
69            return;
70        };
71        if open.fields.len() == FIELDS_MAX {
72            open.ctx
73                .inner
74                .shared
75                .dropped
76                .fetch_add(1, Ordering::Relaxed);
77            return;
78        }
79        open.fields.push((key.to_owned(), value.into()));
80        assert!(open.fields.len() <= FIELDS_MAX);
81    }
82
83    /// Marks the span failed with `msg`; the `end` record has `ok: false`.
84    /// Input: the error text. Output: none.
85    pub fn fail(&mut self, msg: impl Into<String>) {
86        if let Some(open) = self.open.as_mut() {
87            open.err = Some(msg.into());
88        }
89    }
90
91    /// Runs `f` with this span as the current parent on this thread.
92    /// Input: the closure. Output: its result.
93    pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
94        match &self.open {
95            Some(open) => open.ctx.enter(f),
96            None => f(),
97        }
98    }
99
100    /// Wraps `fut` so this span is the current parent on every poll.
101    /// A disabled span leaves the caller's scope as it is. Nothing is
102    /// boxed: the future is pinned inside the returned future.
103    pub fn instrument<F: Future>(&self, fut: F) -> impl Future<Output = F::Output> {
104        let ctx = self.open.as_ref().map(|open| open.ctx.clone());
105        async move {
106            let mut fut = pin!(fut);
107            poll_fn(|cx| match &ctx {
108                Some(ctx) => ctx.enter(|| fut.as_mut().poll(cx)),
109                None => fut.as_mut().poll(cx),
110            })
111            .await
112        }
113    }
114}
115
116impl Drop for Span {
117    fn drop(&mut self) {
118        let Some(open) = self.open.take() else { return };
119        let line = record::end(&open);
120        open.ctx.emit(&line);
121        if open.parent == 0 {
122            open.ctx.flush();
123        }
124    }
125}