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
423
424
425
426
427
428
429
430
431
432
433
//! Backtrace capture and frame parsing.
//!
//! Turns a `backtrace::Backtrace` into the structured [`Frame`]s the backend
//! uses for grouping (`metadata["exception_frames"]`) and source-context
//! display. Two judgement calls live here:
//!
//! 1. **Noise trimming.** A backtrace captured from inside the SDK or a panic
//!    hook starts with our own frames and the panic runtime. We drop that
//!    contiguous leading run so the top frame is the user's call site.
//! 2. **`in_app` classification.** Frames under `~/.cargo`, the rustc sysroot,
//!    or a registry checkout are dependencies/std; everything else is your
//!    code. Callers can override with `in_app_include` / `in_app_exclude`.

use crate::config::Config;
use crate::event::Frame;

/// Hard cap on frames per event. A runaway recursion can produce tens of
/// thousands of frames; without a cap the event blows past the 512 KB
/// ingestion limit. The backend and peer SDKs settle on 50.
pub const MAX_FRAMES: usize = 50;

/// Capture the current backtrace and parse it into frames, trimming the SDK /
/// panic-runtime prefix and attaching source context to `in_app` frames.
pub fn current_frames(config: &Config) -> Vec<Frame> {
    let bt = backtrace::Backtrace::new();
    frames_from(&bt, config)
}

/// Parse an already-captured backtrace into frames. Used by the panic hook
/// (which captures at the panic site) and by `current_frames`.
pub fn frames_from(bt: &backtrace::Backtrace, config: &Config) -> Vec<Frame> {
    // Flatten frame→symbols (inlined calls produce multiple symbols per frame),
    // most-recent-first, the order `backtrace` already yields.
    let mut raw: Vec<RawFrame> = Vec::new();
    for frame in bt.frames() {
        for symbol in frame.symbols() {
            let function = symbol
                .name()
                // `{:#}` is the demangled form without the trailing `::h<hash>`.
                .map(|n| format!("{n:#}"));
            let filename = symbol.filename().map(|p| p.display().to_string());
            raw.push(RawFrame {
                function,
                filename,
                lineno: symbol.lineno(),
                colno: symbol.colno(),
            });
        }
    }
    finalize_raw(raw, config)
}

/// Parse the textual `Display` of a `std::backtrace::Backtrace` into frames.
///
/// `std::backtrace::Backtrace` exposes no structured frame API, so the
/// `anyhow` integration hands us its rendered form. The format is a numbered
/// list of `N: function` lines, each optionally followed by an indented
/// `at file:line:col` line. Best-effort: anything we can't parse is skipped.
#[cfg(feature = "anyhow")]
pub(crate) fn parse_std_backtrace(text: &str, config: &Config) -> Vec<Frame> {
    let mut raw: Vec<RawFrame> = Vec::new();
    let mut pending: Option<RawFrame> = None;

    for line in text.lines() {
        let trimmed = line.trim_start();
        if let Some(function) = parse_frame_header(trimmed) {
            if let Some(prev) = pending.take() {
                raw.push(prev);
            }
            pending = Some(RawFrame {
                function: Some(function),
                filename: None,
                lineno: None,
                colno: None,
            });
        } else if let Some((file, lineno, colno)) = parse_at_line(trimmed) {
            if let Some(p) = pending.as_mut() {
                p.filename = Some(file);
                p.lineno = lineno;
                p.colno = colno;
            }
        }
    }
    if let Some(prev) = pending.take() {
        raw.push(prev);
    }
    finalize_raw(raw, config)
}

/// `0: some::function` → `Some("some::function")`. The leading token must be
/// digits followed by a colon, which is what distinguishes a frame header from
/// an `at …` location line.
#[cfg(feature = "anyhow")]
fn parse_frame_header(s: &str) -> Option<String> {
    let (idx, rest) = s.split_once(':')?;
    if idx.is_empty() || !idx.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let func = rest.trim();
    if func.is_empty() {
        None
    } else {
        Some(func.to_string())
    }
}

/// `at /path/to/file.rs:10:5` → `("/path/to/file.rs", Some(10), Some(5))`.
/// Parses trailing `:line:col` / `:line` from the right so paths containing
/// colons (Windows drives) survive.
#[cfg(feature = "anyhow")]
fn parse_at_line(s: &str) -> Option<(String, Option<u32>, Option<u32>)> {
    let rest = s.strip_prefix("at ")?.trim();
    if let Some((head, tail)) = rest.rsplit_once(':') {
        if let Ok(n) = tail.parse::<u32>() {
            if let Some((head2, mid)) = head.rsplit_once(':') {
                if let Ok(m) = mid.parse::<u32>() {
                    return Some((head2.to_string(), Some(m), Some(n)));
                }
            }
            return Some((head.to_string(), Some(n), None));
        }
    }
    Some((rest.to_string(), None, None))
}

