errsight 0.1.1

Rust client for ErrSight error tracking — captures panics, errors, and log/tracing events and ships them to the ErrSight API from a background thread.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Client configuration: [`Config`] and its [`ConfigBuilder`].
//!
//! Defaults mirror the Ruby SDK so behaviour is predictable across languages:
//! `min_level = Warning`, batch of 10, 2-second flush cadence, 1,000-event
//! queue, 5-second HTTP and shutdown timeouts. Anything not set explicitly
//! falls back to `ERRSIGHT_*` environment variables, then to these defaults.

use std::sync::Arc;
use std::time::Duration;

use crate::event::Event;
use crate::level::Level;
use crate::transport::Transport;

/// A `before_send` hook: final-mile filter run on the calling thread before an
/// event is queued. Return `Some(event)` (possibly mutated) to send, or `None`
/// to drop.
///
/// Notes:
/// - The `min_level` gate runs *before* this hook (events below the threshold
///   are never built), so changing `event.level` here does not re-open the
///   gate. `None` is the only way the hook drops an event.
/// - On panic, behaviour follows [`Config::before_send_fail_open`]: by default
///   the event is dropped (fail-closed), so a scrubber bug can't leak the
///   un-scrubbed original.
pub type BeforeSend = Arc<dyn Fn(Event) -> Option<Event> + Send + Sync>;

/// Immutable client configuration. Build with [`Config::builder`] or
/// [`Config::from_env`]; once handed to [`crate::init`] it lives behind an
/// `Arc` and never changes.
#[derive(Clone)]
pub struct Config {
    /// Project write key (`elp_…`). Without it the client is disabled.
    pub api_key: Option<String>,
    /// Environment tag attached to every event. Default `"production"`.
    pub environment: String,
    /// Release / version identifier. Default from `ERRSIGHT_RELEASE`.
    pub release: Option<String>,
    /// API base URL. Default `https://errsight.com`.
    pub host: String,
    /// Drop events below this level before building them. Default `Warning`.
    pub min_level: Level,
    /// Per-request HTTP timeout. Default 5s.
    pub timeout: Duration,
    /// Master switch. Combined with a present API key to decide `enabled()`.
    pub enabled: bool,
    /// Events per HTTP request. Default 10.
    pub batch_size: usize,
    /// Background flush cadence. Default 2s.
    pub flush_interval: Duration,
    /// Drop new events once this many are queued. Default 1,000.
    pub max_queue_size: usize,
    /// Max time the background thread spends draining on shutdown. Default 5s.
    pub shutdown_timeout: Duration,
    /// Ring-buffer cap for breadcrumbs per scope. Default 100.
    pub max_breadcrumbs: usize,
    /// Attach the current backtrace to `capture_message` events too, not just
    /// errors/panics. Default false.
    pub attach_stacktrace: bool,
    /// Install a panic hook on [`crate::init`] so panics are captured as fatal
    /// events. Default true — capturing panics is the headline feature, and
    /// the hook chains the previous one rather than replacing it. Opt out if
    /// you manage the panic hook yourself.
    pub panic_hook: bool,
    /// Path substrings that force a frame to be treated as `in_app`.
    pub in_app_include: Vec<String>,
    /// Path substrings that force a frame to be treated as **not** `in_app`.
    pub in_app_exclude: Vec<String>,
    /// Emit internal diagnostics to stderr (queue-full drops, send failures).
    /// Default false. Enable while debugging SDK behaviour.
    pub debug: bool,
    /// Optional `before_send` filter.
    pub before_send: Option<BeforeSend>,
    /// What to do when `before_send` panics. Default `false` (fail-closed): the
    /// event is dropped, because `before_send` is the PII/secret scrubber and
    /// shipping the un-scrubbed original would be a leak. Set `true` to send the
    /// event unmodified instead (availability over confidentiality).
    pub before_send_fail_open: bool,
    /// Permit sending over cleartext `http://` to a non-local host without a
    /// warning. Default `false` — the default transport carries the API key and
    /// PII, so a plaintext downgrade is warned about loudly unless opted in.
    pub allow_insecure_transport: bool,
    /// Optional transport override (for tests or a custom HTTP stack). When
    /// `None`, the built-in `ureq` transport is used.
    pub transport: Option<Arc<dyn Transport>>,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            api_key: None,
            environment: "production".to_string(),
            release: None,
            host: "https://errsight.com".to_string(),
            min_level: Level::Warning,
            timeout: Duration::from_secs(5),
            enabled: true,
            batch_size: 10,
            flush_interval: Duration::from_secs(2),
            max_queue_size: 1_000,
            shutdown_timeout: Duration::from_secs(5),
            max_breadcrumbs: 100,
            attach_stacktrace: false,
            panic_hook: true,
            in_app_include: Vec::new(),
            in_app_exclude: Vec::new(),
            debug: false,
            before_send: None,
            before_send_fail_open: false,
            allow_insecure_transport: false,
            transport: None,
        }
    }
}

