runnerd-cli 0.0.7

Command-line client for the runnerd daemon
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
//! `runnerctl` against a fake daemon on a temporary Unix socket: what it prints, what it asks the daemon, and how
//! it reports a daemon that is not there or refuses.

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    reason = "tests fail by panicking"
)]

use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use axum::Router;
use axum::extract::{Path as UrlPath, RawQuery, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
use runnerd_core::api::{
    Advice, Budget, Busy, Check, CheckStatus, ConfigCheck, ConfigFile, Doctor, ErrorResponse,
    Event, EventEnvelope, Job, JobMetrics, JobRunner, JobSizing, JobState, JobSummary, LogSummary,
    Paused, Peaks, ProfileSizing, ProfileStatus, QueuedJob, Record, RecordLimits, Records,
    RemovedRecords, RepositoryStatus, RunnerStatus, RunningJob, Sizing, SlotStatus, Spread, Status,
    Timeline,
};

/// A fresh directory under the system temp dir, removed on drop.
struct TempDir(PathBuf);

impl TempDir {
    fn new() -> TempDir {
        static NEXT: AtomicU32 = AtomicU32::new(0);
        let path = std::env::temp_dir().join(format!(
            "runnerctl-test-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = std::fs::remove_dir_all(&path);
        std::fs::create_dir_all(&path).unwrap();
        TempDir(path)
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn status() -> Status {
    Status {
        version: "0.0.1".to_owned(),
        shutting_down: false,
        budget: Budget {
            admission: runnerd_core::api::AdmissionPolicy::Caps,
            held: false,
            slice: "runnerd.slice".to_owned(),
            memory_max: Some(16 << 30),
            memory_in_use: 6 << 30,
            mirror_memory: 0,
            seed_memory: Vec::new(),
            shell_memory: Vec::new(),
        },
        profiles: vec![ProfileStatus {
            name: "jvm".to_owned(),
            image: "runnerd-runner:jvm".to_owned(),
            cpus: 4,
            memory: 6 << 30,
            reseeding: false,
            slots: vec![
                SlotStatus {
                    slot: 1,
                    runner: Some(RunnerStatus {
                        repository: "halyard/ledger".to_owned(),
                        name: "runnerd-5f2a-jvm-1-k3j9".to_owned(),
                        runner_id: 81,
                        container: "4e1d".to_owned(),
                        busy: true,
                        started_at: 1_700_000_000,
                        reserved: 9 << 30,
                    }),
                },
                SlotStatus {
                    slot: 2,
                    runner: None,
                },
            ],
        }],
        repositories: vec![RepositoryStatus {
            name: "halyard/ledger".to_owned(),
            profile: "jvm".to_owned(),
            labels: vec!["self-hosted".to_owned(), "jvm".to_owned()],
            paused: false,
            queued_jobs: 1,
        }],
        queued: vec![QueuedJob {
            id: 9002,
            repository: "halyard/ledger".to_owned(),
            run_id: 78,
            run_attempt: 1,
            workflow: Some("build".to_owned()),
            name: "lint".to_owned(),
            branch: Some("main".to_owned()),
            url: None,
            queued_at: 1_000_000,
        }],
    }
}

fn job(state: JobState) -> Job {
    Job {
        admission: None,
        summary: JobSummary {
            id: 9001,
            repository: "halyard/ledger".to_owned(),
            run_id: 77,
            run_attempt: 1,
            workflow: Some("build".to_owned()),
            name: "test".to_owned(),
            branch: Some("main".to_owned()),
            url: None,
            labels: vec!["self-hosted".to_owned()],
            state,
            conclusion: state.is_final().then(|| "success".to_owned()),
            runner: Some(JobRunner {
                name: "runnerd-5f2a-jvm-1-k3j9".to_owned(),
                profile: "jvm".to_owned(),
                slot: 1,
                memory_cap: Some(6 << 30),
                cpu_cap: Some(4000),
            }),
            timeline: Timeline {
                queued_at: 1_700_000_000,
                started_at: Some(1_700_000_004),
                ..Timeline::default()
            },
            metrics: JobMetrics::default(),
            log: LogSummary::default(),
        },
        steps: Vec::new(),
        record: None,
    }
}

/// What the fake daemon was asked, and what it answers next.
#[derive(Default)]
struct Fake {
    /// The query string of every log request.
    log_queries: Vec<String>,
    /// The `Last-Event-ID` of every event stream request.
    event_ids: Vec<Option<String>>,
    /// Every request but log and status reads, in order, as `METHOD path`.
    requests: Vec<String>,
    /// The body of every config check.
    checked: Vec<String>,
    /// The body of every config replacement.
    replaced: Vec<String>,
}

type Shared = Arc<Mutex<Fake>>;

async fn get_status() -> axum::Json<Status> {
    axum::Json(status())
}

async fn get_job(State(fake): State<Shared>) -> axum::Json<Job> {
    // Final once the client asked for the log twice: the first followed response ended early, as on a restart.
    let final_now = fake.lock().unwrap().log_queries.len() >= 2;
    axum::Json(job(if final_now {
        JobState::Completed
    } else {
        JobState::Running
    }))
}

async fn get_logs(State(fake): State<Shared>, RawQuery(query): RawQuery) -> String {
    let mut fake = fake.lock().unwrap();
    fake.log_queries.push(query.unwrap_or_default());
    if fake.log_queries.len() == 1 {
        "Run ./gradlew test\nBUILD SUCCESSFUL\n".to_owned()
    } else {
        "Cleaning up\n".to_owned()
    }
}

/// `halyard/ledger` runs a job: a pause without force is refused, a forced one stops it. `halyard/wharf`'s pause
/// holds, but the daemon's history cannot record it.
async fn pause(
    UrlPath((owner, name)): UrlPath<(String, String)>,
    RawQuery(query): RawQuery,
) -> Response {
    paused(&format!("{owner}/{name}"), query.as_deref())
}

/// A pause of every repository: `halyard/ledger`'s job is in the way, as for its own pause.
async fn pause_all(RawQuery(query): RawQuery) -> Response {
    paused("halyard/ledger", query.as_deref())
}

fn paused(repository: &str, query: Option<&str>) -> Response {
    let running = RunningJob {
        repository: repository.to_owned(),
        runner: "runnerd-5f2a-jvm-1-k3j9".to_owned(),
        job: Some(9001),
    };
    match (repository, query) {
        ("halyard/ledger", Some("force=true")) => axum::Json(Paused {
            stopped: vec![running],
        })
        .into_response(),
        ("halyard/wharf", _) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            axum::Json(ErrorResponse {
                message: "halyard/wharf is paused until runnerd restarts, but the job history cannot record it, \
                          so a restart resumes it"
                    .to_owned(),
            }),
        )
            .into_response(),
        ("halyard/ledger", _) => (
            StatusCode::CONFLICT,
            axum::Json(Busy {
                message: format!("{repository} runs {running}"),
                jobs: vec![running],
            }),
        )
            .into_response(),
        _ => (
            StatusCode::NOT_FOUND,
            axum::Json(ErrorResponse {
                message: format!("{repository} is not a configured repository"),
            }),
        )
            .into_response(),
    }
}

async fn reseed(State(fake): State<Shared>, UrlPath(profile): UrlPath<String>) -> StatusCode {
    fake.lock()
        .unwrap()
        .requests
        .push(format!("POST /v1/profiles/{profile}/reseed"));
    StatusCode::ACCEPTED
}

async fn check_config(State(fake): State<Shared>, body: String) -> axum::Json<ConfigCheck> {
    fake.lock().unwrap().checked.push(body);
    axum::Json(ConfigCheck {
        valid: false,
        message: "memory caps sum to 20G, more than runnerd.slice's MemoryMax of 16G".to_owned(),
        warnings: Vec::new(),
        memory_caps: Some(20 << 30),
        memory_max: Some(16 << 30),
    })
}

/// The daemon's config: `node` 2 × 7G, with a comment that must survive an edit.
const CONFIG: &str = "[profiles.node]\nimage_stage = \"node\"\ncpus = 8\nmemory = \"7G\" # peaked at 6G once\nslots = 2\n";

async fn get_config() -> axum::Json<ConfigFile> {
    axum::Json(ConfigFile {
        path: "/home/u/.config/runnerd/runnerd.toml".to_owned(),
        text: CONFIG.to_owned(),
    })
}

async fn replace_config(State(fake): State<Shared>, body: String) -> axum::Json<ConfigCheck> {
    fake.lock().unwrap().replaced.push(body);
    axum::Json(ConfigCheck {
        valid: true,
        message: "valid, memory caps sum to 13G".to_owned(),
        warnings: Vec::new(),
        memory_caps: Some(13 << 30),
        memory_max: Some(16 << 30),
    })
}

/// `node`'s 100 builds peak at 2.1G: 2.5G with the margin, 5 of them in the 14G its 2 slots take.
async fn get_sizing() -> axum::Json<Sizing> {
    let spread = |p50, p95, p99, max| Spread { p50, p95, p99, max };
    let peaks = Peaks {
        jobs: 100,
        at_cap: 0,
        memory: spread(1500 << 20, 2 << 30, 2150 << 20, 2200 << 20),
        cpu: spread(3000, 6000, 7500, 8000),
    };
    let advice = Advice::Lower {
        memory: 2560 << 20,
        slots: 5,
    };
    axum::Json(Sizing {
        since: 1_700_000_000,
        until: 1_700_086_400,
        margin: 15,
        sample_interval: 2,
        min_jobs: 10,
        memory_max: Some(16 << 30),
        profiles: vec![ProfileSizing {
            name: "node".to_owned(),
            memory: 7 << 30,
            cpus: 8,
            slots: 2,
            peaks: peaks.clone(),
            wait: spread(30, 240, 300, 320),
            busy: 80,
            advice,
            jobs: vec![JobSizing {
                repository: "halyard/storefront".to_owned(),
                workflow: Some("CI".to_owned()),
                name: "build".to_owned(),
                peaks,
                wait: spread(30, 240, 300, 320),
                advice,
            }],
        }],
    })
}

async fn get_doctor() -> axum::Json<Doctor> {
    axum::Json(Doctor {
        checks: vec![
            Check {
                name: "Docker".to_owned(),
                status: CheckStatus::Pass,
                detail: "29.1.0".to_owned(),
                fix: None,
            },
            Check {
                name: "sysbox".to_owned(),
                status: CheckStatus::Fail,
                detail: "sysbox-runc is not a Docker runtime".to_owned(),
                fix: Some("install sysbox".to_owned()),
            },
        ],
    })
}

fn sse(envelope: &EventEnvelope) -> String {
    let id = envelope
        .id
        .map(|id| format!("id: {id}\n"))
        .unwrap_or_default();
    format!(
        "event: {}\n{id}data: {}\n\n",
        envelope.event.kind(),
        serde_json::to_string(envelope).unwrap()
    )
}

async fn events(State(fake): State<Shared>, headers: HeaderMap) -> Response {
    let mut fake = fake.lock().unwrap();
    fake.requests.push("GET /v1/events".to_owned());
    fake.event_ids.push(
        headers
            .get("last-event-id")
            .map(|value| value.to_str().unwrap().to_owned()),
    );
    // The first stream sends two events and ends, as for a client that fell behind; later ones end at once.
    let body = if fake.event_ids.len() == 1 {
        let mut summary = job(JobState::Running).summary;
        summary.state = JobState::Running;
        format!(
            ": keep-alive\n\n{}{}{}{}",
            sse(&EventEnvelope {
                id: Some(41),
                at: 1_700_000_004,
                event: Event::JobStarted { job: summary },
            }),
            sse(&EventEnvelope {
                id: None,
                at: 1_700_000_006,
                event: Event::LogLine {
                    job: 9001,
                    line: 0,
                    text: "live only".to_owned()
                },
            }),
            sse(&EventEnvelope {
                id: Some(42),
                at: 1_700_000_007,
                event: Event::CacheReseeded {
                    profile: "node".to_owned(),
                    output: "node: slot 1 changed 3.0G".to_owned(),
                    error: None,
                },
            }),
            sse(&EventEnvelope {
                id: Some(43),
                at: 1_700_000_008,
                event: Event::CacheReseeded {
                    profile: "jvm".to_owned(),
                    output: "jvm: slot 1 changed 2.1G".to_owned(),
                    error: None,
                },
            }),
        )
    } else {
        String::new()
    };
    ([(header::CONTENT_TYPE, "text/event-stream")], body).into_response()
}

/// Serves the fake daemon on `socket` until the test process ends.
fn serve(socket: &Path) -> Shared {
    let fake = Shared::default();
    let app = Router::new()
        .route("/v1/status", get(get_status))
        .route("/v1/jobs/{id}", get(get_job))
        .route("/v1/jobs/{id}/logs", get(get_logs))
        .route("/v1/repositories/{owner}/{name}/pause", post(pause))
        .route("/v1/repositories/pause", post(pause_all))
        .route(
            "/v1/repositories/resume",
            post(async || StatusCode::NO_CONTENT),
        )
        .route("/v1/profiles/{name}/reseed", post(reseed))
        .route("/v1/config/check", post(check_config))
        .route("/v1/config", get(get_config).put(replace_config))
        .route("/v1/sizing", get(get_sizing))
        .route("/v1/doctor", get(get_doctor))
        .route("/v1/events", get(events))
        .route("/v1/records", get(get_records))
        .route("/v1/records", delete(remove_records))
        .route("/v1/records/{job}", delete(remove_record))
        .route(
            "/v1/records/{job}/shell",
            post(async || {
                refuse(
                    StatusCode::CONFLICT,
                    "the budget is full: 8G of the slice's 8G is held",
                )
            }),
        )
        .with_state(fake.clone());
    let runtime = tokio::runtime::Runtime::new().unwrap();
    let listener = runtime
        .block_on(async { tokio::net::UnixListener::bind(socket) })
        .unwrap();
    std::thread::spawn(move || {
        runtime.block_on(async { axum::serve(listener, app).await.unwrap() });
    });
    fake
}

fn refuse(status: StatusCode, message: &str) -> Response {
    (
        status,
        axum::Json(ErrorResponse {
            message: message.to_owned(),
        }),
    )
        .into_response()
}

async fn get_records() -> axum::Json<Records> {
    let record = |job: u64, gib: u64| Record {
        job,
        repository: "halyard/ledger".to_owned(),
        profile: "app".to_owned(),
        workflow: Some("build".to_owned()),
        name: Some("test".to_owned()),
        created_at: 1_792_000_000,
        bytes: gib << 30,
        image: format!("runnerd-record:{job}"),
    };
    axum::Json(Records {
        records: vec![record(9001, 1), record(9002, 3)],
        limits: RecordLimits {
            max_total: 20 << 30,
            max_count: 10,
            max_age: 7 * 86_400,
            min_free: 10 << 30,
        },
        shells: vec![9002],
    })
}

async fn remove_records(
    State(fake): State<Shared>,
    RawQuery(query): RawQuery,
) -> axum::Json<RemovedRecords> {
    fake.lock()
        .unwrap()
        .requests
        .push(format!("DELETE /v1/records?{}", query.unwrap_or_default()));
    axum::Json(RemovedRecords {
        jobs: vec![9001],
        bytes: 1 << 30,
    })
}

async fn remove_record(UrlPath(job): UrlPath<u64>) -> Response {
    refuse(
        StatusCode::CONFLICT,
        &format!("a shell is open in the record of job {job}; remove it once the shell exits"),
    )
}

/// Runs `runnerctl --socket socket args`, with stdout a pipe, failing the test after 10 s.
fn runnerctl(socket: &Path, args: &[&str]) -> Output {
    let mut child = Command::new(env!("CARGO_BIN_EXE_runnerctl"))
        .arg("--socket")
        .arg(socket)
        .args(args)
        .env_remove("NO_COLOR")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(10);
    while child.try_wait().unwrap().is_none() {
        if Instant::now() > deadline {
            child.kill().unwrap();
            panic!("runnerctl {args:?} did not finish within 10 s");
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    child.wait_with_output().unwrap()
}

fn stdout(output: &Output) -> String {
    String::from_utf8(output.stdout.clone()).unwrap()
}

fn stderr(output: &Output) -> String {
    String::from_utf8(output.stderr.clone()).unwrap()
}

#[test]
fn the_version_is_reported_under_the_command_name() {
    // The package is runnerd-cli; what people type and read is runnerctl.
    let output = Command::new(env!("CARGO_BIN_EXE_runnerctl"))
        .arg("--version")
        .output()
        .unwrap();
    assert!(output.status.success(), "{}", stderr(&output));
    assert_eq!(
        stdout(&output),
        format!("runnerctl {}\n", env!("CARGO_PKG_VERSION"))
    );
}

#[test]
fn status_json_is_the_api_type_unchanged() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    serve(&socket);
    let output = runnerctl(&socket, &["status", "--json"]);
    assert!(output.status.success(), "{}", stderr(&output));
    let printed: Status = serde_json::from_str(&stdout(&output)).unwrap();
    assert_eq!(printed, status());
}

#[test]
fn status_piped_to_another_program_is_aligned_text_without_colour() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    serve(&socket);
    let output = runnerctl(&socket, &["status"]);
    assert!(output.status.success(), "{}", stderr(&output));
    let text = stdout(&output);
    assert!(!text.contains('\x1b'), "{text:?}");
    assert!(
        text.contains("6G of 16G reserved in runnerd.slice"),
        "{text}"
    );
    let slots: Vec<&str> = text
        .lines()
        .filter(|line| line.starts_with("jvm"))
        .collect();
    assert_eq!(slots.len(), 2, "{text}");
    assert_eq!(
        slots[0].find("busy"),
        slots[1].find("free"),
        "the state column lines up:\n{text}"
    );
    assert!(
        text.lines().any(
            |line| line.starts_with("9002  halyard/ledger  build / lint  ")
                && line.ends_with(" ago")
        ),
        "the queued job is listed under the repositories:\n{text}"
    );
}

#[test]
fn a_followed_log_resumes_after_the_last_line_and_stops_once_the_job_is_final() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    let fake = serve(&socket);
    let output = runnerctl(&socket, &["logs", "9001", "-f"]);
    assert!(output.status.success(), "{}", stderr(&output));
    assert_eq!(
        stdout(&output),
        "Run ./gradlew test\nBUILD SUCCESSFUL\nCleaning up\n"
    );
    assert_eq!(
        fake.lock().unwrap().log_queries,
        ["from=0&follow=true", "from=2&follow=true"]
    );
}

#[test]
fn watch_resumes_after_the_last_durable_event_when_the_stream_ends() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    let fake = serve(&socket);
    let output = runnerctl(&socket, &["watch", "--json"]);
    // The second stream ends at once too, so watch gives up.
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("keeps closing the event stream"),
        "{}",
        stderr(&output)
    );
    let printed: Vec<EventEnvelope> = stdout(&output)
        .lines()
        .map(|line| serde_json::from_str(line).unwrap())
        .collect();
    assert_eq!(printed.len(), 4);
    assert_eq!(printed[0].id, Some(41));
    assert_eq!(
        fake.lock().unwrap().event_ids,
        [None, Some("43".to_owned())]
    );
}

#[test]
fn with_no_daemon_it_says_runnerd_is_not_running_and_how_to_start_it() {
    let dir = TempDir::new();
    let output = runnerctl(&dir.0.join("runnerd.sock"), &["status"]);
    assert!(!output.status.success());
    let error = stderr(&output);
    assert!(error.contains("runnerd is not running"), "{error}");
    assert!(error.contains("systemctl --user start runnerd"), "{error}");
}

#[test]
fn the_daemons_error_message_reaches_the_user() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    serve(&socket);
    let output = runnerctl(&socket, &["pause", "halyard/ledgr"]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("halyard/ledgr is not a configured repository"),
        "{}",
        stderr(&output)
    );
}

