1use hierarchical_hash_wheel_timer::wheels::quad_wheel::no_prune;
2use hierarchical_hash_wheel_timer::wheels::Skip;
3pub use hierarchical_hash_wheel_timer::TimerError;
4use kumo_chrono_helper::Instant;
5use kumo_prometheus::declare_metric;
6use std::time::Duration;
7
8pub use hierarchical_hash_wheel_timer::wheels::quad_wheel::QuadWheelWithOverflow;
9pub use hierarchical_hash_wheel_timer::wheels::TimerEntryWithDelay;
10
11pub struct TimeQ<EntryType: TimerEntryWithDelay> {
17 wheel: QuadWheelWithOverflow<EntryType>,
18 last_check: Instant,
19 len: usize,
20}
21
22declare_metric! {
23static POP_INTERVAL: Histogram(
28 "timeq_pop_interval",
29 vec![3.0, 4.0, 5.0, 8.0, 10.0, 12.0, 15.0, 20.0, 25.0, 30.0]
33);
34}
35
36#[must_use]
37pub enum PopResult<EntryType> {
38 Items(Vec<EntryType>),
40 Sleep(Duration),
42 Empty,
44}
45
46impl<EntryType: TimerEntryWithDelay> Default for TimeQ<EntryType> {
47 fn default() -> Self {
48 Self::new()
49 }
50}
51
52impl<EntryType: TimerEntryWithDelay> TimeQ<EntryType> {
53 pub fn new() -> Self {
54 Self {
55 wheel: QuadWheelWithOverflow::new(no_prune),
56 last_check: Instant::now(),
57 len: 0,
58 }
59 }
60
61 pub fn is_empty(&self) -> bool {
63 matches!(self.wheel.can_skip(), Skip::Empty)
64 }
65
66 pub fn len(&self) -> usize {
67 self.len
68 }
69
70 pub fn insert(&mut self, entry: EntryType) -> Result<(), TimerError<EntryType>> {
72 self.wheel.insert(entry)?;
73 self.len += 1;
74 Ok(())
75 }
76
77 pub fn pop(&mut self) -> PopResult<EntryType> {
79 let now = Instant::now();
80 let elapsed = now.saturating_duration_since(self.last_check);
81 self.last_check = now;
82 let mut elapsed_ms = elapsed.as_millis() as u32;
83 POP_INTERVAL.observe(elapsed.as_secs_f64());
84
85 let mut items = vec![];
86
87 while elapsed_ms > 0 {
88 match self.wheel.can_skip() {
89 Skip::Empty => break,
90 Skip::None => {
91 items.append(&mut self.wheel.tick());
92 elapsed_ms -= 1;
93 }
94 Skip::Millis(m) => {
95 let amount = m.min(elapsed_ms);
96 self.wheel.skip(amount);
97 elapsed_ms -= amount;
98 }
99 }
100 }
101
102 if !items.is_empty() {
103 self.len -= items.len();
104 return PopResult::Items(items);
105 }
106
107 match self.wheel.can_skip() {
108 Skip::None => PopResult::Sleep(Duration::from_millis(1)),
109 Skip::Empty => PopResult::Empty,
110 Skip::Millis(ms) => PopResult::Sleep(Duration::from_millis(ms.into())),
111 }
112 }
113
114 pub fn drain(&mut self) -> Vec<EntryType> {
117 let mut items = vec![];
118 loop {
119 match self.wheel.can_skip() {
120 Skip::Empty => {
121 self.last_check = Instant::now();
122 self.len = 0;
123 return items;
124 }
125 Skip::None => {
126 items.append(&mut self.wheel.tick());
127 }
128 Skip::Millis(m) => {
129 self.wheel.skip(m);
130 }
131 }
132 }
133 }
134}
135
136#[cfg(test)]
137mod tests {
138 use super::*;
139
140 #[derive(Debug, PartialEq, Clone)]
141 struct Entry {
142 id: u64,
143 value: &'static str,
144 delay: Duration,
145 }
146
147 impl TimerEntryWithDelay for &Entry {
148 fn delay(&self) -> Duration {
149 self.delay
150 }
151 }
152
153 #[test]
154 fn draining() {
155 let item1 = Entry {
156 id: 1,
157 value: "foo",
158 delay: Duration::from_millis(1),
159 };
160 let item2 = Entry {
161 id: 2,
162 value: "bar",
163 delay: Duration::from_millis(10),
164 };
165 let item3 = Entry {
166 id: 3,
167 value: "baz",
168 delay: Duration::from_millis(5),
169 };
170
171 let mut queue = TimeQ::new();
172 queue.insert(&item1).unwrap();
173 queue.insert(&item2).unwrap();
174 queue.insert(&item3).unwrap();
175
176 let items = queue.drain();
177 assert_eq!(queue.len(), 0);
178 assert!(queue.is_empty());
179 assert_eq!(items, vec![&item1, &item3, &item2]);
180 }
181
182 #[test]
183 fn basic_queue() {
184 let mut queue = TimeQ::new();
185
186 let item1 = Entry {
187 id: 1,
188 value: "foo",
189 delay: Duration::from_millis(1),
190 };
191 let item2 = Entry {
192 id: 2,
193 value: "bar",
194 delay: Duration::from_secs(1),
195 };
196 let item3 = Entry {
197 id: 3,
198 value: "baz",
199 delay: Duration::from_millis(100),
200 };
201
202 queue.insert(&item1).unwrap();
203 queue.insert(&item2).unwrap();
204 queue.insert(&item3).unwrap();
205
206 assert_eq!(queue.len(), 3);
207 assert!(!queue.is_empty());
208
209 std::thread::sleep(Duration::from_millis(2));
210
211 match queue.pop() {
212 PopResult::Items(items) => assert_eq!(items, vec![&item1]),
213 _ => unreachable!(),
214 }
215
216 assert_eq!(queue.len(), 2);
217 assert!(!queue.is_empty());
218
219 std::thread::sleep(Duration::from_millis(2));
220
221 match queue.pop() {
222 PopResult::Sleep(ms) => std::thread::sleep(ms),
223 _ => unreachable!(),
224 }
225
226 std::thread::sleep(Duration::from_millis(100));
229
230 match queue.pop() {
231 PopResult::Items(items) => assert_eq!(items, vec![&item3]),
232 PopResult::Sleep(ms) => unreachable!("still have {ms:?} to go"),
233 _ => unreachable!(),
234 }
235
236 assert_eq!(queue.len(), 1);
237 assert!(!queue.is_empty());
238
239 std::thread::sleep(Duration::from_secs(1));
240 match queue.pop() {
241 PopResult::Items(items) => assert_eq!(items, vec![&item2]),
242 _ => unreachable!(),
243 }
244
245 assert_eq!(queue.len(), 0);
246 assert!(queue.is_empty());
247 }
248}