moirai_core/task/id_and_context.rs
1/// A unique identifier for tasks in the Moirai runtime.
2#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3pub struct TaskId(pub u64);
4
5impl core::fmt::Display for TaskId {
6 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
7 write!(f, "Task#{}", self.0)
8 }
9}
10
11impl TaskId {
12 /// Create a new task ID.
13 pub const fn new(id: u64) -> Self {
14 Self(id)
15 }
16}
17
18/// Priority levels for task scheduling.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
20pub enum Priority {
21 /// Low priority tasks (background work)
22 Low = 0,
23 /// Normal priority tasks (default)
24 #[default]
25 Normal = 1,
26 /// High priority tasks (interactive work)
27 High = 2,
28 /// Critical priority tasks (system-level work)
29 Critical = 3,
30}
31
32impl Priority {
33 /// Scheduling index of this priority: `Low = 0`, `Normal = 1`, `High = 2`,
34 /// `Critical = 3`.
35 ///
36 /// Single source of truth for the priority-to-index mapping used by
37 /// priority-partitioned queues and worker/route selection weights.
38 ///
39 /// # Examples
40 /// ```
41 /// use moirai_core::Priority;
42 /// assert_eq!(Priority::Low.index(), 0);
43 /// assert_eq!(Priority::Critical.index(), 3);
44 /// ```
45 #[must_use]
46 pub const fn index(self) -> usize {
47 self as usize
48 }
49}
50
51/// Task execution context and metadata.
52#[derive(Debug, Clone)]
53pub struct TaskContext {
54 /// Unique identifier for this task
55 pub id: TaskId,
56 /// Priority level for scheduling
57 pub priority: Priority,
58 /// Optional name for debugging
59 pub name: Option<&'static str>,
60}
61
62impl TaskContext {
63 /// Create a new task context.
64 pub const fn new(id: TaskId) -> Self {
65 Self {
66 id,
67 priority: Priority::Normal,
68 name: None,
69 }
70 }
71
72 /// Set the priority for this task.
73 pub const fn with_priority(mut self, priority: Priority) -> Self {
74 self.priority = priority;
75 self
76 }
77
78 /// Set the name for this task.
79 pub const fn with_name(mut self, name: &'static str) -> Self {
80 self.name = Some(name);
81 self
82 }
83}