use crate::enums::{BackoffStrategy, HealthStatus, RestartPolicy, TaskState};
#[async_trait::async_trait]
pub trait SupervisedTask: Send + Sync {
fn name(&self) -> String;
async fn run(&self) -> anyhow::Result<()>;
fn restart_policy(&self) -> RestartPolicy {
RestartPolicy::Always
}
fn backoff_strategy(&self) -> BackoffStrategy {
BackoffStrategy::default()
}
async fn setup(&self) -> anyhow::Result<()> {
Ok(())
}
async fn cleanup(&self) {
}
async fn should_restart(&self, _attempt: usize, _last_error: &str) -> bool {
true
}
async fn health_check(&self) -> HealthStatus {
HealthStatus::Healthy
}
async fn metrics(&self) -> Option<TaskMetrics> {
None
}
async fn on_restart(&self, _attempt: usize) {
}
async fn on_error(&self, _error: &str, _attempt: usize) {
}
async fn on_panic(&self, _panic_info: &str, _attempt: usize) {
}
async fn on_shutdown(&self) {
}
}
#[async_trait::async_trait]
pub trait StatefulTask: SupervisedTask {
async fn state(&self) -> TaskState;
}
#[derive(Debug, Clone)]
pub struct TaskMetrics {
pub success_count: u64,
pub error_count: u64,
pub processed_count: u64,
pub processing_rate: f64,
pub avg_processing_time_ms: f64,
pub custom: std::collections::HashMap<String, f64>,
}
impl Default for TaskMetrics {
fn default() -> Self {
Self {
success_count: 0,
error_count: 0,
processed_count: 0,
processing_rate: 0.0,
avg_processing_time_ms: 0.0,
custom: std::collections::HashMap::new(),
}
}
}
impl TaskMetrics {
pub fn new() -> Self {
Self::default()
}
pub fn add_custom(&mut self, key: impl Into<String>, value: f64) {
self.custom.insert(key.into(), value);
}
}