Skip to main content

rust_web_utils/cronutil/
debounced.rs

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    /// 正在执行的刷新回调所属实例 id, 用于识别回调内重入调用 close
16    static IN_FLUSH: usize;
17}
18
19static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
20
21struct State<T> {
22    /// 未成批的缓冲
23    buf: Vec<T>,
24    /// 已成批待刷新的 FIFO 队列
25    pending: VecDeque<Vec<T>>,
26    timer: Option<AbortHandle>,
27    /// 时间窗定时器代号; 每次成批递增, 过期定时器触发时据此作废
28    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    /// 同一时刻只有一个 drain 任务, 保证回调串行且 FIFO。正常路径只在持有 `state` 锁时读写;
40    /// drain 任务异常结束 (运行时关闭) 时由 [`DrainGuard`] 无锁复位, 避免 close 永久等待
41    draining: AtomicBool,
42    idle: Notify,
43}
44
45/// drain 任务的复位守卫: 任务 future 未正常走完 (被运行时丢弃) 时清除 draining 并唤醒 close
46struct 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            // 不取 state 锁: spawn 到已关闭的运行时会在 ensure_drain 持锁期间同步丢弃 future
55            self.inner.draining.store(false, Ordering::Release);
56            self.inner.idle.notify_waiters();
57        }
58    }
59}
60
61/// 去抖聚合队列: 攒到阈值条数或时间窗口先到者触发一次批量刷新。
62/// 即时直发仅限低频单条场景; 采集 / 回灌 / 批量管道应走本队列。
63///
64/// - 刷新回调是 async 函数, 在 Tokio 任务里串行执行, 批次间保持 FIFO
65/// - [`Debounced::add`] / [`Debounced::flush`] 是同步非阻塞调用, 可在任意线程调用,
66///   回调内也可安全调用 (如失败回灌重试)
67/// - 回调 panic 被捕获并丢弃该批, 业务错误与重试在回调内自行处理
68/// - `Clone` 共享同一队列; 退出前调用 [`Debounced::close`] 刷完剩余条目, 未 close 直接丢弃会丢掉缓冲
69///
70/// ```
71/// use std::time::Duration;
72/// use rust_web_utils::cronutil::Debounced;
73///
74/// # #[tokio::main(flavor = "current_thread")]
75/// # async fn main() {
76/// let q = Debounced::new(100, Duration::from_secs(2), |batch: Vec<String>| async move {
77///     // bulk_index(batch).await
78///     let _ = batch;
79/// });
80/// q.add(["doc-1".to_owned()]);
81/// q.close().await;
82/// # }
83/// ```
84pub 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    /// 创建去抖队列: `threshold` 为触发刷新的条数阈值 (零时按 1), `window` 为最长等待时间窗
107    /// (零时按 1s), `flush` 为批量刷新回调 (串行调用, 不会并发)。
108    ///
109    /// 必须在 Tokio 运行时上下文内调用 (取当前运行时句柄), 否则 panic;
110    /// 运行时外创建用 [`Debounced::with_handle`]
111    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    /// 同 [`Debounced::new`], 显式指定定时器与回调运行的 Tokio 运行时
120    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    /// 追加条目; 达到阈值立即成批, 否则等待时间窗。close 之后调用同样入队并立即刷新, 不丢数据
152    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            // 首条入队时启动时间窗定时器
163            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; // 本任务即将结束, 不必 abort 自己
170                    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    /// 立即把当前缓冲成批并触发刷新 (不等阈值与时间窗); 缓冲为空时是空操作。不等待刷新完成
180    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    /// 关闭队列, 刷新剩余条目并等待全部在途批次完成; 之后的 [`Debounced::add`] 入队即刷。
187    /// 在刷新回调内直接 `.await` 时不等待 (剩余批次由当前 drain 继续处理), 不会死锁;
188    /// 回调内把 close 再 `spawn` 出去并等待它会死锁 (它在等回调自己结束)
189    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    /// 缓冲与待刷批次中的条目总数 (不含正在刷新的批次)
211    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    /// 缓冲与待刷批次是否为空
217    pub fn is_empty(&self) -> bool {
218        self.len() == 0
219    }
220}
221
222/// 把缓冲成批推入待刷队列并作废时间窗定时器
223fn 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        // 临界区只做容器操作, 回调在锁外执行, 中毒后状态仍一致
237        self.state.lock().unwrap_or_else(PoisonError::into_inner)
238    }
239
240    /// 有待刷批次且没有 drain 任务时启动一个
241    fn ensure_drain(this: &Arc<Self>, s: &mut State<T>) {
242        // 调用方持有 state 锁, draining 的检查与置位不会与 drain 收尾交错
243        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            // 回调 (含其同步部分) 放进独立任务执行: panic 只让该任务失败, drain 循环继续
271            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        // close 之后入队即刷
321        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        // 手动 flush 作废旧定时器, 新批次重新计时
340        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(); // 空缓冲是空操作
347        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)); // 失败回灌
386                    q.close().await; // 回调内 close 不死锁
387                }
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); // 运行时关闭, 之后的 drain 任务无法运行
443        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}