ostrya 0.19.1

Pure-Rust async reimplementation of the ostree repository library
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
//! Helpers that the integration tests of `ostrya` share.

#![allow(dead_code)]

use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

use futures_io::AsyncWrite;

pub mod composefs;
pub mod modes;
pub mod pipe;
#[cfg(feature = "receive")]
pub mod receive;
#[cfg(feature = "s3")]
pub mod s3;

/// Returns the read rights of an anonymous client under the implicit group
/// of a config with no client group.
pub fn anyone() -> ostrya::access::ReadAccess {
    read_access("", "anonymous")
}

/// Returns the read rights of the client with the auth item `item` under
/// the client groups `groups`, in a repository with no collection id.
pub fn read_access(groups: &str, item: &str) -> ostrya::access::ReadAccess {
    let text = format!("[core]\nrepo_version=1\nmode=archive-z2\n{groups}");
    let config = ostrya::RepoConfig::parse(&text).unwrap();
    let access = ostrya::access::ClientAccess::from_config(&config).unwrap();
    let item = ostrya::access::AuthItem::parse(item).unwrap();
    ostrya::access::ReadAccess::new(Arc::new(access), item, None)
}

/// Returns the read rights of the client with the auth item `item` under
/// the client groups of the config of `repo`.
pub fn repo_access(repo: &ostrya::Repo, item: &str) -> ostrya::access::ReadAccess {
    let access = ostrya::access::ClientAccess::from_config(repo.config()).unwrap();
    let item = ostrya::access::AuthItem::parse(item).unwrap();
    ostrya::access::ReadAccess::new(Arc::new(access), item, None)
}

/// Returns the root directory of the fixture repositories of the `ostree` command.
///
/// The `ostree` command generated these repositories. The root holds one
/// subdirectory for each repository mode.
pub fn fixture_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/generated")
}

/// Returns the `repo/` path of a fixture, and unpacks the fixture if necessary.
///
/// The `archive` and `bare` fixtures are plain trees, so the function returns
/// their path directly. The fixtures of the bare-user family (`bare-user`,
/// `canon`, `xattr`) keep the logical metadata of each file in a
/// `user.ostreemeta` xattr. Git does not track xattrs, so these fixtures ship
/// as tarballs, and the function unpacks them on demand.
pub fn fixture_repo(mode: &str) -> PathBuf {
    match mode {
        "bare-user" | "canon" | "xattr" => unpack_fixture(mode).join("repo"),
        _ => fixture_root().join(mode).join("repo"),
    }
}

/// Creates the directories `refs/remotes` and `refs/mirrors` in the
/// repository `repo`, if they do not exist.
///
/// Git keeps no empty directory, so a fixture repository holds
/// `refs/heads` alone. The `ostree` command fails to list the refs of a
/// repository with no `refs/remotes`. A test that runs an `ostree` command
/// that lists refs (for example `fsck`, `refs`, `summary -u`, or `prune`)
/// on a copy of a fixture repository calls this function on the copy.
pub fn add_empty_ref_dirs(repo: &Path) {
    for sub in ["refs/remotes", "refs/mirrors"] {
        std::fs::create_dir_all(repo.join(sub)).unwrap();
    }
}

/// Unpacks the fixture tarball `<fixture_root>/<name>.tar` with its `user.*`
/// xattrs.
///
/// The function returns the directory that holds the `repo/` of the fixture.
/// It unpacks each tarball once in each test process. It keeps the result for
/// the rest of the process, so the returned paths stay valid for the whole
/// test run.
pub fn unpack_fixture(name: &str) -> PathBuf {
    static REGISTRY: OnceLock<Mutex<HashMap<String, PathBuf>>> = OnceLock::new();
    let registry = REGISTRY.get_or_init(|| Mutex::new(HashMap::new()));
    let mut map = registry.lock().unwrap();
    if let Some(dir) = map.get(name) {
        return dir.clone();
    }
    let dir = std::env::temp_dir()
        .join(format!("ostrya-fixtures-{}", std::process::id()))
        .join(name);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("create fixture unpack dir");
    let tar = fixture_root().join(format!("{name}.tar"));
    let status = Command::new("tar")
        .args(["--xattrs", "--xattrs-include=user.*", "-xf"])
        .arg(&tar)
        .arg("-C")
        .arg(&dir)
        .status()
        .expect("run tar to unpack fixture");
    assert!(status.success(), "tar failed to unpack {}", tar.display());
    map.insert(name.to_owned(), dir.clone());
    dir
}

