Skip to main content

actor_lite/
manager.rs

1//! Actor 管理器模块。
2//!
3//! [`ActorManager`] 是一个特殊的 [`AsyncActor`],它管理一组同类型的子 actor,
4//! 并聚合它们的状态、进度和事件,对外暴露为单一 actor 接口。
5//!
6//! # 架构
7//!
8//! ```text
9//! ActorManager (本身也是 AsyncActor)
10//! ├── Child Actor 0  (id=1)
11//! ├── Child Actor 1  (id=2)
12//! └── Child Actor 2  (id=3)
13//! ```
14//!
15//! - 每个子 actor 由 [`ActorManager`] 启动并分配一个唯一 `id`。
16//! - 管理器自动监听子 actor 的状态、进度和事件,并聚合到自身的 [`ManagerState`] 和 [`ManagerProgress`] 中。
17//! - 外部通过 [`ManagerCmd`] 向管理器发送命令:启动/停止子 actor,或转发命令给某个子 actor。
18//!
19//! # 限制
20//!
21//! manager 及其子 actor 目前都要求异步壳([`AsyncActor`]):子 actor 走 `tokio::spawn`,
22//! 聚合用的 `tokio::time::interval` 也依赖 runtime。因此整个 manager 必须跑在 tokio runtime 里。
23//!
24//! # 示例
25//!
26//! ```no_run
27//! # use actor_lite::{ActorCore, AsyncActor, ActorContext, ActorHandle};
28//! # use actor_lite::manager::{ActorManager, ManagerCmd, ManagerState, ManagerProgress, ManagerEvent};
29//! # struct MyActor;
30//! # impl ActorCore for MyActor {
31//! #     type Cmd = ();
32//! #     type Event = ();
33//! #     type State = ();
34//! #     type Progress = ();
35//! #     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) { ((), ()) }
36//! # }
37//! # impl AsyncActor for MyActor {
38//! #     fn run(self, context: ActorContext<Self>) -> impl std::future::Future<Output = ()> + Send + 'static {
39//! #         async {}
40//! #     }
41//! # }
42//! # async fn example() {
43//! // 创建并启动 manager
44//! let manager = ActorManager::<MyActor>::new();
45//! let handle = manager.spawn();
46//!
47//! let (id_tx,id_rx) = tokio::sync::oneshot::channel();
48//! handle.send_cmd(ManagerCmd::SpawnActor{actor:MyActor,id_tx:Some(id_tx)}).unwrap();
49//! let id = id_rx.await.unwrap();
50//! // 读取所有子 actor 的状态
51//! let state: ManagerState<()> = handle.get_state();
52//! assert_eq!(state.len(), 1);
53//!
54//! // 向指定子 actor 转发命令
55//! handle.send_cmd(ManagerCmd::Forward { id: 1, cmd: () }).unwrap();
56//!
57//! // 停止指定子 actor
58//! handle.send_cmd(ManagerCmd::StopActor(1)).unwrap();
59//! # }
60//! ```
61use crate::async_actor::AsyncActor;
62use crate::core::{ActorContext, ActorCore, ActorHandle, CancelToken};
63use std::collections::HashMap;
64use std::sync::atomic::{AtomicUsize, Ordering};
65use tokio::sync::{broadcast, mpsc, oneshot};
66use tokio::time::Duration;
67use tracing::{debug, warn};
68
69/// 子 actor 管理器。
70///
71/// `ActorManager` 本身实现了 [`AsyncActor`],因此可以像普通 actor 一样被 [`AsyncActor::spawn`]
72/// 启动和持有。
73///
74/// 它管理一组同类型的子 actor,对外提供:
75/// - 启动/停止子 actor
76/// - 向指定子 actor 转发命令
77/// - 聚合所有子 actor 的状态、进度和事件
78///
79/// # 类型参数
80///
81/// - `A`: 子 actor 的类型,必须实现 [`AsyncActor`]。
82/// - `E`: 管理器事件通道(`broadcast`)的容量。
83///
84/// # 示例
85///
86/// ```no_run
87/// # use actor_lite::{ActorCore, AsyncActor, ActorContext};
88/// # use actor_lite::manager::{ActorManager, ManagerCmd};
89/// # struct MyActor;
90/// # impl ActorCore for MyActor {
91/// #     type Cmd = ();
92/// #     type Event = ();
93/// #     type State = ();
94/// #     type Progress = ();
95/// #     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) { ((), ()) }
96/// # }
97/// # impl AsyncActor for MyActor {
98/// #     fn run(self, context: ActorContext<Self>) -> impl std::future::Future<Output = ()> + Send + 'static {
99/// #         async {}
100/// #     }
101/// # }
102/// # async fn example() {
103/// let manager = ActorManager::<MyActor>::new();
104/// let handle = manager.spawn();
105///
106/// // 启动子 actor,返回分配的 id
107/// let (id_tx,id_rx) = tokio::sync::oneshot::channel();
108/// handle.send_cmd(ManagerCmd::SpawnActor{actor:MyActor,id_tx:Some(id_tx)}).unwrap();
109/// let id = id_rx.await.unwrap();
110///
111/// # }
112/// ```
113pub struct ActorManager<A: AsyncActor, const E: usize = 256> {
114    actors: HashMap<usize, ActorHandle<A>>,
115    next_id: AtomicUsize,
116    state: ManagerState<A::State>,
117    progress: ManagerProgress<A::Progress>,
118    listeners: HashMap<usize, CancelListeners>,
119    update_interval: Duration,
120}
121
122impl<A: AsyncActor, const E: usize> Default for ActorManager<A, E> {
123    fn default() -> Self {
124        Self::new()
125    }
126}
127
128impl<A: AsyncActor, const E: usize> ActorManager<A, E> {
129    /// 创建一个空的 `ActorManager`。
130    ///
131    /// 初始时不管理任何子 actor,需要启动后通过 [`ManagerCmd::SpawnActor`] 添加。
132    pub fn new() -> Self {
133        Self {
134            actors: HashMap::new(),
135            next_id: AtomicUsize::new(1),
136            state: ManagerState {
137                actors: HashMap::new(),
138            },
139            progress: ManagerProgress {
140                actors: HashMap::new(),
141            },
142            listeners: HashMap::new(),
143            update_interval: Duration::from_millis(500),
144        }
145    }
146    pub fn set_update_interval(&mut self, interval: Duration) {
147        self.update_interval = interval;
148    }
149    fn get_id(&self) -> usize {
150        self.next_id.fetch_add(1, Ordering::SeqCst)
151    }
152    fn spawn_actor(
153        &mut self,
154        actor: A,
155        update_tx: mpsc::Sender<Update>,
156        event_tx: broadcast::Sender<ManagerEvent<A::Event>>,
157    ) -> usize {
158        let id = self.get_id();
159        let handle = actor.spawn();
160        let progress = Self::listen_progress(&handle, id, update_tx.clone());
161        let state = Self::listen_state(&handle, id, update_tx);
162        let events = Self::listen_events(&handle, id, event_tx);
163        self.actors.insert(id, handle);
164        self.listeners.insert(
165            id,
166            CancelListeners {
167                state,
168                progress,
169                events,
170            },
171        );
172        id
173    }
174
175    fn stop_actor(&mut self, id: usize) {
176        if let Some(handle) = self.actors.remove(&id) {
177            handle.stop();
178        };
179        self.state.actors.remove(&id);
180        self.progress.actors.remove(&id);
181        if let Some(listeners) = self.listeners.remove(&id) {
182            listeners.stop_all();
183        }
184    }
185
186    fn listen_state(
187        handle: &ActorHandle<A>,
188        id: usize,
189        update_tx: mpsc::Sender<Update>,
190    ) -> CancelToken {
191        handle.state_listen_async(move |_| {
192            let state_tx = update_tx.clone();
193            async move {
194                let _ = state_tx.send(Update::State(id)).await;
195            }
196        })
197    }
198
199    fn listen_progress(
200        handle: &ActorHandle<A>,
201        id: usize,
202        update_tx: mpsc::Sender<Update>,
203    ) -> CancelToken {
204        handle.progress_listen_async(move |_| {
205            let progress_tx = update_tx.clone();
206            async move {
207                let _ = progress_tx.send(Update::Progress(id)).await;
208            }
209        })
210    }
211    fn listen_events(
212        handle: &ActorHandle<A>,
213        id: usize,
214        event_tx: broadcast::Sender<ManagerEvent<A::Event>>,
215    ) -> CancelToken {
216        handle.events_listen_async(move |event| {
217            let events_tx = event_tx.clone();
218            async move {
219                let _ = events_tx.send(ManagerEvent::ChildEvent { id, event });
220            }
221        })
222    }
223}
224
225impl<A: AsyncActor, const E: usize> ActorCore for ActorManager<A, E> {
226    type Cmd = ManagerCmd<A>;
227    type State = ManagerState<A::State>;
228    type Progress = ManagerProgress<A::Progress>;
229    type Event = ManagerEvent<A::Event>;
230    const EVENT_CAPACITY: usize = E;
231
232    fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
233        (self.state.clone(), self.progress.clone())
234    }
235}
236impl<A: AsyncActor, const E: usize> AsyncActor for ActorManager<A, E> {
237    fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
238        let mut context = context;
239        let mut manager = self;
240        let cancel = context.cancel_clone();
241
242        async move {
243            let (update_tx, mut update_rx) = mpsc::channel::<Update>(256);
244            let mut push_interval = tokio::time::interval(manager.update_interval);
245            push_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
246            loop {
247                tokio::select! {
248                    _ = cancel.cancelled() => { debug!("Manager 被 cancel 了!");break},
249                    Some(cmd) = context.wait_for_cmd() => {
250                        match cmd {
251                            ManagerCmd::SpawnActor{actor, id_tx} => {
252                                let id = manager.spawn_actor(actor, update_tx.clone(), context.get_events_clone());
253                                if let Some(tx) = id_tx{
254                                    let _ = tx.send(id);
255                                }
256                                context.send_event(ManagerEvent::Spawned { id });
257                            }
258                            ManagerCmd::StopActor(id) => {
259                                manager.stop_actor(id);
260                                context.update_state(manager.state.clone());
261                                context.update_progress(manager.progress.clone());
262                                context.send_event(ManagerEvent::Stopped { id });
263                            }
264                            ManagerCmd::Forward { id, cmd } => {
265                                match manager.actors.get(&id) {
266                                    Some(handle) => {
267                                        if handle.send_cmd(cmd).is_err() {
268                                            warn!("子Actor已经停止了: id={id}");
269                                        }
270                                    }
271                                    None => warn!("没有找到id对应的子Actor: id={id}"),
272                                }
273                            }
274                        }
275                    }
276                    Some(update) = update_rx.recv() => {
277                        match update {
278                            Update::State(id) => {
279                                if let Some(handle) = manager.actors.get(&id) {
280                                    let state = handle.get_state();
281                                    manager.state.actors.insert(id, state);
282                                    context.update_state(manager.state.clone());
283                                }
284                            }
285                            Update::Progress(id) => {
286                                if let Some(handle) = manager.actors.get(&id) {
287                                    let progress = handle.get_progress();
288                                    manager.progress.actors.insert(id, progress);
289                                }
290                            }
291                        }
292                        }
293                    _ = push_interval.tick() => {
294                        context.update_progress(manager.progress.clone());
295                    }
296                }
297            }
298        }
299    }
300}
301
302enum Update {
303    State(usize),
304    Progress(usize),
305}
306
307struct CancelListeners {
308    state: CancelToken,
309    progress: CancelToken,
310    events: CancelToken,
311}
312
313impl CancelListeners {
314    fn stop_all(self) {
315        self.state.cancel();
316        self.progress.cancel();
317        self.events.cancel();
318    }
319}
320
321/// 管理器的命令枚举。
322///
323/// 通过 [`ActorHandle::send_cmd`] 发送给 [`ActorManager`],控制子 actor 的生命周期和通信。
324///
325/// # 变体
326///
327/// | 变体 | 说明 |
328/// |------|------|
329/// | [`ManagerCmd::SpawnActor`] | 启动一个新的子 actor,可以选择返回分配的 `id`(通过oneshot通道) |
330/// | [`ManagerCmd::StopActor`] | 停止指定 `id` 的子 actor |
331/// | [`ManagerCmd::Forward`] | 向指定 `id` 的子 actor 转发一条命令 |
332///
333/// # 示例
334///
335/// ```no_run
336/// # use actor_lite::{ActorCore, AsyncActor, ActorContext};
337/// # use actor_lite::manager::{ActorManager, ManagerCmd};
338/// # struct MyActor;
339/// # impl ActorCore for MyActor {
340/// #     type Cmd = String;
341/// #     type Event = ();
342/// #     type State = ();
343/// #     type Progress = ();
344/// #     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) { ((), ()) }
345/// # }
346/// # impl AsyncActor for MyActor {
347/// #     fn run(self, context: ActorContext<Self>) -> impl std::future::Future<Output = ()> + Send + 'static {
348/// #         async {}
349/// #     }
350/// # }
351/// # async fn example() {
352/// let handle = ActorManager::<MyActor>::new().spawn();
353///
354/// // 启动子 actor
355/// let (id_tx,id_rx) = tokio::sync::oneshot::channel();
356/// handle.send_cmd(ManagerCmd::SpawnActor{actor:MyActor,id_tx:Some(id_tx)}).unwrap();
357/// let id = id_rx.await.unwrap();
358/// // 转发命令给 id=1 的子 actor
359/// handle.send_cmd(ManagerCmd::Forward { id: 1, cmd: "hello".into() }).unwrap();
360///
361/// // 停止 id=1 的子 actor
362/// handle.send_cmd(ManagerCmd::StopActor(1)).unwrap();
363/// # }
364/// ```
365pub enum ManagerCmd<A: AsyncActor> {
366    /// 启动一个新的子 actor。
367    ///
368    /// 管理器会为其分配唯一 `id`,并通过 [`ManagerEvent::Spawned`] 事件通知。
369    SpawnActor {
370        actor: A,
371        id_tx: Option<oneshot::Sender<usize>>,
372    },
373    /// 停止指定 `id` 的子 actor。
374    ///
375    /// 停止后通过 [`ManagerEvent::Stopped`] 事件通知。
376    StopActor(usize),
377    /// 向指定 `id` 的子 actor 转发一条命令。
378    ///
379    /// 若 `id` 不存在,命令会被静默丢弃。
380    Forward { id: usize, cmd: A::Cmd },
381}
382
383/// 管理器聚合的所有子 actor 状态。
384///
385/// 以 `id` 为键,存储每个子 actor 的最新状态。
386/// 通过 [`ActorHandle::get_state`] 获取。
387///
388/// # 示例
389///
390/// ```no_run
391/// # use actor_lite::{ActorCore, AsyncActor, ActorContext};
392/// # use actor_lite::manager::{ActorManager, ManagerState};
393/// # struct MyActor;
394/// # impl ActorCore for MyActor {
395/// #     type Cmd = ();
396/// #     type Event = ();
397/// #     type State = u32;
398/// #     type Progress = ();
399/// #     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) { (0, ()) }
400/// # }
401/// # impl AsyncActor for MyActor {
402/// #     fn run(self, context: ActorContext<Self>) -> impl std::future::Future<Output = ()> + Send + 'static {
403/// #         async {}
404/// #     }
405/// # }
406/// # async fn example() {
407/// # let handle = ActorManager::<MyActor>::new().spawn();
408/// let state: ManagerState<u32> = handle.get_state();
409///
410/// // 按 id 读取
411/// if let Some(&42) = state.get(1) {
412///     println!("actor 1 的状态是 42");
413/// }
414///
415/// // 遍历所有子 actor 状态
416/// for (id, s) in state.iter() {
417///     println!("actor {id}: {s}");
418/// }
419///
420/// println!("共 {} 个子 actor", state.len());
421/// # }
422/// ```
423#[derive(Debug, Clone)]
424pub struct ManagerState<State> {
425    actors: HashMap<usize, State>,
426}
427
428impl<State> ManagerState<State> {
429    /// 按 `id` 读取某个子 actor 的状态。
430    pub fn get(&self, id: usize) -> Option<&State> {
431        self.actors.get(&id)
432    }
433
434    /// 遍历所有子 actor 的状态,返回 `(id, &state)` 迭代器。
435    pub fn iter(&self) -> impl Iterator<Item = (usize, &State)> {
436        self.actors.iter().map(|(&id, s)| (id, s))
437    }
438
439    /// 当前管理的子 actor 数量。
440    pub fn len(&self) -> usize {
441        self.actors.len()
442    }
443
444    /// 是否没有子 actor。
445    pub fn is_empty(&self) -> bool {
446        self.actors.is_empty()
447    }
448}
449
450/// 管理器聚合的所有子 actor 进度。
451///
452/// 以 `id` 为键,存储每个子 actor 的最新进度。
453/// 进度会定时(每秒)推送到管理器的 `progress` 通道。
454///
455/// # 示例
456///
457/// ```no_run
458/// # use actor_lite::{ActorCore, AsyncActor, ActorContext};
459/// # use actor_lite::manager::{ActorManager, ManagerProgress};
460/// # struct MyActor;
461/// # impl ActorCore for MyActor {
462/// #     type Cmd = ();
463/// #     type Event = ();
464/// #     type State = ();
465/// #     type Progress = f32;
466/// #     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) { ((), 0.0) }
467/// # }
468/// # impl AsyncActor for MyActor {
469/// #     fn run(self, context: ActorContext<Self>) -> impl std::future::Future<Output = ()> + Send + 'static {
470/// #         async {}
471/// #     }
472/// # }
473/// # async fn example() {
474/// # let handle = ActorManager::<MyActor>::new().spawn();
475/// let progress: ManagerProgress<f32> = handle.get_progress();
476///
477/// for (id, p) in progress.iter() {
478///     println!("actor {id} 进度: {:.1}%", p * 100.0);
479/// }
480/// # }
481/// ```
482#[derive(Debug, Clone)]
483pub struct ManagerProgress<Progress> {
484    actors: HashMap<usize, Progress>,
485}
486
487impl<Progress> ManagerProgress<Progress> {
488    /// 按 `id` 读取某个子 actor 的进度。
489    pub fn get(&self, id: usize) -> Option<&Progress> {
490        self.actors.get(&id)
491    }
492
493    /// 遍历所有子 actor 的进度,返回 `(id, &progress)` 迭代器。
494    pub fn iter(&self) -> impl Iterator<Item = (usize, &Progress)> {
495        self.actors.iter().map(|(&id, s)| (id, s))
496    }
497
498    /// 当前管理的子 actor 数量。
499    pub fn len(&self) -> usize {
500        self.actors.len()
501    }
502
503    /// 是否没有子 actor。
504    pub fn is_empty(&self) -> bool {
505        self.actors.is_empty()
506    }
507}
508
509/// 管理器发出的事件枚举。
510///
511/// 聚合了所有子 actor 的事件以及管理器自身的生命周期事件。
512/// 通过 [`ActorHandle::get_events_rx`] 或 `events_listen_async` 订阅。
513///
514/// # 变体
515///
516/// | 变体 | 说明 |
517/// |------|------|
518/// | [`ManagerEvent::ChildEvent`] | 某个子 actor 发出的事件,附带其 `id` |
519/// | [`ManagerEvent::Spawned`] | 新子 actor 已启动,附带分配的 `id` |
520/// | [`ManagerEvent::Stopped`] | 子 actor 已停止,附带其 `id` |
521///
522/// # 示例
523///
524/// ```no_run
525/// # use actor_lite::{ActorCore, AsyncActor, ActorContext};
526/// # use actor_lite::manager::{ActorManager, ManagerEvent};
527/// # struct MyActor;
528/// # impl ActorCore for MyActor {
529/// #     type Cmd = ();
530/// #     type Event = String;
531/// #     type State = ();
532/// #     type Progress = ();
533/// #     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) { ((), ()) }
534/// # }
535/// # impl AsyncActor for MyActor {
536/// #     fn run(self, context: ActorContext<Self>) -> impl std::future::Future<Output = ()> + Send + 'static {
537/// #         async {}
538/// #     }
539/// # }
540/// # async fn example() {
541/// let handle = ActorManager::<MyActor>::new().spawn();
542/// let mut rx = handle.get_events_rx();
543///
544/// while let Ok(event) = rx.recv().await {
545///     match event {
546///         ManagerEvent::ChildEvent { id, event } => {
547///             println!("actor {id} 发出事件: {event}");
548///         }
549///         ManagerEvent::Spawned { id } => {
550///             println!("新 actor 已启动,id={id}");
551///         }
552///         ManagerEvent::Stopped { id } => {
553///             println!("actor {id} 已停止");
554///         }
555///     }
556/// }
557/// # }
558/// ```
559#[derive(Debug, Clone)]
560pub enum ManagerEvent<Event> {
561    /// 某个子 actor 发出的事件。
562    ChildEvent { id: usize, event: Event },
563    /// 新子 actor 已启动,`id` 为其分配的标识。
564    Spawned { id: usize },
565    /// 子 actor 已停止,`id` 为其标识。
566    Stopped { id: usize },
567}