Skip to main content

flare_core_runtime/state/
event.rs

1//! 状态事件定义
2
3use crate::task::TaskState;
4use std::time::Instant;
5
6/// 状态事件
7///
8/// 当任务状态变更时发出的事件
9#[derive(Debug, Clone)]
10pub struct StateEvent {
11    /// 任务名称
12    pub task_name: String,
13    /// 旧状态
14    pub old_state: TaskState,
15    /// 新状态
16    pub new_state: TaskState,
17    /// 事件时间
18    pub timestamp: Instant,
19    /// 错误信息(如果状态变更为 Failed)
20    pub error: Option<String>,
21}
22
23impl StateEvent {
24    /// 创建新的状态事件
25    pub fn new(task_name: impl Into<String>, old_state: TaskState, new_state: TaskState) -> Self {
26        Self {
27            task_name: task_name.into(),
28            old_state,
29            new_state,
30            timestamp: Instant::now(),
31            error: None,
32        }
33    }
34
35    /// 添加错误信息
36    pub fn with_error(mut self, error: impl Into<String>) -> Self {
37        self.error = Some(error.into());
38        self
39    }
40
41    /// 检查是否为失败事件
42    pub fn is_failure(&self) -> bool {
43        self.new_state == TaskState::Failed
44    }
45
46    /// 检查是否为终态事件
47    pub fn is_terminal(&self) -> bool {
48        self.new_state.is_terminal()
49    }
50}
51
52/// 运行时事件
53///
54/// 运行时级别的事件
55#[derive(Debug, Clone)]
56pub enum RuntimeEvent {
57    /// 运行时启动
58    Startup {
59        /// 运行时名称
60        name: String,
61        /// 启动时间
62        timestamp: Instant,
63    },
64
65    /// 运行时停机
66    Shutdown {
67        /// 运行时名称
68        name: String,
69        /// 停机时间
70        timestamp: Instant,
71    },
72
73    /// 任务状态变更
74    TaskStateChanged(StateEvent),
75
76    /// 健康检查失败
77    HealthCheckFailed {
78        /// 检查名称
79        check_name: String,
80        /// 失败原因
81        reason: String,
82        /// 时间
83        timestamp: Instant,
84    },
85
86    /// 服务注册成功
87    ServiceRegistered {
88        /// 服务名称
89        service_name: String,
90        /// 服务 ID
91        service_id: String,
92        /// 时间
93        timestamp: Instant,
94    },
95
96    /// 服务注销
97    ServiceDeregistered {
98        /// 服务名称
99        service_name: String,
100        /// 服务 ID
101        service_id: String,
102        /// 时间
103        timestamp: Instant,
104    },
105}
106
107impl RuntimeEvent {
108    /// 获取事件时间
109    pub fn timestamp(&self) -> Instant {
110        match self {
111            RuntimeEvent::Startup { timestamp, .. } => *timestamp,
112            RuntimeEvent::Shutdown { timestamp, .. } => *timestamp,
113            RuntimeEvent::TaskStateChanged(event) => event.timestamp,
114            RuntimeEvent::HealthCheckFailed { timestamp, .. } => *timestamp,
115            RuntimeEvent::ServiceRegistered { timestamp, .. } => *timestamp,
116            RuntimeEvent::ServiceDeregistered { timestamp, .. } => *timestamp,
117        }
118    }
119}