#[test]
fn a_pause_while_the_repository_runs_a_job_names_the_job_and_how_to_force_it() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    serve(&socket);
    let refused = runnerctl(&socket, &["pause", "halyard/ledger"]);
    assert!(!refused.status.success());
    let error = stderr(&refused);
    assert!(
        error.contains("job 9001 on runnerd-5f2a-jvm-1-k3j9"),
        "{error}"
    );
    assert!(
        error.contains("runnerctl pause --force halyard/ledger"),
        "{error}"
    );

    let forced = runnerctl(&socket, &["pause", "--force", "halyard/ledger"]);
    assert!(forced.status.success(), "{}", stderr(&forced));
    assert!(
        stdout(&forced).contains("stopped job 9001 on runnerd-5f2a-jvm-1-k3j9"),
        "{}",
        stdout(&forced)
    );
}

#[test]
fn a_pause_the_daemon_cannot_record_fails_saying_a_restart_resumes_it() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    serve(&socket);
    let output = runnerctl(&socket, &["pause", "halyard/wharf"]);
    assert!(
        !output.status.success(),
        "a pause that is not durable fails"
    );
    assert!(
        stderr(&output).contains("a restart resumes it"),
        "{}",
        stderr(&output)
    );
    assert!(!stdout(&output).contains("paused:"), "{}", stdout(&output));
}

