oluso 0.2.0

AI-powered error monitoring for Rust applications: automatic panic reporting, breadcrumb tracking, and intelligent error grouping.
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;

use serde::Serialize;

use crate::fingerprint::generate_fingerprint;
use crate::queue::OfflineQueue;
use crate::rate_limiter::RateLimiter;
use crate::sanitizer::Sanitizer;
use crate::scope::ScopeManager;
use crate::time::now_millis;
use crate::transport::send_error_report;
use crate::types::{
    ErrorContext, ErrorReport, ExceptionDetails, NewBreadcrumb, Options, RequestContext, SdkInfo,
    ServerContext, Severity, UserContext,
};

/// The Oluso client. Cheap to clone (everything inside is either `Copy`,
/// an `Arc`, or a handle type that's already internally reference-counted),
/// but is normally held as `Arc<Client>` -- via [`Client::new`] -- since
/// [`Client::install_panic_hook`] needs a `'static` handle it can move into
/// the global panic hook.
pub struct Client {
    pub(crate) options: Options,
    pub(crate) http: reqwest::Client,
    scope: ScopeManager,
    pub(crate) sanitizer: Sanitizer,
    rate_limiter: RateLimiter,
    queue: OfflineQueue,
}

impl Client {
    pub fn new(options: Options) -> Arc<Self> {
        let sanitizer = Sanitizer::new(&options.sensitive_keys);
        let rate_limiter = RateLimiter::new(options.max_errors_per_minute);
        let queue = OfflineQueue::new(options.max_queue_size);
        let scope = ScopeManager::new(options.max_breadcrumbs);
        let http = reqwest::Client::new();

        Arc::new(Self {
            options,
            http,
            scope,
            sanitizer,
            rate_limiter,
            queue,
        })
    }

    /// Runs `f` with a fresh, request-scoped breadcrumb/user/context store,
    /// built on `tokio::task_local!`. Unlike Node's `AsyncLocalStorage`,
    /// this only follows a single top-level task's `.await`s -- it does not
    /// propagate into a `tokio::spawn`ed task. Re-enter the scope
    /// explicitly inside spawned work if it should still report against
    /// the same request.
    pub async fn run_in_scope<F, Fut, T>(&self, f: F) -> T
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = T>,
    {
        self.scope.run(f).await
    }

    pub fn add_breadcrumb(&self, breadcrumb: NewBreadcrumb) {
        self.scope.add_breadcrumb(breadcrumb);
    }

    pub fn set_user_context(&self, user: UserContext) {
        self.scope.set_user_context(user);
    }

    /// Attaches an arbitrary, serializable value as custom context on the
    /// next report. Silently drops the value (logging to stderr if
    /// `log_to_console` is set) if it can't be serialized to JSON -- there's
    /// nothing more actionable to do at a call site that can't return a
    /// `Result` without making every breadcrumb call fallible.
    pub fn set_custom_context(&self, key: impl Into<String>, value: impl Serialize) {
        match serde_json::to_value(value) {
            Ok(json) => self.scope.set_custom_context(key, json),
            Err(err) => {
                if self.options.log_to_console {
                    eprintln!("[Oluso] Failed to serialize custom context: {err}");
                }
            }
        }
    }

    /// Reports a Rust error. The reported error type is the concrete type's
    /// short name (via `std::any::type_name`), which only works when `E` is
    /// known at the call site -- a `Box<dyn Error>` reports as `Box<dyn
    /// Error>` rather than the type it was built from, since that
    /// information is erased. For that case, use
    /// [`Client::capture_dyn_error`] and supply the type name yourself.
    pub async fn capture_error<E: std::error::Error>(&self, err: &E) {
        let error_type = type_short_name::<E>();
        self.capture_with_exception(
            &error_type,
            err.to_string(),
            None,
            None,
            None,
            exception_details(&error_type, err),
        )
        .await;
    }

    /// Same as [`Client::capture_error`], but for a type-erased error
    /// (`Box<dyn Error>`, `anyhow::Error`, ...) where you have to supply the
    /// error type name yourself since it can't be recovered from the trait
    /// object.
    pub async fn capture_dyn_error(&self, error_type: &str, err: &dyn std::error::Error) {
        self.capture_with_exception(
            error_type,
            err.to_string(),
            None,
            None,
            None,
            exception_details(error_type, err),
        )
        .await;
    }

    /// Reports an error together with the request it happened during.
    /// Intended for framework integrations -- the core crate has no
    /// framework-specific `RequestContext` builder, so callers construct
    /// one from whatever request type their framework hands them.
    pub async fn capture_error_with_request<E: std::error::Error>(
        &self,
        err: &E,
        request: RequestContext,
    ) {
        let error_type = type_short_name::<E>();
        self.capture_with_exception(
            &error_type,
            err.to_string(),
            None,
            None,
            Some(request),
            exception_details(&error_type, err),
        )
        .await;
    }

