Skip to main content

webserver_base/observability/
mod.rs

1//! Sentry and tracing, initialised in the one order that works.
2//!
3//! `sentry::init` binds its hub to the calling thread; threads spawned
4//! afterwards inherit it. `#[tokio::main]` spawns its workers *before* running
5//! the body of `main`, so initialising there never reaches them and every error
6//! raised on a worker is dropped. Hence: initialise on the main thread, then
7//! build the runtime — which is what [`bootstrap`](crate::bootstrap) does.
8//!
9//! [`ObservabilityGuard`] flushes on drop, so it must outlive the server.
10
11use std::fmt::{self, Debug, Formatter};
12
13use sentry::integrations::tracing::{BreadcrumbLayer, ErrorLayer, SpanLayer};
14use tracing::{Level, info, instrument, warn};
15use tracing_subscriber::filter::{LevelFilter, filter_fn};
16use tracing_subscriber::layer::SubscriberExt;
17use tracing_subscriber::util::SubscriberInitExt;
18use tracing_subscriber::{EnvFilter, Layer};
19
20use crate::env::{self, EnvError};
21use crate::environment::Environment;
22use crate::traces::{HTTP_SERVER_OP, TracesSampleRate};
23
24/// The environment variable holding the Sentry DSN.
25pub const ENV_SENTRY_DSN: &str = "WSB_SENTRY_SERVER_DSN";
26
27/// The log filter fallback when `RUST_LOG` is unset.
28pub const DEFAULT_LOG_FILTER: &str = "info";
29
30/// Why observability could not be configured.
31#[derive(Debug, thiserror::Error)]
32pub enum ObservabilityError {
33    /// Production without a DSN. Deliberately fatal: a production server with
34    /// monitoring off looks healthy while reporting nothing.
35    #[error(
36        "environment variable `{ENV_SENTRY_DSN}` is required in production; \
37         error monitoring cannot be disabled there"
38    )]
39    MissingDsnInProduction,
40
41    /// An environment variable could not be read.
42    #[error(transparent)]
43    Env(#[from] EnvError),
44}
45
46/// How this process reports errors and logs.
47#[derive(Clone)]
48pub struct Observability {
49    dsn: Option<String>,
50    environment: Environment,
51    log_filter: Option<String>,
52    release: String,
53    traces_sample_rate: TracesSampleRate,
54}
55
56/// The release string used when the application does not name itself.
57///
58/// Sentry's own `release_name!` resolves `CARGO_PKG_NAME` where it is *written*
59/// — inside this crate — so every project that used it would report the same
60/// release and Sentry could not tell one site's deploys from another's. The
61/// application must supply its own; this is only the fallback.
62pub const UNKNOWN_RELEASE: &str = "unknown";
63
64impl Observability {
65    /// Error monitoring pointed at `dsn`.
66    #[must_use]
67    pub fn new(environment: Environment, dsn: impl Into<String>) -> Self {
68        Self {
69            dsn: Some(dsn.into()),
70            environment,
71            log_filter: None,
72            release: String::from(UNKNOWN_RELEASE),
73            traces_sample_rate: TracesSampleRate::SERVER_DEFAULT,
74        }
75    }
76
77    /// Tracing only, with no error monitoring. For local runs and tests.
78    #[must_use]
79    pub fn none(environment: Environment) -> Self {
80        Self {
81            dsn: None,
82            environment,
83            log_filter: None,
84            release: String::from(UNKNOWN_RELEASE),
85            traces_sample_rate: TracesSampleRate::SERVER_DEFAULT,
86        }
87    }
88
89    /// Reads [`ENV_SENTRY_DSN`], which every environment must set.
90    ///
91    /// Required locally too, deliberately: a DSN exercised only in production
92    /// is a DSN nobody has proved works. Point local runs at a development
93    /// Sentry project.
94    ///
95    /// # Errors
96    ///
97    /// [`ObservabilityError::Env`] if it is unset or blank.
98    pub fn from_env(environment: Environment) -> Result<Self, ObservabilityError> {
99        // Required in every environment, not just production. A DSN that is
100        // only exercised in production is a DSN nobody has proved works.
101        let dsn: String = env::required(ENV_SENTRY_DSN)?;
102
103        Ok(Self {
104            dsn: Some(dsn),
105            environment,
106            log_filter: None,
107            release: String::from(UNKNOWN_RELEASE),
108            traces_sample_rate: TracesSampleRate::SERVER_DEFAULT,
109        })
110    }
111
112    /// Names the running build, as `my-project@1.2.3`.
113    ///
114    /// This is what Sentry attributes issues to, so it must identify the
115    /// *application*, not this library. Deriving it here is impossible: the
116    /// crate metadata available inside this crate is this crate's own.
117    #[must_use]
118    pub fn with_release(mut self, release: impl Into<String>) -> Self {
119        self.release = release.into();
120        self
121    }
122
123    /// Overrides the `RUST_LOG` fallback. `RUST_LOG` itself stays unprefixed —
124    /// it is an ecosystem convention.
125    #[must_use]
126    pub fn with_log_filter(mut self, log_filter: impl Into<String>) -> Self {
127        self.log_filter = Some(log_filter.into());
128        self
129    }
130
131    /// The share of dynamic requests that send a trace. Defaults to
132    /// [`TracesSampleRate::SERVER_DEFAULT`]; [`TracesSampleRate::OFF`] sends
133    /// none.
134    ///
135    /// Static assets, health checks, the analytics and Sentry proxies and 404s
136    /// are never traced, whatever the rate (see
137    /// [`webserver`](crate::webserver)).
138    #[must_use]
139    pub const fn with_traces_sample_rate(mut self, traces_sample_rate: TracesSampleRate) -> Self {
140        self.traces_sample_rate = traces_sample_rate;
141        self
142    }
143
144    /// Whether error monitoring is configured.
145    #[must_use]
146    pub const fn has_error_monitoring(&self) -> bool {
147        self.dsn.is_some()
148    }
149
150    /// Which deployment this is.
151    #[must_use]
152    pub const fn environment(&self) -> Environment {
153        self.environment
154    }
155
156    /// Installs the tracing subscriber and, when a DSN is set, Sentry.
157    ///
158    /// Main thread, before any runtime. Hold the guard for the process.
159    #[must_use]
160    #[instrument(skip_all)]
161    pub fn init(self) -> ObservabilityGuard {
162        let sentry_guard: Option<sentry::ClientInitGuard> = self.dsn.as_ref().map(|dsn| {
163            // `ClientOptions` is `#[non_exhaustive]` as of sentry 0.49, so it
164            // has to be built by mutation rather than a struct expression.
165            let mut options: sentry::ClientOptions = sentry::ClientOptions::default();
166            // Not `sentry::release_name!()`: that macro reads the crate
167            // metadata of wherever it is expanded, which here is this library —
168            // so every project would report an identical release and Sentry
169            // could not attribute an issue to the deploy that caused it.
170            options.release = Some(self.release.clone().into());
171            options.environment = Some(self.environment.as_str().into());
172            options.attach_stacktrace = true;
173            let options: sentry::ClientOptions = with_traces(options, self.traces_sample_rate);
174
175            sentry::init((dsn.clone(), options))
176        });
177
178        let fallback: &str = self.log_filter.as_deref().unwrap_or(DEFAULT_LOG_FILTER);
179        let directives: String =
180            std::env::var(EnvFilter::DEFAULT_ENV).unwrap_or_else(|_| fallback.to_string());
181        let filter: EnvFilter =
182            EnvFilter::try_new(&directives).unwrap_or_else(|_| EnvFilter::new(DEFAULT_LOG_FILTER));
183
184        // A human reads the local log; a machine reads the production one.
185        // `with_ansi(false)` in production because a log driver stores escape
186        // codes verbatim and nothing downstream strips them.
187        let format = if self.environment.is_production() {
188            tracing_subscriber::fmt::layer()
189                .json()
190                .flatten_event(true)
191                .with_current_span(true)
192                .with_span_list(false)
193                .with_ansi(false)
194                .with_filter(filter)
195                .boxed()
196        } else {
197            tracing_subscriber::fmt::layer().with_filter(filter).boxed()
198        };
199
200        tracing_subscriber::registry()
201            .with(format)
202            // Harmless without Sentry: the layers forward to a disabled hub.
203            // Together they are the retired `sentry_tracing::layer()`'s
204            // defaults: INFO+ spans become transactions, `error!` an event, and
205            // `warn!`/`info!` breadcrumbs. The breadcrumb filter must exclude
206            // ERROR, or every error would also ride along as its own crumb.
207            .with(SpanLayer::new().with_filter(LevelFilter::INFO))
208            .with(BreadcrumbLayer::new().with_filter(filter_fn(|metadata| {
209                matches!(*metadata.level(), Level::WARN | Level::INFO)
210            })))
211            .with(ErrorLayer::new().with_filter(LevelFilter::ERROR))
212            .init();
213
214        // The one thing no other log line can tell you: which build is running.
215        // Everything else here is either inferable or already stated elsewhere,
216        // so this stays to three fields.
217        info!(
218            release = %self.release,
219            environment = %self.environment,
220            log_filter = %directives,
221            "starting"
222        );
223
224        if sentry_guard.is_none() {
225            warn!("error monitoring is not configured; nothing will reach Sentry");
226        }
227
228        ObservabilityGuard {
229            sentry: sentry_guard,
230        }
231    }
232}
233
234/// `options`, sampling traces at `rate`.
235///
236/// Left unset (not a zero rate) when off: an unset strategy ignores an incoming
237/// `sentry-trace` sampled flag, whereas a zero fixed rate would honour it and
238/// let the browser turn server tracing on.
239pub(crate) fn with_traces(
240    options: sentry::ClientOptions,
241    rate: TracesSampleRate,
242) -> sentry::ClientOptions {
243    if rate.is_on() {
244        let rate: f32 = rate.get();
245        options
246            .traces_sampler(move |context: &sentry::TransactionContext| sample_rate(context, rate))
247    } else {
248        options
249    }
250}
251
252/// The rate for one new transaction.
253///
254/// Only a request the server chose to trace (op [`HTTP_SERVER_OP`]) gets the
255/// configured rate; every other root span is dropped, because the tracing
256/// layer turns *any* root `info` span into a transaction (a background task, a
257/// proxy handler) and each would spend span quota nobody budgeted.
258///
259/// A sampled parent (`sentry-trace` from the browser) is deliberately not
260/// honoured: the browser's rate is ten to a hundred times the server's, so
261/// honouring it would send every request of every sampled page load and
262/// defeat the server rate. The trace id is still continued, so a sampled
263/// server transaction joins the browser's trace when the browser sampled too.
264fn sample_rate(context: &sentry::TransactionContext, rate: f32) -> f32 {
265    if context.operation() == HTTP_SERVER_OP {
266        rate
267    } else {
268        0.0
269    }
270}
271
272impl Debug for Observability {
273    /// Never prints the DSN — it is a credential, and this type reaches logs.
274    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
275        f.debug_struct("Observability")
276            .field("environment", &self.environment)
277            .field("release", &self.release)
278            // The DSN itself is deliberately absent: it is a credential, and
279            // this type reaches logs.
280            .field("error_monitoring", &self.dsn.is_some())
281            .field("log_filter", &self.log_filter)
282            .field("traces_sample_rate", &self.traces_sample_rate)
283            .finish()
284    }
285}
286
287/// Keeps error monitoring alive, and flushes it on drop. Bind it to `_guard`,
288/// never `_`, which would drop it immediately.
289pub struct ObservabilityGuard {
290    sentry: Option<sentry::ClientInitGuard>,
291}
292
293impl Debug for ObservabilityGuard {
294    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
295        f.debug_struct("ObservabilityGuard")
296            .field("error_monitoring", &self.sentry.is_some())
297            .finish()
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use sentry::TransactionContext;
304
305    use super::{Observability, sample_rate};
306    use crate::environment::Environment;
307    use crate::traces::{HTTP_SERVER_OP, TracesSampleRate};
308
309    #[test]
310    fn debug_output_never_contains_the_dsn() {
311        let observability: Observability =
312            Observability::new(Environment::Production, "https://sup3rs3cret@example.com/1");
313
314        let actual: String = format!("{observability:?}");
315        assert!(!actual.contains("sup3rs3cret"));
316        assert!(actual.contains("error_monitoring: true"));
317    }
318
319    #[test]
320    fn a_custom_log_filter_is_retained() {
321        let observability: Observability =
322            Observability::none(Environment::Local).with_log_filter("debug");
323
324        let actual: String = format!("{observability:?}");
325        assert!(actual.contains("debug"));
326    }
327
328    #[test]
329    fn a_traced_request_gets_the_configured_rate() {
330        let context: TransactionContext = TransactionContext::new("GET /{slug}", HTTP_SERVER_OP);
331
332        assert_eq!(0.25, sample_rate(&context, 0.25));
333    }
334
335    #[test]
336    fn any_other_root_span_is_never_sampled() {
337        for op in [
338            "http.server.untraced",
339            "tower_http::trace::make_span",
340            "task",
341        ] {
342            let context: TransactionContext = TransactionContext::new("anything", op);
343
344            assert_eq!(0.0, sample_rate(&context, 1.0), "{op}");
345        }
346    }
347
348    #[test]
349    fn a_sampled_browser_parent_does_not_raise_the_server_rate() {
350        let mut context: TransactionContext = TransactionContext::continue_from_headers(
351            "GET /",
352            HTTP_SERVER_OP,
353            [(
354                "sentry-trace",
355                "771a43a4192642f0b136d5159a501700-1234567890abcdef-1",
356            )],
357        );
358        context.set_sampled(true);
359
360        assert_eq!(0.001, sample_rate(&context, 0.001));
361    }
362
363    #[test]
364    fn the_server_rate_defaults_to_the_named_constant_and_can_be_set() {
365        let default: Observability = Observability::none(Environment::Local);
366        assert!(format!("{default:?}").contains("traces_sample_rate: TracesSampleRate(0.01)"));
367
368        let set: Observability =
369            Observability::none(Environment::Local).with_traces_sample_rate(TracesSampleRate::OFF);
370        assert!(format!("{set:?}").contains("traces_sample_rate: TracesSampleRate(0.0)"));
371    }
372}