#[test]
fn pause_all_is_refused_while_a_job_runs_says_how_to_force_it_and_resume_all_resumes() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    serve(&socket);
    let refused = runnerctl(&socket, &["pause", "--all"]);
    assert!(!refused.status.success(), "a pause while a job runs fails");
    let error = stderr(&refused);
    assert!(error.contains("job 9001"), "{error}");
    assert!(error.contains("runnerctl pause --force --all"), "{error}");

    let forced = runnerctl(&socket, &["pause", "--all", "--force"]);
    assert!(forced.status.success(), "{}", stderr(&forced));
    assert!(
        stdout(&forced).contains("every repository paused"),
        "{}",
        stdout(&forced)
    );

    let resumed = runnerctl(&socket, &["resume", "--all"]);
    assert!(resumed.status.success(), "{}", stderr(&resumed));
    assert_eq!(stdout(&resumed), "every repository resumed\n");
}

#[test]
fn reseed_listens_before_asking_and_waits_for_its_own_profile() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    let fake = serve(&socket);
    let output = runnerctl(&socket, &["reseed", "jvm"]);
    assert!(output.status.success(), "{}", stderr(&output));
    let text = stdout(&output);
    assert!(
        text.contains("jvm: slot 1 changed 2.1G\njvm: reseeded"),
        "{text}"
    );
    assert!(!text.contains("node"), "{text}");
    assert_eq!(
        fake.lock().unwrap().requests,
        ["GET /v1/events", "POST /v1/profiles/jvm/reseed"]
    );
}

