bouncing 0.1.0

A flexible async debouncer for Rust with cancellation support, max wait limits, and event hooks
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::time::Instant;
use tokio::{sync::oneshot, task::JoinHandle};
use tokio_util::sync::CancellationToken;
use tracing::{debug, trace, warn};

// core debouncer
#[derive(Clone)]
pub struct Debouncer {
    name: Arc<str>,
    debounce_duration: Duration,
    max_debounce: Option<Duration>,
    cancel_task_timeout: Duration,
    current_task: Arc<Mutex<Option<TaskToken>>>,
    timer_handle: Arc<Mutex<Option<TimerHandle>>>,
    event_handler: Option<EventHandler>,
    cancel_token: CancellationToken,
}

pub type StoredTask = Arc<
    dyn Fn(CancellationToken) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
>;

// coupling of a Debouncer with a function
#[derive(Clone)]
pub struct StoredTaskDebouncer {
    debouncer: Debouncer,
    task_fn: StoredTask,
}

// trait for the TaskDebouncer
pub trait DebouncedTask: Send + Sync + 'static {
    fn execute(&self, token: CancellationToken) -> impl Future<Output = ()> + Send + Sync;
}

// coupling of a Debouncer with a trait
#[derive(Clone)]
pub struct TaskDebouncer<T: DebouncedTask> {
    debouncer: Debouncer,
    task: Arc<T>,
}

// stores info, the handle, the token, and exit receiver for the current debounce timer
#[derive(Debug)]
pub struct TimerHandle {
    debounced_at: Instant,
    first_debounce_at: Option<Instant>,
    timer_token: CancellationToken,
    join_handle: JoinHandle<()>,
    exit_rx: oneshot::Receiver<TaskExit>,
}

// stores info and the token for the current task
#[derive(Debug)]
pub struct TaskToken {
    pub started_at: Instant,
    pub task_token: CancellationToken,
}

#[derive(Clone, Debug, Copy)]
pub enum TaskExit {
    Normal,
    Cancelled,
    Aborted,
    NotStarted,
}

#[derive(Clone, Debug)]
pub enum DebounceEvent {
    Debounced {
        instant: Instant,
        first_debounce_at: Option<Instant>,
        debounce_ends_at: Instant,
    },
    Started {
        instant: Instant,
    },
    Ended {
        instant: Instant,
        exit_status: TaskExit,
    },
}

pub type EventHandler = Arc<dyn Fn(DebounceEvent) + Send + Sync + 'static>;

impl Debouncer {
    pub fn new(
        debounce_duration: Duration,
        cancel_token: CancellationToken,
        task_name: impl AsRef<str>,
    ) -> Self {
        Self {
            debounce_duration,
            max_debounce: None,
            cancel_task_timeout: Duration::from_secs(2),
            timer_handle: Arc::new(Mutex::new(None)),
            cancel_token,
            name: Arc::from(task_name.as_ref()),
            current_task: Arc::new(Mutex::new(None)),
            event_handler: None,
        }
    }

    pub fn with_task_timeout(mut self, task_timeout: Duration) -> Self {
        self.cancel_task_timeout = task_timeout;
        self
    }

    pub fn with_max_wait(mut self, max_wait: Duration) -> Self {
        self.max_debounce = Some(max_wait);
        self
    }

