foxtive-cron 0.6.0

Foxtive Cron
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
use async_trait::async_trait;
use foxtive_cron::contracts::{
    JobContract, MisfirePolicy, RetryPolicy, Schedule, ValidatedSchedule,
};
use foxtive_cron::{Cron, CronError, CronResult, FnJob, JobItem};
use std::borrow::Cow;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;
use tokio::time::timeout;

#[allow(dead_code)]
/// Minimal hand-rolled `JobContract` used throughout the tests.
struct MockJob {
    id: String,
    name: String,
    schedule: ValidatedSchedule,
    /// Incremented every time `run` is called.
    run_count: Arc<AtomicUsize>,
    /// When `true`, `run` returns an error instead of `Ok(())`.
    should_fail: bool,
    /// Incremented every time `on_start` is called.
    start_count: Arc<AtomicUsize>,
    /// Incremented every time `on_complete` is called.
    complete_count: Arc<AtomicUsize>,
    /// Incremented every time `on_error` is called.
    error_count: Arc<AtomicUsize>,
    timeout: Option<Duration>,
    priority: i32,
    concurrency_limit: Option<usize>,
    misfire_policy: MisfirePolicy,
    retry_policy: RetryPolicy,
}

#[allow(dead_code)]
impl MockJob {
    fn new(id: impl Into<String>, schedule_expr: &str) -> Self {
        let id = id.into();
        Self {
            id: id.clone(),
            name: id,
            schedule: ValidatedSchedule::parse(schedule_expr).unwrap(),
            run_count: Arc::new(AtomicUsize::new(0)),
            should_fail: false,
            start_count: Arc::new(AtomicUsize::new(0)),
            complete_count: Arc::new(AtomicUsize::new(0)),
            error_count: Arc::new(AtomicUsize::new(0)),
            timeout: None,
            priority: 0,
            concurrency_limit: None,
            misfire_policy: MisfirePolicy::Skip,
            retry_policy: RetryPolicy::None,
        }
    }

    fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    fn with_priority(mut self, priority: i32) -> Self {
        self.priority = priority;
        self
    }

    fn with_concurrency_limit(mut self, limit: usize) -> Self {
        self.concurrency_limit = Some(limit);
        self
    }

    fn with_misfire_policy(mut self, policy: MisfirePolicy) -> Self {
        self.misfire_policy = policy;
        self
    }

    fn with_retry_policy(mut self, policy: RetryPolicy) -> Self {
        self.retry_policy = policy;
        self
    }

    fn failing(id: impl Into<String>, schedule_expr: &str) -> Self {
        Self {
            should_fail: true,
            ..Self::new(id, schedule_expr)
        }
    }
}

#[async_trait]
impl JobContract for MockJob {
    async fn run(&self) -> CronResult<()> {
        self.run_count.fetch_add(1, Ordering::SeqCst);
        if self.should_fail {
            Err(CronError::ExecutionError(anyhow::anyhow!(
                "intentional failure"
            )))
        } else {
            Ok(())
        }
    }

    fn id(&self) -> Cow<'_, str> {
        Cow::Borrowed(&self.id)
    }

    fn name(&self) -> Cow<'_, str> {
        Cow::Borrowed(&self.name)
    }

    fn schedule(&self) -> &dyn Schedule {
        &self.schedule
    }

    fn timeout(&self) -> Option<Duration> {
        self.timeout
    }

    fn priority(&self) -> i32 {
        self.priority
    }

    fn concurrency_limit(&self) -> Option<usize> {
        self.concurrency_limit
    }

    fn misfire_policy(&self) -> MisfirePolicy {
        self.misfire_policy
    }

    fn retry_policy(&self) -> RetryPolicy {
        self.retry_policy.clone()
    }

    async fn on_start(&self) {
        self.start_count.fetch_add(1, Ordering::SeqCst);
    }

    async fn on_complete(&self) {
        self.complete_count.fetch_add(1, Ordering::SeqCst);
    }

    async fn on_error(&self, _error: &CronError) {
        self.error_count.fetch_add(1, Ordering::SeqCst);
    }
}

// ValidatedSchedule

