falco_event_serde/de/
events.rs

1use crate::de::repr::Repr;
2use falco_event::events::EventMetadata;
3use falco_event::fields::ToBytes;
4use serde::Deserialize;
5
6#[derive(Debug, Deserialize)]
7pub struct RawEvent {
8    pub ts: u64,
9    pub tid: i64,
10    pub event_type_id: u16,
11    pub large_payload: bool,
12    pub params: Vec<Repr>,
13}
14
15impl RawEvent {
16    pub fn append_to_vec(&self, mut buf: &mut Vec<u8>) {
17        let meta = EventMetadata {
18            ts: self.ts,
19            tid: self.tid,
20        };
21
22        let lengths = self
23            .params
24            .iter()
25            .map(|p| p.binary_size())
26            .collect::<Vec<usize>>();
27
28        let len_size = match self.large_payload {
29            true => 4,
30            false => 2,
31        };
32
33        let len = 26 + (len_size * lengths.len()) + lengths.iter().sum::<usize>();
34        meta.write_header(
35            len as u32,
36            self.event_type_id,
37            lengths.len() as u32,
38            &mut buf,
39        )
40        .unwrap();
41
42        if self.large_payload {
43            for len in lengths {
44                buf.extend_from_slice(&(len as u32).to_ne_bytes());
45            }
46        } else {
47            for len in lengths {
48                buf.extend_from_slice(&(len as u16).to_ne_bytes());
49            }
50        }
51
52        for param in &self.params {
53            param.write(&mut buf).unwrap();
54        }
55    }
56}
57
58pub trait ToRawEvent {
59    fn to_raw(self, metadata: &EventMetadata) -> RawEvent;
60}
61
62/// Represents a deserialized Falco event.
63///
64/// This struct contains an intermediate representation of a Falco event that can be serialized
65/// into a byte vector using [`Event::to_vec`] or appended to an existing byte vector using
66/// [`Event::append_to_vec`]. The resulting byte vector can then be parsed into
67/// a [`falco_event::events::RawEvent`] and further into a concrete event type.
68#[derive(Debug, Deserialize)]
69pub struct Event {
70    ts: u64,
71    tid: i64,
72    #[serde(flatten)]
73    event: crate::de::payload::AnyEvent<'static>,
74}
75
76impl Event {
77    /// Appends the serialized event to the provided byte vector.
78    pub fn append_to_vec(self, buf: &mut Vec<u8>) {
79        let metadata = EventMetadata {
80            ts: self.ts,
81            tid: self.tid,
82        };
83        self.event.to_raw(&metadata).append_to_vec(buf)
84    }
85
86    /// Converts the event into a byte vector.
87    pub fn to_vec(self) -> Vec<u8> {
88        let mut buf = Vec::new();
89        self.append_to_vec(&mut buf);
90        buf
91    }
92}