wordval-actor 1.0.5

Wordval actor system: high-performance message foundation for drone ground stations
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
//! 定时器 —— 全局单一驱动任务,所有 `schedule_*` 复用一条 tokio 任务。
//!
//! 采用"活跃条目表(HashMap)+ 到期键最小堆"结构:
//! - 条目表只保存活跃定时器,`cancel` / `reset` 即时生效、零残留;
//!   周期条目在目标 Actor 最终退出(接收端关闭)后自动退场;
//! - 堆中因 reset/cancel 过期的键在弹出时按 ticket 惰性淘汰;
//! - 看门狗走 `TimerDriver::schedule_watchdog`:deadline 存共享原子量,
//!   喂狗一次原子写完成滑动(零跨任务命令、零驱动唤醒),驱动到点先
//!   exchange 接管触发权再重读 deadline,被推进则按新值重新入堆不触发。
//! - 动作 panic 隔离:驱动是全局单点,单个动作内 panic(周期消息
//!   `Clone`、投递路径等用户代码)只移除该条目并记 error,驱动继续运行。
//!
//! 时间源抽象为 [`Clock`],默认走 `tokio::time`(测试可注入手动时钟)。

use futures_core::future::BoxFuture;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering as AtomicOrdering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;

/// 周期定时器的间隔下限:零间隔会让驱动忙循环(每拍立即到点重入堆,
/// 仅靠邮箱背压限速 —— 空邮箱时纯自旋烧 CPU),钳制到此值并记 warn。
const MIN_INTERVAL: Duration = Duration::from_millis(1);

/// 周期条目背压丢弃告警的节流窗口:丢弃/恢复两类告警共用同一窗口,
/// 保证**至多每秒一条 warn**。持续背压(卡死 Actor + 心跳)与窗口内
/// 振荡背压都不会洪泛日志;窗口内的丢弃数随汇总告警一并给出。
const DROP_WARN_WINDOW: Duration = Duration::from_secs(1);

/// 背压告警节流判定:距上次告警 ≥ [`DROP_WARN_WINDOW`](或从未告警)时
/// 返回 true 并推进 `last`;否则调用方降级为 debug。
fn warn_due(last: &mut Option<tokio::time::Instant>, now: tokio::time::Instant) -> bool {
    if last.map_or(true, |t| now.saturating_duration_since(t) >= DROP_WARN_WINDOW) {
        *last = Some(now);
        true
    } else {
        false
    }
}

/// 时间源抽象 —— 默认为 [`TokioClock`]。
///
/// 抽象出 `now + sleep_until` 两个原语即可驱动整个定时器堆;
/// 测试中可注入手动推进的虚拟时钟(配合
/// [`ActorSystem::with_clock`](crate::ActorSystem::with_clock))。
pub trait Clock: Send + Sync {
    /// 当前时刻。
    fn now(&self) -> tokio::time::Instant;

    /// 等待到指定时刻。
    fn sleep_until(&self, when: tokio::time::Instant) -> BoxFuture<'static, ()>;
}

/// 基于 `tokio::time` 的默认时钟。
#[derive(Debug, Clone, Copy)]
pub struct TokioClock;

impl Clock for TokioClock {
    fn now(&self) -> tokio::time::Instant {
        tokio::time::Instant::now()
    }

    fn sleep_until(&self, when: tokio::time::Instant) -> BoxFuture<'static, ()> {
        Box::pin(tokio::time::sleep_until(when))
    }
}

/// 系统时钟源 —— 默认 tokio 实时钟,或注入的自定义 [`Clock`](虚拟时间测试)。
///
/// 默认分支的 `sleep_until` 生成栈上 future:ask 超时等热路径零装箱;
/// 仅自定义时钟分支经 [`Clock::sleep_until`] 走装箱分发(测试专用,冷路径)。
#[derive(Clone)]
pub(crate) enum ClockSource {
    Tokio,
    Custom(Arc<dyn Clock>),
}

impl ClockSource {
    #[inline]
    pub(crate) fn now(&self) -> tokio::time::Instant {
        match self {
            Self::Tokio => tokio::time::Instant::now(),
            Self::Custom(c) => c.now(),
        }
    }

    #[inline]
    pub(crate) async fn sleep_until(&self, when: tokio::time::Instant) {
        match self {
            Self::Tokio => tokio::time::sleep_until(when).await,
            Self::Custom(c) => c.sleep_until(when).await,
        }
    }
}

/// 定时任务句柄 —— 支持显式取消与滑动重置;句柄析构不会自动取消。
#[derive(Clone)]
pub struct TimerHandle {
    id: u64,
    tx: mpsc::UnboundedSender<Cmd>,
    clock: ClockSource,
    /// 本地意图标记:`cancel()` 立即置位(`is_cancelled` 查询无需等驱动)。
    cancelled: Arc<AtomicBool>,
    /// 触发标记:驱动执行到点动作前置位;仅 once 任务具备(interval 为 None)。
    fired: Option<Arc<AtomicBool>>,
}

