sos_core/events/
record.rs

1use crate::{
2    commit::{CommitHash, CommitTree},
3    decode, encode, Result, UtcDateTime,
4};
5use binary_stream::futures::{Decodable, Encodable};
6
7/// Record for a row in an event log.
8#[derive(Default, Debug, Clone, Eq, PartialEq)]
9pub struct EventRecord(
10    pub(crate) UtcDateTime,
11    pub(crate) CommitHash,
12    pub(crate) CommitHash,
13    pub(crate) Vec<u8>,
14);
15
16impl EventRecord {
17    /// Create an event record.
18    pub fn new(
19        time: UtcDateTime,
20        last_commit: CommitHash,
21        commit: CommitHash,
22        event: Vec<u8>,
23    ) -> Self {
24        Self(time, last_commit, commit, event)
25    }
26
27    /// Date and time the record was created.
28    pub fn time(&self) -> &UtcDateTime {
29        &self.0
30    }
31
32    /// Set the record time.
33    pub fn set_time(&mut self, time: UtcDateTime) {
34        self.0 = time;
35    }
36
37    /// Last commit hash for the record.
38    pub fn last_commit(&self) -> &CommitHash {
39        &self.1
40    }
41
42    /// Set last commit hash for the record.
43    pub fn set_last_commit(&mut self, commit: Option<CommitHash>) {
44        self.1 = commit.unwrap_or_default();
45    }
46
47    /// Commit hash for the record.
48    pub fn commit(&self) -> &CommitHash {
49        &self.2
50    }
51
52    /// Record event bytes.
53    pub fn event_bytes(&self) -> &[u8] {
54        self.3.as_slice()
55    }
56
57    /// Size of the event buffer.
58    pub fn size(&self) -> usize {
59        self.3.len()
60    }
61
62    /// Decode this event record.
63    pub async fn decode_event<T: Default + Decodable>(&self) -> Result<T> {
64        Ok(decode(&self.3).await?)
65    }
66
67    /// Encode an event into an event record.
68    ///
69    /// Encodes using a zero last commit and now
70    /// as the date time.
71    pub async fn encode_event<T: Default + Encodable>(
72        event: &T,
73    ) -> Result<Self> {
74        let bytes = encode(event).await?;
75        let commit = CommitHash(CommitTree::hash(&bytes));
76        Ok(EventRecord(
77            Default::default(),
78            Default::default(),
79            commit,
80            bytes,
81        ))
82    }
83}
84
85impl From<EventRecord> for (UtcDateTime, CommitHash, CommitHash, Vec<u8>) {
86    fn from(value: EventRecord) -> Self {
87        (value.0, value.1, value.2, value.3)
88    }
89}