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: Create timer task (使用回调创建定时器任务)
37//!     let callback = Some(CallbackWrapper::new(|| async {
38//!         println!("Timer fired after 1 second!");
39//!     }));
40//!     let task = TimerTask::new_oneshot(Duration::from_secs(1), callback);
41//!     let task_id = task.get_id();
42//!     
43//!     // Step 2: Register timer task and get completion notification (注册定时器任务并获取完成通知)
44//!     let handle = timer.register(task);
45//!     
46//!     // Wait for timer completion (等待定时器完成)
47//!     use kestrel_timer::CompletionReceiver;
48//!     let (rx, _handle) = handle.into_parts();
49//!     match rx {
50//!         CompletionReceiver::OneShot(receiver) => {
51//!             receiver.wait().await;
52//!         },
53//!         _ => {}
54//!     }
55//!     Ok(())
56//! }
57//! ```
58//!
59//! ## English Architecture Description
60//!
61//! ### Timing Wheel Algorithm
62//!
63//! Uses hierarchical timing wheel algorithm with L0 and L1 layers:
64//!
65//! - **L0 Layer (Bottom)**: Handles short delay tasks
66//!   - Slot count: Default 512, configurable, must be power of 2
67//!   - Time precision: Default 10ms, configurable
68//!   - Maximum time span: 5.12 seconds
69//!
70//! - **L1 Layer (Upper)**: Handles long delay tasks
71//!   - Slot count: Default 64, configurable, must be power of 2
72//!   - Time precision: Default 1 second, configurable
73//!   - Maximum time span: 64 seconds
74//!
75//! - **Round Mechanism**: Tasks beyond L1 range use round counting
76//! 
77//! ### Performance Optimization
78//!
79//! - Uses `parking_lot::Mutex` instead of standard library Mutex for better performance
80//!   - Uses `FxHashMap` (rustc-hash) instead of standard HashMap to reduce hash collisions
81//!   - Slot count is power of 2, uses bitwise operations to optimize modulo
82//!   - Task execution in separate tokio tasks to avoid blocking timing wheel advancement
83//! 
84//! 
85//! 
86//! ## 中文架构说明
87//!
88//! ### 时间轮算法
89//!
90//! 采用分层时间轮(Hierarchical Timing Wheel)算法,包含 L0 和 L1 两层:
91//!
92//! - **L0 层(底层)**: 处理短延迟任务
93//!   - 槽位数量: 默认 512 个(可配置,必须是 2 的幂次方)
94//!   - 时间精度: 默认 10ms(可配置)
95//!   - 最大时间跨度: 5.12 秒
96//!
97//! - **L1 层(高层)**: 处理长延迟任务
98//!   - 槽位数量: 默认 64 个(可配置,必须是 2 的幂次方)
99//!   - 时间精度: 默认 1 秒(可配置)
100//!   - 最大时间跨度: 64 秒
101//!
102//! - **轮次机制**: 超出 L1 层范围的任务使用轮次计数处理
103//!
104//! ### 性能优化
105//!
106//! - 使用 `parking_lot::Mutex` 替代标准库的 Mutex,提供更好的性能
107//! - 使用 `FxHashMap`(rustc-hash)替代标准 HashMap,减少哈希冲突
108//! - 槽位数量为 2 的幂次方,使用位运算优化取模操作
109//! - 任务执行在独立的 tokio 任务中,避免阻塞时间轮推进
110//! 
111
112pub mod config;
113pub mod error;
114pub mod task;
115pub mod wheel;
116pub mod timer;
117mod service;
118pub mod utils {
119    pub mod oneshot;
120    pub mod spsc;
121    pub mod ringbuf;
122    pub mod notify;
123    pub(crate) mod vec;
124}
125
126// Re-export public API
127pub use task::{CallbackWrapper, TaskId, TimerTask, TaskCompletion};
128pub use timer::handle::{TimerHandle, TimerHandleWithCompletion, BatchHandle, BatchHandleWithCompletion};
129pub use task::CompletionReceiver;
130pub use timer::TimerWheel;
131pub use service::{TimerService, TaskNotification};
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use std::sync::atomic::{AtomicU32, Ordering};
137    use std::sync::Arc;
138    use std::time::Duration;
139
140    #[tokio::test]
141    async fn test_basic_timer() {
142        let timer = TimerWheel::with_defaults();
143        let counter = Arc::new(AtomicU32::new(0));
144        let counter_clone = Arc::clone(&counter);
145
146        let task = TimerTask::new_oneshot(
147            Duration::from_millis(50),
148            Some(CallbackWrapper::new(move || {
149                let counter =  Arc::clone(&counter_clone);
150                async move {
151                    counter.fetch_add(1, Ordering::SeqCst);
152                }
153            })),
154        );
155        timer.register(task);
156
157        tokio::time::sleep(Duration::from_millis(100)).await;
158        assert_eq!(counter.load(Ordering::SeqCst), 1);
159    }
160
161    #[tokio::test]
162    async fn test_multiple_timers() {
163        let timer = TimerWheel::with_defaults();
164        let counter = Arc::new(AtomicU32::new(0));
165
166        // Create 10 timers
167        for i in 0..10 {
168            let counter_clone = Arc::clone(&counter);
169            let task = TimerTask::new_oneshot(
170                Duration::from_millis(10 * (i + 1)),
171                Some(CallbackWrapper::new(move || {
172                    let counter = Arc::clone(&counter_clone);
173                    async move {
174                        counter.fetch_add(1, Ordering::SeqCst);
175                    }
176                })),
177            );
178            timer.register(task);
179        }
180
181        tokio::time::sleep(Duration::from_millis(200)).await;
182        assert_eq!(counter.load(Ordering::SeqCst), 10);
183    }
184
185    #[tokio::test]
186    async fn test_timer_cancellation() {
187        let timer = TimerWheel::with_defaults();
188        let counter = Arc::new(AtomicU32::new(0));
189
190        // Create 5 timers
191        let mut handles = Vec::new();
192        for _ in 0..5 {
193            let counter_clone = Arc::clone(&counter);
194            let task = TimerTask::new_oneshot(
195                Duration::from_millis(100),
196                Some(CallbackWrapper::new(move || {
197                    let counter = Arc::clone(&counter_clone);
198                    async move {
199                        counter.fetch_add(1, Ordering::SeqCst);
200                    }
201                })),
202            );
203            let handle = timer.register(task);
204            handles.push(handle);
205        }
206
207        // Cancel first 3 timers
208        for i in 0..3 {
209            let cancel_result = handles[i].cancel();
210            assert!(cancel_result);
211        }
212
213        tokio::time::sleep(Duration::from_millis(200)).await;
214        // Only 2 timers should be triggered
215        assert_eq!(counter.load(Ordering::SeqCst), 2);
216    }
217
218    #[tokio::test]
219    async fn test_completion_notification_once() {
220        let timer = TimerWheel::with_defaults();
221        let counter = Arc::new(AtomicU32::new(0));
222        let counter_clone = Arc::clone(&counter);
223
224        let task = TimerTask::new_oneshot(
225            Duration::from_millis(50),
226            Some(CallbackWrapper::new(move || {
227                let counter = Arc::clone(&counter_clone);
228                async move {
229                    counter.fetch_add(1, Ordering::SeqCst);
230                }
231            })),
232        );
233        let handle = timer.register(task);
234
235        // Wait for completion notification
236        let (rx, _handle) = handle.into_parts();
237        match rx {
238            task::CompletionReceiver::OneShot(receiver) => {
239                receiver.wait().await;
240            },
241            _ => panic!("Expected OneShot completion receiver"),
242        }
243
244        // Verify callback has been executed (wait a moment to ensure callback execution is complete)
245        tokio::time::sleep(Duration::from_millis(20)).await;
246        assert_eq!(counter.load(Ordering::SeqCst), 1);
247    }
248
249    #[tokio::test]
250    async fn test_notify_only_timer_once() {
251        let timer = TimerWheel::with_defaults();
252        
253        let task = TimerTask::new_oneshot(Duration::from_millis(50), None);
254        let handle = timer.register(task);
255
256        // Wait for completion notification (no callback, only notification)
257        let (rx, _handle) = handle.into_parts();
258        match rx {
259            task::CompletionReceiver::OneShot(receiver) => {
260                receiver.wait().await;
261            },
262            _ => panic!("Expected OneShot completion receiver"),
263        }
264    }
265
266    #[tokio::test]
267    async fn test_batch_completion_notifications() {
268        let timer = TimerWheel::with_defaults();
269        let counter = Arc::new(AtomicU32::new(0));
270
271        // Create batch callbacks
272        let callbacks: Vec<TimerTask> = (0..5)
273            .map(|i| {
274                let counter = Arc::clone(&counter);
275                let delay = Duration::from_millis(50 + i * 10);
276                let callback = CallbackWrapper::new(move || {
277                    let counter = Arc::clone(&counter);
278                    async move {
279                        counter.fetch_add(1, Ordering::SeqCst);
280                    }
281                });
282                TimerTask::new_oneshot(delay, Some(callback))
283            })
284            .collect();
285
286        let batch = timer.register_batch(callbacks);
287        let (receivers, _batch_handle) = batch.into_parts();
288
289        // Wait for all completion notifications
290        for rx in receivers {
291            match rx {
292                task::CompletionReceiver::OneShot(receiver) => {
293                    receiver.wait().await;
294                },
295                _ => panic!("Expected OneShot completion receiver"),
296            }
297        }
298
299        // Wait a moment to ensure callback execution is complete
300        tokio::time::sleep(Duration::from_millis(50)).await;
301
302        // Verify all callbacks have been executed
303        assert_eq!(counter.load(Ordering::SeqCst), 5);
304    }
305
306    #[tokio::test]
307    async fn test_completion_reason_expired() {
308        let timer = TimerWheel::with_defaults();
309        
310        let task = TimerTask::new_oneshot(Duration::from_millis(50), None);
311        let handle = timer.register(task);
312
313        // Wait for completion notification and verify reason is Expired
314        let (rx, _handle) = handle.into_parts();
315        let result = match rx {
316            task::CompletionReceiver::OneShot(receiver) => {
317                receiver.wait().await
318            },
319            _ => panic!("Expected OneShot completion receiver"),
320        };
321        assert_eq!(result, TaskCompletion::Called);
322    }
323
324    #[tokio::test]
325    async fn test_completion_reason_cancelled() {
326        let timer = TimerWheel::with_defaults();
327        
328        let task = TimerTask::new_oneshot(Duration::from_secs(10), None);
329        let handle = timer.register(task);
330
331        // Cancel task
332        let cancelled = handle.cancel();
333        assert!(cancelled);
334
335        // Wait for completion notification and verify reason is Cancelled
336        let (rx, _handle) = handle.into_parts();
337        let result = match rx {
338            task::CompletionReceiver::OneShot(receiver) => {
339                receiver.wait().await
340            },
341            _ => panic!("Expected OneShot completion receiver"),
342        };
343        assert_eq!(result, TaskCompletion::Cancelled);
344    }
345
346    #[tokio::test]
347    async fn test_batch_completion_reasons() {
348        let timer = TimerWheel::with_defaults();
349        
350        // Create 5 tasks, delay 10 seconds
351        let tasks: Vec<_> = (0..5)
352            .map(|_| TimerTask::new_oneshot(Duration::from_secs(10), None))
353            .collect();
354        
355        let batch = timer.register_batch(tasks);
356        let task_ids: Vec<_> = batch.task_ids().to_vec();
357        let (mut receivers, _batch_handle) = batch.into_parts();
358
359        // Cancel first 3 tasks
360        timer.cancel_batch(&task_ids[0..3]);
361
362        // Verify first 3 tasks received Cancelled notification
363        for rx in receivers.drain(0..3) {
364            let result = match rx {
365                task::CompletionReceiver::OneShot(receiver) => {
366                    receiver.wait().await
367                },
368                _ => panic!("Expected OneShot completion receiver"),
369            };
370            assert_eq!(result, TaskCompletion::Cancelled);
371        }
372
373        // Cancel remaining tasks and verify
374        timer.cancel_batch(&task_ids[3..5]);
375        for rx in receivers {
376            let result = match rx {
377                task::CompletionReceiver::OneShot(receiver) => {
378                    receiver.wait().await
379                },
380                _ => panic!("Expected OneShot completion receiver"),
381            };
382            assert_eq!(result, TaskCompletion::Cancelled);
383        }
384    }
385}