datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
Documentation
//! Cluster-sharding integration for event-sourced entity behaviors.
//!
//! [`EventSourcedEntity::register`] derives each [`PersistenceId`] from the
//! sharding entity type and entity id, then spawns the resulting
//! [`EventSourcedBehavior`] behind sharding's actor-entity ingress. Passivation,
//! handoff, or behavior stop terminates that actor; the next sharded delivery
//! creates a new incarnation and recovery runs before its command.
//!
//! # Ask/reply
//!
//! Commands sent through [`datum_cluster_sharding::EntityRef::ask`] must carry
//! [`datum_cluster_sharding::ReplyPort`], not `datum_core`'s actor reply port.
//! Move that port into [`crate::Effect::then_run`] and send the reply only after
//! persistence succeeds:
//!
//! ```ignore
//! CounterCommand::Add { amount, reply_to } =>
//!     Effect::persist(amount).then_run(move |state| {
//!         let _ = reply_to.send(*state);
//!     })
//! ```

use std::sync::Arc;

use datum_cluster_sharding::{
    ActorEntity, ActorEntityHandle, ActorEntitySpawnFuture, EntityContext, ShardingError,
    ShardingHandle, ShardingResult,
    serde::{Serialize, de::DeserializeOwned},
};

use crate::{EventSourcedBehavior, EventSourcedMessage, EventSourcedRuntime, PersistenceId};

/// One-call registration helper for sharded [`EventSourcedBehavior`] entities.
///
/// The behavior factory receives the ordinary sharding [`EntityContext`]. Its
/// blueprint persistence id is replaced with the canonical
/// `type_name|entity_id` id before spawn, so every incarnation recovers the
/// same journal. The runtime template's journal, snapshot store, writer-id
/// override, and topic capacity are cloned for each incarnation.
pub struct EventSourcedEntity;

impl EventSourcedEntity {
    /// Register one event-sourced entity type with a sharding region.
    ///
    /// This is the persistence spelling of
    /// [`ShardingHandle::register_actor_entity_type`]. The factory remains a
    /// side-effect-free behavior blueprint factory; journal access and recovery
    /// begin only when the first message spawns an entity.
    pub async fn register<C, E, S, J, F>(
        sharding: &ShardingHandle,
        type_name: impl Into<String>,
        runtime: EventSourcedRuntime,
        factory: F,
    ) -> ShardingResult<()>
    where
        C: Serialize + DeserializeOwned + Send + 'static,
        E: Send + Sync + 'static,
        S: Clone + Send + Sync + 'static,
        J: Send + 'static,
        F: Fn(EntityContext) -> EventSourcedBehavior<C, E, S, J> + Send + Sync + 'static,
    {
        sharding
            .register_actor_entity_type(type_name, move |context| {
                let behavior = factory(context.clone());
                SpawnEventSourcedEntity {
                    persistence_id: PersistenceId::new(
                        context.type_name.clone(),
                        context.entity_id.clone(),
                    ),
                    behavior,
                    runtime: clone_runtime(&runtime),
                    context,
                }
            })
            .await
    }
}

struct SpawnEventSourcedEntity<C, E, S, J> {
    persistence_id: crate::PersistenceResult<PersistenceId>,
    behavior: EventSourcedBehavior<C, E, S, J>,
    runtime: EventSourcedRuntime,
    context: EntityContext,
}

impl<C, E, S, J> ActorEntity<C> for SpawnEventSourcedEntity<C, E, S, J>
where
    C: Serialize + DeserializeOwned + Send + 'static,
    E: Send + Sync + 'static,
    S: Clone + Send + Sync + 'static,
    J: Send + 'static,
{
    fn spawn(self: Box<Self>) -> ActorEntitySpawnFuture<C> {
        Box::pin(async move {
            let SpawnEventSourcedEntity {
                persistence_id,
                mut behavior,
                runtime,
                context,
            } = *self;
            behavior.persistence_id = persistence_id.map_err(|error| {
                ShardingError::Actor(format!(
                    "invalid persistence id for {}/{}: {error}",
                    context.type_name, context.entity_id
                ))
            })?;
            let handle = behavior.spawn(runtime).await.map_err(|error| {
                ShardingError::Actor(format!(
                    "event-sourced entity {}/{} failed to spawn: {error}",
                    context.type_name, context.entity_id
                ))
            })?;
            Ok(ActorEntityHandle::from_actor_ref(
                handle.actor_ref().clone(),
                EventSourcedMessage::command,
            ))
        })
    }
}

fn clone_runtime(runtime: &EventSourcedRuntime) -> EventSourcedRuntime {
    EventSourcedRuntime {
        journal: Arc::clone(&runtime.journal),
        snapshot_store: runtime.snapshot_store.as_ref().map(Arc::clone),
        writer_uuid: runtime.writer_uuid.clone(),
        topic_capacity: runtime.topic_capacity,
    }
}