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
//! Edge-triggered timer wheel for lease expiry / refresh scheduling.
//!
//! Replaces the `thread::sleep(ttl/3)` polling loop in `lease_loop` with
//! a bucket-granular timer wheel: the worker thread sleeps until the next
//! bucket is due, fires all leases in that bucket, then sleeps again.
//!
//! ## Design (top-half / bottom-half)
//!
//! * **Top-half** (`schedule` / `cancel`): callable from any thread, O(log n).
//! * **Bottom-half** (`run_until_shutdown`): dedicated worker thread; wakes
//! only when a bucket fires. Zero CPU for idle leases.
//!
//! Bucket granularity is configurable (default 100 ms). All expirations
//! within the same granularity window coalesce into one wake-up.
//!
//! ## Scalability
//!
//! With N idle leases all expiring far in the future, the worker sleeps
//! exactly until the earliest bucket — not once per lease. CPU overhead
//! is O(0) while idle and O(k) where k is the number of leases firing in
//! the current bucket.
use std::collections::{BTreeMap, HashMap};
use std::sync::{Condvar, Mutex};
use std::time::{Duration, Instant};
pub type LeaseId = String;
struct WheelState {
/// Sorted map: fire instant → ids firing at that bucket boundary.
schedule: BTreeMap<Instant, Vec<LeaseId>>,
/// Reverse index: id → fire instant for O(1) cancel / reschedule.
id_to_fire: HashMap<LeaseId, Instant>,
shutdown: bool,
}
/// Timer wheel that schedules leases to fire at specific wall-clock times.
///
/// Construct once, share via `Arc`. Call [`schedule`] from producer threads,
/// call [`run_until_shutdown`] on a dedicated worker thread.
pub struct LeaseTimerWheel {
state: Mutex<WheelState>,
cvar: Condvar,
granularity: Duration,
}
impl LeaseTimerWheel {
/// New wheel with `granularity_ms` bucket width (minimum 1 ms).
pub fn new(granularity_ms: u64) -> Self {
Self {
state: Mutex::new(WheelState {
schedule: BTreeMap::new(),
id_to_fire: HashMap::new(),
shutdown: false,
}),
cvar: Condvar::new(),
granularity: Duration::from_millis(granularity_ms.max(1)),
}
}
/// Schedule `id` to fire at or after `expiry`.
///
/// The expiry is snapped forward to the next granularity boundary so
/// near-simultaneous expirations coalesce into a single wake-up.
/// Re-scheduling an existing id silently replaces the prior entry.
pub fn schedule(&self, id: LeaseId, expiry: Instant) {
let fire_time = self.snap(expiry);
let mut state = self.state.lock().expect("wheel mutex poisoned");
self.remove_existing(&mut state, &id);
state
.schedule
.entry(fire_time)
.or_default()
.push(id.clone());
state.id_to_fire.insert(id, fire_time);
self.cvar.notify_one();
}
/// Cancel a scheduled lease. No-op if `id` is not scheduled.
pub fn cancel(&self, id: &str) {
let mut state = self.state.lock().expect("wheel mutex poisoned");
self.remove_existing(&mut state, id);
}
/// Signal the worker to stop after the current batch (if any) finishes.
pub fn shutdown(&self) {
let mut state = self.state.lock().expect("wheel mutex poisoned");
state.shutdown = true;
self.cvar.notify_all();
}
/// Block until `shutdown()` is called or `handler` returns `false`.
///
/// For each fired lease id, calls `handler(id)`. If the handler returns
/// `false`, the wheel stops immediately (even mid-batch).
///
/// CPU: the thread is parked in `Condvar::wait_timeout` between buckets.
/// With 10 k idle leases scheduled far in the future the CPU cost is
/// effectively zero — one wake-up per bucket boundary, not per lease.
pub fn run_until_shutdown(&self, mut handler: impl FnMut(LeaseId) -> bool + Send) {
loop {
// Hold the lock through sleep-duration computation AND the
// wait_timeout call so no `schedule()` notification is lost.
// (If we released between computing sleep_for and calling
// wait_timeout, a notification fired in that window would be
// dropped and the worker could sleep past the item's due time.)
let fired: Vec<LeaseId> = {
let state = self.state.lock().expect("wheel mutex poisoned");
if state.shutdown {
return;
}
let sleep_for = match state.schedule.keys().next().copied() {
Some(t) => {
let now = Instant::now();
if t <= now {
Duration::ZERO
} else {
t - now
}
}
// Nothing scheduled: park up to 1 h; condvar unparks on
// schedule() or shutdown().
None => Duration::from_secs(3600),
};
// Optionally sleep, keeping the lock through the call so
// any concurrent schedule() unparks us promptly.
let mut state = if sleep_for > Duration::ZERO {
let (guard, _) = self
.cvar
.wait_timeout(state, sleep_for)
.expect("condvar wait_timeout failed");
if guard.shutdown {
return;
}
guard
} else {
state
};
// Drain all due buckets while still holding the lock.
let now = Instant::now();
let mut ids = Vec::new();
while let Some((&fire_time, _)) = state.schedule.iter().next() {
if fire_time > now {
break;
}
let bucket = state.schedule.remove(&fire_time).unwrap_or_default();
for id in &bucket {
state.id_to_fire.remove(id.as_str());
}
ids.extend(bucket);
}
ids
// Lock released here.
};
// Invoke handler outside the lock so schedule() / cancel() can
// be called from within the handler (e.g. to reschedule).
for id in fired {
if !handler(id) {
return;
}
}
}
}
// Snap `expiry` forward to the next granularity boundary at-or-after
// `expiry`. Monotonic: result is always >= Instant::now().
fn snap(&self, expiry: Instant) -> Instant {
let now = Instant::now();
let base = expiry.max(now);
let nanos_from_now = (base - now).as_nanos() as u64;
let gran_nanos = self.granularity.as_nanos() as u64;
let snapped = nanos_from_now.div_ceil(gran_nanos) * gran_nanos;
now + Duration::from_nanos(snapped)
}
fn remove_existing(&self, state: &mut WheelState, id: &str) {
if let Some(old_time) = state.id_to_fire.remove(id) {
if let Some(v) = state.schedule.get_mut(&old_time) {
v.retain(|x| x != id);
if v.is_empty() {
state.schedule.remove(&old_time);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
fn ms(n: u64) -> Duration {
Duration::from_millis(n)
}
#[test]
fn single_lease_fires_within_granularity() {
let wheel = Arc::new(LeaseTimerWheel::new(50));
let fired = Arc::new(AtomicUsize::new(0));
let fired_clone = Arc::clone(&fired);
let wheel_clone = Arc::clone(&wheel);
// Schedule to fire in 50 ms.
wheel.schedule("lease-1".to_string(), Instant::now() + ms(50));
let t = thread::spawn(move || {
wheel_clone.run_until_shutdown(move |_id| {
fired_clone.fetch_add(1, Ordering::SeqCst);
false // stop after first fire
});
});
t.join().unwrap();
assert_eq!(fired.load(Ordering::SeqCst), 1);
}
#[test]
fn fires_at_roughly_the_right_time() {
let wheel = Arc::new(LeaseTimerWheel::new(50));
let start = Instant::now();
let fired_at = Arc::new(Mutex::new(None::<Instant>));
let fired_at_clone = Arc::clone(&fired_at);
let wheel_clone = Arc::clone(&wheel);
wheel.schedule("t".to_string(), start + ms(100));
let t = thread::spawn(move || {
wheel_clone.run_until_shutdown(move |_id| {
*fired_at_clone.lock().unwrap() = Some(Instant::now());
false
});
});
t.join().unwrap();
let elapsed = fired_at.lock().unwrap().unwrap() - start;
// Must fire at or after 100 ms, and within 100 ms + 2 * granularity (slack for CI).
assert!(elapsed >= ms(100), "fired too early: {elapsed:?}");
assert!(
elapsed < ms(400),
"fired too late (CI slowness?): {elapsed:?}"
);
}
#[test]
fn coalesces_multiple_leases_in_same_bucket() {
let wheel = Arc::new(LeaseTimerWheel::new(100));
let fired = Arc::new(AtomicUsize::new(0));
let fired_clone = Arc::clone(&fired);
let wheel_clone = Arc::clone(&wheel);
let total = Arc::new(AtomicUsize::new(0));
let total_clone = Arc::clone(&total);
// Three leases scheduled within the same 100 ms bucket.
let deadline = Instant::now() + ms(100);
wheel.schedule("a".to_string(), deadline);
wheel.schedule("b".to_string(), deadline);
wheel.schedule("c".to_string(), deadline);
let t = thread::spawn(move || {
wheel_clone.run_until_shutdown(move |_id| {
let n = fired_clone.fetch_add(1, Ordering::SeqCst) + 1;
total_clone.store(n, Ordering::SeqCst);
n < 3 // stop after 3 fires
});
});
t.join().unwrap();
assert_eq!(total.load(Ordering::SeqCst), 3);
}
#[test]
fn cancel_prevents_fire() {
let wheel = Arc::new(LeaseTimerWheel::new(50));
let fired = Arc::new(AtomicUsize::new(0));
let fired_clone = Arc::clone(&fired);
let wheel_clone = Arc::clone(&wheel);
wheel.schedule("doomed".to_string(), Instant::now() + ms(200));
wheel.schedule("survivor".to_string(), Instant::now() + ms(100));
wheel.cancel("doomed");
let t = thread::spawn(move || {
wheel_clone.run_until_shutdown(move |id| {
fired_clone.fetch_add(1, Ordering::SeqCst);
assert_eq!(id, "survivor", "cancelled lease must not fire");
false
});
});
t.join().unwrap();
assert_eq!(fired.load(Ordering::SeqCst), 1);
}
#[test]
fn reschedule_replaces_prior_entry() {
let wheel = Arc::new(LeaseTimerWheel::new(50));
let fire_times = Arc::new(Mutex::new(Vec::<Instant>::new()));
let fire_times_clone = Arc::clone(&fire_times);
let wheel_clone = Arc::clone(&wheel);
// Schedule at t+50, then immediately reschedule to t+150.
wheel.schedule("x".to_string(), Instant::now() + ms(50));
wheel.schedule("x".to_string(), Instant::now() + ms(150));
let start = Instant::now();
let t = thread::spawn(move || {
wheel_clone.run_until_shutdown(move |_id| {
fire_times_clone.lock().unwrap().push(Instant::now());
false
});
});
t.join().unwrap();
let times = fire_times.lock().unwrap();
assert_eq!(times.len(), 1, "only one fire expected after reschedule");
// Should not fire before 150 ms.
assert!(
times[0] - start >= ms(150),
"fired at wrong time: {:?}",
times[0] - start
);
}
#[test]
fn shutdown_stops_worker_with_no_scheduled_leases() {
let wheel = Arc::new(LeaseTimerWheel::new(100));
let wheel_clone = Arc::clone(&wheel);
let t = thread::spawn(move || {
wheel_clone.run_until_shutdown(|_| true);
});
// Worker is sleeping (nothing scheduled). Signal shutdown.
thread::sleep(ms(20));
wheel.shutdown();
t.join().unwrap(); // must not hang
}
#[test]
fn idle_10k_leases_do_not_spin() {
// 10 k leases all expiring 60 s from now.
// The worker should sleep until then — we verify it does not busy-spin
// by checking that it is still sleeping after 50 ms.
let wheel = Arc::new(LeaseTimerWheel::new(100));
let far_future = Instant::now() + Duration::from_secs(60);
for i in 0..10_000usize {
wheel.schedule(format!("lease-{i}"), far_future);
}
let fired = Arc::new(AtomicUsize::new(0));
let fired_clone = Arc::clone(&fired);
let wheel_clone = Arc::clone(&wheel);
thread::spawn(move || {
wheel_clone.run_until_shutdown(move |_| {
fired_clone.fetch_add(1, Ordering::SeqCst);
true
});
});
// Sleep 50 ms; nothing should have fired.
thread::sleep(ms(50));
assert_eq!(
fired.load(Ordering::SeqCst),
0,
"no leases should fire during idle period"
);
wheel.shutdown();
}
}