uxar 0.1.3

Opinionated Rust web framework built on Axum for Postgres-backed JSON APIs
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
use std::{fmt, future::Future, pin::Pin, sync::Arc};
use serde::{Deserialize, Serialize};
use tokio::sync::Notify;
use tokio::task::JoinHandle;
use tokio::time::{Duration, Instant};
use crate::callables::{Callable, CallError, PayloadData};

#[derive(Default, Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum DebounceMode {
    Leading,
    #[default]
    Trailing,
    Both,
}

#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct DebounceConf {
    pub mode: DebounceMode,
    pub interval: Duration,
}

/// `SleepUntil(Some(t))` resets the timer to `t`; `SleepUntil(None)` cancels it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebounceDecision {
    Run,
    Nothing,
    SleepUntil(Option<Instant>),
}

#[derive(Debug, Default)]
pub struct Debouncer {
    mode: DebounceMode,
    interval: Duration,

    running: bool,
    last_trigger: Option<Instant>,   // deadline for trailing = last_trigger + interval
    last_run_start: Option<Instant>, // used to compute cooldown expiry
    pending: bool,                   // a trailing run is queued: set when triggered-while-running, or on every leading fire
}

impl Debouncer {
    pub fn new(conf: DebounceConf) -> Self {
        Self { mode: conf.mode, interval: conf.interval, ..Default::default() }
    }

    /// Called when a new event arrives.
    pub fn trigger(&mut self) -> DebounceDecision {
        let now = Instant::now();
        match self.mode {
            DebounceMode::Leading => {
                if self.running || !self.cooldown_remaining(now).is_zero() {
                    return DebounceDecision::Nothing;
                }
                self.start_run(now);
                DebounceDecision::Run
            }
            DebounceMode::Trailing => {
                self.last_trigger = Some(now);
                if self.running {
                    self.pending = true;
                    return DebounceDecision::Nothing;
                }
                self.schedule_trailing(now)
            }
            DebounceMode::Both => {
                self.last_trigger = Some(now);
                if self.running {
                    // last_trigger is already updated, so the trailing deadline extends naturally
                    return DebounceDecision::Nothing;
                }
                if self.cooldown_remaining(now).is_zero() {
                    self.pending = true; // trailing always follows a leading fire in Both mode
                    self.start_run(now);
                    return DebounceDecision::Run;
                }
                self.schedule_trailing(now)
            }
        }
    }

    /// Called when the scheduled timer fires.
    pub fn awake(&mut self) -> DebounceDecision {
        let now = Instant::now();
        match self.mode {
            DebounceMode::Leading => DebounceDecision::Nothing,
            DebounceMode::Trailing | DebounceMode::Both => {
                if self.running {
                    return DebounceDecision::Nothing;
                }
                self.schedule_trailing(now)
            }
        }
    }

    /// Called when the running action finishes.
    pub fn done(&mut self) -> DebounceDecision {
        self.running = false;
        let now = Instant::now();
        match self.mode {
            DebounceMode::Leading => DebounceDecision::Nothing,
            DebounceMode::Trailing | DebounceMode::Both => {
                if self.pending {
                    self.pending = false;
                    self.schedule_trailing(now)
                } else {
                    DebounceDecision::Nothing
                }
            }
        }
    }

    fn schedule_trailing(&mut self, now: Instant) -> DebounceDecision {
        let Some(deadline) = self.last_trigger.map(|t| t + self.interval) else {
            return DebounceDecision::SleepUntil(None);
        };
        if now >= deadline {
            self.start_run(now);
            DebounceDecision::Run
        } else {
            DebounceDecision::SleepUntil(Some(deadline))
        }
    }

    fn cooldown_remaining(&self, now: Instant) -> Duration {
        self.last_run_start
            .map(|t| (t + self.interval).saturating_duration_since(now))
            .unwrap_or(Duration::ZERO)
    }