    pub async fn capture_message(&self, message: impl Into<String>, severity: Severity) {
        self.capture("Message", message.into(), None, Some(severity), None)
            .await;
    }

    /// Low-level entry point the ergonomic `capture_*` methods above are
    /// built on. Exposed directly so framework integrations built outside
    /// this crate can report with a specific severity/stack trace/request
    /// without losing access to any of it.
    pub async fn capture(
        &self,
        error_type: &str,
        message: impl Into<String>,
        stack_trace: Option<String>,
        severity: Option<Severity>,
        request: Option<RequestContext>,
    ) {
        let message = message.into();
        let exception = ExceptionDetails {
            r#type: error_type.to_string(),
            message: truncate(&message, 4000),
            stack_trace: stack_trace.as_deref().map(|s| truncate(s, 16000)),
            attributes: HashMap::new(),
            causes: Vec::new(),
        };
        self.capture_with_exception(
            error_type,
            message,
            stack_trace,
            severity,
            request,
            exception,
        )
        .await;
    }

    async fn capture_with_exception(
        &self,
        error_type: &str,
        message: String,
        stack_trace: Option<String>,
        severity: Option<Severity>,
        request: Option<RequestContext>,
        exception: ExceptionDetails,
    ) {
        if let Some(should_report) = &self.options.should_report {
            if !should_report(&message) {
                return;
            }
        }

        if !self.rate_limiter.can_send() {
            if self.options.log_to_console {
                eprintln!("[Oluso] Rate limit exceeded, error not reported");
            }
            return;
        }

        if self.options.log_to_console {
            eprintln!("[Oluso] {error_type}: {message}");
        }

        let (breadcrumbs, user, custom) = self.scope.snapshot();
        let context = ErrorContext {
            request: request.map(|r| self.sanitize_request(r)),
            user,
            server: server_context(),
            custom,
            breadcrumbs,
        };

        let fingerprint = match &self.options.fingerprint {
            Some(f) => f(&message, &context),
            None => generate_fingerprint(error_type, &message, stack_trace.as_deref()),
        };

        let report = ErrorReport {
            schema_version: 2,
            title: generate_error_title(&message, error_type),
            message,
            stack_trace,
            environment: self.options.environment.clone(),
            severity: severity.unwrap_or(self.options.default_severity),
            tags: self.options.tags.clone(),
            fingerprint,
            context,
            timestamp: now_millis(),
            exception,
            sdk: SdkInfo {
                name: "oluso-rust".to_string(),
                version: env!("CARGO_PKG_VERSION").to_string(),
                language: "rust".to_string(),
            },
        };

        self.send_report(report).await;
    }

    /// Flushes any reports that failed to send and are waiting in the
    /// offline queue. There's no background timer driving this
    /// automatically -- call it wherever your application already has a
    /// natural "done with this unit of work" point (end of a request, a
    /// graceful-shutdown hook, ...).
    pub async fn flush(&self) {
        self.queue
            .process(|report| async move {
                send_error_report(
                    &self.http,
                    &self.options.endpoint,
                    &self.options.api_key,
                    self.options.timeout,
                    &report,
                )
                .await
            })
            .await;
    }

    /// Installs a global panic hook that reports panics as critical errors.
    /// Chains after (doesn't replace) whatever hook was previously
    /// installed, so the default "thread panicked at ..." stderr output
    /// still happens.
    ///
    /// Reporting a panic needs an async call, but panic hooks are strictly
    /// synchronous -- this works by spawning onto the current Tokio runtime
    /// (`tokio::runtime::Handle::try_current()`), which is available in the
    /// overwhelmingly common case of panicking inside a request handler on
    /// an async web framework. If no runtime is current when the panic
    /// happens (e.g. a panic on a plain `std::thread`), the panic is only
    /// logged to stderr, not reported -- there's no runtime to run the send
    /// on and spinning one up just for this would outlive the panic hook
    /// itself in surprising ways.
    pub fn install_panic_hook(self: &Arc<Self>) {
        let client = Arc::clone(self);
        let previous = std::panic::take_hook();

        std::panic::set_hook(Box::new(move |info| {
            previous(info);

            let message = panic_message(info);
            let location = info
                .location()
                .map(|l| format!("panicked at {}:{}:{}", l.file(), l.line(), l.column()));
            let backtrace = std::backtrace::Backtrace::force_capture().to_string();
            let stack_trace = Some(match location {
                Some(loc) => format!("{loc}\n{backtrace}"),
                None => backtrace,
            });

            let client = Arc::clone(&client);
            match tokio::runtime::Handle::try_current() {
                Ok(handle) => {
                    handle.spawn(async move {
                        client
                            .capture(
                                "panic",
                                message,
                                stack_trace,
                                Some(Severity::Critical),
                                None,
                            )
                            .await;
                    });
                }
                Err(_) => {
                    if client.options.log_to_console {
                        eprintln!(
                            "[Oluso] Panic occurred outside a Tokio runtime; unable to report it: {message}"
                        );
                    }
                }
            }
        }));
    }

