1#![allow(clippy::cast_possible_truncation)]
2use std::collections::{BTreeMap, VecDeque};
3use std::task::Poll;
4use std::time::{Duration, Instant};
5use std::{cell::Cell, cell::RefCell, mem, num::NonZeroUsize, ops, rc::Rc};
6
7use ntex_rt::{Arbiter, LocalWaker};
8use ntex_util::time::{Millis, Seconds, now, sleep};
9use ntex_util::{HashSet, spawn_detached};
10use slab::Slab;
11
12use crate::IoRef;
13
14const CAP: usize = 32;
15const MAX_CACHED_SET_CAP: usize = 512;
17
18thread_local! {
19 static MANAGER: RefCell<Option<IoManager>> = const { RefCell::new(None) };
20 static IOPS_TASK: Cell<u64> = const { Cell::new(0) };
22}
23
24#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
25pub struct Id(Option<NonZeroUsize>);
29
30#[derive(Copy, Clone, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
31pub struct TimerHandle(u32);
41
42impl TimerHandle {
43 pub const ZERO: TimerHandle = TimerHandle(0);
45
46 pub fn is_set(&self) -> bool {
51 self.0 != 0
52 }
53
54 pub fn remains(&self) -> Seconds {
60 let rem = self.instant().saturating_duration_since(now());
61 let secs = rem.as_secs() + u64::from(rem.subsec_nanos() != 0);
62 Seconds(secs.min(u64::from(u16::MAX)) as u16)
63 }
64
65 pub fn instant(&self) -> Instant {
70 IoManager::with(|mgr| mgr.timers.base + Duration::from_secs(u64::from(self.0)))
71 }
72
73 pub(crate) fn update(self, timeout: Seconds, io: &IoRef) -> TimerHandle {
74 IoManager::with(|mgr| {
75 let new_hnd = mgr.timers.deadline(timeout);
76 if self.0 == new_hnd || self.0 == new_hnd + 1 {
77 self
78 } else {
79 mgr.timers.unregister(self, io);
80 mgr.timers.register(timeout, io)
81 }
82 })
83 }
84
85 pub(crate) fn unregister(self, io: &IoRef) {
86 IoManager::with(|manager| manager.timers.unregister(self, io));
87 }
88
89 pub(crate) fn register(timeout: Seconds, io: &IoRef) -> TimerHandle {
90 IoManager::with(move |mgr| mgr.timers.register(timeout, io))
91 }
92}
93
94impl ops::Add<Seconds> for TimerHandle {
95 type Output = TimerHandle;
96
97 #[inline]
98 fn add(self, other: Seconds) -> TimerHandle {
99 TimerHandle(self.0 + u32::from(other.0))
100 }
101}
102
103struct TimerStorage {
104 running: bool,
105 base: Instant,
106 current: u32,
108 now: (Instant, Duration),
111 cache: VecDeque<HashSet<Id>>,
112 notifications: BTreeMap<u32, HashSet<Id>>,
113}
114
115impl TimerStorage {
116 fn new(base: Instant) -> Self {
117 TimerStorage {
118 running: false,
119 base,
120 current: 0,
121 now: (base, Duration::ZERO),
122 cache: VecDeque::with_capacity(CAP),
123 notifications: BTreeMap::default(),
124 }
125 }
126
127 fn unregister(&mut self, hnd: TimerHandle, io: &IoRef) {
128 if let Some(items) = self.notifications.get_mut(&hnd.0) {
129 items.remove(&io.id());
130 if items.is_empty() {
131 let items = self.notifications.remove(&hnd.0).unwrap();
133 self.recycle(items);
134 }
135 }
136 }
137
138 fn recycle(&mut self, items: HashSet<Id>) {
141 debug_assert!(items.is_empty());
142 if self.cache.len() < CAP && items.capacity() <= MAX_CACHED_SET_CAP {
143 self.cache.push_back(items);
144 }
145 }
146
147 fn update_current(&mut self) -> u32 {
149 self.current = self.base.elapsed().as_secs() as u32;
150 self.current
151 }
152
153 fn deadline(&mut self, timeout: Seconds) -> u32 {
159 self.deadline_at(timeout, now())
160 }
161
162 fn deadline_at(&mut self, timeout: Seconds, now: Instant) -> u32 {
163 let elapsed = self.elapsed(now);
164 let secs = elapsed.as_secs() as u32;
165 if secs < self.current {
166 return self.current + 1 + u32::from(timeout.0);
168 }
169 self.current = secs;
170
171 if self.notifications.is_empty() {
172 self.base += Duration::new(0, elapsed.subsec_nanos());
176 self.now.1 = Duration::from_secs(elapsed.as_secs());
177 self.current + u32::from(timeout.0)
178 } else {
179 let partial = u32::from(elapsed.subsec_nanos() != 0);
180 self.current + partial + u32::from(timeout.0)
181 }
182 }
183
184 fn elapsed(&mut self, now: Instant) -> Duration {
187 if self.now.0 != now {
188 self.now = (now, now.saturating_duration_since(self.base));
189 }
190 self.now.1
191 }
192
193 fn register(&mut self, timeout: Seconds, io: &IoRef) -> TimerHandle {
194 let hnd = self.deadline(timeout);
195 if let Some(items) = self.notifications.get_mut(&hnd) {
196 items.insert(io.id());
197 } else {
198 let mut items = self.cache.pop_front().unwrap_or_default();
199 items.insert(io.id());
200 self.notifications.insert(hnd, items);
201 }
202
203 self.run_timer();
204
205 TimerHandle(hnd)
206 }
207
208 fn run_timer(&mut self) {
209 if self.running {
210 return;
211 }
212 self.running = true;
213
214 spawn_detached(async move {
215 let guard = TimerGuard;
216 let timer = sleep(Self::next_tick());
218 loop {
219 timer.wait().await;
220
221 let stop = IoManager::with(|mgr| {
222 let current = mgr.timers.update_current();
223
224 while let Some(entry) = mgr.timers.notifications.first_entry() {
226 if *entry.key() > current {
227 break;
228 }
229 let mut items = entry.remove();
230 for id in items.drain() {
231 if let Some(io) = mgr.get(id) {
232 io.notify_timeout();
233 }
234 }
235 mgr.timers.recycle(items);
236 }
237
238 if mgr.timers.notifications.is_empty() {
239 mgr.timers.running = false;
240 true
241 } else {
242 false
243 }
244 });
245
246 if stop {
247 break;
248 }
249 timer.reset(Self::next_tick());
250 }
251 drop(guard);
252 });
253 }
254
255 fn next_tick() -> Millis {
258 let next = IoManager::with(|mgr| {
259 let t = &mgr.timers;
260 let next = t.base + Duration::from_secs(u64::from(t.current) + 1);
261 next.saturating_duration_since(Instant::now())
262 });
263 Millis(next.as_millis() as u32 + 1)
264 }
265}
266
267struct TimerGuard;
268
269impl Drop for TimerGuard {
270 fn drop(&mut self) {
271 IoManager::with(|mgr| {
272 mgr.timers.running = false;
273 mgr.timers.notifications.clear();
274 });
275 }
276}
277
278pub(crate) struct IoManager {
279 storage: Slab<Option<IoRef>>,
280 timers: TimerStorage,
281 pub(crate) iops: Iops,
282}
283
284impl Default for IoManager {
285 fn default() -> IoManager {
286 let mut storage = Slab::new();
287 assert_eq!(storage.insert(None), 0);
288
289 IoManager {
290 storage,
291 timers: TimerStorage::new(now()),
293 iops: Iops {
294 running: false,
295 waker: None,
296 task: 0,
297 ops: Vec::with_capacity(32),
298 },
299 }
300 }
301}
302
303impl IoManager {
304 fn with<F, R>(f: F) -> R
311 where
312 F: FnOnce(&mut IoManager) -> R,
313 {
314 let mut f = Some(f);
315 MANAGER
316 .try_with(|cell| {
317 let mut mgr = cell.borrow_mut();
318 let mgr = mgr.get_or_insert_with(|| {
319 Arbiter::on_shutdown(IoManager::reset);
320 IoManager::default()
321 });
322 (f.take().unwrap())(mgr)
323 })
324 .unwrap_or_else(|_| (f.take().unwrap())(&mut IoManager::default()))
325 }
326
327 fn reset() {
328 let mgr = MANAGER
331 .try_with(|cell| cell.borrow_mut().take())
332 .ok()
333 .flatten();
334 drop(mgr);
335 }
336
337 fn get(&self, id: Id) -> Option<&IoRef> {
338 if let Some(id) = id.0 {
339 self.storage.get(id.get()).and_then(|item| item.as_ref())
340 } else {
341 None
342 }
343 }
344
345 pub(crate) fn register(io: &IoRef) -> Id {
346 IoManager::with(|manager| {
347 let entry = manager.storage.vacant_entry();
348 let id = Id(NonZeroUsize::new(entry.key()));
349 entry.insert(Some(io.clone()));
350 id
351 })
352 }
353
354 pub(crate) fn unregister(io: &IoRef) {
355 if let Some(id) = io.id().0 {
356 io.0.id.set(Id(None));
357 IoManager::with(|manager| {
358 if let Some(Some(item)) = manager.storage.get(id.get())
361 && Rc::ptr_eq(&item.0, &io.0)
362 {
363 manager.storage.remove(id.get());
364 }
365 });
366 }
367 }
368}
369
370pub(crate) struct Iops {
371 running: bool,
372 waker: Option<LocalWaker>,
377 task: u64,
380 pub(crate) ops: Vec<Id>,
381}
382
383#[cfg(target_pointer_width = "64")]
384const _: () = assert!(mem::size_of::<Iops>() == 56);
385
386impl Iops {
387 pub(crate) fn schedule_write(id: Id) {
388 IoManager::with(|mgr| {
389 mgr.iops.ops.push(id);
390
391 if !mgr.iops.running {
392 mgr.iops.running = true;
393 if let Some(waker) = &mgr.iops.waker {
394 waker.wake_by_ref();
395 } else {
396 let task = IOPS_TASK
397 .try_with(|id| {
398 id.set(id.get().wrapping_add(1));
399 id.get()
400 })
401 .unwrap_or_default();
402 mgr.iops.task = task;
403 spawn_detached(Iops::task(task));
404 }
405 }
406 });
407 }
408
409 async fn task(id: u64) {
410 struct Guard(u64);
413
414 impl Drop for Guard {
415 fn drop(&mut self) {
416 let waker = MANAGER.try_with(|cell| {
417 if let Ok(mut mgr) = cell.try_borrow_mut()
418 && let Some(mgr) = mgr.as_mut()
419 && mgr.iops.task == self.0
420 {
421 mgr.iops.running = false;
422 mgr.iops.waker.take()
423 } else {
424 None
425 }
426 });
427 drop(waker);
428 }
429 }
430
431 let _guard = Guard(id);
432 std::future::poll_fn(|cx| {
433 Iops::run();
434 let replaced = IoManager::with(|mgr| {
435 if mgr.iops.task == id
436 && !mgr
437 .iops
438 .waker
439 .as_ref()
440 .is_some_and(|w| w.will_wake(cx.waker()))
441 {
442 mgr.iops.waker.replace(LocalWaker::from_waker(cx.waker()))
443 } else {
444 None
445 }
446 });
447 drop(replaced);
448 Poll::<()>::Pending
449 })
450 .await;
451 }
452
453 pub(crate) fn run() {
454 IoManager::with(|mgr| {
455 mgr.iops.running = false;
456
457 let mut ops = mem::take(&mut mgr.iops.ops);
458 for id in ops.drain(..) {
459 if let Some(io) = mgr.get(id) {
460 io.ops_send_buf();
461 }
462 }
463 let _ = mem::replace(&mut mgr.iops.ops, ops);
464 });
465 }
466
467 #[cfg(test)]
468 pub(crate) fn is_registered(io: &IoRef) -> bool {
469 IoManager::with(|mgr| mgr.iops.ops.contains(&io.id()))
470 }
471}
472
473#[cfg(test)]
474mod tests {
475 use ntex::rt::{DefaultRuntime, System};
476
477 use super::*;
478
479 async fn wait_timeout(io: &crate::Io) -> Duration {
480 let start = Instant::now();
481 let st = std::future::poll_fn(|cx| io.poll_status_update(cx)).await;
482 assert!(matches!(st, crate::IoStatusUpdate::Timeout));
483 start.elapsed()
484 }
485
486 #[test]
492 fn large_timer_sets_are_not_cached() {
493 let mut timers = TimerStorage::new(Instant::now());
494
495 let mut small = HashSet::default();
496 small.insert(Id(NonZeroUsize::new(1)));
497 small.clear();
498 timers.recycle(small);
499 assert_eq!(timers.cache.len(), 1);
500
501 let mut large = HashSet::default();
503 for i in 1..=10_000 {
504 large.insert(Id(NonZeroUsize::new(i)));
505 }
506 large.clear();
507 timers.recycle(large);
508 assert_eq!(timers.cache.len(), 1);
509 assert!(timers.cache[0].capacity() <= MAX_CACHED_SET_CAP);
510
511 for _ in 0..2 * CAP {
513 timers.recycle(HashSet::default());
514 }
515 assert_eq!(timers.cache.len(), CAP);
516 }
517
518 #[test]
525 fn deadline_reuses_elapsed_after_reanchor() {
526 let base = Instant::now();
527 let mut timers = TimerStorage::new(base);
528
529 let at = base + Duration::from_millis(1500);
530 let first = timers.deadline_at(Seconds(5), at);
531 assert_eq!(first, 6);
532 assert_eq!(timers.base, base + Duration::from_millis(500));
533
534 timers
535 .notifications
536 .entry(first)
537 .or_default()
538 .insert(Id(NonZeroUsize::new(1)));
539 assert_eq!(timers.deadline_at(Seconds(5), at), 6);
540
541 let later = base + Duration::from_millis(1750);
542 assert_eq!(timers.deadline_at(Seconds(5), later), 7);
543 }
544
545 #[ntex::test]
551 async fn timer_expires_after_timeout() {
552 use ntex_service::cfg::SharedCfg;
553
554 use crate::{Io, testing::IoTest};
555
556 let (_client, server) = IoTest::create();
557 let io = Io::new(server, SharedCfg::new("T"));
558
559 sleep(Millis(500)).await;
561
562 io.start_timer(Seconds(1));
563 let elapsed = wait_timeout(&io).await;
564 assert!(
565 elapsed >= Duration::from_secs(1) && elapsed < Duration::from_millis(1300),
566 "elapsed: {elapsed:?}"
567 );
568 }
569
570 #[ntex::test]
576 async fn timer_expires_within_second_after_timeout() {
577 use ntex_service::cfg::SharedCfg;
578
579 use crate::{Io, testing::IoTest};
580
581 let (_client1, server1) = IoTest::create();
582 let (_client2, server2) = IoTest::create();
583 let io1 = Io::new(server1, SharedCfg::new("T"));
584 let io2 = Io::new(server2, SharedCfg::new("T"));
585
586 io1.start_timer(Seconds(10));
587 sleep(Millis(500)).await;
588
589 io2.start_timer(Seconds(1));
591 let elapsed = wait_timeout(&io2).await;
592 assert!(
593 elapsed >= Duration::from_secs(1) && elapsed < Duration::from_millis(1800),
594 "elapsed: {elapsed:?}"
595 );
596 }
597
598 fn has_manager() -> bool {
599 MANAGER.with(|mgr| mgr.borrow().is_some())
600 }
601
602 fn iops_state() -> (bool, u64, bool) {
603 IoManager::with(|mgr| (mgr.iops.running, mgr.iops.task, mgr.iops.waker.is_some()))
604 }
605
606 #[ntex::test]
612 async fn local_write_task_replacement_and_cleanup() {
613 use std::sync::{Arc, atomic::AtomicUsize, atomic::Ordering};
614 use std::task::{Context, Wake, Waker};
615
616 struct Probe {
617 notifications: Arc<AtomicUsize>,
618 drops: Arc<AtomicUsize>,
619 registered_on_drop: bool,
620 }
621
622 impl Wake for Probe {
623 fn wake(self: Arc<Self>) {
624 self.notifications.fetch_add(1, Ordering::Relaxed);
625 }
626 }
627
628 impl Drop for Probe {
629 fn drop(&mut self) {
630 assert_eq!(iops_state(), (false, 1, self.registered_on_drop));
631 self.drops.fetch_add(1, Ordering::Relaxed);
632 }
633 }
634
635 IoManager::with(|mgr| mgr.iops.task = 1);
636 let mut task = Box::pin(Iops::task(1));
637 let notifications = Arc::new(AtomicUsize::new(0));
638 let drops = Arc::new(AtomicUsize::new(0));
639 let probe = |registered_on_drop| {
640 Waker::from(Arc::new(Probe {
641 notifications: notifications.clone(),
642 drops: drops.clone(),
643 registered_on_drop,
644 }))
645 };
646 let waker = probe(true);
647 assert!(
648 task.as_mut()
649 .poll(&mut Context::from_waker(&waker))
650 .is_pending()
651 );
652 drop(waker);
653 Iops::schedule_write(Id(None));
654 assert_eq!(notifications.load(Ordering::Relaxed), 1);
655
656 std::future::poll_fn(|cx| {
657 assert!(task.as_mut().poll(cx).is_pending());
658 Poll::Ready(())
659 })
660 .await;
661 assert_eq!(drops.load(Ordering::Relaxed), 1);
662
663 let waker = probe(false);
664 assert!(
665 task.as_mut()
666 .poll(&mut Context::from_waker(&waker))
667 .is_pending()
668 );
669 drop(waker);
670 Iops::schedule_write(Id(None));
671 assert_eq!(notifications.load(Ordering::Relaxed), 2);
672 drop(task);
673 assert_eq!(drops.load(Ordering::Relaxed), 2);
674 assert_eq!(iops_state(), (false, 1, false));
675
676 IoManager::with(|mgr| mgr.iops.task = 2);
677 let mut old = Box::pin(Iops::task(2));
678 assert!(
679 old.as_mut()
680 .poll(&mut Context::from_waker(Waker::noop()))
681 .is_pending()
682 );
683 IoManager::with(|mgr| mgr.iops.task = 3);
684 let mut new = Box::pin(Iops::task(3));
685 std::future::poll_fn(|cx| {
686 assert!(new.as_mut().poll(cx).is_pending());
687 Poll::Ready(())
688 })
689 .await;
690 Iops::schedule_write(Id(None));
691 drop(old);
692 assert_eq!(iops_state(), (true, 3, true));
693 drop(new);
694 assert_eq!(iops_state(), (false, 3, false));
695 }
696
697 #[test]
703 fn write_task_is_reused() {
704 std::thread::spawn(|| {
705 let first = System::new("test", DefaultRuntime).block_on(async {
706 Iops::schedule_write(Id(None));
707 sleep(Millis(5)).await;
708 let (running, task, waker) = iops_state();
709 assert!(!running && waker, "batch was not run");
710
711 for _ in 0..3 {
712 Iops::schedule_write(Id(None));
713 Iops::schedule_write(Id(None));
714 assert!(iops_state().0);
715 sleep(Millis(5)).await;
716 assert_eq!(iops_state(), (false, task, true));
717 }
718 task
719 });
720
721 System::new("test", DefaultRuntime).block_on(async move {
722 Iops::schedule_write(Id(None));
723 sleep(Millis(5)).await;
724 let (running, task, waker) = iops_state();
725 assert!(!running && waker, "batch of the next runtime was not run");
726 assert_ne!(task, first);
727 });
728 })
729 .join()
730 .unwrap();
731 }
732
733 #[test]
739 fn manager_reset_on_shutdown() {
740 std::thread::spawn(|| {
741 System::new("test", DefaultRuntime).block_on(async {
742 Iops::schedule_write(Id(None));
743 assert!(has_manager());
744 });
745 assert!(!has_manager());
746
747 System::build()
748 .build(DefaultRuntime)
749 .run(|| {
750 Iops::schedule_write(Id(None));
751 System::current().stop();
752 Ok(())
753 })
754 .unwrap();
755 assert!(!has_manager());
756 })
757 .join()
758 .unwrap();
759 }
760}