    fn start_run(&mut self, now: Instant) {
        self.running = true;
        self.last_run_start = Some(now);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::time;

    const INTERVAL: Duration = Duration::from_millis(100);

    fn leading() -> Debouncer { Debouncer::new(DebounceConf { mode: DebounceMode::Leading, interval: INTERVAL }) }
    fn trailing() -> Debouncer { Debouncer::new(DebounceConf { mode: DebounceMode::Trailing, interval: INTERVAL }) }
    fn both() -> Debouncer { Debouncer::new(DebounceConf { mode: DebounceMode::Both, interval: INTERVAL }) }

    fn deadline_of(d: DebounceDecision) -> Instant {
        match d {
            DebounceDecision::SleepUntil(Some(t)) => t,
            other => panic!("expected SleepUntil(Some(_)), got {other:?}"),
        }
    }

    #[tokio::test]
    async fn leading_idle_fires() {
        time::pause();
        assert_eq!(leading().trigger(), DebounceDecision::Run);
    }

    #[tokio::test]
    async fn leading_trigger_while_running_nothing() {
        time::pause();
        let mut d = leading();
        assert_eq!(d.trigger(), DebounceDecision::Run);
        assert_eq!(d.trigger(), DebounceDecision::Nothing);
        assert_eq!(d.trigger(), DebounceDecision::Nothing);
    }

    #[tokio::test]
    async fn leading_trigger_during_cooldown_nothing() {
        time::pause();
        let mut d = leading();
        d.trigger();
        d.done();
        // still in cooldown
        time::advance(Duration::from_millis(50)).await;
        assert_eq!(d.trigger(), DebounceDecision::Nothing);
    }

    #[tokio::test]
    async fn leading_trigger_after_cooldown_fires() {
        time::pause();
        let mut d = leading();
        d.trigger();
        d.done();
        time::advance(INTERVAL).await;
        assert_eq!(d.trigger(), DebounceDecision::Run);
    }

    #[tokio::test]
    async fn leading_awake_always_nothing() {
        time::pause();
        let mut d = leading();
        assert_eq!(d.awake(), DebounceDecision::Nothing);
        d.trigger();
        assert_eq!(d.awake(), DebounceDecision::Nothing);
    }

    #[tokio::test]
    async fn leading_done_nothing() {
        time::pause();
        let mut d = leading();
        d.trigger();
        assert_eq!(d.done(), DebounceDecision::Nothing);
    }

    #[tokio::test]
    async fn leading_burst_only_first_fires() {
        time::pause();
        let mut d = leading();
        assert_eq!(d.trigger(), DebounceDecision::Run);
        for _ in 0..9 { assert_eq!(d.trigger(), DebounceDecision::Nothing); }
    }

    #[tokio::test]
    async fn trailing_idle_schedules_sleep() {
        time::pause();
        let t0 = Instant::now();
        let mut d = trailing();
        let dec = d.trigger();
        assert_eq!(deadline_of(dec), t0 + INTERVAL);
    }

    #[tokio::test]
    async fn trailing_burst_extends_deadline() {
        time::pause();
        let mut d = trailing();
        d.trigger();
        time::advance(Duration::from_millis(50)).await;
        let t1 = Instant::now();
        let dec = d.trigger();
        // deadline should reset to the new trigger time
        assert_eq!(deadline_of(dec), t1 + INTERVAL);
    }

    #[tokio::test]
    async fn trailing_awake_at_deadline_fires() {
        time::pause();
        let mut d = trailing();
        d.trigger();
        time::advance(INTERVAL).await;
        assert_eq!(d.awake(), DebounceDecision::Run);
    }

    #[tokio::test]
    async fn trailing_awake_before_deadline_resleeps() {
        time::pause();
        let t0 = Instant::now();
        let mut d = trailing();
        d.trigger();
        time::advance(Duration::from_millis(50)).await;
        let dec = d.awake(); // woke up 50ms early
        assert_eq!(deadline_of(dec), t0 + INTERVAL);
    }

    #[tokio::test]
    async fn trailing_done_no_pending_nothing() {
        time::pause();
        let mut d = trailing();
        d.trigger();
        time::advance(INTERVAL).await;
        d.awake(); // → Run
        assert_eq!(d.done(), DebounceDecision::Nothing);
    }

    #[tokio::test]
    async fn trailing_trigger_while_running_pending() {
        time::pause();
        let mut d = trailing();
        d.trigger();
        time::advance(INTERVAL).await;
        d.awake(); // → Run
        // trigger during run
        let dec = d.trigger();
        assert_eq!(dec, DebounceDecision::Nothing);
    }

    #[tokio::test]
    async fn trailing_done_with_pending_schedules_trailing() {
        time::pause();
        let mut d = trailing();
        d.trigger();
        time::advance(INTERVAL).await;
        d.awake(); // → Run
        let t1 = Instant::now();
        d.trigger(); // sets pending
        let dec = d.done();
        assert_eq!(deadline_of(dec), t1 + INTERVAL);
    }

    #[tokio::test]
    async fn trailing_burst_during_run_uses_latest_trigger() {
        time::pause();
        let mut d = trailing();
        d.trigger();
        time::advance(INTERVAL).await;
        d.awake(); // → Run
        time::advance(Duration::from_millis(10)).await;
        d.trigger(); // t = 110ms
        time::advance(Duration::from_millis(20)).await;
        let t_last = Instant::now(); // t = 130ms
        d.trigger(); // last trigger
        let dec = d.done();
        assert_eq!(deadline_of(dec), t_last + INTERVAL);
    }

    #[tokio::test]
    async fn trailing_awake_stale_while_running_nothing() {
        time::pause();
        let mut d = trailing();
        d.trigger();
        time::advance(INTERVAL).await;
        d.awake(); // → Run
        // stale wake while still running
        assert_eq!(d.awake(), DebounceDecision::Nothing);
    }

    #[tokio::test]
    async fn both_idle_leading_fires() {
        time::pause();
        assert_eq!(both().trigger(), DebounceDecision::Run);
    }

    #[tokio::test]
    async fn both_done_always_schedules_trailing() {
        time::pause();
        let t0 = Instant::now();
        let mut d = both();
        d.trigger(); // → Run + pending=true
        let dec = d.done();
        assert_eq!(deadline_of(dec), t0 + INTERVAL);
    }

    #[tokio::test]
    async fn both_trailing_awake_fires() {
        time::pause();
        let mut d = both();
        let t0 = Instant::now();
        d.trigger();
        d.done(); // → SleepUntil(t0 + 100ms)
        time::advance(INTERVAL).await;
        assert_eq!(d.awake(), DebounceDecision::Run);
    }

    #[tokio::test]
    async fn both_trailing_done_nothing() {
        time::pause();
        let mut d = both();
        d.trigger();
        d.done(); // leading done → trailing sleep
        time::advance(INTERVAL).await;
        d.awake(); // trailing run
        assert_eq!(d.done(), DebounceDecision::Nothing);
    }

    #[tokio::test]
    async fn both_trigger_while_leading_running_nothing() {
        time::pause();
        let mut d = both();
        d.trigger(); // → Run
        assert_eq!(d.trigger(), DebounceDecision::Nothing);
        assert_eq!(d.trigger(), DebounceDecision::Nothing);
    }

    #[tokio::test]
    async fn both_burst_during_leading_extends_trailing_deadline() {
        // triggers during the leading run should push the trailing deadline out
        time::pause();
        let mut d = both();
        d.trigger(); // t=0 → Run
        time::advance(Duration::from_millis(40)).await;
        d.trigger(); // t=40 → Nothing, last_trigger=40ms
        time::advance(Duration::from_millis(30)).await;
        let t_last = Instant::now(); // t=70ms
        d.trigger(); // last_trigger=70ms
        let dec = d.done(); // trailing → deadline = 70ms + 100ms = 170ms
        assert_eq!(deadline_of(dec), t_last + INTERVAL);
    }

    #[tokio::test]
    async fn both_trigger_in_cooldown_trailing() {
        // in cooldown, a new trigger should schedule a trailing run, not a leading one
        time::pause();
        let mut d = both();
        d.trigger(); // leading
        d.done();    // schedules trailing sleep
        time::advance(INTERVAL).await;
        d.awake();   // trailing run
        d.done();    // trailing done → Nothing
        time::advance(Duration::from_millis(20)).await;
        let t1 = Instant::now();
        let dec = d.trigger(); // cooldown still active → SleepUntil
        assert_eq!(deadline_of(dec), t1 + INTERVAL);
    }

    #[tokio::test]
    async fn both_awake_before_deadline_resleeps() {
        time::pause();
        let t0 = Instant::now();
        let mut d = both();
        d.trigger();
        d.done(); // SleepUntil(t0 + 100ms)
        time::advance(Duration::from_millis(40)).await;
        let dec = d.awake(); // stale wake
        assert_eq!(deadline_of(dec), t0 + INTERVAL);
    }

    #[tokio::test]
    async fn both_awake_stale_while_running_nothing() {
        time::pause();
        let mut d = both();
        d.trigger();
        d.done(); // trailing sleep
        time::advance(INTERVAL).await;
        d.awake(); // trailing → Run
        assert_eq!(d.awake(), DebounceDecision::Nothing); // stale wake while trailing run is still active
    }

    #[tokio::test]
    async fn both_second_burst_after_full_cycle() {
        time::pause();
        let mut d = both();
        d.trigger();
        d.done();
        time::advance(INTERVAL).await;
        d.awake(); // trailing run
        d.done();
        // cooldown is anchored to the trailing run_start, advance past it
        time::advance(INTERVAL).await;
        assert_eq!(d.trigger(), DebounceDecision::Run);
    }
}

/// Wraps a [`Callable`] with debounce logic.
/// Calling `trigger` is non-blocking — the actual invocation happens in a background task.
pub struct DebounceCall<C, E = CallError>
where
    C: Send + 'static,
    E: Send + 'static,
{
    latest: Arc<parking_lot::Mutex<Option<C>>>, // the background task always uses the most recent context
    notify: Arc<Notify>,                        // wakes the background task when a new trigger arrives
    _task: Arc<JoinHandle<()>>,
    _e: std::marker::PhantomData<E>,
}

impl<C, E> Clone for DebounceCall<C, E>
where
    C: Send + 'static,
    E: Send + 'static,
{
    fn clone(&self) -> Self {
        Self {
            latest: Arc::clone(&self.latest),
            notify: Arc::clone(&self.notify),
            _task: Arc::clone(&self._task),
            _e: std::marker::PhantomData,
        }
    }
}

impl<C, E> DebounceCall<C, E>
where
    C: Send + Clone + 'static,
    E: fmt::Debug + From<CallError> + Send + 'static,
{
    pub fn new(conf: DebounceConf, callable: Callable<C, E>) -> Self {
        let latest = Arc::new(parking_lot::Mutex::new(None::<C>));
        let notify = Arc::new(Notify::new());
        let task = tokio::spawn(debounce_task(
            conf, callable, Arc::clone(&latest), Arc::clone(&notify),
        ));
        Self { latest, notify, _task: Arc::new(task), _e: std::marker::PhantomData }
    }

    /// Stores the latest context and wakes the background task. Never blocks.
    pub fn trigger(&self, ctx: C) {
        *self.latest.lock() = Some(ctx);
        self.notify.notify_one();
    }
}

async fn debounce_task<C, E>(
    conf: DebounceConf,
    callable: Callable<C, E>,
    latest: Arc<parking_lot::Mutex<Option<C>>>,
    notify: Arc<Notify>,
)
where
    C: Send + Clone + 'static,
    E: fmt::Debug + From<CallError> + Send + 'static,
{
    let mut state = Debouncer::new(conf);
    let mut timer_active = false;
    let sleep = tokio::time::sleep(Duration::ZERO);
    tokio::pin!(sleep);

    // call_fut holds the in-flight handler; pending() when idle so the select
    // branch is always valid — call_active gates whether it's actually polled.
    let mut call_active = false;
    let mut call_fut: Pin<Box<dyn Future<Output = Result<PayloadData, E>> + Send>> =
        Box::pin(std::future::pending());

    loop {
        let decision = tokio::select! {
            () = notify.notified() => state.trigger(),
            () = &mut sleep, if timer_active => {
                timer_active = false;
                state.awake()
            }
            result = &mut call_fut, if call_active => {
                call_active = false;
                if let Err(e) = result {
                    tracing::error!("debounce handler error: {:?}", e);
                }
                state.done()
            }
        };

        match decision {
            DebounceDecision::Run => {
                timer_active = false;
                let ctx = latest.lock().clone();
                if let Some(ctx) = ctx {
                    call_fut = callable.call(ctx);
                    call_active = true;
                } else {
                    // ctx missing despite Run decision — reset state to avoid getting stuck
                    tracing::warn!("debounce Run with no queued context");
                    let _ = state.done();
                }
            }
            DebounceDecision::SleepUntil(Some(t)) => { sleep.as_mut().reset(t); timer_active = true; }
            DebounceDecision::SleepUntil(None)     => { timer_active = false; }
            DebounceDecision::Nothing => {}
        }
    }
}

#[cfg(test)]
mod call_tests {
    use super::*;
    use std::sync::{
        Arc,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    };
    use tokio::time;

