actor-lite 0.1.2

基于 tokio 的轻量 actor 抽象:一份核(命令通道 + 状态/进度 + 事件 + 取消)+ 异步壳(tokio::spawn)与线程壳(独占线程,可装 !Send 资源)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
use core::fmt;
use tokio::sync::{broadcast, mpsc, watch};
use tracing::warn;

use crate::wait::{self, SharedWaker};
/// Actor 的**数据面** trait。
///
/// `ActorCore` 只定义 actor「有什么」,不定义「怎么跑」。每个 actor 有四个关联类型:
///
/// | 类型 | 说明 |
/// |------|------|
/// | [`Cmd`](ActorCore::Cmd) | 命令枚举,外部通过它向 actor 发送指令 |
/// | [`Event`](ActorCore::Event) | 事件类型,actor 对外广播的异步消息 |
/// | [`State`](ActorCore::State) | 低频状态,变化不频繁,可随时读取最新值 |
/// | [`Progress`](ActorCore::Progress) | 高频进度,适合进度条、实时指标等场景 |
///
/// 实现之后,[`ActorCore::channel`] 会给你两端:[`ActorContext`](后台端,收命令、更新状态、
/// 广播事件)和 [`ActorHandle`](控制端,发命令、读状态、订阅事件)。
///
/// # 怎么跑
///
/// 「怎么跑」由壳 trait 决定,`ActorCore` 自己不关心:
///
/// - [`AsyncActor`](crate::AsyncActor):`run` 返回一个 future,[`AsyncActor::spawn`](crate::AsyncActor::spawn) 用 `tokio::spawn` 起任务;
/// - 也可以完全不用壳:自己调用 [`ActorCore::channel`],再把 [`ActorContext`] 交给任意
///   runtime 或线程驱动 —— 本 crate 不规定 actor 怎么运行。
///
/// # 生命周期
///
/// 1. 启动 actor(如 [`AsyncActor::spawn`](crate::AsyncActor::spawn)),得到 [`ActorHandle`]
/// 2. 通过 [`ActorHandle`] 发送命令、读取状态/进度、订阅事件
/// 3. 调用 [`ActorHandle::stop`] 显式停止;所有 handle 都被 drop 后命令通道关闭,
///    `run` 里的等待会返回 `None`,actor 自然退出
///
/// # 与其他 trait 的关系
///
/// 0.1.0 起原 `Actor` 拆成两层:关联类型与初始化留在 `ActorCore`,
/// `run`/`spawn` 移到壳 trait([`AsyncActor`](crate::AsyncActor))。因此定义一个 actor 需要两段 `impl`。
///
/// # 示例
///
/// ```no_run
/// # use actor_lite::{ActorCore, AsyncActor, ActorContext};
/// struct Counter {
///     target: u32,
/// }
///
/// enum CounterCmd {
///     Reset,
/// }
///
/// impl ActorCore for Counter {
///     type Cmd = CounterCmd;
///     type Event = u32;
///     type State = u32;
///     type Progress = f32;
///
///     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
///         (0, 0.0)
///     }
///
/// }
/// impl AsyncActor for Counter {
///     fn run(self, context: ActorContext<Self>) -> impl std::future::Future<Output = ()> + Send + 'static {
///         let mut context = context;
///         async move {
///             let mut count = 0u32;
///             loop {
///                 if let Some(cmd) = context.check_cmd() {
///                     match cmd {
///                         CounterCmd::Reset => {
///                             count = 0;
///                             context.update_state(count);
///                             context.update_progress(0.0);
///                         }
///                     }
///                 }
///                 if count >= self.target {
///                     break;
///                 }
///                 count += 1;
///                 context.update_state(count);
///                 context.update_progress(count as f32 / self.target as f32);
///                 context.send_event(count);
///             }
///         }
///     }
/// }
/// ```
pub trait ActorCore: Sized {
    /// actor 命令枚举
    ///
    /// 例如:
    /// ```
    /// enum MyCmd {
    ///     Start,
    ///     Pause,
    ///     //...
    /// }
    /// ```
    type Cmd: Send + 'static;
    /// actor 里的事件结构体,需要实现`Clone`
    type Event: Clone + Send + 'static;
    /// actor 里的低频状态,如果不需要,用 `type State = ();`。
    type State: Clone + Send + Sync + 'static;
    /// actor 里的高频状态,如果没有高频进度时,用 `type Progress = ();`。
    type Progress: Clone + Send + Sync + 'static;

