1use crate::system::{ActorConfig, ActorSystem};
10use async_trait::async_trait;
11use std::sync::{Mutex, OnceLock};
12use wordval_core::Result;
13
14static GLOBAL: OnceLock<Mutex<Option<ActorSystem>>> = OnceLock::new();
17
18fn slot() -> &'static Mutex<Option<ActorSystem>> {
19 GLOBAL.get_or_init(|| Mutex::new(None))
20}
21
22pub fn actor_system() -> ActorSystem {
28 try_actor_system().expect("ActorSystem 未就绪,请确保 ActorPlugin 已启动且未停止")
29}
30
31pub fn try_actor_system() -> Option<ActorSystem> {
33 slot().lock().unwrap_or_else(|e| e.into_inner()).clone()
34}
35
36pub struct ActorPlugin {
55 config: ActorConfig,
56}
57
58impl ActorPlugin {
59 pub fn new() -> Self {
61 Self {
62 config: ActorConfig::default(),
63 }
64 }
65
66 pub fn with_config(mut self, config: ActorConfig) -> Self {
68 self.config = config;
69 self
70 }
71
72 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 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 }
124}