Skip to main content

actor_lite/
manager.rs

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