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 /// Executor-unique task identifier.
14 pub id: u64,
15 /// Instant the task was accepted.
16 pub created_at: Instant,
17 /// Instant the body started, once running.
18 pub started_at: Option<Instant>,
19 /// Instant the body finished, once complete.
20 pub completed_at: Option<Instant>,
21 /// Worker that executed the body, once assigned.
22 pub worker_id: Option<usize>,
23 /// Priority the task was spawned with.
24 pub priority: Priority,
25 /// True when the task ended without producing a result: a cancel request
26 /// was honored before the body ran, or the task was discarded unfinished.
27 pub cancelled: bool,
28}
29
30impl TaskMetadata {
31 /// Create new task metadata
32 pub fn new(id: u64) -> Self {
33 Self {
34 id,
35 created_at: Instant::now(),
36 started_at: None,
37 completed_at: None,
38 worker_id: None,
39 priority: Priority::Normal,
40 cancelled: false,
41 }
42 }
43
44 /// Mark task as started
45 pub fn mark_started(&mut self, worker_id: usize) {
46 self.started_at = Some(Instant::now());
47 self.worker_id = Some(worker_id);
48 }
49
50 /// Mark task as completed
51 pub fn mark_completed(&mut self) {
52 self.completed_at = Some(Instant::now());
53 }
54
55 /// Get task execution duration
56 pub fn execution_duration(&self) -> Option<Duration> {
57 match (self.started_at, self.completed_at) {
58 (Some(start), Some(end)) => Some(end.duration_since(start)),
59 _ => None,
60 }
61 }
62}