Skip to main content

wordval_actor/
plugin.rs

1//! ActorPlugin —— wordval 插件系统集成。
2//!
3//! 两处关键契约:
4//! - 全局句柄为 `Mutex<Option<ActorSystem>>` 可重启槽位:`stop` 真正
5//!   shutdown 并释放句柄,再次 `start` 重建全新系统(无 OnceLock 毒化)。
6//! - 配置(mailbox_capacity / shutdown_grace)真正传入
7//!   [`ActorSystem::with_config`],启动参数必须实际生效。
8
9use crate::system::{ActorConfig, ActorSystem};
10use async_trait::async_trait;
11use std::sync::{Mutex, OnceLock};
12use wordval_core::Result;
13
14/// 全局系统槽。`OnceLock<Mutex<Option<_>>>` 仅用于槽位本身的懒初始化,
15/// 槽内内容随 start/stop 反复装填/清空,支持系统整体重启。
16static GLOBAL: OnceLock<Mutex<Option<ActorSystem>>> = OnceLock::new();
17
18fn slot() -> &'static Mutex<Option<ActorSystem>> {
19    GLOBAL.get_or_init(|| Mutex::new(None))
20}
21
22/// 获取当前全局 ActorSystem。
23///
24/// # Panics
25///
26/// 若 [`ActorPlugin`] 尚未启动(或已停止),panic 并提示装配顺序。
27pub fn actor_system() -> ActorSystem {
28    try_actor_system().expect("ActorSystem 未就绪,请确保 ActorPlugin 已启动且未停止")
29}
30
31/// 尝试获取当前全局 ActorSystem(不 panic);未启动/已停止返回 None。
32pub fn try_actor_system() -> Option<ActorSystem> {
33    slot().lock().unwrap_or_else(|e| e.into_inner()).clone()
34}
35
36/// wordval Actor 插件:管理全局 [`ActorSystem`] 生命周期。
37///
38/// # 示例
39///
40/// ```no_run
41/// use wordval_actor::{ActorConfig, ActorPlugin};
42/// use wordval_core::plugin::PluginManager;
43///
44/// # async fn demo() -> wordval_core::Result<()> {
45/// let plugin = ActorPlugin::new().with_config(ActorConfig {
46///     mailbox_capacity: 512,
47///     ..Default::default()
48/// });
49/// let mgr = PluginManager::new().add(plugin);
50/// mgr.start_all().await?;
51/// # Ok(())
52/// # }
53/// ```
54pub struct ActorPlugin {
55    config: ActorConfig,
56}
57
58impl ActorPlugin {
59    /// 以默认配置创建插件。
60    pub fn new() -> Self {
61        Self {
62            config: ActorConfig::default(),
63        }
64    }
65
66    /// 指定系统配置(在 `start` 时生效)。
67    pub fn with_config(mut self, config: ActorConfig) -> Self {
68        self.config = config;
69        self
70    }
71
72    /// 快捷设置控制通道默认容量。
73    pub fn with_mailbox_capacity(mut self, capacity: usize) -> Self {
74        self.config.mailbox_capacity = capacity.max(1);
75        self
76    }
77}
78
79impl Default for ActorPlugin {
80    fn default() -> Self {
81        Self::new()
82    }
83}
84
85#[async_trait]
86impl wordval_core::Plugin for ActorPlugin {
87    fn name(&self) -> &str {
88        "actor"
89    }
90
91    async fn start(&self) -> Result<()> {
92        let system = ActorSystem::with_config(self.config.clone());
93        // 上一次 stop 未执行(异常路径):先无锁关闭旧系统,再装填新的
94        // (sync Mutex guard 绝不跨 await,否则 Future 非 Send)
95        let stale = slot().lock().unwrap_or_else(|e| e.into_inner()).take();
96        if let Some(old) = stale {
97            old.shutdown().await;
98        }
99        *slot().lock().unwrap_or_else(|e| e.into_inner()) = Some(system);
100        tracing::info!(
101            mailbox_capacity = self.config.mailbox_capacity,
102            "ActorPlugin 已启动(ActorSystem 就绪)"
103        );
104        Ok(())
105    }
106
107    async fn stop(&self) -> Result<()> {
108        let system = slot().lock().unwrap_or_else(|e| e.into_inner()).take();
109        match system {
110            Some(system) => {
111                system.shutdown().await;
112                tracing::info!("ActorPlugin 已停止(ActorSystem 已关闭)");
113            }
114            None => {
115                tracing::warn!("ActorPlugin stop 调用时系统未启动,忽略");
116            }
117        }
118        Ok(())
119    }
120
121    fn priority(&self) -> i32 {
122        50 // 框架基础设施,应在业务插件之前启动
123    }
124}