summaryrefslogtreecommitdiffstats
path: root/plugins/plugin_log/src/lib.rs
blob: a23023958d124bd47f7a4e19a70bdea6dbb53eed (plain)
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
use std::marker::PhantomData;

use async_trait::async_trait;

use tedge_api::address::ReplySenderFor;
use tedge_api::plugin::BuiltPlugin;
use tedge_api::plugin::DoesHandle;
use tedge_api::plugin::Handle;
use tedge_api::plugin::HandleTypes;
use tedge_api::plugin::Message;
use tedge_api::plugin::MessageBundle;
use tedge_api::plugin::PluginExt;
use tedge_api::Plugin;
use tedge_api::PluginBuilder;
use tedge_api::PluginConfiguration;
use tedge_api::PluginDirectory;
use tedge_api::PluginError;
use tokio_util::sync::CancellationToken;
use tracing::debug;
use tracing::event;

pub struct LogPluginBuilder<MB: MessageBundle> {
    _pd: PhantomData<MB>,
}

impl<MB: MessageBundle> LogPluginBuilder<MB> {
    pub fn new() -> Self {
        LogPluginBuilder {
            _pd: PhantomData,
        }
    }
}

#[derive(serde::Deserialize, Debug)]
struct LogConfig {
    level: log::Level,
    acknowledge: bool,
}

#[derive(Debug, miette::Diagnostic, thiserror::Error)]
enum Error {
    #[error("Failed to parse configuration")]
    ConfigParseFailed(#[from] toml::de::Error),
}


#[async_trait]
impl<PD, MB> PluginBuilder<PD> for LogPluginBuilder<MB>
where
    PD: PluginDirectory,
    MB: MessageBundle + Sync + Send + 'static,
    LogPlugin<MB>: DoesHandle<MB>,
{
    fn kind_name() -> &'static str {
        "log"
    }

    fn kind_message_types() -> HandleTypes
    where
        Self: Sized,
    {
        LogPlugin::get_handled_types()
    }

    async fn verify_configuration(
        &self,
        config: &PluginConfiguration,
    ) -> Result<(), tedge_api::error::PluginError> {
        config
            .clone()
            .try_into()
            .map(|_: LogConfig| ())
            .map_err(Error::from)
            .map_err(PluginError::from)
    }

    async fn instantiate(
        &self,
        config: PluginConfiguration,
        _cancellation_token: CancellationToken,
        _plugin_dir: &PD,
    ) -> Result<BuiltPlugin, PluginError> {
        let config = config
            .try_into::<LogConfig>()
            .map_err(Error::from)?;

        Ok(LogPlugin::<MB>::new(config).finish())
    }
}

struct LogPlugin<MB> {
    _pd: PhantomData<MB>,
    config: LogConfig,
}

impl<MB> tedge_api::plugin::PluginDeclaration for LogPlugin<MB>
    where MB: MessageBundle + Sync + Send + 'static,
{
    type HandledMessages = MB;
}


impl<MB> LogPlugin<MB>
where
    MB: MessageBundle + Sync + Send + 'static,
{
    fn new(config: LogConfig) -> Self {
        Self { _pd: PhantomData, config }
    }
}

#[async_trait]
impl<MB> Plugin for LogPlugin<MB>
where
    MB: MessageBundle + Sync + Send + 'static,
{
    async fn start(&mut self) -> Result<(), PluginError> {
        debug!(
            "Setting up log plugin with default level = {}, acknowledge = {}!",
            self.config.level, self.config.acknowledge
        );

        Ok(())
    }

    async fn shutdown(&mut self) -> Result<(), PluginError> {
        debug!("Shutting down log plugin!");
        Ok(())
    }
}

#[async_trait]
impl<M, MB> Handle<M> for LogPlugin<MB>
where
    M: Message + std::fmt::Debug,
    MB: MessageBundle + Sync + Send + 'static,
{
    async fn handle_message(
        &self,
        message: M,
        _sender: ReplySenderFor<M>,
    ) -> Result<(), PluginError> {
        match self.config.level {
            log::Level::Trace => {
                event!(tracing::Level::TRACE, "Received Message: {:?}", message);
            }
            log::Level::Debug => {
                event!(tracing::Level::DEBUG, "Received Message: {:?}", message);
            }
            log::Level::Info => event!(tracing::Level::INFO, "Received Message: {:?}", message),
            log::Level::Warn => event!(tracing::Level::WARN, "Received Message: {:?}", message),
            log::Level::Error => {
                event!(tracing::Level::ERROR, "Received Message: {:?}", message)
            }
        }

        Ok(())
    }
}