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/// 两种读法,按需选:
169///
170/// - [`get_state`](ActorHandle::get_state) / [`get_progress`](ActorHandle::get_progress):
171/// 同步取一份最新快照,适合偶尔读一次;
172/// - [`state_rx`](ActorHandle::state_rx) / [`progress_rx`](ActorHandle::progress_rx):
173/// 拿 `watch::Receiver` 自己驱动(每帧 `has_changed()`,或 `changed().await`),适合接 GUI 帧循环。
174///
175/// 两者都不需要 runtime;需要回调式的(`op(value).await`)才用 `*_listen_async`,
176/// 那个内部 `tokio::spawn`,要求调用线程有 tokio runtime。
177///
178/// # 示例
179///
180/// ```no_run
181/// # use actor_lite::{ActorCore, AsyncActor, ActorHandle, ActorContext};
182/// # struct MyActor;
183/// # impl ActorCore for MyActor {
184/// # type Cmd = ();
185/// # type Event = ();
186/// # type State = ();
187/// # type Progress = ();
188/// # fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
189/// # ((), ())
190/// # }
191/// # }
192/// # impl AsyncActor for MyActor {
193/// # fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
194/// # async {}
195/// # }
196/// # }
197/// # async fn example() {
198/// let (context, handle) = MyActor::channel( (), ());
199///
200/// handle.send_cmd(()).unwrap();
201/// let state = handle.get_state();
202///
203/// let listener = handle.state_listen_async(|s| async move { });
204/// listener.cancel();
205/// # }
206/// ```
207pub struct ActorHandle<A: ActorCore> {
208 cmd_tx: mpsc::UnboundedSender<A::Cmd>,
209 pub(crate) state_rx: watch::Receiver<A::State>,
210 pub(crate) event_tx: broadcast::Sender<A::Event>,
211 pub(crate) progress_rx: watch::Receiver<A::Progress>,
212 cancel: CancelToken,
213 pub(crate) waker: SharedWaker,
214 pub(crate) alive_rx: watch::Receiver<bool>,
215}
216
217impl<A: ActorCore> ActorHandle<A> {
218 /// 向 actor 发送一条命令。
219 ///
220 /// 同步、不阻塞(命令通道是无界的),不会阻塞调用线程。失败只会在 actor 已停止
221 /// ([`ActorHandle::stop`] 之后,或后台端已退出)时发生。
222 pub fn send_cmd(&self, cmd: A::Cmd) -> Result<(), SendCmdError> {
223 if self.cancel.is_cancelled() {
224 warn!("send cmd failed: actor stopped");
225 return Err(SendCmdError::Closed);
226 }
227 self.cmd_tx.send(cmd).map_err(|_| {
228 warn!("send cmd failed: channel closed");
229 SendCmdError::Stopped
230 })?;
231 self.waker.wake();
232 Ok(())
233 }
234 /// 获取 actor 的最新状态(同步快照)。
235 ///
236 /// 每次调用都拷贝一份 `watch` 的当前值,不阻塞、不需要 runtime。
237 /// 适合"偶尔读一次";想"变了就叫我"而不是轮询,用
238 /// [`state_rx`](ActorHandle::state_rx) 拿接收端自己驱动。
239 pub fn get_state(&self) -> A::State {
240 self.state_rx.borrow().to_owned()
241 }
242
243 /// 获取 actor 的最新进度(同步快照)。
244 ///
245 /// 进度通道是 `watch`:读者只会看到**最新值**,中间值可能被跳过。
246 /// 适合进度条、实时指标,不要拿它当消息队列用。
247 /// 想订阅变化而非每次拉快照,用 [`progress_rx`](ActorHandle::progress_rx)。
248 pub fn get_progress(&self) -> A::Progress {
249 self.progress_rx.borrow().to_owned()
250 }
251
252 /// 订阅事件流,返回一个 `broadcast` 接收端。
253 ///
254 /// 这是**同步**用法:在 GUI 帧循环里 `try_recv()` 即可,不需要 async runtime。
255 /// 落后太多时 `recv()` 会返回 `Lagged`,需要自行决定是跳过还是重试。
256 pub fn get_events_rx(&self) -> broadcast::Receiver<A::Event> {
257 self.event_tx.subscribe()
258 }
259
260 /// 请求 actor 停止。
261 ///
262 /// 只是发出取消信号([`CancelToken::cancel`]),**不会**强行中断 `run`:
263 /// 实现者需要在自己的循环里检查取消信号(如 `select!` 到 `cancel.cancelled()`,
264 /// 或每轮 `is_cancelled()`),否则 actor 会继续跑到 `run` 返回为止。
265 pub fn stop(&self) {
266 self.cancel.cancel();
267 }
268 /// actor 是否还活着。
269 ///
270 /// # `false` 的准确含义(0.1.1 起)
271 ///
272 /// **actor 已结束,并且它持有的资源已经析构完。**
273 ///
274 /// 线程壳下,`run(self, ctx)` 返回后 actor 自身还要 drop —— Vulkan 设备、解码器、
275 /// 字体库这类"释放起来要几十毫秒"的东西。本标志在**那之后**才变 `false`,
276 /// 因此用它判断"可以安全退出进程 / 可以安全复用这块资源"是成立的。
277 ///
278 /// 0.1.0 里它只表示"`run` 已返回",比资源释放早一个窗口:依赖它做退出判断的调用方
279 /// 会与后台线程的 `free()` 赛跑,偶发 glibc 堆损坏(`corrupted double-linked list` /
280 /// `corrupted size vs. prev_size`)→ SIGABRT。详见 CHANGELOG 的 0.1.1。
281 ///
282 /// 反方向不成立:`true` 不代表 actor 干得动活 —— 阻塞调用卡死时它仍然是 `true`。
283 pub fn is_alive(&self) -> bool {
284 *self.alive_rx.borrow()
285 }
286
287 /// 订阅"存活状态",actor 结束时变成 `false`。
288 ///
289 /// `false` 的含义与 [`is_alive`](ActorHandle::is_alive) 相同:**资源已释放完**,
290 /// 不只是 `run` 返回。
291 ///
292 /// 用来替代轮询 [`is_alive`](ActorHandle::is_alive):GUI 每帧
293 /// `has_changed()` 一次即可(`watch` 语义,中间变化可丢,只关心最终值)。
294 ///
295 /// 后台端 drop 后 sender 也随之消失,因此 `changed()` 可能返回 `Err`
296 /// —— 那同样意味着 actor 已经结束,按 `false` 处理即可。
297 pub fn alive_rx(&self) -> watch::Receiver<bool> {
298 self.alive_rx.clone()
299 }
300
301 /// 订阅状态变化,返回一个 `watch::Receiver`。
302 ///
303 /// 与 [`get_state`](ActorHandle::get_state) 是一对:那个每次拉一份最新快照,
304 /// 这个给你一个能"等下一次变化"的接收端。用途是**自己驱动**的更新循环:
305 ///
306 /// - 同步宿主(GUI 帧循环、GTK/iOS 主线程等):每帧 `has_changed()` 一次;
307 /// - 异步:在 `select!` 里 `rx.changed().await`。本方法只是 `watch` 通道的接收端,
308 /// **不需要 tokio runtime**,也不会自己 `spawn` 任务。
309 ///
310 /// ```no_run
311 /// # use actor_lite::{ActorCore, ActorHandle};
312 /// # struct MyActor;
313 /// # impl ActorCore for MyActor {
314 /// # type Cmd = ();
315 /// # type Event = ();
316 /// # type State = u32;
317 /// # type Progress = ();
318 /// # fn init_state_and_progress(&self) -> (u32, ()) {
319 /// # (0, ())
320 /// # }
321 /// # }
322 /// # fn gui_frame(handle: &ActorHandle<MyActor>) {
323 /// let mut states = handle.state_rx();
324 ///
325 /// // 每帧调一次:有变化就取新值重绘(没有就什么也不做)
326 /// if states.has_changed().unwrap_or(false) {
327 /// let state: u32 = states.borrow_and_update().clone();
328 /// # let _ = state;
329 /// // draw(state);
330 /// }
331 /// # }
332 /// ```
333 ///
334 /// # 语义(`watch`)
335 ///
336 /// 只保留**最新值**,中间值可能被跳过:actor 连续更新多次而读者没跟上,只看到最后那次。
337 /// 要一条不漏地收消息,请用 [`get_events_rx`](ActorHandle::get_events_rx)(`broadcast`),
338 /// 别把状态当事件流用。
339 ///
340 /// # 第一次 `changed()` 可能立刻返回
341 ///
342 /// 每次调用都 clone 出一个**独立**的接收端(各自维护"已读"位置,多个读者互不影响),
343 /// 而 clone 带过来的是 handle 内部的已读位置。因此如果 actor 在
344 /// [`channel`](ActorCore::channel) 之后已经更新过状态,新接收端的 `has_changed()` /
345 /// `changed()` 会**立刻**就绪 —— 那读到的是**当前值**,不是"刚刚又变了一次"。
346 ///
347 /// 所以正确顺序是:先用 `borrow()` / `borrow_and_update()` 取初始值,再等 `changed()`
348 /// 拿增量;别把第一次 `changed()` 当成一次独立的变化通知。
349 ///
350 /// # actor 结束后
351 ///
352 /// 后台端 drop 后 sender 随之消失:`changed()` 返回 `Err`,`has_changed()` 返回
353 /// `Err(RecvError)`,此时 `borrow()` 仍能读到**最后一个值**。
354 /// 处理方式与 [`alive_rx`](ActorHandle::alive_rx) 相同 —— `Err` 就是"actor 已经结束",
355 /// 不必当成致命错误。
356 ///
357 /// # 与 `state_listen_async` 的区别
358 ///
359 /// `state_listen_async` 是回调式(每次变化 `op(state).await`),内部 `tokio::spawn`,
360 /// 要求调用线程有 runtime;本方法只交出接收端,由调用方决定在哪读、多久读一次。
361 /// 同步宿主或已经有自己的循环时,用这个更省事,也更好控制背压。
362 pub fn state_rx(&self) -> watch::Receiver<A::State> {
363 self.state_rx.clone()
364 }
365
366 /// 订阅进度变化,返回一个 `watch::Receiver`。
367 ///
368 /// 与 [`get_progress`](ActorHandle::get_progress) 是一对:那个是"现在多少",这个能
369 /// "等下一次进度变化"。典型用法是进度条 / 实时指标:同步宿主每帧 `has_changed()`
370 /// 后重绘,异步里 `select!` 到 `rx.changed()`。不需要 tokio runtime,也不自己起任务。
371 ///
372 /// # 语义(`watch`,比状态更需要小心)
373 ///
374 /// 进度是**高频、可丢**的:actor 在一帧里推进了 100 次,读者只看到最后那次。
375 /// 这正适合进度条(画面本来就只能显示最新值),但如果你要的是"每个中间值都要处理"
376 /// (逐条日志、逐笔成交),那是 [`get_events_rx`](ActorHandle::get_events_rx) 的场景。
377 ///
378 /// 与 [`state_rx`](ActorHandle::state_rx) 一样,clone 出来的接收端第一次 `changed()`
379 /// 可能立刻就绪(读到的是当前值),所以先 `borrow()` 拿初值再等 `changed()`。
380 /// actor 结束后 `changed()` 返回 `Err`,`borrow()` 仍能读到最后一个进度值。
381 ///
382 /// # 示例
383 ///
384 /// ```no_run
385 /// # use actor_lite::{ActorCore, ActorHandle};
386 /// # struct Player;
387 /// # impl ActorCore for Player {
388 /// # type Cmd = ();
389 /// # type Event = ();
390 /// # type State = ();
391 /// # type Progress = f32;
392 /// # fn init_state_and_progress(&self) -> ((), f32) {
393 /// # ((), 0.0)
394 /// # }
395 /// # }
396 /// # fn gui_frame(handle: &ActorHandle<Player>) {
397 /// let mut progress = handle.progress_rx();
398 ///
399 /// if progress.has_changed().unwrap_or(false) {
400 /// let pct: f32 = *progress.borrow_and_update();
401 /// # let _ = pct;
402 /// // set_progress_bar(pct);
403 /// }
404 /// # }
405 /// ```
406 pub fn progress_rx(&self) -> watch::Receiver<A::Progress> {
407 self.progress_rx.clone()
408 }
409}
410impl<A: ActorCore> Clone for ActorHandle<A> {
411 fn clone(&self) -> Self {
412 Self {
413 cmd_tx: self.cmd_tx.clone(),
414 state_rx: self.state_rx.clone(),
415 event_tx: self.event_tx.clone(),
416 progress_rx: self.progress_rx.clone(),
417 cancel: self.cancel.clone(),
418 waker: self.waker.clone(),
419 alive_rx: self.alive_rx.clone(),
420 }
421 }
422}
423/// actor 的后台端。
424///
425/// 由 [`ActorCore::channel`] 创建,交给 `run` 持有。用于接收命令、更新状态/进度、广播事件。
426///
427/// # 同步 API
428///
429/// 这里的写入方法([`update_state`](ActorContext::update_state)、
430/// [`update_progress`](ActorContext::update_progress)、
431/// [`send_event`](ActorContext::send_event))和 [`check_cmd`](ActorContext::check_cmd)
432/// 都是同步的,不需要 runtime;只有 [`wait_for_cmd`](ActorContext::wait_for_cmd) 返回 future。
433///
434/// # 收命令
435///
436/// - [`check_cmd`](ActorContext::check_cmd):非阻塞 `try_recv`,适合"每轮循环顺带看一眼";
437/// - [`wait_for_cmd`](ActorContext::wait_for_cmd):`recv().await`,适合异步壳;
438/// - `recv_cmd_timeout` / `recv_cmd`:**阻塞**版本,只在 [`ThreadActor`](crate::ThreadActor)
439/// 的上下文里才有(见 `thread_actor` 模块)。
440///
441/// 命令通道关闭(所有 [`ActorHandle`] 都 drop 了)后两者分别返回 `None`,
442/// 实现者据此退出循环即可。
443pub struct ActorContext<A: ActorCore> {
444 pub(crate) cmd_rx: mpsc::UnboundedReceiver<A::Cmd>,
445 state_tx: watch::Sender<A::State>,
446 event_tx: broadcast::Sender<A::Event>,
447 progress_tx: watch::Sender<A::Progress>,
448 pub(crate) cancel: CancelToken,
449 pub(crate) waker: SharedWaker,
450 pub(crate) _alive: Option<AliveGuard>,
451}
452impl<A: ActorCore> ActorContext<A> {
453 /// 获取额外的事件发送端。
454 ///
455 /// 用于把事件发送端交给别的线程/任务(比如 IO 回调里直接发事件出队列)。
456 pub fn get_events_clone(&self) -> broadcast::Sender<A::Event> {
457 self.event_tx.clone()
458 }
459 /// 发送事件(同步,永不失败;没有订阅者时事件被丢弃)。
460 pub fn send_event(&self, event: A::Event) {
461 let _ = self.event_tx.send(event);
462 }
463 /// 更新状态。
464 ///
465 /// `watch` 语义:读者只会看到最新值,中间值可能被跳过。
466 /// 状态应是低频、可幂等覆盖的数据;高频数据用 [`update_progress`](ActorContext::update_progress)。
467 pub fn update_state(&self, state: A::State) {
468 self.state_tx.send_replace(state);
469 }
470 /// 更新进度。
471 ///
472 /// `watch` 语义:读者只会看到最新值,中间值可能被跳过 —— 对进度条是优点,
473 /// 但**不要**拿它当消息队列(每一帧都要的话走事件)。
474 pub fn update_progress(&self, progress: A::Progress) {
475 self.progress_tx.send_replace(progress);
476 }
477 /// 等待下一条命令(async)。
478 ///
479 /// 命令通道关闭时返回 `None`,可据此结束 `run`。
480 pub fn wait_for_cmd(&mut self) -> impl Future<Output = Option<A::Cmd>> {
481 self.cmd_rx.recv()
482 }
483 /// 非阻塞检查命令。
484 ///
485 /// 立即返回:有命令就 `Some`,没有或通道已关闭都是 `None`。
486 pub fn check_cmd(&mut self) -> Option<A::Cmd> {
487 self.cmd_rx.try_recv().ok()
488 }
489
490 /// 获取取消信号,用于在自己循环里检查/等待停止。
491 ///
492 /// 异步壳一般写 `select! { _ = cancel.cancelled() => break, ... }`。
493 pub fn cancel_clone(&self) -> CancelToken {
494 self.cancel.clone()
495 }
496 /// actor 是否已被要求停止。
497 pub fn is_cancelled(&self) -> bool {
498 self.cancel.is_cancelled()
499 }
500}
501/// 取消信号。
502///
503/// 可在多个任务/线程间 clone 共享,clone 出来的所有副本共享同一个取消状态:
504///
505/// - [`cancel`](CancelToken::cancel):同步、幂等、永不失败。即使当下没有等待者,
506/// 后来的 [`is_cancelled`](CancelToken::is_cancelled) 也会是 `true`;
507/// - [`is_cancelled`](CancelToken::is_cancelled):同步查询,适合轮询/每轮检查;
508/// - [`cancelled`](CancelToken::cancelled):async 等待,已经取消时立即返回。
509///
510/// 典型来源是 [`ActorHandle::stop`];[`ActorHandle`] 上的 `*_listen_async` 返回的也是它。
511#[derive(Clone, Debug)]
512pub struct CancelToken {
513 tx: watch::Sender<bool>,
514 waker: SharedWaker,
515}
516impl Default for CancelToken {
517 fn default() -> Self {
518 Self::new()
519 }
520}
521impl CancelToken {
522 /// 创建一个未取消的信号。
523 pub fn new() -> Self {
524 let tx = watch::channel(false).0;
525 let waker = SharedWaker::default();
526 Self { tx, waker }
527 }
528 pub(crate) fn with_waker(waker: SharedWaker) -> Self {
529 Self {
530 tx: watch::channel(false).0,
531 waker,
532 }
533 }
534 /// 检查取消信号。
535 pub fn is_cancelled(&self) -> bool {
536 *self.tx.borrow()
537 }
538 /// 等待取消信号;已经取消时立即返回。
539 pub async fn cancelled(&self) {
540 let mut rx = self.tx.subscribe();
541 // wait_for 会先拿当前值比一次,再等变化 → 不存在"通知丢失"的窗口
542 let _ = rx.wait_for(|cancelled| *cancelled).await;
543 }
544 /// 发送取消信号(幂等)。
545 ///
546 /// 唤醒所有正在 [`cancelled`](CancelToken::cancelled) 上等待的任务;
547 /// 信号不会"过期",之后再调用 `cancelled()` 也会立即返回。
548 pub fn cancel(&self) {
549 self.tx.send_replace(true);
550 self.waker.wake();
551 }
552 /// 阻塞等待取消(线程 actor 用;异步壳请用 `cancelled()`)。
553 pub fn cancelled_blocking(&self) {
554 if self.is_cancelled() {
555 return;
556 }
557 let waker = self.waker.waker();
558 let _ = wait::drive_until(self.cancelled(), None, &waker);
559 }
560}
561#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
562#[non_exhaustive]
563pub enum SendCmdError {
564 /// 已经调用过 [`ActorHandle::stop`],actor 不再接受新命令。
565 Stopped,
566 /// 后台端已结束:`run` 返回、panic,或所有 [`ActorContext`] 都已 drop。
567 Closed,
568}
569
570impl fmt::Display for SendCmdError {
571 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
572 f.write_str(match self {
573 Self::Stopped => "actor has been stopped",
574 Self::Closed => "actor is closed",
575 })
576 }
577}
578
579impl std::error::Error for SendCmdError {}
580/// 把存活状态置 `false` 的守卫。
581///
582/// **谁持有它,决定了 `is_alive()` 的语义**,所以不要随手塞回 [`ActorContext`]:
583/// 线程壳用 [`ActorContext::take_alive_guard`] 把它取出来,由线程闭包持有,
584/// 在 `actor.run(ctx)` 消费掉 actor、其字段析构完之后**最后**才 drop ——
585/// 这样 `is_alive() == false` 才等于"线程已结束且资源已释放"。
586///
587/// 若留在 [`ActorContext`] 里,它会在 `run(self, ctx)` 返回时就 drop,
588/// 比 actor 字段的析构早一个窗口(0.1.0 的 bug,见 CHANGELOG)。
589pub(crate) struct AliveGuard(watch::Sender<bool>);
590impl Drop for AliveGuard {
591 fn drop(&mut self) {
592 self.0.send_replace(false);
593 }
594}