impl Config {
    /// Start a builder seeded from environment variables (see [`Config::from_env`]).
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder {
            config: Config::from_env(),
        }
    }

    /// A config populated from `ERRSIGHT_*` environment variables, falling back
    /// to defaults:
    ///
    /// - `ERRSIGHT_API_KEY`
    /// - `ERRSIGHT_ENV` → environment (default `production`)
    /// - `ERRSIGHT_HOST` → host (default `https://errsight.com`)
    /// - `ERRSIGHT_RELEASE` → release
    /// - `ERRSIGHT_DEBUG` (`1`/`true`) → debug logging
    pub fn from_env() -> Self {
        let mut c = Config::default();
        if let Ok(k) = std::env::var("ERRSIGHT_API_KEY") {
            if !k.trim().is_empty() {
                c.api_key = Some(k);
            }
        }
        if let Ok(env) = std::env::var("ERRSIGHT_ENV") {
            if !env.trim().is_empty() {
                c.environment = env;
            }
        }
        if let Ok(host) = std::env::var("ERRSIGHT_HOST") {
            if !host.trim().is_empty() {
                c.host = host;
            }
        }
        if let Ok(rel) = std::env::var("ERRSIGHT_RELEASE") {
            if !rel.trim().is_empty() {
                c.release = Some(rel);
            }
        }
        if let Ok(dbg) = std::env::var("ERRSIGHT_DEBUG") {
            c.debug = matches!(
                dbg.trim().to_ascii_lowercase().as_str(),
                "1" | "true" | "yes"
            );
        }
        c
    }

    /// True when the client should actually send: enabled flag set and a
    /// non-blank API key present. Capture is a cheap no-op otherwise, so apps
    /// can ship `capture_*` calls unconditionally.
    pub fn enabled(&self) -> bool {
        self.enabled
            && self
                .api_key
                .as_deref()
                .map(|k| !k.trim().is_empty())
                .unwrap_or(false)
    }

    /// The full events endpoint, e.g. `https://errsight.com/api/v1/events`.
    pub fn events_endpoint(&self) -> String {
        format!("{}/api/v1/events", self.host.trim_end_matches('/'))
    }

    /// True if the host is plaintext `http://` and not a loopback address —
    /// i.e. sending would leak the API key and PII over the wire. Loopback
    /// (`localhost` / `127.0.0.1` / `[::1]`) is exempt since it never leaves the host.
    pub fn is_insecure_remote_host(&self) -> bool {
        let host = self.host.trim();
        let Some(rest) = host
            .strip_prefix("http://")
            .or_else(|| host.strip_prefix("HTTP://"))
        else {
            return false; // https (or scheme-less) — not a cleartext downgrade
        };
        let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
        // Strip an optional port for the loopback comparison.
        let hostname = authority.rsplit_once(':').map_or(authority, |(h, _)| h);
        let is_loopback = matches!(hostname, "localhost" | "127.0.0.1" | "[::1]" | "::1");
        !is_loopback
    }
}

impl std::fmt::Debug for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Never print the API key; redact it. before_send/transport are
        // closures/trait objects with no useful Debug.
        f.debug_struct("Config")
            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
            .field("environment", &self.environment)
            .field("release", &self.release)
            .field("host", &self.host)
            .field("min_level", &self.min_level)
            .field("timeout", &self.timeout)
            .field("enabled", &self.enabled)
            .field("batch_size", &self.batch_size)
            .field("flush_interval", &self.flush_interval)
            .field("max_queue_size", &self.max_queue_size)
            .field("shutdown_timeout", &self.shutdown_timeout)
            .field("max_breadcrumbs", &self.max_breadcrumbs)
            .field("attach_stacktrace", &self.attach_stacktrace)
            .field("panic_hook", &self.panic_hook)
            .field("in_app_include", &self.in_app_include)
            .field("in_app_exclude", &self.in_app_exclude)
            .field("debug", &self.debug)
            .field("before_send_fail_open", &self.before_send_fail_open)
            .field("allow_insecure_transport", &self.allow_insecure_transport)
            .field("before_send", &self.before_send.as_ref().map(|_| "<fn>"))
            .field("transport", &self.transport.as_ref().map(|_| "<custom>"))
            .finish()
    }
}

/// Fluent builder for [`Config`]. Every setter returns `self`; finish with
/// [`ConfigBuilder::build`].
pub struct ConfigBuilder {
    config: Config,
}