impl std::fmt::Debug for TimerHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TimerHandle")
            .field("id", &self.id)
            .field("cancelled", &self.cancelled.load(AtomicOrdering::Relaxed))
            .field("fired", &self.has_fired())
            .finish()
    }
}

impl TimerHandle {
    /// 取消该定时任务(对已触发的 once 任务为 no-op)。
    pub fn cancel(&self) {
        self.cancelled.store(true, AtomicOrdering::Relaxed);
        let _ = self.tx.send(Cmd::Cancel { id: self.id });
    }

    /// 是否已取消(反映调用方意图,不反映驱动侧实际状态)。
    pub fn is_cancelled(&self) -> bool {
        self.cancelled.load(AtomicOrdering::Relaxed)
    }

    /// 该 once 任务是否已触发。
    ///
    /// 触发标记在驱动执行到点动作**之前**置位,且 Actor 事件循环
    /// 单线程消费消息,因此“触发后首批消息先于定时消息被处理”
    /// 不可能发生 —— 该查询在 Actor 上下文内无竞态。
    /// 周期任务恒返回 false(无单次触发语义)。
    pub fn has_fired(&self) -> bool {
        self.fired
            .as_ref()
            .is_some_and(|f| f.load(AtomicOrdering::Relaxed))
    }

    /// 滑动 deadline:从现在起重新等待 `delay`。对已触发/已取消的任务为 no-op。
    ///
    /// 复用既有条目:驱动内活跃条目保持 O(1),不产生已取消条目残留。
    /// 代价是每次调用向驱动投递一条重置命令(跨任务发送 + 堆插入 +
    /// 唤醒驱动)。
    ///
    /// 高频滑动(如每帧喂狗,100–1000Hz)请改用
    /// [`ActorContext::watchdog`](crate::ActorContext::watchdog):其滑动
    /// 走共享原子 deadline,零跨任务命令、零驱动唤醒。
    pub fn reset(&self, delay: Duration) {
        let deadline = deadline_after(self.clock.now(), delay);
        let _ = self.tx.send(Cmd::Reset { id: self.id, deadline });
    }
}

/// 看门狗共享原子 deadline 的"已被驱动接管触发权"哨兵值。
pub(crate) const WATCHDOG_FIRED: u64 = u64::MAX;

/// 计算以 `base` 为基准的 deadline 相对纳秒数(喂狗滑动与驱动
/// 重读共用的时间表示;时钟回拨时钳制为 0)。
///
/// 饱和上界取 `u64::MAX - 1`,为 [`WATCHDOG_FIRED`] 哨兵值保留 `u64::MAX`。
pub(crate) fn rel_nanos(base: tokio::time::Instant, deadline: tokio::time::Instant) -> u64 {
    deadline
        .checked_duration_since(base)
        .map_or(0, |d| d.as_nanos().min((u64::MAX - 1) as u128) as u64)
}

/// 溢出安全 deadline:等价于 `now + d`,但极端 `Duration`(如
/// `Duration::MAX`)下 `Instant::add` 会溢出 panic —— 此时钳制为远期
/// 时刻(30 年上界,与 tokio 内部 `far_future` 取同值:更长的上界在
/// macOS/FreeBSD 等平台的 Instant 表示范围下仍可能溢出),语义等价于
/// "永不触发",实际取消/停止由各控制路径(stop / disarm / cancel)兜底。
pub(crate) fn deadline_after(now: tokio::time::Instant, d: Duration) -> tokio::time::Instant {
    const FAR_FUTURE: Duration = Duration::from_secs(86400 * 365 * 30);
    now.checked_add(d)
        .or_else(|| now.checked_add(FAR_FUTURE))
        .unwrap_or(now)
}

/// 堆键:到期时间升序(反向 Ord 让堆顶为最早到期)。
#[derive(Debug, Clone, Copy)]
struct Key {
    deadline: tokio::time::Instant,
    id: u64,
    /// 条目版本票号:reset/cancel 后旧键弹出时按此淘汰。
    ticket: u64,
}

impl PartialEq for Key {
    fn eq(&self, other: &Self) -> bool {
        self.deadline == other.deadline && self.ticket == other.ticket
    }
}

impl Eq for Key {}