/// The commit and object checksums that the fixture generator recorded.
///
/// These checksums do not depend on the repository mode, so they are the same
/// in every fixture repository. This is the invariant of commit identity
/// across modes.
pub const COMMIT: &str = "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89";
pub const CONTENT: &str = "d79e5560a90877b47660b639e3d7c88c20ca5a7604f867960e155c552025e104";
pub const ROOT_DIRTREE: &str = "1075002e681eb1fe7ff54ae6b76b1f65285e514b54d96deaa0952330b10c7983";
pub const ROOT_DIRMETA: &str = "446a0ef11b7cc167f3b603e585c7eeeeb675faa412d5ec73f62988eb0b6c5488";
pub const EMPTY_TXT: &str = "cc700d46f407c6c5ab2d5dde474366a928b7398277e61162e7f8ec06f469f07e";
pub const HELLO_TXT: &str = "cfffd52f38d14c87cf46e18d5260074421ba5961f0895954e9921f165f9c91db";
pub const LINK: &str = "f66efa496a72379413c44593de510dc344beb045294f1a543da87b2b6118db35";
pub const SUBDIR_DIRTREE: &str = "78154b9650d2a28716fd4a83584a2d9cba1833be4851714d8a0e89e8933c875a";
pub const NESTED_TXT: &str = "a4d80a620354908d76238bea8185775d2f6d60f55a1506d16ee06af212b4a125";
/// The commit of the archive fixture that `--generate-sizes` made.
///
/// Its metadata holds the `ostree.sizes` key, so it differs from [`COMMIT`],
/// which has no sizes.
pub const SIZES_COMMIT: &str = "3ecadc59022c36743e1b233afbf3bde7b25239b77035185a3acc2af9d84478f0";

/// A temporary directory that is removed when the value drops.
pub struct TmpDir(PathBuf);

