Skip to main content

rsigma_eval/correlation/
buffers.rs

1use std::collections::VecDeque;
2use std::io::{Read as IoRead, Write as IoWrite};
3use std::sync::Arc;
4
5use flate2::Compression;
6use flate2::read::DeflateDecoder;
7use flate2::write::DeflateEncoder;
8use serde::Serialize;
9
10use crate::result::EventSource;
11
12// =============================================================================
13// Compressed Event Buffer
14// =============================================================================
15
16/// Default compression level — fast compression (level 1) for minimal latency.
17/// Deflate level 1 still achieves ~2-3x compression on JSON while being very fast.
18const COMPRESSION_LEVEL: Compression = Compression::fast();
19
20/// One retained event body: the sequence number the event was processed with,
21/// its timestamp, its deflate-compressed JSON, and where it came from.
22#[derive(Debug, Clone)]
23pub(crate) struct FullEntry {
24    pub(crate) seq: u64,
25    pub(crate) ts: i64,
26    pub(crate) data: Vec<u8>,
27    /// Referenced rule the event matched.
28    pub(crate) rule: Option<Arc<str>>,
29    /// Child correlation that delivered the event to this buffer.
30    pub(crate) via: Option<Arc<str>>,
31}
32
33impl FullEntry {
34    /// Convert this entry to a reference entry, keeping its sequence number
35    /// and source.
36    pub(crate) fn to_ref(&self) -> Option<RefEntry> {
37        let event = decompress_event(&self.data)?;
38        Some(RefEntry {
39            r: EventRef {
40                timestamp: self.ts,
41                id: extract_event_id(&event),
42            },
43            seq: self.seq,
44            rule: self.rule.clone(),
45            via: self.via.clone(),
46        })
47    }
48}
49
50fn event_source(rule: &Option<Arc<str>>, via: &Option<Arc<str>>) -> EventSource {
51    EventSource {
52        rule: rule.as_deref().map(str::to_owned),
53        via: via.as_deref().map(str::to_owned),
54    }
55}
56
57/// Compressed event storage for correlation event inclusion.
58///
59/// Stores event JSON payloads as individually deflate-compressed blobs alongside
60/// their timestamps. This enables per-event eviction (matching `WindowState`
61/// eviction) while keeping memory usage low.
62///
63/// # Memory Model
64///
65/// Each stored event costs approximately `compressed_size + 24` bytes
66/// (8 for timestamp, 16 for Vec overhead). Typical JSON events (500B–5KB)
67/// compress to 100B–1KB with deflate, giving 3–5x memory savings.
68///
69/// The buffer enforces a hard cap (`max_events`) so memory is bounded at:
70///   `max_events × (avg_compressed_size + 24)` bytes per group key.
71#[derive(Debug, Clone, Serialize, serde::Deserialize)]
72pub struct EventBuffer {
73    /// (timestamp, deflate-compressed event JSON) pairs, ordered by timestamp.
74    #[serde(with = "event_buffer_serde")]
75    entries: VecDeque<FullEntry>,
76    /// Maximum number of events to retain. When exceeded, the oldest event is
77    /// evicted regardless of the time window.
78    max_events: usize,
79}
80
81/// Custom serde for EventBuffer entries: encodes compressed bytes as base64
82/// instead of JSON number arrays, cutting snapshot size ~3x.
83mod event_buffer_serde {
84    use serde::{Deserialize, Deserializer, Serialize, Serializer};
85    use std::collections::VecDeque;
86    use std::sync::Arc;
87
88    use super::FullEntry;
89
90    #[derive(Serialize, Deserialize)]
91    struct Entry {
92        ts: i64,
93        #[serde(with = "base64_bytes")]
94        data: Vec<u8>,
95        #[serde(default)]
96        seq: u64,
97        #[serde(default, skip_serializing_if = "Option::is_none")]
98        rule: Option<Arc<str>>,
99        #[serde(default, skip_serializing_if = "Option::is_none")]
100        via: Option<Arc<str>>,
101    }
102
103    mod base64_bytes {
104        use base64::Engine as _;
105        use base64::engine::general_purpose::STANDARD;
106        use serde::{Deserializer, Serializer};
107
108        pub fn serialize<S: Serializer>(bytes: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> {
109            s.serialize_str(&STANDARD.encode(bytes))
110        }
111
112        pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
113            let s: String = serde::Deserialize::deserialize(d)?;
114            STANDARD.decode(s).map_err(serde::de::Error::custom)
115        }
116    }
117
118    pub fn serialize<S: Serializer>(
119        entries: &VecDeque<FullEntry>,
120        s: S,
121    ) -> Result<S::Ok, S::Error> {
122        let v: Vec<Entry> = entries
123            .iter()
124            .map(|e| Entry {
125                ts: e.ts,
126                data: e.data.clone(),
127                seq: e.seq,
128                rule: e.rule.clone(),
129                via: e.via.clone(),
130            })
131            .collect();
132        v.serialize(s)
133    }
134
135    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<VecDeque<FullEntry>, D::Error> {
136        let v: Vec<Entry> = Vec::deserialize(d)?;
137        Ok(v.into_iter()
138            .map(|e| FullEntry {
139                seq: e.seq,
140                ts: e.ts,
141                data: e.data,
142                rule: e.rule,
143                via: e.via,
144            })
145            .collect())
146    }
147}
148
149impl EventBuffer {
150    /// Create a new event buffer with the given capacity cap.
151    pub fn new(max_events: usize) -> Self {
152        EventBuffer {
153            entries: VecDeque::with_capacity(max_events.min(64)),
154            max_events,
155        }
156    }
157
158    /// Compress and store an event with sequence number 0, meaning unsequenced,
159    /// and no source.
160    pub fn push(&mut self, ts: i64, event: &serde_json::Value) {
161        self.push_seq(0, ts, event, None);
162    }
163
164    /// Compress and store an event under its processing sequence number and
165    /// the referenced rule it matched. Evicts the oldest entry if at capacity.
166    pub(crate) fn push_seq(
167        &mut self,
168        seq: u64,
169        ts: i64,
170        event: &serde_json::Value,
171        rule: Option<Arc<str>>,
172    ) {
173        // Compress the event JSON with deflate
174        if let Some(compressed) = compress_event(event) {
175            if self.entries.len() >= self.max_events {
176                self.entries.pop_front();
177            }
178            self.entries.push_back(FullEntry {
179                seq,
180                ts,
181                data: compressed,
182                rule,
183                via: None,
184            });
185        }
186    }
187
188    /// Remove all entries older than the cutoff timestamp.
189    pub fn evict(&mut self, cutoff: i64) {
190        while self.entries.front().is_some_and(|e| e.ts < cutoff) {
191            self.entries.pop_front();
192        }
193    }
194
195    /// Decompress and return all stored events.
196    pub fn decompress_all(&self) -> Vec<serde_json::Value> {
197        self.entries
198            .iter()
199            .filter_map(|e| decompress_event(&e.data))
200            .collect()
201    }
202
203    /// Returns true if there are no stored events.
204    pub fn is_empty(&self) -> bool {
205        self.entries.is_empty()
206    }
207
208    /// Clear all stored events.
209    pub fn clear(&mut self) {
210        self.entries.clear();
211    }
212
213    /// Total compressed bytes stored (for monitoring/diagnostics).
214    pub fn compressed_bytes(&self) -> usize {
215        self.entries.iter().map(|e| e.data.len()).sum()
216    }
217
218    /// Number of stored events.
219    pub fn len(&self) -> usize {
220        self.entries.len()
221    }
222
223    /// Snapshot of the retained entries, for a parent correlation to merge.
224    pub(crate) fn retained(&self) -> Retained {
225        Retained::Full(self.entries.iter().cloned().collect())
226    }
227
228    /// Merge entries delivered by the firing child correlation `via` into this
229    /// buffer.
230    ///
231    /// Entries are inserted in `(timestamp, seq)` order with `via` as their
232    /// source, an entry with a nonzero seq that is already present is skipped
233    /// and keeps its existing source, and the oldest entries above the cap are
234    /// dropped.
235    pub(crate) fn merge(&mut self, entries: &[FullEntry], via: Option<&Arc<str>>) {
236        for entry in entries {
237            // An event is processed once with one timestamp, so a nonzero seq
238            // always comes with the same `ts` and a duplicate sorts right
239            // before the insertion point.
240            let pos = self
241                .entries
242                .partition_point(|e| (e.ts, e.seq) <= (entry.ts, entry.seq));
243            if entry.seq != 0 && pos > 0 && self.entries[pos - 1].seq == entry.seq {
244                continue;
245            }
246            let mut entry = entry.clone();
247            entry.via = via.cloned();
248            self.entries.insert(pos, entry);
249        }
250        while self.entries.len() > self.max_events {
251            self.entries.pop_front();
252        }
253    }
254
255    /// Decompress the newest `n` entries, oldest first, with their sources
256    /// index for index.
257    pub(crate) fn newest_events(&self, n: usize) -> (Vec<serde_json::Value>, Vec<EventSource>) {
258        let start = self.entries.len().saturating_sub(n);
259        self.entries
260            .iter()
261            .skip(start)
262            .filter_map(|e| Some((decompress_event(&e.data)?, event_source(&e.rule, &e.via))))
263            .unzip()
264    }
265
266    /// Convert the newest `n` entries to event references, oldest first, with
267    /// their sources index for index.
268    pub(crate) fn newest_refs(&self, n: usize) -> (Vec<EventRef>, Vec<EventSource>) {
269        let start = self.entries.len().saturating_sub(n);
270        self.entries
271            .iter()
272            .skip(start)
273            .filter_map(FullEntry::to_ref)
274            .map(|e| {
275                let source = event_source(&e.rule, &e.via);
276                (e.r, source)
277            })
278            .unzip()
279    }
280
281    /// Highest sequence number currently retained.
282    pub(crate) fn max_seq(&self) -> u64 {
283        self.entries.iter().map(|e| e.seq).max().unwrap_or(0)
284    }
285
286    /// Assign fresh sequence numbers to entries restored without one.
287    pub(crate) fn sequence_unsequenced(&mut self, next: &mut u64) {
288        for entry in &mut self.entries {
289            if entry.seq == 0 {
290                entry.seq = *next;
291                *next = next.saturating_add(1);
292            }
293        }
294    }
295}
296
297/// Compress an event JSON value using deflate.
298pub(super) fn compress_event(event: &serde_json::Value) -> Option<Vec<u8>> {
299    let json_bytes = serde_json::to_vec(event).ok()?;
300    let mut encoder = DeflateEncoder::new(Vec::new(), COMPRESSION_LEVEL);
301    encoder.write_all(&json_bytes).ok()?;
302    encoder.finish().ok()
303}
304
305/// Decompress a deflate-compressed event back to a JSON value.
306pub(super) fn decompress_event(compressed: &[u8]) -> Option<serde_json::Value> {
307    let mut decoder = DeflateDecoder::new(compressed);
308    let mut json_bytes = Vec::new();
309    decoder.read_to_end(&mut json_bytes).ok()?;
310    serde_json::from_slice(&json_bytes).ok()
311}
312
313// =============================================================================
314// Event Reference (lightweight mode)
315// =============================================================================
316
317/// A lightweight event reference: timestamp plus optional event ID.
318///
319/// Used in `Refs` mode for memory-efficient correlation event tracking.
320/// Each ref costs ~40 bytes (vs. 100–1000+ bytes for compressed events),
321/// making this mode suitable for high-volume correlations where only
322/// traceability is needed.
323#[derive(Debug, Clone, Serialize, serde::Deserialize)]
324pub struct EventRef {
325    /// Event timestamp (epoch seconds).
326    pub timestamp: i64,
327    /// Event ID extracted from common fields (`id`, `_id`, `event_id`, etc.).
328    #[serde(skip_serializing_if = "Option::is_none")]
329    pub id: Option<String>,
330}
331
332/// One retained event reference: the reference plus the sequence number the
333/// event was processed with and where it came from.
334#[derive(Debug, Clone, Serialize, serde::Deserialize)]
335pub(crate) struct RefEntry {
336    #[serde(flatten)]
337    pub(crate) r: EventRef,
338    #[serde(default)]
339    pub(crate) seq: u64,
340    /// Referenced rule the event matched.
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub(crate) rule: Option<Arc<str>>,
343    /// Child correlation that delivered the event to this buffer.
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub(crate) via: Option<Arc<str>>,
346}
347
348/// Lightweight event reference buffer for `Refs` mode.
349///
350/// Stores only timestamps and optional event IDs — no event payload,
351/// no compression. This is the minimal-memory alternative to `EventBuffer`.
352#[derive(Debug, Clone, Serialize, serde::Deserialize)]
353pub struct EventRefBuffer {
354    /// Event references, ordered by timestamp.
355    entries: VecDeque<RefEntry>,
356    /// Maximum number of refs to retain.
357    max_events: usize,
358}
359
360impl EventRefBuffer {
361    /// Create a new ref buffer with the given capacity cap.
362    pub fn new(max_events: usize) -> Self {
363        EventRefBuffer {
364            entries: VecDeque::with_capacity(max_events.min(64)),
365            max_events,
366        }
367    }
368
369    /// Store a reference to an event with sequence number 0, meaning
370    /// unsequenced, and no source.
371    pub fn push(&mut self, ts: i64, event: &serde_json::Value) {
372        self.push_seq(0, ts, event, None);
373    }
374
375    /// Store a reference to an event under its processing sequence number and
376    /// the referenced rule it matched. Evicts the oldest ref if at capacity.
377    pub(crate) fn push_seq(
378        &mut self,
379        seq: u64,
380        ts: i64,
381        event: &serde_json::Value,
382        rule: Option<Arc<str>>,
383    ) {
384        if self.entries.len() >= self.max_events {
385            self.entries.pop_front();
386        }
387        let id = extract_event_id(event);
388        self.entries.push_back(RefEntry {
389            r: EventRef { timestamp: ts, id },
390            seq,
391            rule,
392            via: None,
393        });
394    }
395
396    /// Remove all refs older than the cutoff timestamp.
397    pub fn evict(&mut self, cutoff: i64) {
398        while self.entries.front().is_some_and(|e| e.r.timestamp < cutoff) {
399            self.entries.pop_front();
400        }
401    }
402
403    /// Return cloned refs.
404    pub fn refs(&self) -> Vec<EventRef> {
405        self.entries.iter().map(|e| e.r.clone()).collect()
406    }
407
408    /// Returns true if there are no stored refs.
409    pub fn is_empty(&self) -> bool {
410        self.entries.is_empty()
411    }
412
413    /// Clear all stored refs.
414    pub fn clear(&mut self) {
415        self.entries.clear();
416    }
417
418    /// Number of stored refs.
419    pub fn len(&self) -> usize {
420        self.entries.len()
421    }
422
423    /// Snapshot of the retained entries, for a parent correlation to merge.
424    pub(crate) fn retained(&self) -> Retained {
425        Retained::Refs(self.entries.iter().cloned().collect())
426    }
427
428    /// Merge entries delivered by the firing child correlation `via` into this
429    /// buffer.
430    ///
431    /// Entries are inserted in `(timestamp, seq)` order with `via` as their
432    /// source, an entry with a nonzero seq that is already present is skipped
433    /// and keeps its existing source, and the oldest entries above the cap are
434    /// dropped.
435    pub(crate) fn merge(&mut self, entries: &[RefEntry], via: Option<&Arc<str>>) {
436        for entry in entries {
437            // See `EventBuffer::merge`: a duplicate sorts right before the
438            // insertion point.
439            let pos = self
440                .entries
441                .partition_point(|e| (e.r.timestamp, e.seq) <= (entry.r.timestamp, entry.seq));
442            if entry.seq != 0 && pos > 0 && self.entries[pos - 1].seq == entry.seq {
443                continue;
444            }
445            let mut entry = entry.clone();
446            entry.via = via.cloned();
447            self.entries.insert(pos, entry);
448        }
449        while self.entries.len() > self.max_events {
450            self.entries.pop_front();
451        }
452    }
453
454    /// Clone the newest `n` entries, oldest first, with their sources index
455    /// for index.
456    pub(crate) fn newest_refs(&self, n: usize) -> (Vec<EventRef>, Vec<EventSource>) {
457        let start = self.entries.len().saturating_sub(n);
458        self.entries
459            .iter()
460            .skip(start)
461            .map(|e| (e.r.clone(), event_source(&e.rule, &e.via)))
462            .unzip()
463    }
464
465    /// Highest sequence number currently retained.
466    pub(crate) fn max_seq(&self) -> u64 {
467        self.entries.iter().map(|e| e.seq).max().unwrap_or(0)
468    }
469
470    /// Assign fresh sequence numbers to entries restored without one.
471    pub(crate) fn sequence_unsequenced(&mut self, next: &mut u64) {
472        for entry in &mut self.entries {
473            if entry.seq == 0 {
474                entry.seq = *next;
475                *next = next.saturating_add(1);
476            }
477        }
478    }
479}
480
481/// Retained entries captured from a correlation that fired.
482#[derive(Debug, Clone)]
483pub(crate) enum Retained {
484    /// Compressed event bodies.
485    Full(Vec<FullEntry>),
486    /// Lightweight event references.
487    Refs(Vec<RefEntry>),
488}
489
490/// Try to extract an event ID from common fields.
491///
492/// Checks (in order): `id`, `_id`, `event_id`, `EventRecordID`, `event.id`.
493/// Returns the first found value as a string.
494pub(super) fn extract_event_id(event: &serde_json::Value) -> Option<String> {
495    const ID_FIELDS: &[&str] = &["id", "_id", "event_id", "EventRecordID", "event.id"];
496    for field in ID_FIELDS {
497        if let Some(val) = event.get(field) {
498            return match val {
499                serde_json::Value::String(s) => Some(s.clone()),
500                serde_json::Value::Number(n) => Some(n.to_string()),
501                _ => None,
502            };
503        }
504    }
505    None
506}