Skip to main content

flare_core_runtime/task/
state.rs

1//! 任务状态定义
2
3use std::fmt;
4
5/// 任务状态
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub enum TaskState {
8    /// 等待启动
9    Pending,
10    /// 启动中
11    Starting,
12    /// 运行中
13    Running,
14    /// 停止中
15    Stopping,
16    /// 已停止
17    Stopped,
18    /// 失败
19    Failed,
20}
21
22impl TaskState {
23    /// 检查是否为终态(Stopped 或 Failed)
24    pub fn is_terminal(&self) -> bool {
25        matches!(self, TaskState::Stopped | TaskState::Failed)
26    }
27
28    /// 检查是否可以转换到目标状态
29    pub fn can_transition_to(&self, target: TaskState) -> bool {
30        use TaskState::*;
31        match (self, target) {
32            // Pending 可以转换到 Starting
33            (Pending, Starting) => true,
34            // Starting 可以转换到 Running 或 Failed
35            (Starting, Running) | (Starting, Failed) => true,
36            // Running 可以转换到 Stopping 或 Failed
37            (Running, Stopping) | (Running, Failed) => true,
38            // Stopping 可以转换到 Stopped 或 Failed
39            (Stopping, Stopped) | (Stopping, Failed) => true,
40            // 终态不能转换
41            (Stopped, _) | (Failed, _) => false,
42            // 其他转换无效
43            _ => false,
44        }
45    }
46}
47
48impl fmt::Display for TaskState {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        match self {
51            TaskState::Pending => write!(f, "Pending"),
52            TaskState::Starting => write!(f, "Starting"),
53            TaskState::Running => write!(f, "Running"),
54            TaskState::Stopping => write!(f, "Stopping"),
55            TaskState::Stopped => write!(f, "Stopped"),
56            TaskState::Failed => write!(f, "Failed"),
57        }
58    }
59}