    const INTERVAL: Duration = Duration::from_millis(100);

    // callable that just counts how many times it was invoked
    fn counter_call(counter: Arc<AtomicUsize>) -> Callable<(), CallError> {
        Callable::new(move || {
            let c = Arc::clone(&counter);
            async move { c.fetch_add(1, Ordering::SeqCst); }
        })
    }

    fn make(mode: DebounceMode, callable: Callable<(), CallError>) -> DebounceCall<(), CallError> {
        DebounceCall::new(DebounceConf { mode, interval: INTERVAL }, callable)
    }

    // sleep(ZERO) flushes the timer wheel so tasks whose sleeps expired via advance() get
    // scheduled on the executor; the yield_nows then let them run to completion.
    async fn settle() {
        tokio::time::sleep(Duration::ZERO).await;
        for _ in 0..5 {
            tokio::task::yield_now().await;
        }
    }

    #[tokio::test]
    async fn leading_fires_immediately() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Leading, counter_call(Arc::clone(&c)));
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn leading_burst_fires_once() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Leading, counter_call(Arc::clone(&c)));
        dc.trigger(());
        dc.trigger(());
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn leading_cooldown_blocks() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Leading, counter_call(Arc::clone(&c)));
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1);
        time::advance(Duration::from_millis(50)).await;
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1, "cooldown must block re-fire");
    }

    #[tokio::test]
    async fn leading_fires_after_cooldown() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Leading, counter_call(Arc::clone(&c)));
        dc.trigger(());
        settle().await;
        time::advance(INTERVAL).await;
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn trailing_defers_until_quiet() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Trailing, counter_call(Arc::clone(&c)));
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 0, "must not fire before interval");
        time::advance(INTERVAL).await;
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn trailing_burst_fires_once_after_last() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Trailing, counter_call(Arc::clone(&c)));
        dc.trigger(());
        time::advance(Duration::from_millis(40)).await;
        dc.trigger(());
        time::advance(Duration::from_millis(40)).await;
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 0, "must not fire mid-burst");
        time::advance(INTERVAL).await;
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn trailing_sequential_triggers_each_fire() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Trailing, counter_call(Arc::clone(&c)));
        for _ in 0..3 {
            dc.trigger(());
            settle().await; // let the task record the trigger before advancing time
            time::advance(INTERVAL).await;
            settle().await;
        }
        assert_eq!(c.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn trailing_no_fire_without_trigger() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let _dc = make(DebounceMode::Trailing, counter_call(Arc::clone(&c)));
        time::advance(INTERVAL * 10).await;
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn both_leading_fires_immediately() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Both, counter_call(Arc::clone(&c)));
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1, "leading must fire immediately");
    }

    #[tokio::test]
    async fn both_trailing_fires_after_interval() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Both, counter_call(Arc::clone(&c)));
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1);
        time::advance(INTERVAL).await;
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 2, "trailing must follow leading");
    }

    #[tokio::test]
    async fn both_burst_fires_leading_and_one_trailing() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Both, counter_call(Arc::clone(&c)));
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1); // leading
        time::advance(Duration::from_millis(40)).await;
        dc.trigger(());
        time::advance(Duration::from_millis(40)).await;
        dc.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1, "no extra fires during burst");
        time::advance(INTERVAL).await;
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 2, "trailing fires once after quiet");
    }

    #[tokio::test]
    async fn both_no_fire_without_trigger() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let _dc = make(DebounceMode::Both, counter_call(Arc::clone(&c)));
        time::advance(INTERVAL * 10).await;
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn clone_shares_background_task() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc1 = make(DebounceMode::Leading, counter_call(Arc::clone(&c)));
        let dc2 = dc1.clone();
        dc1.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1);
        // still within the cooldown window
        dc2.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1, "clone must share cooldown");
        time::advance(INTERVAL).await;
        dc2.trigger(());
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 2, "clone fires after shared cooldown expires");
    }

    #[tokio::test]
    async fn trailing_runs_are_sequential() {
        time::pause();
        let running = Arc::new(AtomicBool::new(false));
        let overlap_seen = Arc::new(AtomicBool::new(false));
        let counter = Arc::new(AtomicUsize::new(0));
        let r = Arc::clone(&running);
        let o = Arc::clone(&overlap_seen);
        let cnt = Arc::clone(&counter);
        let callable: Callable<(), CallError> = Callable::new(move || {
            let r = Arc::clone(&r);
            let o = Arc::clone(&o);
            let cnt = Arc::clone(&cnt);
            async move {
                if r.swap(true, Ordering::SeqCst) {
                    o.store(true, Ordering::SeqCst);
                }
                cnt.fetch_add(1, Ordering::SeqCst);
                r.store(false, Ordering::SeqCst);
            }
        });
        let dc = make(DebounceMode::Trailing, callable);
        for _ in 0..3 {
            dc.trigger(());
            settle().await; // let the task record the trigger before advancing time
            time::advance(INTERVAL).await;
            settle().await;
        }
        assert_eq!(counter.load(Ordering::SeqCst), 3, "handler should run once per quiet period");
        assert!(!overlap_seen.load(Ordering::SeqCst), "runs must never overlap");
    }

    #[tokio::test]
    async fn drop_does_not_panic() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc = make(DebounceMode::Trailing, counter_call(Arc::clone(&c)));
        dc.trigger(());
        drop(dc);
        settle().await;
    }

    #[tokio::test]
    async fn drop_last_clone_releases_task() {
        time::pause();
        let c = Arc::new(AtomicUsize::new(0));
        let dc1 = make(DebounceMode::Trailing, counter_call(Arc::clone(&c)));
        let dc2 = dc1.clone();
        drop(dc1);
        // dc2 still holds the task alive
        dc2.trigger(());
        settle().await; // let the task record the trigger before advancing time
        time::advance(INTERVAL).await;
        settle().await;
        assert_eq!(c.load(Ordering::SeqCst), 1);
        drop(dc2);
        settle().await;
    }
}