impl PartialOrd for Key {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Key {
    fn cmp(&self, other: &Self) -> Ordering {
        // 反转 deadline 比较:堆顶为最早到期;ticket 反转保证同
        // deadline 下先注册/先重置者先触发(先到先触发)。
        other
            .deadline
            .cmp(&self.deadline)
            .then_with(|| other.ticket.cmp(&self.ticket))
    }
}

/// 到点动作单次执行结果。
enum Step {
    /// 本次动作完结,按此时刻重新入堆(看门狗滑动竞态复核 / 周期续期)。
    RequeueAt(tokio::time::Instant),
    /// 任务完结,条目移除(once 触发完毕 / 周期目标已停止)。
    Done,
}

/// 活跃定时器条目。
struct Entry {
    deadline: tokio::time::Instant,
    ticket: u64,
    /// 到点动作。返回 [`Step::RequeueAt`] 表示按新时刻重新入堆;
    /// [`Step::Done`] 表示条目移除,驱动不再为其唤醒。
    action: Box<dyn FnMut() -> Step + Send>,
}

enum Cmd {
    Add { id: u64, entry: Entry },
    Reset { id: u64, deadline: tokio::time::Instant },
    Cancel { id: u64 },
    /// 测试专用:查询活跃条目数(驱动 round-trip)。
    #[cfg(test)]
    Count(tokio::sync::oneshot::Sender<usize>),
}

/// 定时器驱动 —— Clone,内部共享同一条驱动任务。
#[derive(Clone)]
pub struct TimerDriver {
    tx: mpsc::UnboundedSender<Cmd>,
    clock: ClockSource,
    next_id: Arc<AtomicU64>,
}

impl TimerDriver {
    /// 启动驱动任务。所有克隆共享此任务;
    /// 全部克隆被丢弃后驱动任务自然退出。
    pub(crate) fn spawn(clock: ClockSource) -> Self {
        let (tx, rx) = mpsc::unbounded_channel();
        Self {
            tx,
            clock,
            next_id: Arc::new(AtomicU64::new(0)),
        }
        .attach(rx)
    }

    fn attach(self, rx: mpsc::UnboundedReceiver<Cmd>) -> Self {
        let clock = self.clock.clone();
        tokio::spawn(async move { run(clock, rx).await });
        self
    }

    /// 测试专用:当前活跃条目数(驱动 round-trip,读值保证与驱动顺序一致)。
    #[cfg(test)]
    pub(crate) async fn active_entries(&self) -> usize {
        let (tx, rx) = tokio::sync::oneshot::channel();
        let _ = self.tx.send(Cmd::Count(tx));
        rx.await.expect("定时器驱动应存活")
    }

    /// 注册一条到点执行的定时任务(内部原语)。
    fn add(
        &self,
        deadline: tokio::time::Instant,
        action: Box<dyn FnMut() -> Step + Send>,
    ) -> TimerHandle {
        let id = self.next_id.fetch_add(1, AtomicOrdering::Relaxed);
        let _ = self.tx.send(Cmd::Add {
            id,
            entry: Entry {
                deadline,
                ticket: 0,
                action,
            },
        });
        TimerHandle {
            id,
            tx: self.tx.clone(),
            clock: self.clock.clone(),
            cancelled: Arc::new(AtomicBool::new(false)),
            fired: None,
        }
    }

    /// 一次性延迟投递:`delay` 后将 `payload` 投入 `ctl` 通道。
    ///
    /// 投递语义:**once 消息不丢弃**。触发瞬间邮箱满(瞬时背压)时
    /// 转为异步等待空位补投(失控保护类消息必须送达);仅当目标
    /// 已停止(通道关闭)才静默丢弃。
    pub fn schedule_message<E: Send + 'static>(
        &self,
        delay: Duration,
        ctl: mpsc::Sender<E>,
        payload: E,
    ) -> TimerHandle {
        let deadline = deadline_after(self.clock.now(), delay);
        let mut payload = Some(payload);
        let fired = Arc::new(AtomicBool::new(false));
        let fired_flag = Arc::clone(&fired);
        let action = Box::new(move || -> Step {
            // 先置位再投递:调用方经 has_fired() 感知触发,与消息送达顺序一致
            fired_flag.store(true, AtomicOrdering::Relaxed);
            let Some(m) = payload.take() else {
                return Step::Done;
            };
            match ctl.try_send(m) {
                Ok(()) => {}
                Err(mpsc::error::TrySendError::Closed(_)) => {
                    tracing::debug!("定时消息投递失败:目标已停止,已丢弃");
                }
                Err(mpsc::error::TrySendError::Full(frame)) => {
                    // once 消息(如链路看门狗 LinkLost)不得因瞬时背压
                    // 丢失:转为异步阻塞投递,等待邮箱空位
                    let ctl = ctl.clone();
                    tokio::spawn(async move {
                        if ctl.send(frame).await.is_err() {
                            tracing::debug!("定时消息异步补投失败:目标已停止,已丢弃");
                        }
                    });
                }
            }
            Step::Done
        });
        let mut handle = self.add(deadline, action);
        handle.fired = Some(fired);
        handle
    }

