atap 0.1.0

Threadsafe futureless async runtime for macOS
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
mod common;

use atap::{
    Runtime, RuntimeError, TaskState,
    sleep::{Sleep, SleepMode},
};
use common::{drain, report, take_a_run};
use std::{
    thread,
    time::{Duration, Instant},
};

/// Prints how a blocking precise sleep compares to `thread::sleep`
#[test]
fn sleep_accuracy_vs_std_blocking() {
    let _ = Runtime::init();

    let duration = Duration::from_secs(1);

    let handle = thread::spawn(move || {
        println!("Running std ...\n");
        let start = Instant::now();
        thread::sleep(duration);
        let elapsed = start.elapsed();
        println!("std slept for: {:?}", elapsed);

        elapsed
    });

    println!("Running atap ...");
    let result = Runtime::block(Sleep::sleep(duration));

    println!("Result: {:?}", result);

    let std = handle.join().unwrap();

    println!("\nDiff: {:?}", std - result);
    println!(
        "std error:{:?}\natap error:{:?}\n",
        std - duration,
        result - duration
    )
}

/// Blocking sleeps on several threads at once
#[test]
fn sleep_multi_threaded_blocking() {
    let _ = Runtime::init();

    let threads = 4;

    (1..=threads).into_iter().for_each(|i| {
        thread::spawn(move || {
            let duration = Duration::from_secs(i);

            // Every other thread sleeps the other way
            let mode = match i % 2 == 0 {
                true => SleepMode::Precise,
                false => SleepMode::Relaxed,
            };

            let time = Runtime::block(Sleep::sleep(duration).mode(mode));

            let error = time - duration;
            println!("Thread {} slept for {:?}\n{:?} error\n", i, time, error);
        });
    });

    Runtime::block(Sleep::sleep(Duration::from_secs(threads + 2)).mode(SleepMode::Relaxed));
}

/// A single spawned sleep joins
#[test]
fn single_spawned_task() {
    let _ = Runtime::init();

    let handle = Runtime::task(Sleep::sleep(Duration::from_secs(2))).spawn();

    if let Ok(time) = handle.join() {
        println!("atap slept for: {:?}", time);
    } else {
        println!("Failed");
    };
}

/// Two handles to one task both read the same output
#[test]
fn duplicated_handles_both_join() {
    let _ = Runtime::init();

    let duration = Duration::from_millis(200);

    let first = Runtime::task(Sleep::sleep(duration).mode(SleepMode::Relaxed)).spawn();
    let second = first.clone();

    let one = first.join().expect("first listener");
    let two = second.join().expect("second listener");

    println!("first got {:?}, second got {:?}", one, two);

    assert_eq!(one, two, "both listeners read the same output");
    assert!(one >= duration, "the task actually ran");
}

/// A take leaves other handles reading `AlreadyTaken`
#[test]
fn take_invalidates_other_handles() {
    let _ = Runtime::init();

    let first =
        Runtime::task(Sleep::sleep(Duration::from_millis(200)).mode(SleepMode::Relaxed)).spawn();
    let second = first.clone();

    let taken = first.take().expect("the value moves out once");
    println!("took {:?}", taken);

    assert_eq!(
        second.join(),
        Err(RuntimeError::AlreadyTaken),
        "the second listener finds the value gone rather than blocking",
    );
}

/// A cancelled task reads `Cancelled` through every handle
#[test]
fn cancelled_task_is_unreadable() {
    let _ = Runtime::init();

    let first =
        Runtime::task(Sleep::sleep(Duration::from_secs(1)).mode(SleepMode::Relaxed)).spawn();
    let second = first.clone();

    first.cancel();

    assert_eq!(
        second.join(),
        Err(RuntimeError::Cancelled),
        "a cancelled task hands nothing out",
    );
}

/// `try_join` says why there is nothing to read
#[test]
fn try_join_says_why_rather_than_just_nothing() {
    let _ = Runtime::init();

    let handle =
        Runtime::task(Sleep::sleep(Duration::from_secs(1)).mode(SleepMode::Relaxed)).spawn();
    let watcher = handle.clone();

    assert_eq!(
        watcher.try_join(),
        Err(RuntimeError::NotReady),
        "a task still running hasn't failed, it just isn't finished",
    );

    handle.cancel();

    assert_eq!(
        watcher.try_join(),
        Err(RuntimeError::Cancelled),
        "a cancelled task says so rather than looking unfinished",
    );
}

