use bytes::Bytes;
use crate::{CacheRecord, IntoCache};
use super::{EventKind, EventRepo, EventRepoError};
#[derive(Clone)]
pub struct Event {
pub stream_name: String,
pub kind: EventKind,
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(),
}
}
pub fn entry(stream_name: impl AsRef<str>, data: impl Into<Bytes>) -> Self {
Self::new(stream_name, EventKind::Entry, data)
}
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,
data: serde_json::to_vec(&EventLogReadMarker {
subscriber_name: subscriber_name.as_ref().to_owned(),
position,
})
.expect("failed to serialize event log read marker")
.into(),
}
}
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)
}
}