usiem/components/dataset/
text_map.rs

1use crate::prelude::types::LogString;
2use crossbeam_channel::Sender;
3use serde::Serialize;
4use std::collections::BTreeMap;
5use std::sync::Arc;
6#[derive(Serialize, Debug)]
7pub enum UpdateTextMap {
8    Add((LogString, LogString)),
9    Remove(LogString),
10    Replace(TextMapDataset),
11}
12#[derive(Debug, Clone)]
13pub struct TextMapSynDataset {
14    dataset: Arc<TextMapDataset>,
15    comm: Sender<UpdateTextMap>,
16}
17impl TextMapSynDataset {
18    pub fn new(dataset: Arc<TextMapDataset>, comm: Sender<UpdateTextMap>) -> Self {
19        Self { dataset, comm }
20    }
21    pub fn empty() -> Self {
22        let (sender, _) = crossbeam_channel::bounded(1);
23        Self {
24            dataset: Arc::new(TextMapDataset::new()),
25            comm: sender,
26        }
27    }
28    pub fn insert<S>(&self, key: S, data: S)
29    where
30        S: Into<LogString>,
31    {
32        let _ = self
33            .comm
34            .try_send(UpdateTextMap::Add((key.into(), data.into())));
35    }
36    pub fn remove<S>(&self, key: S)
37    where
38        S: Into<LogString>,
39    {
40        // Todo: improve with local cache to send retries
41        let _ = self.comm.try_send(UpdateTextMap::Remove(key.into()));
42    }
43    pub fn update(&self, data: TextMapDataset) {
44        // Todo: improve with local cache to send retries
45        let _ = self.comm.try_send(UpdateTextMap::Replace(data));
46    }
47    pub fn get(&self, key: &str) -> Option<&LogString> {
48        // Todo improve with cached content
49        self.dataset.get(key)
50    }
51}
52#[derive(Serialize, Debug, Default)]
53pub struct TextMapDataset {
54    data: BTreeMap<LogString, LogString>,
55}
56
57impl TextMapDataset {
58    pub fn new() -> TextMapDataset {
59        Self::default()
60    }
61    pub fn insert<S>(&mut self, key: S, data: S)
62    where
63        S: Into<LogString>,
64    {
65        self.data.insert(key.into(), data.into());
66    }
67    pub fn get(&self, key: &str) -> Option<&LogString> {
68        self.data.get(key)
69    }
70    pub fn internal_ref(&self) -> &BTreeMap<LogString, LogString> {
71        &self.data
72    }
73}
74
75#[cfg(test)]
76mod tests {
77
78    use super::*;
79    #[test]
80    fn should_find_data_in_map() {
81        let mut dataset = TextMapDataset::new();
82        dataset.insert(
83            LogString::Borrowed("192.168.1.1"),
84            LogString::Borrowed("Local IP"),
85        );
86        assert_eq!(
87            dataset.get("192.168.1.1"),
88            Some(&LogString::Borrowed("Local IP"))
89        );
90    }
91}