rust-web-utils 0.1.0

Lightweight web utilities: client IP & trusted proxies, bot/browser detection, unified JSON response, business timezone, auth cookies + CSRF, cron guards, Next.js static export hosting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
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! {
    /// 正在执行的刷新回调所属实例 id, 用于识别回调内重入调用 close
    static IN_FLUSH: usize;
}

static NEXT_ID: AtomicUsize = AtomicUsize::new(1);

struct State<T> {
    /// 未成批的缓冲
    buf: Vec<T>,
    /// 已成批待刷新的 FIFO 队列
    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>>,
    /// 同一时刻只有一个 drain 任务, 保证回调串行且 FIFO。正常路径只在持有 `state` 锁时读写;
    /// drain 任务异常结束 (运行时关闭) 时由 [`DrainGuard`] 无锁复位, 避免 close 永久等待
    draining: AtomicBool,
    idle: Notify,
}

/// drain 任务的复位守卫: 任务 future 未正常走完 (被运行时丢弃) 时清除 draining 并唤醒 close
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 {
            // 不取 state 锁: spawn 到已关闭的运行时会在 ensure_drain 持锁期间同步丢弃 future
            self.inner.draining.store(false, Ordering::Release);
            self.inner.idle.notify_waiters();
        }
    }
}

/// 去抖聚合队列: 攒到阈值条数或时间窗口先到者触发一次批量刷新。
/// 即时直发仅限低频单条场景; 采集 / 回灌 / 批量管道应走本队列。
///
/// - 刷新回调是 async 函数, 在 Tokio 任务里串行执行, 批次间保持 FIFO
/// - [`Debounced::add`] / [`Debounced::flush`] 是同步非阻塞调用, 可在任意线程调用,
///   回调内也可安全调用 (如失败回灌重试)
/// - 回调 panic 被捕获并丢弃该批, 业务错误与重试在回调内自行处理
/// - `Clone` 共享同一队列; 退出前调用 [`Debounced::close`] 刷完剩余条目, 未 close 直接丢弃会丢掉缓冲
///
/// ```
/// use std::time::Duration;
/// use rust_web_utils::cronutil::Debounced;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let q = Debounced::new(100, Duration::from_secs(2), |batch: Vec<String>| async move {
///     // bulk_index(batch).await
///     let _ = batch;
/// });
/// q.add(["doc-1".to_owned()]);
/// q.close().await;
/// # }
/// ```
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> {
    /// 创建去抖队列: `threshold` 为触发刷新的条数阈值 (零时按 1), `window` 为最长等待时间窗
    /// (零时按 1s), `flush` 为批量刷新回调 (串行调用, 不会并发)。
    ///
    /// 必须在 Tokio 运行时上下文内调用 (取当前运行时句柄), 否则 panic;
    /// 运行时外创建用 [`Debounced::with_handle`]
    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)
    }

    /// 同 [`Debounced::new`], 显式指定定时器与回调运行的 Tokio 运行时
    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(),
            }),
        }
    }

    /// 追加条目; 达到阈值立即成批, 否则等待时间窗。close 之后调用同样入队并立即刷新, 不丢数据
    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; // 本任务即将结束, 不必 abort 自己
                    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);
    }

    /// 关闭队列, 刷新剩余条目并等待全部在途批次完成; 之后的 [`Debounced::add`] 入队即刷。
    /// 在刷新回调内直接 `.await` 时不等待 (剩余批次由当前 drain 继续处理), 不会死锁;
    /// 回调内把 close 再 `spawn` 出去并等待它会死锁 (它在等回调自己结束)
    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)
    }

    /// 有待刷批次且没有 drain 任务时启动一个
    fn ensure_drain(this: &Arc<Self>, s: &mut State<T>) {
        // 调用方持有 state 锁, draining 的检查与置位不会与 drain 收尾交错
        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;
                    }
                }
            };
            // 回调 (含其同步部分) 放进独立任务执行: panic 只让该任务失败, drain 循环继续
            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());

        // close 之后入队即刷
        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]]);

        // 手动 flush 作废旧定时器, 新批次重新计时
        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; // 回调内 close 不死锁
                }
            }
        });
        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); // 运行时关闭, 之后的 drain 任务无法运行
        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]]);
    }
}