intrepid-model 0.2.0

Manage complex async business logic with ease
Documentation
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)
    }
}