Skip to main content

gix_trace/forest/tree/
mod.rs

1//! Collected trace data: [`Span`] branches and [`Event`] leaves in a [`Tree`].
2//!
3//! A [`Processor`](crate::forest::Processor) receives completed trees and can inspect
4//! their fields, child nodes, and durations before storing or formatting them.
5use crate::forest::{Tag, Tree};
6use std::{fmt, time::Duration};
7use tracing::Level;
8
9mod field;
10
11pub use field::Field;
12pub(crate) use field::FieldSet;
13
14/// A leaf node in the log tree carrying information about a Tracing event.
15#[derive(Clone, Debug)]
16pub struct Event {
17    /// Shared fields between events and spans.
18    pub(crate) shared: Shared,
19
20    /// The message associated with the event.
21    pub(crate) message: Option<String>,
22
23    /// The tag that the event was collected with.
24    pub(crate) tag: Option<Tag>,
25}
26
27/// An internal node in the log tree carrying information about a Tracing span.
28#[derive(Clone, Debug)]
29pub struct Span {
30    /// Shared fields between events and spans.
31    pub(crate) shared: Shared,
32
33    /// The name of the span.
34    pub(crate) name: &'static str,
35
36    /// The duration with at least one active entry, raised to at least `inner_duration`.
37    pub(crate) total_duration: Duration,
38
39    /// The sum of child spans' total durations, including overlaps between children.
40    pub(crate) inner_duration: Duration,
41
42    #[cfg(feature = "forest-cpu-time")]
43    pub(crate) base_cpu_time: Option<CpuTime>,
44
45    #[cfg(feature = "forest-cpu-time")]
46    pub(crate) inner_cpu_time: Option<CpuTime>,
47
48    /// Events and spans collected while the span was open.
49    pub(crate) nodes: Vec<Tree>,
50}
51
52/// CPU time consumed in user mode and kernel mode, excluding time blocked on I/O or sleeping.
53///
54/// Available with `forest-cpu-time`. Concurrent threads contribute separately, so
55/// their accumulated CPU time can exceed elapsed wall-clock time. Counter resolution
56/// depends on the operating system; short operations may measure as zero.
57#[cfg(feature = "forest-cpu-time")]
58#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
59pub struct CpuTime {
60    /// CPU time executing user-space code.
61    pub user: Duration,
62    /// CPU time executing kernel code on behalf of the measured threads.
63    pub system: Duration,
64}
65
66#[cfg(feature = "forest-cpu-time")]
67impl CpuTime {
68    pub(crate) fn checked_add(self, other: Self) -> Option<Self> {
69        Some(Self {
70            user: self.user.checked_add(other.user)?,
71            system: self.system.checked_add(other.system)?,
72        })
73    }
74
75    pub(crate) fn checked_sub(self, earlier: Self) -> Option<Self> {
76        Some(Self {
77            user: self.user.checked_sub(earlier.user)?,
78            system: self.system.checked_sub(earlier.system)?,
79        })
80    }
81}
82
83#[derive(Clone, Debug)]
84pub(crate) struct Shared {
85    /// The level the event or span occurred at.
86    pub(crate) level: Level,
87
88    /// Key-value data.
89    pub(crate) fields: FieldSet,
90}
91
92/// Error returned by [`Tree::event`][event].
93///
94/// [event]: crate::forest::Tree::event
95#[derive(Debug)]
96pub struct ExpectedEventError(());
97
98impl fmt::Display for ExpectedEventError {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.write_str("Expected an event, found a span")
101    }
102}
103
104impl std::error::Error for ExpectedEventError {}
105
106/// Error returned by [`Tree::span`][span].
107///
108/// [span]: crate::forest::Tree::span
109#[derive(Debug)]
110pub struct ExpectedSpanError(());
111
112impl fmt::Display for ExpectedSpanError {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.write_str("Expected a span, found an event")
115    }
116}
117
118impl std::error::Error for ExpectedSpanError {}
119
120impl Tree {
121    /// Returns a reference to the inner [`Event`] if the tree is an event.
122    ///
123    /// # Errors
124    ///
125    /// This function returns an error if the `Tree` contains the `Span` variant.
126    ///
127    /// # Examples
128    ///
129    /// Collect a completed tree with a channel and inspect its event:
130    /// ```
131    /// use gix_trace::{ForestLayer, forest::{processor, tree::Event}};
132    /// use tracing_subscriber::layer::SubscriberExt;
133    ///
134    /// let (sender, receiver) = std::sync::mpsc::channel();
135    /// let processor = processor::from_fn(move |tree| {
136    ///     sender.send(tree).expect("the receiver lives until the tree is inspected");
137    ///     Ok(())
138    /// });
139    /// let subscriber = tracing_subscriber::Registry::default().with(ForestLayer::from(processor));
140    /// tracing::subscriber::with_default(subscriber, || {
141    ///     tracing::info!("some information");
142    /// });
143    /// let tree = receiver.recv()?;
144    /// let event: &Event = tree.event()?;
145    /// assert_eq!(event.message(), Some("some information"), "the event retains its message");
146    /// # Ok::<_, Box<dyn std::error::Error>>(())
147    /// ```
148    pub fn event(&self) -> Result<&Event, ExpectedEventError> {
149        match self {
150            Tree::Event(event) => Ok(event),
151            Tree::Span(_) => Err(ExpectedEventError(())),
152        }
153    }
154
155    /// Returns a reference to the inner [`Span`] if the tree is a span.
156    ///
157    /// # Errors
158    ///
159    /// This function returns an error if the `Tree` contains the `Event` variant.
160    ///
161    /// # Examples
162    ///
163    /// Collect a completed tree with a channel and inspect its span:
164    /// ```
165    /// use gix_trace::{ForestLayer, forest::{processor, tree::Span}};
166    /// use tracing_subscriber::layer::SubscriberExt;
167    ///
168    /// let (sender, receiver) = std::sync::mpsc::channel();
169    /// let processor = processor::from_fn(move |tree| {
170    ///     sender.send(tree).expect("the receiver lives until the tree is inspected");
171    ///     Ok(())
172    /// });
173    /// let subscriber = tracing_subscriber::Registry::default().with(ForestLayer::from(processor));
174    /// tracing::subscriber::with_default(subscriber, || {
175    ///     tracing::info_span!("my_span").in_scope(|| tracing::info!("inside the span"));
176    /// });
177    /// let tree = receiver.recv()?;
178    /// let span: &Span = tree.span()?;
179    /// assert_eq!(span.name(), "my_span", "the completed span retains its name");
180    /// # Ok::<_, Box<dyn std::error::Error>>(())
181    /// ```
182    pub fn span(&self) -> Result<&Span, ExpectedSpanError> {
183        match self {
184            Tree::Event(_) => Err(ExpectedSpanError(())),
185            Tree::Span(span) => Ok(span),
186        }
187    }
188}
189
190impl Event {
191    /// Returns the event's [`Level`].
192    pub fn level(&self) -> Level {
193        self.shared.level
194    }
195
196    /// Returns the event's message, if there is one.
197    pub fn message(&self) -> Option<&str> {
198        self.message.as_deref()
199    }
200
201    /// Returns the event's [`Tag`], if there is one.
202    pub fn tag(&self) -> Option<Tag> {
203        self.tag
204    }
205
206    /// Returns the event's fields.
207    pub fn fields(&self) -> &[Field] {
208        &self.shared.fields
209    }
210}
211
212impl Span {
213    pub(crate) fn new(shared: Shared, name: &'static str) -> Self {
214        Span {
215            shared,
216            name,
217            total_duration: Duration::ZERO,
218            inner_duration: Duration::ZERO,
219            #[cfg(feature = "forest-cpu-time")]
220            base_cpu_time: crate::forest::cpu::initial_time(),
221            #[cfg(feature = "forest-cpu-time")]
222            inner_cpu_time: crate::forest::cpu::initial_time(),
223            nodes: Vec::new(),
224        }
225    }
226
227    /// Returns the span's [`Level`].
228    pub fn level(&self) -> Level {
229        self.shared.level
230    }
231
232    /// Returns the span's name.
233    pub fn name(&self) -> &str {
234        self.name
235    }
236
237    /// Returns the span's fields, including values recorded after its creation.
238    ///
239    /// Each key occurs once and retains its most recently recorded value.
240    pub fn fields(&self) -> &[Field] {
241        &self.shared.fields
242    }
243
244    /// Returns the span's child trees.
245    pub fn nodes(&self) -> &[Tree] {
246        &self.nodes
247    }
248
249    /// Returns the accumulated duration measured while the span had at least one active entry.
250    ///
251    /// Nested or concurrent entries of this same span count overlapping intervals
252    /// only once: the first entry starts timing and the last matching exit stops it.
253    ///
254    /// When the span closes, this is raised to at least the sum of its child
255    /// spans' durations. Children can run concurrently or while their parent is
256    /// not entered, so this can exceed elapsed wall-clock time.
257    ///
258    /// For an instrumented `Future`, only time spent polling is measured.
259    pub fn total_duration(&self) -> Duration {
260        self.total_duration
261    }
262
263    /// Returns the sum of the child spans' total durations.
264    ///
265    /// Concurrent children contribute separately even when their execution overlaps.
266    pub fn inner_duration(&self) -> Duration {
267        self.inner_duration
268    }
269
270    /// Returns the total duration minus the sum of the child spans' durations.
271    pub fn base_duration(&self) -> Duration {
272        self.total_duration
273            .checked_sub(self.inner_duration)
274            .expect("the forest layer raises the total duration to at least the sum of its children")
275    }
276
277    /// Returns this span's own CPU time plus its children's total CPU time.
278    ///
279    /// Children contribute even when they run on other threads or while their
280    /// parent is not entered. Returns `None` on unsupported platforms or if any
281    /// contributing measurement failed, went backwards, or overflowed.
282    #[cfg(feature = "forest-cpu-time")]
283    pub fn total_cpu_time(&self) -> Option<CpuTime> {
284        self.base_cpu_time?.checked_add(self.inner_cpu_time?)
285    }
286
287    /// Returns CPU time charged directly to this span, excluding other active spans.
288    ///
289    /// Each thread charges its most recently entered distinct forest span. Re-entering
290    /// an already active span leaves the current span unchanged, as in the tracing
291    /// registry. Nested spans with a different explicit parent or subscriber also
292    /// receive their own CPU time. Concurrent entries contribute separately, and
293    /// instrumented futures accumulate time only while they are polled or dropped.
294    ///
295    /// Returns `None` on unsupported platforms or if this span's own measurement
296    /// failed, went backwards, or overflowed.
297    #[cfg(feature = "forest-cpu-time")]
298    pub fn base_cpu_time(&self) -> Option<CpuTime> {
299        self.base_cpu_time
300    }
301
302    /// Returns the sum of the child spans' total CPU times, including parallel work.
303    ///
304    /// Returns `None` on unsupported platforms or if any child measurement is
305    /// unavailable or their sum overflowed.
306    #[cfg(feature = "forest-cpu-time")]
307    pub fn inner_cpu_time(&self) -> Option<CpuTime> {
308        self.inner_cpu_time
309    }
310}