1use 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
23const MIN_INTERVAL: Duration = Duration::from_millis(1);
26
27const DROP_WARN_WINDOW: Duration = Duration::from_secs(1);
31
32fn 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
43pub trait Clock: Send + Sync {
49 fn now(&self) -> tokio::time::Instant;
51
52 fn sleep_until(&self, when: tokio::time::Instant) -> BoxFuture<'static, ()>;
54}
55
56#[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#[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#[derive(Clone)]
100pub struct TimerHandle {
101 id: u64,
102 tx: mpsc::UnboundedSender<Cmd>,
103 clock: ClockSource,
104 cancelled: Arc<AtomicBool>,
106 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 pub fn cancel(&self) {
123 self.cancelled.store(true, AtomicOrdering::Relaxed);
124 let _ = self.tx.send(Cmd::Cancel { id: self.id });
125 }
126
127 pub fn is_cancelled(&self) -> bool {
129 self.cancelled.load(AtomicOrdering::Relaxed)
130 }
131
132 pub fn has_fired(&self) -> bool {
139 self.fired
140 .as_ref()
141 .is_some_and(|f| f.load(AtomicOrdering::Relaxed))
142 }
143
144 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
159pub(crate) const WATCHDOG_FIRED: u64 = u64::MAX;
161
162pub(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
172pub(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#[derive(Debug, Clone, Copy)]
186struct Key {
187 deadline: tokio::time::Instant,
188 id: u64,
189 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 other
212 .deadline
213 .cmp(&self.deadline)
214 .then_with(|| other.ticket.cmp(&self.ticket))
215 }
216}
217
218enum Step {
220 RequeueAt(tokio::time::Instant),
222 Done,
224}
225
226struct Entry {
228 deadline: tokio::time::Instant,
229 ticket: u64,
230 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 #[cfg(test)]
241 Count(tokio::sync::oneshot::Sender<usize>),
242}
243
244#[derive(Clone)]
246pub struct TimerDriver {
247 tx: mpsc::UnboundedSender<Cmd>,
248 clock: ClockSource,
249 next_id: Arc<AtomicU64>,
250}
251
252impl TimerDriver {
253 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 #[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 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 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 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 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 pub fn schedule_interval<E: Send + Clone + 'static>(
358 &self,
359 interval: Duration,
360 ctl: mpsc::Sender<E>,
361 payload: E,
362 ) -> TimerHandle {
363 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 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 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 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 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 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 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 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
481fn 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 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); }
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 while let Ok(cmd) = rx.try_recv() {
527 apply(cmd, &mut entries, &mut heap, &mut next_ticket);
528 }
529 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 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; };
552 if e.ticket != key.ticket {
553 continue; }
555 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 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 entries.remove(&key.id);
585 }
586 }
587 }
588 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 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 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 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 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 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 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 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 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 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 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 #[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 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 #[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 #[test]
802 fn interval_drop_warn_is_rate_limited() {
803 #[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 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 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 #[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 #[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 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 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}