datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
Documentation
use std::{future::Future, pin::Pin};

use datum::ReplyPort;

use crate::SerializedPayload;

pub(crate) type BoxEffectFuture<C, E, S> =
    Pin<Box<dyn Future<Output = Effect<C, E, S>> + Send + 'static>>;

pub(crate) struct EventWithMetadata<E> {
    pub(crate) event: E,
    pub(crate) metadata: Option<SerializedPayload>,
}

pub(crate) enum MainEffect<C, E, S> {
    Persist(Vec<EventWithMetadata<E>>),
    None,
    Unhandled,
    Stash(C),
    Async(BoxEffectFuture<C, E, S>),
}

pub(crate) enum ChainedEffect<S> {
    Run(Box<dyn FnOnce(&S) + Send + 'static>),
    Stop,
    UnstashAll,
}

/// A command decision for an [`EventSourcedBehavior`](super::EventSourcedBehavior).
///
/// One main effect is followed by zero or more side effects. Side effects retain
/// registration order and run only after the main effect completes successfully.
#[must_use]
pub struct Effect<C, E, S> {
    pub(crate) main: MainEffect<C, E, S>,
    pub(crate) chained: Vec<ChainedEffect<S>>,
}

impl<C, E, S> Effect<C, E, S> {
    /// Persists one event.
    pub fn persist(event: E) -> Self {
        Self::persist_with_metadata(event, None)
    }

    /// Persists one event with an optional already-serialized metadata frame.
    pub fn persist_with_metadata(event: E, metadata: Option<SerializedPayload>) -> Self {
        Self {
            main: MainEffect::Persist(vec![EventWithMetadata { event, metadata }]),
            chained: Vec::new(),
        }
    }

    /// Persists all events as one all-or-nothing atomic journal write.
    pub fn persist_all(events: impl IntoIterator<Item = E>) -> Self {
        Self::persist_all_with_metadata(events.into_iter().map(|event| (event, None)))
    }

    /// Persists all events and metadata as one all-or-nothing atomic journal write.
    pub fn persist_all_with_metadata(
        events: impl IntoIterator<Item = (E, Option<SerializedPayload>)>,
    ) -> Self {
        Self {
            main: MainEffect::Persist(
                events
                    .into_iter()
                    .map(|(event, metadata)| EventWithMetadata { event, metadata })
                    .collect(),
            ),
            chained: Vec::new(),
        }
    }

    /// Handles the command without changing persistent state.
    pub fn none() -> Self {
        Self {
            main: MainEffect::None,
            chained: Vec::new(),
        }
    }

    /// Marks the command unhandled without changing persistent state.
    pub fn unhandled() -> Self {
        Self {
            main: MainEffect::Unhandled,
            chained: Vec::new(),
        }
    }

    /// Stops the behavior after processing the command.
    pub fn stop() -> Self {
        Self::none().then_stop()
    }

    /// Places an owned command in the bounded in-memory manual stash.
    ///
    /// Datum handlers consume commands so commands may own one-shot
    /// [`ReplyPort`] values. Passing the command explicitly preserves that
    /// ownership without imposing a `Clone` bound on the command type. If the
    /// stash is full, the command is dropped and chained side effects are not
    /// run because the main effect did not succeed.
    pub fn stash(command: C) -> Self {
        Self {
            main: MainEffect::Stash(command),
            chained: Vec::new(),
        }
    }

    /// Starts draining the commands that were manually stashed at this point.
    pub fn unstash_all() -> Self {
        Self::none().then_unstash_all()
    }

    /// Replies immediately after a successful no-persist effect.
    pub fn reply<R>(reply_to: ReplyPort<R>, reply: R) -> ReplyEffect<C, E, S>
    where
        R: Send + 'static,
    {
        Self::none().then_reply(reply_to, move |_| reply)
    }

    /// Explicitly chooses not to reply in an enforced-replies handler.
    pub fn no_reply() -> ReplyEffect<C, E, S> {
        Self::none().then_no_reply()
    }

    /// Defers the command decision to an asynchronous computation.
    ///
    /// This is the Rust-native spelling of Akka's `Effect.async`; Akka readers
    /// can treat `async_effect` as its direct behavioral alias.
    pub fn async_effect<F>(future: F) -> Self
    where
        F: Future<Output = Self> + Send + 'static,
    {
        Self {
            main: MainEffect::Async(Box::pin(future)),
            chained: Vec::new(),
        }
    }

    /// Defers an enforced-replies decision to an asynchronous computation.
    pub fn async_reply<F>(future: F) -> ReplyEffect<C, E, S>
    where
        C: Send + 'static,
        E: Send + 'static,
        S: Send + 'static,
        F: Future<Output = ReplyEffect<C, E, S>> + Send + 'static,
    {
        ReplyEffect(Self::async_effect(
            async move { future.await.into_effect() },
        ))
    }

    /// Runs a callback with the resulting state.
    pub fn then_run<F>(mut self, callback: F) -> Self
    where
        F: FnOnce(&S) + Send + 'static,
    {
        self.chained.push(ChainedEffect::Run(Box::new(callback)));
        self
    }

    /// Stops the behavior after all earlier side effects have run.
    pub fn then_stop(mut self) -> Self {
        self.chained.push(ChainedEffect::Stop);
        self
    }

    /// Starts a bounded drain of the current manual stash after earlier side effects.
    pub fn then_unstash_all(mut self) -> Self {
        self.chained.push(ChainedEffect::UnstashAll);
        self
    }

    /// Sends a reply computed from the resulting state.
    pub fn then_reply<R, F>(mut self, reply_to: ReplyPort<R>, reply: F) -> ReplyEffect<C, E, S>
    where
        R: Send + 'static,
        F: FnOnce(&S) -> R + Send + 'static,
    {
        self.chained.push(ChainedEffect::Run(Box::new(move |state| {
            let _ = reply_to.send(reply(state));
        })));
        ReplyEffect(self)
    }

    /// Explicitly records that this command will not reply.
    pub fn then_no_reply(self) -> ReplyEffect<C, E, S> {
        ReplyEffect(self)
    }
}

/// An effect that statically records either a reply or an explicit no-reply decision.
#[must_use]
pub struct ReplyEffect<C, E, S>(Effect<C, E, S>);

impl<C, E, S> ReplyEffect<C, E, S> {
    /// Runs a callback with the resulting state while preserving reply enforcement.
    pub fn then_run<F>(self, callback: F) -> Self
    where
        F: FnOnce(&S) + Send + 'static,
    {
        Self(self.0.then_run(callback))
    }

    /// Stops the behavior after all earlier side effects have run.
    pub fn then_stop(self) -> Self {
        Self(self.0.then_stop())
    }

    /// Starts a bounded drain of the current manual stash.
    pub fn then_unstash_all(self) -> Self {
        Self(self.0.then_unstash_all())
    }

    pub(crate) fn into_effect(self) -> Effect<C, E, S> {
        self.0
    }
}