    /// actor 的事件通道容量
    const EVENT_CAPACITY: usize = 32;
    /// 创建 actor 的通道。
    /// ActorContext 是 actor 的后台端,ActorHandle 是 actor 的控制端。
    fn channel(
        init_state: Self::State,
        init_progress: Self::Progress,
    ) -> (ActorContext<Self>, ActorHandle<Self>) {
        let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
        let (state_tx, state_rx) = watch::channel(init_state);
        let (event_tx, _) = broadcast::channel(Self::EVENT_CAPACITY);
        let (progress_tx, progress_rx) = watch::channel(init_progress);

        let waker = SharedWaker::default();
        let cancel = CancelToken::with_waker(waker.clone());
        let context_cancel = cancel.clone();
        let (alive_tx, alive_rx) = watch::channel(true);
        let context = ActorContext {
            cmd_rx,
            event_tx: event_tx.clone(),
            state_tx,
            progress_tx,
            cancel: context_cancel,
            waker: waker.clone(),
            _alive: Some(AliveGuard(alive_tx)),
        };
        let handle = ActorHandle {
            cmd_tx,
            event_tx,
            state_rx,
            progress_rx,
            cancel,
            waker,
            alive_rx,
        };
        (context, handle)
    }

    fn init_state_and_progress(&self) -> (Self::State, Self::Progress);
}

/// actor 的控制端。
///
/// 由 [`ActorCore::channel`] 创建,通常由外部控制方持有。用于发送命令、读取状态/进度、
/// 订阅事件,以及注册异步监听。
///
/// # 线程安全
///
/// `ActorHandle<A>` 的 `Send`/`Sync` 只取决于四个关联类型,**与 actor 本身是否 `Send` 无关**:
/// 即使 `A` 是 `!Send`(比如握着 `Rc<...>` 资源的线程 actor),它照样可以放进 GUI props、
/// 跨线程传递、塞进 `Arc`。
///
/// # 发送命令
///
/// [`send_cmd`](ActorHandle::send_cmd) 是**同步**的:不阻塞、不返回 future,唯一的失败原因是
/// actor 已停止(或所有后台端已退出)。因此可以在 GUI 回调、`Drop`、同步宿主里直接调用。
///
/// # 读状态 / 进度
///
/// 两种读法,按需选:
///
/// - [`get_state`](ActorHandle::get_state) / [`get_progress`](ActorHandle::get_progress):
///   同步取一份最新快照,适合偶尔读一次;
/// - [`state_rx`](ActorHandle::state_rx) / [`progress_rx`](ActorHandle::progress_rx):
///   拿 `watch::Receiver` 自己驱动(每帧 `has_changed()`,或 `changed().await`),适合接 GUI 帧循环。
///
/// 两者都不需要 runtime;需要回调式的(`op(value).await`)才用 `*_listen_async`,
/// 那个内部 `tokio::spawn`,要求调用线程有 tokio runtime。
///
/// # 示例
///
/// ```no_run
/// # use actor_lite::{ActorCore, AsyncActor, ActorHandle, ActorContext};
/// # struct MyActor;
/// # impl ActorCore for MyActor {
/// #    type Cmd = ();
/// #    type Event = ();
/// #    type State = ();
/// #    type Progress = ();
/// #    fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
/// #        ((), ())
/// #    }
/// # }
/// # impl AsyncActor for MyActor {
/// #    fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
/// #         async {}
/// #     }
/// # }
/// # async fn example() {
/// let (context, handle) = MyActor::channel( (), ());
///
/// handle.send_cmd(()).unwrap();
/// let state = handle.get_state();
///
/// let listener = handle.state_listen_async(|s| async move { });
/// listener.cancel();
/// # }
/// ```
pub struct ActorHandle<A: ActorCore> {
    cmd_tx: mpsc::UnboundedSender<A::Cmd>,
    pub(crate) state_rx: watch::Receiver<A::State>,
    pub(crate) event_tx: broadcast::Sender<A::Event>,
    pub(crate) progress_rx: watch::Receiver<A::Progress>,
    cancel: CancelToken,
    pub(crate) waker: SharedWaker,
    pub(crate) alive_rx: watch::Receiver<bool>,
}