    pub fn with_event_handler<E: Fn(DebounceEvent) + Send + Sync + 'static>(
        mut self,
        event_handler: E,
    ) -> Self {
        self.event_handler = Some(Arc::new(event_handler));
        self
    }

    fn fire_event(&self, event: DebounceEvent) {
        if let Some(event_handler) = &self.event_handler {
            event_handler(event)
        }
    }

    async fn should_wait_for_debounce(&self, first_debounce_at: Option<Instant>) -> bool {
        if let Some(max_wait) = self.max_debounce {
            if let Some(first_debounce) = first_debounce_at {
                let wait_period = Instant::now().duration_since(first_debounce);
                if wait_period >= max_wait {
                    trace!(
                        "task {:?} exceeded the max debounce waiting period, {wait_period:?} >= {max_wait:?}",
                        self.name
                    );
                    return false;
                }
            }
        }
        true
    }

    async fn spawn_task<Task, Fut>(&self, task: Task) -> TaskExit
    where
        Task: FnOnce(CancellationToken) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let task_token = CancellationToken::new();
        let now = {
            let mut current_task_token = self.current_task.lock().await;
            if let Some(current_token) = current_task_token.take() {
                current_token.task_token.cancel();
            }
            let now = Instant::now();
            *current_task_token = Some(TaskToken {
                started_at: now,
                task_token: task_token.clone(),
            });
            now
        };

        let (tx, rx) = oneshot::channel();
        let (tx2, rx2) = oneshot::channel();
        let task_handle = tokio::spawn({
            let task_token = task_token.clone();
            async move {
                task(task_token).await;
                let _ = tx.send(());
                let _ = tx2.send(());
            }
        });

        self.fire_event(DebounceEvent::Started { instant: now });

        let exit_status = tokio::select! {
            _ = rx => TaskExit::Normal,
            _ = self.wait_for_cancellation(&task_token) => {
                // Give task time to exit gracefully after cancelling
                tokio::select! {
                    _ = tokio::time::sleep(self.cancel_task_timeout) => {
                        // Task not exiting fast enough, abort it
                        task_handle.abort();
                        TaskExit::Aborted
                    }
                    _ = rx2 => {
                        // Task exited (cancelled) normally
                        TaskExit::Cancelled
                    }
                }
            }
        };

        self.fire_event(DebounceEvent::Ended {
            exit_status,
            instant: Instant::now(),
        });

        exit_status
    }

    async fn wait_for_cancellation(&self, task_token: &CancellationToken) {
        tokio::select! {
            _ = self.cancel_token.cancelled() => {
                trace!("task {:?} debouncer token cancelled", self.name);
                task_token.cancel();
            }
            _ = task_token.cancelled() => {
                trace!("task {:?} task token cancelled", self.name);
            }
        }
    }

    async fn timer<F, Fut>(
        &self,
        now: Instant,
        first_debounce_at: Option<Instant>,
        exit_tx: oneshot::Sender<TaskExit>,
        timer_token: CancellationToken,
        f: F,
    ) where
        F: FnOnce(CancellationToken) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.fire_event(DebounceEvent::Debounced {
            instant: now,
            debounce_ends_at: now.checked_add(self.debounce_duration).unwrap_or(now),
            first_debounce_at,
        });

        let exit_status = tokio::select! {
            _ = timer_token.cancelled() => {
                trace!("task {:?} timer cancelled by next trigger", self.name);
                TaskExit::NotStarted
            }
            _ = self.cancel_token.cancelled() => {
                trace!("task {:?} cancelled while waiting to execute next task", self.name);
                TaskExit::NotStarted
            }
            _ = self.wait_for_debounce(first_debounce_at) => {
                self.spawn_task(f).await
            }
        };
        let _ = exit_tx.send(exit_status);
    }

    async fn wait_for_debounce(&self, first_debounce_at: Option<Instant>) {
        if self.should_wait_for_debounce(first_debounce_at).await {
            tokio::time::sleep(self.debounce_duration).await;
        }
    }

    pub async fn run_now<Task, Fut>(&self, task: Task)
    where
        Task: FnOnce(CancellationToken) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let mut timer_handle = self.timer_handle.lock().await;

        if let Some(timer_handle) = timer_handle.take() {
            if !timer_handle
                .cancel_with_timeout(self.cancel_task_timeout)
                .await
            {
                warn!("task {:?} aborted timer handle", self.name);
            }
        }

        drop(timer_handle);
        self.spawn_task(task).await;
    }

    pub async fn debounce<Task, Fut>(&self, task: Task)
    where
        Task: FnOnce(CancellationToken) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let timer_token = CancellationToken::new();
        let (exit_tx, exit_rx) = oneshot::channel();

        let mut timer_handle = self.timer_handle.lock().await;

        let first_debounce_at = if let Some(existing_timer) = timer_handle.take() {
            let first_debounce = Some(
                existing_timer
                    .first_debounce_at
                    .unwrap_or(existing_timer.debounced_at),
            );

            if !existing_timer
                .cancel_with_timeout(self.cancel_task_timeout)
                .await
            {
                warn!("task {:?} aborted timer handle", self.name);
            }

            first_debounce
        } else {
            None
        };

        let now = Instant::now();
        let debouncer = self.clone();

        *timer_handle = Some(TimerHandle {
            exit_rx,
            timer_token: timer_token.clone(),
            debounced_at: now,
            first_debounce_at,
            join_handle: tokio::spawn(async move {
                debouncer
                    .timer(now, first_debounce_at, exit_tx, timer_token, task)
                    .await;
            }),
        });
    }

    pub async fn stop(&self) {
        debug!("task {:?} stopping...", self.name);

        if let Some(current_token) = self.current_task.lock().await.take() {
            trace!("task {:?} running, cancelling task...", self.name);
            current_token.task_token.cancel();
        }

        if let Some(timer_handle) = self.timer_handle.lock().await.take() {
            trace!("task {:?} waiting on timer....", self.name);

            if !timer_handle
                .cancel_with_timeout(self.cancel_task_timeout)
                .await
            {
                warn!("task {:?} aborted timer handle", self.name);
            }
        }

        debug!("task {:?} stopped", self.name);
    }
}

