Skip to main content

utopia_span/exporter/
mod.rs

1//! Exporters: where finished spans go.
2//!
3//! [`Span::finish`](crate::Span::finish) hands the span to every registered
4//! [`Exporter`] whose [`Exporter::sample`] accepts it. [`None`] discards
5//! spans, [`Stdout`] writes JSON lines, [`Pretty`] writes colourful
6//! multi-line output for a terminal, and [`Sentry`] reports errors to Sentry.
7//!
8//! PHP: the classes of `Utopia\Span\Exporter`.
9
10mod pretty;
11mod sentry;
12mod stdout;
13
14use std::io::Write;
15use std::sync::Mutex;
16
17pub use pretty::Pretty;
18#[cfg(feature = "http")]
19pub use sentry::HttpTransport;
20pub use sentry::{Request, Sentry, SentryField, SentryLevel, Transport};
21pub use stdout::Stdout;
22
23use crate::Span;
24
25/// Receives finished spans.
26///
27/// Implement it to send spans to an observability backend, then register it
28/// with [`Span::set_exporters`](crate::Span::set_exporters).
29///
30/// PHP: `Utopia\Span\Exporter\Exporter`.
31pub trait Exporter: Send + Sync {
32    /// Exports a finished span. Called for spans [`Exporter::sample`]
33    /// accepted.
34    ///
35    /// PHP: `export($span)`.
36    fn export(&self, span: &Span);
37
38    /// Whether to export `span`; `false` drops it.
39    ///
40    /// PHP: `sample($span)`.
41    fn sample(&self, span: &Span) -> bool;
42}
43
44/// Decides whether an exporter exports a span.
45///
46/// PHP: the `Closure(Span): bool` `$sampler` of an exporter's constructor.
47pub type Sampler = Box<dyn Fn(&Span) -> bool + Send + Sync>;
48
49/// Discards every span: [`Exporter::sample`] is always `false`.
50///
51/// PHP: `Utopia\Span\Exporter\None`.
52///
53/// ```
54/// use utopia_span::exporter::{Exporter, None};
55/// use utopia_span::Span;
56///
57/// let span = Span::new("test");
58/// assert!(!None.sample(&span));
59/// None.export(&span); // does nothing
60/// ```
61///
62/// ```php
63/// use Utopia\Span\Exporter\None;
64/// use Utopia\Span\Span;
65///
66/// $span = new Span('test');
67/// var_dump((new None())->sample($span)); // bool(false)
68/// (new None())->export($span);           // does nothing
69/// ```
70#[derive(Debug, Default, Clone, Copy)]
71pub struct None;
72
73impl Exporter for None {
74    fn export(&self, _span: &Span) {}
75
76    fn sample(&self, _span: &Span) -> bool {
77        false
78    }
79}
80
81/// Where an exporter writes: one stream for spans, one for spans with an
82/// error.
83pub(crate) struct Streams {
84    out: Mutex<Box<dyn Write + Send>>,
85    err: Mutex<Box<dyn Write + Send>>,
86}
87
88impl Streams {
89    /// The process's standard output and standard error.
90    pub(crate) fn standard() -> Self {
91        Self::new(Box::new(std::io::stdout()), Box::new(std::io::stderr()))
92    }
93
94    pub(crate) fn new(out: Box<dyn Write + Send>, err: Box<dyn Write + Send>) -> Self {
95        Self { out: Mutex::new(out), err: Mutex::new(err) }
96    }
97
98    /// Writes `bytes` to the error stream when `error`, else to the output.
99    pub(crate) fn write(&self, error: bool, bytes: &[u8]) {
100        let stream = if error { &self.err } else { &self.out };
101        let mut stream = stream.lock().unwrap_or_else(|e| e.into_inner());
102        // Tracing never breaks the application: a closed stream drops spans.
103        let _ = stream.write_all(bytes).and_then(|()| stream.flush());
104    }
105}
106
107/// How many of `len` stack frames an exporter prints at most `max` of.
108pub(crate) fn kept(len: usize, max: usize) -> usize {
109    len.min(max)
110}