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
use crate::action::{Action, ActionSignal, Props, StatefulAction, INFINITE};
use crate::comm::{QWriter, Signal, SignalId};
use crate::resource::{LoggerSignal, ResourceMap, IO};
use crate::server::{AsyncSignal, Config, State, SyncSignal};
use eyre::{eyre, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Debug, Deserialize, Serialize)]
pub struct Logger {
group: String,
in_mapping: BTreeMap<SignalId, String>,
}
stateful!(Logger {
group: String,
in_mapping: BTreeMap<SignalId, String>,
});
impl Action for Logger {
#[inline]
fn in_signals(&self) -> BTreeSet<SignalId> {
self.in_mapping.keys().cloned().collect()
}
fn init(self) -> Result<Box<dyn Action>>
where
Self: 'static + Sized,
{
if self.group.is_empty() {
Err(eyre!("Logger's `group` cannot be empty."))
} else if self.in_mapping.is_empty() {
Err(eyre!("Logger without `in_mapping` is useless."))
} else {
Ok(Box::new(self))
}
}
fn stateful(
&self,
_io: &IO,
_res: &ResourceMap,
_config: &Config,
_sync_writer: &QWriter<SyncSignal>,
_async_writer: &QWriter<AsyncSignal>,
) -> Result<Box<dyn StatefulAction>> {
Ok(Box::new(StatefulLogger {
done: false,
group: self.group.clone(),
in_mapping: self.in_mapping.clone(),
}))
}
}
impl StatefulAction for StatefulLogger {
impl_stateful!();
fn props(&self) -> Props {
INFINITE.into()
}
fn start(
&mut self,
_sync_writer: &mut QWriter<SyncSignal>,
_async_writer: &mut QWriter<AsyncSignal>,
_state: &State,
) -> Result<Signal> {
Ok(Signal::none())
}
fn update(
&mut self,
signal: &ActionSignal,
_sync_writer: &mut QWriter<SyncSignal>,
async_writer: &mut QWriter<AsyncSignal>,
state: &State,
) -> Result<Signal> {
let mut entries = vec![];
if let ActionSignal::StateChanged(_, signal) = signal {
for id in signal {
if let Some(name) = self.in_mapping.get(id) {
if let Some(value) = state.get(id) {
entries.push((name.clone(), value.clone()));
}
}
}
}
async_writer.push(LoggerSignal::Extend(self.group.clone(), entries));
Ok(Signal::none())
}
fn stop(
&mut self,
_sync_writer: &mut QWriter<SyncSignal>,
_async_writer: &mut QWriter<AsyncSignal>,
_state: &State,
) -> Result<Signal> {
self.done = true;
Ok(Signal::none())
}
}