impl TimerHandle {
    pub async fn cancel_with_timeout(self, timeout: Duration) -> bool {
        self.timer_token.cancel();

        tokio::select! {
            _ = tokio::time::sleep(timeout) => {
                self.join_handle.abort();
                false
            }
            _ = self.exit_rx => {
                true
            }
        }
    }
}

impl StoredTaskDebouncer {
    pub fn new<F, Fut>(
        debounce_timeout: Duration,
        debouncer_token: CancellationToken,
        task_type: impl AsRef<str>,
        task_fn: F,
    ) -> Self
    where
        F: Fn(CancellationToken) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        StoredTaskDebouncer {
            debouncer: Debouncer::new(debounce_timeout, debouncer_token, task_type),
            task_fn: Arc::new(move |token| Box::pin(task_fn(token))),
        }
    }

    pub fn with_task_timeout(mut self, task_timeout: Duration) -> Self {
        self.debouncer = self.debouncer.with_task_timeout(task_timeout);
        self
    }

    pub fn with_max_wait(mut self, max_wait: Duration) -> Self {
        self.debouncer = self.debouncer.with_max_wait(max_wait);
        self
    }

    pub fn with_event_handler<E: Fn(DebounceEvent) + Send + Sync + 'static>(
        mut self,
        event_handler: E,
    ) -> Self {
        self.debouncer = self.debouncer.with_event_handler(event_handler);
        self
    }

    pub fn set_task<F, Fut>(&mut self, task_fn: F)
    where
        F: Fn(CancellationToken) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.task_fn = Arc::new(move |token| Box::pin(task_fn(token)));
    }

    pub async fn debounce(&self) {
        let task_fn = self.task_fn.clone();
        self.debouncer
            .debounce(move |token| async move { task_fn(token).await })
            .await
    }

    pub async fn stop(&self) {
        self.debouncer.stop().await
    }
}

impl<T: DebouncedTask> TaskDebouncer<T> {
    pub fn new(
        debounce_timeout: Duration,
        debouncer_token: CancellationToken,
        task_type: impl AsRef<str>,
        task: T,
    ) -> Self {
        TaskDebouncer {
            debouncer: Debouncer::new(debounce_timeout, debouncer_token, task_type),
            task: Arc::new(task),
        }
    }

    pub fn with_task_timeout(mut self, task_timeout: Duration) -> Self {
        self.debouncer = self.debouncer.with_task_timeout(task_timeout);
        self
    }

    pub fn with_max_wait(mut self, max_wait: Duration) -> Self {
        self.debouncer = self.debouncer.with_max_wait(max_wait);
        self
    }

    pub fn with_event_handler<E: Fn(DebounceEvent) + Send + Sync + 'static>(
        mut self,
        event_handler: E,
    ) -> Self {
        self.debouncer = self.debouncer.with_event_handler(event_handler);
        self
    }

    pub fn set_task(&mut self, task: T) {
        self.task = Arc::new(task);
    }

    pub async fn debounce(&self) {
        let task = self.task.clone();
        self.debouncer
            .debounce(move |token| async move { task.execute(token).await })
            .await
    }

    pub async fn stop(&self) {
        self.debouncer.stop().await
    }
}

