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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
pub mod block_on;
pub mod set_callback;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use set_callback::TracebackCallbackType;
use std::{
    error::Error,
    fmt::{Display, Formatter},
    fs::File,
    io::Write,
};

pub use paste;
pub use serde_json;

pub static mut TRACEBACK_ERROR_CALLBACK: Option<TracebackCallbackType> = None;

/// A custom error struct for handling tracebacks in Rust applications.
///
/// This struct is designed to capture error information such as the error message,
/// the file and line where the error occurred, and additional contextual data.
///
/// # Examples
///
/// Creating a new `TracebackError` with a custom message:
///
/// ```rust
/// use chrono::{DateTime, Utc};
/// use serde_json::Value;
///
/// let error = traceback_error::traceback!("Custom error message");
/// println!("{:?}", error);
/// ```
///
/// # Fields
///
/// - `message`: A string containing the error message.
/// - `file`: A string containing the filename where the error occurred.
/// - `line`: An unsigned integer representing the line number where the error occurred.
/// - `parent`: An optional boxed `TracebackError` representing the parent error, if any.
/// - `time_created`: A `chrono::DateTime<Utc>` indicating when the error was created.
/// - `extra_data`: A `serde_json::Value` for storing additional error-related data.
/// - `project`: An optional string representing the project name.
/// - `computer`: An optional string representing the computer name.
/// - `user`: An optional string representing the username.
/// - `is_parent`: A boolean indicating if this error is considered a parent error.
/// - `is_handled`: A boolean indicating if the error has been handled.
/// - `is_default`: A boolean indicating if this error is the default error.
///
/// # Default Implementation
///
/// The `Default` trait is implemented for `TracebackError`, creating a default instance
/// with the following values:
///
/// - `message`: "Default message"
/// - `file`: The current file's name (using `file!()`).
/// - `line`: The current line number (using `line!()`).
/// - `parent`: None
/// - `time_created`: The Unix epoch time.
/// - `extra_data`: Value::Null
/// - `project`: None
/// - `computer`: None
/// - `user`: None
/// - `is_parent`: false
/// - `is_handled`: false
/// - `is_default`: true
///
/// # Equality Comparison
///
/// The `PartialEq` trait is implemented for `TracebackError`, allowing you to compare
/// two `TracebackError` instances for equality based on their message, file, line, and
/// other relevant fields. The `is_handled` and `is_default` fields are not considered
/// when comparing for equality.
///
/// # Dropping Errors
///
/// Errors are automatically dropped when they go out of scope, but before they are dropped,
/// they are handled by the `TRACEBACK_ERROR_CALLBACK` variable.
/// By default, this variable is a function simply set to serialize the error and
/// write it to a JSON file, but the default function can be changed with the
/// `set_callback!` macro.
///
/// # Callback Types
///
/// The callback function can be either synchronous or asynchronous, depending on the
/// `TracebackCallbackType` set globally using the `TRACEBACK_ERROR_CALLBACK` variable.
/// It can be set using the `set_callback!` macro.
///
/// - If `TRACEBACK_ERROR_CALLBACK` is `Some(TracebackCallbackType::Async)`, an
///   asynchronous callback function is used.
/// - If `TRACEBACK_ERROR_CALLBACK` is `Some(TracebackCallbackType::Sync)`, a
///   synchronous callback function is used.
/// - If `TRACEBACK_ERROR_CALLBACK` is `None`, a default callback function is used.
///
/// # Creating Errors
///
/// You can create a new `TracebackError` instance using the `traceback!` macro. Additional
/// data can be added using the `with_extra_data` method, and environment variables are
/// automatically added when the error is being handled.
/// The additional data should be stored in a serde_json::Value struct.
///
/// # Environment Variables
///
/// The `with_env_vars` method populates the `project`, `computer`, and `user` fields with
/// information obtained from environment variables (`CARGO_PKG_NAME`, `COMPUTERNAME`, and
/// `USERNAME`, respectively) or assigns default values if the environment variables are
/// not present.
///
/// # Tracing
///
/// Tracing can be essential for diagnosing and debugging issues in your applications. When an
/// error occurs, you can create a `TracebackError` instance to record the error's details, such
/// as the error message, the location in the code where it occurred, and additional contextual
/// information.
/// Should a function return a TracebackError, it can then be re-captured to trace it even further.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TracebackError {
    pub message: String,
    pub file: String,
    pub line: u32,
    pub parent: Option<Box<TracebackError>>,
    pub time_created: DateTime<Utc>,
    pub extra_data: Value,
    pub project: Option<String>,
    pub computer: Option<String>,
    pub user: Option<String>,
    pub is_parent: bool,
    pub is_handled: bool,
    is_default: bool,
}