/// A timed out join leaves the handle usable
#[test]
fn join_with_timeout_gives_up_without_giving_up_the_handle() {
    let _ = Runtime::init();

    let duration = Duration::from_secs(1);
    let handle = Runtime::task(Sleep::sleep(duration).mode(SleepMode::Relaxed)).spawn();

    assert_eq!(
        handle.join_with_timeout(Duration::from_millis(50)),
        Err(RuntimeError::NotReady),
        "nowhere near long enough, and it says so",
    );

    // Borrowed rather than consumed, so the task is still there
    let slept = handle
        .join_with_timeout(Duration::from_secs(5))
        .expect("the second wait is long enough");

    println!("gave up once, then waited and got {:?}", slept);

    assert!(
        slept >= duration,
        "the task came back with {:?} for a {:?} sleep",
        slept,
        duration,
    );
}

/// A back to back repeat keeps running until it is cancelled
#[test]
fn repeating_runs_until_cancelled() {
    let _ = Runtime::init();

    let wanted = 20;
    let handle = Runtime::task(Sleep::sleep(Duration::from_millis(5)).mode(SleepMode::Relaxed))
        .repeat()
        .spawn();

    // A take that succeeds is a run that happened
    for _ in 0..wanted {
        take_a_run(&handle);
    }

    handle.clone().cancel();

    assert_eq!(
        handle.clone().take(),
        Err(RuntimeError::Cancelled),
        "a cancelled series hands nothing out",
    );

    // Long enough for several more runs, had any been coming
    thread::sleep(Duration::from_millis(100));

    assert_eq!(
        handle.take(),
        Err(RuntimeError::Cancelled),
        "the series carried on after being cancelled",
    );

    println!("{} runs through one handle, then cancelled", wanted);
}

/// A back to back repeat never overlaps its runs
#[test]
fn repeating_finishes_a_run_before_the_next() {
    let _ = Runtime::init();

    let duration = Duration::from_millis(50);
    let runs: u32 = 5;

    let handle = Runtime::task(Sleep::sleep(duration).mode(SleepMode::Relaxed))
        .repeat()
        .spawn();

    // One on its own first, so the clock starts at the end of a run
    take_a_run(&handle);

    let started = Instant::now();

    for _ in 0..runs {
        take_a_run(&handle);
    }

    let elapsed = started.elapsed();

    handle.clone().cancel();

    // Four whole runs between the first take and the last
    let floor = duration * (runs - 1);

    println!(
        "{} runs of {:?} took {:?}, floor {:?}",
        runs, duration, elapsed, floor
    );

    assert!(
        elapsed >= floor,
        "{} runs of {:?} took {:?}, so they were overlapping",
        runs,
        duration,
        elapsed,
    );
}

/// A repeat with a gap waits out the gap between runs
#[test]
fn repeat_every_waits_between_runs() {
    let _ = Runtime::init();

    let interval = Duration::from_millis(50);
    let runs: u32 = 5;

    // A task with nothing in it, so what is measured is the gap
    let handle = Runtime::task(Sleep::sleep(Duration::from_nanos(1)))
        .repeat()
        .every(interval)
        .spawn();

    // One on its own first, so the clock starts at the end of a run
    take_a_run(&handle);

    let started = Instant::now();

    for _ in 0..runs {
        take_a_run(&handle);
    }

    let elapsed = started.elapsed();

    handle.clone().cancel();

    // Four whole gaps between the first take and the last
    let floor = interval * (runs - 1);

    println!(
        "{} runs {:?} apart took {:?}, floor {:?}",
        runs, interval, elapsed, floor,
    );

    assert!(
        elapsed >= floor,
        "{} runs {:?} apart took only {:?}",
        runs,
        interval,
        elapsed,
    );
}

/// `at_rate` starts its runs no closer together than the period
#[test]
fn every_starts_runs_on_the_interval() {
    let _ = Runtime::init();

    let interval = Duration::from_millis(50);
    let runs: u32 = 5;

    // A task with nothing in it, so what is measured is the clock
    let handle = Runtime::task(Sleep::sleep(Duration::from_nanos(1)))
        .at_rate(interval)
        .spawn();

    // One on its own first, so the clock starts at the end of a run
    take_a_run(&handle);

    let started = Instant::now();

    for _ in 0..runs {
        take_a_run(&handle);
    }

    let elapsed = started.elapsed();

    handle.clone().cancel();

    // Four whole periods between the first take and the last
    let floor = interval * (runs - 1);

    println!(
        "{} runs on a {:?} period took {:?}, floor {:?}",
        runs, interval, elapsed, floor,
    );

    assert!(
        elapsed >= floor,
        "{} runs on a {:?} period took only {:?}",
        runs,
        interval,
        elapsed,
    );
}

