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
use std::cell::RefCell;
use schemars::gen::{SchemaGenerator, SchemaSettings};
use crate::error::Error;
thread_local! {
static GEN_CTX: RefCell<GenContext> = RefCell::new(GenContext::new());
}
pub fn in_context<R, F>(cb: F) -> R
where
F: FnOnce(&mut GenContext) -> R,
{
GEN_CTX.with(|ctx| cb(&mut *ctx.borrow_mut()))
}
pub fn on_error(handler: impl Fn(Error) + 'static) {
in_context(|ctx| ctx.error_handler = Some(Box::new(handler)));
}
pub struct GenContext {
pub schema: SchemaGenerator,
pub(crate) show_error: fn(&Error) -> bool,
error_handler: Option<Box<dyn Fn(Error)>>,
}
impl GenContext {
fn new() -> Self {
Self {
schema: SchemaGenerator::new(
SchemaSettings::draft07().with(|s| s.inline_subschemas = true),
),
show_error: default_error_filter,
error_handler: None,
}
}
pub(crate) fn reset_error_filter(&mut self) {
self.show_error = default_error_filter;
}
#[tracing::instrument(skip_all)]
pub fn error(&mut self, error: Error) {
if let Some(handler) = &self.error_handler {
if !(self.show_error)(&error) {
return;
}
handler(error);
}
}
}
fn default_error_filter(_: &Error) -> bool {
true
}