use crate::Signature;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WorkflowEvent {
TaskCompleted { task_id: Uuid },
TaskFailed { task_id: Uuid, error: String },
WorkflowStarted { workflow_id: Uuid },
WorkflowCompleted { workflow_id: Uuid },
WorkflowFailed { workflow_id: Uuid, error: String },
Custom { event_type: String, data: String },
}
impl std::fmt::Display for WorkflowEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::TaskCompleted { task_id } => write!(f, "TaskCompleted[{}]", task_id),
Self::TaskFailed { task_id, .. } => write!(f, "TaskFailed[{}]", task_id),
Self::WorkflowStarted { workflow_id } => write!(f, "WorkflowStarted[{}]", workflow_id),
Self::WorkflowCompleted { workflow_id } => {
write!(f, "WorkflowCompleted[{}]", workflow_id)
}
Self::WorkflowFailed { workflow_id, .. } => {
write!(f, "WorkflowFailed[{}]", workflow_id)
}
Self::Custom { event_type, .. } => write!(f, "Custom[{}]", event_type),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventHandler {
pub event_type: String,
pub handler_task: Signature,
pub filter: Option<String>,
}
impl EventHandler {
pub fn new(event_type: impl Into<String>, handler_task: Signature) -> Self {
Self {
event_type: event_type.into(),
handler_task,
filter: None,
}
}
pub fn with_filter(mut self, filter: impl Into<String>) -> Self {
self.filter = Some(filter.into());
self
}
}
impl std::fmt::Display for EventHandler {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"EventHandler[event={}, handler={}]",
self.event_type, self.handler_task.task
)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventDrivenWorkflow {
pub workflow_id: Uuid,
pub handlers: Vec<EventHandler>,
pub active: bool,
}
impl EventDrivenWorkflow {
pub fn new() -> Self {
Self {
workflow_id: Uuid::new_v4(),
handlers: Vec::new(),
active: true,
}
}
pub fn on_event(mut self, handler: EventHandler) -> Self {
self.handlers.push(handler);
self
}
pub fn on_task_completed(self, task: Signature) -> Self {
self.on_event(EventHandler::new("TaskCompleted", task))
}
pub fn on_task_failed(self, task: Signature) -> Self {
self.on_event(EventHandler::new("TaskFailed", task))
}
pub fn activate(mut self) -> Self {
self.active = true;
self
}
pub fn deactivate(mut self) -> Self {
self.active = false;
self
}
pub fn has_handlers(&self) -> bool {
!self.handlers.is_empty()
}
}
impl Default for EventDrivenWorkflow {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Display for EventDrivenWorkflow {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"EventDrivenWorkflow[id={}, handlers={}]",
self.workflow_id,
self.handlers.len()
)?;
if !self.active {
write!(f, " (inactive)")?;
}
Ok(())
}
}