impl Default for TracebackError {
    fn default() -> Self {
        Self {
            message: "Default message".to_string(),
            file: file!().to_string(),
            line: line!(),
            parent: None,
            time_created: DateTime::from_utc(
                chrono::NaiveDateTime::from_timestamp_opt(0, 0).unwrap(),
                Utc,
            ),
            extra_data: Value::Null,
            project: None,
            computer: None,
            user: None,
            is_parent: false,
            is_handled: false,
            is_default: true,
        }
    }
}

impl PartialEq for TracebackError {
    fn eq(&self, other: &Self) -> bool {
        let (this, mut other) = (self.clone(), other.clone());
        other.is_handled = this.is_handled;
        this.message == other.message
            && this.file == other.file
            && this.line == other.line
            && this.parent == other.parent
            && this.extra_data == other.extra_data
            && this.project == other.project
            && this.computer == other.computer
            && this.user == other.user
            && this.is_parent == other.is_parent
    }
}

impl Drop for TracebackError {
    fn drop(&mut self) {
        if self.is_parent || self.is_handled || self.is_default {
            return;
        }
        let mut this = std::mem::take(self);
        this.is_handled = true;
        unsafe {
            let callback: Option<&mut TracebackCallbackType> = TRACEBACK_ERROR_CALLBACK.as_mut();
            match callback {
                Some(TracebackCallbackType::Async(ref mut f)) => {
                    block_on::block_on(f.call(this)); // bad practice, fix later
                }
                Some(TracebackCallbackType::Sync(ref mut f)) => {
                    f.call(this);
                }
                None => {
                    default_callback(this);
                }
            }
        }
    }
}

