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
//! A simple input logging node.
//!
//! This node logs the input to the console and passes it through unchanged.
use crate::error::AnchorChainError;
use crate::node::Node;
use anchor_chain_macros::Stateless;
#[cfg(feature = "tracing")]
use tracing::instrument;

/// A simple input logging node
#[derive(Debug, Stateless)]
pub struct Logger<T>
where
    T: std::fmt::Debug + Send + Sync,
{
    prefix: String,
    _marker: std::marker::PhantomData<T>,
}

impl<T> Logger<T>
where
    T: std::fmt::Debug + Send + Sync,
{
    /// Create a new Logger node with the given prefix.
    ///
    /// The prefix is prepended to the input in the format `prefix: input`.
    pub fn new(prefix: &str) -> Self {
        Self {
            prefix: prefix.to_string(),
            _marker: std::marker::PhantomData,
        }
    }
}

#[async_trait::async_trait]
impl<T> Node for Logger<T>
where
    T: std::fmt::Debug + Send + Sync,
{
    type Input = T;
    type Output = T;

    /// Log the input and pass it through unchanged.
    #[cfg_attr(feature = "tracing", instrument)]
    async fn process(&self, input: Self::Input) -> Result<Self::Output, AnchorChainError> {
        println!("{}: {:?}", self.prefix, input);
        Ok(input)
    }
}

impl<T> Default for Logger<T>
where
    T: std::fmt::Debug + Send + Sync,
{
    fn default() -> Self {
        Self {
            prefix: "Input".to_string(),
            _marker: std::marker::PhantomData,
        }
    }
}