impl TmpDir {
    pub fn new(tag: &str) -> TmpDir {
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        let path =
            std::env::temp_dir().join(format!("ostrya-read-{}-{tag}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&path);
        std::fs::create_dir_all(&path).expect("create scratch dir");
        TmpDir(path)
    }

    pub fn path(&self) -> &Path {
        &self.0
    }
}

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

/// The time limit of each wait on a writer that an update guard holds back.
pub const GUARD_WAIT: Duration = Duration::from_secs(30);

/// Runs `fut` and fails the test if `fut` takes longer than [`GUARD_WAIT`].
pub async fn within<T>(what: &str, fut: impl Future<Output = T>) -> T {
    futures_lite::future::or(fut, async {
        ostrya_rt::Timer::after(GUARD_WAIT).await;
        panic!("{what} took longer than {GUARD_WAIT:?}");
    })
    .await
}

/// The time that a test holds an update guard after the commit object of a
/// pull under that guard lands.
pub const GUARD_HOLD: Duration = Duration::from_millis(500);

/// Waits until the commit object `commit` is in `repo`, then waits for
/// [`GUARD_HOLD`].
///
/// The test fails if the pull `task` ends while the commit object is absent.
/// The test also fails if the commit object takes longer than [`GUARD_WAIT`].
pub async fn wait_for_commit_under_guard<F>(
    repo: &ostrya::Repo,
    commit: &ostrya::Checksum,
    task: &mut F,
) where
    F: Future + Unpin,
    F::Output: std::fmt::Debug,
{
    let deadline = Instant::now() + GUARD_WAIT;
    while !repo
        .has_object(ostrya::ObjectType::Commit, commit)
        .await
        .unwrap()
    {
        if let Some(result) = futures_lite::future::poll_once(&mut *task).await {
            panic!("the pull ended under the guard: {result:?}");
        }
        assert!(Instant::now() < deadline, "no commit after {GUARD_WAIT:?}");
        ostrya_rt::Timer::after(Duration::from_millis(10)).await;
    }
    // The commit object lands before the pull reaches the lock step, so the
    // hold lets the pull reach that step while the guard is held.
    ostrya_rt::Timer::after(GUARD_HOLD).await;
}

// ---------------------------------------------------------------------------
// A lock that another process holds.
// ---------------------------------------------------------------------------

/// The environment variable that names the repository of the lock helper.
const FOREIGN_LOCK_REPO: &str = "OSTRYA_TEST_FOREIGN_LOCK_REPO";

/// The environment variable that names the lock file of the lock helper,
/// relative to the repository.
const FOREIGN_LOCK_FILE: &str = "OSTRYA_TEST_FOREIGN_LOCK_FILE";

/// The file that the lock helper writes after it takes the lock.
const FOREIGN_LOCK_MARKER: &str = ".foreign-held";

/// The name of the ignored test that calls [`lock_holder_main`].
///
/// Each test binary that starts a lock helper defines this test.
pub const LOCK_HOLDER_TEST: &str = "lock_holder_subprocess";

/// A child process that is killed and reaped when the guard drops.
pub struct ChildGuard(std::process::Child);

impl Drop for ChildGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

/// Waits for at most ten seconds until `marker` exists.
fn wait_for_marker(marker: &Path, what: &str) {
    let started = Instant::now();
    while !marker.exists() {
        assert!(started.elapsed() < Duration::from_secs(10), "{what}");
        std::thread::sleep(Duration::from_millis(20));
    }
}

/// Starts this test binary again as a process that holds a lock on
/// `<repo>/<lock_file>`.
///
/// The child holds an exclusive raw record lock on the file until it is
/// killed.
pub fn foreign_holder(repo: &Path, lock_file: &str) -> ChildGuard {
    let holder = ChildGuard(
        Command::new(std::env::current_exe().unwrap())
            .args([LOCK_HOLDER_TEST, "--exact", "--ignored", "--nocapture"])
            .env(FOREIGN_LOCK_REPO, repo)
            .env(FOREIGN_LOCK_FILE, lock_file)
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn the lock holder"),
    );
    wait_for_marker(
        &repo.join(FOREIGN_LOCK_MARKER),
        "the holder never took the lock",
    );
    holder
}

/// Runs the body of the lock helper.
///
/// The helper takes the record lock that the environment names and writes the
/// readiness marker. Then it waits until standard input closes. Outside a
/// helper process, the function does nothing.
pub fn lock_holder_main() {
    use rustix::fs::{FlockOperation, Mode, OFlags};
    use std::io::Read;

    let (Ok(repo), Ok(lock_file)) = (
        std::env::var(FOREIGN_LOCK_REPO),
        std::env::var(FOREIGN_LOCK_FILE),
    ) else {
        return;
    };
    let repo = Path::new(&repo);
    let fd = rustix::fs::open(
        repo.join(lock_file),
        OFlags::RDWR | OFlags::CREATE,
        Mode::from_raw_mode(0o660),
    )
    .expect("open the lock file");
    rustix::fs::fcntl_lock(&fd, FlockOperation::LockExclusive).expect("take the record lock");
    std::fs::write(repo.join(FOREIGN_LOCK_MARKER), b"1").expect("write the readiness marker");
    let mut sink = Vec::new();
    let _ = std::io::stdin().read_to_end(&mut sink);
}

// ---------------------------------------------------------------------------
// An update guard that another process holds.
// ---------------------------------------------------------------------------

/// The environment variable that names the repository of the guard helper.
const GUARD_HOLDER_REPO: &str = "OSTRYA_TEST_GUARD_HOLDER_REPO";

/// The file that the guard helper writes after it takes the guard.
pub const GUARD_HELD_MARKER: &str = ".guard-held";

/// The file that the guard helper writes after its standard input closes and
/// before it releases the guard.
pub const GUARD_RELEASING_MARKER: &str = ".guard-releasing";

/// The name of the ignored test that calls [`guard_holder_main`].
///
/// Each test binary that starts a guard helper defines this test.
pub const GUARD_HOLDER_TEST: &str = "guard_holder_subprocess";

/// A child process that holds an `UpdateGuard` of one repository.
pub struct GuardHolder {
    child: Option<std::process::Child>,
}

impl GuardHolder {
    /// Closes the standard input of the child and waits for the child to exit.
    ///
    /// The closed input makes the child release the guard. If the child
    /// fails, or its output does not report `1 passed`, the test fails.
    pub fn release(mut self) {
        let mut child = self.child.take().unwrap();
        drop(child.stdin.take());
        let output = child.wait_with_output().unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success() && stdout.contains("1 passed"),
            "the guard holder reported {}:\n{stdout}",
            output.status
        );
    }

    /// Returns the process id of the child.
    pub fn pid(&self) -> u32 {
        self.child.as_ref().unwrap().id()
    }
}

impl Drop for GuardHolder {
    fn drop(&mut self) {
        if let Some(mut child) = self.child.take() {
            let _ = child.kill();
            let _ = child.wait();
        }
    }
}

/// Starts this test binary again as a process that holds an `UpdateGuard` of
/// `repo`.
///
/// The child opens the repository, takes the guard, and holds it until its
/// standard input closes. The call returns after the child takes the guard.
pub fn guard_holder(repo: &Path) -> GuardHolder {
    let child = Command::new(std::env::current_exe().unwrap())
        .args([GUARD_HOLDER_TEST, "--exact", "--ignored", "--nocapture"])
        .env(GUARD_HOLDER_REPO, repo)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .expect("spawn the guard holder");
    let holder = GuardHolder { child: Some(child) };
    wait_for_marker(
        &repo.join(GUARD_HELD_MARKER),
        "the holder never took the guard",
    );
    holder
}

/// Runs the body of the guard helper.
///
/// The helper takes an `UpdateGuard` of the repository that the environment
/// names and writes the readiness marker. Then it waits until standard input
/// closes. After that, it writes the releasing marker and finishes the guard.
/// Outside a helper process, the function does nothing.
pub fn guard_holder_main() {
    use std::io::Read;

    let Some(path) = std::env::var_os(GUARD_HOLDER_REPO).map(PathBuf::from) else {
        return;
    };
    ostrya_rt::block_on(async {
        let repo = ostrya::Repo::open(&path).await.unwrap();
        let guard = repo.begin_update().await.unwrap();
        std::fs::write(path.join(GUARD_HELD_MARKER), b"1").unwrap();
        let mut sink = Vec::new();
        let _ = std::io::stdin().read_to_end(&mut sink);
        std::fs::write(path.join(GUARD_RELEASING_MARKER), b"1").unwrap();
        guard.finish().await.unwrap();
    });
}

// ---------------------------------------------------------------------------
// A writer in another process.
// ---------------------------------------------------------------------------

/// The environment variable that names the repository of the writer helper.
const WRITER_CHILD_REPO: &str = "OSTRYA_TEST_WRITER_CHILD_REPO";

/// The environment variable that carries the argument of the writer helper.
const WRITER_CHILD_ARG: &str = "OSTRYA_TEST_WRITER_CHILD_ARG";

/// The name of the ignored test that calls [`writer_child_main`].
///
/// Each test binary that starts a writer helper defines this test.
pub const WRITER_CHILD_TEST: &str = "writer_child_subprocess";

/// A child process that runs one write on one repository.
pub struct WriterChild {
    child: Option<std::process::Child>,
}

impl WriterChild {
    /// Waits for the child to exit.
    ///
    /// If the write fails, or the output of the child does not report
    /// `1 passed`, the test fails.
    pub fn wait(mut self) {
        let child = self.child.take().unwrap();
        let output = child.wait_with_output().unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success() && stdout.contains("1 passed"),
            "the writer reported {}:\n{stdout}",
            output.status
        );
    }

