runnerd-core 0.1.1

Config, domain logic and API types shared by runnerd and its clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
//! Parsing `runnerd.toml` and checking it against a slice's budget.

use std::path::Path;
use std::time::Duration;

use super::{
    BuildCacheWriters, ByteSize, Config, Image, Warning, keep_secrets, mask_secrets, parse_age,
    parse_memory_max, parse_slice_cpus,
};

const MINIMAL: &str = r#"
[host]
slice = "ci.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 = "app"
cpus = 4
memory = "4G"
slots = 1

[[repositories]]
name = "owner/app"
profile = "app"
labels = ["self-hosted", "app"]
"#;

fn example() -> Config {
    let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/runnerd.toml");
    Config::load(&path).unwrap()
}

/// `text`, which sets no `admission`, under `admission = "caps"`.
fn caps(text: &str) -> String {
    let caps = text.replacen(
        "isolation = \"sysbox\"",
        "isolation = \"sysbox\"\nadmission = \"caps\"",
        1,
    );
    assert_ne!(caps, text, "the config names its isolation");
    caps
}

/// `examples/runnerd.toml` under `admission = "caps"`.
fn example_under_caps() -> Config {
    let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/runnerd.toml");
    let text = std::fs::read_to_string(path).unwrap();
    let caps = text.replace("admission = \"measured\"", "admission = \"caps\"");
    assert_ne!(caps, text, "the example names its admission");
    Config::parse(&caps).unwrap()
}

fn size(s: &str) -> ByteSize {
    s.parse().unwrap()
}

#[test]
fn example_config_fits_its_slice() {
    // 33G as `systemctl show runnerd.slice -p MemoryMax --value` prints it.
    let memory_max = parse_memory_max("35433480192").unwrap();
    assert_eq!(example().validate(memory_max).unwrap(), Vec::new());
}

#[test]
fn example_config_over_a_smaller_slice_names_both_numbers() {
    let error = example_under_caps()
        .validate(Some(size("30G")))
        .unwrap_err()
        .to_string();
    assert!(error.contains("32.5G"), "{error}");
    assert!(error.contains("30G"), "{error}");
}

#[test]
fn config_with_unknown_profile_names_the_repository() {
    let text = MINIMAL.replace("profile = \"app\"", "profile = \"missing\"");
    let error = Config::parse(&text)
        .unwrap()
        .validate(Some(size("33G")))
        .unwrap_err()
        .to_string();
    assert!(error.contains("owner/app"), "{error}");
    assert!(error.contains("missing"), "{error}");
}

#[test]
fn config_with_unsafe_dind_requires_allow_unsafe() {
    let unsafe_dind = MINIMAL.replace("isolation = \"sysbox\"", "isolation = \"unsafe-dind\"");
    let error = Config::parse(&unsafe_dind)
        .unwrap()
        .validate(Some(size("33G")))
        .unwrap_err()
        .to_string();
    assert!(error.contains("allow_unsafe"), "{error}");

    let allowed = unsafe_dind.replace("[host]", "[host]\nallow_unsafe = true");
    Config::parse(&allowed)
        .unwrap()
        .validate(Some(size("33G")))
        .unwrap();
}

#[test]
fn under_caps_a_config_with_an_unlimited_slice_validates_with_a_warning() {
    let memory_max = parse_memory_max("infinity").unwrap();
    let warnings = example_under_caps().validate(memory_max).unwrap();
    assert!(
        matches!(warnings.as_slice(), [Warning::UnlimitedSlice { slice, .. }] if slice == "runnerd.slice"),
        "{warnings:?}"
    );
}

#[test]
fn config_rejects_unknown_fields_in_every_table() {
    for (table, with_typo) in [
        ("top level", format!("typo = 1\n{MINIMAL}")),
        ("host", MINIMAL.replace("[host]", "[host]\ntypo = 1")),
        ("caches", MINIMAL.replace("[caches]", "[caches]\ntypo = 1")),
        (
            "mirror",
            MINIMAL.replace("ttl = \"168h\"", "ttl = \"168h\", typo = 1"),
        ),
        ("pnpm", MINIMAL.replace("pnpm = {", "pnpm = { typo = 1,")),
        (
            "profile",
            MINIMAL.replace("slots = 1", "slots = 1\ntypo = 1"),
        ),
        (
            "repository",
            MINIMAL.replace("profile = \"app\"", "profile = \"app\"\ntypo = 1"),
        ),
        ("records", format!("{MINIMAL}\n[records]\ntypo = 1")),
        ("web", format!("{MINIMAL}\n[web]\ntypo = 1")),
    ] {
        let error = Config::parse(&with_typo).unwrap_err().to_string();
        assert!(error.contains("unknown field `typo`"), "{table}: {error}");
    }
}

#[test]
fn config_with_a_zero_limit_names_the_field() {
    let mirror_enabled = MINIMAL.replace("enabled = false", "enabled = true");
    for (field, text) in [
        (
            "profiles.app.memory",
            MINIMAL.replace("memory = \"4G\"", "memory = \"0G\""),
        ),
        ("profiles.app.cpus", MINIMAL.replace("cpus = 4", "cpus = 0")),
        (
            "profiles.app.slots",
            MINIMAL.replace("slots = 1", "slots = 0"),
        ),
        (
            "caches.mirror.memory",
            mirror_enabled.replace("memory = \"512M\"", "memory = \"0M\""),
        ),
        (
            "caches.mirror.cpus",
            mirror_enabled.replace("cpus = 1,", "cpus = 0,"),
        ),
        (
            "records.max_count",
            format!("{MINIMAL}\n[records]\nmax_count = 0"),
        ),
        (
            "sizing.interval",
            format!("{MINIMAL}\n[sizing]\ninterval = \"0s\""),
        ),
        (
            "sizing.max_step",
            format!("{MINIMAL}\n[sizing]\nmax_step = 0"),
        ),
        (
            "profiles.app.max_slots",
            MINIMAL.replace("slots = 1", "slots = 1\nmax_slots = 0"),
        ),
        (
            "caches.build.max_size",
            MINIMAL.replace(
                "maven = { max_size = \"5G\" }",
                "maven = { max_size = \"5G\" }\nbuild = { max_size = \"0G\" }",
            ),
        ),
    ] {
        let error = Config::parse(&text)
            .unwrap()
            .validate(Some(size("33G")))
            .unwrap_err()
            .to_string();
        assert!(error.contains(field), "{field}: {error}");
    }
}

