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;
22
23/// The environment variable holding the Sentry DSN.
24pub const ENV_SENTRY_DSN: &str = "WSB_SENTRY_SERVER_DSN";
25
26/// The log filter fallback when `RUST_LOG` is unset.
27pub const DEFAULT_LOG_FILTER: &str = "info";
28
29/// Why observability could not be configured.
30#[derive(Debug, thiserror::Error)]
31pub enum ObservabilityError {
32    /// Production without a DSN. Deliberately fatal: a production server with
33    /// monitoring off looks healthy while reporting nothing.
34    #[error(
35        "environment variable `{ENV_SENTRY_DSN}` is required in production; \
36         error monitoring cannot be disabled there"
37    )]
38    MissingDsnInProduction,
39
40    /// An environment variable could not be read.
41    #[error(transparent)]
42    Env(#[from] EnvError),
43}
44
45/// How this process reports errors and logs.
46#[derive(Clone)]
47pub struct Observability {
48    dsn: Option<String>,
49    environment: Environment,
50    log_filter: Option<String>,
51    release: String,
52}
53
54/// The release string used when the application does not name itself.
55///
56/// Sentry's own `release_name!` resolves `CARGO_PKG_NAME` where it is *written*
57/// — inside this crate — so every project that used it would report the same
58/// release and Sentry could not tell one site's deploys from another's. The
59/// application must supply its own; this is only the fallback.
60pub const UNKNOWN_RELEASE: &str = "unknown";
61
62impl Observability {
63    /// Error monitoring pointed at `dsn`.
64    #[must_use]
65    pub fn new(environment: Environment, dsn: impl Into<String>) -> Self {
66        Self {
67            dsn: Some(dsn.into()),
68            environment,
69            log_filter: None,
70            release: String::from(UNKNOWN_RELEASE),
71        }
72    }
73
74    /// Tracing only, with no error monitoring. For local runs and tests.
75    #[must_use]
76    pub fn none(environment: Environment) -> Self {
77        Self {
78            dsn: None,
79            environment,
80            log_filter: None,
81            release: String::from(UNKNOWN_RELEASE),
82        }
83    }
84
85    /// Reads [`ENV_SENTRY_DSN`], which every environment must set.
86    ///
87    /// Required locally too, deliberately: a DSN exercised only in production
88    /// is a DSN nobody has proved works. Point local runs at a development
89    /// Sentry project.
90    ///
91    /// # Errors
92    ///
93    /// [`ObservabilityError::Env`] if it is unset or blank.
94    pub fn from_env(environment: Environment) -> Result<Self, ObservabilityError> {
95        // Required in every environment, not just production. A DSN that is
96        // only exercised in production is a DSN nobody has proved works.
97        let dsn: String = env::required(ENV_SENTRY_DSN)?;
98
99        Ok(Self {
100            dsn: Some(dsn),
101            environment,
102            log_filter: None,
103            release: String::from(UNKNOWN_RELEASE),
104        })
105    }
106
107    /// Names the running build, as `my-project@1.2.3`.
108    ///
109    /// This is what Sentry attributes issues to, so it must identify the
110    /// *application*, not this library. Deriving it here is impossible: the
111    /// crate metadata available inside this crate is this crate's own.
112    #[must_use]
113    pub fn with_release(mut self, release: impl Into<String>) -> Self {
114        self.release = release.into();
115        self
116    }
117
118    /// Overrides the `RUST_LOG` fallback. `RUST_LOG` itself stays unprefixed —
119    /// it is an ecosystem convention.
120    #[must_use]
121    pub fn with_log_filter(mut self, log_filter: impl Into<String>) -> Self {
122        self.log_filter = Some(log_filter.into());
123        self
124    }
125
126    /// Whether error monitoring is configured.
127    #[must_use]
128    pub const fn has_error_monitoring(&self) -> bool {
129        self.dsn.is_some()
130    }
131
132    /// Which deployment this is.
133    #[must_use]
134    pub const fn environment(&self) -> Environment {
135        self.environment
136    }
137
138    /// Installs the tracing subscriber and, when a DSN is set, Sentry.
139    ///
140    /// Main thread, before any runtime. Hold the guard for the process.
141    #[must_use]
142    #[instrument(skip_all)]
143    pub fn init(self) -> ObservabilityGuard {
144        let sentry_guard: Option<sentry::ClientInitGuard> = self.dsn.as_ref().map(|dsn| {
145            // `ClientOptions` is `#[non_exhaustive]` as of sentry 0.49, so it
146            // has to be built by mutation rather than a struct expression.
147            let mut options: sentry::ClientOptions = sentry::ClientOptions::default();
148            // Not `sentry::release_name!()`: that macro reads the crate
149            // metadata of wherever it is expanded, which here is this library —
150            // so every project would report an identical release and Sentry
151            // could not attribute an issue to the deploy that caused it.
152            options.release = Some(self.release.clone().into());
153            options.environment = Some(self.environment.as_str().into());
154            options.attach_stacktrace = true;
155
156            sentry::init((dsn.clone(), options))
157        });
158
159        let fallback: &str = self.log_filter.as_deref().unwrap_or(DEFAULT_LOG_FILTER);
160        let directives: String =
161            std::env::var(EnvFilter::DEFAULT_ENV).unwrap_or_else(|_| fallback.to_string());
162        let filter: EnvFilter =
163            EnvFilter::try_new(&directives).unwrap_or_else(|_| EnvFilter::new(DEFAULT_LOG_FILTER));
164
165        // A human reads the local log; a machine reads the production one.
166        // `with_ansi(false)` in production because a log driver stores escape
167        // codes verbatim and nothing downstream strips them.
168        let format = if self.environment.is_production() {
169            tracing_subscriber::fmt::layer()
170                .json()
171                .flatten_event(true)
172                .with_current_span(true)
173                .with_span_list(false)
174                .with_ansi(false)
175                .with_filter(filter)
176                .boxed()
177        } else {
178            tracing_subscriber::fmt::layer().with_filter(filter).boxed()
179        };
180
181        tracing_subscriber::registry()
182            .with(format)
183            // Harmless without Sentry: the layers forward to a disabled hub.
184            // Together they are the retired `sentry_tracing::layer()`'s
185            // defaults: INFO+ spans become transactions, `error!` an event, and
186            // `warn!`/`info!` breadcrumbs. The breadcrumb filter must exclude
187            // ERROR, or every error would also ride along as its own crumb.
188            .with(SpanLayer::new().with_filter(LevelFilter::INFO))
189            .with(BreadcrumbLayer::new().with_filter(filter_fn(|metadata| {
190                matches!(*metadata.level(), Level::WARN | Level::INFO)
191            })))
192            .with(ErrorLayer::new().with_filter(LevelFilter::ERROR))
193            .init();
194
195        // The one thing no other log line can tell you: which build is running.
196        // Everything else here is either inferable or already stated elsewhere,
197        // so this stays to three fields.
198        info!(
199            release = %self.release,
200            environment = %self.environment,
201            log_filter = %directives,
202            "starting"
203        );
204
205        if sentry_guard.is_none() {
206            warn!("error monitoring is not configured; nothing will reach Sentry");
207        }
208
209        ObservabilityGuard {
210            sentry: sentry_guard,
211        }
212    }
213}
214
215impl Debug for Observability {
216    /// Never prints the DSN — it is a credential, and this type reaches logs.
217    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
218        f.debug_struct("Observability")
219            .field("environment", &self.environment)
220            .field("release", &self.release)
221            // The DSN itself is deliberately absent: it is a credential, and
222            // this type reaches logs.
223            .field("error_monitoring", &self.dsn.is_some())
224            .field("log_filter", &self.log_filter)
225            .finish()
226    }
227}
228
229/// Keeps error monitoring alive, and flushes it on drop. Bind it to `_guard`,
230/// never `_`, which would drop it immediately.
231pub struct ObservabilityGuard {
232    sentry: Option<sentry::ClientInitGuard>,
233}
234
235impl Debug for ObservabilityGuard {
236    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
237        f.debug_struct("ObservabilityGuard")
238            .field("error_monitoring", &self.sentry.is_some())
239            .finish()
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::Observability;
246    use crate::environment::Environment;
247
248    #[test]
249    fn debug_output_never_contains_the_dsn() {
250        let observability: Observability =
251            Observability::new(Environment::Production, "https://sup3rs3cret@example.com/1");
252
253        let actual: String = format!("{observability:?}");
254        assert!(!actual.contains("sup3rs3cret"));
255        assert!(actual.contains("error_monitoring: true"));
256    }
257
258    #[test]
259    fn a_custom_log_filter_is_retained() {
260        let observability: Observability =
261            Observability::none(Environment::Local).with_log_filter("debug");
262
263        let actual: String = format!("{observability:?}");
264        assert!(actual.contains("debug"));
265    }
266}