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
//! error_core is a default implementation of [zerror::Z].

use std::backtrace::Backtrace;
use std::fmt::Debug;

use biometrics::{Collector, Counter};

use buffertk::{Packable, Unpackable};

use tatl::{HeyListen, Stationary};

use prototk::field_types::*;
use prototk::{FieldPackHelper, FieldUnpackHelper, Message, Tag};
use prototk_derive::Message;

//////////////////////////////////////////// biometrics ////////////////////////////////////////////

static DEFAULT_ERROR_CORE: Counter = Counter::new("zerror_core.default");
static DEFAULT_ERROR_CORE_MONITOR: Stationary =
    Stationary::new("zerror_core.default", &DEFAULT_ERROR_CORE);

/// Register the monitors for this crate.
pub fn register_monitors(hey_listen: &mut HeyListen) {
    hey_listen.register_stationary(&DEFAULT_ERROR_CORE_MONITOR);
}

/// Register the biometrics for this crate.
pub fn register_biometrics(collector: Collector) {
    collector.register_counter(&DEFAULT_ERROR_CORE);
}

///////////////////////////////////////////// ErrorCore ////////////////////////////////////////////

#[derive(Clone, Debug, Default, Message, Eq, PartialEq)]
struct Token {
    #[prototk(1, string)]
    identifier: String,
    #[prototk(2, string)]
    value: String,
}

#[derive(Clone, Debug, Default, Message, Eq, PartialEq)]
struct Url {
    #[prototk(1, string)]
    identifier: String,
    #[prototk(2, string)]
    url: String,
}

#[derive(Clone, Debug, Default, Message, Eq, PartialEq)]
struct Variable {
    #[prototk(1, string)]
    identifier: String,
    #[prototk(2, string)]
    value: String,
}

#[derive(Clone, Debug, Default, Message, Eq, PartialEq)]
struct Info {
    #[prototk(1, string)]
    name: String,
    #[prototk(2, string)]
    value: String,
}

#[derive(Clone, Debug, Default, Message, Eq, PartialEq)]
struct Internals {
    // reserved 1: email
    // reserved 2: short
    #[prototk(3, string)]
    backtrace: String,
    #[prototk(4, message)]
    toks: Vec<Token>,
    #[prototk(5, message)]
    urls: Vec<Url>,
    #[prototk(6, message)]
    vars: Vec<Variable>,
    #[prototk(7, message)]
    info: Vec<Info>,
}

/// [ErrorCore] implements 100% of Z for easy error reporting.  It's intended that people will wrap
/// and proxy ErrorCore and then implement a short summary on top that descends from an error enum.
#[derive(Clone, Debug)]
pub struct ErrorCore {
    internals: Box<Internals>,
}

impl ErrorCore {
    /// Create a new ErrorCore with the provided counter.  The provided counter will be clicked
    /// each time a new error is created, to give people insight into the error.  It's advisable to
    /// have a separate counter for different conditions.
    pub fn new(counter: &'static Counter) -> Self {
        counter.click();
        let backtrace = format!("{}", Backtrace::force_capture());
        #[allow(deprecated)]
        let internals = Internals {
            backtrace,
            toks: Vec::new(),
            urls: Vec::new(),
            vars: Vec::new(),
            info: Vec::new(),
        };
        Self {
            internals: Box::new(internals),
        }
    }

    /// Print the long-form of the error.
    pub fn long_form(&self) -> String {
        let mut s = String::default();
        #[allow(deprecated)]
        for token in self.internals.toks.iter() {
            s += &format!("\n{}: {}", token.identifier, token.value);
        }
        #[allow(deprecated)]
        if !self.internals.urls.is_empty() {
            s += "\n";
            #[allow(deprecated)]
            for url in self.internals.urls.iter() {
                s += &format!("\n{}: {}", url.identifier, url.url);
            }
        }
        #[allow(deprecated)]
        if !self.internals.vars.is_empty() {
            s += "\n";
            #[allow(deprecated)]
            for variable in self.internals.vars.iter() {
                s += &format!("\n{} = {}", variable.identifier, variable.value);
            }
        }
        if !self.internals.info.is_empty() {
            for info in self.internals.info.iter() {
                s += &format!("\n{} = {}", info.name, info.value);
            }
        }
        s += &format!("\n\nbacktrace:\n{}", self.internals.backtrace);
        s.trim().to_owned() + "\n"
    }

    /// Set the token associated with identifier.
    #[deprecated(since = "0.5.0", note = "use set_info instead")]
    pub fn set_token(&mut self, identifier: &str, value: &str) {
        #[allow(deprecated)]
        self.internals.toks.push(Token {
            identifier: identifier.to_owned(),
            value: value.to_owned(),
        });
    }

