use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use tokio::runtime::Handle;
use tokio::sync::Notify;
use tokio::task::AbortHandle;
type FlushFn<T> = dyn Fn(Vec<T>) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync;
tokio::task_local! {
static IN_FLUSH: usize;
}
static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
struct State<T> {
buf: Vec<T>,
pending: VecDeque<Vec<T>>,
timer: Option<AbortHandle>,
timer_gen: u64,
closed: bool,
}
struct Inner<T> {
id: usize,
threshold: usize,
window: Duration,
flush: Box<FlushFn<T>>,
handle: Handle,
state: Mutex<State<T>>,
draining: AtomicBool,
idle: Notify,
}
struct DrainGuard<T: Send + 'static> {
inner: Arc<Inner<T>>,
armed: bool,
}
impl<T: Send + 'static> Drop for DrainGuard<T> {
fn drop(&mut self) {
if self.armed {
self.inner.draining.store(false, Ordering::Release);
self.inner.idle.notify_waiters();
}
}
}
pub struct Debounced<T> {
inner: Arc<Inner<T>>,
}
impl<T> Clone for Debounced<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> std::fmt::Debug for Debounced<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Debounced")
.field("threshold", &self.inner.threshold)
.field("window", &self.inner.window)
.finish_non_exhaustive()
}
}
impl<T: Send + 'static> Debounced<T> {
pub fn new<F, Fut>(threshold: usize, window: Duration, flush: F) -> Self
where
F: Fn(Vec<T>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
Self::with_handle(Handle::current(), threshold, window, flush)
}
pub fn with_handle<F, Fut>(handle: Handle, threshold: usize, window: Duration, flush: F) -> Self
where
F: Fn(Vec<T>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let threshold = threshold.max(1);
let window = if window.is_zero() {
Duration::from_secs(1)
} else {
window
};
Self {
inner: Arc::new(Inner {
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
threshold,
window,
flush: Box::new(move |batch| Box::pin(flush(batch))),
handle,
state: Mutex::new(State {
buf: Vec::new(),
pending: VecDeque::new(),
timer: None,
timer_gen: 0,
closed: false,
}),
draining: AtomicBool::new(false),
idle: Notify::new(),
}),
}
}
pub fn add(&self, items: impl IntoIterator<Item = T>) {
let mut s = self.inner.state();
let before = s.buf.len();
s.buf.extend(items);
if s.buf.len() == before {
return;
}
if s.closed || s.buf.len() >= self.inner.threshold {
enqueue(&mut s);
} else if s.timer.is_none() {
let gen_ = s.timer_gen;
let inner = self.inner.clone();
let task = self.inner.handle.spawn(async move {
tokio::time::sleep(inner.window).await;
let mut s = inner.state();
if s.timer_gen == gen_ {
s.timer = None; enqueue(&mut s);
Inner::ensure_drain(&inner, &mut s);
}
});
s.timer = Some(task.abort_handle());
}
Inner::ensure_drain(&self.inner, &mut s);
}
pub fn flush(&self) {
let mut s = self.inner.state();
enqueue(&mut s);
Inner::ensure_drain(&self.inner, &mut s);
}
pub async fn close(&self) {
{
let mut s = self.inner.state();
s.closed = true;
enqueue(&mut s);
Inner::ensure_drain(&self.inner, &mut s);
}
if IN_FLUSH.try_with(|id| *id == self.inner.id).unwrap_or(false) {
return;
}
loop {
let notified = self.inner.idle.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if !self.inner.draining.load(Ordering::Acquire) {
return;
}
notified.await;
}
}
pub fn len(&self) -> usize {
let s = self.inner.state();
s.buf.len() + s.pending.iter().map(Vec::len).sum::<usize>()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
fn enqueue<T>(s: &mut State<T>) {
if !s.buf.is_empty() {
let batch = std::mem::take(&mut s.buf);
s.pending.push_back(batch);
}
if let Some(timer) = s.timer.take() {
timer.abort();
}
s.timer_gen = s.timer_gen.wrapping_add(1);
}
impl<T: Send + 'static> Inner<T> {
fn state(&self) -> MutexGuard<'_, State<T>> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
fn ensure_drain(this: &Arc<Self>, s: &mut State<T>) {
if this.draining.load(Ordering::Acquire) || s.pending.is_empty() {
return;
}
this.draining.store(true, Ordering::Release);
let guard = DrainGuard {
inner: this.clone(),
armed: true,
};
this.handle.spawn(Self::drain(guard));
}
async fn drain(mut guard: DrainGuard<T>) {
let this = guard.inner.clone();
loop {
let batch = {
let mut s = this.state();
match s.pending.pop_front() {
Some(b) => b,
None => {
this.draining.store(false, Ordering::Release);
guard.armed = false;
drop(s);
this.idle.notify_waiters();
return;
}
}
};
let inner = this.clone();
let task = this.handle.spawn(async move {
let id = inner.id;
IN_FLUSH.scope(id, async move { (inner.flush)(batch).await }).await;
});
let _ = task.await;
}
}
}
#[cfg(test)]
mod tests {
use std::sync::OnceLock;
use super::*;
type Log = Arc<Mutex<Vec<Vec<u32>>>>;
fn recorder() -> (Log, impl Fn(Vec<u32>) -> std::future::Ready<()> + Send + Sync + 'static) {
let log: Log = Arc::default();
let l = log.clone();
(log, move |batch| {
l.lock().unwrap().push(batch);
std::future::ready(())
})
}
async fn settle() {
for _ in 0..20 {
tokio::task::yield_now().await;
}
}
#[tokio::test(start_paused = true)]
async fn threshold_then_close() {
let (log, f) = recorder();
let q = Debounced::new(3, Duration::from_secs(3600), f);
q.add([1, 2]);
settle().await;
assert!(log.lock().unwrap().is_empty());
q.add([3, 4]);
settle().await;
assert_eq!(*log.lock().unwrap(), vec![vec![1, 2, 3, 4]]);
q.add([5]);
assert_eq!(q.len(), 1);
q.close().await;
assert_eq!(*log.lock().unwrap(), vec![vec![1, 2, 3, 4], vec![5]]);
assert!(q.is_empty());
q.add([6]);
settle().await;
assert_eq!(log.lock().unwrap().last(), Some(&vec![6]));
}
#[tokio::test(start_paused = true)]
async fn window_flush() {
let (log, f) = recorder();
let q = Debounced::new(100, Duration::from_millis(50), f);
q.add([1]);
tokio::time::sleep(Duration::from_millis(30)).await;
q.add([2]);
settle().await;
assert!(log.lock().unwrap().is_empty());
tokio::time::sleep(Duration::from_millis(25)).await;
settle().await;
assert_eq!(*log.lock().unwrap(), vec![vec![1, 2]]);
q.add([3]);
q.flush();
q.add([4]);
tokio::time::sleep(Duration::from_millis(60)).await;
settle().await;
assert_eq!(*log.lock().unwrap(), vec![vec![1, 2], vec![3], vec![4]]);
q.flush(); q.close().await;
assert_eq!(log.lock().unwrap().len(), 3);
}
#[tokio::test(start_paused = true)]
async fn serial_fifo() {
let log: Log = Arc::default();
let in_flight = Arc::new(AtomicUsize::new(0));
let (l, f) = (log.clone(), in_flight.clone());
let q = Debounced::new(1, Duration::from_secs(1), move |batch: Vec<u32>| {
let (l, f) = (l.clone(), f.clone());
async move {
assert_eq!(f.fetch_add(1, Ordering::SeqCst), 0, "flush ran concurrently");
tokio::time::sleep(Duration::from_millis(5)).await;
l.lock().unwrap().push(batch);
f.fetch_sub(1, Ordering::SeqCst);
}
});
for i in 0..10 {
q.add([i]);
}
q.close().await;
let got: Vec<u32> = log.lock().unwrap().iter().flatten().copied().collect();
assert_eq!(got, (0..10).collect::<Vec<_>>());
}
#[tokio::test(start_paused = true)]
async fn reentrant_retry_and_close() {
let log: Log = Arc::default();
let cell: Arc<OnceLock<Debounced<u32>>> = Arc::default();
let (l, c) = (log.clone(), cell.clone());
let q = Debounced::new(1, Duration::from_secs(1), move |batch: Vec<u32>| {
let (l, c) = (l.clone(), c.clone());
async move {
let q = c.get().unwrap();
let first = l.lock().unwrap().is_empty();
l.lock().unwrap().push(batch.clone());
if first {
q.add(batch.into_iter().map(|x| x + 100)); q.close().await; }
}
});
cell.set(q.clone()).unwrap();
q.add([1]);
q.close().await;
assert_eq!(*log.lock().unwrap(), vec![vec![1], vec![101]]);
}
#[tokio::test(start_paused = true)]
async fn panic_drops_batch() {
let log: Log = Arc::default();
let l = log.clone();
let q = Debounced::new(1, Duration::from_secs(1), move |batch: Vec<u32>| {
let l = l.clone();
async move {
if batch == [1] {
panic!("boom");
}
l.lock().unwrap().push(batch);
}
});
q.add([1]);
q.add([2]);
q.close().await;
assert_eq!(*log.lock().unwrap(), vec![vec![2]]);
}
#[tokio::test(start_paused = true)]
async fn sync_panic_in_closure_does_not_wedge() {
let log: Log = Arc::default();
let l = log.clone();
let q = Debounced::new(1, Duration::from_secs(1), move |batch: Vec<u32>| {
assert_ne!(batch, [1], "sync panic before returning the future");
let l = l.clone();
async move {
l.lock().unwrap().push(batch);
}
});
q.add([1]);
q.add([2]);
q.close().await;
assert_eq!(*log.lock().unwrap(), vec![vec![2]]);
}
#[test]
fn runtime_shutdown_does_not_hang_close() {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let handle = rt.handle().clone();
let (_log, f) = recorder();
let q = Debounced::with_handle(handle, 100, Duration::from_secs(60), f);
q.add([1]);
drop(rt); let other = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
other.block_on(async {
tokio::time::timeout(Duration::from_secs(5), q.close())
.await
.expect("close must not hang");
});
}
#[test]
fn works_from_non_runtime_thread() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let (log, f) = recorder();
let q = Debounced::with_handle(rt.handle().clone(), 2, Duration::from_secs(60), f);
std::thread::spawn({
let q = q.clone();
move || q.add([1, 2])
})
.join()
.unwrap();
rt.block_on(q.close());
assert_eq!(*log.lock().unwrap(), vec![vec![1, 2]]);
}
}