    /// Returns `true` if the child exited.
    pub fn finished(&mut self) -> bool {
        let child = self.child.as_mut().unwrap();
        child.try_wait().unwrap().is_some()
    }
}

impl Drop for WriterChild {
    fn drop(&mut self) {
        if let Some(mut child) = self.child.take() {
            let _ = child.kill();
            let _ = child.wait();
        }
    }
}

/// Starts this test binary again as a process that runs the write of the test
/// binary on `repo`.
///
/// The child runs the write with the argument `arg`. The call returns at once.
pub fn writer_child(repo: &Path, arg: &str) -> WriterChild {
    writer_child_with(repo, arg, |_| {})
}

/// Starts the writer process of [`writer_child`] with a changed command.
///
/// Before the start, `configure` changes the command, for example its
/// environment.
pub fn writer_child_with(
    repo: &Path,
    arg: &str,
    configure: impl FnOnce(&mut Command),
) -> WriterChild {
    let mut command = Command::new(std::env::current_exe().unwrap());
    command
        .args([WRITER_CHILD_TEST, "--exact", "--ignored", "--nocapture"])
        .env(WRITER_CHILD_REPO, repo)
        .env(WRITER_CHILD_ARG, arg)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit());
    configure(&mut command);
    let child = command.spawn().expect("spawn the writer");
    WriterChild { child: Some(child) }
}

/// Runs the body of the writer helper.
///
/// The helper runs `write` on the repository and the argument that the
/// environment names. Outside a helper process, the function does nothing.
pub fn writer_child_main(write: impl FnOnce(&Path, &str)) {
    let (Some(path), Ok(arg)) = (
        std::env::var_os(WRITER_CHILD_REPO).map(PathBuf::from),
        std::env::var(WRITER_CHILD_ARG),
    ) else {
        return;
    };
    write(&path, &arg);
}

/// The environment variable that turns the skip for an absent `ostree` command
/// into a failure.
///
/// A harness that sets it declares that the `ostree` command is installed. If
/// the command is absent in such a run, the harness is broken, so the test
/// fails.
pub const REQUIRE_OSTREE: &str = "OSTRYA_REQUIRE_OSTREE";

/// Returns `true` if the `ostree` command is available for the cross-check
/// tests.
///
/// Some of these tests are the proof that a matrix record cites with
/// `evidence:`. If the command is absent and the test does not fail, the
/// harness reports the cited cells as covered, and no assertion runs. If
/// [`REQUIRE_OSTREE`] is set, an absent command fails the test. If it is not
/// set, the caller skips the test and writes a message about the skip.
pub fn ostree_available() -> bool {
    let found = Command::new("ostree")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);
    assert!(
        found || std::env::var_os(REQUIRE_OSTREE).is_none(),
        "{REQUIRE_OSTREE} is set and `ostree` is not installed, so the \
         tool-comparison tests cannot run"
    );
    found
}

/// Runs `ostree fsck` on `root` and asserts that it passes.
pub fn tool_fsck(root: &Path) {
    let out = tool_fsck_output(root, &[]);
    assert!(
        out.status.success(),
        "ostree fsck failed on {}: {}",
        root.display(),
        String::from_utf8_lossy(&out.stderr)
    );
}

/// Runs `ostree fsck` with `args` on `root`, and returns its output with no
/// check of the exit status.
pub fn tool_fsck_output(root: &Path, args: &[&str]) -> std::process::Output {
    Command::new("ostree")
        .arg("fsck")
        .arg(format!("--repo={}", root.display()))
        .args(args)
        .output()
        .unwrap()
}

/// Writes each key of the bucket repository of `bucket` under `dir`, with
/// the directories of a repository, so the `ostree` command opens it. Keys
/// under `extensions/` stay out.
///
/// The dump reads each key through the S3 client and copies its body to
/// its file through a buffer of fixed size. The harness of `common::s3`
/// holds this function apart, because the tests of `ostrya-cli` include
/// that file and have no `futures-lite`.
#[cfg(feature = "s3")]
pub async fn dump_bucket(bucket: &ostrya::remote::s3::Bucket, dir: &Path) {
    let mut keys: Vec<String> = ["config", "summary", "summary.sig"]
        .into_iter()
        .map(str::to_owned)
        .collect();
    for prefix in ["objects/", "refs/", "deltas/", "delta-indexes/", "state/"] {
        let listing = bucket.list(prefix).await.unwrap();
        keys.extend(listing.objects.into_iter().map(|listed| listed.key));
    }
    for key in keys {
        let Some(stream) = bucket.get_stream(&key).await.unwrap() else {
            continue;
        };
        let path = dir.join(&key);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let file = futures_lite::io::AssertAsync::new(std::fs::File::create(&path).unwrap());
        futures_lite::io::copy(stream, file).await.unwrap();
    }
    for sub in s3::REPO_DIRS {
        std::fs::create_dir_all(dir.join(sub)).unwrap();
    }
}