impl TracebackError {
    pub fn new(message: String, file: String, line: u32) -> Self {
        Self {
            message,
            file,
            line,
            parent: None,
            time_created: Utc::now(),
            extra_data: Value::Null,
            project: None,
            computer: None,
            user: None,
            is_parent: false,
            is_handled: false,
            is_default: false,
        }
    }
    /// This method allows you to attach additional data to a `TracebackError` instance.
    /// This extra data can be valuable when diagnosing and debugging errors,
    /// as it provides context and information related to the error.
    ///
    /// ## Parameters:
    /// - `extra_data`: A `serde_json::Value` containing the extra data you want to associate with the error.
    ///
    /// ## Return Value:
    /// - Returns a modified `TracebackError` instance with the provided `extra_data`.
    ///
    /// ## Example Usage:
    /// ```rs
    /// use traceback_error::{traceback, TracebackError, serde_json::json};
    ///
    /// fn main() {
    ///     // Create a new TracebackError with extra data
    ///     let error = traceback!().with_extra_data(json!({
    ///         "foo": "bar",
    ///         "a": "b",
    ///         "1": "2"
    ///     }));
    ///
    ///     // Now the error instance contains the specified extra data
    /// }
    /// ```
    ///
    /// This method is useful when you want to enrich error objects with additional information
    /// relevant to the context in which the error occurred. It ensures that relevant data is
    /// available for analysis when handling errors in your Rust application.
    pub fn with_extra_data(mut self, extra_data: Value) -> Self {
        self.is_default = false;
        self.extra_data = extra_data;
        self
    }
    /// Adds environment variables to the TracebackError.
    ///
    /// This method populates the `project`, `computer`, and `user` fields of the `TracebackError`
    /// based on the values of specific environment variables. If any of these environment variables
    /// are not found, default values are used, and the error message reflects that the information
    /// is unknown due to the missing environment variables.
    ///
    /// # Example:
    ///
    /// ```
    /// use traceback_error::TracebackError;
    ///
    /// // Create a new TracebackError and populate environment variables
    /// let error = TracebackError::new("An error occurred".to_string(), file!().to_string(), line!())
    ///     .with_env_vars();
    ///
    /// // The error now contains information about the project, computer, and user from
    /// // environment variables, or default values if the environment variables are missing.
    /// ```
    ///
    /// # Environment Variables Used:
    ///
    /// - `CARGO_PKG_NAME`: Used to set the `project` field.
    /// - `COMPUTERNAME`: Used to set the `computer` field.
    /// - `USERNAME`: Used to set the `user` field.
    ///
    /// # Returns:
    ///
    /// A modified `TracebackError` with updated `project`, `computer`, and `user` fields.
    pub fn with_env_vars(mut self) -> Self {
        // get project name using the CARGO_PKG_NAME env variable
        let project_name = match std::env::var("CARGO_PKG_NAME") {
            Ok(p) => p,
            Err(_) => "Unknown due to CARGO_PKG_NAME missing".to_string(),
        };
        // get computer name using the COMPUTERNAME env variable
        let computer_name = match std::env::var("COMPUTERNAME") {
            Ok(c) => c,
            Err(_) => "Unknown due to COMPUTERNAME missing".to_string(),
        };
        // get username using the USERNAME env variable
        let username = match std::env::var("USERNAME") {
            Ok(u) => u,
            Err(_) => "Unknown due to USERNAME missing".to_string(),
        };
        self.is_default = false;
        self.project = Some(project_name);
        self.computer = Some(computer_name);
        self.user = Some(username);
        self
    }
    /// The `with_parent` method allows you to associate a parent error with the current `TracebackError` instance.
    /// This can be useful when you want to create a hierarchical structure of errors, where one error is considered the parent of another.
    ///
    /// ## Parameters:
    /// - `parent`: A `TracebackError` instance that you want to set as the parent of the current error.
    ///
    /// ## Return Value:
    /// - Returns a modified `TracebackError` instance with the specified parent error.
    ///
    /// ## Example:
    /// ```rs
    /// use traceback_error::TracebackError;
    ///
    /// fn main() {
    ///     // Create a new TracebackError
    ///     let parent_error = TracebackError::new("Parent error".to_string(), file!().to_string(), line!());
    ///
    ///     // Create a child error with the parent error
    ///     let child_error = TracebackError::new("Child error".to_string(), file!().to_string(), line!())
    ///         .with_parent(parent_error);
    ///
    ///     // Now, `child_error` has `parent_error` as its parent
    /// }
    /// ```
    ///
    /// The with_parent method is particularly useful when you want to establish relationships between errors,
    /// making it easier to understand error hierarchies and diagnose issues.
    pub fn with_parent(mut self, parent: TracebackError) -> Self {
        self.is_default = false;
        self.parent = Some(Box::new(parent.with_is_parent(true)));
        self
    }
    fn with_is_parent(mut self, is_parent: bool) -> Self {
        self.is_default = false;
        self.is_parent = is_parent;
        self
    }
}

/// This display implementation is recursive, and will print the error and all its parents
/// with a tab in front of each parent.
impl Display for TracebackError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut parent = self.parent.as_ref();
        let mut first = true;
        let mut amount_tabs = 0;
        while let Some(p) = parent {
            if first {
                first = false;
            } else {
                write!(f, "\n")?;
            }
            for _ in 0..amount_tabs {
                write!(f, "\t")?;
            }
            write!(f, "{}", p)?;
            amount_tabs += 1;
            parent = p.parent.as_ref();
        }
        write!(f, "\n")?;
        for _ in 0..amount_tabs {
            write!(f, "\t")?;
        }
        write!(f, "{}:{}: {}", self.file, self.line, self.message)
    }
}

impl Error for TracebackError {}

