use std::sync::Arc;
use uuid::Uuid;
use crate::{event::MEvent, store::StoreRegistry};
#[derive(Debug, Clone)]
pub struct SagaError {
pub saga_id: String,
pub message: String,
}
impl std::fmt::Display for SagaError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "SagaError({}): {}", self.saga_id, self.message)
}
}
impl std::error::Error for SagaError {}
#[derive(Clone)]
pub struct SagaContext {
pub host_id: Uuid,
pub registry: Arc<StoreRegistry>,
pub event_sink: Option<flume::Sender<MEvent>>,
}
impl SagaContext {
pub fn new(host_id: Uuid, registry: Arc<StoreRegistry>) -> Self {
Self {
host_id,
registry,
event_sink: None,
}
}
pub fn with_event_sink(
host_id: Uuid,
registry: Arc<StoreRegistry>,
event_sink: flume::Sender<MEvent>,
) -> Self {
Self {
host_id,
registry,
event_sink: Some(event_sink),
}
}
pub fn host_id(&self) -> Uuid {
self.host_id
}
pub fn registry(&self) -> &Arc<StoreRegistry> {
&self.registry
}
pub fn publish_event(&self, event: MEvent) -> Result<(), SagaError> {
if let Some(ref sink) = self.event_sink {
sink.send(event).map_err(|e| SagaError {
saga_id: "context".to_string(),
message: format!("Failed to publish event: {}", e),
})
} else {
Ok(()) }
}
}