/// Cancelling an `at_rate` schedule ends every run of it
#[test]
fn every_ends_the_whole_series_on_cancel() {
    let _ = Runtime::init();

    let handle = Runtime::task(Sleep::sleep(Duration::from_nanos(1)))
        .at_rate(Duration::from_millis(5))
        .spawn();

    // Several periods in, so the schedule is well established
    for _ in 0..10 {
        take_a_run(&handle);
    }

    handle.clone().cancel();

    assert_eq!(
        handle.clone().take(),
        Err(RuntimeError::Cancelled),
        "a cancelled schedule hands nothing out",
    );

    // Long enough for many more periods, and for every run in
    // flight to have tried to publish
    thread::sleep(Duration::from_millis(200));

    assert_eq!(
        handle.take(),
        Err(RuntimeError::Cancelled),
        "the schedule carried on after being cancelled",
    );
}

/// A million tasks spawned and joined one at a time
#[test]
fn many_one_by_one_tasks() {
    let _ = Runtime::init();

    let tasks = 1_000_000;

    let mut avg = 0.0;

    for _ in 0..tasks {
        let handle = Runtime::task(Sleep::sleep(Duration::from_nanos(500))).spawn();

        if let Ok(time) = handle.join() {
            avg += time.as_nanos() as f32;
        }
    }

    avg /= tasks as f32;

    println!("Average time: {}", avg);
}

/// The pool works through a backlog while the manager is down,
/// alongside every other test in this file, and the manager
/// comes back
#[test]
fn survives_losing_its_manager() {
    let _ = Runtime::init();

    let tasks = 200_000;
    let quick = || Sleep::sleep(Duration::from_nanos(1));

    let started = Instant::now();

    // Deep enough that the pool is still working through it
    // long after the manager has gone
    let before: Vec<_> = (0..tasks).map(|_| Runtime::task(quick()).spawn()).collect();

    Runtime::inject_manager_faults(3);

    let during: Vec<_> = (0..tasks).map(|_| Runtime::task(quick()).spawn()).collect();

    let mut finished = 0u64;

    for handle in before.into_iter().chain(during) {
        handle
            .join()
            .expect("every task finishes with no manager to help it");

        finished += 1;
    }

    report("manager back");

    // Only the manager reads this timer
    let timed = Runtime::task(quick())
        .repeat()
        .every(Duration::from_millis(20))
        .spawn();

    for _ in 0..3 {
        take_a_run(&timed);
    }

    timed.cancel();

    println!(
        "{} tasks through a pool that lost its manager three times in {:?}, and timers after",
        finished,
        started.elapsed(),
    );
}

/// `try_take` polls a task whose output can't be cloned
/// without committing to waiting for it
#[test]
fn try_take_polls_without_committing() {
    let _ = Runtime::init();

    let handle =
        Runtime::task(Sleep::sleep(Duration::from_millis(200)).mode(SleepMode::Relaxed)).spawn();

    assert_eq!(
        handle.try_take(),
        Err(RuntimeError::NotReady),
        "a task still running hasn't failed, it just isn't finished",
    );

    handle.wait().expect("the task settles");

    let taken = handle.try_take().expect("the value moves out once");
    println!("took {taken:?}");

    assert_eq!(
        handle.try_take(),
        Err(RuntimeError::AlreadyTaken),
        "only one caller ever gets the output, however it is asked for",
    );
}

/// Giving up on a take leaves the output where it was
#[test]
fn take_with_timeout_costs_nothing_when_it_gives_up() {
    let _ = Runtime::init();

    let handle =
        Runtime::task(Sleep::sleep(Duration::from_millis(300)).mode(SleepMode::Relaxed)).spawn();

    assert_eq!(
        handle.take_with_timeout(Duration::from_millis(20)),
        Err(RuntimeError::NotReady),
        "ran out of patience before the task ran out of work",
    );

    // Nothing was claimed, so the value is still there
    let taken = handle
        .take_with_timeout(Duration::from_secs(5))
        .expect("the output survived the caller giving up on it");

    println!("took {taken:?} on the second ask");
}