/// Shared tail of frame building: trim SDK/runtime noise, cap, classify
/// `in_app`, shorten the display path, and attach source context.
fn finalize_raw(mut raw: Vec<RawFrame>, config: &Config) -> Vec<Frame> {
    trim_leading_noise(&mut raw);
    let project_root = project_root();

    raw.into_iter()
        .take(MAX_FRAMES)
        .map(|rf| {
            let in_app = classify_in_app(rf.filename.as_deref(), rf.function.as_deref(), config);
            let display = rf
                .filename
                .as_deref()
                .map(|f| relative_filename(f, project_root.as_deref()))
                .unwrap_or_else(|| "<unknown>".to_string());

            let mut frame = Frame {
                filename: display,
                abs_path: rf.filename.clone(),
                lineno: rf.lineno,
                colno: rf.colno,
                function: rf.function,
                in_app,
                pre_context: None,
                context_line: None,
                post_context: None,
            };

            // Source context is the debugging differentiator, but only for our
            // own code and only when the source is actually on disk (dev /
            // CI). In production the files usually aren't present and fetch
            // returns None — that's fine, the frame just lacks context.
            if in_app {
                if let (Some(path), Some(line)) = (rf.filename.as_deref(), rf.lineno) {
                    if let Some(ctx) = crate::source::fetch(path, line) {
                        frame.pre_context = Some(ctx.pre);
                        frame.context_line = Some(ctx.line);
                        frame.post_context = Some(ctx.post);
                    }
                }
            }
            frame
        })
        .collect()
}

/// Render frames as a newline-joined string for the legacy `backtrace` field.
pub fn frames_to_string(frames: &[Frame]) -> String {
    let mut out = String::new();
    for f in frames {
        let func = f.function.as_deref().unwrap_or("<unknown>");
        match (f.lineno, f.colno) {
            (Some(l), Some(c)) => {
                out.push_str(&format!("{func}\n    at {}:{l}:{c}\n", f.filename));
            }
            (Some(l), None) => {
                out.push_str(&format!("{func}\n    at {}:{l}\n", f.filename));
            }
            _ => {
                out.push_str(&format!("{func}\n    at {}\n", f.filename));
            }
        }
    }
    out
}

struct RawFrame {
    function: Option<String>,
    filename: Option<String>,
    lineno: Option<u32>,
    colno: Option<u32>,
}

/// Drop the contiguous run of leading frames that belong to the SDK, the
/// `backtrace` crate, or the panic/runtime machinery, so the first reported
/// frame is the user's. Stops at the first non-noise frame.
fn trim_leading_noise(frames: &mut Vec<RawFrame>) {
    const NOISE_PREFIXES: &[&str] = &[
        "errsight::",
        "errsight ", // closure-rendered variants
        "backtrace::",
        "std::backtrace",
        "std::panicking",
        "std::panic::",
        "core::panicking",
        "std::sys_common::backtrace",
        "std::rt::",
        "__rust_",
        "rust_begin_unwind",
        "___rust",
        "_rust_panic",
    ];
    // A frame counts as "real" only if it HAS a name that matches no noise
    // prefix. A symbol-less frame (no debuginfo) is treated as still-noise so a
    // missing symbol in the leading SDK/panic run doesn't halt trimming and
    // leak our own frames to the top in stripped builds. The all-noise case
    // (`None` below) keeps every frame rather than dropping them all.
    let first_real = frames.iter().position(|f| {
        f.function
            .as_deref()
            .is_some_and(|func| !NOISE_PREFIXES.iter().any(|p| func.starts_with(p)))
    });
    match first_real {
        Some(0) | None => {}
        Some(n) => {
            frames.drain(0..n);
        }
    }
}

/// Decide whether a frame is the user's code. `in_app_exclude` wins over
/// `in_app_include`, which wins over the dependency-path heuristic.
fn classify_in_app(path: Option<&str>, function: Option<&str>, config: &Config) -> bool {
    let matches = |needle: &str| {
        path.map(|p| p.contains(needle)).unwrap_or(false)
            || function.map(|f| f.contains(needle)).unwrap_or(false)
    };

    if config.in_app_exclude.iter().any(|n| matches(n)) {
        return false;
    }
    if config.in_app_include.iter().any(|n| matches(n)) {
        return true;
    }
    match path {
        Some(p) => !is_dependency_path(p),
        // No source path and no explicit include rule — can't confirm it's the
        // user's code, so treat as framework (don't anchor grouping on it).
        None => false,
    }
}

/// Heuristic: is this source path part of a dependency, the standard library,
/// or the toolchain rather than the user's project?
fn is_dependency_path(path: &str) -> bool {
    let p = path.replace('\\', "/");
    p.contains("/.cargo/")
        || p.contains("/registry/src/")
        || p.contains("/git/checkouts/")
        || p.contains("/rustc/")
        || p.starts_with("/rustc")
        || p.contains("/.rustup/")
        || p.contains("/lib/rustlib/")
        || p.contains("/toolchains/")
}

/// Best-effort project root (the current working directory). Used only to
/// shorten display filenames; failure just leaves absolute paths.
fn project_root() -> Option<String> {
    std::env::current_dir()
        .ok()
        .map(|p| p.display().to_string())
}