    /// 周期投递:每隔 `interval` 克隆投入一条 `payload`。
    ///
    /// 投递语义:周期 tick 允许丢拍(下一周期自愈);触发时邮箱满
    /// 丢弃本拍并记日志(告警节流:至多每秒一条 warn,窗口内丢弃数
    /// 随汇总告警给出,其余降为 debug)。
    /// 目标 Actor 最终退出(接收端关闭,非重启瞬时状态)后条目
    /// **自动退场** —— 死条目不再按周期唤醒驱动,连接重建类场景不累积。
    ///
    /// `interval` 为零会退化为驱动忙循环(每拍立即到点重入堆,仅靠
    /// 邮箱背压限速),钳制为 1ms 并记 warn。
    pub fn schedule_interval<E: Send + Clone + 'static>(
        &self,
        interval: Duration,
        ctl: mpsc::Sender<E>,
        payload: E,
    ) -> TimerHandle {
        // 静默忙循环比显式限频更糟,直接拒绝创建又破坏调用方对返回
        // 句柄的假设 —— 钳到 1ms 并 warn 是最小惊讶选择(1ms 已远高于
        // 常规轮询需求的高频)
        let interval = if interval.is_zero() {
            tracing::warn!("周期定时器间隔为 0(等价驱动忙循环),已钳制为 {MIN_INTERVAL:?}");
            MIN_INTERVAL
        } else {
            interval
        };
        let deadline = deadline_after(self.clock.now(), interval);
        let action_clock = self.clock.clone();
        // 背压日志节流状态:丢弃与恢复告警共用 last_warn 窗口
        let mut dropped: u64 = 0;
        let mut last_warn: Option<tokio::time::Instant> = None;
        let action = Box::new(move || -> Step {
            match ctl.try_send(payload.clone()) {
                Ok(()) => {
                    if dropped > 0 {
                        // 恢复汇总:窗口内累计丢弃数一次性给出
                        let now = action_clock.now();
                        if warn_due(&mut last_warn, now) {
                            tracing::warn!(dropped, "周期消息投递恢复:背压窗口内累计丢弃 {dropped} 拍");
                        } else {
                            tracing::debug!(dropped, "周期消息投递恢复:背压窗口内累计丢弃 {dropped} 拍");
                        }
                        dropped = 0;
                    }
                }
                Err(mpsc::error::TrySendError::Closed(_)) => {
                    tracing::debug!("周期消息目标已停止,定时条目退场");
                    return Step::Done;
                }
                Err(mpsc::error::TrySendError::Full(_)) => {
                    dropped += 1;
                    let now = action_clock.now();
                    if warn_due(&mut last_warn, now) {
                        tracing::warn!(dropped, "周期消息投递失败:邮箱满,本窗口累计丢弃 {dropped} 拍(下一周期自愈)");
                    } else {
                        tracing::debug!(dropped, "周期消息投递失败:邮箱满,本拍已丢弃(窗口内告警已节流)");
                    }
                }
            }
            Step::RequeueAt(deadline_after(action_clock.now(), interval))
        });
        self.add(deadline, action)
    }

    /// 看门狗专用一次性定时:滑动 deadline 存共享原子量
    /// `deadline_ns`(距 `base` 的纳秒数,喂狗侧原子更新)。
    ///
    /// 到点时驱动先 `swap` 哨兵接管触发权,再核对 deadline:
    /// - 已被并发喂狗推向未来 → 不触发,按最新 deadline 重新入堆
    ///   (无投递、无唤醒风暴);喂狗与触发的任何交错都以该原子值
    ///   为线性化点,恰好一方胜出 —— 不存在"已滑动仍误报"的窗口;
    /// - 确已到期 → 置位触发标记并投递 `payload`(满邮箱异步补投,
    ///   语义同 [`schedule_message`])。
    pub(crate) fn schedule_watchdog<E: Send + 'static>(
        &self,
        base: tokio::time::Instant,
        deadline_ns: Arc<AtomicU64>,
        delay: Duration,
        ctl: mpsc::Sender<E>,
        payload: E,
    ) -> TimerHandle {
        let action_clock = self.clock.clone();
        let fired = Arc::new(AtomicBool::new(false));
        let fired_flag = Arc::clone(&fired);
        let mut payload = Some(payload);
        let action = Box::new(move || -> Step {
            // 先以 exchange 独占触发权,再核对 deadline:喂狗与触发
            // 的任何交错都恰好一方胜出
            let claimed = deadline_ns.swap(WATCHDOG_FIRED, AtomicOrdering::AcqRel);
            let now_rel = rel_nanos(base, action_clock.now());
            if claimed > now_rel {
                // deadline 已被并发喂狗推进:本按不触发。恢复非哨兵值
                // (若期间又有新 store 则以最新为准),按最新 deadline 重入堆
                let cur = deadline_ns.load(AtomicOrdering::Acquire);
                let requeue_rel = if cur == WATCHDOG_FIRED {
                    claimed
                } else {
                    cur.max(claimed)
                };
                let _ = deadline_ns.compare_exchange(
                    WATCHDOG_FIRED,
                    requeue_rel,
                    AtomicOrdering::AcqRel,
                    AtomicOrdering::Acquire,
                );
                return Step::RequeueAt(deadline_after(base, Duration::from_nanos(requeue_rel)));
            }
            // 真实触发:先置位再投递,与 has_fired() 感知顺序一致
            fired_flag.store(true, AtomicOrdering::Release);
            let Some(p) = payload.take() else {
                return Step::Done;
            };
            match ctl.try_send(p) {
                Ok(()) => {}
                Err(mpsc::error::TrySendError::Closed(_)) => {
                    tracing::debug!("看门狗触发投递失败:目标已停止,已丢弃");
                }
                Err(mpsc::error::TrySendError::Full(frame)) => {
                    // 失控保护消息不得因瞬时背压丢失:异步补投等空位
                    let ctl = ctl.clone();
                    tokio::spawn(async move {
                        if ctl.send(frame).await.is_err() {
                            tracing::debug!("看门狗触发异步补投失败:目标已停止,已丢弃");
                        }
                    });
                }
            }
            Step::Done
        });
        let mut handle = self.add(deadline_after(self.clock.now(), delay), action);
        handle.fired = Some(fired);
        handle
    }
}