    /// Sets a URL under an identifier.
    #[deprecated(since = "0.5.0", note = "use set_info instead")]
    pub fn set_url(&mut self, identifier: &str, url: &str) {
        #[allow(deprecated)]
        self.internals.urls.push(Url {
            identifier: identifier.to_owned(),
            url: url.to_owned(),
        });
    }

    /// Sets a variable that's debug-printable.
    #[deprecated(since = "0.5.0", note = "use set_info instead")]
    pub fn set_variable<X: Debug>(&mut self, variable: &str, x: X) {
        #[allow(deprecated)]
        self.internals.vars.push(Variable {
            identifier: variable.to_owned(),
            value: format!("{:?}", x),
        });
    }

    /// Add debug formatting of a local variable.
    pub fn set_info<X: Debug>(&mut self, name: &str, value: X) {
        self.internals.info.push(Info {
            name: name.to_owned(),
            value: format!("{:?}", value),
        });
    }

    /// Add debug formatting using a closure.
    pub fn set_lazy_info<F: FnOnce() -> String>(&mut self, name: &str, value: F) {
        self.internals.info.push(Info {
            name: name.to_owned(),
            value: value(),
        });
    }
}

impl Default for ErrorCore {
    fn default() -> Self {
        Self::new(&DEFAULT_ERROR_CORE)
    }
}

impl Packable for ErrorCore {
    fn pack_sz(&self) -> usize {
        <Internals as Packable>::pack_sz(&self.internals)
    }

    fn pack(&self, buf: &mut [u8]) {
        <Internals as Packable>::pack(&self.internals, buf)
    }
}

impl<'a> Unpackable<'a> for ErrorCore {
    type Error = prototk::Error;

    fn unpack<'b: 'a>(buf: &'b [u8]) -> Result<(Self, &'b [u8]), Self::Error> {
        let (internals, buf) = <Internals as Unpackable<'a>>::unpack(buf)?;
        Ok((
            Self {
                internals: Box::new(internals),
            },
            buf,
        ))
    }
}

impl<'a> FieldPackHelper<'a, message<ErrorCore>> for ErrorCore {
    fn field_pack_sz(&self, tag: &Tag) -> usize {
        Internals::field_pack_sz(&self.internals, tag)
    }

    fn field_pack(&self, tag: &Tag, out: &mut [u8]) {
        Internals::field_pack(&self.internals, tag, out)
    }
}

impl<'a> FieldUnpackHelper<'a, message<ErrorCore>> for ErrorCore {
    fn merge_field(&mut self, proto: message<ErrorCore>) {
        *self = proto.unwrap_message();
    }
}

impl<'a> Message<'a> for ErrorCore {}

impl From<message<ErrorCore>> for ErrorCore {
    fn from(proto: message<Self>) -> Self {
        proto.unwrap_message()
    }
}

/////////////////////////////////////////////// tests //////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use biometrics::Sensor;

    use buffertk::stack_pack;

    use super::*;

    static TEST_COUNTER1: Counter = Counter::new("zerror_core.test_counter1");
    static TEST_COUNTER2: Counter = Counter::new("zerror_core.test_counter2");

    #[test]
    fn serialize_empty_error_core() {
        assert_eq!(0, TEST_COUNTER1.read());
        let mut error_core = ErrorCore::new(&TEST_COUNTER1);
        assert_eq!(1, TEST_COUNTER1.read());
        "SOME-BACKTRACE\n".clone_into(&mut error_core.internals.backtrace);
        assert_eq!("backtrace:\nSOME-BACKTRACE\n", error_core.long_form());
        let buf = stack_pack(&error_core).to_vec();
        let got: ErrorCore = Unpackable::unpack(&buf).unwrap().0;
        assert_eq!(&error_core.internals, &got.internals);
    }

    #[test]
    fn serialize_used_error_core() {
        assert_eq!(0, TEST_COUNTER2.read());
        let mut error_core = ErrorCore::new(&TEST_COUNTER2);
        assert_eq!(1, TEST_COUNTER2.read());
        "SOME-BACKTRACE\n".clone_into(&mut error_core.internals.backtrace);
        error_core.set_info("VAR", 42);
        assert_eq!(
            "VAR = 42

backtrace:
SOME-BACKTRACE
",
            error_core.long_form()
        );
        let buf = stack_pack(&error_core).to_vec();
        let got: ErrorCore = Unpackable::unpack(&buf).unwrap().0;
        assert_eq!(&error_core.internals, &got.internals);
    }
}