runnerd 0.0.19

Runs ephemeral GitHub Actions runners in containers within a host budget
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
//! The notifier against a fake HTTP endpoint on loopback: a failure delivered once across a restart, a burst folded
//! into one message, a failing endpoint retried while the history goes on, a target added later replaying nothing,
//! an insight told once, the daily digest, ntfy's and Discord's JSON, and no URL or token in a log line.

use std::io::Write as _;
use std::sync::atomic::{AtomicU16, Ordering};
use std::sync::{Arc, Mutex as SyncMutex};
use std::time::Duration;

use axum::Router;
use axum::body::Bytes;
use axum::http::{HeaderMap, StatusCode, Uri};
use axum::routing::post;
use runnerd_core::api::{
    Digest, Event, Insight, InsightKind, JobMetrics, JobState, JobSummary, LogSummary, LongWait,
    Notification, NotifyEvent, Priority, Severity, Timeline,
};
use runnerd_core::config::{Config, DayTime};
use runnerd_core::store::Store;
use tokio::sync::{Mutex, Notify, watch};

use super::{
    ConfigText, Notifier, Setup, Timing, client, deliver, digest_due, digest_message, parse_offset,
    run, send_due, start, test_message,
};
use crate::testdir::Dir;

const SETUP: Setup = Setup {
    timing: Timing {
        gather: Duration::from_millis(100),
        gap: Duration::from_millis(100),
        retry: Duration::from_millis(50),
        retry_max: Duration::from_millis(100),
        check: Duration::from_secs(60),
        timeout: Duration::from_secs(2),
    },
    offset: || Some(0),
};

const CONFIG: &str = r#"
[host]
slice = "runnerd.slice"
isolation = "sysbox"

[caches]
mirror = { enabled = false, memory = "512M", cpus = 1, ttl = "168h" }
pnpm = { max_size = "5G" }
maven = { max_size = "5G" }

[profiles.app]
image_stage = "node"
cpus = 4
memory = "4G"
slots = 2

[[repositories]]
name = "halyard/api"
profile = "app"
labels = ["app"]
"#;

/// What the fake endpoint received: path and query, headers, body, and the status it answered.
type Received = Arc<SyncMutex<Vec<(String, HeaderMap, Vec<u8>, u16)>>>;

/// A loopback endpoint that records every post and answers `status`.
struct Endpoint {
    address: String,
    received: Received,
    status: Arc<AtomicU16>,
}

impl Endpoint {
    async fn start() -> Endpoint {
        let received: Received = Arc::default();
        let status = Arc::new(AtomicU16::new(200));
        let (kept, answer) = (received.clone(), status.clone());
        let app = Router::new().fallback(post(move |uri: Uri, headers: HeaderMap, body: Bytes| {
            let (kept, answer) = (kept.clone(), answer.clone());
            async move {
                let status = answer.load(Ordering::SeqCst);
                kept.lock()
                    .unwrap()
                    .push((uri.to_string(), headers, body.to_vec(), status));
                StatusCode::from_u16(status).unwrap()
            }
        }));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap().to_string();
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        Endpoint {
            address,
            received,
            status,
        }
    }

    fn count(&self) -> usize {
        self.received.lock().unwrap().len()
    }

    /// The webhook notifications received, in order.
    fn notifications(&self) -> Vec<Notification> {
        self.received
            .lock()
            .unwrap()
            .iter()
            .map(|(_, _, body, _)| serde_json::from_slice(body).unwrap())
            .collect()
    }