/// The environment variable that turns the skip for a missing ed25519 engine
/// into a failure.
///
/// A harness that sets it declares that the installed `ostree` command has the
/// ed25519 engine. If the engine is absent in such a run, the harness is
/// broken, so the test fails.
pub const REQUIRE_OSTREE_ED25519: &str = "OSTRYA_REQUIRE_OSTREE_ED25519";

/// Returns `true` if the `ostree` command has its ed25519 signing engine.
///
/// `ostree --version` reports the engine as the `sign-ed25519` feature. The
/// engine is a build option. A build of the command without the engine
/// refuses each ed25519 invocation with
/// `Requested signature type is not implemented`.
///
/// Tests that tell the command to sign or verify with ed25519 skip if the
/// engine is absent. Such a refusal describes the build of the command and
/// states nothing about ostrya. Without the skip, the refusal also satisfies a
/// test that asserts that the command rejects a signature. If
/// [`REQUIRE_OSTREE_ED25519`] is set, an absent engine fails the test.
pub fn ostree_supports_ed25519() -> bool {
    let supported = ostree_available()
        && Command::new("ostree")
            .arg("--version")
            .output()
            .map(|o| String::from_utf8_lossy(&o.stdout).contains("sign-ed25519"))
            .unwrap_or(false);
    assert!(
        supported || std::env::var_os(REQUIRE_OSTREE_ED25519).is_none(),
        "{REQUIRE_OSTREE_ED25519} is set and the installed `ostree` carries no \
         ed25519 engine, so the ed25519 cross-check tests cannot run"
    );
    supported
}

/// The environment variable that turns the skip for a missing spki engine
/// into a failure.
///
/// A harness that sets it declares that the installed `ostree` command has the
/// spki engine. If the engine is absent in such a run, the harness is broken,
/// so the test fails.
pub const REQUIRE_OSTREE_SPKI: &str = "OSTRYA_REQUIRE_OSTREE_SPKI";

/// Returns `true` if the `ostree` command has its spki signing engine.
///
/// `ostree --version` reports the engine as the `sign-spki` feature, next to
/// the `openssl` feature that the engine needs. Each feature is one line of
/// the list. The engine is a build option. A build of the command without the
/// engine refuses each spki invocation with
/// `Requested signature type is not implemented`.
///
/// Tests that tell the command to verify with spki skip if the engine is
/// absent. Such a refusal describes the build of the command and states
/// nothing about ostrya. Without the skip, the refusal also satisfies a test
/// that asserts that the command rejects a signature. If
/// [`REQUIRE_OSTREE_SPKI`] is set, an absent engine fails the test.
pub fn ostree_supports_spki() -> bool {
    let supported = ostree_available()
        && Command::new("ostree")
            .arg("--version")
            .output()
            .map(|o| {
                let stdout = String::from_utf8_lossy(&o.stdout);
                let has = |feature: &str| stdout.lines().any(|line| line.trim() == feature);
                has("- openssl") && has("- sign-spki")
            })
            .unwrap_or(false);
    assert!(
        supported || std::env::var_os(REQUIRE_OSTREE_SPKI).is_none(),
        "{REQUIRE_OSTREE_SPKI} is set and the installed `ostree` carries no \
         spki engine, so the spki cross-check tests cannot run"
    );
    supported
}