/// Strip the project-root prefix for display, leaving e.g. `src/main.rs`.
///
/// Strips only on a path boundary: `strip_prefix` matches bytes, so without the
/// separator check a sibling like `/repo/proj-other/..` under root `/repo/proj`
/// would be mangled to `-other/..`. Such paths fall back to the absolute form.
fn relative_filename(abs: &str, root: Option<&str>) -> String {
    if let Some(root) = root {
        if let Some(rest) = abs.strip_prefix(root) {
            if rest.is_empty() || rest.starts_with('/') || rest.starts_with('\\') {
                return rest.trim_start_matches(['/', '\\']).to_string();
            }
        }
    }
    abs.to_string()
}

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

    #[test]
    fn dependency_paths_are_not_in_app() {
        assert!(is_dependency_path(
            "/Users/me/.cargo/registry/src/index.crates.io-x/serde-1.0/src/lib.rs"
        ));
        assert!(is_dependency_path("/rustc/abc123/library/std/src/panic.rs"));
        assert!(is_dependency_path(
            "/Users/me/.rustup/toolchains/stable/lib/rustlib/src/rust/library/core/src/result.rs"
        ));
        assert!(!is_dependency_path("/Users/me/proj/src/main.rs"));
    }

    #[test]
    fn classify_respects_overrides() {
        let cfg = ConfigBuilder::from_default()
            .in_app_exclude(["generated/"])
            .in_app_include(["my_lib"])
            .build();
        // Exclude wins.
        assert!(!classify_in_app(
            Some("/proj/generated/schema.rs"),
            None,
            &cfg
        ));
        // Include forces in-app even for a cargo path.
        assert!(classify_in_app(
            Some("/Users/me/.cargo/registry/src/x/my_lib-1.0/src/lib.rs"),
            None,
            &cfg
        ));
        // Function-name include match (no filename, e.g. release build).
        assert!(classify_in_app(None, Some("my_lib::do_thing"), &cfg));
        // Plain app path is in-app by default.
        assert!(classify_in_app(Some("/proj/src/api.rs"), None, &cfg));
        // No path, no rule → not in-app.
        assert!(!classify_in_app(None, Some("core::ops::drop"), &cfg));
    }

    #[test]
    fn relative_filename_only_strips_on_boundary() {
        let root = Some("/Users/me/proj");
        // Genuine subdir → stripped.
        assert_eq!(
            relative_filename("/Users/me/proj/src/main.rs", root),
            "src/main.rs"
        );
        // Exact root → empty.
        assert_eq!(relative_filename("/Users/me/proj", root), "");
        // Sibling sharing a textual prefix → NOT mangled, kept absolute.
        assert_eq!(
            relative_filename("/Users/me/proj-other/src/main.rs", root),
            "/Users/me/proj-other/src/main.rs"
        );
        assert_eq!(
            relative_filename("/Users/me/projsrc/main.rs", root),
            "/Users/me/projsrc/main.rs"
        );
    }

    #[test]
    fn trim_skips_symbolless_leading_frames() {
        // A symbol-less frame sits among the leading SDK/panic run (stripped
        // build). It must not halt trimming and leak the SDK frames.
        let mut frames = vec![
            RawFrame {
                function: Some("std::panicking::begin_panic".into()),
                filename: None,
                lineno: None,
                colno: None,
            },
            RawFrame {
                function: None, // no debuginfo
                filename: None,
                lineno: None,
                colno: None,
            },
            RawFrame {
                function: Some("errsight::panic::capture_panic".into()),
                filename: None,
                lineno: None,
                colno: None,
            },
            RawFrame {
                function: Some("my_app::handler".into()),
                filename: Some("/proj/src/handler.rs".into()),
                lineno: Some(7),
                colno: None,
            },
        ];
        trim_leading_noise(&mut frames);
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].function.as_deref(), Some("my_app::handler"));
    }

    #[test]
    fn trims_leading_sdk_frames() {
        let mut frames = vec![
            RawFrame {
                function: Some("backtrace::Backtrace::new".into()),
                filename: None,
                lineno: None,
                colno: None,
            },
            RawFrame {
                function: Some("errsight::capture_error".into()),
                filename: None,
                lineno: None,
                colno: None,
            },
            RawFrame {
                function: Some("my_app::run".into()),
                filename: Some("/proj/src/main.rs".into()),
                lineno: Some(10),
                colno: None,
            },
        ];
        trim_leading_noise(&mut frames);
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].function.as_deref(), Some("my_app::run"));
    }

    #[test]
    fn real_backtrace_parses_and_marks_in_app() {
        // This test's own frames live under the project root and are not in a
        // cargo/rustc path, so at least one should be classified in_app.
        let cfg = ConfigBuilder::from_default().build();
        let frames = current_frames(&cfg);
        assert!(!frames.is_empty(), "expected to capture some frames");
        // Don't assert exact in_app (depends on debuginfo), just that parsing
        // produced function names for some frames.
        assert!(frames.iter().any(|f| f.function.is_some()));
    }
}