use crate::error::{Result, SchedulerError};
use chrono::{DateTime, Utc};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct TaskContext {
pub task_id: String,
pub execution_id: String,
pub scheduled_at: DateTime<Utc>,
pub execution_attempt: u32,
}
#[derive(Debug, Clone)]
pub struct TaskEvent {
pub event_type: String,
pub payload: Vec<u8>,
}
pub trait TaskHandler: Send + Sync {
fn task_type(&self) -> &str;
fn execute(&self, ctx: &TaskContext, payload: &[u8]) -> Result<TaskEvent>;
fn validate(&self, _payload: &[u8]) -> Result<()> {
Ok(())
}
}
#[derive(Clone)]
pub struct TaskHandlerRegistry {
handlers: Arc<HashMap<String, Arc<dyn TaskHandler>>>,
}
impl TaskHandlerRegistry {
pub fn new() -> Self {
Self {
handlers: Arc::new(HashMap::new()),
}
}
pub fn register(&mut self, handler: Arc<dyn TaskHandler>) {
let task_type = handler.task_type().to_string();
Arc::make_mut(&mut self.handlers).insert(task_type, handler);
}
pub fn get(&self, task_type: &str) -> Result<Arc<dyn TaskHandler>> {
self.handlers
.get(task_type)
.cloned()
.ok_or_else(|| SchedulerError::HandlerNotFound(task_type.to_string()))
}
pub fn has(&self, task_type: &str) -> bool {
self.handlers.contains_key(task_type)
}
pub fn task_types(&self) -> Vec<String> {
self.handlers.keys().cloned().collect()
}
}
impl Default for TaskHandlerRegistry {
fn default() -> Self {
Self::new()
}
}