usiem/components/dataset/
text_map_list.rs

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