Initial commit
This commit is contained in:
77
src/tasks.rs
Normal file
77
src/tasks.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use chrono::{NaiveDateTime, Utc};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct TaskInfo {
|
||||
pub id: String,
|
||||
pub task_type: String,
|
||||
pub status: TaskStatus,
|
||||
pub started_at: NaiveDateTime,
|
||||
pub completed_at: Option<NaiveDateTime>,
|
||||
pub result: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
pub enum TaskStatus {
|
||||
Running,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
pub struct TaskManager {
|
||||
tasks: Mutex<HashMap<String, TaskInfo>>,
|
||||
}
|
||||
|
||||
impl TaskManager {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tasks: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Register a new task as Running. Returns the task ID.
|
||||
pub fn register(&self, task_type: &str) -> String {
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
let info = TaskInfo {
|
||||
id: id.clone(),
|
||||
task_type: task_type.to_string(),
|
||||
status: TaskStatus::Running,
|
||||
started_at: Utc::now().naive_utc(),
|
||||
completed_at: None,
|
||||
result: None,
|
||||
};
|
||||
self.tasks.lock().unwrap().insert(id.clone(), info);
|
||||
id
|
||||
}
|
||||
|
||||
/// Mark a task as completed with a result string.
|
||||
pub fn complete(&self, id: &str, result: String) {
|
||||
if let Some(task) = self.tasks.lock().unwrap().get_mut(id) {
|
||||
task.status = TaskStatus::Completed;
|
||||
task.completed_at = Some(Utc::now().naive_utc());
|
||||
task.result = Some(result);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark a task as failed with an error message.
|
||||
pub fn fail(&self, id: &str, error: String) {
|
||||
if let Some(task) = self.tasks.lock().unwrap().get_mut(id) {
|
||||
task.status = TaskStatus::Failed;
|
||||
task.completed_at = Some(Utc::now().naive_utc());
|
||||
task.result = Some(error);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a task by ID.
|
||||
pub fn get(&self, id: &str) -> Option<TaskInfo> {
|
||||
self.tasks.lock().unwrap().get(id).cloned()
|
||||
}
|
||||
|
||||
/// List all tasks.
|
||||
pub fn list(&self) -> Vec<TaskInfo> {
|
||||
self.tasks.lock().unwrap().values().cloned().collect()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user