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
//! Trait for processing log trees on completion.
//!
//! See [`Processor`] for more details.
use crate::printer::{MakeStderr, MakeStdout, Pretty, Printer};
use crate::tree::Tree;
use std::error;
use std::sync::Arc;
use thiserror::Error;

/// Error type returned if a [`Processor`] fails.
#[derive(Error, Debug)]
#[error("{source}")]
pub struct Error {
    /// The recoverable [`Tree`] type that couldn't be processed.
    pub tree: Tree,

    source: Box<dyn error::Error + Send + Sync>,
}

/// Create an error for when a [`Processor`] fails to process a [`Tree`].
pub fn error(tree: Tree, source: Box<dyn error::Error + Send + Sync>) -> Error {
    Error { tree, source }
}

/// The result type of [`Processor::process`].
pub type Result = std::result::Result<(), Error>;

/// A trait for processing completed [`Tree`]s.
///
/// `Processor`s are responsible for both formatting and writing logs to their
/// intended destinations. This is typically implemented using
/// [`Formatter`], [`MakeWriter`], and [`io::Write`].
///
/// While this trait may be implemented on downstream types, [`from_fn`]
/// provides a convenient interface for creating `Processor`s without having to
/// explicitly define new types.
///
/// [trace trees]: crate::tree::Tree
/// [`Formatter`]: crate::printer::Formatter
/// [`MakeWriter`]: tracing_subscriber::fmt::MakeWriter
/// [`io::Write`]: std::io::Write
pub trait Processor: 'static + Sized {
    /// Process a [`Tree`]. This can mean many things, such as writing to
    /// stdout or a file, sending over a network, storing in memory, ignoring,
    /// or anything else.
    ///
    /// # Errors
    ///
    /// If the `Tree` cannot be processed, then it is returned along with a
    /// `Box<dyn Error + Send + Sync>`. If the processor is configured with a
    /// fallback processor from [`Processor::or`], then the `Tree` is deferred
    /// to that processor.
    fn process(&self, tree: Tree) -> Result;

    /// Returns a `Processor` that first attempts processing with `self`, and
    /// resorts to processing with `fallback` on failure.
    ///
    /// Note that [`or_stdout`], [`or_stderr`], and [`or_none`] can be used as
    /// shortcuts for pretty printing or dropping the `Tree` entirely.
    ///
    /// [`or_stdout`]: Processor::or_stdout
    /// [`or_stderr`]: Processor::or_stderr
    /// [`or_none`]: Processor::or_none
    fn or<P: Processor>(self, processor: P) -> WithFallback<Self, P> {
        WithFallback {
            primary: self,
            fallback: processor,
        }
    }

    /// Returns a `Processor` that first attempts processing with `self`, and
    /// resorts to pretty-printing to stdout on failure.
    fn or_stdout(self) -> WithFallback<Self, Printer<Pretty, MakeStdout>> {
        self.or(Printer::new().writer(MakeStdout))
    }

    /// Returns a `Processor` that first attempts processing with `self`, and
    /// resorts to pretty-printing to stderr on failure.
    fn or_stderr(self) -> WithFallback<Self, Printer<Pretty, MakeStderr>> {
        self.or(Printer::new().writer(MakeStderr))
    }

    /// Returns a `Processor` that first attempts processing with `self`, otherwise
    /// silently fails.
    fn or_none(self) -> WithFallback<Self, Sink> {
        self.or(Sink)
    }
}

/// A [`Processor`] composed of a primary and a fallback `Processor`.
///
/// This type is returned by [`Processor::or`].
#[derive(Debug)]
pub struct WithFallback<P, F> {
    primary: P,
    fallback: F,
}

/// A [`Processor`] that ignores any incoming logs.
///
/// This processor cannot fail.
#[derive(Debug)]
pub struct Sink;

/// A [`Processor`] that processes incoming logs via a function.
///
/// Instances of `FromFn` are returned by the [`from_fn`] function.
#[derive(Debug)]
pub struct FromFn<F>(F);

/// Create a processor that processes incoming logs via a function.
///
/// # Examples
///
/// Internally, [`worker_task`] uses `from_fn` to allow the subscriber to send
/// trace data across a channel to a processing task.
/// ```
/// use tokio::sync::mpsc;
/// use tracing_forest::processor;
///
/// let (tx, rx) = mpsc::unbounded_channel();
///
/// let sender_processor = processor::from_fn(move |tree| tx
///     .send(tree)
///     .map_err(|err| {
///         let msg = err.to_string().into();
///         processor::error(err.0, msg)
///     })
/// );
///
/// // -- snip --
/// ```
///
/// [`worker_task`]: crate::runtime::worker_task
pub fn from_fn<F>(f: F) -> FromFn<F>
where
    F: 'static + Fn(Tree) -> Result,
{
    FromFn(f)
}

impl<P, F> Processor for WithFallback<P, F>
where
    P: Processor,
    F: Processor,
{
    fn process(&self, tree: Tree) -> Result {
        self.primary.process(tree).or_else(|err| {
            eprintln!("{}, using fallback processor...", err);
            self.fallback.process(err.tree)
        })
    }
}

impl Processor for Sink {
    fn process(&self, _tree: Tree) -> Result {
        Ok(())
    }
}

impl<F> Processor for FromFn<F>
where
    F: 'static + Fn(Tree) -> Result,
{
    fn process(&self, tree: Tree) -> Result {
        (self.0)(tree)
    }
}

impl<P: Processor> Processor for Box<P> {
    fn process(&self, tree: Tree) -> Result {
        self.as_ref().process(tree)
    }
}

impl<P: Processor> Processor for Arc<P> {
    fn process(&self, tree: Tree) -> Result {
        self.as_ref().process(tree)
    }
}