Skip to main content

webserver_base/
traces.rs

1//! How much of the traffic Sentry traces.
2//!
3//! Browser and server are separate knobs: a page load is a few spans and a
4//! visitor opens many, a server request is one span per handler. Both default
5//! here, so every site traces alike unless it names its own rate.
6
7use std::fmt::{self, Display, Formatter};
8
9/// The browser default: the share of page loads that send a trace.
10///
11/// Placeholder until real traffic numbers set it. Changing it here changes
12/// every site that has not chosen its own.
13pub const DEFAULT_BROWSER_TRACES_SAMPLE_RATE: f32 = 0.2;
14
15/// The server default: the share of dynamic requests that send a trace.
16///
17/// Placeholder until real traffic numbers set it. Low because the server sees
18/// every request, including every browser-initiated one.
19pub const DEFAULT_SERVER_TRACES_SAMPLE_RATE: f32 = 0.01;
20
21/// The `op` of a request the server traces. Anything else is dropped by the
22/// sampler.
23#[cfg(any(feature = "webserver", feature = "observability"))]
24pub(crate) const HTTP_SERVER_OP: &str = "http.server";
25
26/// Response extension: this 5xx is an upstream's, relayed as-is, not a fault of
27/// this server. The server's trace layer treats the response as a success, so
28/// `tower_http` logs no `response failed` error and Sentry files no event for
29/// it. The relay logs a `warn` itself.
30#[cfg(any(feature = "webserver", feature = "analytics"))]
31#[derive(Clone, Copy, Debug)]
32pub(crate) struct UpstreamFailure;
33
34/// A share of traces to send, from `0.0` (off) to `1.0` (all).
35///
36/// `0.0` means tracing is off: nothing is loaded, started or sent for it.
37#[derive(Debug, Clone, Copy, PartialEq)]
38pub struct TracesSampleRate(f32);
39
40/// A rate that is not a number from `0.0` to `1.0`.
41#[derive(Debug, Clone, Copy, PartialEq, thiserror::Error)]
42#[error("traces sample rate {rate} is not between 0.0 and 1.0; use 0.0 to turn tracing off")]
43pub struct TracesSampleRateError {
44    rate: f32,
45}
46
47impl TracesSampleRate {
48    /// Tracing off.
49    pub const OFF: Self = Self(0.0);
50
51    /// Every trace sent.
52    pub const ALL: Self = Self(1.0);
53
54    /// The browser default, [`DEFAULT_BROWSER_TRACES_SAMPLE_RATE`].
55    pub const BROWSER_DEFAULT: Self = Self(DEFAULT_BROWSER_TRACES_SAMPLE_RATE);
56
57    /// The server default, [`DEFAULT_SERVER_TRACES_SAMPLE_RATE`].
58    pub const SERVER_DEFAULT: Self = Self(DEFAULT_SERVER_TRACES_SAMPLE_RATE);
59
60    /// A rate of `rate`, from `0.0` to `1.0` inclusive.
61    ///
62    /// # Errors
63    ///
64    /// [`TracesSampleRateError`] if `rate` is `NaN`, infinite or outside that
65    /// range.
66    pub fn new(rate: f32) -> Result<Self, TracesSampleRateError> {
67        if (0.0..=1.0).contains(&rate) {
68            Ok(Self(rate))
69        } else {
70            Err(TracesSampleRateError { rate })
71        }
72    }
73
74    /// The rate, from `0.0` to `1.0`.
75    #[must_use]
76    pub const fn get(self) -> f32 {
77        self.0
78    }
79
80    /// Whether any trace can be sent.
81    #[must_use]
82    pub const fn is_on(self) -> bool {
83        self.0 > 0.0
84    }
85}
86
87impl Display for TracesSampleRate {
88    /// The shortest decimal that reads back as the same `f32` (`0.2`, never
89    /// `0.20000000298`), which is what a script literal needs.
90    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
91        Display::fmt(&self.0, f)
92    }
93}
94
95impl TryFrom<f32> for TracesSampleRate {
96    type Error = TracesSampleRateError;
97
98    fn try_from(rate: f32) -> Result<Self, Self::Error> {
99        Self::new(rate)
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::{
106        DEFAULT_BROWSER_TRACES_SAMPLE_RATE, DEFAULT_SERVER_TRACES_SAMPLE_RATE, TracesSampleRate,
107    };
108
109    #[test]
110    fn both_ends_of_the_range_are_valid() {
111        assert_eq!(Ok(TracesSampleRate::OFF), TracesSampleRate::new(0.0));
112        assert_eq!(Ok(TracesSampleRate::ALL), TracesSampleRate::new(1.0));
113        assert_eq!(0.25, TracesSampleRate::new(0.25).expect("valid").get());
114    }
115
116    #[test]
117    fn a_rate_outside_the_range_or_not_a_number_is_rejected() {
118        for rate in [
119            -0.001,
120            1.001,
121            2.0,
122            f32::NAN,
123            f32::INFINITY,
124            f32::NEG_INFINITY,
125        ] {
126            assert!(TracesSampleRate::new(rate).is_err(), "{rate}");
127        }
128    }
129
130    #[test]
131    fn the_error_says_what_to_do() {
132        let message: String = TracesSampleRate::new(1.5)
133            .expect_err("too high")
134            .to_string();
135        assert_eq!(
136            "traces sample rate 1.5 is not between 0.0 and 1.0; use 0.0 to turn tracing off",
137            message
138        );
139    }
140
141    #[test]
142    fn only_a_rate_above_zero_is_on() {
143        assert!(!TracesSampleRate::OFF.is_on());
144        assert!(TracesSampleRate::SERVER_DEFAULT.is_on());
145        assert!(TracesSampleRate::ALL.is_on());
146    }
147
148    #[test]
149    fn the_defaults_are_the_named_constants() {
150        assert_eq!(
151            DEFAULT_BROWSER_TRACES_SAMPLE_RATE,
152            TracesSampleRate::BROWSER_DEFAULT.get()
153        );
154        assert_eq!(
155            DEFAULT_SERVER_TRACES_SAMPLE_RATE,
156            TracesSampleRate::SERVER_DEFAULT.get()
157        );
158    }
159
160    #[test]
161    fn a_rate_prints_as_the_shortest_decimal_for_a_script_literal() {
162        assert_eq!("0.2", TracesSampleRate::BROWSER_DEFAULT.to_string());
163        assert_eq!("0.01", TracesSampleRate::SERVER_DEFAULT.to_string());
164        assert_eq!("1", TracesSampleRate::ALL.to_string());
165        assert_eq!("0", TracesSampleRate::OFF.to_string());
166    }
167}