impl ConfigBuilder {
    /// Start from defaults only, ignoring environment variables.
    pub fn from_default() -> Self {
        ConfigBuilder {
            config: Config::default(),
        }
    }

    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.config.api_key = Some(key.into());
        self
    }
    pub fn environment(mut self, env: impl Into<String>) -> Self {
        self.config.environment = env.into();
        self
    }
    pub fn release(mut self, release: impl Into<String>) -> Self {
        self.config.release = Some(release.into());
        self
    }
    pub fn host(mut self, host: impl Into<String>) -> Self {
        self.config.host = host.into();
        self
    }
    pub fn min_level(mut self, level: Level) -> Self {
        self.config.min_level = level;
        self
    }
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.config.timeout = timeout;
        self
    }
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }
    pub fn batch_size(mut self, n: usize) -> Self {
        // Clamp to the backend's 100-event-per-request limit; the send site
        // also enforces this, but clamp here so the configured value is honest.
        self.config.batch_size = n.clamp(1, 100);
        self
    }
    pub fn flush_interval(mut self, interval: Duration) -> Self {
        self.config.flush_interval = interval;
        self
    }
    pub fn max_queue_size(mut self, n: usize) -> Self {
        self.config.max_queue_size = n.max(1);
        self
    }
    pub fn shutdown_timeout(mut self, timeout: Duration) -> Self {
        self.config.shutdown_timeout = timeout;
        self
    }
    pub fn max_breadcrumbs(mut self, n: usize) -> Self {
        self.config.max_breadcrumbs = n;
        self
    }
    pub fn attach_stacktrace(mut self, yes: bool) -> Self {
        self.config.attach_stacktrace = yes;
        self
    }
    /// Whether [`crate::init`] should install the panic-capturing hook. Default true.
    pub fn panic_hook(mut self, yes: bool) -> Self {
        self.config.panic_hook = yes;
        self
    }
    pub fn in_app_include(mut self, paths: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.config
            .in_app_include
            .extend(paths.into_iter().map(Into::into));
        self
    }
    pub fn in_app_exclude(mut self, paths: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.config
            .in_app_exclude
            .extend(paths.into_iter().map(Into::into));
        self
    }
    pub fn debug(mut self, yes: bool) -> Self {
        self.config.debug = yes;
        self
    }
    /// Set the `before_send` filter.
    pub fn before_send<F>(mut self, f: F) -> Self
    where
        F: Fn(Event) -> Option<Event> + Send + Sync + 'static,
    {
        self.config.before_send = Some(Arc::new(f));
        self
    }
    /// If `true`, a panicking `before_send` sends the event unmodified instead
    /// of dropping it. Default `false` (fail-closed) — see [`Config::before_send_fail_open`].
    pub fn before_send_fail_open(mut self, yes: bool) -> Self {
        self.config.before_send_fail_open = yes;
        self
    }
    /// Permit cleartext `http://` to a non-local host without a startup warning.
    /// Default `false`.
    pub fn allow_insecure_transport(mut self, yes: bool) -> Self {
        self.config.allow_insecure_transport = yes;
        self
    }
    /// Inject a custom transport (tests, or a non-`ureq` HTTP stack).
    pub fn transport(mut self, transport: Arc<dyn Transport>) -> Self {
        self.config.transport = Some(transport);
        self
    }

    pub fn build(self) -> Config {
        self.config
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn disabled_without_key() {
        let c = ConfigBuilder::from_default().build();
        assert!(!c.enabled());
        let c = ConfigBuilder::from_default().api_key("elp_x").build();
        assert!(c.enabled());
        let c = ConfigBuilder::from_default().api_key("  ").build();
        assert!(!c.enabled(), "blank key must not enable");
    }

    #[test]
    fn endpoint_trims_trailing_slash() {
        let c = ConfigBuilder::from_default()
            .host("https://example.com/")
            .build();
        assert_eq!(c.events_endpoint(), "https://example.com/api/v1/events");
    }

    #[test]
    fn debug_redacts_key() {
        let c = ConfigBuilder::from_default().api_key("elp_secret").build();
        let s = format!("{c:?}");
        assert!(!s.contains("elp_secret"));
        assert!(s.contains("redacted"));
    }

    #[test]
    fn batch_size_clamped_to_backend_limit() {
        assert_eq!(
            ConfigBuilder::from_default()
                .batch_size(500)
                .build()
                .batch_size,
            100
        );
        assert_eq!(
            ConfigBuilder::from_default()
                .batch_size(0)
                .build()
                .batch_size,
            1
        );
        assert_eq!(
            ConfigBuilder::from_default()
                .batch_size(25)
                .build()
                .batch_size,
            25
        );
    }

    #[test]
    fn insecure_host_detection() {
        let insecure = |h: &str| {
            ConfigBuilder::from_default()
                .host(h)
                .build()
                .is_insecure_remote_host()
        };
        // Plaintext to a remote host is insecure.
        assert!(insecure("http://errsight.example.com"));
        assert!(insecure("http://10.0.0.5:8080/ingest"));
        // https is fine.
        assert!(!insecure("https://errsight.com"));
        // Loopback over http is exempt (never leaves the host).
        assert!(!insecure("http://localhost:3000"));
        assert!(!insecure("http://127.0.0.1:3000"));
        assert!(!insecure("http://[::1]:3000"));
    }
}