mod effect;
mod runtime;
use std::{marker::PhantomData, sync::Arc};
use datum::{
RestartSettings,
actor::{ActorRef, Message},
};
use crate::{
DurableStateStore, EventAdapter, Journal, PersistenceId, PersistenceResult, SerializerCatalog,
StateAdapter, Tag,
};
pub use effect::{Effect, ReplyEffect};
pub use runtime::DurableStateMessage;
use runtime::{ChangeEventCodec, StateCodec};
type CommandHandler<C, S> = dyn Fn(&S, C) -> Effect<C, S> + Send + Sync + 'static;
type SignalHandler<S> = dyn Fn(&S, &DurableStateSignal) + Send + Sync + 'static;
type ChangeUpdateHandler<C, S, E> = dyn Fn(&S, &S, &C) -> E + Send + Sync + 'static;
type ChangeDeleteHandler<C, S, E> = dyn Fn(&S, &C) -> E + Send + Sync + 'static;
#[derive(Debug)]
#[non_exhaustive]
pub enum DurableStateSignal {
RecoveryCompleted,
RecoveryFailed(crate::PersistenceError),
}
pub struct ChangeEventHandler<C, S, E> {
update: Arc<ChangeUpdateHandler<C, S, E>>,
delete: Arc<ChangeDeleteHandler<C, S, E>>,
}
impl<C, S, E> ChangeEventHandler<C, S, E> {
pub fn new<U, D>(update: U, delete: D) -> Self
where
U: Fn(&S, &S, &C) -> E + Send + Sync + 'static,
D: Fn(&S, &C) -> E + Send + Sync + 'static,
{
Self {
update: Arc::new(update),
delete: Arc::new(delete),
}
}
}
pub struct DurableStateBehavior<C, S, J = S> {
pub(crate) persistence_id: PersistenceId,
pub(crate) empty_state: S,
pub(crate) command_handler: Arc<CommandHandler<C, S>>,
pub(crate) state_codec: Option<Arc<dyn StateCodec<S>>>,
pub(crate) tag: Option<Tag>,
pub(crate) persist_failure_backoff: Option<RestartSettings>,
pub(crate) stash_capacity: usize,
pub(crate) signal_handler: Arc<SignalHandler<S>>,
pub(crate) change_event_codec: Option<Arc<dyn ChangeEventCodec<C, S>>>,
pub(crate) change_event_journal: Option<Arc<dyn Journal>>,
pub(crate) _journal_state: PhantomData<fn() -> J>,
}
impl<C, S> DurableStateBehavior<C, S, S> {
pub fn new<H>(persistence_id: PersistenceId, empty_state: S, command_handler: H) -> Self
where
H: Fn(&S, C) -> Effect<C, S> + Send + Sync + 'static,
{
Self::from_handler(persistence_id, empty_state, Arc::new(command_handler))
}
pub fn with_enforced_replies<H>(
persistence_id: PersistenceId,
empty_state: S,
command_handler: H,
) -> Self
where
H: Fn(&S, C) -> ReplyEffect<C, S> + Send + Sync + 'static,
{
Self::from_handler(
persistence_id,
empty_state,
Arc::new(move |state, command| command_handler(state, command).into_effect()),
)
}
fn from_handler(
persistence_id: PersistenceId,
empty_state: S,
command_handler: Arc<CommandHandler<C, S>>,
) -> Self {
Self {
persistence_id,
empty_state,
command_handler,
state_codec: None,
tag: None,
persist_failure_backoff: None,
stash_capacity: 1_024,
signal_handler: Arc::new(|_, _| {}),
change_event_codec: None,
change_event_journal: None,
_journal_state: PhantomData,
}
}
}
impl<C, S, J> DurableStateBehavior<C, S, J> {
#[must_use]
pub fn with_state_adapter<J2, A>(
self,
adapter: A,
catalog: SerializerCatalog<J2>,
) -> DurableStateBehavior<C, S, J2>
where
A: StateAdapter<S, J2>,
S: 'static,
J2: 'static,
{
DurableStateBehavior {
persistence_id: self.persistence_id,
empty_state: self.empty_state,
command_handler: self.command_handler,
state_codec: Some(Arc::new(runtime::AdaptedStateCodec::new(adapter, catalog))),
tag: self.tag,
persist_failure_backoff: self.persist_failure_backoff,
stash_capacity: self.stash_capacity,
signal_handler: self.signal_handler,
change_event_codec: self.change_event_codec,
change_event_journal: self.change_event_journal,
_journal_state: PhantomData,
}
}
#[must_use]
pub fn with_tag(mut self, tag: Tag) -> Self {
self.tag = Some(tag);
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_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, &DurableStateSignal) + Send + Sync + 'static,
{
self.signal_handler = Arc::new(handler);
self
}
#[must_use]
pub fn with_change_event_handler<E, EJ, A>(
mut self,
handler: ChangeEventHandler<C, S, E>,
adapter: A,
catalog: SerializerCatalog<EJ>,
) -> Self
where
C: Clone + Send + 'static,
S: 'static,
E: 'static,
EJ: 'static,
A: EventAdapter<E, EJ>,
{
self.change_event_codec = Some(Arc::new(runtime::AdaptedChangeEventCodec::new(
handler, adapter, catalog,
)));
self
}
#[must_use]
pub fn with_change_event_journal(mut self, journal: Arc<dyn Journal>) -> Self {
self.change_event_journal = Some(journal);
self
}
}
impl<C, S, J> DurableStateBehavior<C, S, J>
where
C: Message,
S: Clone + Send + Sync + 'static,
J: 'static,
{
pub async fn spawn(
self,
store: Arc<dyn DurableStateStore>,
) -> PersistenceResult<DurableStateHandle<C, S>> {
runtime::spawn(self, store).await
}
pub async fn run_on(
self,
store: Arc<dyn DurableStateStore>,
) -> PersistenceResult<DurableStateHandle<C, S>> {
self.spawn(store).await
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DurableState<S> {
pub state: S,
pub revision: crate::Revision,
}
pub struct DurableStateHandle<C: Message, S: Send + 'static> {
pub(crate) control: ActorRef<runtime::DurableStateMessage<C, S>>,
}
impl<C, S> DurableStateHandle<C, S>
where
C: Message,
S: Clone + Send + 'static,
{
#[must_use]
pub fn actor_ref(&self) -> &ActorRef<DurableStateMessage<C, S>> {
&self.control
}
pub fn tell(&self, command: C) -> PersistenceResult<()> {
self.control
.cast(runtime::DurableStateMessage::command(command))
.map_err(|error| {
crate::PersistenceError::Failure(format!(
"durable behavior command send failed: {error}"
))
})
}
pub async fn state(&self) -> PersistenceResult<DurableState<S>> {
let (sender, receiver) = tokio::sync::oneshot::channel();
self.control
.cast(runtime::DurableStateMessage::get_state(sender))
.map_err(|error| {
crate::PersistenceError::Failure(format!(
"durable behavior state query failed: {error}"
))
})?;
receiver.await.map_err(|_| {
crate::PersistenceError::Failure(
"durable behavior stopped before answering state query".into(),
)
})
}
pub fn stop(&self) {
self.control.stop(None);
}
}
impl<C, S> Clone for DurableStateHandle<C, S>
where
C: Message,
S: Send + 'static,
{
fn clone(&self) -> Self {
Self {
control: self.control.clone(),
}
}
}