actor_lite/core.rs
1use core::fmt;
2use tokio::sync::{broadcast, mpsc, watch};
3use tracing::warn;
4
5use crate::wait::{self, SharedWaker};
6/// Actor 的**数据面** trait。
7///
8/// `ActorCore` 只定义 actor「有什么」,不定义「怎么跑」。每个 actor 有四个关联类型:
9///
10/// | 类型 | 说明 |
11/// |------|------|
12/// | [`Cmd`](ActorCore::Cmd) | 命令枚举,外部通过它向 actor 发送指令 |
13/// | [`Event`](ActorCore::Event) | 事件类型,actor 对外广播的异步消息 |
14/// | [`State`](ActorCore::State) | 低频状态,变化不频繁,可随时读取最新值 |
15/// | [`Progress`](ActorCore::Progress) | 高频进度,适合进度条、实时指标等场景 |
16///
17/// 实现之后,[`ActorCore::channel`] 会给你两端:[`ActorContext`](后台端,收命令、更新状态、
18/// 广播事件)和 [`ActorHandle`](控制端,发命令、读状态、订阅事件)。
19///
20/// # 怎么跑
21///
22/// 「怎么跑」由壳 trait 决定,`ActorCore` 自己不关心:
23///
24/// - [`AsyncActor`](crate::AsyncActor):`run` 返回一个 future,[`AsyncActor::spawn`](crate::AsyncActor::spawn) 用 `tokio::spawn` 起任务;
25/// - 也可以完全不用壳:自己调用 [`ActorCore::channel`],再把 [`ActorContext`] 交给任意
26/// runtime 或线程驱动 —— 本 crate 不规定 actor 怎么运行。
27///
28/// # 生命周期
29///
30/// 1. 启动 actor(如 [`AsyncActor::spawn`](crate::AsyncActor::spawn)),得到 [`ActorHandle`]
31/// 2. 通过 [`ActorHandle`] 发送命令、读取状态/进度、订阅事件
32/// 3. 调用 [`ActorHandle::stop`] 显式停止;所有 handle 都被 drop 后命令通道关闭,
33/// `run` 里的等待会返回 `None`,actor 自然退出
34///
35/// # 与其他 trait 的关系
36///
37/// 0.1.0 起原 `Actor` 拆成两层:关联类型与初始化留在 `ActorCore`,
38/// `run`/`spawn` 移到壳 trait([`AsyncActor`](crate::AsyncActor))。因此定义一个 actor 需要两段 `impl`。
39///
40/// # 示例
41///
42/// ```no_run
43/// # use actor_lite::{ActorCore, AsyncActor, ActorContext};
44/// struct Counter {
45/// target: u32,
46/// }
47///
48/// enum CounterCmd {
49/// Reset,
50/// }
51///
52/// impl ActorCore for Counter {
53/// type Cmd = CounterCmd;
54/// type Event = u32;
55/// type State = u32;
56/// type Progress = f32;
57///
58/// fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
59/// (0, 0.0)
60/// }
61///
62/// }
63/// impl AsyncActor for Counter {
64/// fn run(self, context: ActorContext<Self>) -> impl std::future::Future<Output = ()> + Send + 'static {
65/// let mut context = context;
66/// async move {
67/// let mut count = 0u32;
68/// loop {
69/// if let Some(cmd) = context.check_cmd() {
70/// match cmd {
71/// CounterCmd::Reset => {
72/// count = 0;
73/// context.update_state(count);
74/// context.update_progress(0.0);
75/// }
76/// }
77/// }
78/// if count >= self.target {
79/// break;
80/// }
81/// count += 1;
82/// context.update_state(count);
83/// context.update_progress(count as f32 / self.target as f32);
84/// context.send_event(count);
85/// }
86/// }
87/// }
88/// }
89/// ```
90pub trait ActorCore: Sized {
91 /// actor 命令枚举
92 ///
93 /// 例如:
94 /// ```
95 /// enum MyCmd {
96 /// Start,
97 /// Pause,
98 /// //...
99 /// }
100 /// ```
101 type Cmd: Send + 'static;
102 /// actor 里的事件结构体,需要实现`Clone`
103 type Event: Clone + Send + 'static;
104 /// actor 里的低频状态,如果不需要,用 `type State = ();`。
105 type State: Clone + Send + Sync + 'static;
106 /// actor 里的高频状态,如果没有高频进度时,用 `type Progress = ();`。
107 type Progress: Clone + Send + Sync + 'static;
108
109 /// actor 的事件通道容量
110 const EVENT_CAPACITY: usize = 32;
111 /// 创建 actor 的通道。
112 /// ActorContext 是 actor 的后台端,ActorHandle 是 actor 的控制端。
113 fn channel(
114 init_state: Self::State,
115 init_progress: Self::Progress,
116 ) -> (ActorContext<Self>, ActorHandle<Self>) {
117 let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
118 let (state_tx, state_rx) = watch::channel(init_state);
119 let (event_tx, _) = broadcast::channel(Self::EVENT_CAPACITY);
120 let (progress_tx, progress_rx) = watch::channel(init_progress);
121
122 let waker = SharedWaker::default();
123 let cancel = CancelToken::with_waker(waker.clone());
124 let context_cancel = cancel.clone();
125 let (alive_tx, alive_rx) = watch::channel(true);
126 let context = ActorContext {
127 cmd_rx,
128 event_tx: event_tx.clone(),
129 state_tx,
130 progress_tx,
131 cancel: context_cancel,
132 waker: waker.clone(),
133 _alive: Some(AliveGuard(alive_tx)),
134 };
135 let handle = ActorHandle {
136 cmd_tx,
137 event_tx,
138 state_rx,
139 progress_rx,
140 cancel,
141 waker,
142 alive_rx,
143 };
144 (context, handle)
145 }
146
147 fn init_state_and_progress(&self) -> (Self::State, Self::Progress);
148}
149
150/// actor 的控制端。
151///
152/// 由 [`ActorCore::channel`] 创建,通常由外部控制方持有。用于发送命令、读取状态/进度、
153/// 订阅事件,以及注册异步监听。
154///
155/// # 线程安全
156///
157/// `ActorHandle<A>` 的 `Send`/`Sync` 只取决于四个关联类型,**与 actor 本身是否 `Send` 无关**:
158/// 即使 `A` 是 `!Send`(比如握着 `Rc<...>` 资源的线程 actor),它照样可以放进 GUI props、
159/// 跨线程传递、塞进 `Arc`。
160///
161/// # 发送命令
162///
163/// [`send_cmd`](ActorHandle::send_cmd) 是**同步**的:不阻塞、不返回 future,唯一的失败原因是
164/// actor 已停止(或所有后台端已退出)。因此可以在 GUI 回调、`Drop`、同步宿主里直接调用。
165///
166/// # 示例
167///
168/// ```no_run
169/// # use actor_lite::{ActorCore, AsyncActor, ActorHandle, ActorContext};
170/// # struct MyActor;
171/// # impl ActorCore for MyActor {
172/// # type Cmd = ();
173/// # type Event = ();
174/// # type State = ();
175/// # type Progress = ();
176/// # fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
177/// # ((), ())
178/// # }
179/// # }
180/// # impl AsyncActor for MyActor {
181/// # fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
182/// # async {}
183/// # }
184/// # }
185/// # async fn example() {
186/// let (context, handle) = MyActor::channel( (), ());
187///
188/// handle.send_cmd(()).unwrap();
189/// let state = handle.get_state();
190///
191/// let listener = handle.state_listen_async(|s| async move { });
192/// listener.cancel();
193/// # }
194/// ```
195pub struct ActorHandle<A: ActorCore> {
196 cmd_tx: mpsc::UnboundedSender<A::Cmd>,
197 pub(crate) state_rx: watch::Receiver<A::State>,
198 pub(crate) event_tx: broadcast::Sender<A::Event>,
199 pub(crate) progress_rx: watch::Receiver<A::Progress>,
200 cancel: CancelToken,
201 pub(crate) waker: SharedWaker,
202 pub(crate) alive_rx: watch::Receiver<bool>,
203}
204
205impl<A: ActorCore> ActorHandle<A> {
206 /// 向 actor 发送一条命令。
207 ///
208 /// 同步、不阻塞(命令通道是无界的),不会阻塞调用线程。失败只会在 actor 已停止
209 /// ([`ActorHandle::stop`] 之后,或后台端已退出)时发生。
210 pub fn send_cmd(&self, cmd: A::Cmd) -> Result<(), SendCmdError> {
211 if self.cancel.is_cancelled() {
212 warn!("send cmd failed: actor stopped");
213 return Err(SendCmdError::Closed);
214 }
215 self.cmd_tx.send(cmd).map_err(|_| {
216 warn!("send cmd failed: channel closed");
217 SendCmdError::Stopped
218 })?;
219 self.waker.wake();
220 Ok(())
221 }
222 /// 获取 actor 的最新状态。
223 pub fn get_state(&self) -> A::State {
224 self.state_rx.borrow().to_owned()
225 }
226
227 /// 获取 actor 的最新进度。
228 ///
229 /// 进度通道是 `watch`:读者只会看到**最新值**,中间值可能被跳过。
230 /// 适合进度条、实时指标,不要拿它当消息队列用。
231 pub fn get_progress(&self) -> A::Progress {
232 self.progress_rx.borrow().to_owned()
233 }
234
235 /// 订阅事件流,返回一个 `broadcast` 接收端。
236 ///
237 /// 这是**同步**用法:在 GUI 帧循环里 `try_recv()` 即可,不需要 async runtime。
238 /// 落后太多时 `recv()` 会返回 `Lagged`,需要自行决定是跳过还是重试。
239 pub fn get_events_rx(&self) -> broadcast::Receiver<A::Event> {
240 self.event_tx.subscribe()
241 }
242
243 /// 请求 actor 停止。
244 ///
245 /// 只是发出取消信号([`CancelToken::cancel`]),**不会**强行中断 `run`:
246 /// 实现者需要在自己的循环里检查取消信号(如 `select!` 到 `cancel.cancelled()`,
247 /// 或每轮 `is_cancelled()`),否则 actor 会继续跑到 `run` 返回为止。
248 pub fn stop(&self) {
249 self.cancel.cancel();
250 }
251 /// actor 是否还活着。
252 ///
253 /// # `false` 的准确含义(0.1.1 起)
254 ///
255 /// **actor 已结束,并且它持有的资源已经析构完。**
256 ///
257 /// 线程壳下,`run(self, ctx)` 返回后 actor 自身还要 drop —— Vulkan 设备、解码器、
258 /// 字体库这类"释放起来要几十毫秒"的东西。本标志在**那之后**才变 `false`,
259 /// 因此用它判断"可以安全退出进程 / 可以安全复用这块资源"是成立的。
260 ///
261 /// 0.1.0 里它只表示"`run` 已返回",比资源释放早一个窗口:依赖它做退出判断的调用方
262 /// 会与后台线程的 `free()` 赛跑,偶发 glibc 堆损坏(`corrupted double-linked list` /
263 /// `corrupted size vs. prev_size`)→ SIGABRT。详见 CHANGELOG 的 0.1.1。
264 ///
265 /// 反方向不成立:`true` 不代表 actor 干得动活 —— 阻塞调用卡死时它仍然是 `true`。
266 pub fn is_alive(&self) -> bool {
267 *self.alive_rx.borrow()
268 }
269
270 /// 订阅"存活状态",actor 结束时变成 `false`。
271 ///
272 /// `false` 的含义与 [`is_alive`](ActorHandle::is_alive) 相同:**资源已释放完**,
273 /// 不只是 `run` 返回。
274 ///
275 /// 用来替代轮询 [`is_alive`](ActorHandle::is_alive):GUI 每帧
276 /// `has_changed()` 一次即可(`watch` 语义,中间变化可丢,只关心最终值)。
277 ///
278 /// 后台端 drop 后 sender 也随之消失,因此 `changed()` 可能返回 `Err`
279 /// —— 那同样意味着 actor 已经结束,按 `false` 处理即可。
280 pub fn alive_rx(&self) -> watch::Receiver<bool> {
281 self.alive_rx.clone()
282 }
283}
284impl<A: ActorCore> Clone for ActorHandle<A> {
285 fn clone(&self) -> Self {
286 Self {
287 cmd_tx: self.cmd_tx.clone(),
288 state_rx: self.state_rx.clone(),
289 event_tx: self.event_tx.clone(),
290 progress_rx: self.progress_rx.clone(),
291 cancel: self.cancel.clone(),
292 waker: self.waker.clone(),
293 alive_rx: self.alive_rx.clone(),
294 }
295 }
296}
297/// actor 的后台端。
298///
299/// 由 [`ActorCore::channel`] 创建,交给 `run` 持有。用于接收命令、更新状态/进度、广播事件。
300///
301/// # 同步 API
302///
303/// 这里的写入方法([`update_state`](ActorContext::update_state)、
304/// [`update_progress`](ActorContext::update_progress)、
305/// [`send_event`](ActorContext::send_event))和 [`check_cmd`](ActorContext::check_cmd)
306/// 都是同步的,不需要 runtime;只有 [`wait_for_cmd`](ActorContext::wait_for_cmd) 返回 future。
307///
308/// # 收命令
309///
310/// - [`check_cmd`](ActorContext::check_cmd):非阻塞 `try_recv`,适合"每轮循环顺带看一眼";
311/// - [`wait_for_cmd`](ActorContext::wait_for_cmd):`recv().await`,适合异步壳;
312/// - `recv_cmd_timeout` / `recv_cmd`:**阻塞**版本,只在 [`ThreadActor`](crate::ThreadActor)
313/// 的上下文里才有(见 `thread_actor` 模块)。
314///
315/// 命令通道关闭(所有 [`ActorHandle`] 都 drop 了)后两者分别返回 `None`,
316/// 实现者据此退出循环即可。
317pub struct ActorContext<A: ActorCore> {
318 pub(crate) cmd_rx: mpsc::UnboundedReceiver<A::Cmd>,
319 state_tx: watch::Sender<A::State>,
320 event_tx: broadcast::Sender<A::Event>,
321 progress_tx: watch::Sender<A::Progress>,
322 pub(crate) cancel: CancelToken,
323 pub(crate) waker: SharedWaker,
324 pub(crate) _alive: Option<AliveGuard>,
325}
326impl<A: ActorCore> ActorContext<A> {
327 /// 获取额外的事件发送端。
328 ///
329 /// 用于把事件发送端交给别的线程/任务(比如 IO 回调里直接发事件出队列)。
330 pub fn get_events_clone(&self) -> broadcast::Sender<A::Event> {
331 self.event_tx.clone()
332 }
333 /// 发送事件(同步,永不失败;没有订阅者时事件被丢弃)。
334 pub fn send_event(&self, event: A::Event) {
335 let _ = self.event_tx.send(event);
336 }
337 /// 更新状态。
338 ///
339 /// `watch` 语义:读者只会看到最新值,中间值可能被跳过。
340 /// 状态应是低频、可幂等覆盖的数据;高频数据用 [`update_progress`](ActorContext::update_progress)。
341 pub fn update_state(&self, state: A::State) {
342 self.state_tx.send_replace(state);
343 }
344 /// 更新进度。
345 ///
346 /// `watch` 语义:读者只会看到最新值,中间值可能被跳过 —— 对进度条是优点,
347 /// 但**不要**拿它当消息队列(每一帧都要的话走事件)。
348 pub fn update_progress(&self, progress: A::Progress) {
349 self.progress_tx.send_replace(progress);
350 }
351 /// 等待下一条命令(async)。
352 ///
353 /// 命令通道关闭时返回 `None`,可据此结束 `run`。
354 pub fn wait_for_cmd(&mut self) -> impl Future<Output = Option<A::Cmd>> {
355 self.cmd_rx.recv()
356 }
357 /// 非阻塞检查命令。
358 ///
359 /// 立即返回:有命令就 `Some`,没有或通道已关闭都是 `None`。
360 pub fn check_cmd(&mut self) -> Option<A::Cmd> {
361 self.cmd_rx.try_recv().ok()
362 }
363
364 /// 获取取消信号,用于在自己循环里检查/等待停止。
365 ///
366 /// 异步壳一般写 `select! { _ = cancel.cancelled() => break, ... }`。
367 pub fn cancel_clone(&self) -> CancelToken {
368 self.cancel.clone()
369 }
370 /// actor 是否已被要求停止。
371 pub fn is_cancelled(&self) -> bool {
372 self.cancel.is_cancelled()
373 }
374}
375/// 取消信号。
376///
377/// 可在多个任务/线程间 clone 共享,clone 出来的所有副本共享同一个取消状态:
378///
379/// - [`cancel`](CancelToken::cancel):同步、幂等、永不失败。即使当下没有等待者,
380/// 后来的 [`is_cancelled`](CancelToken::is_cancelled) 也会是 `true`;
381/// - [`is_cancelled`](CancelToken::is_cancelled):同步查询,适合轮询/每轮检查;
382/// - [`cancelled`](CancelToken::cancelled):async 等待,已经取消时立即返回。
383///
384/// 典型来源是 [`ActorHandle::stop`];[`ActorHandle`] 上的 `*_listen_async` 返回的也是它。
385#[derive(Clone, Debug)]
386pub struct CancelToken {
387 tx: watch::Sender<bool>,
388 waker: SharedWaker,
389}
390impl Default for CancelToken {
391 fn default() -> Self {
392 Self::new()
393 }
394}
395impl CancelToken {
396 /// 创建一个未取消的信号。
397 pub fn new() -> Self {
398 let tx = watch::channel(false).0;
399 let waker = SharedWaker::default();
400 Self { tx, waker }
401 }
402 pub(crate) fn with_waker(waker: SharedWaker) -> Self {
403 Self {
404 tx: watch::channel(false).0,
405 waker,
406 }
407 }
408 /// 检查取消信号。
409 pub fn is_cancelled(&self) -> bool {
410 *self.tx.borrow()
411 }
412 /// 等待取消信号;已经取消时立即返回。
413 pub async fn cancelled(&self) {
414 let mut rx = self.tx.subscribe();
415 // wait_for 会先拿当前值比一次,再等变化 → 不存在"通知丢失"的窗口
416 let _ = rx.wait_for(|cancelled| *cancelled).await;
417 }
418 /// 发送取消信号(幂等)。
419 ///
420 /// 唤醒所有正在 [`cancelled`](CancelToken::cancelled) 上等待的任务;
421 /// 信号不会"过期",之后再调用 `cancelled()` 也会立即返回。
422 pub fn cancel(&self) {
423 self.tx.send_replace(true);
424 self.waker.wake();
425 }
426 /// 阻塞等待取消(线程 actor 用;异步壳请用 `cancelled()`)。
427 pub fn cancelled_blocking(&self) {
428 if self.is_cancelled() {
429 return;
430 }
431 let waker = self.waker.waker();
432 let _ = wait::drive_until(self.cancelled(), None, &waker);
433 }
434}
435#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
436#[non_exhaustive]
437pub enum SendCmdError {
438 /// 已经调用过 [`ActorHandle::stop`],actor 不再接受新命令。
439 Stopped,
440 /// 后台端已结束:`run` 返回、panic,或所有 [`ActorContext`] 都已 drop。
441 Closed,
442}
443
444impl fmt::Display for SendCmdError {
445 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446 f.write_str(match self {
447 Self::Stopped => "actor has been stopped",
448 Self::Closed => "actor is closed",
449 })
450 }
451}
452
453impl std::error::Error for SendCmdError {}
454/// 把存活状态置 `false` 的守卫。
455///
456/// **谁持有它,决定了 `is_alive()` 的语义**,所以不要随手塞回 [`ActorContext`]:
457/// 线程壳用 [`ActorContext::take_alive_guard`] 把它取出来,由线程闭包持有,
458/// 在 `actor.run(ctx)` 消费掉 actor、其字段析构完之后**最后**才 drop ——
459/// 这样 `is_alive() == false` 才等于"线程已结束且资源已释放"。
460///
461/// 若留在 [`ActorContext`] 里,它会在 `run(self, ctx)` 返回时就 drop,
462/// 比 actor 字段的析构早一个窗口(0.1.0 的 bug,见 CHANGELOG)。
463pub(crate) struct AliveGuard(watch::Sender<bool>);
464impl Drop for AliveGuard {
465 fn drop(&mut self) {
466 self.0.send_replace(false);
467 }
468}