Skip to main content

sentry_core/
clientoptions.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::sync::Arc;
4use std::time::Duration;
5
6use crate::constants::USER_AGENT;
7use crate::performance::TracesSampler;
8use crate::protocol::{Breadcrumb, Event, Log, Metric};
9use crate::types::Dsn;
10use crate::{Integration, IntoDsn, TransportFactory};
11
12/// Type alias for before event/breadcrumb handlers.
13pub type BeforeCallback<T> = Arc<dyn Fn(T) -> Option<T> + Send + Sync>;
14
15/// The Session Mode of the SDK.
16///
17/// Depending on the use-case, the SDK can be set to two different session modes:
18///
19/// * **Application Mode Sessions**:
20///   This mode should be used for user-attended programs, which typically have
21///   a single long running session that span the applications' lifetime.
22///
23/// * **Request Mode Sessions**:
24///   This mode is intended for servers that use one session per incoming
25///   request, and thus have a lot of very short lived sessions.
26///
27/// Setting the SDK to *request-mode* sessions means that session durations will
28/// not be tracked, and sessions will be pre-aggregated before being sent upstream.
29/// This applies both to automatic and manually triggered sessions.
30///
31/// **NOTE**: Support for *request-mode* sessions was added in Sentry `21.2`.
32///
33/// See the [Documentation on Session Modes](https://develop.sentry.dev/sdk/sessions/#sdk-considerations)
34/// for more information.
35///
36/// **NOTE**: The `release-health` feature (enabled by default) needs to be enabled for this option to have
37/// any effect.
38#[derive(Copy, Clone, Debug, PartialEq, Eq)]
39pub enum SessionMode {
40    /// Long running application session.
41    Application,
42    /// Lots of short per-request sessions.
43    Request,
44}
45
46/// The maximum size of an HTTP request body that the SDK captures.
47///
48/// Only request bodies that parse as JSON or form data are currently captured.
49/// See the [Documentation on attaching request body](https://develop.sentry.dev/sdk/expected-features/#attaching-request-body-in-server-sdks)
50/// and the [Documentation on handling sensitive data](https://develop.sentry.dev/sdk/expected-features/data-handling/#sensitive-data)
51/// for more information.
52#[derive(Clone, Copy, PartialEq)]
53pub enum MaxRequestBodySize {
54    /// Don't capture request body
55    None,
56    /// Capture up to 1000 bytes
57    Small,
58    /// Capture up to 10000 bytes
59    Medium,
60    /// Capture entire body
61    Always,
62    /// Capture up to a specific size
63    Explicit(usize),
64}
65
66impl MaxRequestBodySize {
67    /// Check if the content length is within the size limit.
68    pub fn is_within_size_limit(&self, content_length: usize) -> bool {
69        match self {
70            MaxRequestBodySize::None => false,
71            MaxRequestBodySize::Small => content_length <= 1_000,
72            MaxRequestBodySize::Medium => content_length <= 10_000,
73            MaxRequestBodySize::Always => true,
74            MaxRequestBodySize::Explicit(size) => content_length <= *size,
75        }
76    }
77}
78
79/// Configuration settings for the client.
80///
81/// These options are explained in more detail in the general
82/// [sentry documentation](https://docs.sentry.io/error-reporting/configuration/?platform=rust).
83///
84/// # Examples
85///
86/// ```
87/// let _options = sentry::ClientOptions {
88///     debug: true,
89///     ..Default::default()
90/// };
91/// ```
92#[derive(Clone)]
93pub struct ClientOptions {
94    // Common options
95    /// The DSN to use.  If not set the client is effectively disabled.
96    pub dsn: Option<Dsn>,
97    /// Enables debug mode.
98    ///
99    /// In debug mode debug information is printed to stderr to help you understand what
100    /// sentry is doing.
101    pub debug: bool,
102    /// The release to be sent with events.
103    pub release: Option<Cow<'static, str>>,
104    /// The environment to be sent with events.
105    ///
106    /// Defaults to either `"development"` or `"production"` depending on the
107    /// `debug_assertions` cfg-attribute.
108    pub environment: Option<Cow<'static, str>>,
109    /// The sample rate for event submission. (0.0 - 1.0, defaults to 1.0)
110    pub sample_rate: f32,
111    /// The sample rate for tracing transactions. (0.0 - 1.0, defaults to 0.0)
112    pub traces_sample_rate: f32,
113    /// If given, called with a SamplingContext for each transaction to determine the sampling rate.
114    ///
115    /// Return a sample rate between 0.0 and 1.0 for the transaction in question.
116    /// Takes priority over the `sample_rate`.
117    pub traces_sampler: Option<Arc<TracesSampler>>,
118    /// Maximum number of breadcrumbs. (defaults to 100)
119    pub max_breadcrumbs: usize,
120    /// Attaches stacktraces to messages.
121    pub attach_stacktrace: bool,
122    /// If turned on, some information that can be considered PII is captured, such as potentially sensitive HTTP headers and user IP address in HTTP server integrations.
123    pub send_default_pii: bool,
124    /// The server name to be reported.
125    pub server_name: Option<Cow<'static, str>>,
126    /// Module prefixes that are always considered "in_app".
127    pub in_app_include: Vec<&'static str>,
128    /// Module prefixes that are never "in_app".
129    pub in_app_exclude: Vec<&'static str>,
130    // Integration options
131    /// A list of integrations to enable.
132    ///
133    /// See [`sentry::integrations`](integrations/index.html#installing-integrations) for
134    /// how to use this to enable extra integrations.
135    pub integrations: Vec<Arc<dyn Integration>>,
136    /// Whether to add default integrations.
137    ///
138    /// See [`sentry::integrations`](integrations/index.html#default-integrations) for
139    /// details how this works and interacts with manually installed integrations.
140    pub default_integrations: bool,
141    // Hooks
142    /// Callback that is executed before event sending.
143    pub before_send: Option<BeforeCallback<Event<'static>>>,
144    /// Callback that is executed for each Breadcrumb being added.
145    pub before_breadcrumb: Option<BeforeCallback<Breadcrumb>>,
146    /// Callback that is executed for each Log being added.
147    ///
148    /// This callback has no effect unless the `logs` feature is enabled at compile-time, as the
149    /// feature is a pre-requisite to capturing logs.
150    pub before_send_log: Option<BeforeCallback<Log>>,
151    // Transport options
152    /// The transport to use.
153    ///
154    /// This is typically either a boxed function taking the client options by
155    /// reference and returning a `Transport`, a boxed `Arc<Transport>` or
156    /// alternatively the `DefaultTransportFactory`.
157    pub transport: Option<Arc<dyn TransportFactory>>,
158    /// An optional HTTP proxy to use.
159    ///
160    /// This will default to the `http_proxy` environment variable.
161    pub http_proxy: Option<Cow<'static, str>>,
162    /// An optional HTTPS proxy to use.
163    ///
164    /// This will default to the `HTTPS_PROXY` environment variable
165    /// or `http_proxy` if that one exists.
166    pub https_proxy: Option<Cow<'static, str>>,
167    /// The timeout on client drop for draining events on shutdown.
168    pub shutdown_timeout: Duration,
169    /// Controls the maximum size of an HTTP request body that can be captured when using HTTP
170    /// server integrations. Needs `send_default_pii` to be enabled to have any effect.
171    pub max_request_body_size: MaxRequestBodySize,
172    /// Determines whether captured structured logs should be sent to Sentry (defaults to false).
173    ///
174    /// This setting has no effect unless the `logs` feature is enabled at compile-time, as the
175    /// feature is a pre-requisite to sending logs.
176    pub enable_logs: bool,
177    /// Determines whether metric capture APIs should capture metrics (defaults to true).
178    ///
179    /// Metric capture APIs are only available when the `metrics` feature is enabled at compile
180    /// time. If the `metrics` feature is enabled, set this to `false` to prevent metrics from
181    /// being captured and sent at runtime.
182    pub enable_metrics: bool,
183    /// Callback that is executed for each Metric before sending.
184    ///
185    /// This setting has no effect unless the `metrics` feature is enabled at compile-time,
186    /// as the feature is a prerequisite for capturing metrics.
187    pub before_send_metric: Option<BeforeCallback<Metric>>,
188    // Other options not documented in Unified API
189    /// Disable SSL verification.
190    ///
191    /// # Warning
192    ///
193    /// This introduces significant vulnerabilities, and should only be used as a last resort.
194    pub accept_invalid_certs: bool,
195    /// Enable Release Health Session tracking.
196    ///
197    /// When automatic session tracking is enabled, a new "user-mode" session
198    /// is started at the time of `sentry::init`, and will persist for the
199    /// application lifetime.
200    ///
201    /// This setting has no effect unless the `release-health` feature is enabled at compile-time,
202    /// as the feature is a pre-requisite to tracking sessions.
203    pub auto_session_tracking: bool,
204    /// Determine how Sessions are being tracked.
205    ///
206    /// This setting has no effect unless the `release-health` feature is enabled at compile-time,
207    /// as the feature is a pre-requisite to tracking sessions.
208    pub session_mode: SessionMode,
209    /// The user agent that should be reported.
210    pub user_agent: Cow<'static, str>,
211}
212
213impl ClientOptions {
214    /// Creates new Options.
215    pub fn new() -> Self {
216        Self::default()
217    }
218
219    /// Adds a configured integration to the options.
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// struct MyIntegration;
225    ///
226    /// impl sentry::Integration for MyIntegration {}
227    ///
228    /// let options = sentry::ClientOptions::new().add_integration(MyIntegration);
229    /// assert_eq!(options.integrations.len(), 1);
230    /// ```
231    #[must_use]
232    pub fn add_integration<I: Integration>(mut self, integration: I) -> Self {
233        self.integrations.push(Arc::new(integration));
234        self
235    }
236}
237
238impl fmt::Debug for ClientOptions {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        #[derive(Debug)]
241        struct BeforeSend;
242        let before_send = self.before_send.as_ref().map(|_| BeforeSend);
243        #[derive(Debug)]
244        struct BeforeBreadcrumb;
245        let before_breadcrumb = self.before_breadcrumb.as_ref().map(|_| BeforeBreadcrumb);
246        let before_send_log = {
247            #[derive(Debug)]
248            struct BeforeSendLog;
249            self.before_send_log.as_ref().map(|_| BeforeSendLog)
250        };
251        let before_send_metric = {
252            #[derive(Debug)]
253            struct BeforeSendMetric;
254            self.before_send_metric.as_ref().map(|_| BeforeSendMetric)
255        };
256        #[derive(Debug)]
257        struct TransportFactory;
258
259        let integrations: Vec<_> = self.integrations.iter().map(|i| i.name()).collect();
260
261        let mut debug_struct = f.debug_struct("ClientOptions");
262        debug_struct
263            .field("dsn", &self.dsn)
264            .field("debug", &self.debug)
265            .field("release", &self.release)
266            .field("environment", &self.environment)
267            .field("sample_rate", &self.sample_rate)
268            .field("traces_sample_rate", &self.traces_sample_rate)
269            .field(
270                "traces_sampler",
271                &self
272                    .traces_sampler
273                    .as_ref()
274                    .map(|arc| std::ptr::addr_of!(**arc)),
275            )
276            .field("max_breadcrumbs", &self.max_breadcrumbs)
277            .field("attach_stacktrace", &self.attach_stacktrace)
278            .field("send_default_pii", &self.send_default_pii)
279            .field("server_name", &self.server_name)
280            .field("in_app_include", &self.in_app_include)
281            .field("in_app_exclude", &self.in_app_exclude)
282            .field("integrations", &integrations)
283            .field("default_integrations", &self.default_integrations)
284            .field("before_send", &before_send)
285            .field("before_breadcrumb", &before_breadcrumb)
286            .field("transport", &TransportFactory)
287            .field("http_proxy", &self.http_proxy)
288            .field("https_proxy", &self.https_proxy)
289            .field("shutdown_timeout", &self.shutdown_timeout)
290            .field("accept_invalid_certs", &self.accept_invalid_certs)
291            .field("auto_session_tracking", &self.auto_session_tracking)
292            .field("session_mode", &self.session_mode)
293            .field("enable_logs", &self.enable_logs)
294            .field("before_send_log", &before_send_log)
295            .field("enable_metrics", &self.enable_metrics)
296            .field("before_send_metric", &before_send_metric)
297            .field("user_agent", &self.user_agent)
298            .finish()
299    }
300}
301
302impl Default for ClientOptions {
303    fn default() -> ClientOptions {
304        ClientOptions {
305            dsn: None,
306            debug: false,
307            release: None,
308            environment: None,
309            sample_rate: 1.0,
310            traces_sample_rate: 0.0,
311            traces_sampler: None,
312            max_breadcrumbs: 100,
313            attach_stacktrace: false,
314            send_default_pii: false,
315            server_name: None,
316            in_app_include: vec![],
317            in_app_exclude: vec![],
318            integrations: vec![],
319            default_integrations: true,
320            before_send: None,
321            before_breadcrumb: None,
322            transport: None,
323            http_proxy: None,
324            https_proxy: None,
325            shutdown_timeout: Duration::from_secs(2),
326            accept_invalid_certs: false,
327            auto_session_tracking: false,
328            session_mode: SessionMode::Application,
329            user_agent: Cow::Borrowed(USER_AGENT),
330            max_request_body_size: MaxRequestBodySize::Medium,
331            enable_logs: true,
332            before_send_log: None,
333            enable_metrics: true,
334            before_send_metric: None,
335        }
336    }
337}
338
339impl<T: IntoDsn> From<(T, ClientOptions)> for ClientOptions {
340    fn from((into_dsn, mut opts): (T, ClientOptions)) -> ClientOptions {
341        opts.dsn = into_dsn.into_dsn().expect("invalid value for DSN");
342        opts
343    }
344}
345
346impl<T: IntoDsn> From<T> for ClientOptions {
347    fn from(into_dsn: T) -> ClientOptions {
348        ClientOptions {
349            dsn: into_dsn.into_dsn().expect("invalid value for DSN"),
350            ..ClientOptions::default()
351        }
352    }
353}