wordval-actor 1.0.5

Wordval actor system: high-performance message foundation for drone ground stations
Documentation
//! 消息定义 —— Actor 消息契约与系统信号。

use crate::addr::{ActorId, ActorName};
use std::fmt;
use tokio::sync::watch;

/// Actor 消息标记 trait —— 所有进出 Actor 邮箱的消息必须 `Send + 'static`。
///
/// 任意满足约束的类型自动实现,无需手动 derive。
///
/// 仅要求 `Send`:tokio 的 `oneshot::Sender<T>` 是 `Send + !Sync`,
/// ask/回执类消息(携带 `Reply`/`oneshot` 端口)必须能够满足本 bound。
/// 邮箱与回执链路(mpsc / oneshot / Mutex 槽)只跨线程移动值,从不共享引用。
/// 需要 `Sync` 的泛型容器([`Topic`](crate::Topic) / [`SnapshotTopic`](crate::SnapshotTopic)
/// 内部以 `Arc<T>` 跨线程共享)由各自的类型级 bound 单独约束。
pub trait ActorMsg: Send + 'static {}
impl<T: Send + 'static> ActorMsg for T {}

/// Actor 停止原因。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StopCause {
    /// 通过 [`ActorRef::try_stop`](crate::ActorRef::try_stop) /
    /// [`ActorSystem::stop`](crate::ActorSystem::stop) 或 [`ActorAction::Stop`](crate::ActorAction::Stop) 主动停止。
    Requested,
    /// 事件循环 panic,且监督策略不允许(或无法)重启。
    Panicked,
    /// 重启次数超过 [`RestartPolicy::Transient`](crate::RestartPolicy::Transient) 上限。
    ResourceLimit,
    /// 系统级 [`ActorSystem::shutdown`](crate::ActorSystem::shutdown) 优雅关闭:
    /// 关闭请求送达后正常退出的 Actor,与宽限超时被强制注销的 Actor,
    /// 均记此因。
    SystemShutdown,
    /// 邮箱发送端全部关闭且注册表条目已释放(系统被丢弃)。
    ///
    /// 防御性变体,理论不可达:世代运行期间 Supervisor 与 ctx 恒持
    /// 控制通道发送端,`recv()` 不会返回 `None`。
    MailboxClosed,
    /// watch 注册时目标已终止且终止详情不可考(竞态复核补发)。
    Missing,
}

impl fmt::Display for StopCause {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            StopCause::Requested => "requested",
            StopCause::Panicked => "panicked",
            StopCause::ResourceLimit => "resource-limit",
            StopCause::SystemShutdown => "system-shutdown",
            StopCause::MailboxClosed => "mailbox-closed",
            StopCause::Missing => "missing",
        };
        f.write_str(s)
    }
}

/// Actor 生命周期相位 —— 任意时刻可查的运行状态
/// ([`ActorRef::phase`](crate::ActorRef::phase))。
///
/// 与一次性的 [`ActorSignal::Terminated`] 通知互补:通知只描述"刚刚终止"
/// 这一时刻事件,相位是**持续可查**的状态 —— 通道保留末值,Actor 停止后
/// 再查询/订阅照样能读到最终死因与 panic 详情(无需额外墓碑表)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ActorPhase {
    /// 世代正在运行(含世代启动前的初始态)。
    Running,
    /// 监督重启空窗:上一世代已退出,新世代尚未启动。
    ///
    /// 由 `Transient` 退避等待期间发布,供上层观测/展示重启过程
    /// (如地面站 UI 的"链路重连中")。
    Restarting {
        /// 即将启动的世代号(与 [`ActorContext::generation`](crate::ActorContext::generation) 同源)。
        generation: u32,
        /// 本次重启计数(与 [`ActorContext::restarts`](crate::ActorContext::restarts) 同源)。
        attempt: u32,
    },
    /// 已停止:停止请求已落值(`detail` 为 `None`),或已最终退出
    /// (`cause` 为真实死因,panic 详情随 `detail`)。
    ///
    /// 一旦进入不可逆 —— 运行期状态发布(`Running` / `Restarting`)不会
    /// 覆盖它;唯一例外是最终退出:finalize 以真实死因覆盖"停止请求"占位。
    Stopped {
        /// 停止原因。
        cause: StopCause,
        /// panic 详情(仅 [`StopCause::Panicked`] 及其衍生情形可能非空)。
        detail: Option<String>,
    },
}

