saito_core/core/
stat_thread.rs1use std::collections::VecDeque;
2use std::time::Duration;
3
4use async_trait::async_trait;
5use log::info;
6
7use crate::core::defs::Timestamp;
8use crate::core::io::interface_io::InterfaceIO;
9use crate::core::io::network_event::NetworkEvent;
10use crate::core::process::process_event::ProcessEvent;
11
12const STAT_FILENAME: &str = "./data/saito.stats";
13
14pub struct StatThread {
15 pub stat_queue: VecDeque<String>,
16 pub io_interface: Box<dyn InterfaceIO + Send + Sync>,
17 pub enabled: bool,
18}
19
20impl StatThread {
21 pub async fn new(io_interface: Box<dyn InterfaceIO + Send + Sync>) -> StatThread {
22 StatThread {
23 io_interface,
24 stat_queue: VecDeque::new(),
25 enabled: true,
26 }
27 }
28}
29
30#[async_trait]
31impl ProcessEvent<String> for StatThread {
32 async fn process_network_event(&mut self, _event: NetworkEvent) -> Option<()> {
33 None
34 }
35
36 async fn process_timer_event(&mut self, _duration: Duration) -> Option<()> {
37 let mut work_done = false;
38 if !self.enabled {
39 return None;
40 }
41
42 for stat in self.stat_queue.drain(..) {
43 let stat = stat + "\r\n";
44 self.io_interface
45 .append_value(STAT_FILENAME, stat.as_bytes())
46 .await
47 .unwrap();
48 work_done = true;
49 }
50 if work_done {
51 self.io_interface.flush_data(STAT_FILENAME).await.unwrap();
52 return Some(());
53 }
54 None
55 }
56
57 async fn process_event(&mut self, event: String) -> Option<()> {
58 if !self.enabled {
59 return None;
60 }
61 self.stat_queue.push_back(event);
62 Some(())
63 }
64
65 async fn on_init(&mut self) {
66 info!("initializing stat thread");
67 if !self.enabled {
68 info!("stat thread is off");
69 return;
70 }
71 self.io_interface
72 .write_value(STAT_FILENAME, vec![].as_slice())
73 .await
74 .unwrap();
75 info!("stat thread is on");
76 }
77
78 async fn on_stat_interval(&mut self, _current_time: Timestamp) {}
79
80 fn is_ready_to_process(&self) -> bool {
81 true
82 }
83}