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