    /// Waits until it received `count` posts, then a little longer for any it should not get.
    async fn wait_for(&self, count: usize) {
        for _ in 0..200 {
            if self.count() >= count {
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        tokio::time::sleep(Duration::from_millis(300)).await;
    }
}

/// `CONFIG` with a webhook target `phone` at `url`.
fn webhook(url: &str) -> String {
    format!(
        "{CONFIG}\n[[notify.targets]]\nname = \"phone\"\nkind = \"webhook\"\nurl = \"{url}\"\n\
         headers = {{ Authorization = \"Bearer tk_hunter2\" }}\n"
    )
}

/// A finished job of `halyard/api`.
fn finished(id: u64, state: JobState, conclusion: Option<&str>) -> Event {
    Event::JobFinished {
        job: JobSummary {
            id,
            repository: "halyard/api".to_owned(),
            run_id: 7,
            run_attempt: 1,
            workflow: Some("CI".to_owned()),
            name: format!("test {id}"),
            branch: Some("main".to_owned()),
            url: Some(format!(
                "https://github.com/halyard/api/actions/runs/7/job/{id}"
            )),
            labels: vec!["app".to_owned()],
            state,
            conclusion: conclusion.map(str::to_owned),
            runner: None,
            timeline: Timeline::default(),
            metrics: JobMetrics::default(),
            log: LogSummary::default(),
        },
    }
}

fn failed(id: u64) -> Event {
    finished(id, JobState::Completed, Some("failure"))
}

/// A running notifier over `store`, reading the config from `config`.
struct Running {
    stop: watch::Sender<bool>,
    task: tokio::task::JoinHandle<()>,
    /// What a replaced config signals, as `PUT /v1/config` and auto sizing do.
    replaced: Arc<Notify>,
}

impl Running {
    async fn start(store: &Store, config: &Arc<Mutex<ConfigText>>) -> Running {
        let (stop, stopping) = watch::channel(false);
        let replaced = Arc::new(Notify::new());
        let task = tokio::spawn(run(Notifier {
            store: store.clone(),
            config: config.clone(),
            replaced: replaced.clone(),
            stopping,
            setup: SETUP,
        }));
        // Lets it read where each target got to before the test stores events.
        tokio::time::sleep(Duration::from_millis(100)).await;
        Running {
            stop,
            task,
            replaced,
        }
    }

    async fn stop(self) {
        self.stop.send(true).unwrap();
        self.task.await.unwrap();
    }
}

fn config_text(dir: &Dir, text: &str) -> Arc<Mutex<ConfigText>> {
    Arc::new(Mutex::new(ConfigText {
        path: dir.0.join("runnerd.toml"),
        text: text.to_owned(),
    }))
}

#[tokio::test]
async fn a_failure_is_delivered_once_across_a_restart() {
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let config = config_text(&dir, &webhook(&format!("http://{}/hook", endpoint.address)));

    let notifier = Running::start(&store, &config).await;
    store.event(finished(1, JobState::Completed, Some("success")));
    store.event(failed(2));
    endpoint.wait_for(1).await;
    notifier.stop().await;
    // Fails while the daemon is down.
    store.event(failed(3));
    store.flush().await;

    let notifier = Running::start(&store, &config).await;
    endpoint.wait_for(2).await;
    notifier.stop().await;

    let jobs: Vec<Vec<u64>> = endpoint
        .notifications()
        .iter()
        .map(|sent| sent.jobs.iter().map(|job| job.id).collect())
        .collect();
    assert_eq!(
        jobs,
        [vec![2], vec![3]],
        "job 2 once, and job 3, which failed while it was down, after the restart"
    );
    let first = &endpoint.notifications()[0];
    assert_eq!(first.event, NotifyEvent::Failed);
    assert_eq!(first.title, "halyard/api: CI / test 2 failed");
    assert_eq!(first.priority, Priority::High);
    let headers = &endpoint.received.lock().unwrap()[0].1;
    assert_eq!(headers["authorization"], "Bearer tk_hunter2");
}

#[tokio::test]
async fn a_burst_of_failures_is_one_message() {
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let config = config_text(&dir, &webhook(&format!("http://{}/hook", endpoint.address)));
    let notifier = Running::start(&store, &config).await;

    for id in 1..=30 {
        store.event(failed(id));
    }
    store.event(finished(31, JobState::Lost, None));
    endpoint.wait_for(1).await;
    notifier.stop().await;

    let sent = endpoint.notifications();
    assert_eq!(sent.len(), 1, "{sent:#?}");
    assert_eq!(sent[0].title, "30 jobs failed, 1 job lost");
    assert_eq!(
        sent[0].jobs.len(),
        21,
        "the first 20 failures and the lost job: a red main does not grow the body without end"
    );
    let lines: Vec<&str> = sent[0].message.lines().collect();
    assert_eq!(
        lines.len(),
        7,
        "five failures, how many more, the lost one: {lines:#?}"
    );
    assert_eq!(lines[5], "and 25 more");
}

/// A warning that `halyard/api`'s test is flaky.
fn flaky() -> Insight {
    Insight {
        key: "flaky:halyard/api/CI/test".to_owned(),
        severity: Severity::Warning,
        repository: "halyard/api".to_owned(),
        workflow: Some("CI".to_owned()),
        job: Some("test".to_owned()),
        sentence: "halyard/api: CI / test failed and then passed on a re-run in 2 of its 9 runs."
            .to_owned(),
        kind: InsightKind::Flaky { flaky: 2, total: 9 },
        runs: Vec::new(),
    }
}

#[tokio::test]
async fn an_insight_is_told_once_and_again_only_after_it_went_away_for_a_day() {
    const MINUTE: u64 = 60_000;
    const HOUR: u64 = 60 * MINUTE;
    let timing = Timing {
        gather: Duration::ZERO,
        gap: Duration::ZERO,
        ..SETUP.timing
    };
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let config = Config::parse(&webhook(&format!("http://{}/hook", endpoint.address))).unwrap();
    let phone = &config.notify.targets[0];
    let http = client(timing.timeout).unwrap();
    let mut target = start(&store, None, phone, &config).await.unwrap();
    let t0 = 1_800_000_000_000;
    let looks = async |target: &mut super::Target, held: Vec<Insight>, at: u64| {
        target.look(&held, at);
        send_due(&store, &http, &timing, target).await;
    };

    looks(&mut target, vec![flaky()], t0).await;
    for minutes in [5, 10, 15] {
        looks(&mut target, vec![flaky()], t0 + minutes * MINUTE).await;
    }
    assert_eq!(endpoint.count(), 1, "held across several looks: told once");

    // A restart remembers it was told.
    let kept = store.notify_state().await.unwrap().remove("phone");
    let mut target = start(&store, kept, phone, &config).await.unwrap();
    looks(&mut target, vec![flaky()], t0 + 20 * MINUTE).await;
    // Gone for less than a day and back: not again.
    looks(&mut target, Vec::new(), t0 + HOUR).await;
    looks(&mut target, vec![flaky()], t0 + 12 * HOUR).await;
    // Held for more than a day since it was told: still not again.
    looks(&mut target, vec![flaky()], t0 + 30 * HOUR).await;
    assert_eq!(
        endpoint.count(),
        1,
        "told once across a restart, a short gap and a long hold"
    );

    // Gone for more than a day and back: told again.
    looks(&mut target, Vec::new(), t0 + 31 * HOUR).await;
    looks(&mut target, Vec::new(), t0 + 56 * HOUR).await;
    looks(&mut target, vec![flaky()], t0 + 57 * HOUR).await;
    let sent = endpoint.notifications();
    assert_eq!(sent.len(), 2, "{sent:#?}");
    assert_eq!(sent[1].event, NotifyEvent::Insights);
    assert_eq!(sent[1].title, "halyard/api: CI / test is flaky");
}

#[tokio::test]
async fn a_digest_delivered_after_midnight_counts_for_the_day_it_was_made() {
    const HOUR: u64 = 3600;
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let text = webhook(&format!("http://{}/hook", endpoint.address));
    let config = Config::parse(&text).unwrap();
    let http = client(SETUP.timing.timeout).unwrap();
    let mut target = start(&store, None, &config.notify.targets[0], &config)
        .await
        .unwrap();
    let today = super::now();
    let midnight = today - today % (24 * HOUR);
    let late = DayTime {
        minutes: 23 * 60 + 50,
    };
    // Made at 23:50 UTC yesterday; the endpoint answers only today.
    target.digest = Some(runnerd_core::insights::digest(
        &[],
        &config,
        (midnight - 10 * 60) * 1000,
    ));
    send_due(&store, &http, &SETUP.timing, &mut target).await;

    assert_eq!(endpoint.count(), 1);
    let last = store.notify_state().await.unwrap()["phone"]["digest"] / 1000;
    assert!(
        digest_due(midnight + 23 * HOUR + 50 * 60, 0, late, last),
        "today's digest still goes at 23:50"
    );
}

#[tokio::test]
async fn the_digest_goes_once_at_its_time_across_a_restart() {
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    // It last went long ago, and is due from midnight.
    assert!(
        store
            .notify_record(
                "phone",
                vec![("event".to_owned(), 0), ("digest".to_owned(), 0)],
                Vec::new()
            )
            .await,
        "recorded"
    );
    let text = format!(
        "{CONFIG}\n[notify]\ndigest_at = \"00:00\"\n\n[[notify.targets]]\nname = \"phone\"\n\
         kind = \"webhook\"\nurl = \"http://{}/hook\"\nevents = [\"digest\"]\n",
        endpoint.address
    );
    let config = config_text(&dir, &text);
    let notifier = Running::start(&store, &config).await;
    store.event(failed(1));
    endpoint.wait_for(1).await;
    notifier.stop().await;
    let notifier = Running::start(&store, &config).await;
    endpoint.wait_for(2).await;
    notifier.stop().await;

    let sent = endpoint.notifications();
    assert_eq!(
        sent.len(),
        1,
        "once a day, not again after a restart: {sent:#?}"
    );
    assert_eq!(sent[0].event, NotifyEvent::Digest);
    assert_eq!(sent[0].title, "CI in the last 24 hours");
    assert_eq!(sent[0].priority, Priority::Low);
    assert!(sent[0].jobs.is_empty(), "failed is not among its events");
    assert!(
        sent[0].digest.is_some(),
        "the digest's figures come with it"
    );
}

#[tokio::test]
async fn a_failing_endpoint_is_retried_without_holding_back_the_history() {
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    endpoint.status.store(502, Ordering::SeqCst);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let config = config_text(&dir, &webhook(&format!("http://{}/hook", endpoint.address)));
    let notifier = Running::start(&store, &config).await;

    store.event(failed(1));
    endpoint.wait_for(2).await;
    // The history takes writes as before while the target refuses.
    store.event(failed(2));
    tokio::time::timeout(Duration::from_secs(1), store.flush())
        .await
        .expect("the store is not held back");
    endpoint.status.store(200, Ordering::SeqCst);
    endpoint.wait_for(endpoint.count() + 1).await;
    notifier.stop().await;

    let received = endpoint.received.lock().unwrap().clone();
    let refused = received.iter().filter(|post| post.3 == 502).count();
    assert!(refused >= 2, "retried: {refused} posts refused");
    let delivered: Vec<Notification> = received
        .iter()
        .filter(|post| post.3 == 200)
        .map(|post| serde_json::from_slice(&post.2).unwrap())
        .collect();
    assert_eq!(delivered.len(), 1, "delivered once, then nothing");
    assert_eq!(
        delivered[0]
            .jobs
            .iter()
            .map(|job| job.id)
            .collect::<Vec<_>>(),
        [1, 2],
        "the job that came while it was refused is folded in"
    );
}

#[tokio::test]
async fn nothing_is_sent_without_notify_and_a_target_added_later_replays_nothing() {
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let config = config_text(&dir, CONFIG);
    let notifier = Running::start(&store, &config).await;

    store.event(failed(1));
    store.flush().await;
    tokio::time::sleep(Duration::from_millis(200)).await;
    assert!(
        store.notify_state().await.unwrap().is_empty(),
        "without [notify] the notifier keeps nothing"
    );

    config.lock().await.text = webhook(&format!("http://{}/hook", endpoint.address));
    // Any durable event wakes it, and it reads the config again.
    store.event(finished(2, JobState::Completed, Some("success")));
    tokio::time::sleep(Duration::from_millis(300)).await;
    store.event(failed(3));
    endpoint.wait_for(1).await;
    notifier.stop().await;

    let jobs: Vec<Vec<u64>> = endpoint
        .notifications()
        .iter()
        .map(|sent| sent.jobs.iter().map(|job| job.id).collect())
        .collect();
    assert_eq!(jobs, [vec![3]], "job 1 failed before the target existed");
}

#[tokio::test]
async fn an_ntfy_target_gets_ntfys_json_at_the_server_with_its_topic() {
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let text = format!(
        "{CONFIG}\n[[notify.targets]]\nname = \"phone\"\nkind = \"ntfy\"\n\
         url = \"http://{}/halyard-ci-6f3a\"\nevents = [\"lost\"]\n",
        endpoint.address
    );
    let config = config_text(&dir, &text);
    let notifier = Running::start(&store, &config).await;

    store.event(failed(1));
    store.event(finished(2, JobState::Lost, None));
    endpoint.wait_for(1).await;
    notifier.stop().await;

    let received = endpoint.received.lock().unwrap().clone();
    assert_eq!(
        received.len(),
        1,
        "only the lost job: failed is not among its events"
    );
    let (path, _, body, _) = &received[0];
    assert_eq!(path, "/");
    let body: serde_json::Value = serde_json::from_slice(body).unwrap();
    assert_eq!(body["topic"], "halyard-ci-6f3a");
    assert_eq!(body["title"], "halyard/api: CI / test 2 lost its runner");
    assert_eq!(body["priority"], 3);
    assert_eq!(
        body["click"],
        "https://github.com/halyard/api/actions/runs/7/job/2"
    );
}

/// `CONFIG` with a Discord target `chat` at `url`.
fn discord(url: &str) -> String {
    format!("{CONFIG}\n[[notify.targets]]\nname = \"chat\"\nkind = \"discord\"\nurl = \"{url}\"\n")
}

#[tokio::test]
async fn a_discord_target_gets_one_red_embed_for_a_burst_of_failures_that_pings_no_one() {
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    endpoint.status.store(204, Ordering::SeqCst);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let config = config_text(
        &dir,
        &discord(&format!("http://{}/api/webhooks/123/abc", endpoint.address)),
    );
    let notifier = Running::start(&store, &config).await;

    for id in 1..=7 {
        store.event(failed(id));
    }
    endpoint.wait_for(1).await;
    notifier.stop().await;

    let received = endpoint.received.lock().unwrap().clone();
    assert_eq!(received.len(), 1, "one message, delivered on Discord's 204");
    let (path, _, body, _) = &received[0];
    assert_eq!(path, "/api/webhooks/123/abc");
    let body: serde_json::Value = serde_json::from_slice(body).unwrap();
    assert_eq!(body["allowed_mentions"], serde_json::json!({ "parse": [] }));
    let embeds = body["embeds"].as_array().unwrap();
    assert_eq!(embeds.len(), 1, "{body:#}");
    assert_eq!(embeds[0]["title"], "7 jobs failed");
    assert_eq!(embeds[0]["color"], 0x00ED_4245, "failures are red");
    assert_eq!(
        embeds[0]["url"],
        "https://github.com/halyard/api/actions/runs/7/job/1"
    );
    let description = embeds[0]["description"].as_str().unwrap();
    assert_eq!(
        description.lines().collect::<Vec<_>>(),
        [
            "halyard/api: CI / test 1 failed on main",
            "halyard/api: CI / test 2 failed on main",
            "halyard/api: CI / test 3 failed on main",
            "halyard/api: CI / test 4 failed on main",
            "halyard/api: CI / test 5 failed on main",
            "and 2 more",
        ]
    );
}

#[tokio::test]
async fn a_long_message_is_cut_to_discords_limits_and_a_429_is_not_delivered() {
    let endpoint = Endpoint::start().await;
    let config = Config::parse(&discord(&format!(
        "http://{}/api/webhooks/123/abc",
        endpoint.address
    )))
    .unwrap();
    let target = &config.notify.targets[0];
    let http = client(SETUP.timing.timeout).unwrap();
    let long = Notification {
        title: "é".repeat(300),
        message: "halyard/api: CI / test failed on main\n".repeat(200),
        ..test_message("chat")
    };

    assert_eq!(deliver(&http, target, &long).await, Ok(()));
    endpoint.status.store(429, Ordering::SeqCst);
    assert_eq!(
        deliver(&http, target, &long).await,
        Err("the target answered HTTP 429 Too Many Requests".to_owned()),
        "rate limited is a failed send, retried like any other"
    );

    let body: serde_json::Value =
        serde_json::from_slice(&endpoint.received.lock().unwrap()[0].2).unwrap();
    let embed = &body["embeds"][0];
    let title = embed["title"].as_str().unwrap();
    let description = embed["description"].as_str().unwrap();
    assert_eq!(title.chars().count(), 256);
    assert_eq!(description.chars().count(), 4096);
    assert!(
        title.ends_with('…') && description.ends_with('…'),
        "both say they were cut"
    );
    assert!(title.chars().count() + description.chars().count() <= 6000);
    assert_eq!(body["allowed_mentions"], serde_json::json!({ "parse": [] }));
}

#[tokio::test]
async fn a_discord_test_message_is_a_green_embed() {
    let endpoint = Endpoint::start().await;
    let config = Config::parse(&discord(&format!(
        "http://{}/api/webhooks/123/abc",
        endpoint.address
    )))
    .unwrap();
    let (target, http) = (
        &config.notify.targets[0],
        client(SETUP.timing.timeout).unwrap(),
    );

    deliver(&http, target, &test_message("chat")).await.unwrap();

    let body: serde_json::Value =
        serde_json::from_slice(&endpoint.received.lock().unwrap()[0].2).unwrap();
    assert_eq!(
        body,
        serde_json::json!({
            "embeds": [{
                "title": "runnerd can reach you",
                "description": "A test from runnerd: notify target \"chat\" works.",
                "color": 0x0057_F287,
            }],
            "allowed_mentions": { "parse": [] },
        })
    );
}

/// Log lines written while it is set as the thread's subscriber.
#[derive(Clone, Default)]
struct Captured(Arc<SyncMutex<Vec<u8>>>);

impl std::io::Write for Captured {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.0.lock().unwrap().extend_from_slice(bytes);
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[tokio::test]
async fn no_log_line_shows_a_targets_url_or_token() {
    let captured = Captured::default();
    let writer = captured.clone();
    let subscriber = tracing_subscriber::fmt()
        .with_writer(move || writer.clone())
        .with_ansi(false)
        .finish();
    // With one subscriber registered, tracing asks only the calling thread's whether a log line is wanted, so a line
    // another test's thread reaches first would be cached as unwanted here too. With two, it asks both.
    let _second = tracing::Dispatch::new(
        tracing_subscriber::fmt()
            .with_writer(std::io::sink)
            .finish(),
    );
    let _guard = tracing::subscriber::set_default(subscriber);
    tracing::callsite::rebuild_interest_cache();

    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    endpoint.status.store(401, Ordering::SeqCst);
    // A closed port too: a connection error must not quote the URL either.
    let closed = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let closed_address = closed.local_addr().unwrap().to_string();
    drop(closed);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let text = format!(
        "{}\n[[notify.targets]]\nname = \"desk\"\nkind = \"ntfy\"\nurl = \"http://{closed_address}/s3cret-topic\"\n",
        webhook(&format!("http://{}/hook?key=s3cret", endpoint.address))
    );
    let config = config_text(&dir, &text);
    let notifier = Running::start(&store, &config).await;
    store.event(failed(1));
    endpoint.wait_for(2).await;
    notifier.stop().await;
    let _ = captured.clone().flush();

    let logs = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
    assert!(
        logs.contains("notify phone: not delivered: the target answered HTTP 401 Unauthorized"),
        "{logs}"
    );
    assert!(
        logs.contains("notify desk: not delivered: cannot connect to the target"),
        "{logs}"
    );
    for secret in [
        "s3cret",
        "hunter2",
        endpoint.address.as_str(),
        closed_address.as_str(),
        "/hook",
    ] {
        assert!(!logs.contains(secret), "a log line shows {secret}");
    }
}

#[test]
fn the_digest_goes_once_a_day_after_its_local_time() {
    const HOUR: u64 = 3600;
    let midnight = 1_799_971_200 - 1_799_971_200 % (24 * HOUR);
    let nine = DayTime { minutes: 9 * 60 };
    let paris = parse_offset("+0100").unwrap();
    assert_eq!(paris, 3600);
    assert_eq!(parse_offset("-0530"), Some(-(5 * 3600 + 30 * 60)));

    // 08:30 in Paris is 07:30 UTC: not yet.
    assert!(!digest_due(midnight + 7 * HOUR + 1800, paris, nine, 0));
    // 09:00 in Paris, last sent yesterday: due.
    assert!(digest_due(
        midnight + 8 * HOUR,
        paris,
        nine,
        midnight - 15 * HOUR
    ));
    // Sent at 09:00; at 15:00 it is not due again.
    assert!(!digest_due(
        midnight + 14 * HOUR,
        paris,
        nine,
        midnight + 8 * HOUR
    ));
    // Sent at 09:00, then moved to 16:00: not a second today.
    assert!(!digest_due(
        midnight + 15 * HOUR,
        paris,
        DayTime { minutes: 16 * 60 },
        midnight + 8 * HOUR
    ));
}

#[tokio::test]
async fn a_target_that_redirects_is_not_counted_as_delivered() {
    // A proxy in front of ntfy that sends http to https: a POST followed there would arrive as a GET without its
    // body, which the server's web page answers with 200.
    let (dir, received) = (Dir::new(), Received::default());
    let (posts, gets) = (received.clone(), received.clone());
    let app = Router::new()
        .route(
            "/hook",
            post(move || {
                let posts = posts.clone();
                async move {
                    posts.lock().unwrap().push((
                        "/hook".to_owned(),
                        HeaderMap::new(),
                        Vec::new(),
                        301,
                    ));
                    (StatusCode::MOVED_PERMANENTLY, [("location", "/moved")])
                }
            }),
        )
        .route(
            "/moved",
            axum::routing::get(move || {
                let gets = gets.clone();
                async move {
                    gets.lock().unwrap().push((
                        "/moved".to_owned(),
                        HeaderMap::new(),
                        Vec::new(),
                        200,
                    ));
                    StatusCode::OK
                }
            }),
        );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap().to_string();
    tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let config = config_text(&dir, &webhook(&format!("http://{address}/hook")));
    let notifier = Running::start(&store, &config).await;

    store.event(failed(1));
    for _ in 0..200 {
        if received.lock().unwrap().len() >= 2 {
            break;
        }
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    notifier.stop().await;

    let paths: Vec<String> = received
        .lock()
        .unwrap()
        .iter()
        .map(|post| post.0.clone())
        .collect();
    assert!(
        paths.len() >= 2 && paths.iter().all(|path| path == "/hook"),
        "the failure is posted again, never followed to a GET: {paths:?}"
    );
}

#[tokio::test]
async fn an_insight_told_before_a_long_downtime_is_not_told_again_while_it_holds() {
    const HOUR: u64 = 3_600_000;
    let timing = Timing {
        gather: Duration::ZERO,
        gap: Duration::ZERO,
        ..SETUP.timing
    };
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let config = Config::parse(&webhook(&format!("http://{}/hook", endpoint.address))).unwrap();
    let phone = &config.notify.targets[0];
    let http = client(timing.timeout).unwrap();
    let mut target = start(&store, None, phone, &config).await.unwrap();
    let t0 = 1_800_000_000_000;
    target.look(&[flaky()], t0);
    send_due(&store, &http, &timing, &mut target).await;
    assert_eq!(endpoint.count(), 1, "told once");

    // The host is off for a weekend; the job is still flaky when the daemon starts again.
    let kept = store.notify_state().await.unwrap().remove("phone");
    let mut target = start(&store, kept, phone, &config).await.unwrap();
    target.look(&[flaky()], t0 + 60 * HOUR);
    send_due(&store, &http, &timing, &mut target).await;
    assert_eq!(
        endpoint.count(),
        1,
        "a daemon that was off did not see it go away"
    );
}

#[tokio::test]
async fn a_target_added_by_a_reload_gets_the_first_failure_after_it() {
    let (dir, endpoint) = (Dir::new(), Endpoint::start().await);
    let store = Store::open(&dir.0.join("runnerd.db")).unwrap();
    let config = config_text(&dir, CONFIG);
    let notifier = Running::start(&store, &config).await;

    // A phone added while a job runs; that job's failure is the next event.
    config.lock().await.text = webhook(&format!("http://{}/hook", endpoint.address));
    notifier.replaced.notify_one();
    tokio::time::sleep(Duration::from_millis(200)).await;
    store.event(failed(1));
    endpoint.wait_for(1).await;
    notifier.stop().await;

    let jobs: Vec<Vec<u64>> = endpoint
        .notifications()
        .iter()
        .map(|sent| sent.jobs.iter().map(|job| job.id).collect())
        .collect();
    assert_eq!(jobs, [vec![1]], "the failure after the reload is sent");
}

#[test]
fn a_digests_longest_wait_of_a_job_without_a_name_names_it_by_its_id() {
    let message = digest_message(Digest {
        since: 0,
        until: 86_400,
        finished: 1,
        failed: 0,
        new: Vec::new(),
        waits: vec![LongWait {
            job: 7,
            repository: "halyard/ledger".to_owned(),
            workflow: None,
            name: String::new(),
            waited: 60,
            url: None,
        }],
        savings: None,
    })
    .message;
    assert!(
        message.contains("halyard/ledger job 7 waited"),
        "as runnerctl's digest names it: {message}"
    );
}