intrepid-model 0.3.0

Manage complex async business logic with ease
Documentation
use bytes::Bytes;

use crate::{CacheRecord, IntoCache, SubscriptionMarker};

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, Debug)]
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,
}

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>,
        target_stream_name: impl AsRef<str>,
        position: i64,
    ) -> Self {
        SubscriptionMarker::read_marker(stream_name, target_stream_name, position)
    }

    /// 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)
    }
}