/// 应用一条驱动命令(抽干阶段与 select 唤醒阶段共用)。
fn apply(
    cmd: Cmd,
    entries: &mut HashMap<u64, Entry>,
    heap: &mut BinaryHeap<Key>,
    next_ticket: &mut u64,
) {
    match cmd {
        Cmd::Add { id, mut entry } => {
            let ticket = *next_ticket;
            *next_ticket += 1;
            entry.ticket = ticket;
            heap.push(Key {
                deadline: entry.deadline,
                id,
                ticket,
            });
            entries.insert(id, entry);
        }
        Cmd::Reset { id, deadline } => {
            // 已触发/已取消的条目不存在:reset 为 no-op
            if let Some(e) = entries.get_mut(&id) {
                let ticket = *next_ticket;
                *next_ticket += 1;
                e.deadline = deadline;
                e.ticket = ticket;
                heap.push(Key { deadline, id, ticket });
            }
        }
        Cmd::Cancel { id } => {
            entries.remove(&id); // 堆中残留键弹出时按 ticket 淘汰
        }
        #[cfg(test)]
        Cmd::Count(reply) => {
            let _ = reply.send(entries.len());
        }
    }
}

async fn run(clock: ClockSource, mut rx: mpsc::UnboundedReceiver<Cmd>) {
    let mut entries: HashMap<u64, Entry> = HashMap::new();
    let mut heap: BinaryHeap<Key> = BinaryHeap::new();
    let mut next_ticket: u64 = 0;
    loop {
        // 抽干注册命令
        while let Ok(cmd) = rx.try_recv() {
            apply(cmd, &mut entries, &mut heap, &mut next_ticket);
        }
        // 堆膨胀控制:reset/cancel 的过期键只在弹出时惰性淘汰,高频
        // reset(如 1000Hz 看门狗)会让堆相对活跃条目持续膨胀。过期键
        // 超过活跃条目两倍(且越过底噪阈值)时按条目表 O(n) 重建压缩。
        if heap.len() > entries.len().saturating_mul(2).saturating_add(64) {
            heap = entries
                .iter()
                .map(|(&id, e)| Key {
                    deadline: e.deadline,
                    id,
                    ticket: e.ticket,
                })
                .collect();
        }
        // 触发所有到期任务
        let now = clock.now();
        while let Some(key) = heap.peek().copied() {
            if key.deadline > now {
                break;
            }
            heap.pop();
            let Some(e) = entries.get_mut(&key.id) else {
                continue; // 已取消
            };
            if e.ticket != key.ticket {
                continue; // 过期键:已被 reset/cancel 取代
            }
            // 捕获动作 panic:驱动是全局单点(所有定时器/看门狗共用),
            // 单个动作内跑到的用户代码(周期消息 Clone、投递时的 tokio::spawn)
            // panic 不得炸毁驱动 —— 否则全部看门狗静默失效。panic 条目移除,
            // 驱动继续服务其余定时器。
            let action_result =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (e.action)()));
            let step = match action_result {
                Ok(step) => step,
                Err(_) => {
                    tracing::error!(timer = key.id, "定时器动作 panic,已移除该条目(驱动继续运行)");
                    entries.remove(&key.id);
                    continue;
                }
            };
            match step {
                Step::RequeueAt(next) => {
                    // 看门狗滑动竞态复核 / 周期续期:按新时刻重新入堆
                    e.deadline = next;
                    let ticket = next_ticket;
                    next_ticket += 1;
                    e.ticket = ticket;
                    heap.push(Key {
                        deadline: next,
                        id: key.id,
                        ticket,
                    });
                }
                Step::Done => {
                    // once 触发完毕 / 周期目标已停止:条目退场,不再唤醒驱动
                    entries.remove(&key.id);
                }
            }
        }
        // 等待下一个到期或新注册(堆顶键可能因 reset 过期而提前唤醒,无害)
        match heap.peek().map(|k| k.deadline) {
            Some(when) => {
                tokio::select! {
                    cmd = rx.recv() => match cmd {
                        Some(cmd) => apply(cmd, &mut entries, &mut heap, &mut next_ticket),
                        None => break,
                    },
                    _ = clock.sleep_until(when) => {}
                }
            }
            None => match rx.recv().await {
                Some(cmd) => apply(cmd, &mut entries, &mut heap, &mut next_ticket),
                None => break,
            },
        }
    }
    tracing::debug!("定时器驱动退出(全部句柄已释放)");
}

