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