mod effect;
mod runtime;
use std::{marker::PhantomData, sync::Arc};
use datum::{
RestartSettings, Topic,
actor::{ActorRef, Message},
};
use crate::{
EventAdapter, Journal, PersistenceError, PersistenceId, PersistenceResult, SequenceNr,
SerializerCatalog, SnapshotCriteria, SnapshotMetadata, SnapshotStore, StateAdapter, Tag,
};
pub use effect::{Effect, ReplyEffect};
use runtime::{EventCodec, StateCodec};
type CommandHandler<C, E, S> = dyn Fn(&S, C) -> Effect<C, E, S> + Send + Sync + 'static;
type EventHandler<E, S> = dyn Fn(&S, &E) -> PersistenceResult<S> + Send + Sync + 'static;
type SnapshotPredicate<E, S> = dyn Fn(&S, &E, SequenceNr) -> bool + Send + Sync + 'static;
type Tagger<E, S> = dyn Fn(&S, &E) -> Vec<Tag> + Send + Sync + 'static;
type SignalHandler<S> = dyn Fn(&S, &EventSourcedSignal) + Send + Sync + 'static;
pub trait IntoEventHandlerResult<S> {
fn into_event_handler_result(self) -> PersistenceResult<S>;
}
impl<S> IntoEventHandlerResult<S> for S {
fn into_event_handler_result(self) -> PersistenceResult<S> {
Ok(self)
}
}
impl<S> IntoEventHandlerResult<S> for PersistenceResult<S> {
fn into_event_handler_result(self) -> PersistenceResult<S> {
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SnapshotSelection {
Latest,
None,
Criteria(SnapshotCriteria),
}
impl SnapshotSelection {
pub(crate) fn criteria(self) -> SnapshotCriteria {
match self {
Self::Latest => SnapshotCriteria::latest(),
Self::None => SnapshotCriteria::none(),
Self::Criteria(criteria) => criteria,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Recovery {
Enabled(SnapshotSelection),
Disabled,
}
impl Recovery {
#[must_use]
pub const fn with_snapshot_selection(selection: SnapshotSelection) -> Self {
Self::Enabled(selection)
}
}
impl Default for Recovery {
fn default() -> Self {
Self::Enabled(SnapshotSelection::Latest)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RetentionCriteria {
#[default]
Disabled,
SnapshotEvery {
every: u64,
keep: u64,
delete_events: bool,
},
}
impl RetentionCriteria {
pub fn snapshot_every(every: u64, keep: u64) -> PersistenceResult<Self> {
if every == 0 {
return Err(PersistenceError::Rejected(
"snapshot frequency must be greater than zero".into(),
));
}
if keep == 0 {
return Err(PersistenceError::Rejected(
"snapshot retention count must be greater than zero".into(),
));
}
Ok(Self::SnapshotEvery {
every,
keep,
delete_events: false,
})
}
#[must_use]
pub fn with_delete_events_on_snapshot(self) -> Self {
match self {
Self::Disabled => Self::Disabled,
Self::SnapshotEvery { every, keep, .. } => Self::SnapshotEvery {
every,
keep,
delete_events: true,
},
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum EventSourcedSignal {
SnapshotRecovered(SnapshotMetadata),
RecoveryCompleted,
RecoveryFailed(PersistenceError),
PersistFailed {
sequence_nr: SequenceNr,
error: PersistenceError,
},
PersistRejected {
sequence_nr: SequenceNr,
reason: String,
},
SnapshotCompleted(SnapshotMetadata),
SnapshotFailed {
metadata: SnapshotMetadata,
error: PersistenceError,
},
DeleteEventsCompleted(SequenceNr),
DeleteEventsFailed {
to: SequenceNr,
error: PersistenceError,
},
DeleteSnapshotsCompleted(SnapshotCriteria),
DeleteSnapshotsFailed {
criteria: SnapshotCriteria,
error: PersistenceError,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublishedEvent<E> {
pub persistence_id: PersistenceId,
pub sequence_nr: SequenceNr,
pub event: E,
pub timestamp_ms: i64,
pub tags: Vec<Tag>,
}
pub struct EventSourcedRuntime {
pub(crate) journal: Arc<dyn Journal>,
pub(crate) snapshot_store: Option<Arc<dyn SnapshotStore>>,
pub(crate) writer_uuid: Option<String>,
pub(crate) topic_capacity: usize,
}
impl EventSourcedRuntime {
#[must_use]
pub fn new(journal: Arc<dyn Journal>) -> Self {
Self {
journal,
snapshot_store: None,
writer_uuid: None,
topic_capacity: 256,
}
}
#[must_use]
pub fn with_snapshot_store(mut self, snapshot_store: Arc<dyn SnapshotStore>) -> Self {
self.snapshot_store = Some(snapshot_store);
self
}
#[must_use]
pub fn with_writer_uuid(mut self, writer_uuid: impl Into<String>) -> Self {
self.writer_uuid = Some(writer_uuid.into());
self
}
#[must_use]
pub fn with_topic_capacity(mut self, capacity: usize) -> Self {
assert!(
capacity > 0,
"published-event topic capacity must be greater than zero"
);
self.topic_capacity = capacity;
self
}
}
pub struct EventSourcedBehavior<C, E, S, J = E> {
pub(crate) persistence_id: PersistenceId,
pub(crate) empty_state: S,
pub(crate) command_handler: Arc<CommandHandler<C, E, S>>,
pub(crate) event_handler: Arc<EventHandler<E, S>>,
pub(crate) event_codec: Option<EventCodec<E, J>>,
pub(crate) state_codec: Option<Arc<dyn StateCodec<S>>>,
pub(crate) snapshot_when: Arc<SnapshotPredicate<E, S>>,
pub(crate) retention: RetentionCriteria,
pub(crate) tagger: Arc<Tagger<E, S>>,
pub(crate) persist_failure_backoff: Option<RestartSettings>,
pub(crate) recovery: Recovery,
pub(crate) publish_events: bool,
pub(crate) stash_capacity: usize,
pub(crate) signal_handler: Arc<SignalHandler<S>>,
pub(crate) _journal: PhantomData<fn() -> J>,
}
impl<C, E, S> EventSourcedBehavior<C, E, S, E> {
pub fn new<CH, EH, O>(
persistence_id: PersistenceId,
empty_state: S,
command_handler: CH,
event_handler: EH,
) -> Self
where
CH: Fn(&S, C) -> Effect<C, E, S> + Send + Sync + 'static,
EH: Fn(&S, &E) -> O + Send + Sync + 'static,
O: IntoEventHandlerResult<S>,
{
Self::from_handlers(
persistence_id,
empty_state,
Arc::new(command_handler),
Arc::new(move |state, event| event_handler(state, event).into_event_handler_result()),
)
}
pub fn with_enforced_replies<CH, EH, O>(
persistence_id: PersistenceId,
empty_state: S,
command_handler: CH,
event_handler: EH,
) -> Self
where
CH: Fn(&S, C) -> ReplyEffect<C, E, S> + Send + Sync + 'static,
EH: Fn(&S, &E) -> O + Send + Sync + 'static,
O: IntoEventHandlerResult<S>,
{
Self::from_handlers(
persistence_id,
empty_state,
Arc::new(move |state, command| command_handler(state, command).into_effect()),
Arc::new(move |state, event| event_handler(state, event).into_event_handler_result()),
)
}
fn from_handlers(
persistence_id: PersistenceId,
empty_state: S,
command_handler: Arc<CommandHandler<C, E, S>>,
event_handler: Arc<EventHandler<E, S>>,
) -> Self {
Self {
persistence_id,
empty_state,
command_handler,
event_handler,
event_codec: None,
state_codec: None,
snapshot_when: Arc::new(|_, _, _| false),
retention: RetentionCriteria::Disabled,
tagger: Arc::new(|_, _| Vec::new()),
persist_failure_backoff: None,
recovery: Recovery::default(),
publish_events: true,
stash_capacity: 1_024,
signal_handler: Arc::new(|_, _| {}),
_journal: PhantomData,
}
}
}
impl<C, E, S, J> EventSourcedBehavior<C, E, S, J> {
#[must_use]
pub fn with_event_adapter<J2, A>(
self,
adapter: A,
catalog: SerializerCatalog<J2>,
) -> EventSourcedBehavior<C, E, S, J2>
where
A: EventAdapter<E, J2>,
J2: 'static,
{
EventSourcedBehavior {
persistence_id: self.persistence_id,
empty_state: self.empty_state,
command_handler: self.command_handler,
event_handler: self.event_handler,
event_codec: Some(EventCodec::new(adapter, catalog)),
state_codec: self.state_codec,
snapshot_when: self.snapshot_when,
retention: self.retention,
tagger: self.tagger,
persist_failure_backoff: self.persist_failure_backoff,
recovery: self.recovery,
publish_events: self.publish_events,
stash_capacity: self.stash_capacity,
signal_handler: self.signal_handler,
_journal: PhantomData,
}
}
#[must_use]
pub fn with_state_adapter<SJ, A>(mut self, adapter: A, catalog: SerializerCatalog<SJ>) -> Self
where
A: StateAdapter<S, SJ>,
SJ: 'static,
S: 'static,
{
self.state_codec = Some(Arc::new(runtime::AdaptedStateCodec::new(adapter, catalog)));
self
}
#[must_use]
pub fn snapshot_when<F>(mut self, predicate: F) -> Self
where
F: Fn(&S, &E, SequenceNr) -> bool + Send + Sync + 'static,
{
self.snapshot_when = Arc::new(predicate);
self
}
#[must_use]
pub fn with_retention(mut self, retention: RetentionCriteria) -> Self {
self.retention = retention;
self
}
#[must_use]
pub fn with_tagger<F>(mut self, tagger: F) -> Self
where
F: Fn(&E) -> Vec<Tag> + Send + Sync + 'static,
{
self.tagger = Arc::new(move |_, event| tagger(event));
self
}
#[must_use]
pub fn with_state_tagger<F>(mut self, tagger: F) -> Self
where
F: Fn(&S, &E) -> Vec<Tag> + Send + Sync + 'static,
{
self.tagger = Arc::new(tagger);
self
}
#[must_use]
pub fn on_persist_failure(mut self, settings: RestartSettings) -> Self {
self.persist_failure_backoff = Some(settings);
self
}
#[must_use]
pub fn with_recovery(mut self, recovery: Recovery) -> Self {
self.recovery = recovery;
self
}
#[must_use]
pub fn with_event_publishing(mut self, enabled: bool) -> Self {
self.publish_events = enabled;
self
}
#[must_use]
pub fn with_stash_capacity(mut self, capacity: usize) -> Self {
self.stash_capacity = capacity;
self
}
#[must_use]
pub fn on_signal<F>(mut self, handler: F) -> Self
where
F: Fn(&S, &EventSourcedSignal) + Send + Sync + 'static,
{
self.signal_handler = Arc::new(handler);
self
}
}
impl<C, E, S, J> EventSourcedBehavior<C, E, S, J>
where
C: Message,
E: Send + Sync + 'static,
S: Clone + Send + Sync + 'static,
J: Send + 'static,
{
pub async fn spawn(
self,
runtime: EventSourcedRuntime,
) -> PersistenceResult<EventSourcedHandle<C, E, S>> {
runtime::spawn(self, runtime).await
}
pub async fn run_on(
self,
runtime: EventSourcedRuntime,
) -> PersistenceResult<EventSourcedHandle<C, E, S>> {
self.spawn(runtime).await
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventSourcedState<S> {
pub state: S,
pub sequence_nr: SequenceNr,
}
pub struct EventSourcedHandle<C: Message, E: Send + Sync + 'static, S: Send + 'static> {
pub(crate) control: ActorRef<runtime::EventSourcedMessage<C, S>>,
pub(crate) published_events: Option<Topic<PublishedEvent<E>>>,
}
impl<C, E, S> EventSourcedHandle<C, E, S>
where
C: Message,
E: Send + Sync + 'static,
S: Clone + Send + 'static,
{
#[must_use]
pub fn actor_ref(&self) -> &ActorRef<EventSourcedMessage<C, S>> {
&self.control
}
pub fn tell(&self, command: C) -> PersistenceResult<()> {
self.control
.cast(runtime::EventSourcedMessage::command(command))
.map_err(|error| {
PersistenceError::Failure(format!("behavior command send failed: {error}"))
})
}
pub async fn state(&self) -> PersistenceResult<EventSourcedState<S>> {
let (sender, receiver) = tokio::sync::oneshot::channel();
self.control
.cast(runtime::EventSourcedMessage::get_state(sender))
.map_err(|error| {
PersistenceError::Failure(format!("behavior state query failed: {error}"))
})?;
receiver.await.map_err(|_| {
PersistenceError::Failure("behavior stopped before answering state query".into())
})
}
#[must_use]
pub fn published_events(&self) -> Option<&Topic<PublishedEvent<E>>> {
self.published_events.as_ref()
}
pub fn stop(&self) {
self.control.stop(None);
}
}
impl<C, E, S> Clone for EventSourcedHandle<C, E, S>
where
C: Message,
E: Send + Sync + 'static,
S: Send + 'static,
{
fn clone(&self) -> Self {
Self {
control: self.control.clone(),
published_events: self.published_events.clone(),
}
}
}
pub use runtime::EventSourcedMessage;