/// Returns `true` if the `openssl` command is available for the cross-check
/// tests.
pub fn openssl_available() -> bool {
    Command::new("openssl")
        .arg("version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Returns a PEM block of `kind` around the base64 text `b64`. The body has
/// one line for each 64 characters, the line width of RFC 7468.
pub fn wrap_pem(kind: &str, b64: &str) -> String {
    let mut body = String::new();
    for chunk in b64.as_bytes().chunks(64) {
        body.push_str(std::str::from_utf8(chunk).unwrap());
        body.push('\n');
    }
    format!("-----BEGIN {kind}-----\n{body}-----END {kind}-----\n")
}

/// The environment variable that turns the skip for an absent GnuPG binary
/// into a failure.
///
/// A harness that sets it declares that the GnuPG binaries are installed. If a
/// binary is absent in such a run, the harness is broken, so the test fails.
pub const REQUIRE_GNUPG: &str = "OSTRYA_REQUIRE_GNUPG";

/// Returns `true` if each named GnuPG binary answers.
///
/// The GPG cases build their fixtures with `gpg`, and the agreement gate
/// compares against `gpgv`. If a binary is absent and the test does not fail,
/// the harness reports these cases as tested, and no assertion runs. If
/// [`REQUIRE_GNUPG`] is set, an absent binary fails the test. If it is not
/// set, the function writes the name of the absent binary to stderr, and the
/// caller skips the test.
pub fn gnupg_available(programs: &[&str]) -> bool {
    for program in programs {
        let found = Command::new(program)
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);
        if !found {
            assert!(
                std::env::var_os(REQUIRE_GNUPG).is_none(),
                "{REQUIRE_GNUPG} is set and `{program}` is not available, so \
                 the GPG tests cannot run"
            );
            eprintln!("skipping: {program} not available");
            return false;
        }
    }
    true
}

/// Stops each GnuPG daemon of the home directory `dir` and removes its socket
/// directory.
///
/// GnuPG makes the socket directory under the user runtime directory. GnuPG
/// names that directory from the path string of `dir`, so the call also works
/// after `dir` is removed. The function ignores failures.
pub fn remove_gnupg_sockets(dir: &Path) {
    for action in [&["--kill", "all"][..], &["--remove-socketdir"][..]] {
        let _ = Command::new("gpgconf")
            .arg("--homedir")
            .arg(dir)
            .args(action)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status();
    }
}

/// A private GnuPG home that holds one new signing key with no passphrase.
/// A drop of the value stops the GnuPG daemons of the home and removes their
/// socket directory.
#[cfg(feature = "verify-gpg")]
pub struct GnupgHome {
    pub dir: std::path::PathBuf,
}

#[cfg(feature = "verify-gpg")]
impl GnupgHome {
    pub fn new(dir: &Path, uid: &str) -> GnupgHome {
        use std::os::unix::fs::DirBuilderExt;
        std::fs::DirBuilder::new().mode(0o700).create(dir).unwrap();
        let status = std::process::Command::new("gpg")
            .arg("--homedir")
            .arg(dir)
            .args(["--batch", "--pinentry-mode", "loopback", "--passphrase", ""])
            .args(["--quick-gen-key", uid, "ed25519", "sign", "never"])
            .status()
            .unwrap();
        assert!(status.success(), "gpg --quick-gen-key failed");
        GnupgHome {
            dir: dir.to_owned(),
        }
    }

    /// Returns the public certificates of the home, as `gpg --export` writes
    /// them.
    pub fn export(&self) -> Vec<u8> {
        let out = std::process::Command::new("gpg")
            .arg("--homedir")
            .arg(&self.dir)
            .args(["--batch", "--export"])
            .output()
            .unwrap();
        assert!(
            out.status.success() && !out.stdout.is_empty(),
            "gpg --export failed"
        );
        out.stdout
    }
}

#[cfg(feature = "verify-gpg")]
impl Drop for GnupgHome {
    fn drop(&mut self) {
        remove_gnupg_sockets(&self.dir);
    }
}

/// Returns each regular file and symlink under `root/sub`, sorted by path.
///
/// Each entry holds the path relative to `root` and the bytes of the file. For
/// a symlink, the bytes are the target of the symlink.
pub fn file_inventory(root: &Path, sub: &str) -> Vec<(String, Vec<u8>)> {
    let mut out = Vec::new();
    let mut stack = vec![root.join(sub)];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let kind = entry.file_type().unwrap();
            let name = path
                .strip_prefix(root)
                .unwrap()
                .to_string_lossy()
                .into_owned();
            if kind.is_dir() {
                stack.push(path);
            } else if kind.is_symlink() {
                let target = std::fs::read_link(&path).unwrap();
                out.push((name, target.into_os_string().into_encoded_bytes()));
            } else {
                out.push((name, std::fs::read(&path).unwrap()));
            }
        }
    }
    out.sort();
    out
}

/// Marks `commit` as partial in `repo`, as a stopped pull leaves it.
pub fn mark_partial(repo: &ostrya::Repo, commit: &ostrya::Checksum) {
    std::fs::write(
        repo.path().join(format!("state/{commit}.commitpartial")),
        b"",
    )
    .unwrap();
}

/// One entry of field 2 as stored: a name and the bytes of a checksum.
pub type Field2Entry<'a> = (&'a str, &'a [u8]);