#[test]
fn a_config_over_the_budget_fails_the_check_with_the_daemons_reason() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    let fake = serve(&socket);
    let file = dir.0.join("runnerd.toml");
    std::fs::write(&file, "[host]\nslice = \"runnerd.slice\"\n").unwrap();
    let output = runnerctl(&socket, &["config", "check", file.to_str().unwrap()]);
    assert!(!output.status.success());
    assert!(
        stdout(&output).contains(
            "runnerd.toml: memory caps sum to 20G, more than runnerd.slice's MemoryMax of 16G"
        ),
        "{}",
        stdout(&output)
    );
    assert_eq!(
        fake.lock().unwrap().checked,
        ["[host]\nslice = \"runnerd.slice\"\n"]
    );
}

#[test]
fn doctor_prints_each_check_as_runnerd_does_and_fails_when_one_fails() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    serve(&socket);
    let output = runnerctl(&socket, &["doctor"]);
    assert!(!output.status.success());
    assert_eq!(
        stdout(&output),
        "ok    Docker: 29.1.0\nFAIL  sysbox: sysbox-runc is not a Docker runtime\n      fix: install sysbox\n"
    );
}

#[test]
fn web_prints_the_login_url_the_daemon_wrote_next_to_its_socket() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    let missing = runnerctl(&socket, &["web", "--no-open"]);
    assert!(!missing.status.success());
    assert!(
        stderr(&missing).contains("runnerd is not running, or was started with --web off"),
        "{}",
        stderr(&missing)
    );
    let url = "http://127.0.0.1:7477/login?code=0f3a";
    std::fs::write(dir.0.join("runnerd.web"), format!("{url}\n")).unwrap();
    let output = runnerctl(&socket, &["web", "--no-open"]);
    assert!(output.status.success(), "{}", stderr(&output));
    assert_eq!(stdout(&output), format!("{url}\n"));
}

