Skip to main content

nexus_timer/
lib.rs

1//! Low-latency timer primitives: a hierarchical **timer wheel** (O(1) insert +
2//! cancel) for arbitrary deadlines, and a fixed-duration **[`TimeoutQueue`]** for
3//! the common case where every timer shares one timeout.
4//!
5//! # Two structures — pick by workload
6//!
7//! - [`TimerWheel`] ([`Wheel`] / [`BoundedWheel`]) — **arbitrary deadlines**:
8//!   timers that fire at different, unrelated future times.
9//! - [`TimeoutQueue`] ([`BoundedTimeoutQueue`]) — **a single fixed timeout**:
10//!   every timer expires the *same* duration after it is scheduled.
11//!
12//! The tell: *"do all my timers time out after the same amount of time?"* —
13//! yes → [`TimeoutQueue`], no → the wheel.
14//!
15//! | | [`TimerWheel`] | [`TimeoutQueue`] |
16//! |---|---|---|
17//! | Timeout per timer | arbitrary | one fixed duration |
18//! | Poll | O(active population) | **O(fired)** |
19//! | `next_deadline` | lower bound (cached) | **O(1) exact** |
20//! | Clock | any monotone source | monotone, non-decreasing |
21//!
22//! Reach for [`TimeoutQueue`] on the hot path when it fits — idle timeouts (all
23//! 30 s), request deadlines (all 5 s), a fixed retry/debounce delay, uniform
24//! TTL expiry. Fixed duration ⇒ monotone deadlines ⇒ a sorted list, so a
25//! nothing-due poll stays flat (~12 cycles) no matter how many timers are
26//! outstanding. A handful of distinct durations → one list each; many or
27//! arbitrary deadlines → the wheel.
28//!
29//! # The clock
30//!
31//! Every constructor takes `now` — it fixes the **reference epoch**. An
32//! `Instant` has no absolute zero (you can only measure durations *between*
33//! instants), so deadlines are stored relative to this epoch. Pass one monotone
34//! clock source (e.g. `Instant::now()`) to the constructor *and* to every
35//! `schedule` / `poll`. A `now` that goes backwards is a bug — [`TimeoutQueue`]
36//! debug-asserts on it.
37//!
38//! # Timer wheel design
39//!
40//! The wheel is hierarchical: a timer is placed into a slot at the level whose
41//! granularity matches how far away its deadline is — coarse levels for distant
42//! deadlines, fine levels for near ones.
43//!
44//! - **Rebalance, don't re-walk:** as a timer's deadline approaches it is moved
45//!   ("rebalanced") down to finer levels, so `poll` collects ready timers from
46//!   small, exact fine-level slots instead of walking a fat coarse slot on every
47//!   call. Rebalancing can be folded into the poll
48//!   ([`TimerWheel::poll_and_rebalance`]), bounded per poll
49//!   ([`WheelBuilder::max_rebalances_per_poll`]), or run proactively off the hot
50//!   path ([`TimerWheel::rebalance`]) to keep the poll tail flat under a large
51//!   number of timers. Timers still fire at their exact tick.
52//! - **Intrusive active-slot lists:** Only non-empty slots are visited
53//!   during poll and next-deadline queries. No bitmap, no full scan.
54//! - **Embedded refcounting:** Lightweight `Cell<u8>` refcount per entry
55//!   enables fire-and-forget timers alongside cancellable timers without
56//!   external reference-counting machinery.
57//! - **Generic storage:** Parameterized over slab backend — bounded
58//!   (fixed-capacity) or unbounded (growable).
59//!
60//! # Quick Start
61//!
62//! ```
63//! use std::time::{Duration, Instant};
64//! use nexus_timer::Wheel;
65//!
66//! let now = Instant::now();
67//! let mut wheel: Wheel<u64> = Wheel::unbounded(4096, now);
68//!
69//! // Schedule a timer 100ms from now
70//! let handle = wheel.schedule(now + Duration::from_millis(100), 42u64);
71//!
72//! // Cancel before it fires — get the value back
73//! let value = wheel.cancel(handle);
74//! assert_eq!(value, Some(42));
75//! ```
76
77#![warn(missing_docs)]
78
79mod entry;
80mod handle;
81mod level;
82pub mod store;
83pub mod timeout_queue;
84mod wheel;
85
86pub use entry::WheelEntry;
87pub use handle::TimerHandle;
88pub use timeout_queue::{
89    BoundedTimeoutQueue, BoundedTimeoutQueueBuilder, TimeoutQueue, TimeoutQueueBuilder,
90    UnboundedTimeoutQueueBuilder,
91};
92pub use wheel::{
93    BoundedWheel, BoundedWheelBuilder, ConfigError, TimerWheel, UnboundedWheelBuilder, Wheel,
94    WheelBuilder,
95};
96
97// Re-export Full for bounded wheel users
98pub use nexus_slab::Full;