azoth_scheduler/
task_handler.rs1use crate::error::{Result, SchedulerError};
4use chrono::{DateTime, Utc};
5use std::collections::HashMap;
6use std::sync::Arc;
7
8#[derive(Debug, Clone)]
10pub struct TaskContext {
11 pub task_id: String,
13 pub execution_id: String,
15 pub scheduled_at: DateTime<Utc>,
17 pub execution_attempt: u32,
19}
20
21#[derive(Debug, Clone)]
23pub struct TaskEvent {
24 pub event_type: String,
26 pub payload: Vec<u8>,
28}
29
30pub trait TaskHandler: Send + Sync {
35 fn task_type(&self) -> &str;
37
38 fn execute(&self, ctx: &TaskContext, payload: &[u8]) -> Result<TaskEvent>;
43
44 fn validate(&self, _payload: &[u8]) -> Result<()> {
49 Ok(())
50 }
51}
52
53#[derive(Clone)]
55pub struct TaskHandlerRegistry {
56 handlers: Arc<HashMap<String, Arc<dyn TaskHandler>>>,
57}
58
59impl TaskHandlerRegistry {
60 pub fn new() -> Self {
62 Self {
63 handlers: Arc::new(HashMap::new()),
64 }
65 }
66
67 pub fn register(&mut self, handler: Arc<dyn TaskHandler>) {
69 let task_type = handler.task_type().to_string();
70 Arc::make_mut(&mut self.handlers).insert(task_type, handler);
71 }
72
73 pub fn get(&self, task_type: &str) -> Result<Arc<dyn TaskHandler>> {
75 self.handlers
76 .get(task_type)
77 .cloned()
78 .ok_or_else(|| SchedulerError::HandlerNotFound(task_type.to_string()))
79 }
80
81 pub fn has(&self, task_type: &str) -> bool {
83 self.handlers.contains_key(task_type)
84 }
85
86 pub fn task_types(&self) -> Vec<String> {
88 self.handlers.keys().cloned().collect()
89 }
90}
91
92impl Default for TaskHandlerRegistry {
93 fn default() -> Self {
94 Self::new()
95 }
96}