#[test]
fn a_job_shows_the_caps_its_container_ran_with() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    serve(&socket);
    let output = runnerctl(&socket, &["job", "9001"]);
    assert!(output.status.success(), "{}", stderr(&output));
    assert!(
        stdout(&output).contains("(profile jvm, slot 1, capped at 6G and 4 CPUs)"),
        "{}",
        stdout(&output)
    );
}

#[test]
fn records_list_their_sizes_and_limits_and_go_by_age_or_one_by_one() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    let fake = serve(&socket);

    let listed = runnerctl(&socket, &["records"]);
    assert!(listed.status.success(), "{}", stderr(&listed));
    let text = stdout(&listed);
    assert!(
        text.starts_with("2 records, 4G of 20G; at most 10, each for 7d"),
        "{text}"
    );
    assert!(text.contains("9002"), "{text}");
    assert!(text.contains("shell open"), "{text}");

    let removed = runnerctl(&socket, &["records", "rm", "--older-than", "2d"]);
    assert!(removed.status.success(), "{}", stderr(&removed));
    assert_eq!(stdout(&removed), "removed 1 record, 1G freed\n");
    assert_eq!(
        fake.lock().unwrap().requests,
        ["DELETE /v1/records?all=false&older_than=2d"]
    );

    let refused = runnerctl(&socket, &["records", "rm", "9002"]);
    assert!(
        !refused.status.success(),
        "a record with a shell open stays"
    );
    assert!(
        stderr(&refused).contains("a shell is open in the record of job 9002"),
        "{}",
        stderr(&refused)
    );
}

