Skip to main content

actor_lite/
actor.rs

1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3use tokio::sync::{Notify, broadcast, mpsc, watch};
4use tracing::debug;
5/// Actor 模型的核心 trait。
6///
7/// 实现此 trait 来定义一个 actor 的行为。每个 actor 有四个关联类型:
8///
9/// | 类型 | 说明 |
10/// |------|------|
11/// | [`Cmd`](Actor::Cmd) | 命令枚举,外部通过它向 actor 发送指令 |
12/// | [`Event`](Actor::Event) | 事件类型,actor 对外广播的异步消息 |
13/// | [`State`](Actor::State) | 低频状态,变化不频繁,可随时读取最新值 |
14/// | [`Progress`](Actor::Progress) | 高频进度,适合进度条、实时指标等场景 |
15///
16/// # 生命周期
17///
18/// 1. 调用 [`Actor::spawn`] 启动 actor,得到 [`ActorHandle`]
19/// 2. 通过 [`ActorHandle`] 发送命令、读取状态/进度、订阅事件
20/// 3. 调用 [`ActorHandle::stop`] 或 drop handle 来停止 actor
21///
22/// # 示例
23///
24/// ```no_run
25/// # use actor_kit::{Actor, ActorContext};
26/// struct Counter {
27///     target: u32,
28/// }
29///
30/// enum CounterCmd {
31///     Reset,
32/// }
33///
34/// impl Actor for Counter {
35///     type Cmd = CounterCmd;
36///     type Event = u32;
37///     type State = u32;
38///     type Progress = f32;
39///
40///     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
41///         (0, 0.0)
42///     }
43///
44///     fn run(self, context: ActorContext<Self>) -> impl std::future::Future<Output = ()> + Send + 'static {
45///         let mut context = context;
46///         async move {
47///             let mut count = 0u32;
48///             loop {
49///                 if let Some(cmd) = context.check_cmd() {
50///                     match cmd {
51///                         CounterCmd::Reset => {
52///                             count = 0;
53///                             context.update_state(count);
54///                             context.update_progress(0.0);
55///                         }
56///                     }
57///                 }
58///                 if count >= self.target {
59///                     break;
60///                 }
61///                 count += 1;
62///                 context.update_state(count);
63///                 context.update_progress(count as f32 / self.target as f32);
64///                 context.send_event(count);
65///             }
66///         }
67///     }
68/// }
69/// ```
70pub trait Actor: Sized + Send + 'static {
71    /// actor 命令枚举
72    ///
73    /// 例如:
74    /// ```
75    /// enum MyCmd {
76    ///     Start,
77    ///     Pause,
78    ///     //...
79    /// }
80    /// ```
81    type Cmd: Send + 'static;
82    /// actor 里的事件结构体,需要实现`Clone`
83    type Event: Clone + Send + 'static;
84    /// actor 里的低频状态,如果不需要,用 `type State = ();`。
85    type State: Clone + Send + Sync + 'static;
86    /// actor 里的高频状态,如果没有高频进度时,用 `type Progress = ();`。
87    type Progress: Clone + Send + Sync + 'static;
88
89    /// actor 的命令通道容量
90    const CMD_CAPACITY: usize = 16;
91    /// actor 的事件通道容量
92    const EVENT_CAPACITY: usize = 16;
93    /// 创建 actor 的通道。
94    /// ActorContext 是 actor 的后台端,ActorHandle 是 actor 的控制端。
95    fn channel(
96        init_state: Self::State,
97        init_progress: Self::Progress,
98    ) -> (ActorContext<Self>, ActorHandle<Self>) {
99        let (cmd_tx, cmd_rx) = mpsc::channel(Self::CMD_CAPACITY);
100        let (state_tx, state_rx) = watch::channel(init_state);
101        let (event_tx, _) = broadcast::channel(Self::EVENT_CAPACITY);
102        let (progress_tx, progress_rx) = watch::channel(init_progress);
103        let cancel = CancelToken::new();
104        let handle_cancel = CancelHandle { cancel };
105        let context_cancel = handle_cancel.clone();
106
107        let context = ActorContext {
108            cmd_rx,
109            event_tx: event_tx.clone(),
110            state_tx,
111            progress_tx,
112            cancel: context_cancel,
113        };
114        let handle = ActorHandle {
115            cmd_tx,
116            event_tx,
117            state_rx,
118            progress_rx,
119            cancel: handle_cancel,
120        };
121        (context, handle)
122    }
123
124    fn init_state_and_progress(&self) -> (Self::State, Self::Progress);
125    /// 启动 actor。
126    ///
127    /// 返回 actor 的控制端。
128    ///
129    ///  外部通过 [`ActorHandle`] 的方法发送命令、监听状态/进度、订阅事件。
130    ///
131    fn spawn(self) -> ActorHandle<Self> {
132        let (init_state, init_progress) = self.init_state_and_progress();
133        let (context, handle) = Self::channel(init_state, init_progress);
134        tokio::spawn(self.run(context));
135        handle
136    }
137    /// actor的主要循环
138    ///
139    /// 运行 actor 的主要逻辑。
140    ///
141    /// # 注意
142    ///
143    /// 接收后台端并自行决定循环和发送事件,更新状态的流程
144    ///
145    /// # 示例
146    ///
147    /// ```no_run
148    ///  # use actor_kit::{Actor, ActorHandle, ActorContext};
149    /// struct MyActor;
150    /// impl Actor for MyActor {
151    ///     type Cmd = ();
152    ///     type Event = ();
153    ///     type State = ();
154    ///     type Progress = ();
155    ///     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
156    ///         ((), ())
157    ///     }
158    ///     fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
159    ///         let mut context = context;
160    ///     async move {
161    ///     
162    ///         loop {
163    ///         if let Some(cmd) = context.check_cmd() {
164    ///             // ...处理命令
165    ///             }
166    ///          //...主要逻辑
167    ///
168    ///          //发送事件和进度,更新状态
169    ///          context.send_event(());
170    ///          context.update_progress(());
171    ///          context.update_state(());
172    ///       }
173    ///     }
174    ///   }
175    /// }
176    /// ```
177    fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static;
178}
179/// actor 的控制端。
180///
181/// 由 [`Actor::channel`] 创建,通常由外部控制方持有。
182/// 用于发送命令、读取状态/进度、订阅事件,以及注册异步监听。
183/// # 示例
184///
185/// ```no_run
186/// # use actor_kit::{Actor, ActorHandle, ActorContext};
187/// # struct MyActor;
188/// # impl Actor for MyActor {
189/// #    type Cmd = ();
190/// #    type Event = ();
191/// #    type State = ();
192/// #    type Progress = ();
193/// #    fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
194/// #        ((), ())
195/// #    }
196/// #    fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
197/// #         async {}
198/// #     }
199/// # }
200/// # async fn example() {
201/// let (context, handle) = MyActor::channel( (), ());
202///
203/// handle.send_cmd(()).await.unwrap();
204/// let state = handle.get_state();
205///
206/// let listener = handle.state_listen_async(|s| async move { true });
207/// listener.cancel();
208/// # }
209/// ```
210#[derive(Debug, Clone)]
211pub struct ActorHandle<A: Actor> {
212    cmd_tx: mpsc::Sender<A::Cmd>,
213    state_rx: watch::Receiver<A::State>,
214    event_tx: broadcast::Sender<A::Event>,
215    progress_rx: watch::Receiver<A::Progress>,
216    cancel: CancelHandle,
217}
218
219impl<A: Actor> ActorHandle<A> {
220    /// 向 actor 发送一条命令。
221    pub async fn send_cmd(&self, cmd: A::Cmd) -> Result<(), mpsc::error::SendError<A::Cmd>> {
222        self.cmd_tx.send(cmd).await
223    }
224    /// 获取 actor 的最新状态。
225    pub fn get_state(&self) -> A::State {
226        self.state_rx.borrow().to_owned()
227    }
228    /// 异步监听状态变化。
229    ///
230    /// 每次状态变化时会调用 `op`,传入最新状态。
231    /// `op` 返回 `true` 继续监听,返回 `false` 停止。
232    ///
233    /// 返回的 [`ListenerHandle`] 被 drop 或调用 `cancel()` 时停止监听。
234
235    pub fn state_listen_async<F, Fut>(&self, mut op: F) -> CancelHandle
236    where
237        F: FnMut(A::State) -> Fut + Send + 'static,
238        Fut: Future<Output = bool> + Send,
239    {
240        let token = CancelToken::new();
241        let wait_token = token.clone();
242        let mut rx = self.state_rx.clone();
243        let listen = async move {
244            loop {
245                tokio::select! {
246                    _ = wait_token.cancelled() => break,
247                    result = rx.changed() => {
248                        match result {
249                        Ok(())=>{
250                            let state = rx.borrow_and_update().to_owned();
251                             if !op(state).await{
252                                break;
253                            }
254                        }
255                        Err(_) => {break}}
256                    }
257                }
258            }
259        };
260        tokio::spawn(listen);
261        CancelHandle { cancel: token }
262    }
263    /// 获取 actor 的最新进度。
264    pub fn get_progress(&self) -> A::Progress {
265        self.progress_rx.borrow().to_owned()
266    }
267    pub fn progress_listen_async<F, Fut>(&self, mut op: F) -> CancelHandle
268    where
269        F: FnMut(A::Progress) -> Fut + Send + 'static,
270        Fut: Future<Output = bool> + Send,
271    {
272        let token = CancelToken::new();
273        let wait_token = token.clone();
274        let mut rx = self.progress_rx.clone();
275        let listen = async move {
276            loop {
277                tokio::select! {
278                    _ = wait_token.cancelled() => break,
279                    result = rx.changed() => {
280                        match result {
281                        Ok(())=>{
282                            let progress = rx.borrow_and_update().to_owned();
283                             if !op(progress).await{
284                                break;
285                            }
286                        }
287                        Err(_) => {break}}
288                    }// 幂等、同步、永不失败
289                }
290            }
291        };
292        tokio::spawn(listen);
293        CancelHandle { cancel: token }
294    }
295
296    pub fn get_events_rx(&self) -> broadcast::Receiver<A::Event> {
297        self.event_tx.subscribe()
298    }
299    pub fn events_listen_async<F, Fut>(&self, mut op: F) -> CancelHandle
300    where
301        F: FnMut(A::Event) -> Fut + Send + 'static,
302        Fut: Future<Output = bool> + Send,
303    {
304        let mut rx = self.event_tx.subscribe();
305        let token = CancelToken::new();
306        let wait_token = token.clone();
307        let listen = async move {
308            loop {
309                tokio::select! {
310                    _ = wait_token.cancelled() => break,
311                    result = rx.recv() => {
312                        match result {
313                            Ok(e) => { if  !op(e).await { break; } }
314                            Err(broadcast::error::RecvError::Closed) => break,
315                            Err(broadcast::error::RecvError::Lagged(n)) => {
316                                debug!("事件监听落后 {n} 条");
317                                break;
318                            // 继续,或 break,看语义
319                        }
320                    }}
321                }
322            }
323        };
324        tokio::spawn(listen);
325        CancelHandle { cancel: token }
326    }
327    pub fn stop(&self) {
328        self.cancel.cancel();
329    }
330}
331
332/// actor 的后台端。
333///
334/// 由 [`Actor::channel`] 创建,通常由后台任务持有。
335/// 用于接收命令、更新状态/进度、广播事件。
336pub struct ActorContext<A: Actor> {
337    cmd_rx: mpsc::Receiver<A::Cmd>,
338    state_tx: watch::Sender<A::State>,
339    event_tx: broadcast::Sender<A::Event>,
340    progress_tx: watch::Sender<A::Progress>,
341    cancel: CancelHandle,
342}
343impl<A: Actor> ActorContext<A> {
344    /// 获取额外的事件发送端。
345    pub fn get_events_clone(&self) -> broadcast::Sender<A::Event> {
346        self.event_tx.clone()
347    }
348    /// 发送事件。
349    pub fn send_event(&self, event: A::Event) {
350        let _ = self.event_tx.send(event);
351    }
352    /// 更新状态。
353    pub fn update_state(&self, state: A::State) {
354        let _ = self.state_tx.send(state);
355    }
356    /// 更新进度。
357    pub fn update_progress(&self, progress: A::Progress) {
358        let _ = self.progress_tx.send(progress);
359    }
360    /// 阻塞等待命令。
361    pub fn wait_for_cmd(&mut self) -> impl Future<Output = Option<A::Cmd>> {
362        self.cmd_rx.recv()
363    }
364    /// 非阻塞检查命令。
365    pub fn check_cmd(&mut self) -> Option<A::Cmd> {
366        self.cmd_rx.try_recv().ok()
367    }
368
369    pub fn cancel_clone(&self) -> CancelHandle {
370        self.cancel.clone()
371    }
372}
373/// 取消信号。
374///
375/// 可在多个任务间 clone 共享。任意一份调用 [`CancelToken::cancel`],
376/// 所有通过 [`CancelToken::cancelled`] 等待的任务都会收到通知。
377/// `cancel` 是幂等的。
378/// ...
379/// # 注意
380///
381/// `CancelToken` 是 `Clone` 的,clone 出来的所有副本共享同一个取消信号。
382/// 任意一份 `cancel()` 都会让所有副本的 `cancelled()` 返回。
383#[derive(Clone, Debug)]
384struct CancelToken {
385    cancelled: Arc<AtomicBool>,
386    notify: Arc<Notify>,
387}
388
389impl CancelToken {
390    pub fn new() -> Self {
391        Self {
392            cancelled: Arc::new(AtomicBool::new(false)),
393            notify: Arc::new(Notify::new()),
394        }
395    }
396    /// 检查取消信号。
397    pub fn is_cancelled(&self) -> bool {
398        self.cancelled.load(Ordering::Acquire)
399    }
400    /// 等待取消信号。
401    pub async fn cancelled(&self) {
402        if self.is_cancelled() {
403            return;
404        }
405        let notified = self.notify.notified();
406        if self.is_cancelled() {
407            return;
408        }
409        notified.await;
410    }
411    /// 发送取消信号。
412    pub fn cancel(&self) {
413        if !self.cancelled.swap(true, Ordering::AcqRel) {
414            self.notify.notify_waiters();
415        }
416    }
417}
418/// 监听句柄。
419///
420/// 由 `state_listen_async` / `progress_listen_async` / `events_listen_async` 返回。
421/// 调用 [`CancelHandle::cancel`] 或直接 drop 都会停止对应的监听任务。
422#[derive(Debug, Clone)]
423pub struct CancelHandle {
424    cancel: CancelToken,
425}
426
427impl CancelHandle {
428    pub fn cancel(&self) {
429        self.cancel.cancel();
430    }
431
432    pub fn is_cancelled(&self) -> bool {
433        self.cancel.is_cancelled()
434    }
435
436    pub async fn cancelled(&self) {
437        self.cancel.cancelled().await;
438    }
439}
440
441impl Drop for CancelHandle {
442    fn drop(&mut self) {
443        self.cancel.cancel();
444    }
445}