#[test]
fn a_config_without_build_cache_settings_gives_every_repository_one_main_writes() {
    let config = Config::parse(MINIMAL).unwrap();
    let build = &config.caches.build;
    assert!(build.enabled, "on: its defaults are safe");
    assert!(
        build.branches.is_empty(),
        "only each repository's default branch writes"
    );
    assert_eq!(build.max_size, size("10G"));
    assert!(build.actions_cache, "it serves GitHub Actions' cache");
    assert_eq!(
        build.actions_cache_check().detail,
        "served from the build cache on this host, in place of GitHub's"
    );
    assert!(config.repositories[0].build_cache, "owner/app gets it");
    for (build, place) in [
        (
            "build = { actions_cache = false }",
            "GitHub's, as [caches.build] actions_cache = false sets",
        ),
        (
            "build = { enabled = false }",
            "GitHub's, as the build cache is off",
        ),
    ] {
        let text = MINIMAL.replace("[caches]", &format!("[caches]\n{build}"));
        let config = Config::parse(&text).unwrap();
        assert_eq!(
            config.caches.build.actions_cache_check().detail,
            place,
            "{build}"
        );
    }
    assert_eq!(
        config.repositories[0].build_cache_writers,
        BuildCacheWriters::DefaultBranch,
        "no pull request writes unless the repository says so"
    );
}

#[test]
fn auto_sizing_is_off_and_bounded_unless_configured() {
    let config = Config::parse(MINIMAL).unwrap();
    assert!(
        !config.sizing.auto,
        "auto sizing stays off unless asked for"
    );
    assert_eq!(config.sizing.interval, Duration::from_hours(1));
    assert_eq!(config.sizing.max_step, 50);
    // app has 4G and 1 slot.
    for (bounds, why) in [
        (
            "min_memory = \"6G\"\nmax_memory = \"5G\"",
            "min_memory is above its max_memory",
        ),
        ("max_memory = \"2G\"", "memory is above its max_memory"),
        ("min_memory = \"6G\"", "memory is below its min_memory"),
        ("slots = 2\nmax_slots = 1", "slots are above its max_slots"),
    ] {
        let text = MINIMAL.replace("slots = 1", &format!("slots = 1\n{bounds}"));
        let text = text.replace("slots = 1\nslots = 2", "slots = 2");
        let error = Config::parse(&text)
            .unwrap()
            .validate(Some(size("33G")))
            .unwrap_err()
            .to_string();
        assert_eq!(error, format!("profiles.app: {why}"));
    }
}

fn origins(list: &str) -> Result<Vec<String>, String> {
    Config::parse(&format!("{MINIMAL}\n[web]\norigins = [{list}]\n"))
        .map(|config| config.web.origins.iter().map(ToString::to_string).collect())
        .map_err(|error| error.to_string())
}

#[test]
fn the_dashboard_takes_writes_from_no_other_origin_unless_configured() {
    let config = Config::parse(MINIMAL).unwrap();
    assert!(config.web.origins.is_empty(), "no extra origins by default");
}