#[test]
fn a_shell_the_budget_has_no_room_for_says_so() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    serve(&socket);
    let refused = runnerctl(&socket, &["shell", "9001"]);
    assert!(!refused.status.success(), "the shell is refused");
    assert!(
        stderr(&refused).contains("the budget is full"),
        "{}",
        stderr(&refused)
    );
}

#[test]
fn sizing_shows_the_advice_and_applies_it_only_when_told_to() {
    let dir = TempDir::new();
    let socket = dir.0.join("runnerd.sock");
    let fake = serve(&socket);
    let shown = runnerctl(&socket, &["sizing"]);
    assert!(shown.status.success(), "{}", stderr(&shown));
    let text = stdout(&shown);
    assert!(
        text.contains("node  7G × 2, 8 CPUs; 100 jobs, slots busy 80%"),
        "{text}"
    );
    assert!(
        text.contains(
            "lower memory to 2.5G from 7G, its largest peak + 15%; 5 slots fit in the same 14G"
        ),
        "{text}"
    );
    assert!(text.contains("runnerctl sizing apply node"), "{text}");
    assert!(text.contains("halyard/storefront  CI / build"), "{text}");

    // No terminal to ask on: nothing is written.
    let asked = runnerctl(&socket, &["sizing", "apply", "node"]);
    assert!(!asked.status.success());
    assert!(stderr(&asked).contains("pass --yes"), "{}", stderr(&asked));
    assert!(
        fake.lock().unwrap().replaced.is_empty(),
        "nothing is written without a yes"
    );

    let applied = runnerctl(&socket, &["sizing", "apply", "node", "--yes"]);
    assert!(applied.status.success(), "{}", stderr(&applied));
    assert!(
        stdout(&applied).contains("node: memory 2.5G, 5 slots written"),
        "{}",
        stdout(&applied)
    );
    let replaced = fake.lock().unwrap().replaced.clone();
    assert_eq!(
        replaced,
        [CONFIG
            .replace("memory = \"7G\"", "memory = \"2.5G\"")
            .replace("slots = 2", "slots = 5")]
    );
}