impl serde::de::Error for TracebackError {
    fn custom<T: std::fmt::Display>(msg: T) -> Self {
        // Create a new TracebackError with the provided message
        TracebackError {
            message: msg.to_string(),
            file: String::new(),
            line: 0,
            parent: None,
            time_created: Utc::now(),
            extra_data: json!({
                "error_type": "serde::de::Error",
                "error_message": msg.to_string()
            }),
            project: None,
            computer: None,
            user: None,
            is_parent: false,
            is_handled: false,
            is_default: false,
        }
    }
}

pub fn default_callback(err: TracebackError) {
    let err = err.with_env_vars();

    // get current time
    let current_time = chrono::Utc::now();
    let current_time_string = current_time.format("%Y-%m-%d.%H-%M-%S").to_string();
    let nanosecs = current_time.timestamp_nanos();
    let current_time_string = format!("{}.{}", current_time_string, nanosecs);
    // check if errors folder exists
    match std::fs::read_dir("errors") {
        Ok(_) => {}
        Err(_) => {
            // if not, create it
            match std::fs::create_dir("errors") {
                Ok(_) => {}
                Err(e) => {
                    println!("Error when creating directory: {}", e);
                    return;
                }
            };
        }
    };
    // create {current_time_string}.json
    let filename = format!("./errors/{current_time_string}.json");
    println!("Writing error to file: {}", filename);
    let mut file = match File::create(filename) {
        Ok(f) => f,
        Err(e) => {
            println!("Error when creating file: {}", e);
            return;
        }
    };
    // parse error to json
    let err = match serde_json::to_string_pretty(&err) {
        Ok(e) => e,
        Err(e) => {
            println!("Error when parsing error: {}", e);
            return;
        }
    };
    // write json to file
    match file.write_all(err.as_bytes()) {
        Ok(_) => {}
        Err(e) => {
            println!("Error when writing to file: {}", e);
            return;
        }
    };
}
/// A macro for creating instances of the `TracebackError` struct with various options.
///
/// The `traceback!` macro simplifies the creation of `TracebackError` instances by providing
/// convenient syntax for specifying error messages and handling different error types.
///
/// # Examples
///
/// Creating a new `TracebackError` with a custom message:
///
/// ```rust
/// let error = traceback_error::traceback!("Custom error message");
/// println!("{:?}", error);
/// ```
///
/// Creating a new `TracebackError` from a generic error:
///
/// ```rust
/// fn custom_function() -> Result<(), traceback_error::TracebackError> {
///     // ...
///     // Some error occurred
///     let generic_error: Box<dyn std::error::Error> = Box::new(std::io::Error::new(std::io::ErrorKind::Other, "Generic error"));
///     Err(traceback_error::traceback!(err generic_error))
/// }
/// ```
///
/// Creating a new `TracebackError` from a generic error with a custom message:
///
/// ```rust
/// fn custom_function() -> Result<(), traceback_error::TracebackError> {
///     // ...
///     // Some error occurred
///     let generic_error: Box<dyn std::error::Error> = Box::new(std::io::Error::new(std::io::ErrorKind::Other, "Generic error"));
///     Err(traceback_error::traceback!(err generic_error, "Custom error message"))
/// }
/// ```
///
/// Tracing an error:
/// ```rust
/// fn main() {
///     match caller_of_tasks() {
///         Ok(_) => {}
///         Err(e) => {
///             traceback_error::traceback!(err e, "One of the tasks failed");
///         }
///     }
/// }
///
/// fn task_that_may_fail() -> Result<(), traceback_error::TracebackError> {
///     return Err(traceback_error::traceback!("task_that_may_fail failed"));
/// }
///
/// fn other_task_that_may_fail() -> Result<(), traceback_error::TracebackError> {
///     return Err(traceback_error::traceback!("other_task_that_may_fail failed"));
/// }
///
/// fn caller_of_tasks() -> Result<(), traceback_error::TracebackError> {
///     match task_that_may_fail() {
///         Ok(_) => {}
///         Err(e) => {
///             return Err(traceback_error::traceback!(err e));
///         }
///     };
///     match other_task_that_may_fail() {
///         Ok(_) => {}
///         Err(e) => {
///             return Err(traceback_error::traceback!(err e));
///         }
///     };
///     Ok(())
/// }
/// ```
/// When the error is dropped at the end of main() in the above example, the default callback
/// function generates the following JSON error file:
/// ```json
/// {
///   "message": "One of the tasks failed",
///   "file": "src\\main.rs",
///   "line": 7,
///   "parent": {
///     "message": "task_that_may_fail failed",
///     "file": "src\\main.rs",
///     "line": 24,
///     "parent": {
///       "message": "task_that_may_fail failed",
///       "file": "src\\main.rs",
///       "line": 13,
///       "parent": null,
///       "time_created": "2023-09-11T10:27:25.195697400Z",
///       "extra_data": null,
///       "project": null,
///       "computer": null,
///       "user": null,
///       "is_parent": true,
///       "is_handled": true,
///       "is_default": false
///     },
///     "time_created": "2023-09-11T10:27:25.195789100Z",
///     "extra_data": null,
///     "project": null,
///     "computer": null,
///     "user": null,
///     "is_parent": true,
///     "is_handled": true,
///     "is_default": false
///   },
///   "time_created": "2023-09-11T10:27:25.195836Z",
///   "extra_data": null,
///   "project": "traceback_test",
///   "computer": "tommypc",
///   "user": "tommy",
///   "is_parent": false,
///   "is_handled": true,
///   "is_default": false
/// }
/// ```
///
/// # Syntax
///
/// The `traceback!` macro supports the following syntax variations:
///
/// - `traceback!()`: Creates a `TracebackError` with an empty message, using the current file
///   and line number.
///
/// - `traceback!($msg:expr)`: Creates a `TracebackError` with the specified error message,
///   using the current file and line number.
///
/// - `traceback!(err $e:expr)`: Attempts to downcast the provided error (`$e`) to a
///   `TracebackError`. If successful, it marks the error as handled and creates a new
///   `TracebackError` instance based on the downcasted error. If the downcast fails, it
///   creates a `TracebackError` with an empty message and includes the original error's
///   description in the extra data field.
///
/// - `traceback!(err $e:expr, $msg:expr)`: Similar to the previous variation but allows specifying
///   a custom error message for the new `TracebackError` instance.
///
/// # Error Handling
///
/// When using the `traceback!` macro to create `TracebackError` instances from other error types,
/// it automatically sets the `is_handled` flag to `true` for the original error to indicate that
/// it has been handled. This prevents the `TRACEBACK_ERROR_CALLBACK` function to be called on it.
///
/// # Environment Variables
///
/// Environment variables such as `CARGO_PKG_NAME`, `COMPUTERNAME`, and `USERNAME` are automatically
/// added to the `project`, `computer`, and `user` fields when the error is being handled.
///
#[macro_export]
macro_rules! traceback {
    () => {
        $crate::TracebackError::new("".to_string(), file!().to_string(), line!())
    };
    ($msg:expr) => {
        $crate::TracebackError::new($msg.to_string(), file!().to_string(), line!())
    };
    (err $e:expr) => {{
        use $crate::serde_json::json;
        let err_string = $e.to_string();
        let mut boxed: Box<dyn std::any::Any> = Box::new($e);
        if let Some(traceback_err) = boxed.downcast_mut::<$crate::TracebackError>() {
            traceback_err.is_handled = true;
            $crate::TracebackError::new(
                traceback_err.message.to_string(),
                file!().to_string(),
                line!(),
            )
            .with_parent(traceback_err.clone())
        } else {
            $crate::TracebackError::new(String::from(""), file!().to_string(), line!())
                .with_extra_data(json!({
                    "error": err_string
                }))
        }
    }};
    (err $e:expr, $msg:expr) => {{
        use $crate::serde_json::json;
        let err_string = $e.to_string();
        let mut boxed: Box<dyn std::any::Any> = Box::new($e);
        if let Some(traceback_err) = boxed.downcast_mut::<$crate::TracebackError>() {
            traceback_err.is_handled = true;
            $crate::TracebackError::new(
                $msg.to_string(),
                file!().to_string(),
                line!(),
            )
            .with_parent(traceback_err.clone())
        } else {
            $crate::TracebackError::new(String::from(""), file!().to_string(), line!())
                .with_extra_data(json!({
                    "error": err_string
                }))
        }
    }};
}