mod validated_schedule {
    use super::*;

    #[test]
    fn accepts_valid_seven_field_expression() {
        assert!(ValidatedSchedule::parse("*/5 * * * * * *").is_ok());
    }

    #[test]
    fn accepts_every_second_expression() {
        assert!(ValidatedSchedule::parse("* * * * * * *").is_ok());
    }

    #[test]
    fn accepts_specific_time_expression() {
        // Every day at 03:30:00
        assert!(ValidatedSchedule::parse("0 30 3 * * * *").is_ok());
    }

    #[test]
    fn rejects_empty_expression() {
        assert!(ValidatedSchedule::parse("").is_err());
    }

    #[test]
    fn rejects_nonsense_expression() {
        assert!(ValidatedSchedule::parse("not a cron expression").is_err());
    }

    #[test]
    fn rejects_out_of_range_field() {
        // Seconds field goes 0-59; 99 is invalid.
        assert!(ValidatedSchedule::parse("99 * * * * * *").is_err());
    }

    #[test]
    fn error_message_includes_original_expression() {
        let err = ValidatedSchedule::parse("bad expr").unwrap_err();
        assert!(err.to_string().contains("bad expr"));
    }
}

// FnJob

mod fn_job {
    use super::*;

    #[test]
    fn new_returns_ok_with_valid_schedule() {
        let result = FnJob::new("job-id", "Job Name", "*/1 * * * * * *", || async { Ok(()) });
        assert!(result.is_ok());
    }

    #[test]
    fn new_returns_err_with_invalid_schedule() {
        let result = FnJob::new("job-id", "Job Name", "not-valid", || async { Ok(()) });
        assert!(result.is_err());
    }

    #[test]
    fn new_blocking_returns_ok_with_valid_schedule() {
        let result = FnJob::new_blocking("job-id", "Job Name", "*/1 * * * * * *", || Ok(()));
        assert!(result.is_ok());
    }

    #[test]
    fn new_blocking_returns_err_with_invalid_schedule() {
        let result = FnJob::new_blocking("job-id", "Job Name", "bad", || Ok(()));
        assert!(result.is_err());
    }

    #[test]
    fn id_returns_correct_value() {
        let job = FnJob::new("my-id", "My Name", "*/1 * * * * * *", || async { Ok(()) }).unwrap();
        assert_eq!(job.id(), "my-id");
    }

    #[test]
    fn name_returns_correct_value() {
        let job = FnJob::new("my-id", "My Name", "*/1 * * * * * *", || async { Ok(()) }).unwrap();
        assert_eq!(job.name(), "My Name");
    }

    #[test]
    fn description_defaults_to_none() {
        let job = FnJob::new("id", "Name", "*/1 * * * * * *", || async { Ok(()) }).unwrap();
        assert!(job.description().is_none());
    }

