use crate::events::{AlienEvent, EventBus, EventState};
use crate::Result;
use alien_error::{AlienError, AlienErrorData};
use serde::{Deserialize, Serialize};
#[cfg(feature = "openapi")]
use utoipa::ToSchema;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct EventHandle {
pub id: String,
pub parent_id: Option<String>,
#[serde(skip)]
pub is_noop: bool,
}
impl EventHandle {
pub fn new(id: String, parent_id: Option<String>) -> Self {
Self {
id,
parent_id,
is_noop: false,
}
}
pub fn noop() -> Self {
Self {
id: "noop".to_string(),
parent_id: None,
is_noop: true,
}
}
pub async fn update(&self, event: AlienEvent) -> Result<()> {
if self.is_noop {
return Ok(());
}
EventBus::update(&self.id, event).await
}
pub async fn complete(&self) -> Result<()> {
if self.is_noop {
return Ok(());
}
EventBus::update_state(&self.id, EventState::Success).await
}
pub async fn fail<E>(&self, error: AlienError<E>) -> Result<()>
where
E: AlienErrorData + Clone + std::fmt::Debug + Serialize,
{
if self.is_noop {
return Ok(());
}
EventBus::update_state(
&self.id,
EventState::Failed {
error: Some(error.into_generic()),
},
)
.await
}
pub async fn as_parent<F, Fut, T>(&self, f: F) -> T
where
F: FnOnce(&EventHandle) -> Fut,
Fut: std::future::Future<Output = T>,
{
if self.is_noop {
return f(self).await;
}
let parent_id = self.id.clone();
EventBus::with_parent(Some(parent_id), f).await
}
}