#[cfg(test)]
mod tests {
    use super::*;

    fn driver() -> TimerDriver {
        TimerDriver::spawn(ClockSource::Tokio)
    }

    #[tokio::test]
    async fn once_fires_then_stops() {
        let driver = driver();
        let (tx, mut rx) = mpsc::channel::<u32>(8);
        let _h = driver.schedule_message(Duration::from_millis(10), tx.clone(), 42u32);
        let msg = tokio::time::timeout(Duration::from_secs(1), rx.recv())
            .await
            .expect("应在 1s 内触发")
            .expect("收到帧");
        assert_eq!(msg, 42);
        // once 不再触发第二次
        assert!(tokio::time::timeout(Duration::from_millis(50), rx.recv())
            .await
            .is_err());
    }

    #[tokio::test]
    async fn interval_fires_repeatedly() {
        let driver = driver();
        let (tx, mut rx) = mpsc::channel::<u32>(8);
        let h = driver.schedule_interval(Duration::from_millis(10), tx.clone(), 7u32);
        for _ in 0..3 {
            let m = tokio::time::timeout(Duration::from_secs(1), rx.recv())
                .await
                .expect("周期触发")
                .expect("帧");
            assert_eq!(m, 7);
        }
        h.cancel();
        assert!(h.is_cancelled());
        // 取消后不再触发
        assert!(tokio::time::timeout(Duration::from_millis(60), rx.recv())
            .await
            .is_err());
    }

    #[tokio::test]
    async fn earlier_deadline_wakes_driver() {
        // 驱动先空闲等待远期任务,随后插入一条近期任务应被准点触发
        let driver = driver();
        let (tx, mut rx) = mpsc::channel::<u8>(8);
        let _far = driver.schedule_message(Duration::from_secs(3600), tx.clone(), 1u8);
        let _near = driver.schedule_message(Duration::from_millis(20), tx.clone(), 2u8);
        let mut got = None;
        for _ in 0..2 {
            if let Ok(Some(v)) = tokio::time::timeout(Duration::from_secs(1), rx.recv())
                .await
            {
                if v == 2 {
                    got = Some(v);
                    break;
                }
            }
        }
        assert_eq!(got, Some(2));
    }

    #[tokio::test]
    async fn reset_delays_fire() {
        // 看门狗滑动语义:reset 推迟触发时刻
        let driver = driver();
        let (tx, mut rx) = mpsc::channel::<u32>(8);
        let h = driver.schedule_message(Duration::from_millis(60), tx.clone(), 1u32);
        tokio::time::sleep(Duration::from_millis(20)).await;
        h.reset(Duration::from_millis(120));
        // 原 deadline 已过但被 reset 推迟:此刻不应触发
        assert!(
            tokio::time::timeout(Duration::from_millis(80), rx.recv())
                .await
                .is_err(),
            "reset 后不应按原 deadline 触发"
        );
        let msg = tokio::time::timeout(Duration::from_secs(1), rx.recv())
            .await
            .expect("应在重置后的 deadline 触发");
        assert_eq!(msg, Some(1));
    }

    #[tokio::test]
    async fn repeated_reset_keeps_single_fire() {
        // 高频 reset(1000Hz 看门狗模式)只应触发一次,且不重复投递
        let driver = driver();
        let (tx, mut rx) = mpsc::channel::<u32>(8);
        let h = driver.schedule_message(Duration::from_millis(50), tx.clone(), 9u32);
        for _ in 0..10 {
            tokio::time::sleep(Duration::from_millis(10)).await;
            h.reset(Duration::from_millis(50));
        }
        let msg = tokio::time::timeout(Duration::from_secs(1), rx.recv())
            .await
            .expect("停止 reset 后应触发");
        assert_eq!(msg, Some(9));
        // 且仅触发一次
        assert!(
            tokio::time::timeout(Duration::from_millis(80), rx.recv())
                .await
                .is_err(),
            "repeated reset 不得产生多次触发"
        );
    }

