ntex-error 3.0.0

ntex error management
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
//! Backtrace
#![allow(warnings)]
use std::collections::HashMap;
use std::hash::{BuildHasher, Hasher};
use std::panic::Location;
use std::{cell::RefCell, fmt, fmt::Write, os, path, ptr, sync::Arc, sync::LazyLock};

use backtrace::{BacktraceFmt, BacktraceFrame, BytesOrWideString, Frame};

thread_local! {
    static FRAMES: RefCell<HashMap<usize, Arc<BacktraceFrame>>> = RefCell::new(HashMap::default());
    static REPRS: RefCell<HashMap<u64, Arc<str>>> = RefCell::new(HashMap::default());
    static DEFAULT: Arc<str> = Arc::from("Unresolved backtrace");
}

static mut START: Option<(&'static str, u32)> = None;
static mut START_ALT: Option<(&'static str, u32)> = None;

/// Sets the source location where rendered backtraces are cut off.
///
/// The frame matching `file` (a path suffix) and `line` (`0` matches any line),
/// and all of its callers, are omitted from the rendered backtrace.
/// Must be called once during initialization, before any backtrace is resolved.
pub fn set_backtrace_start(file: &'static str, line: u32) {
    unsafe {
        START = Some((file, line));
    }
}

#[doc(hidden)]
pub fn set_backtrace_start_alt(file: &'static str, line: u32) {
    unsafe {
        START_ALT = Some((file, line));
    }
}

#[derive(Clone)]
/// Representation of a backtrace.
///
/// This structure can be used to capture a backtrace at various
/// points in a program and later used to inspect what the backtrace
/// was at that time.
pub struct Backtrace(Arc<BacktraceRaw>);

#[derive(Debug)]
/// Backtrace resolver.
///
/// Symbol resolution may require filesystem access and can be blocking.
/// In asynchronous contexts, this work should be offloaded to a thread
/// pool.
///
/// **Note:** Once resolution is complete, control must return to the
/// originating thread to ensure caching is performed correctly.
pub struct BacktraceResolver {
    bt: Arc<BacktraceRaw>,
    repr: Option<Arc<str>>,
    resolved: bool,
    frames: HashMap<usize, Arc<BacktraceFrame>>,
}

#[derive(Debug)]
/// Representation of a backtrace.
pub struct BacktraceRaw {
    id: u64,
    frames: [Option<Frame>; 80],
    location: &'static str,
}

impl BacktraceRaw {
    /// Create new backtrace
    pub fn new(location: &'static Location<'static>) -> Self {
        Self::with_filename(location.file())
    }

    #[track_caller]
    /// Create new backtrace with current location
    pub fn with_current() -> Self {
        Self::new(Location::caller())
    }

    /// Create new backtrace with filename location
    pub fn with_filename(location: &'static str) -> Self {
        Self::capture(location, |cb| backtrace::trace(cb))
    }

    #[doc(hidden)]
    /// Create new backtrace without acquiring the global backtrace lock.
    ///
    /// Does not allocate or lock, so it can be used from a signal handler
    /// (subject to the platform unwinder being signal-safe).
    ///
    /// # Safety
    ///
    /// Same requirements as [`backtrace::trace_unsynchronized`].
    pub unsafe fn with_filename_unsynchronized(location: &'static str) -> Self {
        Self::capture(location, |cb| unsafe {
            backtrace::trace_unsynchronized(cb);
        })
    }

    fn capture<F>(location: &'static str, trace: F) -> Self
    where
        F: FnOnce(&mut dyn FnMut(&Frame) -> bool),
    {
        let mut st = foldhash::fast::FixedState::default().build_hasher();
        let mut idx = 0;
        let mut frames: [Option<Frame>; 80] = [const { None }; 80];

        trace(&mut |frm| {
            let ip = frm.ip();
            st.write_usize(ip as usize);
            frames[idx] = Some(frm.clone());
            idx += 1;
            idx < 80
        });
        let id = st.finish();

        BacktraceRaw {
            id,
            frames,
            location,
        }
    }
}

impl From<BacktraceRaw> for Backtrace {
    fn from(bt: BacktraceRaw) -> Backtrace {
        Backtrace(Arc::new(bt))
    }
}

impl Backtrace {
    /// Create new backtrace
    pub fn new(location: &'static Location<'static>) -> Self {
        Self(Arc::new(BacktraceRaw::new(location)))
    }

    #[track_caller]
    /// Create new backtrace with current location
    pub fn with_current() -> Self {
        Self(Arc::new(BacktraceRaw::new(Location::caller())))
    }

    /// Create new backtrace with filename location
    pub fn with_filename(location: &'static str) -> Self {
        Self(Arc::new(BacktraceRaw::with_filename(location)))
    }

    /// Returns the rendered backtrace, if it has been resolved on the current thread.
    pub fn repr(&self) -> Option<Arc<str>> {
        REPRS.with(|r| r.borrow_mut().get(&self.0.id).cloned())
    }

    /// Returns `true` if this backtrace has been resolved (or resolution
    /// has started) on the current thread.
    pub fn is_resolved(&self) -> bool {
        REPRS.with(|r| r.borrow_mut().contains_key(&self.0.id))
    }

    /// Resolves the backtrace symbols on the current thread and caches the result.
    #[must_use]
    pub fn resolve(self) -> Self {
        self.resolver().resolve();
        self
    }

    /// Returns a resolver that can resolve symbols outside the current thread.
    ///
    /// See [`BacktraceResolver`] for details.
    pub fn resolver(&self) -> BacktraceResolver {
        REPRS.with(|r| {
            let mut reprs = r.borrow_mut();
            if let Some(repr) = reprs.get(&self.0.id) {
                BacktraceResolver {
                    repr: None,
                    resolved: true,
                    bt: self.0.clone(),
                    frames: HashMap::default(),
                }
            } else {
                DEFAULT.with(|s| {
                    reprs.insert(self.0.id, s.clone());
                });

                let mut frames = HashMap::default();

                FRAMES.with(|c| {
                    let mut cache = c.borrow();

                    for frm in &self.0.frames {
                        if let Some(frm) = frm {
                            let ip = frm.ip() as usize;
                            if let Some(frame) = cache.get(&ip) {
                                frames.insert(ip, frame.clone());
                            }
                        }
                    }
                });

                BacktraceResolver {
                    frames,
                    resolved: false,
                    repr: None,
                    bt: self.0.clone(),
                }
            }
        })
    }
}

impl BacktraceResolver {
    /// Resolves backtrace symbols and renders the representation.
    ///
    /// The result is cached when the resolver is dropped.
    #[allow(clippy::return_self_not_must_use)]
    pub fn resolve(mut self) -> Self {
        if self.resolved {
            return self;
        }

        for frm in &self.bt.frames {
            if let Some(frm) = frm {
                let ip = frm.ip() as usize;
                if self.frames.contains_key(&ip) {
                    continue;
                }

                let mut f = BacktraceFrame::from(frm.clone());
                f.resolve();
                self.frames.insert(ip, Arc::new(f));
            }
        }

        let mut idx = 0;
        let mut frames: [Option<&BacktraceFrame>; 80] = [None; 80];
        for frm in &self.bt.frames {
            if let Some(frm) = frm {
                let ip = frm.ip() as usize;
                frames[idx] = Some(self.frames[&ip].as_ref());
                idx += 1;
            }
        }

        find_loc(self.bt.location, &mut frames);

        #[allow(static_mut_refs)]
        {
            if let Some(start) = unsafe { START } {
                find_loc_start(start, &mut frames);
            }
            if let Some(start) = unsafe { START_ALT } {
                find_loc_start(start, &mut frames);
            }
            PATHS2.with(|paths| {
                for s in paths {
                    find_loc_start((s.as_str(), 0), &mut frames);
                }
            });
        }

        let mut idx = 0;
        for frm in &mut frames {
            if frm.is_some() {
                if idx > 10 {
                    *frm = None;
                } else {
                    idx += 1;
                }
            }
        }

        let bt = Bt(&frames[..]);
        let mut buf = String::new();
        let _ = write!(&mut buf, "\n{bt:?}");
        self.repr = Some(Arc::from(buf));

        self
    }
}

impl Drop for BacktraceResolver {
    fn drop(&mut self) {
        if !self.resolved {
            if let Some(repr) = self.repr.take() {
                REPRS.with(|r| {
                    r.borrow_mut().insert(self.bt.id, repr);
                });
            }

            FRAMES.with(|c| {
                let mut cache = c.borrow_mut();

                for (ip, frm) in &self.frames {
                    let ip = frm.ip() as usize;
                    if !cache.contains_key(&ip) {
                        cache.insert(ip, frm.clone());
                    }
                }
            });
        }
    }
}

fn find_loc(loc: &str, frames: &mut [Option<&BacktraceFrame>]) {
    let mut idx = 0;

    'outter: for (i, frm) in frames.iter().enumerate() {
        if let Some(f) = frm {
            for sym in f.symbols() {
                if let Some(fname) = sym.filename()
                    && fname.ends_with(loc)
                {
                    idx = i;
                    break 'outter;
                }
            }
        } else {
            break;
        }
    }

    for f in frames.iter_mut().take(idx) {
        *f = None;
    }

    PATHS.with(|paths| {
        'outter: for frm in &mut frames[idx..] {
            if let Some(f) = frm {
                for sym in f.symbols() {
                    if let Some(fname) = sym.filename() {
                        for p in paths {
                            if fname.ends_with(p) {
                                *frm = None;
                                continue 'outter;
                            }
                        }
                    }
                }
            }
        }
    });
}

thread_local! {
    static PATHS: Vec<String> = {
        let mut paths = Vec::new();
        for item in [
            &["src", "ctx.rs"][..],
            &["src", "map_err.rs"][..],
            &["src", "and_then.rs"][..],
            &["src", "fn_service.rs"][..],
            &["src", "pipeline.rs"][..],
            &["src", "net", "factory.rs"][..],
            &["src", "future", "future.rs"][..],
            &["src", "net", "service.rs"][..],
            &["src", "boxed.rs"][..],
            &["src", "error.rs"][..],
            &["src", "wrk.rs"][..],
            &["src", "future.rs"][..],
            &["std", "src", "thread", "local.rs"][..],
        ] {
            paths.push(item.iter().collect::<path::PathBuf>().to_string_lossy().into_owned());
        }
        paths
    };

    static PATHS2: Vec<String> = {
        let mut paths = Vec::new();
        for item in [
            &["src", "driver.rs"][..],
            &["src", "rt_compio.rs"][..],
            &["core", "src", "panic", "unwind_safe.rs"][..],
            &["src", "runtime", "task", "core.rs"][..]
        ] {
            paths.push(item.iter().collect::<path::PathBuf>().to_string_lossy().into_owned());
        }
        paths
    }
}

fn find_loc_start(loc: (&str, u32), frames: &mut [Option<&BacktraceFrame>]) {
    let mut idx = 0;
    while idx < frames.len() {
        if let Some(frm) = &frames[idx] {
            for sym in frm.symbols() {
                if let Some(fname) = sym.filename()
                    && let Some(lineno) = sym.lineno()
                    && fname.ends_with(loc.0)
                    && (loc.1 == 0 || lineno == loc.1)
                {
                    for f in frames.iter_mut().skip(idx) {
                        if f.is_some() {
                            *f = None;
                        }
                    }
                    return;
                }
            }
        }
        idx += 1;
    }
}

struct Bt<'a>(&'a [Option<&'a BacktraceFrame>]);

impl fmt::Debug for Bt<'_> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let cwd = std::env::current_dir();
        let mut print_path = move |fmt: &mut fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
            let path = crate::utils::module_path_fs(path.to_str_lossy().as_ref());
            fmt::Display::fmt(&path, fmt)
        };

        let mut f = BacktraceFmt::new(fmt, backtrace::PrintFmt::Short, &mut print_path);
        f.add_context()?;
        for frm in self.0.iter().flatten() {
            f.frame().backtrace_frame(frm)?;
        }
        f.finish()?;
        Ok(())
    }
}

impl fmt::Debug for Backtrace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(repr) = self.repr() {
            fmt::Display::fmt(repr.as_ref(), f)
        } else {
            Ok(())
        }
    }
}

impl fmt::Display for Backtrace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(repr) = self.repr() {
            fmt::Display::fmt(repr.as_ref(), f)
        } else {
            Ok(())
        }
    }
}