impl<A: ActorCore> ActorHandle<A> {
    /// 向 actor 发送一条命令。
    ///
    /// 同步、不阻塞(命令通道是无界的),不会阻塞调用线程。失败只会在 actor 已停止
    /// ([`ActorHandle::stop`] 之后,或后台端已退出)时发生。
    pub fn send_cmd(&self, cmd: A::Cmd) -> Result<(), SendCmdError> {
        if self.cancel.is_cancelled() {
            warn!("send cmd failed: actor stopped");
            return Err(SendCmdError::Closed);
        }
        self.cmd_tx.send(cmd).map_err(|_| {
            warn!("send cmd failed: channel closed");
            SendCmdError::Stopped
        })?;
        self.waker.wake();
        Ok(())
    }
    /// 获取 actor 的最新状态(同步快照)。
    ///
    /// 每次调用都拷贝一份 `watch` 的当前值,不阻塞、不需要 runtime。
    /// 适合"偶尔读一次";想"变了就叫我"而不是轮询,用
    /// [`state_rx`](ActorHandle::state_rx) 拿接收端自己驱动。
    pub fn get_state(&self) -> A::State {
        self.state_rx.borrow().to_owned()
    }

    /// 获取 actor 的最新进度(同步快照)。
    ///
    /// 进度通道是 `watch`:读者只会看到**最新值**,中间值可能被跳过。
    /// 适合进度条、实时指标,不要拿它当消息队列用。
    /// 想订阅变化而非每次拉快照,用 [`progress_rx`](ActorHandle::progress_rx)。
    pub fn get_progress(&self) -> A::Progress {
        self.progress_rx.borrow().to_owned()
    }

    /// 订阅事件流,返回一个 `broadcast` 接收端。
    ///
    /// 这是**同步**用法:在 GUI 帧循环里 `try_recv()` 即可,不需要 async runtime。
    /// 落后太多时 `recv()` 会返回 `Lagged`,需要自行决定是跳过还是重试。
    pub fn get_events_rx(&self) -> broadcast::Receiver<A::Event> {
        self.event_tx.subscribe()
    }

    /// 请求 actor 停止。
    ///
    /// 只是发出取消信号([`CancelToken::cancel`]),**不会**强行中断 `run`:
    /// 实现者需要在自己的循环里检查取消信号(如 `select!` 到 `cancel.cancelled()`,
    /// 或每轮 `is_cancelled()`),否则 actor 会继续跑到 `run` 返回为止。
    pub fn stop(&self) {
        self.cancel.cancel();
    }
    /// actor 是否还活着。
    ///
    /// # `false` 的准确含义(0.1.1 起)
    ///
    /// **actor 已结束,并且它持有的资源已经析构完。**
    ///
    /// 线程壳下,`run(self, ctx)` 返回后 actor 自身还要 drop —— Vulkan 设备、解码器、
    /// 字体库这类"释放起来要几十毫秒"的东西。本标志在**那之后**才变 `false`,
    /// 因此用它判断"可以安全退出进程 / 可以安全复用这块资源"是成立的。
    ///
    /// 0.1.0 里它只表示"`run` 已返回",比资源释放早一个窗口:依赖它做退出判断的调用方
    /// 会与后台线程的 `free()` 赛跑,偶发 glibc 堆损坏(`corrupted double-linked list` /
    /// `corrupted size vs. prev_size`)→ SIGABRT。详见 CHANGELOG 的 0.1.1。
    ///
    /// 反方向不成立:`true` 不代表 actor 干得动活 —— 阻塞调用卡死时它仍然是 `true`。
    pub fn is_alive(&self) -> bool {
        *self.alive_rx.borrow()
    }

    /// 订阅"存活状态",actor 结束时变成 `false`。
    ///
    /// `false` 的含义与 [`is_alive`](ActorHandle::is_alive) 相同:**资源已释放完**,
    /// 不只是 `run` 返回。
    ///
    /// 用来替代轮询 [`is_alive`](ActorHandle::is_alive):GUI 每帧
    /// `has_changed()` 一次即可(`watch` 语义,中间变化可丢,只关心最终值)。
    ///
    /// 后台端 drop 后 sender 也随之消失,因此 `changed()` 可能返回 `Err`
    /// —— 那同样意味着 actor 已经结束,按 `false` 处理即可。
    pub fn alive_rx(&self) -> watch::Receiver<bool> {
        self.alive_rx.clone()
    }