    #[tokio::test]
    async fn once_message_survives_full_mailbox() {
        // 契约:once 定时消息触发瞬间邮箱满时,转为异步补投而非丢弃
        let driver = driver();
        let (tx, mut rx) = mpsc::channel::<u32>(1);
        tx.try_send(0).expect("占满唯一槽位");
        let _h = driver.schedule_message(Duration::from_millis(10), tx.clone(), 7u32);
        // 定时器在 10ms 触发时邮箱仍满 → 异步补投挂起;30ms 后腾出空位
        tokio::time::sleep(Duration::from_millis(30)).await;
        assert_eq!(rx.recv().await, Some(0));
        let got = tokio::time::timeout(Duration::from_secs(1), rx.recv()).await;
        assert!(
            matches!(got, Ok(Some(7))),
            "once 消息必须经异步补投送达,实际 {got:?}"
        );
    }

    #[tokio::test]
    async fn reset_after_fire_is_noop() {
        let driver = driver();
        let (tx, mut rx) = mpsc::channel::<u32>(8);
        let h = driver.schedule_message(Duration::from_millis(10), tx.clone(), 5u32);
        let _ = tokio::time::timeout(Duration::from_secs(1), rx.recv()).await;
        // 已触发的 once 任务:reset 不应复活它
        h.reset(Duration::from_millis(10));
        assert!(
            tokio::time::timeout(Duration::from_millis(80), rx.recv())
                .await
                .is_err(),
            "已触发任务不得因 reset 复活"
        );
    }

    /// 回归:单个定时器动作内 panic(周期消息的 `Clone` 是用户代码)
    /// 不得炸毁全局驱动 —— 其余定时器必须照常触发。
    #[tokio::test]
    async fn panicking_action_does_not_kill_driver() {
        struct Bomb;
        impl Clone for Bomb {
            fn clone(&self) -> Self {
                panic!("clone bomb")
            }
        }
        let driver = driver();
        let (tx, mut rx) = mpsc::channel::<u32>(8);
        let (bomb_tx, _bomb_rx) = mpsc::channel::<Bomb>(8);
        // 5ms 处周期条目动作 panic(clone 炸弹),10ms 处的正常条目必须存活
        let _bomb = driver.schedule_interval(Duration::from_millis(5), bomb_tx, Bomb);
        let _ok = driver.schedule_message(Duration::from_millis(10), tx, 42u32);
        let msg = tokio::time::timeout(Duration::from_secs(1), rx.recv())
            .await
            .expect("驱动必须存活:其余定时器应在 1s 内触发")
            .expect("收到帧");
        assert_eq!(msg, 42, "单条定时器动作 panic 后驱动必须继续服务其余定时器");
    }

