Skip to main content

wordval_actor/
msg.rs

1//! 消息定义 —— Actor 消息契约与系统信号。
2
3use crate::addr::{ActorId, ActorName};
4use std::fmt;
5use tokio::sync::watch;
6
7/// Actor 消息标记 trait —— 所有进出 Actor 邮箱的消息必须 `Send + 'static`。
8///
9/// 任意满足约束的类型自动实现,无需手动 derive。
10///
11/// 仅要求 `Send`:tokio 的 `oneshot::Sender<T>` 是 `Send + !Sync`,
12/// ask/回执类消息(携带 `Reply`/`oneshot` 端口)必须能够满足本 bound。
13/// 邮箱与回执链路(mpsc / oneshot / Mutex 槽)只跨线程移动值,从不共享引用。
14/// 需要 `Sync` 的泛型容器([`Topic`](crate::Topic) / [`SnapshotTopic`](crate::SnapshotTopic)
15/// 内部以 `Arc<T>` 跨线程共享)由各自的类型级 bound 单独约束。
16pub trait ActorMsg: Send + 'static {}
17impl<T: Send + 'static> ActorMsg for T {}
18
19/// Actor 停止原因。
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum StopCause {
22    /// 通过 [`ActorRef::try_stop`](crate::ActorRef::try_stop) /
23    /// [`ActorSystem::stop`](crate::ActorSystem::stop) 或 [`ActorAction::Stop`](crate::ActorAction::Stop) 主动停止。
24    Requested,
25    /// 事件循环 panic,且监督策略不允许(或无法)重启。
26    Panicked,
27    /// 重启次数超过 [`RestartPolicy::Transient`](crate::RestartPolicy::Transient) 上限。
28    ResourceLimit,
29    /// 系统级 [`ActorSystem::shutdown`](crate::ActorSystem::shutdown) 优雅关闭:
30    /// 关闭请求送达后正常退出的 Actor,与宽限超时被强制注销的 Actor,
31    /// 均记此因。
32    SystemShutdown,
33    /// 邮箱发送端全部关闭且注册表条目已释放(系统被丢弃)。
34    ///
35    /// 防御性变体,理论不可达:世代运行期间 Supervisor 与 ctx 恒持
36    /// 控制通道发送端,`recv()` 不会返回 `None`。
37    MailboxClosed,
38    /// watch 注册时目标已终止且终止详情不可考(竞态复核补发)。
39    Missing,
40}
41
42impl fmt::Display for StopCause {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        let s = match self {
45            StopCause::Requested => "requested",
46            StopCause::Panicked => "panicked",
47            StopCause::ResourceLimit => "resource-limit",
48            StopCause::SystemShutdown => "system-shutdown",
49            StopCause::MailboxClosed => "mailbox-closed",
50            StopCause::Missing => "missing",
51        };
52        f.write_str(s)
53    }
54}
55
56/// Actor 生命周期相位 —— 任意时刻可查的运行状态
57/// ([`ActorRef::phase`](crate::ActorRef::phase))。
58///
59/// 与一次性的 [`ActorSignal::Terminated`] 通知互补:通知只描述"刚刚终止"
60/// 这一时刻事件,相位是**持续可查**的状态 —— 通道保留末值,Actor 停止后
61/// 再查询/订阅照样能读到最终死因与 panic 详情(无需额外墓碑表)。
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum ActorPhase {
64    /// 世代正在运行(含世代启动前的初始态)。
65    Running,
66    /// 监督重启空窗:上一世代已退出,新世代尚未启动。
67    ///
68    /// 由 `Transient` 退避等待期间发布,供上层观测/展示重启过程
69    /// (如地面站 UI 的"链路重连中")。
70    Restarting {
71        /// 即将启动的世代号(与 [`ActorContext::generation`](crate::ActorContext::generation) 同源)。
72        generation: u32,
73        /// 本次重启计数(与 [`ActorContext::restarts`](crate::ActorContext::restarts) 同源)。
74        attempt: u32,
75    },
76    /// 已停止:停止请求已落值(`detail` 为 `None`),或已最终退出
77    /// (`cause` 为真实死因,panic 详情随 `detail`)。
78    ///
79    /// 一旦进入不可逆 —— 运行期状态发布(`Running` / `Restarting`)不会
80    /// 覆盖它;唯一例外是最终退出:finalize 以真实死因覆盖"停止请求"占位。
81    Stopped {
82        /// 停止原因。
83        cause: StopCause,
84        /// panic 详情(仅 [`StopCause::Panicked`] 及其衍生情形可能非空)。
85        detail: Option<String>,
86    },
87}
88
89impl ActorPhase {
90    /// 是否尚未停止。注意:停止请求一落值即为 `Stopped`,本判定不区分
91    /// "停止中"(请求已送达、事件循环尚在收尾)与"已停止"。
92    #[must_use = "存活探测结果不应被静默忽略"]
93    pub fn is_alive(&self) -> bool {
94        !matches!(self, ActorPhase::Stopped { .. })
95    }
96}
97
98/// 请求停止:向相位通道写入 `Stopped { cause, detail: None }`。
99///
100/// - 返回写入前是否存在监听端(`false` 表示目标已最终退出,监督者
101///   不再持接收端);
102/// - 不覆盖既有 `Stopped`(含 finalize 写入的真实死因),但**会**覆盖
103///   `Running` / `Restarting`:停止请求一旦落值,就不会被后续状态发布吞掉。
104pub(crate) fn request_stop(tx: &watch::Sender<ActorPhase>, cause: StopCause) -> bool {
105    let listeners = !tx.is_closed();
106    let _ = tx.send_if_modified(|phase| match phase {
107        ActorPhase::Stopped { .. } => false,
108        _ => {
109            *phase = ActorPhase::Stopped {
110                cause,
111                detail: None,
112            };
113            true
114        }
115    });
116    listeners
117}
118
119/// 发布运行期相位(`Running` / `Restarting`):终态不可逆,`Stopped` 不被覆盖。
120///
121/// 用 `send_if_modified`:零接收端时仍落值,相位状态不静默丢失;
122/// 仅在值确实变化时唤醒订阅者。
123pub(crate) fn publish_phase(tx: &watch::Sender<ActorPhase>, phase: ActorPhase) {
124    let _ = tx.send_if_modified(|cur| {
125        if *cur == phase || matches!(cur, ActorPhase::Stopped { .. }) {
126            return false;
127        }
128        *cur = phase;
129        true
130    });
131}
132
133/// 目标 Actor 终止通知的载荷。
134#[derive(Debug, Clone)]
135pub struct Terminated {
136    /// 终止的 Actor ID。
137    pub actor: ActorId,
138    /// 终止的 Actor 名称(若以命名方式 spawn)。
139    pub name: Option<ActorName>,
140    /// 终止原因。
141    pub cause: StopCause,
142    /// panic 详情(仅 [`StopCause::Panicked`] 及其衍生情形可能非空):
143    /// 事件循环 panic 时从 `JoinError` 载荷提取的文本 —— `&'static str` /
144    /// `String` 载荷原样取出,其余类型载荷给固定占位文本;非 panic
145    /// 终止时为 `None`。
146    pub detail: Option<String>,
147}
148
149/// 系统信号 —— 经**专用信号通道**(独立于用户消息邮箱)送达 Actor。
150///
151/// 系统投递的信号(如 watch 终止通知)走物理隔离的小容量通道,
152/// 事件循环每轮优先抽干:失控保护类逻辑(如监视的子机体终止)
153/// 不会被遥测/业务消息洪泛饿死。
154///
155/// 通道内还承载内部的看门狗触发标记:
156/// 它同样绕过用户消息积压,但被事件循环拦截后转投
157/// [`Actor::handle`](crate::Actor::handle)(携带超时消息),
158/// **不会**出现在 [`on_signal`](crate::Actor::on_signal) 中。
159#[derive(Debug, Clone)]
160pub enum ActorSignal {
161    /// 被 watch 的目标 Actor 已终止(无论何种原因)。
162    Terminated(Terminated),
163}
164
165/// 专用信号通道的内部载荷 —— 系统信号与看门狗触发标记共用该通道,
166/// 二者都绕过用户消息积压、由事件循环每轮优先抽干。
167///
168/// 两条通道各司其职:控制通道只承载用户消息,信号通道承载一切
169/// 控制面事件 —— 控制面事件不得混入用户队列被积压延迟。
170pub(crate) enum Signal {
171    /// 看门狗触发标记:`arm` 为武装世代号(全局单调分配)。
172    /// 消费时与当前武装世代比对,已被新帧喂狗/再武装/解除取代的
173    /// 陈旧触发静默丢弃。
174    WatchdogFire { arm: u64 },
175    /// 系统信号(如 watch 终止通知),投递给 [`on_signal`](crate::Actor::on_signal)。
176    System(ActorSignal),
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    #[test]
184    fn stop_cause_display() {
185        assert_eq!(StopCause::Requested.to_string(), "requested");
186        assert_eq!(StopCause::Panicked.to_string(), "panicked");
187        assert_eq!(StopCause::ResourceLimit.to_string(), "resource-limit");
188        assert_eq!(StopCause::SystemShutdown.to_string(), "system-shutdown");
189        assert_eq!(StopCause::MailboxClosed.to_string(), "mailbox-closed");
190    }
191
192    /// 相位通道守卫契约:
193    /// - 运行期状态发布可覆盖 `Running`/`Restarting`,但不得覆盖终态;
194    /// - 停止请求可覆盖运行期相位、不得覆盖既有终态(真实死因优先);
195    /// - 零接收端时停止请求报 `false`,值照常落库(死后补订阅仍可读)。
196    #[test]
197    fn phase_channel_guards() {
198        let (tx, rx) = watch::channel(ActorPhase::Running);
199
200        // 状态发布:Running → Restarting 生效
201        publish_phase(
202            &tx,
203            ActorPhase::Restarting {
204                generation: 2,
205                attempt: 1,
206            },
207        );
208        assert_eq!(
209            *tx.borrow(),
210            ActorPhase::Restarting {
211                generation: 2,
212                attempt: 1
213            }
214        );
215
216        // 停止请求:覆盖运行期相位,返回存在监听端
217        assert!(request_stop(&tx, StopCause::Requested), "有监听端应报 true");
218        assert_eq!(
219            *tx.borrow(),
220            ActorPhase::Stopped {
221                cause: StopCause::Requested,
222                detail: None
223            }
224        );
225
226        // 运行期状态发布不得复活终态
227        publish_phase(&tx, ActorPhase::Running);
228        assert!(
229            matches!(&*tx.borrow(), ActorPhase::Stopped { .. }),
230            "Stopped 之后发布 Running 必须被守卫拒绝"
231        );
232
233        // finalize 以真实死因覆盖占位值后,迟到的停止请求不得改写
234        let _ = tx.send_replace(ActorPhase::Stopped {
235            cause: StopCause::Panicked,
236            detail: Some("boom".to_string()),
237        });
238        assert!(request_stop(&tx, StopCause::Requested));
239        assert_eq!(
240            *tx.borrow(),
241            ActorPhase::Stopped {
242                cause: StopCause::Panicked,
243                detail: Some("boom".to_string())
244            },
245            "停止请求不得覆盖真实死因"
246        );
247        drop(rx);
248
249        // 零接收端:请求报 false(无监听端),但值必须落库
250        let (tx, rx) = watch::channel(ActorPhase::Running);
251        drop(rx);
252        assert!(
253            !request_stop(&tx, StopCause::SystemShutdown),
254            "零接收端时停止请求必须报 false"
255        );
256        assert_eq!(
257            *tx.borrow(),
258            ActorPhase::Stopped {
259                cause: StopCause::SystemShutdown,
260                detail: None
261            },
262            "零接收端下停止请求仍须落值(死后补订阅可读)"
263        );
264    }
265
266    /// 契约:ask/回执类消息(携带 `oneshot::Sender`,Send + !Sync)必须满足
267    /// `ActorMsg` —— bound 若重新收紧到 Sync 会直接破坏该用例。
268    #[test]
269    fn oneshot_reply_message_satisfies_actor_msg() {
270        fn assert_msg<T: ActorMsg>() {}
271        #[allow(dead_code)] // 仅验证类型满足 ActorMsg,字段本身不被消费
272        struct WithOneshot {
273            reply: tokio::sync::oneshot::Sender<u32>,
274        }
275        assert_msg::<WithOneshot>();
276        assert_msg::<crate::Reply<u32>>();
277    }
278}