    /// 订阅状态变化,返回一个 `watch::Receiver`。
    ///
    /// 与 [`get_state`](ActorHandle::get_state) 是一对:那个每次拉一份最新快照,
    /// 这个给你一个能"等下一次变化"的接收端。用途是**自己驱动**的更新循环:
    ///
    /// - 同步宿主(GUI 帧循环、GTK/iOS 主线程等):每帧 `has_changed()` 一次;
    /// - 异步:在 `select!` 里 `rx.changed().await`。本方法只是 `watch` 通道的接收端,
    ///   **不需要 tokio runtime**,也不会自己 `spawn` 任务。
    ///
    /// ```no_run
    /// # use actor_lite::{ActorCore, ActorHandle};
    /// # struct MyActor;
    /// # impl ActorCore for MyActor {
    /// #     type Cmd = ();
    /// #     type Event = ();
    /// #     type State = u32;
    /// #     type Progress = ();
    /// #     fn init_state_and_progress(&self) -> (u32, ()) {
    /// #         (0, ())
    /// #     }
    /// # }
    /// # fn gui_frame(handle: &ActorHandle<MyActor>) {
    /// let mut states = handle.state_rx();
    ///
    /// // 每帧调一次:有变化就取新值重绘(没有就什么也不做)
    /// if states.has_changed().unwrap_or(false) {
    ///     let state: u32 = states.borrow_and_update().clone();
    ///     # let _ = state;
    ///     // draw(state);
    /// }
    /// # }
    /// ```
    ///
    /// # 语义(`watch`)
    ///
    /// 只保留**最新值**,中间值可能被跳过:actor 连续更新多次而读者没跟上,只看到最后那次。
    /// 要一条不漏地收消息,请用 [`get_events_rx`](ActorHandle::get_events_rx)(`broadcast`),
    /// 别把状态当事件流用。
    ///
    /// # 第一次 `changed()` 可能立刻返回
    ///
    /// 每次调用都 clone 出一个**独立**的接收端(各自维护"已读"位置,多个读者互不影响),
    /// 而 clone 带过来的是 handle 内部的已读位置。因此如果 actor 在
    /// [`channel`](ActorCore::channel) 之后已经更新过状态,新接收端的 `has_changed()` /
    /// `changed()` 会**立刻**就绪 —— 那读到的是**当前值**,不是"刚刚又变了一次"。
    ///
    /// 所以正确顺序是:先用 `borrow()` / `borrow_and_update()` 取初始值,再等 `changed()`
    /// 拿增量;别把第一次 `changed()` 当成一次独立的变化通知。
    ///
    /// # actor 结束后
    ///
    /// 后台端 drop 后 sender 随之消失:`changed()` 返回 `Err`,`has_changed()` 返回
    /// `Err(RecvError)`,此时 `borrow()` 仍能读到**最后一个值**。
    /// 处理方式与 [`alive_rx`](ActorHandle::alive_rx) 相同 —— `Err` 就是"actor 已经结束",
    /// 不必当成致命错误。
    ///
    /// # 与 `state_listen_async` 的区别
    ///
    /// `state_listen_async` 是回调式(每次变化 `op(state).await`),内部 `tokio::spawn`,
    /// 要求调用线程有 runtime;本方法只交出接收端,由调用方决定在哪读、多久读一次。
    /// 同步宿主或已经有自己的循环时,用这个更省事,也更好控制背压。
    pub fn state_rx(&self) -> watch::Receiver<A::State> {
        self.state_rx.clone()
    }