#[test]
fn the_dashboard_opens_on_one_of_its_origins_or_the_config_is_refused() {
    let web = |lines: &str| {
        Config::parse(&format!("{MINIMAL}\n[web]\n{lines}\n"))
            .unwrap()
            .validate(Some(size("33G")))
            .map_err(|error| error.to_string())
    };
    assert_eq!(
        Config::parse(MINIMAL).unwrap().web.open,
        None,
        "loopback by default"
    );
    let tailnet = r#"origins = ["https://forge.tail0b5e.ts.net:8443"]"#;
    web(&format!(
        "{tailnet}\nopen = \"https://forge.tail0b5e.ts.net:8443\""
    ))
    .unwrap();
    let error = web(&format!(
        "{tailnet}\nopen = \"https://other.tail0b5e.ts.net\""
    ))
    .unwrap_err();
    assert!(
        error.contains("https://other.tail0b5e.ts.net")
            && error.contains("not one of [web] origins"),
        "{error}"
    );
    web(r#"open = "https://forge.tail0b5e.ts.net:8443""#).unwrap_err();
}

/// Each input and what `new URL(input).origin` gives for it in Node 24, which follows the WHATWG URL standard as
/// browsers do: the `Origin` header a page at that address sends.
const BROWSER_ORIGINS: [(&str, &str); 11] = [
    (
        "https://Host.Example.ts.net:443",
        "https://host.example.ts.net",
    ),
    ("https://host.example.:8443", "https://host.example.:8443"),
    ("http://localhost:8080", "http://localhost:8080"),
    ("http://[0:0:0:0:0:0:0:1]:8443", "http://[::1]:8443"),
    ("https://[2001:0DB8::1]:8443", "https://[2001:db8::1]:8443"),
    (
        "https://[2001:db8:0:0:1:0:0:1]",
        "https://[2001:db8::1:0:0:1]",
    ),
    ("https://[1:0:0:2:0:0:0:3]", "https://[1:0:0:2::3]"),
    ("https://[0:0:1:0:0:0:0:0]", "https://[0:0:1::]"),
    (
        "https://[::ffff:127.0.0.1]:8443",
        "https://[::ffff:7f00:1]:8443",
    ),
    ("http://127.0.0.1.:7477", "http://127.0.0.1:7477"),
    ("https://192.0.2.1:8443", "https://192.0.2.1:8443"),
];

#[test]
fn an_origin_is_kept_as_the_browser_sends_it() {
    for (input, browser) in BROWSER_ORIGINS {
        assert_eq!(
            origins(&format!("{input:?}")),
            Ok(vec![browser.to_owned()]),
            "{input}"
        );
    }
}

#[test]
fn an_ipv4_address_in_another_form_than_four_decimals_is_refused() {
    // Browsers read each as 127.0.0.1 or 8.0.0.1; written that way they would be a second spelling to get wrong.
    for input in [
        "https://2130706433:8443",
        "https://0x7f.1",
        "http://127.1:7477",
        "https://127.000.0.1",
        "https://010.0.0.1",
        "https://example.0x",
    ] {
        let error = origins(&format!("{input:?}")).unwrap_err();
        assert!(error.contains("four decimal numbers"), "{input}: {error}");
    }
}

#[test]
fn an_origin_with_a_path_plain_http_or_no_port_number_is_refused() {
    for (origin, why) in [
        ("https://host.example.ts.net:8443/", "it has a path"),
        ("https://host.example/dashboard", "it has a path"),
        (
            "http://host.example.ts.net:8443",
            "http is for a loopback host only",
        ),
        ("host.example.ts.net:8443", "it has no scheme"),
        ("ftp://host.example", "its scheme is not https"),
        ("https://host.example:http", "its port is not a number"),
        ("https://host.example:0", "its port is not a number"),
        ("https://me@host.example", "it names a user"),
        ("https://", "its host is not a name"),
    ] {
        let error = origins(&format!("{origin:?}")).unwrap_err();
        assert!(error.contains(why), "{origin}: {error}");
        assert!(
            error.contains("origins = ["),
            "{origin} shows the line: {error}"
        );
    }
}

#[test]
fn records_are_off_and_bounded_unless_configured() {
    let config = Config::parse(MINIMAL).unwrap();
    assert!(
        !config.profiles["app"].record_failures,
        "a profile records no failures unless it asks to"
    );
    assert_eq!(config.records.max_total, size("20G"));
    assert_eq!(config.records.max_count, 10);
    assert_eq!(config.records.max_age, Duration::from_hours(7 * 24));

    let text = MINIMAL.replace("slots = 1", "slots = 1\nrecord_failures = true")
        + "\n[records]\nmax_total = \"5G\"\nmax_age = \"2d\"\n";
    let config = Config::parse(&text).unwrap();
    assert!(
        config.profiles["app"].record_failures,
        "app records failures"
    );
    assert_eq!(config.records.max_total, size("5G"));
    assert_eq!(config.records.max_age, Duration::from_hours(48));
    assert_eq!(
        config.records.max_count, 10,
        "unset limits keep their default"
    );
}

#[test]
fn config_rejects_a_size_beyond_u64() {
    let text = MINIMAL.replace("memory = \"4G\"", "memory = \"16777216T\"");
    let error = Config::parse(&text).unwrap_err().to_string();
    assert!(error.contains("too large"), "{error}");
}

#[test]
fn config_whose_caps_overflow_is_refused() {
    // 2 × 2^63 bytes does not fit in u64; a saturating sum would pass against the largest slice.
    let text = MINIMAL
        .replace("memory = \"4G\"", "memory = \"8388608T\"")
        .replace("slots = 1", "slots = 2");
    let error = Config::parse(&text)
        .unwrap()
        .validate(Some(ByteSize(u64::MAX)))
        .unwrap_err()
        .to_string();
    assert!(error.contains("too large"), "{error}");
}

#[test]
fn config_rejects_a_size_without_unit() {
    let text = MINIMAL.replace("memory = \"4G\"", "memory = \"4\"");
    let error = Config::parse(&text).unwrap_err().to_string();
    assert!(error.contains("\"4\""), "{error}");
}

#[test]
fn config_rejects_empty_labels() {
    let text = MINIMAL.replace("labels = [\"self-hosted\", \"app\"]", "labels = []");
    let error = Config::parse(&text)
        .unwrap()
        .validate(Some(size("33G")))
        .unwrap_err()
        .to_string();
    assert!(error.contains("owner/app"), "{error}");
}

#[test]
fn profile_runs_a_local_stage_or_a_pulled_reference() {
    let local = Config::parse(MINIMAL).unwrap();
    assert_eq!(
        local.profiles["app"].image.reference(),
        "runnerd-runner:app"
    );
    let text = MINIMAL.replace(
        "image_stage = \"app\"",
        "image = \"ghcr.io/ayagmar/runnerd-runner:jvm-0.0.5\"",
    );
    let pulled = Config::parse(&text).unwrap();
    assert_eq!(
        pulled.profiles["app"].image,
        Image::Pulled("ghcr.io/ayagmar/runnerd-runner:jvm-0.0.5".to_owned())
    );
}

#[test]
fn profile_needs_exactly_one_image() {
    for (case, text) in [
        ("neither", MINIMAL.replace("image_stage = \"app\"\n", "")),
        (
            "both",
            MINIMAL.replace(
                "image_stage = \"app\"",
                "image_stage = \"app\"\nimage = \"ghcr.io/ayagmar/runnerd-runner:jvm-0.0.5\"",
            ),
        ),
        (
            "empty",
            MINIMAL.replace("image_stage = \"app\"", "image = \"\""),
        ),
    ] {
        let error = Config::parse(&text).unwrap_err().to_string();
        assert!(error.contains("set image_stage"), "{case}: {error}");
    }
}

#[test]
fn example_config_pulls_published_images_no_older_than_this_release() {
    let numbers = |version: &str| -> Vec<u32> {
        version
            .split('-')
            .next()
            .unwrap()
            .split('.')
            .map(|part| part.parse().unwrap())
            .collect()
    };
    let release = numbers(env!("CARGO_PKG_VERSION"));
    for (name, profile) in example().profiles {
        let Image::Pulled(reference) = &profile.image else {
            panic!("examples/runnerd.toml's {name} profile does not pull its image");
        };
        let tag = reference
            .strip_prefix(&format!("ghcr.io/ayagmar/runnerd-runner:{name}-"))
            .unwrap_or_else(|| panic!("{name} runs {reference}, not its published stage"));
        assert!(
            numbers(tag) >= release,
            "{name} runs {reference}, older than this release; bump the example's tags"
        );
    }
}

#[test]
fn a_resized_memory_reads_back_to_the_byte_at_every_scale() {
    // Every 256M step to 3T, where `Display` switches to T and keeps two decimals, and sizes off any step.
    let granules = (1..=12 * 1024).map(|step| step * (256 << 20));
    let odd = [
        1,
        1023,
        (1 << 30) + 1,
        (1029 << 30) + (5 << 29) + 4097,
        5 << 40,
    ];
    for memory in granules.chain(odd) {
        let resized = super::resize_profile(
            MINIMAL,
            "app",
            crate::api::Resize {
                memory,
                slots: 1,
                cpus: None,
            },
        )
        .unwrap();
        let read = Config::parse(&resized).unwrap().profiles["app"].memory;
        assert_eq!(read, ByteSize(memory), "{resized}");
    }
    assert_eq!(ByteSize(1029 * (1 << 30) + (1 << 29)).exact(), "1029.5G");
    assert_eq!(
        ByteSize(9 << 30).exact(),
        "9G",
        "a size Display says exactly"
    );
}

#[test]
fn a_resized_profile_keeps_the_rest_of_the_file_as_written() {
    let text = MINIMAL.replace(
        "memory = \"4G\"\nslots = 1",
        "memory = \"4G\" # peaked at 3.1G\nslots = 1",
    );
    let resized = super::resize_profile(
        &format!("# the app's runners\n{text}"),
        "app",
        crate::api::Resize {
            memory: 2560 << 20,
            slots: 3,
            cpus: None,
        },
    )
    .unwrap();
    assert!(resized.starts_with("# the app's runners\n"), "{resized}");
    assert!(
        resized.contains("memory = \"2.5G\" # peaked at 3.1G\nslots = 3\n"),
        "{resized}"
    );
    let profile = &Config::parse(&resized).unwrap().profiles["app"];
    assert_eq!((profile.memory, profile.slots), (size("2.5G"), 3));
    let cpus = Config::parse(&text).unwrap().profiles["app"].cpus;
    assert_eq!(profile.cpus, cpus, "a resize without cpus leaves them");
    let with_cpus = super::resize_profile(
        &text,
        "app",
        crate::api::Resize {
            memory: 4 << 30,
            slots: 1,
            cpus: Some(cpus + 2),
        },
    )
    .unwrap();
    assert_eq!(
        Config::parse(&with_cpus).unwrap().profiles["app"].cpus,
        cpus + 2
    );
}

#[test]
fn resizing_a_profile_the_config_lacks_names_it() {
    let error = super::resize_profile(
        MINIMAL,
        "jvm",
        crate::api::Resize {
            memory: 1 << 30,
            slots: 1,
            cpus: None,
        },
    )
    .unwrap_err();
    assert_eq!(
        error.to_string(),
        "the config has no profile \"jvm\" under [profiles]"
    );
}

/// `MINIMAL` under measured admission with `slots` slots.
fn measured(slots: u32) -> String {
    MINIMAL
        .replace(
            "isolation = \"sysbox\"",
            "isolation = \"sysbox\"\nadmission = \"measured\"",
        )
        .replace("slots = 1", &format!("slots = {slots}"))
}

#[test]
fn measured_admission_lets_the_caps_add_up_past_memory_max() {
    // 8 × 4G = 32G of caps on a 10G slice: one runner fits, the predictions decide how many more.
    let (config, check) = Config::check(&measured(8), |_| Ok(Some(size("10G"))));
    assert!(check.valid, "{}", check.message);
    assert!(check.message.contains("measured"), "{}", check.message);
    assert_eq!(config.unwrap().host.admission, super::Admission::Measured);
    // The check names the rule, and the figure it holds to MemoryMax is one runner, not every cap.
    assert_eq!(check.admission, crate::api::AdmissionPolicy::Measured);
    let max = size("10G").0;
    assert!(
        check.memory_caps > Some(max),
        "the caps add up past MemoryMax"
    );
    assert!(
        check.memory_needed.is_some_and(|needed| needed <= max),
        "one runner fits: {check:?}"
    );
    // The same caps admitted by caps do not fit, and there the caps are what must fit.
    let caps = caps(MINIMAL).replace("slots = 1", "slots = 8");
    let refused = Config::check(&caps, |_| Ok(Some(size("10G")))).1;
    assert!(!refused.valid, "8 × 4G of caps do not fit 10G");
    assert_eq!(refused.memory_needed, refused.memory_caps);
}

#[test]
fn measured_admission_needs_one_runner_of_every_profile_to_fit() {
    let error = Config::parse(&measured(2))
        .unwrap()
        .validate(Some(size("3G")))
        .unwrap_err()
        .to_string();
    assert!(error.contains("one runner of app"), "{error}");
}

#[test]
fn measured_admission_without_a_profile_still_needs_the_mirror_to_fit() {
    let text = r#"
repositories = []

[host]
slice = "ci.slice"
isolation = "sysbox"
admission = "measured"

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

[profiles]
"#;
    let (_, check) = Config::check(text, |_| Ok(Some(size("256M"))));
    assert!(
        !check.valid,
        "a 512M mirror does not fit 256M: {}",
        check.message
    );
    assert!(check.message.contains("512M"), "{}", check.message);
    let (_, check) = Config::check(text, |_| Ok(Some(size("1G"))));
    assert!(check.valid, "a 512M mirror fits 1G: {}", check.message);
}

#[test]
fn measured_admission_needs_a_memory_max_to_admit_against() {
    let error = Config::parse(&measured(2))
        .unwrap()
        .validate(None)
        .unwrap_err()
        .to_string();
    assert!(error.contains("has none"), "{error}");
}

#[test]
fn without_the_key_admission_is_measured_and_a_slice_without_memory_max_names_caps() {
    // MINIMAL sets no `admission`: 4 × 4G of caps on a 10G slice fit one runner, which is all measured asks.
    let (config, check) = Config::check(&MINIMAL.replace("slots = 1", "slots = 4"), |_| {
        Ok(Some(size("10G")))
    });
    assert_eq!(config.unwrap().host.admission, super::Admission::Measured);
    assert!(check.valid, "{}", check.message);
    assert_eq!(check.admission, crate::api::AdmissionPolicy::Measured);

    let (_, check) = Config::check(MINIMAL, |_| Ok(None));
    assert!(!check.valid, "no MemoryMax to admit against");
    for named in ["ci.slice", "runnerd doctor", "admission = \"caps\""] {
        assert!(
            check.message.contains(named),
            "lacks {named:?}: {}",
            check.message
        );
    }
    let (_, under_caps) = Config::check(&caps(MINIMAL), |_| Ok(None));
    assert!(under_caps.valid, "caps only warns: {}", under_caps.message);
}

#[test]
fn an_age_reads_in_seconds_to_weeks_and_names_its_units_when_it_does_not() {
    assert_eq!(parse_age("30m"), Ok(Duration::from_mins(30)));
    assert_eq!(parse_age("30d"), Ok(Duration::from_hours(30 * 24)));
    assert_eq!(parse_age("2w"), Ok(Duration::from_hours(14 * 24)));
    for wrong in ["30", "d", "3x", "1.5d", ""] {
        assert_eq!(
            parse_age(wrong),
            Err("expected a number and s, m, h, d or w, such as 12h".to_owned()),
            "{wrong:?}"
        );
    }
}

#[test]
fn the_pooled_count_is_on_unless_turned_off() {
    let config = Config::parse(MINIMAL).unwrap();
    assert!(config.host.pooled_count, "on by default");
    let off = MINIMAL.replace(
        "isolation = \"sysbox\"",
        "isolation = \"sysbox\"\npooled_count = false",
    );
    let config = Config::parse(&off).unwrap();
    assert!(!config.host.pooled_count, "turned off under [host]");
    let host_off = MINIMAL.replace(
        "isolation = \"sysbox\"",
        "isolation = \"sysbox\"\npooled_host = false",
    );
    assert!(
        Config::parse(&host_off).is_err(),
        "one switch for both budgets: pooled_host is gone"
    );
}

#[test]
fn cpu_admission_is_off_unless_an_overcommit_above_0_is_set() {
    assert_eq!(Config::parse(MINIMAL).unwrap().host.cpu_overcommit, None);
    let with = |factor: &str| {
        MINIMAL.replace(
            "isolation = \"sysbox\"",
            &format!("isolation = \"sysbox\"\ncpu_overcommit = {factor}"),
        )
    };
    let config = Config::parse(&with("1.5")).unwrap();
    assert_eq!(config.host.cpu_overcommit, Some(1.5));
    assert!(config.validate(Some(size("10G"))).is_ok());
    for factor in ["0", "-1.0", "17", "nan"] {
        let error = Config::parse(&with(factor))
            .unwrap()
            .validate(Some(size("10G")))
            .unwrap_err()
            .to_string();
        assert!(error.contains("host.cpu_overcommit"), "{factor}: {error}");
    }
}

#[test]
fn a_memory_ceiling_is_unset_unless_given_and_takes_a_size() {
    assert_eq!(Config::parse(MINIMAL).unwrap().host.memory_ceiling, None);
    let config = Config::parse(&MINIMAL.replace(
        "isolation = \"sysbox\"",
        "isolation = \"sysbox\"\nmemory_ceiling = \"24G\"",
    ))
    .unwrap();
    assert_eq!(config.host.memory_ceiling, Some(size("24G")));
    assert!(
        config.validate(Some(size("10G"))).is_ok(),
        "a 24G ceiling passes under a 10G slice"
    );
    let error = Config::parse(&MINIMAL.replace(
        "isolation = \"sysbox\"",
        "isolation = \"sysbox\"\nmemory_ceiling = 24",
    ))
    .unwrap_err()
    .to_string();
    assert!(error.contains("memory_ceiling"), "{error}");
}

#[test]
fn a_memory_ceiling_of_0_or_under_the_largest_runner_is_refused() {
    let with = |ceiling: &str| {
        Config::parse(&MINIMAL.replace(
            "isolation = \"sysbox\"",
            &format!("isolation = \"sysbox\"\nmemory_ceiling = \"{ceiling}\""),
        ))
        .unwrap()
        .validate(Some(size("10G")))
    };
    let zero = with("0G").unwrap_err().to_string();
    assert!(zero.contains("host.memory_ceiling is 0"), "{zero}");
    // The app profile's runner takes 4G, and the mirror is off.
    let typo = with("4M").unwrap_err().to_string();
    assert!(
        typo.contains("host.memory_ceiling is 4M, under the 4G one runner of app"),
        "{typo}"
    );
    assert!(with("4G").is_ok(), "a ceiling that fits one runner passes");
}

#[test]
fn a_memory_ceiling_counts_the_mirror_only_while_it_is_enabled() {
    let with = |mirror: &str| {
        Config::parse(
            &MINIMAL
                .replace(
                    "isolation = \"sysbox\"",
                    "isolation = \"sysbox\"\nmemory_ceiling = \"4G\"",
                )
                .replace("enabled = false, memory = \"512M\"", mirror),
        )
        .unwrap()
        .validate(Some(size("10G")))
    };
    assert!(
        with("enabled = false, memory = \"512M\"").is_ok(),
        "a disabled mirror takes nothing beside the 4G runner"
    );
    let error = with("enabled = true, memory = \"512M\"")
        .unwrap_err()
        .to_string();
    assert!(
        error.contains("under the 4.5G one runner of app and the mirror take"),
        "{error}"
    );
}

#[test]
fn a_slices_cpus_are_its_cpu_set_or_the_hosts_less_under_a_lower_quota() {
    let show = |effective: &str, allowed: &str, quota: &str| {
        format!("EffectiveCPUs={effective}\nAllowedCPUs={allowed}\nCPUQuotaPerSecUSec={quota}\n")
    };
    assert_eq!(
        parse_slice_cpus(&show("", "", "infinity"), 32),
        Some(32_000)
    );
    assert_eq!(
        parse_slice_cpus(&show("0-11,16", "", "infinity"), 32),
        Some(13_000)
    );
    assert_eq!(
        parse_slice_cpus(&show("", "0-3", "infinity"), 32),
        Some(4000)
    );
    // A 250% quota: two and a half CPUs' time each second.
    assert_eq!(
        parse_slice_cpus(&show("0-31", "", "2.500000s"), 32),
        Some(2500)
    );
    assert_eq!(parse_slice_cpus(&show("", "", "800ms"), 32), Some(800));
    assert_eq!(parse_slice_cpus(&show("0-3", "", "8s"), 32), Some(4000));
    // As systemctl prints disjoint ranges, and a 6400% and a 10000% quota.
    assert_eq!(
        parse_slice_cpus(&show("0-3 8-11", "", "infinity"), 32),
        Some(8000)
    );
    assert_eq!(
        parse_slice_cpus(&show("", "0 2 4-5", "infinity"), 32),
        Some(4000)
    );
    assert_eq!(
        parse_slice_cpus(&show("", "", "1min 4s"), 128),
        Some(64_000)
    );
    assert_eq!(
        parse_slice_cpus(&show("", "", "1min 40s"), 128),
        Some(100_000)
    );
    assert_eq!(parse_slice_cpus(&show("zero", "", "infinity"), 32), None);
    assert_eq!(parse_slice_cpus(&show("", "", "4 parsecs"), 32), None);
}

const NOTIFY: &str = r#"
[notify]
digest_at = "07:30"

[[notify.targets]]
name = "phone"
kind = "ntfy"
url = "https://ntfy.example/halyard-ci-6f3a"
headers = { Authorization = "Bearer tk_hunter2" }

[[notify.targets]]
name = "relay"
kind = "webhook"
url = "https://hooks.example/runnerd?key=s3cret"
events = ["failed", "digest"]
"#;

#[test]
fn notify_targets_get_failures_lost_jobs_runners_and_insights_by_default() {
    use crate::api::NotifyEvent;

    let config = Config::parse(&format!("{MINIMAL}{NOTIFY}")).unwrap();

    assert!(config.validate(Some(size("33G"))).is_ok());
    assert_eq!(config.notify.digest_at.to_string(), "07:30");
    let events: Vec<_> = config
        .notify
        .targets
        .iter()
        .map(|target| target.events.clone())
        .collect();
    assert_eq!(
        events,
        [
            vec![
                NotifyEvent::Failed,
                NotifyEvent::Lost,
                NotifyEvent::Runner,
                NotifyEvent::Insights
            ],
            vec![NotifyEvent::Failed, NotifyEvent::Digest],
        ]
    );
    assert!(
        Config::parse(MINIMAL).unwrap().notify.targets.is_empty(),
        "nothing is sent without [notify]"
    );
}

#[test]
fn a_notify_targets_url_and_headers_never_show_in_debug_output_or_errors() {
    let config = Config::parse(&format!("{MINIMAL}{NOTIFY}")).unwrap();
    let shown = format!("{config:?}");
    for secret in ["halyard-ci-6f3a", "hunter2", "s3cret", "hooks.example"] {
        assert!(!shown.contains(secret), "Debug shows {secret}: {shown}");
    }

    let broken = NOTIFY.replace(
        "https://hooks.example/runnerd?key=s3cret",
        "hooks.example/runnerd?key=s3cret",
    );
    let error = Config::parse(&format!("{MINIMAL}{broken}"))
        .unwrap()
        .validate(None)
        .unwrap_err()
        .to_string();
    assert_eq!(
        error,
        "notify target \"relay\": url does not start with https:// or http://"
    );
}

#[test]
fn an_ntfy_target_needs_a_topic_and_targets_need_their_own_names() {
    let refused = |notify: &str| {
        Config::parse(&format!("{MINIMAL}{notify}"))
            .unwrap()
            .validate(None)
            .unwrap_err()
            .to_string()
    };
    assert_eq!(
        refused(&NOTIFY.replace("ntfy.example/halyard-ci-6f3a", "ntfy.example/")),
        "notify target \"phone\": url is not an ntfy topic's, such as https://ntfy.sh/<topic>"
    );
    assert_eq!(
        refused(&NOTIFY.replace("\"relay\"", "\"phone\"")),
        "notify target \"phone\": another target has this name"
    );
    assert!(
        Config::parse(&format!("{MINIMAL}{}", NOTIFY.replace("07:30", "7:30"))).is_err(),
        "a time of day is HH:MM"
    );
}

#[test]
fn a_config_shown_with_its_notify_secrets_masked_saves_with_them_kept() {
    // Headers as a table of their own too, with the targets swapped round in the edit.
    let stored = format!(
        "{MINIMAL}{}\n[notify.targets.headers]\nX-Key = \"k3y\"\n",
        NOTIFY.replace("events = [\"failed\", \"digest\"]\n", "")
    );

    let shown = mask_secrets(&stored).unwrap();

    for secret in ["halyard-ci-6f3a", "hunter2", "s3cret", "k3y"] {
        assert!(!shown.contains(secret), "shows {secret}: {shown}");
    }
    assert_eq!(
        mask_secrets(MINIMAL).as_deref(),
        Some(MINIMAL),
        "a config without targets is shown as written"
    );
    assert_eq!(keep_secrets(&shown, &stored), stored);
    let edited = shown.replace("07:30", "08:00");
    assert_eq!(
        keep_secrets(&edited, &stored),
        stored.replace("07:30", "08:00")
    );
    let rewritten = shown.replace(
        "url = \"<secret>\"\nheaders",
        "url = \"https://ntfy.example/new-topic\"\nheaders",
    );
    assert!(
        keep_secrets(&rewritten, &stored).contains("https://ntfy.example/new-topic"),
        "a value written over the mask is the new one"
    );
}

/// MINIMAL with a `light` profile serving owner/app's jobs that ask for `labels` (a TOML array), with `extra` lines.
fn with_light_pool(labels: &str, extra: &str) -> Config {
    Config::parse(&format!(
        "{MINIMAL}
[profiles.light]
image_stage = \"app\"
cpus = 1
memory = \"1G\"
slots = 1

[[repositories]]
name = \"owner/app\"
profile = \"light\"
labels = {labels}
{extra}"
    ))
    .unwrap()
}

#[test]
fn a_repository_may_be_served_by_pools_with_labels_of_their_own() {
    let config = with_light_pool("[\"app-light\"]", "");
    assert_eq!(config.validate(Some(size("33G"))).unwrap(), Vec::new());
    let profile = |labels: &[&str]| {
        let labels: Vec<String> = labels.iter().map(|label| (*label).to_owned()).collect();
        config
            .pool("owner/app", &labels)
            .map(|pool| pool.profile.as_str())
    };
    assert_eq!(profile(&["self-hosted"]), Some("app"));
    assert_eq!(profile(&["APP-LIGHT"]), Some("light"));
    assert_eq!(profile(&["self-hosted", "app-light"]), None);
    assert_eq!(config.repository_names(), ["owner/app"]);
}

#[test]
fn pools_of_a_repository_sharing_a_label_are_rejected() {
    // A job asking for `self-hosted` alone could land in either.
    let error = with_light_pool("[\"Self-Hosted\", \"app-light\"]", "")
        .validate(Some(size("33G")))
        .unwrap_err()
        .to_string();
    assert!(error.contains("owner/app"), "{error}");
    assert!(error.contains("self-hosted"), "{error}");
    assert!(error.contains("app") && error.contains("light"), "{error}");
}

#[test]
fn a_pool_without_labels_is_rejected() {
    let error = with_light_pool("[]", "")
        .validate(Some(size("33G")))
        .unwrap_err()
        .to_string();
    assert!(
        error.contains("needs at least one non-empty label"),
        "{error}"
    );
}

#[test]
fn two_pools_of_a_repository_in_one_profile_are_rejected() {
    let text = format!(
        "{MINIMAL}
[[repositories]]
name = \"owner/app\"
profile = \"app\"
labels = [\"app-light\"]
"
    );
    let error = Config::parse(&text)
        .unwrap()
        .validate(Some(size("33G")))
        .unwrap_err()
        .to_string();
    assert!(
        error.contains("two entries with profile \"app\""),
        "{error}"
    );
}

#[test]
fn pools_of_a_repository_must_agree_on_who_writes_to_the_build_cache() {
    let error = with_light_pool("[\"app-light\"]", "build_cache_writers = \"pull-requests\"")
        .validate(Some(size("33G")))
        .unwrap_err()
        .to_string();
    assert!(error.contains("build_cache_writers"), "{error}");
}

#[test]
fn a_profile_is_priced_at_the_github_runner_it_names() {
    let config =
        Config::parse(&MINIMAL.replace("slots = 1\n", "slots = 1\npriced_as = \"linux_8_core\"\n"))
            .unwrap();
    assert_eq!(
        config.pricing().of(Some("app")),
        crate::api::Sku::Linux8Core
    );
    assert_eq!(
        config.pricing().of(Some("gone")),
        crate::api::Sku::standard_for(std::env::consts::ARCH),
        "a profile gone from the config is priced at the standard runner"
    );
    for refused in ["windows_4_core", "linux_4_core_gpu", "8-core"] {
        let error = Config::parse(&MINIMAL.replace(
            "slots = 1\n",
            &format!("slots = 1\npriced_as = \"{refused}\"\n"),
        ))
        .unwrap_err()
        .to_string();
        assert!(
            error.contains("linux_8_core"),
            "{refused}: names the runners it takes: {error}"
        );
    }
}

#[test]
fn a_resized_profile_is_found_where_its_sizes_were_written_not_in_a_comment_or_another_profile() {
    let text = &format!(
        "# node used memory = \"7G\" before\n{MINIMAL}\n\
         [profiles.node]\nimage_stage = \"node\"\ncpus = 8\nmemory = \"7G\" # peaked at 2.1G\nslots = 2\n"
    );
    let advice = crate::api::Resize {
        memory: 3328 << 20,
        slots: 4,
        cpus: None,
    };
    let resized = super::resize_profile(text, "node", advice).unwrap();
    let at = super::resized_at(&resized, "node", advice).unwrap();
    assert_eq!(
        &resized[at],
        "memory = \"3.25G\" # peaked at 2.1G\nslots = 4"
    );
    let with_cpus = crate::api::Resize {
        cpus: Some(6),
        ..advice
    };
    let resized = super::resize_profile(text, "node", with_cpus).unwrap();
    let at = super::resized_at(&resized, "node", with_cpus).unwrap();
    assert_eq!(
        &resized[at],
        "cpus = 6\nmemory = \"3.25G\" # peaked at 2.1G\nslots = 4"
    );
    assert_eq!(super::resized_at(&resized, "rust", advice), None);
    let before = super::profile_sizes(text, "node").unwrap();
    assert_eq!(
        before,
        crate::api::Resize {
            memory: 7 << 30,
            slots: 2,
            cpus: Some(8),
        },
        "node's sizes as the file sets them, not jvm's or the comment's"
    );
    assert_eq!(super::profile_sizes(text, "rust"), None);
    assert_eq!(super::profile_sizes("[profiles.node", "node"), None);
    assert_eq!(
        advice.line_from(Some(&before)),
        "memory 7G → 3.25G, slots 2 → 4"
    );
    assert_eq!(
        with_cpus.line_from(Some(&before)),
        "memory 7G → 3.25G, slots 2 → 4, cpus 8 → 6"
    );
    assert_eq!(advice.line_from(None), "memory 3.25G, slots 4");
    assert_eq!(super::resized_at("[profiles.node", "node", advice), None);
}

#[test]
fn a_config_that_does_not_parse_names_the_line_an_editor_marks() {
    assert_eq!(
        Config::parse_error(MINIMAL),
        None,
        "a config that parses has none"
    );
    let text = format!("{MINIMAL}\n[host\nslice = 1\n");
    let error = Config::parse_error(&text).unwrap();
    let marked = text.lines().nth(error.line - 1).unwrap_or_default();
    assert_eq!(marked, "[host", "{error:?}");
    assert!(
        !error.message.is_empty() && !error.message.contains('|'),
        "{error:?}"
    );
}

/// The smallest config the reference's defaults are tried in, by table, with each table's keys; `[name]` is an array
/// of tables. As site/scripts/reference/config.py writes it.
const REFERENCE_BASE: &[(&str, &[(&str, &str)])] = &[
    (
        "host",
        &[
            ("slice", r#""runnerd.slice""#),
            ("isolation", r#""sysbox""#),
        ],
    ),
    ("caches", &[]),
    (
        "caches.mirror",
        &[
            ("enabled", "true"),
            ("memory", r#""512M""#),
            ("cpus", "1"),
            ("ttl", r#""168h""#),
        ],
    ),
    ("caches.pnpm", &[("max_size", r#""5G""#)]),
    ("caches.maven", &[("max_size", r#""5G""#)]),
    ("caches.build", &[]),
    (
        "profiles.jvm",
        &[
            ("image", r#""ghcr.io/ayagmar/runnerd-runner:jvm-0.1.1""#),
            ("cpus", "8"),
            ("memory", r#""9G""#),
            ("slots", "2"),
        ],
    ),
    (
        "[repositories]",
        &[
            ("name", r#""halyard/ledger""#),
            ("profile", r#""jvm""#),
            ("labels", r#"["self-hosted"]"#),
        ],
    ),
    ("history", &[]),
    ("records", &[]),
    ("sizing", &[]),
    ("web", &[]),
    ("github", &[]),
    ("notify", &[]),
    (
        "[notify.targets]",
        &[
            ("name", r#""phone""#),
            ("kind", r#""ntfy""#),
            ("url", r#""https://ntfy.sh/halyard-ci""#),
        ],
    ),
];

/// The reference's headings, as the tables of `REFERENCE_BASE` they document.
const REFERENCE_SECTIONS: &[(&str, &str)] = &[
    ("[host]", "host"),
    ("[caches]", "caches"),
    ("[profiles.<name>]", "profiles.jvm"),
    ("[[repositories]]", "[repositories]"),
    ("[history]", "history"),
    ("[records]", "records"),
    ("[sizing]", "sizing"),
    ("[github]", "github"),
    ("[web]", "web"),
    ("[notify]", "notify"),
    ("[[notify.targets]]", "[notify.targets]"),
];

/// A key the reference gives a default as a TOML value for: its table, its name and that value.
struct Documented {
    table: String,
    key: String,
    default: String,
}

/// Every key of the configuration reference's tables whose default is one code span, such as `"caps"`.
fn documented_defaults() -> Vec<Documented> {
    let docs = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../site/src/content/docs/reference");
    let mut rows = Vec::new();
    for page in ["configuration.md", "configuration-more.md"] {
        let text = std::fs::read_to_string(docs.join(page)).unwrap();
        let mut table = None;
        for line in text.lines() {
            if line.starts_with("##") {
                let heading = line.trim_start_matches('#').trim();
                let named = heading
                    .strip_prefix('`')
                    .and_then(|heading| heading.strip_suffix('`'))
                    .filter(|heading| heading.starts_with('['));
                table = named.map(|named| {
                    REFERENCE_SECTIONS
                        .iter()
                        .find(|(name, _)| *name == named)
                        .map_or_else(
                            || panic!("{page} documents {named}, which REFERENCE_SECTIONS lacks"),
                            |(_, table)| *table,
                        )
                });
                continue;
            }
            let (Some(table), true) = (table, line.starts_with("| `")) else {
                continue;
            };
            let cells: Vec<&str> = line
                .trim()
                .trim_matches('|')
                .split('|')
                .map(str::trim)
                .collect();
            let [keys, default, ..] = cells.as_slice() else {
                continue;
            };
            let Some(default) = default
                .strip_prefix('`')
                .and_then(|default| default.strip_suffix('`'))
                .filter(|default| !default.contains('`') && !default.starts_with('$'))
            else {
                continue;
            };
            for key in keys.split('`').skip(1).step_by(2) {
                let (table, key) = match key.rsplit_once('.') {
                    Some((sub, leaf)) => (format!("{table}.{sub}"), leaf),
                    None => (table.to_owned(), key),
                };
                rows.push(Documented {
                    table,
                    key: key.to_owned(),
                    default: default.to_owned(),
                });
            }
        }
    }
    rows
}

/// `REFERENCE_BASE` as TOML, with `key` of `table` left out, or set to `value`.
fn reference_config(table: &str, key: &str, value: Option<&str>) -> String {
    let mut lines = Vec::new();
    for (name, keys) in REFERENCE_BASE {
        lines.push(match name.strip_prefix('[') {
            Some(array) => format!("[[{array}]"),
            None => format!("[{name}]"),
        });
        lines.extend(
            keys.iter()
                .filter(|(k, _)| !(*name == table && *k == key))
                .map(|(k, v)| format!("{k} = {v}")),
        );
        if *name == table
            && let Some(value) = value
        {
            lines.push(format!("{key} = {value}"));
        }
        lines.push(String::new());
    }
    lines.join("\n")
}

#[test]
fn every_default_the_configuration_reference_gives_is_the_one_the_config_uses() {
    let rows = documented_defaults();
    // Every key the reference gives a TOML default for, `targets` too; a row that stops reading as one changes the
    // count.
    assert_eq!(
        rows.len(),
        36,
        "the reference's keys with a default to check"
    );
    let mut wrong = Vec::new();
    for Documented {
        table,
        key,
        default,
    } in &rows
    {
        // A key that is a table of its own in the base config (`targets`) is documented by its own table.
        let own = [format!("{table}.{key}"), format!("[{table}.{key}]")];
        if REFERENCE_BASE
            .iter()
            .any(|(name, _)| own.iter().any(|own| own == name))
        {
            continue;
        }
        let omitted = Config::parse(&reference_config(table, key, None));
        let given = Config::parse(&reference_config(table, key, Some(default)));
        match (omitted, given) {
            (Ok(omitted), Ok(given)) if format!("{omitted:?}") == format!("{given:?}") => {}
            (Ok(_), Ok(_)) => wrong.push(format!(
                "[{table}] {key}: the reference says {default}, the config differs"
            )),
            (omitted, given) => wrong.push(format!(
                "[{table}] {key} = {default}: left out {:?}, given {:?}",
                omitted.err().map(|error| error.to_string()),
                given.err().map(|error| error.to_string())
            )),
        }
    }
    assert!(
        wrong.is_empty(),
        "the reference's defaults are the config's:\n{}",
        wrong.join("\n")
    );
}