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;
118
119// Re-export public API
120pub use task::{CallbackWrapper, TaskId, TimerTask, TaskCompletion};
121pub use timer::handle::{TimerHandle, TimerHandleWithCompletion, BatchHandle, BatchHandleWithCompletion};
122pub use task::CompletionReceiver;
123pub use timer::TimerWheel;
124pub use service::{TimerService, TaskNotification};
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use std::sync::atomic::{AtomicU32, Ordering};
130    use std::sync::Arc;
131    use std::time::Duration;
132
133    #[tokio::test]
134    async fn test_basic_timer() {
135        let timer = TimerWheel::with_defaults();
136        let counter = Arc::new(AtomicU32::new(0));
137        let counter_clone = Arc::clone(&counter);
138
139        let task = TimerTask::new_oneshot(
140            Duration::from_millis(50),
141            Some(CallbackWrapper::new(move || {
142                let counter =  Arc::clone(&counter_clone);
143                async move {
144                    counter.fetch_add(1, Ordering::SeqCst);
145                }
146            })),
147        );
148        timer.register(task);
149
150        tokio::time::sleep(Duration::from_millis(100)).await;
151        assert_eq!(counter.load(Ordering::SeqCst), 1);
152    }
153
154    #[tokio::test]
155    async fn test_multiple_timers() {
156        let timer = TimerWheel::with_defaults();
157        let counter = Arc::new(AtomicU32::new(0));
158
159        // Create 10 timers
160        for i in 0..10 {
161            let counter_clone = Arc::clone(&counter);
162            let task = TimerTask::new_oneshot(
163                Duration::from_millis(10 * (i + 1)),
164                Some(CallbackWrapper::new(move || {
165                    let counter = Arc::clone(&counter_clone);
166                    async move {
167                        counter.fetch_add(1, Ordering::SeqCst);
168                    }
169                })),
170            );
171            timer.register(task);
172        }
173
174        tokio::time::sleep(Duration::from_millis(200)).await;
175        assert_eq!(counter.load(Ordering::SeqCst), 10);
176    }
177
178    #[tokio::test]
179    async fn test_timer_cancellation() {
180        let timer = TimerWheel::with_defaults();
181        let counter = Arc::new(AtomicU32::new(0));
182
183        // Create 5 timers
184        let mut handles = Vec::new();
185        for _ in 0..5 {
186            let counter_clone = Arc::clone(&counter);
187            let task = TimerTask::new_oneshot(
188                Duration::from_millis(100),
189                Some(CallbackWrapper::new(move || {
190                    let counter = Arc::clone(&counter_clone);
191                    async move {
192                        counter.fetch_add(1, Ordering::SeqCst);
193                    }
194                })),
195            );
196            let handle = timer.register(task);
197            handles.push(handle);
198        }
199
200        // Cancel first 3 timers
201        for i in 0..3 {
202            let cancel_result = handles[i].cancel();
203            assert!(cancel_result);
204        }
205
206        tokio::time::sleep(Duration::from_millis(200)).await;
207        // Only 2 timers should be triggered
208        assert_eq!(counter.load(Ordering::SeqCst), 2);
209    }
210
211    #[tokio::test]
212    async fn test_completion_notification_once() {
213        let timer = TimerWheel::with_defaults();
214        let counter = Arc::new(AtomicU32::new(0));
215        let counter_clone = Arc::clone(&counter);
216
217        let task = TimerTask::new_oneshot(
218            Duration::from_millis(50),
219            Some(CallbackWrapper::new(move || {
220                let counter = Arc::clone(&counter_clone);
221                async move {
222                    counter.fetch_add(1, Ordering::SeqCst);
223                }
224            })),
225        );
226        let handle = timer.register(task);
227
228        // Wait for completion notification
229        let (rx, _handle) = handle.into_parts();
230        match rx {
231            task::CompletionReceiver::OneShot(receiver) => {
232                receiver.wait().await;
233            },
234            _ => panic!("Expected OneShot completion receiver"),
235        }
236
237        // Verify callback has been executed (wait a moment to ensure callback execution is complete)
238        tokio::time::sleep(Duration::from_millis(20)).await;
239        assert_eq!(counter.load(Ordering::SeqCst), 1);
240    }
241
242    #[tokio::test]
243    async fn test_notify_only_timer_once() {
244        let timer = TimerWheel::with_defaults();
245        
246        let task = TimerTask::new_oneshot(Duration::from_millis(50), None);
247        let handle = timer.register(task);
248
249        // Wait for completion notification (no callback, only notification)
250        let (rx, _handle) = handle.into_parts();
251        match rx {
252            task::CompletionReceiver::OneShot(receiver) => {
253                receiver.wait().await;
254            },
255            _ => panic!("Expected OneShot completion receiver"),
256        }
257    }
258
259    #[tokio::test]
260    async fn test_batch_completion_notifications() {
261        let timer = TimerWheel::with_defaults();
262        let counter = Arc::new(AtomicU32::new(0));
263
264        // Create batch callbacks
265        let callbacks: Vec<TimerTask> = (0..5)
266            .map(|i| {
267                let counter = Arc::clone(&counter);
268                let delay = Duration::from_millis(50 + i * 10);
269                let callback = CallbackWrapper::new(move || {
270                    let counter = Arc::clone(&counter);
271                    async move {
272                        counter.fetch_add(1, Ordering::SeqCst);
273                    }
274                });
275                TimerTask::new_oneshot(delay, Some(callback))
276            })
277            .collect();
278
279        let batch = timer.register_batch(callbacks);
280        let (receivers, _batch_handle) = batch.into_parts();
281
282        // Wait for all completion notifications
283        for rx in receivers {
284            match rx {
285                task::CompletionReceiver::OneShot(receiver) => {
286                    receiver.wait().await;
287                },
288                _ => panic!("Expected OneShot completion receiver"),
289            }
290        }
291
292        // Wait a moment to ensure callback execution is complete
293        tokio::time::sleep(Duration::from_millis(50)).await;
294
295        // Verify all callbacks have been executed
296        assert_eq!(counter.load(Ordering::SeqCst), 5);
297    }
298
299    #[tokio::test]
300    async fn test_completion_reason_expired() {
301        let timer = TimerWheel::with_defaults();
302        
303        let task = TimerTask::new_oneshot(Duration::from_millis(50), None);
304        let handle = timer.register(task);
305
306        // Wait for completion notification and verify reason is Expired
307        let (rx, _handle) = handle.into_parts();
308        let result = match rx {
309            task::CompletionReceiver::OneShot(receiver) => {
310                receiver.wait().await
311            },
312            _ => panic!("Expected OneShot completion receiver"),
313        };
314        assert_eq!(result, TaskCompletion::Called);
315    }
316
317    #[tokio::test]
318    async fn test_completion_reason_cancelled() {
319        let timer = TimerWheel::with_defaults();
320        
321        let task = TimerTask::new_oneshot(Duration::from_secs(10), None);
322        let handle = timer.register(task);
323
324        // Cancel task
325        let cancelled = handle.cancel();
326        assert!(cancelled);
327
328        // Wait for completion notification and verify reason is Cancelled
329        let (rx, _handle) = handle.into_parts();
330        let result = match rx {
331            task::CompletionReceiver::OneShot(receiver) => {
332                receiver.wait().await
333            },
334            _ => panic!("Expected OneShot completion receiver"),
335        };
336        assert_eq!(result, TaskCompletion::Cancelled);
337    }
338
339    #[tokio::test]
340    async fn test_batch_completion_reasons() {
341        let timer = TimerWheel::with_defaults();
342        
343        // Create 5 tasks, delay 10 seconds
344        let tasks: Vec<_> = (0..5)
345            .map(|_| TimerTask::new_oneshot(Duration::from_secs(10), None))
346            .collect();
347        
348        let batch = timer.register_batch(tasks);
349        let task_ids: Vec<_> = batch.task_ids().to_vec();
350        let (mut receivers, _batch_handle) = batch.into_parts();
351
352        // Cancel first 3 tasks
353        timer.cancel_batch(&task_ids[0..3]);
354
355        // Verify first 3 tasks received Cancelled notification
356        for rx in receivers.drain(0..3) {
357            let result = match rx {
358                task::CompletionReceiver::OneShot(receiver) => {
359                    receiver.wait().await
360                },
361                _ => panic!("Expected OneShot completion receiver"),
362            };
363            assert_eq!(result, TaskCompletion::Cancelled);
364        }
365
366        // Cancel remaining tasks and verify
367        timer.cancel_batch(&task_ids[3..5]);
368        for rx in receivers {
369            let result = match rx {
370                task::CompletionReceiver::OneShot(receiver) => {
371                    receiver.wait().await
372                },
373                _ => panic!("Expected OneShot completion receiver"),
374            };
375            assert_eq!(result, TaskCompletion::Cancelled);
376        }
377    }
378}