use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
pub const DEFAULT_TASK_QUEUE_NAME: &str = "default";
pub const TASK_MIN_PRIORITY: i32 = 0;
pub const TASK_MAX_PRIORITY: i32 = 9;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TaskId(pub uuid::Uuid);
impl TaskId {
pub fn new() -> Self {
Self(uuid::Uuid::new_v4())
}
}
impl Default for TaskId {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for TaskId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for TaskId {
type Err = uuid::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(uuid::Uuid::parse_str(s)?))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TaskStatus {
Pending,
Running,
Success,
Failure,
Retry,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TaskPriority(i32);
impl TaskPriority {
pub fn new(priority: i32) -> Self {
Self(priority.clamp(TASK_MIN_PRIORITY, TASK_MAX_PRIORITY))
}
pub fn value(&self) -> i32 {
self.0
}
}
impl Default for TaskPriority {
fn default() -> Self {
Self(5)
}
}
pub trait Task: Send + Sync {
fn id(&self) -> TaskId;
fn name(&self) -> &str;
fn priority(&self) -> TaskPriority {
TaskPriority::default()
}
}
#[async_trait]
pub trait TaskExecutor: Task {
async fn execute(&self) -> crate::TaskResult<()>;
}