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_lite::{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
105        let context_cancel = 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,
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        debug!("spawn actor: {}", std::any::type_name::<Self>());
136        handle
137    }
138    /// actor的主要循环
139    ///
140    /// 运行 actor 的主要逻辑。
141    ///
142    /// # 注意
143    ///
144    /// 接收后台端并自行决定循环和发送事件,更新状态的流程
145    ///
146    /// # 示例
147    ///
148    /// ```no_run
149    ///  # use actor_lite::{Actor, ActorHandle, ActorContext};
150    /// struct MyActor;
151    /// impl Actor for MyActor {
152    ///     type Cmd = ();
153    ///     type Event = ();
154    ///     type State = ();
155    ///     type Progress = ();
156    ///     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
157    ///         ((), ())
158    ///     }
159    ///     fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
160    ///         let mut context = context;
161    ///     async move {
162    ///     
163    ///         loop {
164    ///         if let Some(cmd) = context.check_cmd() {
165    ///             // ...处理命令
166    ///             }
167    ///          //...主要逻辑
168    ///
169    ///          //发送事件和进度,更新状态
170    ///          context.send_event(());
171    ///          context.update_progress(());
172    ///          context.update_state(());
173    ///       }
174    ///     }
175    ///   }
176    /// }
177    /// ```
178    fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static;
179}
180/// actor 的控制端。
181///
182/// 由 [`Actor::channel`] 创建,通常由外部控制方持有。
183/// 用于发送命令、读取状态/进度、订阅事件,以及注册异步监听。
184/// # 示例
185///
186/// ```no_run
187/// # use actor_lite::{Actor, ActorHandle, ActorContext};
188/// # struct MyActor;
189/// # impl Actor for MyActor {
190/// #    type Cmd = ();
191/// #    type Event = ();
192/// #    type State = ();
193/// #    type Progress = ();
194/// #    fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
195/// #        ((), ())
196/// #    }
197/// #    fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
198/// #         async {}
199/// #     }
200/// # }
201/// # async fn example() {
202/// let (context, handle) = MyActor::channel( (), ());
203///
204/// handle.send_cmd(()).await.unwrap();
205/// let state = handle.get_state();
206///
207/// let listener = handle.state_listen_async(|s| async move { });
208/// listener.cancel();
209/// # }
210/// ```
211
212pub struct ActorHandle<A: Actor> {
213    cmd_tx: mpsc::Sender<A::Cmd>,
214    state_rx: watch::Receiver<A::State>,
215    event_tx: broadcast::Sender<A::Event>,
216    progress_rx: watch::Receiver<A::Progress>,
217    cancel: CancelToken,
218}
219
220impl<A: Actor> ActorHandle<A> {
221    /// 向 actor 发送一条命令。
222    pub async fn send_cmd(&self, cmd: A::Cmd) -> Result<(), mpsc::error::SendError<A::Cmd>> {
223        self.cmd_tx.send(cmd).await
224    }
225    /// 获取 actor 的最新状态。
226    pub fn get_state(&self) -> A::State {
227        self.state_rx.borrow().to_owned()
228    }
229    /// 异步监听状态变化。
230    ///
231    /// 每次状态变化时会调用 `op`,传入最新状态。
232    /// `op` 返回 `true` 继续监听,返回 `false` 停止。
233    ///
234    /// 返回的 [`ListenerHandle`] 被 drop 或调用 `cancel()` 时停止监听。
235
236    pub fn state_listen_async<F, Fut>(&self, mut op: F) -> CancelToken
237    where
238        F: FnMut(A::State) -> Fut + Send + 'static,
239        Fut: Future<Output = ()> + Send,
240    {
241        let token = CancelToken::new();
242        let wait_token = token.clone();
243        let mut rx = self.state_rx.clone();
244        let listen = async move {
245            loop {
246                tokio::select! {
247                _ = wait_token.cancelled() => break,
248                result = rx.changed() => {
249                    match result {
250                    Ok(())=>{
251                        let state = rx.borrow_and_update().to_owned();
252                         op(state).await;
253                        }
254
255                    Err(_) => break}
256                }
257                }
258            }
259        };
260        tokio::spawn(listen);
261        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) -> CancelToken
268    where
269        F: FnMut(A::Progress) -> Fut + Send + 'static,
270        Fut: Future<Output = ()> + 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                            op(progress).await;
284                        }
285                        Err(_) => break}
286                    }// 幂等、同步、永不失败
287                }
288            }
289        };
290        tokio::spawn(listen);
291        token
292    }
293
294    pub fn get_events_rx(&self) -> broadcast::Receiver<A::Event> {
295        self.event_tx.subscribe()
296    }
297    pub fn events_listen_async<F, Fut>(&self, mut op: F) -> CancelToken
298    where
299        F: FnMut(A::Event) -> Fut + Send + 'static,
300        Fut: Future<Output = ()> + Send,
301    {
302        let mut rx = self.event_tx.subscribe();
303        let token = CancelToken::new();
304        let wait_token = token.clone();
305        let listen = async move {
306            loop {
307                tokio::select! {
308                    _ = wait_token.cancelled() => break,
309                    result = rx.recv() => {
310                        match result {
311                            Ok(e) => { op(e).await; }
312                            Err(broadcast::error::RecvError::Closed) => break,
313                            Err(broadcast::error::RecvError::Lagged(n)) => {
314                                debug!("事件监听落后 {n} 条");
315                                continue;
316                        }
317                    }}
318                }
319            }
320        };
321        tokio::spawn(listen);
322        token
323    }
324    pub fn stop(&self) {
325        self.cancel.cancel();
326    }
327}
328impl<A: Actor> Clone for ActorHandle<A> {
329    fn clone(&self) -> Self {
330        Self {
331            cmd_tx: self.cmd_tx.clone(),
332            state_rx: self.state_rx.clone(),
333            event_tx: self.event_tx.clone(),
334            progress_rx: self.progress_rx.clone(),
335            cancel: self.cancel.clone(),
336        }
337    }
338}
339/// actor 的后台端。
340///
341/// 由 [`Actor::channel`] 创建,通常由后台任务持有。
342/// 用于接收命令、更新状态/进度、广播事件。
343pub struct ActorContext<A: Actor> {
344    cmd_rx: mpsc::Receiver<A::Cmd>,
345    state_tx: watch::Sender<A::State>,
346    event_tx: broadcast::Sender<A::Event>,
347    progress_tx: watch::Sender<A::Progress>,
348    cancel: CancelToken,
349}
350impl<A: Actor> ActorContext<A> {
351    /// 获取额外的事件发送端。
352    pub fn get_events_clone(&self) -> broadcast::Sender<A::Event> {
353        self.event_tx.clone()
354    }
355    /// 发送事件。
356    pub fn send_event(&self, event: A::Event) {
357        let _ = self.event_tx.send(event);
358    }
359    /// 更新状态。
360    pub fn update_state(&self, state: A::State) {
361        let _ = self.state_tx.send(state);
362    }
363    /// 更新进度。
364    pub fn update_progress(&self, progress: A::Progress) {
365        let _ = self.progress_tx.send(progress);
366    }
367    /// 阻塞等待命令。
368    pub fn wait_for_cmd(&mut self) -> impl Future<Output = Option<A::Cmd>> {
369        self.cmd_rx.recv()
370    }
371    /// 非阻塞检查命令。
372    pub fn check_cmd(&mut self) -> Option<A::Cmd> {
373        self.cmd_rx.try_recv().ok()
374    }
375
376    pub fn cancel_clone(&self) -> CancelToken {
377        self.cancel.clone()
378    }
379}
380/// 取消信号。
381///
382/// 可在多个任务间 clone 共享。任意一份调用 [`CancelToken::cancel`],
383/// 所有通过 [`CancelToken::cancelled`] 等待的任务都会收到通知。
384/// `cancel` 是幂等的。
385/// ...
386/// # 注意
387///
388/// `CancelToken` 是 `Clone` 的,clone 出来的所有副本共享同一个取消信号。
389/// 任意一份 `cancel()` 都会让所有副本的 `cancelled()` 返回。
390#[derive(Clone, Debug)]
391pub struct CancelToken {
392    cancelled: Arc<AtomicBool>,
393    notify: Arc<Notify>,
394}
395
396impl CancelToken {
397    pub fn new() -> Self {
398        Self {
399            cancelled: Arc::new(AtomicBool::new(false)),
400            notify: Arc::new(Notify::new()),
401        }
402    }
403    /// 检查取消信号。
404    pub fn is_cancelled(&self) -> bool {
405        self.cancelled.load(Ordering::Acquire)
406    }
407    /// 等待取消信号。
408    pub async fn cancelled(&self) {
409        if self.is_cancelled() {
410            return;
411        }
412        let notified = self.notify.notified();
413        if self.is_cancelled() {
414            return;
415        }
416        notified.await;
417    }
418    /// 发送取消信号。
419    pub fn cancel(&self) {
420        if !self.cancelled.swap(true, Ordering::AcqRel) {
421            self.notify.notify_waiters();
422        }
423    }
424}