Skip to main content

intrepid_model/events/
event.rs

1use bytes::Bytes;
2
3use crate::{CacheRecord, IntoCache, SubscriptionMarker};
4
5use super::{EventKind, EventRepo, EventRepoError};
6
7/// An event in a stream. This is slimmer than the `EventRecord` type, and is
8/// used for most public interactions with events.
9#[derive(Clone, Debug)]
10pub struct Event {
11    /// The name of the stream that the event is in.
12    pub stream_name: String,
13    /// The kind of event.
14    pub kind: EventKind,
15    /// The main data of the event.
16    pub data: Bytes,
17}
18
19impl Event {
20    pub(crate) fn new(
21        stream_name: impl AsRef<str>,
22        kind: EventKind,
23        data: impl Into<Bytes>,
24    ) -> Self {
25        Self {
26            stream_name: stream_name.as_ref().to_owned(),
27            kind,
28            data: data.into(),
29        }
30    }
31
32    /// Create a new entry event.
33    pub fn entry(stream_name: impl AsRef<str>, data: impl Into<Bytes>) -> Self {
34        Self::new(stream_name, EventKind::Entry, data)
35    }
36
37    /// Create a new read marker event.
38    pub fn read_marker(
39        stream_name: impl AsRef<str>,
40        target_stream_name: impl AsRef<str>,
41        position: i64,
42    ) -> Self {
43        SubscriptionMarker::read_marker(stream_name, target_stream_name, position)
44    }
45
46    /// Publish the event to the given repository.
47    pub async fn publish(&self, repo: &impl EventRepo) -> Result<(), EventRepoError> {
48        repo.publish(self.clone()).await
49    }
50}
51
52impl IntoCache for Event {
53    fn into_cache(self) -> CacheRecord {
54        CacheRecord::new(self.stream_name, self.data)
55    }
56}