kestrel_timer/lib.rs
1//! # High-Performance Async Timer System
2//!
3//! High-performance async timer based on Timing Wheel algorithm, supports tokio runtime
4//!
5//! ## Features
6//!
7//! - **High Performance**: Uses timing wheel algorithm, insert and delete operations are O(1)
8//! - **Large-Scale Support**: Efficiently manages 10000+ concurrent timers
9//! - **Async Support**: Based on tokio async runtime
10//! - **Thread-Safe**: Uses parking_lot for high-performance locking mechanism
11//!
12//!
13//! # 高性能异步定时器库
14//!
15//! 基于分层时间轮算法的高性能异步定时器库,支持 tokio 运行时
16//!
17//! ## 特性
18//!
19//! - **高性能**: 使用时间轮算法,插入和删除操作均为 O(1)
20//! - **大规模支持**: 高效管理 10000+ 并发定时器
21//! - **异步支持**: 基于 tokio 异步运行时
22//! - **线程安全**: 使用 parking_lot 提供高性能的锁机制
23//!
24//! ## Quick Start (快速开始)
25//!
26//! ```no_run
27//! use kestrel_timer::{TimerWheel, CallbackWrapper, TimerTask};
28//! use std::time::Duration;
29//! use std::sync::Arc;
30//!
31//! #[tokio::main]
32//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
33//! // Create timer manager (创建定时器管理器)
34//! let timer = TimerWheel::with_defaults();
35//!
36//! // Step 1: Allocate handle to get task_id (分配 handle 获取 task_id)
37//! let handle = timer.allocate_handle();
38//! let task_id = handle.task_id();
39//!
40//! // Step 2: Create timer task (创建定时器任务)
41//! let callback = Some(CallbackWrapper::new(|| async {
42//! println!("Timer fired after 1 second!");
43//! }));
44//! let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
45//!
46//! // Step 3: Register timer task and get completion notification (注册定时器任务并获取完成通知)
47//! let timer_handle = timer.register(handle, task);
48//!
49//! // Wait for timer completion (等待定时器完成)
50//! use kestrel_timer::CompletionReceiver;
51//! let (rx, _handle) = timer_handle.into_parts();
52//! match rx {
53//! CompletionReceiver::OneShot(receiver) => {
54//! receiver.wait().await;
55//! },
56//! _ => {}
57//! }
58//! Ok(())
59//! }
60//! ```
61//!
62//! ## English Architecture Description
63//!
64//! ### Timing Wheel Algorithm
65//!
66//! Uses hierarchical timing wheel algorithm with L0 and L1 layers:
67//!
68//! - **L0 Layer (Bottom)**: Handles short delay tasks
69//! - Slot count: Default 512, configurable, must be power of 2
70//! - Time precision: Default 10ms, configurable
71//! - Maximum time span: 5.12 seconds
72//!
73//! - **L1 Layer (Upper)**: Handles long delay tasks
74//! - Slot count: Default 64, configurable, must be power of 2
75//! - Time precision: Default 1 second, configurable
76//! - Maximum time span: 64 seconds
77//!
78//! - **Round Mechanism**: Tasks beyond L1 range use round counting
79//!
80//! ### Task Indexing with DeferredMap
81//!
82//! Uses `DeferredMap` (a generational arena) for efficient task management:
83//!
84//! - **Two-Step Registration**:
85//! 1. Allocate handle to get task ID (cheap, no value needed)
86//! 2. Insert task using the handle (with completion notifiers)
87//!
88//! - **Generational Safety**: Each task ID includes:
89//! - Lower 32 bits: Slot index
90//! - Upper 32 bits: Generation counter
91//! - Prevents use-after-free and ABA problems
92//!
93//! - **Memory Efficiency**: Slots use union-based storage
94//! - Occupied slots: Store task data
95//! - Vacant slots: Store free-list pointer
96//!
97//! ### Performance Optimization
98//!
99//! - Uses `parking_lot::Mutex` instead of standard library Mutex for better performance
100//! - Uses `DeferredMap` (generational arena) for task indexing:
101//! - O(1) task lookup, insertion, and removal
102//! - Generational indices prevent use-after-free bugs
103//! - Memory-efficient slot reuse with union-based storage
104//! - Deferred insertion allows getting task ID before inserting task
105//! - Slot count is power of 2, uses bitwise operations to optimize modulo
106//! - Task execution in separate tokio tasks to avoid blocking timing wheel advancement
107//!
108//!
109//!
110//! ## 中文架构说明
111//!
112//! ### 时间轮算法
113//!
114//! 采用分层时间轮(Hierarchical Timing Wheel)算法,包含 L0 和 L1 两层:
115//!
116//! - **L0 层(底层)**: 处理短延迟任务
117//! - 槽位数量: 默认 512 个(可配置,必须是 2 的幂次方)
118//! - 时间精度: 默认 10ms(可配置)
119//! - 最大时间跨度: 5.12 秒
120//!
121//! - **L1 层(高层)**: 处理长延迟任务
122//! - 槽位数量: 默认 64 个(可配置,必须是 2 的幂次方)
123//! - 时间精度: 默认 1 秒(可配置)
124//! - 最大时间跨度: 64 秒
125//!
126//! - **轮次机制**: 超出 L1 层范围的任务使用轮次计数处理
127//!
128//! ### 基于 DeferredMap 的任务索引
129//!
130//! 使用 `DeferredMap`(代数竞技场)实现高效任务管理:
131//!
132//! - **两步注册流程**:
133//! 1. 分配 handle 获取任务 ID(轻量操作,无需准备任务值)
134//! 2. 使用 handle 插入任务(携带完成通知器)
135//!
136//! - **代数安全**: 每个任务 ID 包含:
137//! - 低 32 位:槽位索引
138//! - 高 32 位:代数计数器
139//! - 防止释放后使用和 ABA 问题
140//!
141//! - **内存高效**: 槽位使用联合体存储
142//! - 已占用槽位:存储任务数据
143//! - 空闲槽位:存储空闲链表指针
144//!
145//! ### 性能优化
146//!
147//! - 使用 `parking_lot::Mutex` 替代标准库的 Mutex,提供更好的性能
148//! - 使用 `DeferredMap`(代数竞技场)进行任务索引:
149//! - O(1) 任务查找、插入和删除
150//! - 代数索引防止释放后使用(use-after-free)错误
151//! - 基于联合体的槽位存储,内存高效复用
152//! - 延迟插入允许在插入任务前获取任务 ID
153//! - 槽位数量为 2 的幂次方,使用位运算优化取模操作
154//! - 任务执行在独立的 tokio 任务中,避免阻塞时间轮推进
155//!
156
157pub mod config;
158pub mod error;
159mod service;
160pub mod task;
161pub mod timer;
162pub mod wheel;
163
164#[cfg(test)]
165mod tests;
166
167// Re-export public API
168pub use service::{TaskNotification, TimerService};
169pub use task::CompletionReceiver;
170pub use task::{CallbackWrapper, TaskCompletion, TaskId, TimerTask};
171pub use timer::TimerWheel;
172pub use timer::handle::{
173 BatchHandle, BatchHandleWithCompletion, TimerHandle, TimerHandleWithCompletion,
174};
175
176#[cfg(test)]
177mod integration_tests {
178 use super::*;
179 use std::sync::Arc;
180 use std::sync::atomic::{AtomicU32, Ordering};
181 use std::time::Duration;
182
183 #[tokio::test]
184 async fn test_basic_timer() {
185 let timer = TimerWheel::with_defaults();
186 let counter = Arc::new(AtomicU32::new(0));
187 let counter_clone = Arc::clone(&counter);
188
189 let handle = timer.allocate_handle();
190 let task = TimerTask::new_oneshot(
191 Duration::from_millis(50),
192 Some(CallbackWrapper::new(move || {
193 let counter = Arc::clone(&counter_clone);
194 async move {
195 counter.fetch_add(1, Ordering::SeqCst);
196 }
197 })),
198 );
199 timer.register(handle, task);
200
201 tokio::time::sleep(Duration::from_millis(100)).await;
202 assert_eq!(counter.load(Ordering::SeqCst), 1);
203 }
204
205 #[tokio::test]
206 async fn test_multiple_timers() {
207 let timer = TimerWheel::with_defaults();
208 let counter = Arc::new(AtomicU32::new(0));
209
210 // Create 10 timers
211 for i in 0..10 {
212 let counter_clone = Arc::clone(&counter);
213 let handle = timer.allocate_handle();
214 let task = TimerTask::new_oneshot(
215 Duration::from_millis(10 * (i + 1)),
216 Some(CallbackWrapper::new(move || {
217 let counter = Arc::clone(&counter_clone);
218 async move {
219 counter.fetch_add(1, Ordering::SeqCst);
220 }
221 })),
222 );
223 timer.register(handle, task);
224 }
225
226 tokio::time::sleep(Duration::from_millis(200)).await;
227 assert_eq!(counter.load(Ordering::SeqCst), 10);
228 }
229
230 #[tokio::test]
231 async fn test_timer_cancellation() {
232 let timer = TimerWheel::with_defaults();
233 let counter = Arc::new(AtomicU32::new(0));
234
235 // Create 5 timers
236 let mut handles = Vec::new();
237 for _ in 0..5 {
238 let counter_clone = Arc::clone(&counter);
239 let alloc_handle = timer.allocate_handle();
240 let task = TimerTask::new_oneshot(
241 Duration::from_millis(100),
242 Some(CallbackWrapper::new(move || {
243 let counter = Arc::clone(&counter_clone);
244 async move {
245 counter.fetch_add(1, Ordering::SeqCst);
246 }
247 })),
248 );
249 let handle = timer.register(alloc_handle, task);
250 handles.push(handle);
251 }
252
253 // Cancel first 3 timers
254 for i in 0..3 {
255 let cancel_result = handles[i].cancel();
256 assert!(cancel_result);
257 }
258
259 tokio::time::sleep(Duration::from_millis(200)).await;
260 // Only 2 timers should be triggered
261 assert_eq!(counter.load(Ordering::SeqCst), 2);
262 }
263
264 #[tokio::test]
265 async fn test_completion_notification_once() {
266 let timer = TimerWheel::with_defaults();
267 let counter = Arc::new(AtomicU32::new(0));
268 let counter_clone = Arc::clone(&counter);
269
270 let alloc_handle = timer.allocate_handle();
271 let task = TimerTask::new_oneshot(
272 Duration::from_millis(50),
273 Some(CallbackWrapper::new(move || {
274 let counter = Arc::clone(&counter_clone);
275 async move {
276 counter.fetch_add(1, Ordering::SeqCst);
277 }
278 })),
279 );
280 let handle = timer.register(alloc_handle, task);
281
282 // Wait for completion notification
283 let (rx, _handle) = handle.into_parts();
284 match rx {
285 task::CompletionReceiver::OneShot(receiver) => {
286 receiver.wait().await;
287 }
288 _ => panic!("Expected OneShot completion receiver"),
289 }
290
291 // Verify callback has been executed (wait a moment to ensure callback execution is complete)
292 tokio::time::sleep(Duration::from_millis(20)).await;
293 assert_eq!(counter.load(Ordering::SeqCst), 1);
294 }
295
296 #[tokio::test]
297 async fn test_notify_only_timer_once() {
298 let timer = TimerWheel::with_defaults();
299
300 let alloc_handle = timer.allocate_handle();
301 let task = TimerTask::new_oneshot(Duration::from_millis(50), None);
302 let handle = timer.register(alloc_handle, task);
303
304 // Wait for completion notification (no callback, only notification)
305 let (rx, _handle) = handle.into_parts();
306 match rx {
307 task::CompletionReceiver::OneShot(receiver) => {
308 receiver.wait().await;
309 }
310 _ => panic!("Expected OneShot completion receiver"),
311 }
312 }
313
314 #[tokio::test]
315 async fn test_batch_completion_notifications() {
316 let timer = TimerWheel::with_defaults();
317 let counter = Arc::new(AtomicU32::new(0));
318
319 // Step 1: Allocate handles
320 let handles = timer.allocate_handles(5);
321
322 // Step 2: Create batch callbacks
323 let tasks: Vec<_> = (0..5)
324 .map(|i| {
325 let counter = Arc::clone(&counter);
326 let delay = Duration::from_millis(50 + i as u64 * 10);
327 let callback = CallbackWrapper::new(move || {
328 let counter = Arc::clone(&counter);
329 async move {
330 counter.fetch_add(1, Ordering::SeqCst);
331 }
332 });
333 TimerTask::new_oneshot(delay, Some(callback))
334 })
335 .collect();
336
337 // Step 3: Batch register
338 let batch = timer
339 .register_batch(handles, tasks)
340 .expect("register_batch should succeed");
341 let (receivers, _batch_handle) = batch.into_parts();
342
343 // Wait for all completion notifications
344 for rx in receivers {
345 match rx {
346 task::CompletionReceiver::OneShot(receiver) => {
347 receiver.wait().await;
348 }
349 _ => panic!("Expected OneShot completion receiver"),
350 }
351 }
352
353 // Wait a moment to ensure callback execution is complete
354 tokio::time::sleep(Duration::from_millis(50)).await;
355
356 // Verify all callbacks have been executed
357 assert_eq!(counter.load(Ordering::SeqCst), 5);
358 }
359
360 #[tokio::test]
361 async fn test_completion_reason_expired() {
362 let timer = TimerWheel::with_defaults();
363
364 let alloc_handle = timer.allocate_handle();
365 let task = TimerTask::new_oneshot(Duration::from_millis(50), None);
366 let handle = timer.register(alloc_handle, task);
367
368 // Wait for completion notification and verify reason is Expired
369 let (rx, _handle) = handle.into_parts();
370 let result = match rx {
371 task::CompletionReceiver::OneShot(receiver) => receiver.wait().await,
372 _ => panic!("Expected OneShot completion receiver"),
373 };
374 assert_eq!(result, TaskCompletion::Called);
375 }
376
377 #[tokio::test]
378 async fn test_completion_reason_cancelled() {
379 let timer = TimerWheel::with_defaults();
380
381 let alloc_handle = timer.allocate_handle();
382 let task = TimerTask::new_oneshot(Duration::from_secs(10), None);
383 let handle = timer.register(alloc_handle, task);
384
385 // Cancel task
386 let cancelled = handle.cancel();
387 assert!(cancelled);
388
389 // Wait for completion notification and verify reason is Cancelled
390 let (rx, _handle) = handle.into_parts();
391 let result = match rx {
392 task::CompletionReceiver::OneShot(receiver) => receiver.wait().await,
393 _ => panic!("Expected OneShot completion receiver"),
394 };
395 assert_eq!(result, TaskCompletion::Cancelled);
396 }
397
398 #[tokio::test]
399 async fn test_batch_completion_reasons() {
400 let timer = TimerWheel::with_defaults();
401
402 // Step 1: Allocate handles
403 let handles = timer.allocate_handles(5);
404
405 // Step 2: Create 5 tasks with 10 seconds delay
406 let tasks: Vec<_> = (0..5)
407 .map(|_| TimerTask::new_oneshot(Duration::from_secs(10), None))
408 .collect();
409
410 // Step 3: Batch register
411 let batch = timer
412 .register_batch(handles, tasks)
413 .expect("register_batch should succeed");
414 let task_ids: Vec<_> = batch.task_ids().to_vec();
415 let (mut receivers, _batch_handle) = batch.into_parts();
416
417 // Cancel first 3 tasks
418 timer.cancel_batch(&task_ids[0..3]);
419
420 // Verify first 3 tasks received Cancelled notification
421 for rx in receivers.drain(0..3) {
422 let result = match rx {
423 task::CompletionReceiver::OneShot(receiver) => receiver.wait().await,
424 _ => panic!("Expected OneShot completion receiver"),
425 };
426 assert_eq!(result, TaskCompletion::Cancelled);
427 }
428
429 // Cancel remaining tasks and verify
430 timer.cancel_batch(&task_ids[3..5]);
431 for rx in receivers {
432 let result = match rx {
433 task::CompletionReceiver::OneShot(receiver) => receiver.wait().await,
434 _ => panic!("Expected OneShot completion receiver"),
435 };
436 assert_eq!(result, TaskCompletion::Cancelled);
437 }
438 }
439}