    /// 订阅进度变化,返回一个 `watch::Receiver`。
    ///
    /// 与 [`get_progress`](ActorHandle::get_progress) 是一对:那个是"现在多少",这个能
    /// "等下一次进度变化"。典型用法是进度条 / 实时指标:同步宿主每帧 `has_changed()`
    /// 后重绘,异步里 `select!` 到 `rx.changed()`。不需要 tokio runtime,也不自己起任务。
    ///
    /// # 语义(`watch`,比状态更需要小心)
    ///
    /// 进度是**高频、可丢**的:actor 在一帧里推进了 100 次,读者只看到最后那次。
    /// 这正适合进度条(画面本来就只能显示最新值),但如果你要的是"每个中间值都要处理"
    /// (逐条日志、逐笔成交),那是 [`get_events_rx`](ActorHandle::get_events_rx) 的场景。
    ///
    /// 与 [`state_rx`](ActorHandle::state_rx) 一样,clone 出来的接收端第一次 `changed()`
    /// 可能立刻就绪(读到的是当前值),所以先 `borrow()` 拿初值再等 `changed()`。
    /// actor 结束后 `changed()` 返回 `Err`,`borrow()` 仍能读到最后一个进度值。
    ///
    /// # 示例
    ///
    /// ```no_run
    /// # use actor_lite::{ActorCore, ActorHandle};
    /// # struct Player;
    /// # impl ActorCore for Player {
    /// #     type Cmd = ();
    /// #     type Event = ();
    /// #     type State = ();
    /// #     type Progress = f32;
    /// #     fn init_state_and_progress(&self) -> ((), f32) {
    /// #         ((), 0.0)
    /// #     }
    /// # }
    /// # fn gui_frame(handle: &ActorHandle<Player>) {
    /// let mut progress = handle.progress_rx();
    ///
    /// if progress.has_changed().unwrap_or(false) {
    ///     let pct: f32 = *progress.borrow_and_update();
    ///     # let _ = pct;
    ///     // set_progress_bar(pct);
    /// }
    /// # }
    /// ```
    pub fn progress_rx(&self) -> watch::Receiver<A::Progress> {
        self.progress_rx.clone()
    }
}
impl<A: ActorCore> Clone for ActorHandle<A> {
    fn clone(&self) -> Self {
        Self {
            cmd_tx: self.cmd_tx.clone(),
            state_rx: self.state_rx.clone(),
            event_tx: self.event_tx.clone(),
            progress_rx: self.progress_rx.clone(),
            cancel: self.cancel.clone(),
            waker: self.waker.clone(),
            alive_rx: self.alive_rx.clone(),
        }
    }
}
/// actor 的后台端。
///
/// 由 [`ActorCore::channel`] 创建,交给 `run` 持有。用于接收命令、更新状态/进度、广播事件。
///
/// # 同步 API
///
/// 这里的写入方法([`update_state`](ActorContext::update_state)、
/// [`update_progress`](ActorContext::update_progress)、
/// [`send_event`](ActorContext::send_event))和 [`check_cmd`](ActorContext::check_cmd)
/// 都是同步的,不需要 runtime;只有 [`wait_for_cmd`](ActorContext::wait_for_cmd) 返回 future。
///
/// # 收命令
///
/// - [`check_cmd`](ActorContext::check_cmd):非阻塞 `try_recv`,适合"每轮循环顺带看一眼";
/// - [`wait_for_cmd`](ActorContext::wait_for_cmd):`recv().await`,适合异步壳;
/// - `recv_cmd_timeout` / `recv_cmd`:**阻塞**版本,只在 [`ThreadActor`](crate::ThreadActor)
///   的上下文里才有(见 `thread_actor` 模块)。
///
/// 命令通道关闭(所有 [`ActorHandle`] 都 drop 了)后两者分别返回 `None`,
/// 实现者据此退出循环即可。
pub struct ActorContext<A: ActorCore> {
    pub(crate) cmd_rx: mpsc::UnboundedReceiver<A::Cmd>,
    state_tx: watch::Sender<A::State>,
    event_tx: broadcast::Sender<A::Event>,
    progress_tx: watch::Sender<A::Progress>,
    pub(crate) cancel: CancelToken,
    pub(crate) waker: SharedWaker,
    pub(crate) _alive: Option<AliveGuard>,
}
impl<A: ActorCore> ActorContext<A> {
    /// 获取额外的事件发送端。
    ///
    /// 用于把事件发送端交给别的线程/任务(比如 IO 回调里直接发事件出队列)。
    pub fn get_events_clone(&self) -> broadcast::Sender<A::Event> {
        self.event_tx.clone()
    }
    /// 发送事件(同步,永不失败;没有订阅者时事件被丢弃)。
    pub fn send_event(&self, event: A::Event) {
        let _ = self.event_tx.send(event);
    }
    /// 更新状态。
    ///
    /// `watch` 语义:读者只会看到最新值,中间值可能被跳过。
    /// 状态应是低频、可幂等覆盖的数据;高频数据用 [`update_progress`](ActorContext::update_progress)。
    pub fn update_state(&self, state: A::State) {
        self.state_tx.send_replace(state);
    }
    /// 更新进度。
    ///
    /// `watch` 语义:读者只会看到最新值,中间值可能被跳过 —— 对进度条是优点,
    /// 但**不要**拿它当消息队列(每一帧都要的话走事件)。
    pub fn update_progress(&self, progress: A::Progress) {
        self.progress_tx.send_replace(progress);
    }
    /// 等待下一条命令(async)。
    ///
    /// 命令通道关闭时返回 `None`,可据此结束 `run`。
    pub fn wait_for_cmd(&mut self) -> impl Future<Output = Option<A::Cmd>> {
        self.cmd_rx.recv()
    }
    /// 非阻塞检查命令。
    ///
    /// 立即返回:有命令就 `Some`,没有或通道已关闭都是 `None`。
    pub fn check_cmd(&mut self) -> Option<A::Cmd> {
        self.cmd_rx.try_recv().ok()
    }

