sigma_rust/
event.rs

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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use crate::field::FieldValue;
use std::collections::HashMap;
use std::hash::Hash;

#[cfg(feature = "serde_json")]
#[derive(Debug, serde::Deserialize)]
struct EventProxy {
    #[serde(flatten)]
    value: serde_json::Value,
}

#[derive(Debug, PartialEq)]
pub enum EventValue {
    Value(FieldValue),
    Sequence(Vec<EventValue>),
    Map(HashMap<String, EventValue>),
}

#[cfg(feature = "serde_json")]
impl TryFrom<serde_json::Value> for EventValue {
    type Error = crate::error::JSONError;

    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
        match value {
            serde_json::Value::Null
            | serde_json::Value::Bool(_)
            | serde_json::Value::Number(_)
            | serde_json::Value::String(_) => Ok(Self::Value(FieldValue::try_from(value)?)),
            serde_json::Value::Array(a) => {
                let mut result = Vec::with_capacity(a.len());
                for item in a {
                    result.push(Self::try_from(item)?);
                }
                Ok(Self::Sequence(result))
            }
            serde_json::Value::Object(data) => {
                let mut result = HashMap::with_capacity(data.len());
                for (key, value) in data {
                    result.insert(key, Self::try_from(value)?);
                }
                Ok(Self::Map(result))
            }
        }
    }
}

impl EventValue {
    pub(crate) fn contains(&self, s: &str) -> bool {
        match self {
            Self::Value(v) => v.value_to_string().contains(s),
            Self::Sequence(seq) => seq.iter().any(|v| v.contains(s)),
            Self::Map(m) => m.values().any(|v| v.contains(s)),
        }
    }
}

impl<T> From<T> for EventValue
where
    T: Into<FieldValue>,
{
    fn from(value: T) -> Self {
        Self::Value(value.into())
    }
}

/// The `Event` struct represents a log event.
///
/// It is a collection of key-value pairs
/// where the key is a string and the value is a string, number, or boolean
/// The value may also be `None` to represent a null value.
#[derive(Debug, Default)]
#[cfg_attr(feature = "serde_json", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde_json", serde(try_from = "EventProxy"))]
pub struct Event {
    inner: HashMap<String, EventValue>,
}

#[cfg(feature = "serde_json")]
impl TryFrom<EventProxy> for Event {
    type Error = crate::error::JSONError;

    fn try_from(other: EventProxy) -> Result<Self, Self::Error> {
        Self::try_from(other.value)
    }
}

impl<T, S, const N: usize> From<[(S, T); N]> for Event
where
    S: Into<String> + Hash + Eq,
    T: Into<EventValue>,
{
    fn from(values: [(S, T); N]) -> Self {
        let mut data = HashMap::with_capacity(N);
        for (k, v) in values {
            data.insert(k.into(), v.into());
        }
        Self { inner: data }
    }
}

impl Event {
    /// Create a new empty event
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert a key-value pair into the event.
    /// If the key already exists, the value will be replaced.
    ///
    /// # Example
    /// ```rust
    /// use sigma_rust::Event;
    /// let mut event = Event::new();
    /// event.insert("name", "John Doe");
    /// event.insert("age", 43);
    /// event.insert("is_admin", true);
    /// event.insert("null_value", None);
    /// ```
    pub fn insert<T, S>(&mut self, key: S, value: T)
    where
        S: Into<String> + Hash + Eq,
        T: Into<EventValue>,
    {
        self.inner.insert(key.into(), value.into());
    }

    /// Iterate over the key-value pairs in the event
    pub fn iter(&self) -> impl Iterator<Item = (&String, &EventValue)> {
        self.inner.iter()
    }

    /// Get the value for a key in the event
    pub fn get(&self, key: &str) -> Option<&EventValue> {
        if let Some(ev) = self.inner.get(key) {
            return Some(ev);
        }

        let mut nested_key = key;
        let mut current = &self.inner;
        while let Some((head, tail)) = nested_key.split_once('.') {
            if let Some(EventValue::Map(map)) = current.get(head) {
                if let Some(value) = map.get(tail) {
                    return Some(value);
                }
                current = map;
                nested_key = tail;
            } else {
                return None;
            }
        }
        None
    }

    pub fn values(&self) -> impl Iterator<Item = &EventValue> {
        self.inner.values()
    }
}

#[cfg(feature = "serde_json")]
impl TryFrom<serde_json::Value> for Event {
    type Error = crate::error::JSONError;

    fn try_from(data: serde_json::Value) -> Result<Self, Self::Error> {
        let mut result = Self::default();
        match data {
            serde_json::Value::Object(data) => {
                for (key, value) in data {
                    result.insert(key, EventValue::try_from(value)?);
                }
            }
            _ => return Err(Self::Error::InvalidEvent()),
        }
        Ok(result)
    }
}

#[cfg(feature = "serde_json")]
#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_load_from_json() {
        let event: Event = json!({
            "name": "John Doe",
            "age": 43,
            "address": {
                "city": "New York",
                "state": "NY"
            }
        })
        .try_into()
        .unwrap();

        assert_eq!(event.inner["name"], EventValue::from("John Doe"));
        assert_eq!(event.inner["age"], EventValue::from(43));
        assert_eq!(
            event.inner["address"],
            EventValue::Map({
                let mut map = HashMap::new();
                map.insert("city".to_string(), EventValue::from("New York"));
                map.insert("state".to_string(), EventValue::from("NY"));
                map
            })
        );
    }
}