1use std::collections::VecDeque;
2use std::future::Future;
3use std::pin::Pin;
4use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
5use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
6use std::time::Duration;
7
8use tokio::runtime::Handle;
9use tokio::sync::Notify;
10use tokio::task::AbortHandle;
11
12type FlushFn<T> = dyn Fn(Vec<T>) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync;
13
14tokio::task_local! {
15 static IN_FLUSH: usize;
17}
18
19static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
20
21struct State<T> {
22 buf: Vec<T>,
24 pending: VecDeque<Vec<T>>,
26 timer: Option<AbortHandle>,
27 timer_gen: u64,
29 closed: bool,
30}
31
32struct Inner<T> {
33 id: usize,
34 threshold: usize,
35 window: Duration,
36 flush: Box<FlushFn<T>>,
37 handle: Handle,
38 state: Mutex<State<T>>,
39 draining: AtomicBool,
42 idle: Notify,
43}
44
45struct DrainGuard<T: Send + 'static> {
47 inner: Arc<Inner<T>>,
48 armed: bool,
49}
50
51impl<T: Send + 'static> Drop for DrainGuard<T> {
52 fn drop(&mut self) {
53 if self.armed {
54 self.inner.draining.store(false, Ordering::Release);
56 self.inner.idle.notify_waiters();
57 }
58 }
59}
60
61pub struct Debounced<T> {
85 inner: Arc<Inner<T>>,
86}
87
88impl<T> Clone for Debounced<T> {
89 fn clone(&self) -> Self {
90 Self {
91 inner: self.inner.clone(),
92 }
93 }
94}
95
96impl<T> std::fmt::Debug for Debounced<T> {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 f.debug_struct("Debounced")
99 .field("threshold", &self.inner.threshold)
100 .field("window", &self.inner.window)
101 .finish_non_exhaustive()
102 }
103}
104
105impl<T: Send + 'static> Debounced<T> {
106 pub fn new<F, Fut>(threshold: usize, window: Duration, flush: F) -> Self
112 where
113 F: Fn(Vec<T>) -> Fut + Send + Sync + 'static,
114 Fut: Future<Output = ()> + Send + 'static,
115 {
116 Self::with_handle(Handle::current(), threshold, window, flush)
117 }
118
119 pub fn with_handle<F, Fut>(handle: Handle, threshold: usize, window: Duration, flush: F) -> Self
121 where
122 F: Fn(Vec<T>) -> Fut + Send + Sync + 'static,
123 Fut: Future<Output = ()> + Send + 'static,
124 {
125 let threshold = threshold.max(1);
126 let window = if window.is_zero() {
127 Duration::from_secs(1)
128 } else {
129 window
130 };
131 Self {
132 inner: Arc::new(Inner {
133 id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
134 threshold,
135 window,
136 flush: Box::new(move |batch| Box::pin(flush(batch))),
137 handle,
138 state: Mutex::new(State {
139 buf: Vec::new(),
140 pending: VecDeque::new(),
141 timer: None,
142 timer_gen: 0,
143 closed: false,
144 }),
145 draining: AtomicBool::new(false),
146 idle: Notify::new(),
147 }),
148 }
149 }
150
151 pub fn add(&self, items: impl IntoIterator<Item = T>) {
153 let mut s = self.inner.state();
154 let before = s.buf.len();
155 s.buf.extend(items);
156 if s.buf.len() == before {
157 return;
158 }
159 if s.closed || s.buf.len() >= self.inner.threshold {
160 enqueue(&mut s);
161 } else if s.timer.is_none() {
162 let gen_ = s.timer_gen;
164 let inner = self.inner.clone();
165 let task = self.inner.handle.spawn(async move {
166 tokio::time::sleep(inner.window).await;
167 let mut s = inner.state();
168 if s.timer_gen == gen_ {
169 s.timer = None; enqueue(&mut s);
171 Inner::ensure_drain(&inner, &mut s);
172 }
173 });
174 s.timer = Some(task.abort_handle());
175 }
176 Inner::ensure_drain(&self.inner, &mut s);
177 }
178
179 pub fn flush(&self) {
181 let mut s = self.inner.state();
182 enqueue(&mut s);
183 Inner::ensure_drain(&self.inner, &mut s);
184 }
185
186 pub async fn close(&self) {
190 {
191 let mut s = self.inner.state();
192 s.closed = true;
193 enqueue(&mut s);
194 Inner::ensure_drain(&self.inner, &mut s);
195 }
196 if IN_FLUSH.try_with(|id| *id == self.inner.id).unwrap_or(false) {
197 return;
198 }
199 loop {
200 let notified = self.inner.idle.notified();
201 tokio::pin!(notified);
202 notified.as_mut().enable();
203 if !self.inner.draining.load(Ordering::Acquire) {
204 return;
205 }
206 notified.await;
207 }
208 }
209
210 pub fn len(&self) -> usize {
212 let s = self.inner.state();
213 s.buf.len() + s.pending.iter().map(Vec::len).sum::<usize>()
214 }
215
216 pub fn is_empty(&self) -> bool {
218 self.len() == 0
219 }
220}
221
222fn enqueue<T>(s: &mut State<T>) {
224 if !s.buf.is_empty() {
225 let batch = std::mem::take(&mut s.buf);
226 s.pending.push_back(batch);
227 }
228 if let Some(timer) = s.timer.take() {
229 timer.abort();
230 }
231 s.timer_gen = s.timer_gen.wrapping_add(1);
232}
233
234impl<T: Send + 'static> Inner<T> {
235 fn state(&self) -> MutexGuard<'_, State<T>> {
236 self.state.lock().unwrap_or_else(PoisonError::into_inner)
238 }
239
240 fn ensure_drain(this: &Arc<Self>, s: &mut State<T>) {
242 if this.draining.load(Ordering::Acquire) || s.pending.is_empty() {
244 return;
245 }
246 this.draining.store(true, Ordering::Release);
247 let guard = DrainGuard {
248 inner: this.clone(),
249 armed: true,
250 };
251 this.handle.spawn(Self::drain(guard));
252 }
253
254 async fn drain(mut guard: DrainGuard<T>) {
255 let this = guard.inner.clone();
256 loop {
257 let batch = {
258 let mut s = this.state();
259 match s.pending.pop_front() {
260 Some(b) => b,
261 None => {
262 this.draining.store(false, Ordering::Release);
263 guard.armed = false;
264 drop(s);
265 this.idle.notify_waiters();
266 return;
267 }
268 }
269 };
270 let inner = this.clone();
272 let task = this.handle.spawn(async move {
273 let id = inner.id;
274 IN_FLUSH.scope(id, async move { (inner.flush)(batch).await }).await;
275 });
276 let _ = task.await;
277 }
278 }
279}
280
281#[cfg(test)]
282mod tests {
283 use std::sync::OnceLock;
284
285 use super::*;
286
287 type Log = Arc<Mutex<Vec<Vec<u32>>>>;
288
289 fn recorder() -> (Log, impl Fn(Vec<u32>) -> std::future::Ready<()> + Send + Sync + 'static) {
290 let log: Log = Arc::default();
291 let l = log.clone();
292 (log, move |batch| {
293 l.lock().unwrap().push(batch);
294 std::future::ready(())
295 })
296 }
297
298 async fn settle() {
299 for _ in 0..20 {
300 tokio::task::yield_now().await;
301 }
302 }
303
304 #[tokio::test(start_paused = true)]
305 async fn threshold_then_close() {
306 let (log, f) = recorder();
307 let q = Debounced::new(3, Duration::from_secs(3600), f);
308 q.add([1, 2]);
309 settle().await;
310 assert!(log.lock().unwrap().is_empty());
311 q.add([3, 4]);
312 settle().await;
313 assert_eq!(*log.lock().unwrap(), vec![vec![1, 2, 3, 4]]);
314 q.add([5]);
315 assert_eq!(q.len(), 1);
316 q.close().await;
317 assert_eq!(*log.lock().unwrap(), vec![vec![1, 2, 3, 4], vec![5]]);
318 assert!(q.is_empty());
319
320 q.add([6]);
322 settle().await;
323 assert_eq!(log.lock().unwrap().last(), Some(&vec![6]));
324 }
325
326 #[tokio::test(start_paused = true)]
327 async fn window_flush() {
328 let (log, f) = recorder();
329 let q = Debounced::new(100, Duration::from_millis(50), f);
330 q.add([1]);
331 tokio::time::sleep(Duration::from_millis(30)).await;
332 q.add([2]);
333 settle().await;
334 assert!(log.lock().unwrap().is_empty());
335 tokio::time::sleep(Duration::from_millis(25)).await;
336 settle().await;
337 assert_eq!(*log.lock().unwrap(), vec![vec![1, 2]]);
338
339 q.add([3]);
341 q.flush();
342 q.add([4]);
343 tokio::time::sleep(Duration::from_millis(60)).await;
344 settle().await;
345 assert_eq!(*log.lock().unwrap(), vec![vec![1, 2], vec![3], vec![4]]);
346 q.flush(); q.close().await;
348 assert_eq!(log.lock().unwrap().len(), 3);
349 }
350
351 #[tokio::test(start_paused = true)]
352 async fn serial_fifo() {
353 let log: Log = Arc::default();
354 let in_flight = Arc::new(AtomicUsize::new(0));
355 let (l, f) = (log.clone(), in_flight.clone());
356 let q = Debounced::new(1, Duration::from_secs(1), move |batch: Vec<u32>| {
357 let (l, f) = (l.clone(), f.clone());
358 async move {
359 assert_eq!(f.fetch_add(1, Ordering::SeqCst), 0, "flush ran concurrently");
360 tokio::time::sleep(Duration::from_millis(5)).await;
361 l.lock().unwrap().push(batch);
362 f.fetch_sub(1, Ordering::SeqCst);
363 }
364 });
365 for i in 0..10 {
366 q.add([i]);
367 }
368 q.close().await;
369 let got: Vec<u32> = log.lock().unwrap().iter().flatten().copied().collect();
370 assert_eq!(got, (0..10).collect::<Vec<_>>());
371 }
372
373 #[tokio::test(start_paused = true)]
374 async fn reentrant_retry_and_close() {
375 let log: Log = Arc::default();
376 let cell: Arc<OnceLock<Debounced<u32>>> = Arc::default();
377 let (l, c) = (log.clone(), cell.clone());
378 let q = Debounced::new(1, Duration::from_secs(1), move |batch: Vec<u32>| {
379 let (l, c) = (l.clone(), c.clone());
380 async move {
381 let q = c.get().unwrap();
382 let first = l.lock().unwrap().is_empty();
383 l.lock().unwrap().push(batch.clone());
384 if first {
385 q.add(batch.into_iter().map(|x| x + 100)); q.close().await; }
388 }
389 });
390 cell.set(q.clone()).unwrap();
391 q.add([1]);
392 q.close().await;
393 assert_eq!(*log.lock().unwrap(), vec![vec![1], vec![101]]);
394 }
395
396 #[tokio::test(start_paused = true)]
397 async fn panic_drops_batch() {
398 let log: Log = Arc::default();
399 let l = log.clone();
400 let q = Debounced::new(1, Duration::from_secs(1), move |batch: Vec<u32>| {
401 let l = l.clone();
402 async move {
403 if batch == [1] {
404 panic!("boom");
405 }
406 l.lock().unwrap().push(batch);
407 }
408 });
409 q.add([1]);
410 q.add([2]);
411 q.close().await;
412 assert_eq!(*log.lock().unwrap(), vec![vec![2]]);
413 }
414
415 #[tokio::test(start_paused = true)]
416 async fn sync_panic_in_closure_does_not_wedge() {
417 let log: Log = Arc::default();
418 let l = log.clone();
419 let q = Debounced::new(1, Duration::from_secs(1), move |batch: Vec<u32>| {
420 assert_ne!(batch, [1], "sync panic before returning the future");
421 let l = l.clone();
422 async move {
423 l.lock().unwrap().push(batch);
424 }
425 });
426 q.add([1]);
427 q.add([2]);
428 q.close().await;
429 assert_eq!(*log.lock().unwrap(), vec![vec![2]]);
430 }
431
432 #[test]
433 fn runtime_shutdown_does_not_hang_close() {
434 let rt = tokio::runtime::Builder::new_current_thread()
435 .enable_all()
436 .build()
437 .unwrap();
438 let handle = rt.handle().clone();
439 let (_log, f) = recorder();
440 let q = Debounced::with_handle(handle, 100, Duration::from_secs(60), f);
441 q.add([1]);
442 drop(rt); let other = tokio::runtime::Builder::new_current_thread()
444 .enable_all()
445 .build()
446 .unwrap();
447 other.block_on(async {
448 tokio::time::timeout(Duration::from_secs(5), q.close())
449 .await
450 .expect("close must not hang");
451 });
452 }
453
454 #[test]
455 fn works_from_non_runtime_thread() {
456 let rt = tokio::runtime::Builder::new_multi_thread()
457 .worker_threads(1)
458 .enable_all()
459 .build()
460 .unwrap();
461 let (log, f) = recorder();
462 let q = Debounced::with_handle(rt.handle().clone(), 2, Duration::from_secs(60), f);
463 std::thread::spawn({
464 let q = q.clone();
465 move || q.add([1, 2])
466 })
467 .join()
468 .unwrap();
469 rt.block_on(q.close());
470 assert_eq!(*log.lock().unwrap(), vec![vec![1, 2]]);
471 }
472}