feldera_observability/
lib.rs

1use actix_http::header::{HeaderName, HeaderValue};
2use awc::ClientRequest;
3use reqwest::RequestBuilder;
4use sentry::{ClientInitGuard, TransactionContext};
5use std::borrow::Cow;
6use std::env;
7
8/// Initializes Sentry if `FELDERA_SENTRY_ENABLED` is set, tagging the service and release.
9///
10/// Use dsn as the default DSN, which can be overridden by the `SENTRY_DSN` environment variable.
11pub fn init(dsn: &str, service_name: &str, release: &str) -> Option<ClientInitGuard> {
12    env::var("FELDERA_SENTRY_ENABLED")
13        .ok()
14        .filter(|v| v == "1")?;
15
16    const DEFAULT_SAMPLE_RATE: f32 = 1.0;
17    const DEFAULT_TRACE_SAMPLE_RATE: f32 = 0.1;
18    const MAX_BREADCRUMBS: usize = 10;
19
20    let dsn = env::var("SENTRY_DSN").ok().unwrap_or(dsn.to_string());
21    let sample_rate = env::var("SENTRY_SAMPLE_RATE")
22        .ok()
23        .and_then(|rate| rate.parse::<f32>().ok())
24        .unwrap_or(DEFAULT_SAMPLE_RATE);
25    let traces_sample_rate = env::var("SENTRY_TRACES_SAMPLE_RATE")
26        .ok()
27        .and_then(|rate| rate.parse::<f32>().ok())
28        .unwrap_or(DEFAULT_TRACE_SAMPLE_RATE);
29    let environment = env::var("SENTRY_ENVIRONMENT")
30        .unwrap_or_else(|_| String::from("dev"))
31        .into();
32    let accept_invalid_certs = environment == "ci" || environment == "dev";
33    let max_breadcrumbs = env::var("SENTRY_MAX_BREADCRUMBS")
34        .ok()
35        .and_then(|rate| rate.parse::<usize>().ok())
36        .unwrap_or(MAX_BREADCRUMBS);
37
38    let guard = sentry::init((
39        dsn,
40        sentry::ClientOptions {
41            environment: Some(environment),
42            release: Some(Cow::Owned(release.to_string())),
43            max_breadcrumbs,
44            sample_rate,
45            traces_sample_rate,
46            enable_logs: true,
47            attach_stacktrace: true,
48            accept_invalid_certs,
49            ..Default::default()
50        },
51    ));
52
53    sentry::configure_scope(|scope| scope.set_tag("service", service_name));
54    Some(guard)
55}
56
57fn sentry_enabled() -> bool {
58    sentry::Hub::current().client().is_some()
59}
60
61/// Returns an Actix middleware that captures errors and traces when Sentry is enabled.
62pub fn actix_middleware() -> sentry::integrations::actix::Sentry {
63    sentry::integrations::actix::Sentry::builder()
64        .emit_header(true)
65        .capture_server_errors(true)
66        .start_transaction(true)
67        .finish()
68}
69
70pub mod json_logging;
71
72fn trace_header_value() -> Option<String> {
73    if !sentry_enabled() {
74        return None;
75    }
76
77    let mut header = None;
78    sentry::configure_scope(|scope| {
79        if let Some(span) = scope.get_span() {
80            header = span.iter_headers().next().map(|(_, value)| value);
81        }
82    });
83    if header.is_none() {
84        let transaction =
85            sentry::start_transaction(TransactionContext::new("http.client", "http.client"));
86        header = transaction.iter_headers().next().map(|(_, value)| value);
87        transaction.finish();
88    }
89    header
90}
91
92/// Adds Sentry trace headers to outgoing awc requests.
93pub trait AwcRequestTracingExt {
94    fn with_sentry_tracing(self) -> Self;
95}
96
97impl AwcRequestTracingExt for ClientRequest {
98    fn with_sentry_tracing(mut self) -> Self {
99        if let Some(value) = trace_header_value()
100            && let Ok(header_value) = HeaderValue::from_str(&value)
101        {
102            self = self.insert_header((HeaderName::from_static("sentry-trace"), header_value));
103        }
104        self
105    }
106}
107
108/// Adds Sentry trace headers to outgoing reqwest requests.
109pub trait ReqwestTracingExt {
110    fn with_sentry_tracing(self) -> Self;
111}
112
113impl ReqwestTracingExt for RequestBuilder {
114    fn with_sentry_tracing(self) -> Self {
115        if let Some(value) = trace_header_value()
116            && let Ok(header_value) = reqwest::header::HeaderValue::from_str(&value)
117        {
118            return self.header(
119                reqwest::header::HeaderName::from_static("sentry-trace"),
120                header_value,
121            );
122        }
123        self
124    }
125}