/// Stores a copy of the commit `source` with field 2 set to `related`, with
/// no check of the entries, and returns its checksum.
pub async fn store_with_field2(
    repo: &ostrya::Repo,
    source: &ostrya::Checksum,
    related: &[Field2Entry<'_>],
) -> ostrya::Checksum {
    let (mut commit, _) = repo.load_commit(source).await.unwrap();
    commit.related = related
        .iter()
        .map(|(name, bytes)| ((*name).to_owned(), bytes.to_vec()))
        .collect();
    let bytes = commit.serialize().unwrap();
    let txn = repo.transaction().await.unwrap();
    let written = txn
        .write_metadata(ostrya::ObjectType::Commit, None, &bytes)
        .await
        .unwrap();
    txn.commit().await.unwrap();
    written
}

/// Stores a copy of the commit `source` whose field 2 does not decode, and
/// returns its checksum.
///
/// Field 2 of the copy holds one entry, and the name of the entry loses its
/// terminating nul byte. The frame of the commit tuple stays correct.
pub async fn store_with_undecodable_field2(
    repo: &ostrya::Repo,
    source: &ostrya::Checksum,
) -> ostrya::Checksum {
    let name = b"lib/undecodable\0";
    let (mut commit, _) = repo.load_commit(source).await.unwrap();
    commit.related = vec![("lib/undecodable".to_owned(), source.as_bytes().to_vec())];
    let mut bytes = commit.serialize().unwrap();
    let at = bytes
        .windows(name.len())
        .position(|window| window == name)
        .unwrap();
    bytes[at + name.len() - 1] = b'!';
    let txn = repo.transaction().await.unwrap();
    let written = txn
        .write_metadata(ostrya::ObjectType::Commit, None, &bytes)
        .await
        .unwrap();
    txn.commit().await.unwrap();
    written
}

/// Returns the commit and the reason of an [`ostrya::Error::InvalidRelations`]
/// for field 2.
pub fn attachment_error(err: ostrya::Error) -> (Option<ostrya::Checksum>, String) {
    match err {
        ostrya::Error::InvalidRelations {
            commit,
            field: ostrya::RelationField::Attachments,
            reason,
        } => (commit, reason),
        other => panic!("expected InvalidRelations in field 2, got {other:?}"),
    }
}

/// Returns a warning of the attachments of `commit`.
pub fn attachment_warning(commit: ostrya::Checksum, reason: &str) -> ostrya::RelationWarning {
    ostrya::RelationWarning {
        commit,
        field: ostrya::RelationField::Attachments,
        reason: reason.to_owned(),
    }
}

/// The entry name in field 2 of R that names C, in a chain of
/// [`write_chain`].
pub const CHAIN_C: &str = "container/fe";

/// The entry name in field 2 of C that names D, in a chain of
/// [`write_chain`].
pub const CHAIN_D: &str = "details/fe";

/// The entry name in field 2 of R that names A, in a diamond of
/// [`write_diamond`].
pub const DIAMOND_A: &str = "lib/a";

/// The entry name in field 2 of R that names B, in a diamond of
/// [`write_diamond`].
pub const DIAMOND_B: &str = "lib/b";

/// The entry name in field 2 of A and of B that names D, in a diamond of
/// [`write_diamond`].
pub const DIAMOND_D: &str = "lib/d";

/// The commits of a chain of attachments: R names C, and C names D.
pub struct Chain {
    pub r: ostrya::Checksum,
    pub c: ostrya::Checksum,
    pub d: ostrya::Checksum,
}

/// The commits of a diamond of attachments: R names A and B, and A and B
/// each name D.
pub struct Diamond {
    pub r: ostrya::Checksum,
    pub a: ostrya::Checksum,
    pub b: ostrya::Checksum,
    pub d: ostrya::Checksum,
}

/// Writes the chain R -> C -> D into `repo` with the commit write, and
/// returns its commits.
///
/// R names C as [`CHAIN_C`], and C names D as [`CHAIN_D`]. The function
/// writes one commit in each transaction, D first. The trees are under
/// `base`, and their labels start with `branch`, so two chains in one
/// repository have different commits. The function sets `branch` to R. C and
/// D get no ref.
pub async fn write_chain(repo: &ostrya::Repo, base: &Path, branch: &str) -> Chain {
    let d = write_labelled(repo, base, &format!("{branch}-d"), &[], None).await;
    let c = write_labelled(repo, base, &format!("{branch}-c"), &[(CHAIN_D, d)], None).await;
    let r = write_labelled(
        repo,
        base,
        &format!("{branch}-r"),
        &[(CHAIN_C, c)],
        Some(branch),
    )
    .await;
    Chain { r, c, d }
}

/// Writes the diamond of attachments into `repo` with the commit write, and
/// returns its commits.
///
/// R names A as [`DIAMOND_A`] and B as [`DIAMOND_B`], and A and B each name
/// D as [`DIAMOND_D`]. The function writes one commit in each transaction, D
/// first. The trees are under `base`, and their labels start with `branch`.
/// The function sets `branch` to R. A, B, and D get no ref.
pub async fn write_diamond(repo: &ostrya::Repo, base: &Path, branch: &str) -> Diamond {
    let d = write_labelled(repo, base, &format!("{branch}-d"), &[], None).await;
    let a = write_labelled(repo, base, &format!("{branch}-a"), &[(DIAMOND_D, d)], None).await;
    let b = write_labelled(repo, base, &format!("{branch}-b"), &[(DIAMOND_D, d)], None).await;
    let r = write_labelled(
        repo,
        base,
        &format!("{branch}-r"),
        &[(DIAMOND_A, a), (DIAMOND_B, b)],
        Some(branch),
    )
    .await;
    Diamond { r, a, b, d }
}

/// Writes the tree `base/<label>` with one file `payload.txt` that holds
/// `label`, and commits it into `repo` in one transaction with the
/// attachments `attachments`. The subject is `label`. If `branch` is set,
/// the transaction sets `branch` to the commit.
async fn write_labelled(
    repo: &ostrya::Repo,
    base: &Path,
    label: &str,
    attachments: &[(&str, ostrya::Checksum)],
    branch: Option<&str>,
) -> ostrya::Checksum {
    use std::os::fd::AsFd;
    let dir = base.join(label);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("payload.txt"), label).unwrap();
    let txn = repo.transaction().await.unwrap();
    let mut mtree = ostrya::MutableTree::new();
    let mut modifier = ostrya::CommitModifier::new(
        ostrya::CommitModifierFlags::SKIP_XATTRS
            | ostrya::CommitModifierFlags::CANONICAL_PERMISSIONS,
    );
    let dfd = std::fs::File::open(base).unwrap();
    txn.write_dfd_to_mtree(
        dfd.as_fd(),
        Path::new(label),
        &mut mtree,
        Some(&mut modifier),
    )
    .await
    .unwrap();
    let root = txn.write_mtree(&mut mtree).await.unwrap();
    let commit = txn
        .write_commit(
            ostrya::CommitOptions {
                subject: Some(label.to_owned()),
                timestamp: Some(1_700_000_000),
                attachments: attachments
                    .iter()
                    .map(|(name, checksum)| ((*name).to_owned(), *checksum))
                    .collect(),
                ..ostrya::CommitOptions::default()
            },
            &root,
        )
        .await
        .unwrap();
    if let Some(branch) = branch {
        txn.set_ref(&branch.parse::<ostrya::Ref>().unwrap(), Some(&commit));
    }
    txn.commit().await.unwrap();
    commit
}