impl ActorPhase {
    /// 是否尚未停止。注意:停止请求一落值即为 `Stopped`,本判定不区分
    /// "停止中"(请求已送达、事件循环尚在收尾)与"已停止"。
    #[must_use = "存活探测结果不应被静默忽略"]
    pub fn is_alive(&self) -> bool {
        !matches!(self, ActorPhase::Stopped { .. })
    }
}

/// 请求停止:向相位通道写入 `Stopped { cause, detail: None }`。
///
/// - 返回写入前是否存在监听端(`false` 表示目标已最终退出,监督者
///   不再持接收端);
/// - 不覆盖既有 `Stopped`(含 finalize 写入的真实死因),但**会**覆盖
///   `Running` / `Restarting`:停止请求一旦落值,就不会被后续状态发布吞掉。
pub(crate) fn request_stop(tx: &watch::Sender<ActorPhase>, cause: StopCause) -> bool {
    let listeners = !tx.is_closed();
    let _ = tx.send_if_modified(|phase| match phase {
        ActorPhase::Stopped { .. } => false,
        _ => {
            *phase = ActorPhase::Stopped {
                cause,
                detail: None,
            };
            true
        }
    });
    listeners
}

/// 发布运行期相位(`Running` / `Restarting`):终态不可逆,`Stopped` 不被覆盖。
///
/// 用 `send_if_modified`:零接收端时仍落值,相位状态不静默丢失;
/// 仅在值确实变化时唤醒订阅者。
pub(crate) fn publish_phase(tx: &watch::Sender<ActorPhase>, phase: ActorPhase) {
    let _ = tx.send_if_modified(|cur| {
        if *cur == phase || matches!(cur, ActorPhase::Stopped { .. }) {
            return false;
        }
        *cur = phase;
        true
    });
}

/// 目标 Actor 终止通知的载荷。
#[derive(Debug, Clone)]
pub struct Terminated {
    /// 终止的 Actor ID。
    pub actor: ActorId,
    /// 终止的 Actor 名称(若以命名方式 spawn)。
    pub name: Option<ActorName>,
    /// 终止原因。
    pub cause: StopCause,
    /// panic 详情(仅 [`StopCause::Panicked`] 及其衍生情形可能非空):
    /// 事件循环 panic 时从 `JoinError` 载荷提取的文本 —— `&'static str` /
    /// `String` 载荷原样取出,其余类型载荷给固定占位文本;非 panic
    /// 终止时为 `None`。
    pub detail: Option<String>,
}

/// 系统信号 —— 经**专用信号通道**(独立于用户消息邮箱)送达 Actor。
///
/// 系统投递的信号(如 watch 终止通知)走物理隔离的小容量通道,
/// 事件循环每轮优先抽干:失控保护类逻辑(如监视的子机体终止)
/// 不会被遥测/业务消息洪泛饿死。
///
/// 通道内还承载内部的看门狗触发标记:
/// 它同样绕过用户消息积压,但被事件循环拦截后转投
/// [`Actor::handle`](crate::Actor::handle)(携带超时消息),
/// **不会**出现在 [`on_signal`](crate::Actor::on_signal) 中。
#[derive(Debug, Clone)]
pub enum ActorSignal {
    /// 被 watch 的目标 Actor 已终止(无论何种原因)。
    Terminated(Terminated),
}

