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};
pub struct EventSourcedEntity;
impl EventSourcedEntity {
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,
}
}