/// Waiting without reading, and without giving up the handle
#[test]
fn wait_settles_without_consuming_or_reading() {
    let _ = Runtime::init();

    let handle =
        Runtime::task(Sleep::sleep(Duration::from_millis(50)).mode(SleepMode::Relaxed)).spawn();

    let state = handle.wait().expect("the task settles");

    assert_eq!(state, TaskState::Ready, "it finished, so it has an output");
    assert!(handle.is_ready(), "and the handle agrees");

    handle.join().expect("the output is still there to be had");
}

/// The state and the predicates say the same thing
#[test]
fn state_and_predicates_agree() {
    let _ = Runtime::init();

    let ready =
        Runtime::task(Sleep::sleep(Duration::from_millis(20)).mode(SleepMode::Relaxed)).spawn();
    ready.wait().expect("it settles");

    assert_eq!(ready.state(), TaskState::Ready);
    assert!(ready.is_ready() && ready.settled());

    let cancelled =
        Runtime::task(Sleep::sleep(Duration::from_secs(5)).mode(SleepMode::Relaxed)).spawn();
    cancelled.clone().cancel();

    assert_eq!(cancelled.state(), TaskState::Cancelled);
    assert!(cancelled.is_cancelled() && cancelled.settled());

    // Settled is not the same as having something to hand out
    assert!(
        !cancelled.is_ready(),
        "a cancelled task has settled and has nothing to give",
    );

    let taken =
        Runtime::task(Sleep::sleep(Duration::from_millis(20)).mode(SleepMode::Relaxed)).spawn();
    let watcher = taken.clone();
    taken.take().expect("the value moves out");

    assert_eq!(watcher.state(), TaskState::Taken);
    assert!(watcher.is_taken());

    // An empty slot is never observable through a handle
    for handle in [&ready, &cancelled, &watcher] {
        assert_ne!(
            handle.state(),
            TaskState::Free,
            "a live handle is never free"
        );
    }
}

/// A repeat built at a priority is still a repeat
#[test]
fn builder_repeats_at_a_priority() {
    let _ = Runtime::init();

    let handle = Runtime::task(Sleep::sleep(Duration::from_millis(10)).mode(SleepMode::Relaxed))
        .priority(200)
        .repeat()
        .spawn();

    let first = handle.take_with_timeout(Duration::from_secs(5));

    // Retried, since a read between runs comes back `AlreadyTaken`
    // rather than waiting
    let deadline = Instant::now() + Duration::from_secs(5);
    let mut second = Err(RuntimeError::AlreadyTaken);

    while Instant::now() < deadline {
        second = handle.take_with_timeout(Duration::from_millis(100));

        if second.is_ok() {
            break;
        }
    }

    // Before the assertions, or a panic leaves it running
    handle.cancel();

    assert!(first.is_ok(), "the first run publishes: {first:?}");
    assert!(
        second.is_ok(),
        "a later read succeeds where a one shot would stay AlreadyTaken: {second:?}",
    );
}

/// A handle can be a map key, which is what hashing one is for
#[test]
fn handles_compare_and_hash_on_the_task() {
    use std::collections::HashSet;

    let _ = Runtime::init();

    let handle =
        Runtime::task(Sleep::sleep(Duration::from_millis(20)).mode(SleepMode::Relaxed)).spawn();
    let same = handle.clone();
    let other =
        Runtime::task(Sleep::sleep(Duration::from_millis(20)).mode(SleepMode::Relaxed)).spawn();

    assert_eq!(handle, same, "a clone points at the same task");
    assert_ne!(handle.id(), other.id(), "two spawns are two tasks");

    let mut seen = HashSet::new();

    assert!(seen.insert(handle.clone()));
    assert!(!seen.insert(same), "the same task doesn't go in twice");
    assert!(seen.insert(other.clone()));

    handle.join().expect("still finishes");
    other.join().expect("still finishes");
}