    /// 回归:周期条目在目标 Actor 最终退出(接收端关闭)后必须退场 ——
    /// 死条目不得在驱动内无上界累积,也不得每拍空醒驱动
    /// (连接重建类场景每会话一个 interval)。
    #[tokio::test]
    async fn interval_entry_retires_when_target_closed() {
        let driver = driver();
        let (tx, rx) = mpsc::channel::<u32>(8);
        let _h = driver.schedule_interval(Duration::from_millis(5), tx, 1u32);
        assert_eq!(driver.active_entries().await, 1, "目标存活时条目应在表");

        drop(rx);
        let retired = tokio::time::timeout(Duration::from_secs(1), async {
            loop {
                if driver.active_entries().await == 0 {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await;
        assert!(retired.is_ok(), "目标关闭后周期条目必须退场(1s 内)");
    }

    /// 回归:持续背压下的丢弃告警必须按窗口节流 —— 否则每拍一条 warn,
    /// 1ms 钳制间隔或高频周期下可达约 1000 条/s 的日志洪泛。
    ///
    /// 验证:①首个窗口内至多 1 条 warn;
    /// ②窗口滚动后汇总告警携带窗口内累计丢弃数。
    #[test]
    fn interval_drop_warn_is_rate_limited() {
        /// 累积日志文本的线程安全 writer。
        #[derive(Clone)]
        struct Buf(Arc<std::sync::Mutex<Vec<u8>>>);
        impl Buf {
            fn text(&self) -> String {
                String::from_utf8_lossy(&self.0.lock().unwrap()).into_owned()
            }
        }
        impl std::io::Write for Buf {
            fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
                self.0.lock().unwrap().extend_from_slice(data);
                Ok(data.len())
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }
        impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Buf {
            type Writer = Buf;
            fn make_writer(&'a self) -> Buf {
                self.clone()
            }
        }

        let buf = Buf(Arc::new(std::sync::Mutex::new(Vec::new())));
        let subscriber = tracing_subscriber::fmt()
            .with_writer(buf.clone())
            .with_ansi(false)
            .with_max_level(tracing::Level::WARN)
            .finish();
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();

        tracing::subscriber::with_default(subscriber, || {
            rt.block_on(async {
                let driver = driver();
                let (tx, mut rx) = mpsc::channel::<u32>(1);
                tx.try_send(0).expect("预占满唯一槽位");
                let _h = driver.schedule_interval(Duration::from_millis(5), tx, 7u32);

                // 阶段一:300ms 持续背压(约 60 拍)—— 仅首拍应告警;
                // 按"速率"断言(条数 ≤ 秒数+1),CPU 竞争下不误报
                let t0 = tokio::time::Instant::now();
                tokio::time::sleep(Duration::from_millis(300)).await;
                let first_window = buf.text().matches("周期消息投递失败").count();
                assert!(first_window >= 1, "背压丢弃必须至少告警一次");
                assert!(
                    first_window as u64 <= t0.elapsed().as_secs() + 2,
                    "首窗口内背压告警必须按窗口节流(旧实现 ~60 条/300ms),实际 {first_window}"
                );

                // 阶段二:腾出槽位(恢复一拍)后继续背压,跨过节流窗口 ——
                // 必须出现携带累计丢弃数的汇总告警
                assert_eq!(rx.recv().await, Some(0), "取走预占消息腾出槽位");
                tokio::time::sleep(Duration::from_millis(900)).await;
                let logs = buf.text();
                let total = logs.matches("周期消息投递失败").count();
                assert!(
                    logs.contains("累计丢弃"),
                    "窗口滚动后的告警必须携带累计丢弃数;实际日志:{logs}"
                );
                assert!(
                    total as u64 <= t0.elapsed().as_secs() + 2,
                    "整段(1.2s 量级)warn 必须被窗口节流(旧实现 ~240 条),实际 {total}"
                );
            });
        });
    }

    /// 回归:极端 `Duration`(`Duration::MAX`)入参不得溢出 panic ——
    /// deadline 由 `deadline_after` 钳制为远期时刻(语义等价"永不触发")。
    #[tokio::test]
    async fn extreme_duration_does_not_panic() {
        let driver = driver();
        let (tx, _rx) = mpsc::channel::<u32>(8);
        let h = driver.schedule_message(Duration::MAX, tx.clone(), 1u32);
        h.reset(Duration::MAX);
        let _ = driver.schedule_interval(Duration::MAX, tx.clone(), 2u32);
        let _ = driver.schedule_watchdog(
            tokio::time::Instant::now(),
            Arc::new(AtomicU64::new(u64::MAX - 1)),
            Duration::MAX,
            tx,
            3u32,
        );
    }

    /// 回归:零间隔钳制为 1ms —— 否则零间隔等价驱动忙循环
    /// (每拍立即到点重入堆,仅靠邮箱背压限速,空邮箱时纯自旋)。
    /// 验证:条目未被拒绝创建、触发频率被限频、且驱动继续服务其他定时器。
    ///
    /// 下限只断言"仍在触发"(≥1 拍)而不绑定具体拍数:拍数同时受
    /// CPU 调度份额影响(弱时钟语义不追平错过周期),CPU 竞争下
    /// 1ms 间隔也可能只兑现个位数拍数。限频性质由上限、条目存活与
    /// 收尾的响应性断言共同守住。
    #[tokio::test]
    async fn zero_interval_is_clamped_and_driver_stays_responsive() {
        let driver = driver();
        let (tx, mut rx) = mpsc::channel::<u32>(64);
        let h = driver.schedule_interval(Duration::ZERO, tx.clone(), 7u32);
        assert_eq!(driver.active_entries().await, 1, "钳制而非拒绝:条目应在表");

        // 150ms 窗口内主动抽干:未钳制的忙循环会投递数量级更多的帧
        // (唯一区别即续期间隔)
        let mut ticks = 0usize;
        let deadline = tokio::time::Instant::now() + Duration::from_millis(150);
        while tokio::time::Instant::now() < deadline {
            if tokio::time::timeout(Duration::from_millis(20), rx.recv())
                .await
                .is_ok()
            {
                ticks += 1;
            }
        }
        assert!(ticks >= 1, "钳制后周期条目必须仍在触发,实际 {ticks} 拍");
        assert!(
            ticks <= 1000,
            "零间隔必须被钳制限频(150ms 窗口 1ms 间隔约 150 拍;忙循环为数千+),实际 {ticks} 拍"
        );

        // 驱动仍照常服务其他定时器(未陷入自旋导致常规投递失约)
        h.cancel();
        let (tx2, mut rx2) = mpsc::channel::<u32>(8);
        let _ = driver.schedule_message(Duration::from_millis(20), tx2, 42u32);
        let got = tokio::time::timeout(Duration::from_secs(1), rx2.recv()).await;
        assert_eq!(got.ok().flatten(), Some(42), "驱动必须保持响应");
        assert_eq!(driver.active_entries().await, 0, "取消后无残留条目");
    }
}