    #[tokio::test]
    async fn run_executes_async_closure() {
        let executed = Arc::new(AtomicBool::new(false));
        let executed_clone = executed.clone();

        let job = FnJob::new("id", "Name", "*/1 * * * * * *", move || {
            let flag = executed_clone.clone();
            async move {
                flag.store(true, Ordering::SeqCst);
                Ok(())
            }
        })
        .unwrap();

        job.run().await.unwrap();
        assert!(executed.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn run_propagates_async_closure_error() {
        let job = FnJob::new("id", "Name", "*/1 * * * * * *", || async {
            Err(CronError::ExecutionError(anyhow::anyhow!("oops")))
        })
        .unwrap();

        assert!(job.run().await.is_err());
    }

    #[tokio::test]
    async fn run_executes_blocking_closure() {
        let executed = Arc::new(AtomicBool::new(false));
        let executed_clone = executed.clone();

        let job = FnJob::new_blocking("id", "Name", "*/1 * * * * * *", move || {
            executed_clone.store(true, Ordering::SeqCst);
            Ok(())
        })
        .unwrap();

        job.run().await.unwrap();
        assert!(executed.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn run_propagates_blocking_closure_error() {
        let job = FnJob::new_blocking("id", "Name", "*/1 * * * * * *", || {
            Err(CronError::ExecutionError(anyhow::anyhow!("blocked error")))
        })
        .unwrap();

        assert!(job.run().await.is_err());
    }
}

// JobContract lifecycle hooks (via MockJob)

mod lifecycle_hooks {
    use super::*;

    #[tokio::test]
    async fn on_start_called_before_run() {
        let mock = Arc::new(MockJob::new("job", "*/1 * * * * * *"));
        let start_count = mock.start_count.clone();
        let run_count = mock.run_count.clone();

        let item = JobItem::new(mock, vec![], None, None).unwrap();
        item.run().await.unwrap();

        assert_eq!(start_count.load(Ordering::SeqCst), 1);
        assert_eq!(run_count.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn on_complete_called_on_success() {
        let mock = Arc::new(MockJob::new("job", "*/1 * * * * * *"));
        let complete_count = mock.complete_count.clone();
        let error_count = mock.error_count.clone();

        let item = JobItem::new(mock, vec![], None, None).unwrap();
        item.run().await.unwrap();

        assert_eq!(complete_count.load(Ordering::SeqCst), 1);
        assert_eq!(error_count.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn on_error_called_on_failure() {
        let mock = Arc::new(MockJob::failing("job", "*/1 * * * * * *"));
        let complete_count = mock.complete_count.clone();
        let error_count = mock.error_count.clone();

        let item = JobItem::new(mock, vec![], None, None).unwrap();
        let result = item.run().await;

        assert!(result.is_err());
        assert_eq!(error_count.load(Ordering::SeqCst), 1);
        assert_eq!(complete_count.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn on_complete_not_called_on_failure() {
        let mock = Arc::new(MockJob::failing("job", "*/1 * * * * * *"));
        let complete_count = mock.complete_count.clone();

        let item = JobItem::new(mock, vec![], None, None).unwrap();
        let _ = item.run().await;

        assert_eq!(complete_count.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn on_error_not_called_on_success() {
        let mock = Arc::new(MockJob::new("job", "*/1 * * * * * *"));
        let error_count = mock.error_count.clone();

        let item = JobItem::new(mock, vec![], None, None).unwrap();
        item.run().await.unwrap();

        assert_eq!(error_count.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn all_hooks_fire_in_correct_sequence() {
        // We use a shared counter to verify ordering: start < run < complete.
        use std::sync::Mutex;

        struct OrderedJob {
            schedule: ValidatedSchedule,
            log: Arc<Mutex<Vec<&'static str>>>,
        }

        #[async_trait]
        impl JobContract for OrderedJob {
            async fn run(&self) -> CronResult<()> {
                self.log.lock().unwrap().push("run");
                Ok(())
            }
            fn id(&self) -> Cow<'_, str> {
                Cow::Borrowed("ordered")
            }
            fn name(&self) -> Cow<'_, str> {
                Cow::Borrowed("Ordered")
            }
            fn schedule(&self) -> &dyn Schedule {
                &self.schedule
            }
            async fn on_start(&self) {
                self.log.lock().unwrap().push("start");
            }
            async fn on_complete(&self) {
                self.log.lock().unwrap().push("complete");
            }
            async fn on_error(&self, _error: &CronError) {
                self.log.lock().unwrap().push("error");
            }
        }

        let log = Arc::new(Mutex::new(Vec::new()));
        let job = Arc::new(OrderedJob {
            schedule: ValidatedSchedule::parse("*/1 * * * * * *").unwrap(),
            log: log.clone(),
        });

        let item = JobItem::new(job, vec![], None, None).unwrap();
        item.run().await.unwrap();

        let entries = log.lock().unwrap().clone();
        assert_eq!(entries, vec!["start", "run", "complete"]);
    }
}

// Cron scheduler

mod cron_scheduler {
    use super::*;

    #[test]
    fn new_creates_empty_scheduler() {
        let cron = Cron::new();
        // We can only observe emptiness indirectly: adding nothing and
        // checking that `default()` also compiles without panic.
        let _ = cron;
        let _ = Cron::default();
    }

    #[test]
    fn add_job_fn_accepts_valid_schedule() {
        let mut cron = Cron::new();
        let result = cron.add_job_fn("id", "Name", "*/1 * * * * * *", || async { Ok(()) });
        assert!(result.is_ok());
    }

    #[test]
    fn add_job_fn_rejects_invalid_schedule() {
        let mut cron = Cron::new();
        let result = cron.add_job_fn("id", "Name", "bad schedule", || async { Ok(()) });
        assert!(result.is_err());
    }

    #[test]
    fn add_blocking_job_fn_accepts_valid_schedule() {
        let mut cron = Cron::new();
        let result = cron.add_blocking_job_fn("id", "Name", "*/1 * * * * * *", || Ok(()));
        assert!(result.is_ok());
    }

    #[test]
    fn add_blocking_job_fn_rejects_invalid_schedule() {
        let mut cron = Cron::new();
        let result = cron.add_blocking_job_fn("id", "Name", "nope", || Ok(()));
        assert!(result.is_err());
    }

    #[test]
    fn add_job_accepts_arc_job_contract() {
        let mut cron = Cron::new();
        let job = MockJob::new("mock", "*/1 * * * * * *");
        assert!(cron.add_job(job).is_ok());
    }

    #[test]
    fn multiple_jobs_can_be_registered() {
        let mut cron = Cron::new();
        for i in 0..5 {
            let job = MockJob::new(format!("mock-{}", i), "*/1 * * * * * *");
            cron.add_job(job)
                .unwrap_or_else(|_| panic!("failed on job {i}"));
        }
    }

    #[test]
    fn list_job_ids_returns_correct_ids() {
        let mut cron = Cron::new();
        cron.add_job_fn("job-1", "Job 1", "*/1 * * * * * *", || async { Ok(()) })
            .unwrap();
        cron.add_job_fn("job-2", "Job 2", "*/1 * * * * * *", || async { Ok(()) })
            .unwrap();

        let ids = cron.list_job_ids();
        assert_eq!(ids.len(), 2);
        assert!(ids.contains(&"job-1".to_string()));
        assert!(ids.contains(&"job-2".to_string()));
    }

    #[tokio::test]
    async fn remove_job_removes_from_registry() {
        let mut cron = Cron::new();
        cron.add_job_fn("job-1", "Job 1", "*/1 * * * * * *", || async { Ok(()) })
            .unwrap();
        assert!(cron.remove_job("job-1").is_some());
        assert_eq!(cron.list_job_ids().len(), 0);
    }

    #[tokio::test]
    async fn trigger_job_executes_immediately() {
        let run_count = Arc::new(AtomicUsize::new(0));
        let run_count_clone = run_count.clone();

        let mut cron = Cron::new();
        cron.add_job_fn("job-1", "Job 1", "0 0 0 1 1 * *", move || {
            let count = run_count_clone.clone();
            async move {
                count.fetch_add(1, Ordering::SeqCst);
                Ok(())
            }
        })
        .unwrap();

        cron.trigger_job("job-1").await.unwrap();

        // Wait a bit for the spawned task to run
        let result = timeout(Duration::from_secs(1), async {
            loop {
                if run_count.load(Ordering::SeqCst) >= 1 {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        })
        .await;

        assert!(result.is_ok(), "manual trigger did not execute job");
    }

    /// Verifies that a job registered on a every-second schedule actually fires
    /// within a reasonable window when the scheduler is running.
    #[tokio::test]
    async fn scheduler_executes_registered_job() {
        let run_count = Arc::new(AtomicUsize::new(0));
        let run_count_clone = run_count.clone();

        let mut cron = Cron::new();
        cron.add_job_fn("id", "Name", "*/1 * * * * * *", move || {
            let count = run_count_clone.clone();
            async move {
                count.fetch_add(1, Ordering::SeqCst);
                Ok(())
            }
        })
        .unwrap();

        let handle = tokio::spawn(async move {
            cron.run().await;
        });

        // Wait up to 3 seconds for at least one execution.
        let result = timeout(Duration::from_secs(3), async {
            loop {
                if run_count.load(Ordering::SeqCst) >= 1 {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        })
        .await;

        handle.abort();
        assert!(result.is_ok(), "job was not executed within 3 seconds");
    }

    /// Verifies that two jobs scheduled every second both fire within a reasonable window.
    #[tokio::test]
    async fn scheduler_executes_multiple_jobs_concurrently() {
        let count_a = Arc::new(AtomicUsize::new(0));
        let count_b = Arc::new(AtomicUsize::new(0));
        let count_a_clone = count_a.clone();
        let count_b_clone = count_b.clone();

        let mut cron = Cron::new();

        cron.add_job_fn("job-a", "Job A", "*/1 * * * * * *", move || {
            let c = count_a_clone.clone();
            async move {
                c.fetch_add(1, Ordering::SeqCst);
                Ok(())
            }
        })
        .unwrap();

        cron.add_job_fn("job-b", "Job B", "*/1 * * * * * *", move || {
            let c = count_b_clone.clone();
            async move {
                c.fetch_add(1, Ordering::SeqCst);
                Ok(())
            }
        })
        .unwrap();

        let handle = tokio::spawn(async move {
            cron.run().await;
        });

        let result = timeout(Duration::from_secs(3), async {
            loop {
                if count_a.load(Ordering::SeqCst) >= 1 && count_b.load(Ordering::SeqCst) >= 1 {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        })
        .await;

        handle.abort();
        assert!(
            result.is_ok(),
            "one or both jobs were not executed within 3 seconds"
        );
    }

    /// A failing job should not crash the scheduler; other jobs must continue firing.
    #[tokio::test]
    async fn failing_job_does_not_crash_scheduler() {
        let good_count = Arc::new(AtomicUsize::new(0));
        let good_count_clone = good_count.clone();

        let mut cron = Cron::new();

        // Register a job that always errors.
        cron.add_job_fn("bad-job", "Bad Job", "*/1 * * * * * *", || async {
            Err(CronError::ExecutionError(anyhow::anyhow!("always fails")))
        })
        .unwrap();

        // Register a healthy job alongside it.
        cron.add_job_fn("good-job", "Good Job", "*/1 * * * * * *", move || {
            let c = good_count_clone.clone();
            async move {
                c.fetch_add(1, Ordering::SeqCst);
                Ok(())
            }
        })
        .unwrap();

        let handle = tokio::spawn(async move {
            cron.run().await;
        });

        let result = timeout(Duration::from_secs(3), async {
            loop {
                if good_count.load(Ordering::SeqCst) >= 1 {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        })
        .await;

        handle.abort();
        assert!(
            result.is_ok(),
            "good job was not executed - scheduler may have crashed on bad job"
        );
    }

    /// An empty scheduler should return promptly rather than hanging forever.
    #[tokio::test]
    async fn empty_scheduler_exits_promptly() {
        let mut cron = Cron::new();
        let result = timeout(Duration::from_millis(200), async move {
            cron.run().await;
        })
        .await;
        assert!(result.is_ok(), "empty scheduler did not exit in time");
    }

    #[tokio::test]
    async fn removed_job_stops_running() {
        let run_count = Arc::new(AtomicUsize::new(0));
        let run_count_clone = run_count.clone();

        let mut cron = Cron::new();
        cron.add_job_fn("job-1", "Job 1", "*/1 * * * * * *", move || {
            let count = run_count_clone.clone();
            async move {
                count.fetch_add(1, Ordering::SeqCst);
                Ok(())
            }
        })
        .unwrap();

        let run_count_for_loop = run_count.clone();
        let handle = tokio::spawn(async move {
            // Wait for at least one run
            while run_count_for_loop.load(Ordering::SeqCst) == 0 {
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
            // Start the scheduler in another task
            let (tx, mut rx) = tokio::sync::mpsc::channel(1);
            let mut cron_inner = cron;

            let handle_inner = tokio::spawn(async move {
                tokio::select! {
                    _ = cron_inner.run() => {},
                    _ = rx.recv() => {
                        cron_inner.remove_job("job-1");
                        // We need to keep running to see if it triggers again
                        cron_inner.run().await;
                    },
                }
            });

            // Signal to remove the job after it has run at least once
            tx.send(()).await.unwrap();

            // Let it "run" for a bit more
            tokio::time::sleep(Duration::from_secs(2)).await;
            handle_inner.abort();
        });

        tokio::time::sleep(Duration::from_secs(1)).await;
        let count_after_removal = run_count.load(Ordering::SeqCst);

        tokio::time::sleep(Duration::from_secs(2)).await;
        let final_count = run_count.load(Ordering::SeqCst);

        handle.abort();

        assert!(
            final_count <= count_after_removal + 1,
            "job continued to run after removal. count_after_removal: {}, final_count: {}",
            count_after_removal,
            final_count
        );
    }

    #[tokio::test]
    async fn job_timeout_is_enforced() {
        struct SlowJob {
            schedule: ValidatedSchedule,
        }
        #[async_trait]
        impl JobContract for SlowJob {
            async fn run(&self) -> CronResult<()> {
                tokio::time::sleep(Duration::from_secs(2)).await;
                Ok(())
            }
            fn id(&self) -> Cow<'_, str> {
                Cow::Borrowed("slow")
            }
            fn name(&self) -> Cow<'_, str> {
                Cow::Borrowed("Slow")
            }
            fn schedule(&self) -> &dyn Schedule {
                &self.schedule
            }
            fn timeout(&self) -> Option<Duration> {
                Some(Duration::from_secs(1))
            }
            async fn on_error(&self, _error: &CronError) {}
        }

        let job = Arc::new(SlowJob {
            schedule: ValidatedSchedule::parse("*/1 * * * * * *").unwrap(),
        });

        let item = JobItem::new(job, vec![], None, None).unwrap();
        let result = item.run().await;

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("timed out"));
    }

    #[tokio::test]
    async fn global_concurrency_limit_is_enforced() {
        let run_count = Arc::new(AtomicUsize::new(0));
        let active_count = Arc::new(AtomicUsize::new(0));
        let max_active = Arc::new(AtomicUsize::new(0));

        let mut cron = Cron::new().with_global_concurrency_limit(2);

        for i in 0..5 {
            let run_count = run_count.clone();
            let active_count = active_count.clone();
            let max_active = max_active.clone();

            cron.add_job_fn(format!("job-{}", i), "Job", "*/1 * * * * * *", move || {
                let run_count = run_count.clone();
                let active_count = active_count.clone();
                let max_active = max_active.clone();
                async move {
                    let current = active_count.fetch_add(1, Ordering::SeqCst) + 1;
                    loop {
                        let prev = max_active.load(Ordering::SeqCst);
                        if current <= prev
                            || max_active
                                .compare_exchange(prev, current, Ordering::SeqCst, Ordering::SeqCst)
                                .is_ok()
                        {
                            break;
                        }
                    }

                    tokio::time::sleep(Duration::from_millis(100)).await;
                    run_count.fetch_add(1, Ordering::SeqCst);
                    active_count.fetch_sub(1, Ordering::SeqCst);
                    Ok(())
                }
            })
            .unwrap();
        }

        let handle = tokio::spawn(async move {
            cron.run().await;
        });

        // Wait for some jobs to run
        tokio::time::sleep(Duration::from_secs(2)).await;
        handle.abort();

        assert!(
            max_active.load(Ordering::SeqCst) <= 2,
            "global concurrency limit exceeded: {}",
            max_active.load(Ordering::SeqCst)
        );
        assert!(run_count.load(Ordering::SeqCst) > 0);
    }

    #[tokio::test]
    async fn per_job_concurrency_limit_is_enforced() {
        let run_count = Arc::new(AtomicUsize::new(0));
        let active_count = Arc::new(AtomicUsize::new(0));
        let max_active = Arc::new(AtomicUsize::new(0));

        let mut cron = Cron::new();
        let run_count_clone = run_count.clone();
        let active_count_clone = active_count.clone();
        let max_active_clone = max_active.clone();

        struct LimitedJob {
            schedule: ValidatedSchedule,
            active_count: Arc<AtomicUsize>,
            max_active: Arc<AtomicUsize>,
            run_count: Arc<AtomicUsize>,
        }
        #[async_trait]
        impl JobContract for LimitedJob {
            async fn run(&self) -> CronResult<()> {
                let current = self.active_count.fetch_add(1, Ordering::SeqCst) + 1;
                loop {
                    let prev = self.max_active.load(Ordering::SeqCst);
                    if current <= prev
                        || self
                            .max_active
                            .compare_exchange(prev, current, Ordering::SeqCst, Ordering::SeqCst)
                            .is_ok()
                    {
                        break;
                    }
                }
                tokio::time::sleep(Duration::from_millis(500)).await;
                self.run_count.fetch_add(1, Ordering::SeqCst);
                self.active_count.fetch_sub(1, Ordering::SeqCst);
                Ok(())
            }
            fn id(&self) -> Cow<'_, str> {
                Cow::Borrowed("limited-job")
            }
            fn name(&self) -> Cow<'_, str> {
                Cow::Borrowed("Limited")
            }
            fn schedule(&self) -> &dyn Schedule {
                &self.schedule
            }
            fn concurrency_limit(&self) -> Option<usize> {
                Some(1)
            }
            async fn on_error(&self, _error: &CronError) {}
        }

        let job = LimitedJob {
            schedule: ValidatedSchedule::parse("* * * * * * *").unwrap(),
            active_count: active_count_clone,
            max_active: max_active_clone,
            run_count: run_count_clone,
        };

        cron.add_job(job).unwrap();

        let handle = tokio::spawn(async move {
            cron.run().await;
        });

        tokio::time::sleep(Duration::from_secs(2)).await;
        handle.abort();

        assert_eq!(
            max_active.load(Ordering::SeqCst),
            1,
            "per-job concurrency limit exceeded"
        );
    }

    #[tokio::test]
    async fn priority_is_respected() {
        let mut cron = Cron::new();

        struct PriorityJob {
            id: String,
            priority: i32,
            schedule: ValidatedSchedule,
        }
        #[async_trait]
        impl JobContract for PriorityJob {
            async fn run(&self) -> CronResult<()> {
                Ok(())
            }
            fn id(&self) -> Cow<'_, str> {
                Cow::Borrowed(&self.id)
            }
            fn name(&self) -> Cow<'_, str> {
                Cow::Borrowed(&self.id)
            }
            fn schedule(&self) -> &dyn Schedule {
                &self.schedule
            }
            fn priority(&self) -> i32 {
                self.priority
            }
            async fn on_error(&self, _error: &CronError) {}
        }

        let schedule = ValidatedSchedule::parse("*/10 * * * * * *").unwrap();

        // Add jobs in "wrong" order
        for p in [1, 3, 2] {
            cron.add_job(PriorityJob {
                id: format!("p-{}", p),
                priority: p,
                schedule: schedule.clone(),
            })
            .unwrap();
        }

        assert_eq!(cron.queue_len(), 3);
        assert_eq!(cron.peek_job_id(), Some("p-3".to_string()));
    }

    #[tokio::test]
    async fn fixed_retry_policy_is_enforced() {
        let job = Arc::new(
            MockJob::failing("retry-job", "*/1 * * * * * *").with_retry_policy(
                RetryPolicy::Fixed {
                    max_retries: 2,
                    interval: Duration::from_millis(10),
                },
            ),
        );

        let run_count_clone = job.run_count.clone();
        let item = JobItem::new(job, vec![], None, None).unwrap();
        let result = item.run().await;

        assert!(result.is_err());
        assert_eq!(run_count_clone.load(Ordering::SeqCst), 3); // 1 original + 2 retries
    }

    #[tokio::test]
    async fn exponential_retry_policy_is_enforced() {
        let job = Arc::new(
            MockJob::failing("retry-job-exp", "*/1 * * * * * *").with_retry_policy(
                RetryPolicy::Exponential {
                    max_retries: 2,
                    initial_interval: Duration::from_millis(10),
                    max_interval: Duration::from_millis(100),
                },
            ),
        );

        let run_count_clone = job.run_count.clone();
        let item = JobItem::new(job, vec![], None, None).unwrap();
        let result = item.run().await;

        assert!(result.is_err());
        assert_eq!(run_count_clone.load(Ordering::SeqCst), 3);
    }
}