/// Returns `true` if fs-verity seals the regular file at `path`.
///
/// A sealed file refuses an open for writing. The objects are writable by the
/// owner, so a refusal shows the seal.
pub fn is_sealed(path: &Path) -> bool {
    std::fs::OpenOptions::new().write(true).open(path).is_err()
}

/// Returns the loose objects under `root/objects` that are regular files.
pub fn regular_objects(root: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    for fanout in std::fs::read_dir(root.join("objects")).unwrap().flatten() {
        if !fanout.file_type().unwrap().is_dir() {
            continue;
        }
        for entry in std::fs::read_dir(fanout.path()).unwrap().flatten() {
            if entry.file_type().unwrap().is_file() {
                out.push(entry.path());
            }
        }
    }
    out
}

/// A writer that fails each call of `poll_write`, `poll_flush`, and
/// `poll_close`, and counts the calls.
pub struct Untouchable {
    pub calls: Arc<AtomicU64>,
}

impl Untouchable {
    fn call<T>(&self) -> Poll<io::Result<T>> {
        self.calls.fetch_add(1, Ordering::Relaxed);
        Poll::Ready(Err(io::Error::other("the output must not be used")))
    }
}

impl AsyncWrite for Untouchable {
    fn poll_write(self: Pin<&mut Self>, _: &mut Context<'_>, _: &[u8]) -> Poll<io::Result<usize>> {
        self.call()
    }

    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
        self.call()
    }

    fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
        self.call()
    }
}

/// A writer that counts the bytes it takes.
pub struct Counting<W> {
    pub inner: W,
    pub written: Arc<AtomicU64>,
}

impl<W: AsyncWrite + Unpin> AsyncWrite for Counting<W> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let me = self.get_mut();
        let n = std::task::ready!(Pin::new(&mut me.inner).poll_write(cx, buf))?;
        me.written.fetch_add(n as u64, Ordering::Relaxed);
        Poll::Ready(Ok(n))
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_close(cx)
    }
}

/// A verifier that accepts each blob under its key and records the thread of
/// each call.
///
/// A clone shares the record, so a test keeps a handle on the record after it
/// gives the verifier to a method.
#[derive(Clone)]
pub struct ThreadRecorder {
    /// The detached-metadata key that the verifier reads.
    key: &'static str,
    /// The thread of each call to `verify`, in order.
    threads: Arc<Mutex<Vec<std::thread::ThreadId>>>,
}

impl ThreadRecorder {
    /// Creates a recorder that reads the blobs under `key`.
    pub fn new(key: &'static str) -> ThreadRecorder {
        ThreadRecorder {
            key,
            threads: Arc::default(),
        }
    }

    /// Returns the thread of each call to `verify`, in order.
    pub fn threads(&self) -> Vec<std::thread::ThreadId> {
        self.threads.lock().unwrap().clone()
    }

    /// Asserts that one call to `verify` ran, on a thread other than the
    /// thread of the test.
    pub fn assert_one_foreign_call(&self) {
        let threads = self.threads();
        assert_eq!(threads.len(), 1, "{threads:?}");
        assert_ne!(threads[0], std::thread::current().id());
    }
}

impl ostrya::Verifier for ThreadRecorder {
    fn metadata_key(&self) -> &str {
        self.key
    }

    fn verify(
        &self,
        _data: &[u8],
        signatures: &[Vec<u8>],
    ) -> ostrya::sign::Result<ostrya::VerifyOutcome> {
        self.threads
            .lock()
            .unwrap()
            .push(std::thread::current().id());
        let mut outcome = ostrya::VerifyOutcome::default();
        outcome.valid = !signatures.is_empty();
        Ok(outcome)
    }
}