/// 专用信号通道的内部载荷 —— 系统信号与看门狗触发标记共用该通道,
/// 二者都绕过用户消息积压、由事件循环每轮优先抽干。
///
/// 两条通道各司其职:控制通道只承载用户消息,信号通道承载一切
/// 控制面事件 —— 控制面事件不得混入用户队列被积压延迟。
pub(crate) enum Signal {
    /// 看门狗触发标记:`arm` 为武装世代号(全局单调分配)。
    /// 消费时与当前武装世代比对,已被新帧喂狗/再武装/解除取代的
    /// 陈旧触发静默丢弃。
    WatchdogFire { arm: u64 },
    /// 系统信号(如 watch 终止通知),投递给 [`on_signal`](crate::Actor::on_signal)。
    System(ActorSignal),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn stop_cause_display() {
        assert_eq!(StopCause::Requested.to_string(), "requested");
        assert_eq!(StopCause::Panicked.to_string(), "panicked");
        assert_eq!(StopCause::ResourceLimit.to_string(), "resource-limit");
        assert_eq!(StopCause::SystemShutdown.to_string(), "system-shutdown");
        assert_eq!(StopCause::MailboxClosed.to_string(), "mailbox-closed");
    }

    /// 相位通道守卫契约:
    /// - 运行期状态发布可覆盖 `Running`/`Restarting`,但不得覆盖终态;
    /// - 停止请求可覆盖运行期相位、不得覆盖既有终态(真实死因优先);
    /// - 零接收端时停止请求报 `false`,值照常落库(死后补订阅仍可读)。
    #[test]
    fn phase_channel_guards() {
        let (tx, rx) = watch::channel(ActorPhase::Running);

        // 状态发布:Running → Restarting 生效
        publish_phase(
            &tx,
            ActorPhase::Restarting {
                generation: 2,
                attempt: 1,
            },
        );
        assert_eq!(
            *tx.borrow(),
            ActorPhase::Restarting {
                generation: 2,
                attempt: 1
            }
        );

        // 停止请求:覆盖运行期相位,返回存在监听端
        assert!(request_stop(&tx, StopCause::Requested), "有监听端应报 true");
        assert_eq!(
            *tx.borrow(),
            ActorPhase::Stopped {
                cause: StopCause::Requested,
                detail: None
            }
        );

        // 运行期状态发布不得复活终态
        publish_phase(&tx, ActorPhase::Running);
        assert!(
            matches!(&*tx.borrow(), ActorPhase::Stopped { .. }),
            "Stopped 之后发布 Running 必须被守卫拒绝"
        );

        // finalize 以真实死因覆盖占位值后,迟到的停止请求不得改写
        let _ = tx.send_replace(ActorPhase::Stopped {
            cause: StopCause::Panicked,
            detail: Some("boom".to_string()),
        });
        assert!(request_stop(&tx, StopCause::Requested));
        assert_eq!(
            *tx.borrow(),
            ActorPhase::Stopped {
                cause: StopCause::Panicked,
                detail: Some("boom".to_string())
            },
            "停止请求不得覆盖真实死因"
        );
        drop(rx);

        // 零接收端:请求报 false(无监听端),但值必须落库
        let (tx, rx) = watch::channel(ActorPhase::Running);
        drop(rx);
        assert!(
            !request_stop(&tx, StopCause::SystemShutdown),
            "零接收端时停止请求必须报 false"
        );
        assert_eq!(
            *tx.borrow(),
            ActorPhase::Stopped {
                cause: StopCause::SystemShutdown,
                detail: None
            },
            "零接收端下停止请求仍须落值(死后补订阅可读)"
        );
    }

    /// 契约:ask/回执类消息(携带 `oneshot::Sender`,Send + !Sync)必须满足
    /// `ActorMsg` —— bound 若重新收紧到 Sync 会直接破坏该用例。
    #[test]
    fn oneshot_reply_message_satisfies_actor_msg() {
        fn assert_msg<T: ActorMsg>() {}
        #[allow(dead_code)] // 仅验证类型满足 ActorMsg,字段本身不被消费
        struct WithOneshot {
            reply: tokio::sync::oneshot::Sender<u32>,
        }
        assert_msg::<WithOneshot>();
        assert_msg::<crate::Reply<u32>>();
    }
}