#[cfg(test)]
mod test_task_debouncer {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};
    use tokio::time::sleep;

    #[tokio::test]
    async fn test_basic_debounce() {
        let cancel_token = CancellationToken::new();
        let debouncer = Debouncer::new(Duration::from_millis(100), cancel_token, "test_task");
        let counter = Arc::new(AtomicU32::new(0));
        let cancelled = Arc::new(AtomicU32::new(0));

        // Rapid triggers
        for _ in 0..5 {
            let counter = counter.clone();
            let cancelled = cancelled.clone();
            debouncer
                .debounce(move |token| async move {
                    tokio::select! {
                        _ = token.cancelled() => {
                            cancelled.fetch_add(1, Ordering::SeqCst);
                        }
                        _ = async {
                            counter.fetch_add(1, Ordering::SeqCst);
                        } => {}
                    }
                })
                .await;
            sleep(Duration::from_millis(10)).await;
        }

        tokio::select! {
            _ = sleep(Duration::from_millis(200)) => {
                assert_eq!(counter.load(Ordering::Acquire), 1);
                assert_eq!(cancelled.load(Ordering::Acquire), 0);
            }
            _ = debouncer.cancel_token.cancelled() => {
                panic!("Test cancelled unexpectedly");
            }
        }
    }

    #[tokio::test]
    async fn test_cancel_task() {
        let cancel_token = CancellationToken::new();
        let task_ms: u64 = 1;
        let debouncer = Debouncer::new(
            Duration::from_millis(task_ms),
            cancel_token.clone(),
            "test_task",
        );
        let started = Arc::new(AtomicU32::new(0));
        let cancelled = Arc::new(AtomicU32::new(0));
        let exited = Arc::new(AtomicU32::new(0));
        let finished = Arc::new(AtomicU32::new(0));

        // Start a long running task
        let (started1_tx, started1_rx) = oneshot::channel();
        let started_clone = started.clone();
        let cancelled_clone = cancelled.clone();
        let excited_clone = exited.clone();
        let finished_clone = finished.clone();
        debouncer
            .debounce(move |token| async move {
                started_clone.fetch_add(1, Ordering::SeqCst);
                started1_tx.send(()).unwrap();
                tokio::select! {
                    _ = token.cancelled() => {
                        // Should exit here when cancelled
                        cancelled_clone.fetch_add(1, Ordering::SeqCst);
                    }
                    _ = sleep(Duration::from_secs(10)) => {
                        finished_clone.fetch_add(1, Ordering::SeqCst);
                    }
                }
                excited_clone.fetch_add(1, Ordering::SeqCst);
            })
            .await;

        // Wait for task to start
        started1_rx.await.unwrap();

        assert_eq!(
            started.load(Ordering::Acquire),
            1,
            "Task should have started"
        );

        // Cancel during execution
        cancel_token.cancel();

        debouncer.stop().await;

        // Verify task was cancelled before finishing
        assert_eq!(
            finished.load(Ordering::Acquire),
            0,
            "Task should not have finished"
        );

        assert_eq!(
            cancelled.load(Ordering::Acquire),
            1,
            "Task should have cancelled"
        );

        assert_eq!(exited.load(Ordering::Acquire), 1, "Task should have exited");
    }

    #[tokio::test]
    async fn test_rapid_debounce_tasks() {
        let cancel_token = CancellationToken::new();
        let debounce_ms: u64 = 15;
        let debouncer = Debouncer::new(
            Duration::from_millis(debounce_ms),
            cancel_token.clone(),
            "test_task",
        );
        let started = Arc::new(AtomicU32::new(0));
        let cancelled = Arc::new(AtomicU32::new(0));
        let exited = Arc::new(AtomicU32::new(0));
        let finished = Arc::new(AtomicU32::new(0));

        let trigger_task = || {
            let started_clone = started.clone();
            let cancelled_clone = cancelled.clone();
            let excited_clone = exited.clone();
            let finished_clone = finished.clone();
            debouncer.debounce(move |token| async move {
                started_clone.fetch_add(1, Ordering::SeqCst);
                tokio::select! {
                    _ = token.cancelled() => {
                        // Should exit here when cancelled
                        cancelled_clone.fetch_add(1, Ordering::SeqCst);
                    }
                    _ = sleep(Duration::from_secs(10)) => {
                        finished_clone.fetch_add(1, Ordering::SeqCst);
                    }
                }
                excited_clone.fetch_add(1, Ordering::SeqCst);
            })
        };

        // Start a long running task
        for _ in 0..5 {
            trigger_task().await;
        }

        tokio::time::sleep(Duration::from_millis(debounce_ms * 2)).await;

        assert_eq!(
            started.load(Ordering::Acquire),
            1,
            "Only 1 Task should have started"
        );

        // Cancel during execution
        cancel_token.cancel();

        debouncer.stop().await;

        // Verify task was cancelled before finishing
        assert_eq!(
            finished.load(Ordering::Acquire),
            0,
            "No Task should have finished"
        );

        assert_eq!(
            cancelled.load(Ordering::Acquire),
            1,
            "Only 1 task should have cancelled"
        );

        assert_eq!(
            exited.load(Ordering::Acquire),
            1,
            "Only 1 task should have exited"
        );
    }

    #[tokio::test]
    async fn test_cancel_zombie_task() {
        let cancel_token = CancellationToken::new();
        let time_ms: u64 = 1;
        let debouncer = Debouncer::new(
            Duration::from_millis(time_ms),
            cancel_token.clone(),
            "test_task",
        )
        .with_task_timeout(Duration::from_millis(time_ms));

        let started = Arc::new(AtomicU32::new(0));
        let cancelled = Arc::new(AtomicU32::new(0));
        let exited = Arc::new(AtomicU32::new(0));
        let finished = Arc::new(AtomicU32::new(0));

        // Start a long running task
        let (started1_tx, started1_rx) = oneshot::channel();
        let started_clone = started.clone();
        let cancelled_clone = cancelled.clone();
        let excited_clone = exited.clone();
        let finished_clone = finished.clone();
        debouncer
            .debounce(move |token| async move {
                started_clone.fetch_add(1, Ordering::SeqCst);
                started1_tx.send(()).unwrap();
                tokio::select! {
                    _ = token.cancelled() => {
                        // Should exit here when cancelled
                        cancelled_clone.fetch_add(1, Ordering::SeqCst);

                        // act like a zombie task
                        loop {
                            sleep(Duration::from_millis(1)).await;
                        }
                    }
                    _ = sleep(Duration::from_secs(10)) => {
                        finished_clone.fetch_add(1, Ordering::SeqCst);
                    }
                }
                excited_clone.fetch_add(1, Ordering::SeqCst);
            })
            .await;

        // Wait for task to start
        started1_rx.await.unwrap();

        assert_eq!(
            started.load(Ordering::Acquire),
            1,
            "Task should have started"
        );

        // Cancel during execution
        cancel_token.cancel();

        debouncer.stop().await;

        // Verify task was cancelled before finishing
        assert_eq!(
            finished.load(Ordering::Acquire),
            0,
            "Task should not have finished"
        );

        assert_eq!(
            cancelled.load(Ordering::Acquire),
            1,
            "Task should have cancelled"
        );

        assert_eq!(
            exited.load(Ordering::Acquire),
            0,
            "Task should not have exited"
        );
    }
    #[tokio::test]
    async fn test_overlapping_tasks() {
        let time_ms: u64 = 1;

        let cancel_token = CancellationToken::new();
        let debouncer = Debouncer::new(Duration::from_millis(time_ms), cancel_token, "test_task");
        let started = Arc::new(AtomicU32::new(0));
        let cancelled = Arc::new(AtomicU32::new(0));
        let finished = Arc::new(AtomicU32::new(0));

        // Start first long task
        let (started1_tx, started1_rx) = oneshot::channel();
        let (ended2_tx, ended2_rx) = oneshot::channel();
        let started_clone = started.clone();
        let started_clone2 = started.clone();
        let cancelled_clone2 = cancelled.clone();
        let cancelled_clone = cancelled.clone();
        let finished_clone = finished.clone();
        let finished_clone2 = finished.clone();
        debouncer
            .debounce(move |token| async move {
                started_clone.fetch_add(1, Ordering::SeqCst);
                sleep(Duration::from_millis(time_ms * 2)).await;
                started1_tx.send(()).unwrap();
                tokio::select! {
                    _ = token.cancelled() => {
                        cancelled_clone.fetch_add(1, Ordering::SeqCst);
                    }
                    _ = sleep(Duration::from_secs(10)) => {
                        finished_clone.fetch_add(1, Ordering::SeqCst);
                    }
                }
            })
            .await;

        // Start second task before first finishes
        started1_rx.await.unwrap();

        debouncer
            .debounce(move |token| async move {
                started_clone2.fetch_add(1, Ordering::SeqCst);
                tokio::select! {
                    _ = token.cancelled() => {
                        cancelled_clone2.fetch_add(1, Ordering::SeqCst);
                    }
                    _ = sleep(Duration::from_millis(time_ms * 2)) => {
                        finished_clone2.fetch_add(1, Ordering::SeqCst);
                    }
                }
                ended2_tx.send(()).unwrap();
            })
            .await;

        // Wait and verify only second task completed
        ended2_rx.await.unwrap();

        sleep(Duration::from_millis(time_ms * 2)).await;

        assert_eq!(
            started.load(Ordering::Acquire),
            2,
            "Both tasks should have started"
        );
        assert_eq!(
            finished.load(Ordering::Acquire),
            1,
            "Only last task should finish"
        );
        assert_eq!(
            cancelled.load(Ordering::Acquire),
            1,
            "Only last task should be cancelled"
        );
    }

    #[tokio::test]
    async fn test_fixed_debouncer() {
        let cancel_token = CancellationToken::new();
        let counter = Arc::new(AtomicU32::new(0));

        let counter_clone = counter.clone();
        let task_debouncer = StoredTaskDebouncer::new(
            Duration::from_millis(100),
            cancel_token,
            "test_task",
            move |_token| {
                let counter = counter_clone.clone();
                async move {
                    counter.fetch_add(1, Ordering::SeqCst);
                }
            },
        );

        // Rapid triggers
        for _ in 0..5 {
            task_debouncer.debounce().await;
            sleep(Duration::from_millis(10)).await;
        }

        sleep(Duration::from_millis(200)).await;
        assert_eq!(counter.load(Ordering::Acquire), 1);
    }

    #[tokio::test]
    async fn test_task_debouncer_with_cancellation() {
        let cancel_token = CancellationToken::new();
        let started = Arc::new(AtomicU32::new(0));
        let cancelled = Arc::new(AtomicU32::new(0));
        let finished = Arc::new(AtomicU32::new(0));

        let started_clone = started.clone();
        let cancelled_clone = cancelled.clone();
        let finished_clone = finished.clone();

        let task_debouncer = StoredTaskDebouncer::new(
            Duration::from_millis(50),
            cancel_token.clone(),
            "test_task",
            move |token| {
                let started = started_clone.clone();
                let cancelled = cancelled_clone.clone();
                let finished = finished_clone.clone();
                async move {
                    started.fetch_add(1, Ordering::SeqCst);
                    tokio::select! {
                        _ = token.cancelled() => {
                            cancelled.fetch_add(1, Ordering::SeqCst);
                        }
                        _ = sleep(Duration::from_secs(10)) => {
                            finished.fetch_add(1, Ordering::SeqCst);
                        }
                    }
                }
            },
        );

        // Trigger the task
        task_debouncer.debounce().await;

        // Wait for task to start
        sleep(Duration::from_millis(100)).await;
        assert_eq!(started.load(Ordering::Acquire), 1);

        // Cancel the task
        cancel_token.cancel();
        task_debouncer.stop().await;

        // Verify cancellation
        assert_eq!(cancelled.load(Ordering::Acquire), 1);
        assert_eq!(finished.load(Ordering::Acquire), 0);
    }

    #[tokio::test]
    async fn test_task_debouncer_set_task() {
        let cancel_token = CancellationToken::new();
        let counter1 = Arc::new(AtomicU32::new(0));
        let counter2 = Arc::new(AtomicU32::new(0));
        let counter1_clone = counter1.clone();
        let mut task_debouncer = StoredTaskDebouncer::new(
            Duration::from_millis(50),
            cancel_token,
            "test_task",
            move |_token| {
                let counter = counter1_clone.clone();
                async move {
                    counter.fetch_add(1, Ordering::SeqCst);
                }
            },
        );

        // Test original task
        task_debouncer.debounce().await;
        sleep(Duration::from_millis(100)).await;
        assert_eq!(counter1.load(Ordering::Acquire), 1);
        assert_eq!(counter2.load(Ordering::Acquire), 0);

        // Set new task
        let counter2_clone = counter2.clone();
        task_debouncer.set_task(move |_token| {
            let counter = counter2_clone.clone();
            async move {
                counter.fetch_add(1, Ordering::SeqCst);
            }
        });

        // Test new task
        task_debouncer.debounce().await;
        sleep(Duration::from_millis(100)).await;
        assert_eq!(counter1.load(Ordering::Acquire), 1); // Should remain unchanged
        assert_eq!(counter2.load(Ordering::Acquire), 1); // Should be incremented
    }

    #[tokio::test]
    async fn test_max_wait_timeout() {
        let cancel_token = CancellationToken::new();
        let debounce_ms: u64 = 100;
        let max_wait_ms: u64 = 250;

        let debouncer = Debouncer::new(
            Duration::from_millis(debounce_ms),
            cancel_token.clone(),
            "test_task",
        )
        .with_max_wait(Duration::from_millis(max_wait_ms));

        let started = Arc::new(AtomicU32::new(0));
        let executed = Arc::new(AtomicU32::new(0));

        let (tx, mut rx) = tokio::sync::mpsc::channel::<Instant>(32);

        // Continuously trigger debounce events
        for _ in 0..10 {
            let started_clone = started.clone();
            let executed_clone = executed.clone();
            let tx = tx.clone();

            debouncer
                .debounce(move |token| async move {
                    started_clone.fetch_add(1, Ordering::SeqCst);
                    let exec_time = Instant::now();
                    tx.send(exec_time).await.unwrap();

                    tokio::select! {
                        _ = token.cancelled() => {}
                        _ = async {
                            executed_clone.fetch_add(1, Ordering::SeqCst);
                        } => {}
                    }
                })
                .await;

            sleep(Duration::from_millis(50)).await;
        }

        let mut exec_times = Vec::new();
        let timeout = sleep(Duration::from_millis(max_wait_ms + 100));

        tokio::pin!(timeout);

        loop {
            tokio::select! {
                Some(time) = rx.recv() => exec_times.push(time),
                _ = &mut timeout => break,
            }
        }

        assert!(
            exec_times.len() >= 2,
            "Should have at least 2 executions due to max_wait"
        );
        assert_eq!(
            started.load(Ordering::SeqCst),
            executed.load(Ordering::SeqCst),
            "All started tasks should have executed"
        );

        // Check intervals between executions
        for window in exec_times.windows(2) {
            let duration = window[1].duration_since(window[0]);
            assert!(
                duration <= Duration::from_millis(max_wait_ms + 50),
                "Time between executions ({:?}) should not exceed max_wait ({:?})",
                duration,
                Duration::from_millis(max_wait_ms)
            );
        }
    }

    #[tokio::test]
    async fn test_simple_debounce_events() {
        let cancel_token = CancellationToken::new();
        let debounce_ms: u64 = 100;

        let (event_tx, mut event_rx) = tokio::sync::mpsc::channel::<DebounceEvent>(32);

        let debouncer = Debouncer::new(
            Duration::from_millis(debounce_ms),
            cancel_token.clone(),
            "test_task",
        )
        .with_event_handler(move |event| {
            let event_tx = event_tx.clone();
            tokio::spawn(async move {
                let _ = event_tx.send(event).await;
            });
        });

        let executed = Arc::new(AtomicU32::new(0));

        // First task triggers debounce
        let executed_clone = executed.clone();
        debouncer
            .debounce(move |token| async move {
                tokio::select! {
                    _ = token.cancelled() => {}
                    _ = async {
                        executed_clone.fetch_add(1, Ordering::SeqCst);
                        sleep(Duration::from_millis(50)).await;
                    } => {}
                }
            })
            .await;

        // Trigger second debounce immediately - should cancel first timer
        let executed_clone = executed.clone();
        debouncer
            .debounce(move |token| async move {
                tokio::select! {
                    _ = token.cancelled() => {}
                    _ = async {
                        executed_clone.fetch_add(1, Ordering::SeqCst);
                        sleep(Duration::from_millis(50)).await;
                    } => {}
                }
            })
            .await;

        let mut events = Vec::new();
        let timeout = sleep(Duration::from_millis(debounce_ms * 3));
        tokio::pin!(timeout);

        loop {
            tokio::select! {
                Some(event) = event_rx.recv() => events.push(event),
                _ = &mut timeout => break,
            }
        }

        // Expected event sequence:
        // 1. Debounced for first task
        // 2. Debounced for second task (with first_debounce_at set)
        // 3. Started for second task
        // 4. Exit(Normal) for second task
        assert_eq!(events.len(), 4, "Should have received 4 events");

        // Verify event sequence
        let mut iter = events.iter();

        // First Debounced event
        if let Some(DebounceEvent::Debounced {
            first_debounce_at,
            instant,
            debounce_ends_at,
        }) = iter.next()
        {
            assert!(
                first_debounce_at.is_none(),
                "First debounce should have no first_debounce_at"
            );
            assert!(debounce_ends_at > instant, "Spawn time should be after now");
        } else {
            panic!("First event should be Debounced");
        }

        // Second Debounced event
        if let Some(DebounceEvent::Debounced {
            first_debounce_at,
            instant,
            debounce_ends_at,
        }) = iter.next()
        {
            assert!(
                first_debounce_at.is_some(),
                "Second debounce should have first_debounce_at set"
            );
            assert!(debounce_ends_at > instant, "Spawn time should be after now");
        } else {
            panic!("Second event should be Debounced");
        }

        // Started event
        if let Some(DebounceEvent::Started { instant: _ }) = iter.next() {
            // Event time exists
        } else {
            panic!("Third event should be Started");
        }

        // Exit event
        if let Some(DebounceEvent::Ended {
            instant: _,
            exit_status: TaskExit::Normal,
        }) = iter.next()
        {
            // Normal exit with timestamp
        } else {
            panic!("Fourth event should be Exit(Normal)");
        }

        assert_eq!(
            executed.load(Ordering::SeqCst),
            1,
            "Only second task should have executed"
        );
    }

    // Test for the new TaskDebouncer with trait
    struct TestTask {
        counter: Arc<AtomicU32>,
    }

    impl DebouncedTask for TestTask {
        async fn execute(&self, token: CancellationToken) {
            tokio::select! {
                _ = token.cancelled() => {}
                _ = async {
                    self.counter.fetch_add(1, Ordering::SeqCst);
                } => {}
            }
        }
    }

    #[tokio::test]
    async fn test_trait_based_task_debouncer() {
        let cancel_token = CancellationToken::new();
        let counter = Arc::new(AtomicU32::new(0));

        let task = TestTask {
            counter: counter.clone(),
        };

        let task_debouncer =
            TaskDebouncer::new(Duration::from_millis(100), cancel_token, "test_task", task);

        // Rapid triggers
        for _ in 0..5 {
            task_debouncer.debounce().await;
            sleep(Duration::from_millis(10)).await;
        }

        sleep(Duration::from_millis(200)).await;
        assert_eq!(counter.load(Ordering::Acquire), 1);
    }

    struct CancellableTestTask {
        started: Arc<AtomicU32>,
        cancelled: Arc<AtomicU32>,
        finished: Arc<AtomicU32>,
    }

    impl DebouncedTask for CancellableTestTask {
        async fn execute(&self, token: CancellationToken) {
            self.started.fetch_add(1, Ordering::SeqCst);
            tokio::select! {
                _ = token.cancelled() => {
                    self.cancelled.fetch_add(1, Ordering::SeqCst);
                }
                _ = sleep(Duration::from_secs(10)) => {
                    self.finished.fetch_add(1, Ordering::SeqCst);
                }
            }
        }
    }

    #[tokio::test]
    async fn test_trait_based_task_debouncer_with_cancellation() {
        let cancel_token = CancellationToken::new();
        let started = Arc::new(AtomicU32::new(0));
        let cancelled = Arc::new(AtomicU32::new(0));
        let finished = Arc::new(AtomicU32::new(0));

        let task = CancellableTestTask {
            started: started.clone(),
            cancelled: cancelled.clone(),
            finished: finished.clone(),
        };

        let task_debouncer = TaskDebouncer::new(
            Duration::from_millis(50),
            cancel_token.clone(),
            "test_task",
            task,
        );

        // Trigger the task
        task_debouncer.debounce().await;

        // Wait for task to start
        sleep(Duration::from_millis(100)).await;
        assert_eq!(started.load(Ordering::Acquire), 1);

        // Cancel the task
        cancel_token.cancel();
        task_debouncer.stop().await;

        // Verify cancellation
        assert_eq!(cancelled.load(Ordering::Acquire), 1);
        assert_eq!(finished.load(Ordering::Acquire), 0);
    }

    #[tokio::test]
    async fn test_trait_based_task_debouncer_set_task() {
        let cancel_token = CancellationToken::new();
        let counter1 = Arc::new(AtomicU32::new(0));
        let counter2 = Arc::new(AtomicU32::new(0));

        let task1 = TestTask {
            counter: counter1.clone(),
        };

        let mut task_debouncer =
            TaskDebouncer::new(Duration::from_millis(50), cancel_token, "test_task", task1);

        // Test original task
        task_debouncer.debounce().await;
        sleep(Duration::from_millis(100)).await;
        assert_eq!(counter1.load(Ordering::Acquire), 1);
        assert_eq!(counter2.load(Ordering::Acquire), 0);

        // Set new task
        let task2 = TestTask {
            counter: counter2.clone(),
        };
        task_debouncer.set_task(task2);

        // Test new task
        task_debouncer.debounce().await;
        sleep(Duration::from_millis(100)).await;
        assert_eq!(counter1.load(Ordering::Acquire), 1); // Should remain unchanged
        assert_eq!(counter2.load(Ordering::Acquire), 1); // Should be incremented
    }
}