/// Every task in a set, in the order they were given
#[test]
fn join_all_keeps_the_order_it_was_given() {
    let _ = Runtime::init();

    let handles: Vec<_> = (1..=5)
        .map(|step| {
            Runtime::task(Sleep::sleep(Duration::from_millis(step * 10)).mode(SleepMode::Relaxed))
                .spawn()
        })
        .collect();

    let results = Runtime::join_all(handles);

    assert_eq!(results.len(), 5, "one result per task");

    // Given longest last, so ascending results are the order kept
    // rather than the order finished
    for (index, result) in results.into_iter().enumerate() {
        let slept = result.expect("every task finishes");
        let asked = Duration::from_millis((index as u64 + 1) * 10);

        assert!(
            slept >= asked,
            "result {index} slept {slept:?} against {asked:?}, so the order moved",
        );
    }
}

/// A healthy runtime says so
#[test]
fn status_reports_a_live_runtime() {
    let _ = Runtime::init();

    let status = Runtime::status();
    println!("{status}");

    assert!(Runtime::initialised(), "init has finished");
    assert!(status.initialised());
    assert!(!status.shut_down(), "nothing has shut this down");

    assert!(status.reactor_alive(), "the reactor is up");
    assert!(status.manager_alive(), "the manager is up");
    assert!(status.healthy());
}

/// A delayed task waits, then runs
#[test]
fn after_waits_before_it_runs() {
    let _ = Runtime::init();

    let delay = Duration::from_millis(200);
    let started = Instant::now();

    let handle = Runtime::task(Sleep::sleep(Duration::from_millis(10)).mode(SleepMode::Relaxed))
        .after(delay)
        .spawn();

    // Sitting on a timer rather than anywhere in the pool
    assert!(!handle.settled(), "nowhere near the delay being up");
    assert_eq!(
        handle.try_join(),
        Err(RuntimeError::NotReady),
        "a task waiting out a delay hasn't failed, it just hasn't started",
    );

    let state = handle.wait().expect("it runs once the delay is up");
    let waited = started.elapsed();

    println!("ran after {waited:?} of a {delay:?} delay");

    assert_eq!(state, TaskState::Ready, "it ran and published");
    assert!(
        waited >= delay,
        "started after only {waited:?}, which is early",
    );
}

/// Far more delayed tasks than the pool has threads all get
/// through, since a delay costs a slot and no thread
#[test]
fn many_delayed_tasks_cost_no_threads() {
    let _ = Runtime::init();

    let delay = Duration::from_millis(300);
    let started = Instant::now();

    let handles: Vec<_> = (0..2_000)
        .map(|_| {
            Runtime::task(Sleep::sleep(Duration::from_micros(50)).mode(SleepMode::Relaxed))
                .after(delay)
                .spawn()
        })
        .collect();

    for (task, handle) in handles.into_iter().enumerate() {
        handle
            .join()
            .unwrap_or_else(|error| panic!("delayed task {task} never ran: {error}"));
    }

    let total = started.elapsed();

    println!("2000 delayed tasks all ran, {total:?} against a {delay:?} delay");

    assert!(
        total >= delay,
        "they can't all have waited their delay in {total:?}",
    );
}

/// The builder reaches the same delay the method does
#[test]
fn builder_after_delays_too() {
    let _ = Runtime::init();

    let delay = Duration::from_millis(150);
    let started = Instant::now();

    let handle = Runtime::task(Sleep::sleep(Duration::from_millis(10)).mode(SleepMode::Relaxed))
        .priority(200)
        .after(delay)
        .spawn();

    handle.wait().expect("it runs once the delay is up");
    let waited = started.elapsed();

    println!("the built one ran after {waited:?} of a {delay:?} delay");

    assert!(waited >= delay, "started after only {waited:?}");

    // Still a one shot
    handle.take().expect("the output is there");
}

/// A delay and a repeat compose rather than replacing each other
#[test]
fn delay_and_repeat_compose() {
    let _ = Runtime::init();

    let delay = Duration::from_millis(200);
    let gap = Duration::from_millis(20);
    let started = Instant::now();

    let handle = Runtime::task(Sleep::sleep(Duration::from_millis(1)).mode(SleepMode::Relaxed))
        .after(delay)
        .repeat()
        .every(gap)
        .spawn();

    handle
        .wait()
        .expect("the first run happens once the delay is up");

    let first = started.elapsed();
    println!("first run after {first:?} of a {delay:?} delay");

    // Before the assertion, or a panic leaves it running
    handle.cancel();

    assert!(
        first >= delay,
        "the first run came after {first:?}, so the delay was lost when the kind was set",
    );
}

