Skip to main content

wordval_actor/
timer.rs

1//! 定时器 —— 全局单一驱动任务,所有 `schedule_*` 复用一条 tokio 任务。
2//!
3//! 采用"活跃条目表(HashMap)+ 到期键最小堆"结构:
4//! - 条目表只保存活跃定时器,`cancel` / `reset` 即时生效、零残留;
5//!   周期条目在目标 Actor 最终退出(接收端关闭)后自动退场;
6//! - 堆中因 reset/cancel 过期的键在弹出时按 ticket 惰性淘汰;
7//! - 看门狗走 `TimerDriver::schedule_watchdog`:deadline 存共享原子量,
8//!   喂狗一次原子写完成滑动(零跨任务命令、零驱动唤醒),驱动到点先
9//!   exchange 接管触发权再重读 deadline,被推进则按新值重新入堆不触发。
10//! - 动作 panic 隔离:驱动是全局单点,单个动作内 panic(周期消息
11//!   `Clone`、投递路径等用户代码)只移除该条目并记 error,驱动继续运行。
12//!
13//! 时间源抽象为 [`Clock`],默认走 `tokio::time`(测试可注入手动时钟)。
14
15use futures_core::future::BoxFuture;
16use std::cmp::Ordering;
17use std::collections::{BinaryHeap, HashMap};
18use std::sync::atomic::{AtomicBool, AtomicU64, Ordering as AtomicOrdering};
19use std::sync::Arc;
20use std::time::Duration;
21use tokio::sync::mpsc;
22
23/// 周期定时器的间隔下限:零间隔会让驱动忙循环(每拍立即到点重入堆,
24/// 仅靠邮箱背压限速 —— 空邮箱时纯自旋烧 CPU),钳制到此值并记 warn。
25const MIN_INTERVAL: Duration = Duration::from_millis(1);
26
27/// 周期条目背压丢弃告警的节流窗口:丢弃/恢复两类告警共用同一窗口,
28/// 保证**至多每秒一条 warn**。持续背压(卡死 Actor + 心跳)与窗口内
29/// 振荡背压都不会洪泛日志;窗口内的丢弃数随汇总告警一并给出。
30const DROP_WARN_WINDOW: Duration = Duration::from_secs(1);
31
32/// 背压告警节流判定:距上次告警 ≥ [`DROP_WARN_WINDOW`](或从未告警)时
33/// 返回 true 并推进 `last`;否则调用方降级为 debug。
34fn warn_due(last: &mut Option<tokio::time::Instant>, now: tokio::time::Instant) -> bool {
35    if last.map_or(true, |t| now.saturating_duration_since(t) >= DROP_WARN_WINDOW) {
36        *last = Some(now);
37        true
38    } else {
39        false
40    }
41}
42
43/// 时间源抽象 —— 默认为 [`TokioClock`]。
44///
45/// 抽象出 `now + sleep_until` 两个原语即可驱动整个定时器堆;
46/// 测试中可注入手动推进的虚拟时钟(配合
47/// [`ActorSystem::with_clock`](crate::ActorSystem::with_clock))。
48pub trait Clock: Send + Sync {
49    /// 当前时刻。
50    fn now(&self) -> tokio::time::Instant;
51
52    /// 等待到指定时刻。
53    fn sleep_until(&self, when: tokio::time::Instant) -> BoxFuture<'static, ()>;
54}
55
56/// 基于 `tokio::time` 的默认时钟。
57#[derive(Debug, Clone, Copy)]
58pub struct TokioClock;
59
60impl Clock for TokioClock {
61    fn now(&self) -> tokio::time::Instant {
62        tokio::time::Instant::now()
63    }
64
65    fn sleep_until(&self, when: tokio::time::Instant) -> BoxFuture<'static, ()> {
66        Box::pin(tokio::time::sleep_until(when))
67    }
68}
69
70/// 系统时钟源 —— 默认 tokio 实时钟,或注入的自定义 [`Clock`](虚拟时间测试)。
71///
72/// 默认分支的 `sleep_until` 生成栈上 future:ask 超时等热路径零装箱;
73/// 仅自定义时钟分支经 [`Clock::sleep_until`] 走装箱分发(测试专用,冷路径)。
74#[derive(Clone)]
75pub(crate) enum ClockSource {
76    Tokio,
77    Custom(Arc<dyn Clock>),
78}
79
80impl ClockSource {
81    #[inline]
82    pub(crate) fn now(&self) -> tokio::time::Instant {
83        match self {
84            Self::Tokio => tokio::time::Instant::now(),
85            Self::Custom(c) => c.now(),
86        }
87    }
88
89    #[inline]
90    pub(crate) async fn sleep_until(&self, when: tokio::time::Instant) {
91        match self {
92            Self::Tokio => tokio::time::sleep_until(when).await,
93            Self::Custom(c) => c.sleep_until(when).await,
94        }
95    }
96}
97
98/// 定时任务句柄 —— 支持显式取消与滑动重置;句柄析构不会自动取消。
99#[derive(Clone)]
100pub struct TimerHandle {
101    id: u64,
102    tx: mpsc::UnboundedSender<Cmd>,
103    clock: ClockSource,
104    /// 本地意图标记:`cancel()` 立即置位(`is_cancelled` 查询无需等驱动)。
105    cancelled: Arc<AtomicBool>,
106    /// 触发标记:驱动执行到点动作前置位;仅 once 任务具备(interval 为 None)。
107    fired: Option<Arc<AtomicBool>>,
108}
109
110impl std::fmt::Debug for TimerHandle {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        f.debug_struct("TimerHandle")
113            .field("id", &self.id)
114            .field("cancelled", &self.cancelled.load(AtomicOrdering::Relaxed))
115            .field("fired", &self.has_fired())
116            .finish()
117    }
118}
119
120impl TimerHandle {
121    /// 取消该定时任务(对已触发的 once 任务为 no-op)。
122    pub fn cancel(&self) {
123        self.cancelled.store(true, AtomicOrdering::Relaxed);
124        let _ = self.tx.send(Cmd::Cancel { id: self.id });
125    }
126
127    /// 是否已取消(反映调用方意图,不反映驱动侧实际状态)。
128    pub fn is_cancelled(&self) -> bool {
129        self.cancelled.load(AtomicOrdering::Relaxed)
130    }
131
132    /// 该 once 任务是否已触发。
133    ///
134    /// 触发标记在驱动执行到点动作**之前**置位,且 Actor 事件循环
135    /// 单线程消费消息,因此“触发后首批消息先于定时消息被处理”
136    /// 不可能发生 —— 该查询在 Actor 上下文内无竞态。
137    /// 周期任务恒返回 false(无单次触发语义)。
138    pub fn has_fired(&self) -> bool {
139        self.fired
140            .as_ref()
141            .is_some_and(|f| f.load(AtomicOrdering::Relaxed))
142    }
143
144    /// 滑动 deadline:从现在起重新等待 `delay`。对已触发/已取消的任务为 no-op。
145    ///
146    /// 复用既有条目:驱动内活跃条目保持 O(1),不产生已取消条目残留。
147    /// 代价是每次调用向驱动投递一条重置命令(跨任务发送 + 堆插入 +
148    /// 唤醒驱动)。
149    ///
150    /// 高频滑动(如每帧喂狗,100–1000Hz)请改用
151    /// [`ActorContext::watchdog`](crate::ActorContext::watchdog):其滑动
152    /// 走共享原子 deadline,零跨任务命令、零驱动唤醒。
153    pub fn reset(&self, delay: Duration) {
154        let deadline = deadline_after(self.clock.now(), delay);
155        let _ = self.tx.send(Cmd::Reset { id: self.id, deadline });
156    }
157}
158
159/// 看门狗共享原子 deadline 的"已被驱动接管触发权"哨兵值。
160pub(crate) const WATCHDOG_FIRED: u64 = u64::MAX;
161
162/// 计算以 `base` 为基准的 deadline 相对纳秒数(喂狗滑动与驱动
163/// 重读共用的时间表示;时钟回拨时钳制为 0)。
164///
165/// 饱和上界取 `u64::MAX - 1`,为 [`WATCHDOG_FIRED`] 哨兵值保留 `u64::MAX`。
166pub(crate) fn rel_nanos(base: tokio::time::Instant, deadline: tokio::time::Instant) -> u64 {
167    deadline
168        .checked_duration_since(base)
169        .map_or(0, |d| d.as_nanos().min((u64::MAX - 1) as u128) as u64)
170}
171
172/// 溢出安全 deadline:等价于 `now + d`,但极端 `Duration`(如
173/// `Duration::MAX`)下 `Instant::add` 会溢出 panic —— 此时钳制为远期
174/// 时刻(30 年上界,与 tokio 内部 `far_future` 取同值:更长的上界在
175/// macOS/FreeBSD 等平台的 Instant 表示范围下仍可能溢出),语义等价于
176/// "永不触发",实际取消/停止由各控制路径(stop / disarm / cancel)兜底。
177pub(crate) fn deadline_after(now: tokio::time::Instant, d: Duration) -> tokio::time::Instant {
178    const FAR_FUTURE: Duration = Duration::from_secs(86400 * 365 * 30);
179    now.checked_add(d)
180        .or_else(|| now.checked_add(FAR_FUTURE))
181        .unwrap_or(now)
182}
183
184/// 堆键:到期时间升序(反向 Ord 让堆顶为最早到期)。
185#[derive(Debug, Clone, Copy)]
186struct Key {
187    deadline: tokio::time::Instant,
188    id: u64,
189    /// 条目版本票号:reset/cancel 后旧键弹出时按此淘汰。
190    ticket: u64,
191}
192
193impl PartialEq for Key {
194    fn eq(&self, other: &Self) -> bool {
195        self.deadline == other.deadline && self.ticket == other.ticket
196    }
197}
198
199impl Eq for Key {}
200
201impl PartialOrd for Key {
202    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
203        Some(self.cmp(other))
204    }
205}
206
207impl Ord for Key {
208    fn cmp(&self, other: &Self) -> Ordering {
209        // 反转 deadline 比较:堆顶为最早到期;ticket 反转保证同
210        // deadline 下先注册/先重置者先触发(先到先触发)。
211        other
212            .deadline
213            .cmp(&self.deadline)
214            .then_with(|| other.ticket.cmp(&self.ticket))
215    }
216}
217
218/// 到点动作单次执行结果。
219enum Step {
220    /// 本次动作完结,按此时刻重新入堆(看门狗滑动竞态复核 / 周期续期)。
221    RequeueAt(tokio::time::Instant),
222    /// 任务完结,条目移除(once 触发完毕 / 周期目标已停止)。
223    Done,
224}
225
226/// 活跃定时器条目。
227struct Entry {
228    deadline: tokio::time::Instant,
229    ticket: u64,
230    /// 到点动作。返回 [`Step::RequeueAt`] 表示按新时刻重新入堆;
231    /// [`Step::Done`] 表示条目移除,驱动不再为其唤醒。
232    action: Box<dyn FnMut() -> Step + Send>,
233}
234
235enum Cmd {
236    Add { id: u64, entry: Entry },
237    Reset { id: u64, deadline: tokio::time::Instant },
238    Cancel { id: u64 },
239    /// 测试专用:查询活跃条目数(驱动 round-trip)。
240    #[cfg(test)]
241    Count(tokio::sync::oneshot::Sender<usize>),
242}
243
244/// 定时器驱动 —— Clone,内部共享同一条驱动任务。
245#[derive(Clone)]
246pub struct TimerDriver {
247    tx: mpsc::UnboundedSender<Cmd>,
248    clock: ClockSource,
249    next_id: Arc<AtomicU64>,
250}
251
252impl TimerDriver {
253    /// 启动驱动任务。所有克隆共享此任务;
254    /// 全部克隆被丢弃后驱动任务自然退出。
255    pub(crate) fn spawn(clock: ClockSource) -> Self {
256        let (tx, rx) = mpsc::unbounded_channel();
257        Self {
258            tx,
259            clock,
260            next_id: Arc::new(AtomicU64::new(0)),
261        }
262        .attach(rx)
263    }
264
265    fn attach(self, rx: mpsc::UnboundedReceiver<Cmd>) -> Self {
266        let clock = self.clock.clone();
267        tokio::spawn(async move { run(clock, rx).await });
268        self
269    }
270
271    /// 测试专用:当前活跃条目数(驱动 round-trip,读值保证与驱动顺序一致)。
272    #[cfg(test)]
273    pub(crate) async fn active_entries(&self) -> usize {
274        let (tx, rx) = tokio::sync::oneshot::channel();
275        let _ = self.tx.send(Cmd::Count(tx));
276        rx.await.expect("定时器驱动应存活")
277    }
278
279    /// 注册一条到点执行的定时任务(内部原语)。
280    fn add(
281        &self,
282        deadline: tokio::time::Instant,
283        action: Box<dyn FnMut() -> Step + Send>,
284    ) -> TimerHandle {
285        let id = self.next_id.fetch_add(1, AtomicOrdering::Relaxed);
286        let _ = self.tx.send(Cmd::Add {
287            id,
288            entry: Entry {
289                deadline,
290                ticket: 0,
291                action,
292            },
293        });
294        TimerHandle {
295            id,
296            tx: self.tx.clone(),
297            clock: self.clock.clone(),
298            cancelled: Arc::new(AtomicBool::new(false)),
299            fired: None,
300        }
301    }
302
303    /// 一次性延迟投递:`delay` 后将 `payload` 投入 `ctl` 通道。
304    ///
305    /// 投递语义:**once 消息不丢弃**。触发瞬间邮箱满(瞬时背压)时
306    /// 转为异步等待空位补投(失控保护类消息必须送达);仅当目标
307    /// 已停止(通道关闭)才静默丢弃。
308    pub fn schedule_message<E: Send + 'static>(
309        &self,
310        delay: Duration,
311        ctl: mpsc::Sender<E>,
312        payload: E,
313    ) -> TimerHandle {
314        let deadline = deadline_after(self.clock.now(), delay);
315        let mut payload = Some(payload);
316        let fired = Arc::new(AtomicBool::new(false));
317        let fired_flag = Arc::clone(&fired);
318        let action = Box::new(move || -> Step {
319            // 先置位再投递:调用方经 has_fired() 感知触发,与消息送达顺序一致
320            fired_flag.store(true, AtomicOrdering::Relaxed);
321            let Some(m) = payload.take() else {
322                return Step::Done;
323            };
324            match ctl.try_send(m) {
325                Ok(()) => {}
326                Err(mpsc::error::TrySendError::Closed(_)) => {
327                    tracing::debug!("定时消息投递失败:目标已停止,已丢弃");
328                }
329                Err(mpsc::error::TrySendError::Full(frame)) => {
330                    // once 消息(如链路看门狗 LinkLost)不得因瞬时背压
331                    // 丢失:转为异步阻塞投递,等待邮箱空位
332                    let ctl = ctl.clone();
333                    tokio::spawn(async move {
334                        if ctl.send(frame).await.is_err() {
335                            tracing::debug!("定时消息异步补投失败:目标已停止,已丢弃");
336                        }
337                    });
338                }
339            }
340            Step::Done
341        });
342        let mut handle = self.add(deadline, action);
343        handle.fired = Some(fired);
344        handle
345    }
346
347    /// 周期投递:每隔 `interval` 克隆投入一条 `payload`。
348    ///
349    /// 投递语义:周期 tick 允许丢拍(下一周期自愈);触发时邮箱满
350    /// 丢弃本拍并记日志(告警节流:至多每秒一条 warn,窗口内丢弃数
351    /// 随汇总告警给出,其余降为 debug)。
352    /// 目标 Actor 最终退出(接收端关闭,非重启瞬时状态)后条目
353    /// **自动退场** —— 死条目不再按周期唤醒驱动,连接重建类场景不累积。
354    ///
355    /// `interval` 为零会退化为驱动忙循环(每拍立即到点重入堆,仅靠
356    /// 邮箱背压限速),钳制为 1ms 并记 warn。
357    pub fn schedule_interval<E: Send + Clone + 'static>(
358        &self,
359        interval: Duration,
360        ctl: mpsc::Sender<E>,
361        payload: E,
362    ) -> TimerHandle {
363        // 静默忙循环比显式限频更糟,直接拒绝创建又破坏调用方对返回
364        // 句柄的假设 —— 钳到 1ms 并 warn 是最小惊讶选择(1ms 已远高于
365        // 常规轮询需求的高频)
366        let interval = if interval.is_zero() {
367            tracing::warn!("周期定时器间隔为 0(等价驱动忙循环),已钳制为 {MIN_INTERVAL:?}");
368            MIN_INTERVAL
369        } else {
370            interval
371        };
372        let deadline = deadline_after(self.clock.now(), interval);
373        let action_clock = self.clock.clone();
374        // 背压日志节流状态:丢弃与恢复告警共用 last_warn 窗口
375        let mut dropped: u64 = 0;
376        let mut last_warn: Option<tokio::time::Instant> = None;
377        let action = Box::new(move || -> Step {
378            match ctl.try_send(payload.clone()) {
379                Ok(()) => {
380                    if dropped > 0 {
381                        // 恢复汇总:窗口内累计丢弃数一次性给出
382                        let now = action_clock.now();
383                        if warn_due(&mut last_warn, now) {
384                            tracing::warn!(dropped, "周期消息投递恢复:背压窗口内累计丢弃 {dropped} 拍");
385                        } else {
386                            tracing::debug!(dropped, "周期消息投递恢复:背压窗口内累计丢弃 {dropped} 拍");
387                        }
388                        dropped = 0;
389                    }
390                }
391                Err(mpsc::error::TrySendError::Closed(_)) => {
392                    tracing::debug!("周期消息目标已停止,定时条目退场");
393                    return Step::Done;
394                }
395                Err(mpsc::error::TrySendError::Full(_)) => {
396                    dropped += 1;
397                    let now = action_clock.now();
398                    if warn_due(&mut last_warn, now) {
399                        tracing::warn!(dropped, "周期消息投递失败:邮箱满,本窗口累计丢弃 {dropped} 拍(下一周期自愈)");
400                    } else {
401                        tracing::debug!(dropped, "周期消息投递失败:邮箱满,本拍已丢弃(窗口内告警已节流)");
402                    }
403                }
404            }
405            Step::RequeueAt(deadline_after(action_clock.now(), interval))
406        });
407        self.add(deadline, action)
408    }
409
410    /// 看门狗专用一次性定时:滑动 deadline 存共享原子量
411    /// `deadline_ns`(距 `base` 的纳秒数,喂狗侧原子更新)。
412    ///
413    /// 到点时驱动先 `swap` 哨兵接管触发权,再核对 deadline:
414    /// - 已被并发喂狗推向未来 → 不触发,按最新 deadline 重新入堆
415    ///   (无投递、无唤醒风暴);喂狗与触发的任何交错都以该原子值
416    ///   为线性化点,恰好一方胜出 —— 不存在"已滑动仍误报"的窗口;
417    /// - 确已到期 → 置位触发标记并投递 `payload`(满邮箱异步补投,
418    ///   语义同 [`schedule_message`])。
419    pub(crate) fn schedule_watchdog<E: Send + 'static>(
420        &self,
421        base: tokio::time::Instant,
422        deadline_ns: Arc<AtomicU64>,
423        delay: Duration,
424        ctl: mpsc::Sender<E>,
425        payload: E,
426    ) -> TimerHandle {
427        let action_clock = self.clock.clone();
428        let fired = Arc::new(AtomicBool::new(false));
429        let fired_flag = Arc::clone(&fired);
430        let mut payload = Some(payload);
431        let action = Box::new(move || -> Step {
432            // 先以 exchange 独占触发权,再核对 deadline:喂狗与触发
433            // 的任何交错都恰好一方胜出
434            let claimed = deadline_ns.swap(WATCHDOG_FIRED, AtomicOrdering::AcqRel);
435            let now_rel = rel_nanos(base, action_clock.now());
436            if claimed > now_rel {
437                // deadline 已被并发喂狗推进:本按不触发。恢复非哨兵值
438                // (若期间又有新 store 则以最新为准),按最新 deadline 重入堆
439                let cur = deadline_ns.load(AtomicOrdering::Acquire);
440                let requeue_rel = if cur == WATCHDOG_FIRED {
441                    claimed
442                } else {
443                    cur.max(claimed)
444                };
445                let _ = deadline_ns.compare_exchange(
446                    WATCHDOG_FIRED,
447                    requeue_rel,
448                    AtomicOrdering::AcqRel,
449                    AtomicOrdering::Acquire,
450                );
451                return Step::RequeueAt(deadline_after(base, Duration::from_nanos(requeue_rel)));
452            }
453            // 真实触发:先置位再投递,与 has_fired() 感知顺序一致
454            fired_flag.store(true, AtomicOrdering::Release);
455            let Some(p) = payload.take() else {
456                return Step::Done;
457            };
458            match ctl.try_send(p) {
459                Ok(()) => {}
460                Err(mpsc::error::TrySendError::Closed(_)) => {
461                    tracing::debug!("看门狗触发投递失败:目标已停止,已丢弃");
462                }
463                Err(mpsc::error::TrySendError::Full(frame)) => {
464                    // 失控保护消息不得因瞬时背压丢失:异步补投等空位
465                    let ctl = ctl.clone();
466                    tokio::spawn(async move {
467                        if ctl.send(frame).await.is_err() {
468                            tracing::debug!("看门狗触发异步补投失败:目标已停止,已丢弃");
469                        }
470                    });
471                }
472            }
473            Step::Done
474        });
475        let mut handle = self.add(deadline_after(self.clock.now(), delay), action);
476        handle.fired = Some(fired);
477        handle
478    }
479}
480
481/// 应用一条驱动命令(抽干阶段与 select 唤醒阶段共用)。
482fn apply(
483    cmd: Cmd,
484    entries: &mut HashMap<u64, Entry>,
485    heap: &mut BinaryHeap<Key>,
486    next_ticket: &mut u64,
487) {
488    match cmd {
489        Cmd::Add { id, mut entry } => {
490            let ticket = *next_ticket;
491            *next_ticket += 1;
492            entry.ticket = ticket;
493            heap.push(Key {
494                deadline: entry.deadline,
495                id,
496                ticket,
497            });
498            entries.insert(id, entry);
499        }
500        Cmd::Reset { id, deadline } => {
501            // 已触发/已取消的条目不存在:reset 为 no-op
502            if let Some(e) = entries.get_mut(&id) {
503                let ticket = *next_ticket;
504                *next_ticket += 1;
505                e.deadline = deadline;
506                e.ticket = ticket;
507                heap.push(Key { deadline, id, ticket });
508            }
509        }
510        Cmd::Cancel { id } => {
511            entries.remove(&id); // 堆中残留键弹出时按 ticket 淘汰
512        }
513        #[cfg(test)]
514        Cmd::Count(reply) => {
515            let _ = reply.send(entries.len());
516        }
517    }
518}
519
520async fn run(clock: ClockSource, mut rx: mpsc::UnboundedReceiver<Cmd>) {
521    let mut entries: HashMap<u64, Entry> = HashMap::new();
522    let mut heap: BinaryHeap<Key> = BinaryHeap::new();
523    let mut next_ticket: u64 = 0;
524    loop {
525        // 抽干注册命令
526        while let Ok(cmd) = rx.try_recv() {
527            apply(cmd, &mut entries, &mut heap, &mut next_ticket);
528        }
529        // 堆膨胀控制:reset/cancel 的过期键只在弹出时惰性淘汰,高频
530        // reset(如 1000Hz 看门狗)会让堆相对活跃条目持续膨胀。过期键
531        // 超过活跃条目两倍(且越过底噪阈值)时按条目表 O(n) 重建压缩。
532        if heap.len() > entries.len().saturating_mul(2).saturating_add(64) {
533            heap = entries
534                .iter()
535                .map(|(&id, e)| Key {
536                    deadline: e.deadline,
537                    id,
538                    ticket: e.ticket,
539                })
540                .collect();
541        }
542        // 触发所有到期任务
543        let now = clock.now();
544        while let Some(key) = heap.peek().copied() {
545            if key.deadline > now {
546                break;
547            }
548            heap.pop();
549            let Some(e) = entries.get_mut(&key.id) else {
550                continue; // 已取消
551            };
552            if e.ticket != key.ticket {
553                continue; // 过期键:已被 reset/cancel 取代
554            }
555            // 捕获动作 panic:驱动是全局单点(所有定时器/看门狗共用),
556            // 单个动作内跑到的用户代码(周期消息 Clone、投递时的 tokio::spawn)
557            // panic 不得炸毁驱动 —— 否则全部看门狗静默失效。panic 条目移除,
558            // 驱动继续服务其余定时器。
559            let action_result =
560                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (e.action)()));
561            let step = match action_result {
562                Ok(step) => step,
563                Err(_) => {
564                    tracing::error!(timer = key.id, "定时器动作 panic,已移除该条目(驱动继续运行)");
565                    entries.remove(&key.id);
566                    continue;
567                }
568            };
569            match step {
570                Step::RequeueAt(next) => {
571                    // 看门狗滑动竞态复核 / 周期续期:按新时刻重新入堆
572                    e.deadline = next;
573                    let ticket = next_ticket;
574                    next_ticket += 1;
575                    e.ticket = ticket;
576                    heap.push(Key {
577                        deadline: next,
578                        id: key.id,
579                        ticket,
580                    });
581                }
582                Step::Done => {
583                    // once 触发完毕 / 周期目标已停止:条目退场,不再唤醒驱动
584                    entries.remove(&key.id);
585                }
586            }
587        }
588        // 等待下一个到期或新注册(堆顶键可能因 reset 过期而提前唤醒,无害)
589        match heap.peek().map(|k| k.deadline) {
590            Some(when) => {
591                tokio::select! {
592                    cmd = rx.recv() => match cmd {
593                        Some(cmd) => apply(cmd, &mut entries, &mut heap, &mut next_ticket),
594                        None => break,
595                    },
596                    _ = clock.sleep_until(when) => {}
597                }
598            }
599            None => match rx.recv().await {
600                Some(cmd) => apply(cmd, &mut entries, &mut heap, &mut next_ticket),
601                None => break,
602            },
603        }
604    }
605    tracing::debug!("定时器驱动退出(全部句柄已释放)");
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611
612    fn driver() -> TimerDriver {
613        TimerDriver::spawn(ClockSource::Tokio)
614    }
615
616    #[tokio::test]
617    async fn once_fires_then_stops() {
618        let driver = driver();
619        let (tx, mut rx) = mpsc::channel::<u32>(8);
620        let _h = driver.schedule_message(Duration::from_millis(10), tx.clone(), 42u32);
621        let msg = tokio::time::timeout(Duration::from_secs(1), rx.recv())
622            .await
623            .expect("应在 1s 内触发")
624            .expect("收到帧");
625        assert_eq!(msg, 42);
626        // once 不再触发第二次
627        assert!(tokio::time::timeout(Duration::from_millis(50), rx.recv())
628            .await
629            .is_err());
630    }
631
632    #[tokio::test]
633    async fn interval_fires_repeatedly() {
634        let driver = driver();
635        let (tx, mut rx) = mpsc::channel::<u32>(8);
636        let h = driver.schedule_interval(Duration::from_millis(10), tx.clone(), 7u32);
637        for _ in 0..3 {
638            let m = tokio::time::timeout(Duration::from_secs(1), rx.recv())
639                .await
640                .expect("周期触发")
641                .expect("帧");
642            assert_eq!(m, 7);
643        }
644        h.cancel();
645        assert!(h.is_cancelled());
646        // 取消后不再触发
647        assert!(tokio::time::timeout(Duration::from_millis(60), rx.recv())
648            .await
649            .is_err());
650    }
651
652    #[tokio::test]
653    async fn earlier_deadline_wakes_driver() {
654        // 驱动先空闲等待远期任务,随后插入一条近期任务应被准点触发
655        let driver = driver();
656        let (tx, mut rx) = mpsc::channel::<u8>(8);
657        let _far = driver.schedule_message(Duration::from_secs(3600), tx.clone(), 1u8);
658        let _near = driver.schedule_message(Duration::from_millis(20), tx.clone(), 2u8);
659        let mut got = None;
660        for _ in 0..2 {
661            if let Ok(Some(v)) = tokio::time::timeout(Duration::from_secs(1), rx.recv())
662                .await
663            {
664                if v == 2 {
665                    got = Some(v);
666                    break;
667                }
668            }
669        }
670        assert_eq!(got, Some(2));
671    }
672
673    #[tokio::test]
674    async fn reset_delays_fire() {
675        // 看门狗滑动语义:reset 推迟触发时刻
676        let driver = driver();
677        let (tx, mut rx) = mpsc::channel::<u32>(8);
678        let h = driver.schedule_message(Duration::from_millis(60), tx.clone(), 1u32);
679        tokio::time::sleep(Duration::from_millis(20)).await;
680        h.reset(Duration::from_millis(120));
681        // 原 deadline 已过但被 reset 推迟:此刻不应触发
682        assert!(
683            tokio::time::timeout(Duration::from_millis(80), rx.recv())
684                .await
685                .is_err(),
686            "reset 后不应按原 deadline 触发"
687        );
688        let msg = tokio::time::timeout(Duration::from_secs(1), rx.recv())
689            .await
690            .expect("应在重置后的 deadline 触发");
691        assert_eq!(msg, Some(1));
692    }
693
694    #[tokio::test]
695    async fn repeated_reset_keeps_single_fire() {
696        // 高频 reset(1000Hz 看门狗模式)只应触发一次,且不重复投递
697        let driver = driver();
698        let (tx, mut rx) = mpsc::channel::<u32>(8);
699        let h = driver.schedule_message(Duration::from_millis(50), tx.clone(), 9u32);
700        for _ in 0..10 {
701            tokio::time::sleep(Duration::from_millis(10)).await;
702            h.reset(Duration::from_millis(50));
703        }
704        let msg = tokio::time::timeout(Duration::from_secs(1), rx.recv())
705            .await
706            .expect("停止 reset 后应触发");
707        assert_eq!(msg, Some(9));
708        // 且仅触发一次
709        assert!(
710            tokio::time::timeout(Duration::from_millis(80), rx.recv())
711                .await
712                .is_err(),
713            "repeated reset 不得产生多次触发"
714        );
715    }
716
717    #[tokio::test]
718    async fn once_message_survives_full_mailbox() {
719        // 契约:once 定时消息触发瞬间邮箱满时,转为异步补投而非丢弃
720        let driver = driver();
721        let (tx, mut rx) = mpsc::channel::<u32>(1);
722        tx.try_send(0).expect("占满唯一槽位");
723        let _h = driver.schedule_message(Duration::from_millis(10), tx.clone(), 7u32);
724        // 定时器在 10ms 触发时邮箱仍满 → 异步补投挂起;30ms 后腾出空位
725        tokio::time::sleep(Duration::from_millis(30)).await;
726        assert_eq!(rx.recv().await, Some(0));
727        let got = tokio::time::timeout(Duration::from_secs(1), rx.recv()).await;
728        assert!(
729            matches!(got, Ok(Some(7))),
730            "once 消息必须经异步补投送达,实际 {got:?}"
731        );
732    }
733
734    #[tokio::test]
735    async fn reset_after_fire_is_noop() {
736        let driver = driver();
737        let (tx, mut rx) = mpsc::channel::<u32>(8);
738        let h = driver.schedule_message(Duration::from_millis(10), tx.clone(), 5u32);
739        let _ = tokio::time::timeout(Duration::from_secs(1), rx.recv()).await;
740        // 已触发的 once 任务:reset 不应复活它
741        h.reset(Duration::from_millis(10));
742        assert!(
743            tokio::time::timeout(Duration::from_millis(80), rx.recv())
744                .await
745                .is_err(),
746            "已触发任务不得因 reset 复活"
747        );
748    }
749
750    /// 回归:单个定时器动作内 panic(周期消息的 `Clone` 是用户代码)
751    /// 不得炸毁全局驱动 —— 其余定时器必须照常触发。
752    #[tokio::test]
753    async fn panicking_action_does_not_kill_driver() {
754        struct Bomb;
755        impl Clone for Bomb {
756            fn clone(&self) -> Self {
757                panic!("clone bomb")
758            }
759        }
760        let driver = driver();
761        let (tx, mut rx) = mpsc::channel::<u32>(8);
762        let (bomb_tx, _bomb_rx) = mpsc::channel::<Bomb>(8);
763        // 5ms 处周期条目动作 panic(clone 炸弹),10ms 处的正常条目必须存活
764        let _bomb = driver.schedule_interval(Duration::from_millis(5), bomb_tx, Bomb);
765        let _ok = driver.schedule_message(Duration::from_millis(10), tx, 42u32);
766        let msg = tokio::time::timeout(Duration::from_secs(1), rx.recv())
767            .await
768            .expect("驱动必须存活:其余定时器应在 1s 内触发")
769            .expect("收到帧");
770        assert_eq!(msg, 42, "单条定时器动作 panic 后驱动必须继续服务其余定时器");
771    }
772
773    /// 回归:周期条目在目标 Actor 最终退出(接收端关闭)后必须退场 ——
774    /// 死条目不得在驱动内无上界累积,也不得每拍空醒驱动
775    /// (连接重建类场景每会话一个 interval)。
776    #[tokio::test]
777    async fn interval_entry_retires_when_target_closed() {
778        let driver = driver();
779        let (tx, rx) = mpsc::channel::<u32>(8);
780        let _h = driver.schedule_interval(Duration::from_millis(5), tx, 1u32);
781        assert_eq!(driver.active_entries().await, 1, "目标存活时条目应在表");
782
783        drop(rx);
784        let retired = tokio::time::timeout(Duration::from_secs(1), async {
785            loop {
786                if driver.active_entries().await == 0 {
787                    break;
788                }
789                tokio::time::sleep(Duration::from_millis(5)).await;
790            }
791        })
792        .await;
793        assert!(retired.is_ok(), "目标关闭后周期条目必须退场(1s 内)");
794    }
795
796    /// 回归:持续背压下的丢弃告警必须按窗口节流 —— 否则每拍一条 warn,
797    /// 1ms 钳制间隔或高频周期下可达约 1000 条/s 的日志洪泛。
798    ///
799    /// 验证:①首个窗口内至多 1 条 warn;
800    /// ②窗口滚动后汇总告警携带窗口内累计丢弃数。
801    #[test]
802    fn interval_drop_warn_is_rate_limited() {
803        /// 累积日志文本的线程安全 writer。
804        #[derive(Clone)]
805        struct Buf(Arc<std::sync::Mutex<Vec<u8>>>);
806        impl Buf {
807            fn text(&self) -> String {
808                String::from_utf8_lossy(&self.0.lock().unwrap()).into_owned()
809            }
810        }
811        impl std::io::Write for Buf {
812            fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
813                self.0.lock().unwrap().extend_from_slice(data);
814                Ok(data.len())
815            }
816            fn flush(&mut self) -> std::io::Result<()> {
817                Ok(())
818            }
819        }
820        impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Buf {
821            type Writer = Buf;
822            fn make_writer(&'a self) -> Buf {
823                self.clone()
824            }
825        }
826
827        let buf = Buf(Arc::new(std::sync::Mutex::new(Vec::new())));
828        let subscriber = tracing_subscriber::fmt()
829            .with_writer(buf.clone())
830            .with_ansi(false)
831            .with_max_level(tracing::Level::WARN)
832            .finish();
833        let rt = tokio::runtime::Builder::new_current_thread()
834            .enable_all()
835            .build()
836            .unwrap();
837
838        tracing::subscriber::with_default(subscriber, || {
839            rt.block_on(async {
840                let driver = driver();
841                let (tx, mut rx) = mpsc::channel::<u32>(1);
842                tx.try_send(0).expect("预占满唯一槽位");
843                let _h = driver.schedule_interval(Duration::from_millis(5), tx, 7u32);
844
845                // 阶段一:300ms 持续背压(约 60 拍)—— 仅首拍应告警;
846                // 按"速率"断言(条数 ≤ 秒数+1),CPU 竞争下不误报
847                let t0 = tokio::time::Instant::now();
848                tokio::time::sleep(Duration::from_millis(300)).await;
849                let first_window = buf.text().matches("周期消息投递失败").count();
850                assert!(first_window >= 1, "背压丢弃必须至少告警一次");
851                assert!(
852                    first_window as u64 <= t0.elapsed().as_secs() + 2,
853                    "首窗口内背压告警必须按窗口节流(旧实现 ~60 条/300ms),实际 {first_window}"
854                );
855
856                // 阶段二:腾出槽位(恢复一拍)后继续背压,跨过节流窗口 ——
857                // 必须出现携带累计丢弃数的汇总告警
858                assert_eq!(rx.recv().await, Some(0), "取走预占消息腾出槽位");
859                tokio::time::sleep(Duration::from_millis(900)).await;
860                let logs = buf.text();
861                let total = logs.matches("周期消息投递失败").count();
862                assert!(
863                    logs.contains("累计丢弃"),
864                    "窗口滚动后的告警必须携带累计丢弃数;实际日志:{logs}"
865                );
866                assert!(
867                    total as u64 <= t0.elapsed().as_secs() + 2,
868                    "整段(1.2s 量级)warn 必须被窗口节流(旧实现 ~240 条),实际 {total}"
869                );
870            });
871        });
872    }
873
874    /// 回归:极端 `Duration`(`Duration::MAX`)入参不得溢出 panic ——
875    /// deadline 由 `deadline_after` 钳制为远期时刻(语义等价"永不触发")。
876    #[tokio::test]
877    async fn extreme_duration_does_not_panic() {
878        let driver = driver();
879        let (tx, _rx) = mpsc::channel::<u32>(8);
880        let h = driver.schedule_message(Duration::MAX, tx.clone(), 1u32);
881        h.reset(Duration::MAX);
882        let _ = driver.schedule_interval(Duration::MAX, tx.clone(), 2u32);
883        let _ = driver.schedule_watchdog(
884            tokio::time::Instant::now(),
885            Arc::new(AtomicU64::new(u64::MAX - 1)),
886            Duration::MAX,
887            tx,
888            3u32,
889        );
890    }
891
892    /// 回归:零间隔钳制为 1ms —— 否则零间隔等价驱动忙循环
893    /// (每拍立即到点重入堆,仅靠邮箱背压限速,空邮箱时纯自旋)。
894    /// 验证:条目未被拒绝创建、触发频率被限频、且驱动继续服务其他定时器。
895    ///
896    /// 下限只断言"仍在触发"(≥1 拍)而不绑定具体拍数:拍数同时受
897    /// CPU 调度份额影响(弱时钟语义不追平错过周期),CPU 竞争下
898    /// 1ms 间隔也可能只兑现个位数拍数。限频性质由上限、条目存活与
899    /// 收尾的响应性断言共同守住。
900    #[tokio::test]
901    async fn zero_interval_is_clamped_and_driver_stays_responsive() {
902        let driver = driver();
903        let (tx, mut rx) = mpsc::channel::<u32>(64);
904        let h = driver.schedule_interval(Duration::ZERO, tx.clone(), 7u32);
905        assert_eq!(driver.active_entries().await, 1, "钳制而非拒绝:条目应在表");
906
907        // 150ms 窗口内主动抽干:未钳制的忙循环会投递数量级更多的帧
908        // (唯一区别即续期间隔)
909        let mut ticks = 0usize;
910        let deadline = tokio::time::Instant::now() + Duration::from_millis(150);
911        while tokio::time::Instant::now() < deadline {
912            if tokio::time::timeout(Duration::from_millis(20), rx.recv())
913                .await
914                .is_ok()
915            {
916                ticks += 1;
917            }
918        }
919        assert!(ticks >= 1, "钳制后周期条目必须仍在触发,实际 {ticks} 拍");
920        assert!(
921            ticks <= 1000,
922            "零间隔必须被钳制限频(150ms 窗口 1ms 间隔约 150 拍;忙循环为数千+),实际 {ticks} 拍"
923        );
924
925        // 驱动仍照常服务其他定时器(未陷入自旋导致常规投递失约)
926        h.cancel();
927        let (tx2, mut rx2) = mpsc::channel::<u32>(8);
928        let _ = driver.schedule_message(Duration::from_millis(20), tx2, 42u32);
929        let got = tokio::time::timeout(Duration::from_secs(1), rx2.recv()).await;
930        assert_eq!(got.ok().flatten(), Some(42), "驱动必须保持响应");
931        assert_eq!(driver.active_entries().await, 0, "取消后无残留条目");
932    }
933}