    /// 获取取消信号,用于在自己循环里检查/等待停止。
    ///
    /// 异步壳一般写 `select! { _ = cancel.cancelled() => break, ... }`。
    pub fn cancel_clone(&self) -> CancelToken {
        self.cancel.clone()
    }
    /// actor 是否已被要求停止。
    pub fn is_cancelled(&self) -> bool {
        self.cancel.is_cancelled()
    }
}
/// 取消信号。
///
/// 可在多个任务/线程间 clone 共享,clone 出来的所有副本共享同一个取消状态:
///
/// - [`cancel`](CancelToken::cancel):同步、幂等、永不失败。即使当下没有等待者,
///   后来的 [`is_cancelled`](CancelToken::is_cancelled) 也会是 `true`;
/// - [`is_cancelled`](CancelToken::is_cancelled):同步查询,适合轮询/每轮检查;
/// - [`cancelled`](CancelToken::cancelled):async 等待,已经取消时立即返回。
///
/// 典型来源是 [`ActorHandle::stop`];[`ActorHandle`] 上的 `*_listen_async` 返回的也是它。
#[derive(Clone, Debug)]
pub struct CancelToken {
    tx: watch::Sender<bool>,
    waker: SharedWaker,
}
impl Default for CancelToken {
    fn default() -> Self {
        Self::new()
    }
}
impl CancelToken {
    /// 创建一个未取消的信号。
    pub fn new() -> Self {
        let tx = watch::channel(false).0;
        let waker = SharedWaker::default();
        Self { tx, waker }
    }
    pub(crate) fn with_waker(waker: SharedWaker) -> Self {
        Self {
            tx: watch::channel(false).0,
            waker,
        }
    }
    /// 检查取消信号。
    pub fn is_cancelled(&self) -> bool {
        *self.tx.borrow()
    }
    /// 等待取消信号;已经取消时立即返回。
    pub async fn cancelled(&self) {
        let mut rx = self.tx.subscribe();
        // wait_for 会先拿当前值比一次,再等变化 → 不存在"通知丢失"的窗口
        let _ = rx.wait_for(|cancelled| *cancelled).await;
    }
    /// 发送取消信号(幂等)。
    ///
    /// 唤醒所有正在 [`cancelled`](CancelToken::cancelled) 上等待的任务;
    /// 信号不会"过期",之后再调用 `cancelled()` 也会立即返回。
    pub fn cancel(&self) {
        self.tx.send_replace(true);
        self.waker.wake();
    }
    /// 阻塞等待取消(线程 actor 用;异步壳请用 `cancelled()`)。
    pub fn cancelled_blocking(&self) {
        if self.is_cancelled() {
            return;
        }
        let waker = self.waker.waker();
        let _ = wait::drive_until(self.cancelled(), None, &waker);
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SendCmdError {
    /// 已经调用过 [`ActorHandle::stop`],actor 不再接受新命令。
    Stopped,
    /// 后台端已结束:`run` 返回、panic,或所有 [`ActorContext`] 都已 drop。
    Closed,
}

impl fmt::Display for SendCmdError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Stopped => "actor has been stopped",
            Self::Closed => "actor is closed",
        })
    }
}

impl std::error::Error for SendCmdError {}
/// 把存活状态置 `false` 的守卫。
///
/// **谁持有它,决定了 `is_alive()` 的语义**,所以不要随手塞回 [`ActorContext`]:
/// 线程壳用 [`ActorContext::take_alive_guard`] 把它取出来,由线程闭包持有,
/// 在 `actor.run(ctx)` 消费掉 actor、其字段析构完之后**最后**才 drop ——
/// 这样 `is_alive() == false` 才等于"线程已结束且资源已释放"。
///
/// 若留在 [`ActorContext`] 里,它会在 `run(self, ctx)` 返回时就 drop,
/// 比 actor 字段的析构早一个窗口(0.1.0 的 bug,见 CHANGELOG)。
pub(crate) struct AliveGuard(watch::Sender<bool>);
impl Drop for AliveGuard {
    fn drop(&mut self) {
        self.0.send_replace(false);
    }
}