/// A deadline already past runs once and stops
#[test]
fn until_in_the_past_runs_once() {
    let _ = Runtime::init();

    let handle = Runtime::task(Sleep::sleep(Duration::from_millis(1)).mode(SleepMode::Relaxed))
        .repeat()
        .until(Instant::now())
        .spawn();

    let seen = drain(&handle, Duration::from_secs(5));

    println!("a deadline already past ran {seen} time(s)");

    assert!(handle.is_finished());
    assert_eq!(seen, 1, "the first run is never the one that is refused");
}

/// A schedule counts what it starts
#[test]
fn at_rate_starts_exactly_its_count() {
    let _ = Runtime::init();

    let runs = 4;

    let handle = Runtime::task(Sleep::sleep(Duration::from_millis(1)).mode(SleepMode::Relaxed))
        .at_rate(Duration::from_millis(40))
        .count(runs)
        .spawn();

    let seen = drain(&handle, Duration::from_secs(10));

    println!("a schedule bounded to {runs} published {seen} times");

    assert!(
        handle.is_finished(),
        "the schedule never reported finishing"
    );

    // Overlapping runs can publish one output between two, so
    // only an upper bound can be seen
    assert!(
        seen > 0 && seen as u32 <= runs,
        "saw {seen} outputs from {runs} runs",
    );
}

/// A schedule can be delayed too
#[test]
fn at_rate_waits_out_a_delay_before_its_first_run() {
    let _ = Runtime::init();

    let delay = Duration::from_millis(200);
    let started = Instant::now();

    let handle = Runtime::task(Sleep::sleep(Duration::from_millis(1)).mode(SleepMode::Relaxed))
        .at_rate(Duration::from_millis(30))
        .after(delay)
        .spawn();

    handle
        .wait()
        .expect("the first run happens once the delay is up");

    let first = started.elapsed();
    println!("the schedule's first run landed after {first:?} of a {delay:?} delay");

    handle.cancel();

    assert!(
        first >= delay,
        "the first run came after {first:?}, so the delay was never served",
    );
}

/// Cancelling a bounded series still ends it
#[test]
fn a_cancelled_bounded_repeat_is_finished() {
    let _ = Runtime::init();

    let handle = Runtime::task(Sleep::sleep(Duration::from_millis(10)).mode(SleepMode::Relaxed))
        .repeat()
        .every(Duration::from_millis(50))
        .count(1_000)
        .spawn();

    let watcher = handle.clone();
    handle.cancel();

    assert_eq!(
        watcher.clone().join(),
        Err(RuntimeError::Cancelled),
        "a cancelled series hands nothing out",
    );

    // The kind still says it repeats, which is why the state
    // alone can't answer this
    assert!(
        watcher.is_finished(),
        "a cancelled series is not going to run again",
    );

    watcher.cancel();
}

/// A repeat with no bound is not finished between runs
#[test]
fn an_unbounded_repeat_is_never_finished() {
    let _ = Runtime::init();

    // A long gap, so the read below lands between runs rather
    // than racing the next one
    let handle = Runtime::task(Sleep::sleep(Duration::from_millis(5)).mode(SleepMode::Relaxed))
        .repeat()
        .every(Duration::from_secs(60))
        .spawn();

    handle.wait().expect("a run publishes");

    let settled = handle.settled();
    let finished = handle.is_finished();

    handle.cancel();

    assert!(settled, "it published, so it has settled");
    assert!(
        !finished,
        "but there is another run coming, so it isn't over"
    );
}

/// A sleep until a moment ends no earlier than that moment
#[test]
fn sleeping_until_a_moment_waits_for_it() {
    let _ = Runtime::init();

    let when = Instant::now() + Duration::from_millis(80);

    let slept = Runtime::block(Sleep::until(when));
    assert!(Instant::now() >= when, "woke before the moment");
    assert!(slept >= Duration::from_millis(70), "slept only {slept:?}");

    let when = Instant::now() + Duration::from_millis(80);
    let handle = Runtime::task(Sleep::until(when).mode(SleepMode::Relaxed)).spawn();

    assert!(handle.join().is_ok());
    assert!(
        Instant::now() >= when,
        "a spawned sleep woke before the moment"
    );
}

/// A sleep until a moment already past returns at once
#[test]
fn sleeping_until_the_past_returns_at_once() {
    let _ = Runtime::init();

    let slept = Runtime::block(Sleep::until(Instant::now() - Duration::from_millis(5)));

    assert!(
        slept < Duration::from_secs(1),
        "slept {slept:?} for a moment already gone"
    );
}