intrepid_model/events/
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
use bytes::Bytes;

use crate::{CacheRecord, IntoCache};

use super::{EventKind, EventRepo, EventRepoError};

/// An event in a stream. This is slimmer than the `EventRecord` type, and is
/// used for most public interactions with events.
#[derive(Clone)]
pub struct Event {
    /// The name of the stream that the event is in.
    pub stream_name: String,
    /// The kind of event.
    pub kind: EventKind,
    /// The main data of the event.
    pub data: Bytes,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct EventLogReadMarker {
    pub subscriber_name: String,
    pub position: i64,
}

impl Event {
    pub(crate) fn new(
        stream_name: impl AsRef<str>,
        kind: EventKind,
        data: impl Into<Bytes>,
    ) -> Self {
        Self {
            stream_name: stream_name.as_ref().to_owned(),
            kind,
            data: data.into(),
        }
    }

    /// Create a new entry event.
    pub fn entry(stream_name: impl AsRef<str>, data: impl Into<Bytes>) -> Self {
        Self::new(stream_name, EventKind::Entry, data)
    }

    /// Create a new read marker event.
    pub fn read_marker(
        stream_name: impl AsRef<str>,
        subscriber_name: impl AsRef<str>,
        position: i64,
    ) -> Self {
        Self {
            stream_name: stream_name.as_ref().to_owned(),
            kind: EventKind::Marker,
            // TODO: Can this be something other than serde_json? It's a bit heavy for this.
            data: serde_json::to_vec(&EventLogReadMarker {
                subscriber_name: subscriber_name.as_ref().to_owned(),
                position,
            })
            .expect("failed to serialize event log read marker")
            .into(),
        }
    }

    /// Publish the event to the given repository.
    pub async fn publish(&self, repo: &impl EventRepo) -> Result<(), EventRepoError> {
        repo.publish(self.clone()).await
    }
}

impl IntoCache for Event {
    fn into_cache(self) -> CacheRecord {
        CacheRecord::new(self.stream_name, self.data)
    }
}