    fn sanitize_request(&self, request: RequestContext) -> RequestContext {
        RequestContext {
            url: request.url,
            method: request.method,
            headers: request
                .headers
                .map(|headers| self.sanitizer.sanitize_string_map(&headers)),
            query: request
                .query
                .map(|query| self.sanitizer.sanitize_string_map(&query)),
            body: request
                .body
                .map(|body| self.sanitizer.sanitize_value(&body)),
        }
    }

    async fn send_report(&self, report: ErrorReport) {
        let result = send_error_report(
            &self.http,
            &self.options.endpoint,
            &self.options.api_key,
            self.options.timeout,
            &report,
        )
        .await;

        match result {
            Ok(()) => {
                if self.options.enable_offline_queue && !self.queue.is_empty().await {
                    self.queue
                        .process(|queued| async move {
                            send_error_report(
                                &self.http,
                                &self.options.endpoint,
                                &self.options.api_key,
                                self.options.timeout,
                                &queued,
                            )
                            .await
                        })
                        .await;
                }
            }
            Err(err) => {
                if self.options.log_to_console {
                    eprintln!("[Oluso] {err}");
                }
                if self.options.enable_offline_queue {
                    self.queue.enqueue(report).await;
                }
            }
        }
    }
}

fn truncate(value: &str, max: usize) -> String {
    if value.chars().count() <= max {
        return value.to_string();
    }
    format!(
        "{}... [truncated]",
        value.chars().take(max).collect::<String>()
    )
}

fn exception_details(error_type: &str, err: &dyn std::error::Error) -> ExceptionDetails {
    let mut root = ExceptionDetails {
        r#type: error_type.to_string(),
        message: truncate(&err.to_string(), 4000),
        stack_trace: Some(truncate(&format!("{err:?}"), 16000)),
        attributes: HashMap::new(),
        causes: Vec::new(),
    };
    let mut cursor = err.source();
    let mut chain = Vec::new();
    for _ in 0..5 {
        let Some(cause) = cursor else { break };
        chain.push(ExceptionDetails {
            r#type: std::any::type_name_of_val(cause).to_string(),
            message: truncate(&cause.to_string(), 4000),
            stack_trace: Some(truncate(&format!("{cause:?}"), 16000)),
            attributes: HashMap::new(),
            causes: Vec::new(),
        });
        cursor = cause.source();
    }
    root.causes = chain;
    root
}

fn type_short_name<E: ?Sized>() -> String {
    let full = std::any::type_name::<E>();
    full.rsplit("::").next().unwrap_or(full).to_string()
}

fn generate_error_title(message: &str, error_type: &str) -> String {
    let first_line = message.lines().next().unwrap_or("").trim();
    if first_line.is_empty() {
        return format!("{error_type} Error");
    }
    if first_line.chars().count() <= 100 {
        first_line.to_string()
    } else {
        let truncated: String = first_line.chars().take(97).collect();
        format!("{truncated}...")
    }
}

fn server_context() -> ServerContext {
    ServerContext {
        hostname: gethostname::gethostname().to_string_lossy().to_string(),
        os: std::env::consts::OS.to_string(),
        arch: std::env::consts::ARCH.to_string(),
        pid: std::process::id(),
    }
}

fn panic_message(info: &std::panic::PanicHookInfo<'_>) -> String {
    if let Some(s) = info.payload().downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = info.payload().downcast_ref::<String>() {
        s.clone()
    } else {
        "unknown panic payload".to_string()
    }
}

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

    #[test]
    fn generates_a_short_title_from_the_first_message_line() {
        assert_eq!(generate_error_title("boom\nwith detail", "Error"), "boom");
    }

    #[test]
    fn truncates_long_titles_at_100_characters() {
        let long = "x".repeat(150);
        let title = generate_error_title(&long, "Error");
        assert_eq!(title.chars().count(), 100);
        assert!(title.ends_with("..."));
    }

    #[test]
    fn falls_back_to_the_error_type_when_the_message_is_empty() {
        assert_eq!(
            generate_error_title("", "TimeoutError"),
            "TimeoutError Error"
        );
    }

    #[test]
    fn type_short_name_strips_the_module_path() {
        assert_eq!(type_short_name::<std::io::Error>(), "Error");
    }
}