Skip to main content

moirai_executor/task/
mod.rs

1//! Task management and execution abstractions.
2//!
3//! This module provides types and functionality for task lifecycle management,
4//! specifically per-task metadata tracking consumed by the task registry.
5
6use std::time::{Duration, Instant};
7
8use moirai_core::Priority;
9
10/// Task metadata for tracking and debugging
11#[derive(Debug, Clone)]
12pub struct TaskMetadata {
13    pub id: u64,
14    pub created_at: Instant,
15    pub started_at: Option<Instant>,
16    pub completed_at: Option<Instant>,
17    pub worker_id: Option<usize>,
18    /// Priority the task was spawned with.
19    pub priority: Priority,
20    /// True when a cancel request was honored before the task body ran.
21    pub cancelled: bool,
22}
23
24impl TaskMetadata {
25    /// Create new task metadata
26    pub fn new(id: u64) -> Self {
27        Self {
28            id,
29            created_at: Instant::now(),
30            started_at: None,
31            completed_at: None,
32            worker_id: None,
33            priority: Priority::Normal,
34            cancelled: false,
35        }
36    }
37
38    /// Mark task as started
39    pub fn mark_started(&mut self, worker_id: usize) {
40        self.started_at = Some(Instant::now());
41        self.worker_id = Some(worker_id);
42    }
43
44    /// Mark task as completed
45    pub fn mark_completed(&mut self) {
46        self.completed_at = Some(Instant::now());
47    }
48
49    /// Get task execution duration
50    pub fn execution_duration(&self) -> Option<Duration> {
51        match (self.started_at, self.completed_at) {
52            (Some(start), Some(end)) => Some(end.duration_since(start)),
53            _ => None,
54        }
55    }
56}