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
//! Integration tests of the read path on the checked-in fixtures.
//!
//! The `ostree` command wrote the fixture repositories. The tests read objects,
//! refs, and full trees from them and compare the result with the view of the
//! `ostree` command.
//!
//! The fixtures share the object bytes, so the metadata and traversal
//! assertions do not depend on the repository mode. They run on both fixture
//! repositories.
//!
//! The bare-user `load_file` path needs the `user.ostreemeta` xattr. The
//! bare-user fixture is a tarball that keeps this xattr, so these assertions
//! always run. The tests unpack the tarball on demand.

mod common;

use std::path::{Path, PathBuf};

use common::*;
use futures_lite::AsyncReadExt;
use ostrya::{
    Checksum, Commit, CommitState, CreateOptions, FileKind, MAX_METADATA_SIZE, ObjectType, Repo,
    RepoMode, TreeEntry, loose_path,
};
use ostrya_core::{ContentHasher, FileHeader};
use ostrya_rt::block_on;

fn repo_path(mode_dir: &str) -> PathBuf {
    fixture_repo(mode_dir)
}

fn csum(hex: &str) -> Checksum {
    Checksum::from_hex(hex).unwrap()
}

/// Reads the whole payload of a file object through its streaming reader.
async fn read_payload(file: &ostrya::FileObject) -> Vec<u8> {
    let mut reader = file.reader().await.expect("open reader");
    let mut buf = Vec::new();
    reader.read_to_end(&mut buf).await.expect("read payload");
    buf
}

/// Computes the checksum of a file object again from its rebuilt header and
/// its streamed payload.
///
/// The result must equal the object name. A match shows that ostrya reads back
/// exactly the bytes that the `ostree` command wrote.
async fn recomputed_checksum(file: &ostrya::FileObject) -> Checksum {
    match &file.kind {
        FileKind::Regular { .. } => {
            let header = FileHeader {
                uid: file.uid,
                gid: file.gid,
                mode: file.mode,
                symlink_target: String::new(),
                xattrs: file.xattrs.clone(),
            };
            let mut hasher = ContentHasher::new(&header).unwrap();
            hasher.update(&read_payload(file).await);
            hasher.finish()
        }
        FileKind::Symlink { target } => {
            let header = FileHeader {
                uid: file.uid,
                gid: file.gid,
                mode: file.mode,
                symlink_target: target.clone(),
                xattrs: file.xattrs.clone(),
            };
            ContentHasher::new(&header).unwrap().finish()
        }
    }
}

#[test]
fn resolves_and_lists_refs() {
    for mode_dir in ["archive", "bare-user"] {
        block_on(async {
            let repo = Repo::open(&repo_path(mode_dir)).await.expect("open repo");

            assert_eq!(
                repo.resolve_rev("test/main", false).await.unwrap(),
                Some(csum(COMMIT)),
                "{mode_dir}: resolve test/main"
            );
            // A commit checksum alone, as the revision, resolves to itself.
            assert_eq!(
                repo.resolve_rev(COMMIT, false).await.unwrap(),
                Some(csum(COMMIT))
            );
            // If `allow_noent` is `true`, an unknown ref gives `None`. If it is
            // `false`, an unknown ref gives an error.
            assert_eq!(repo.resolve_rev("no/such", true).await.unwrap(), None);
            assert!(repo.resolve_rev("no/such", false).await.is_err());

            let refs = repo.list_refs(None).await.unwrap();
            assert_eq!(refs, vec![("test/main".to_owned(), csum(COMMIT))]);
            // A prefix filter keeps the nested ref.
            assert_eq!(repo.list_refs(Some("test")).await.unwrap(), refs);
            assert!(repo.list_refs(Some("other")).await.unwrap().is_empty());
        });
    }
}

#[test]
fn loads_commit_dirtree_and_dirmeta() {
    for mode_dir in ["archive", "bare-user"] {
        block_on(async {
            let repo = Repo::open(&repo_path(mode_dir)).await.expect("open repo");

            let (commit, state) = repo.load_commit(&csum(COMMIT)).await.unwrap();
            assert_eq!(state, CommitState::Normal);
            assert_eq!(commit.root_dirtree, csum(ROOT_DIRTREE));
            assert_eq!(commit.root_dirmeta, csum(ROOT_DIRMETA));
            assert_eq!(commit.timestamp, 1_700_000_000);
            assert_eq!(commit.content_checksum(), csum(CONTENT));

            // `load_commit_with_bytes` gives the same commit and state, and the
            // bytes that `load_object_bytes` gives.
            let (with_bytes, with_state, bytes) =
                repo.load_commit_with_bytes(&csum(COMMIT)).await.unwrap();
            assert_eq!((&with_bytes, with_state), (&commit, state));
            let raw = repo
                .load_object_bytes(ObjectType::Commit, &csum(COMMIT))
                .await
                .unwrap();
            assert_eq!(bytes, raw);
            assert_eq!(Commit::parse(&bytes).unwrap(), commit);

            let root = repo.load_dirtree(&csum(ROOT_DIRTREE)).await.unwrap();
            let files: Vec<&str> = root.files.iter().map(|(n, _)| n.as_str()).collect();
            assert_eq!(files, ["empty.txt", "hello.txt", "link"]);
            let dirs: Vec<&str> = root.dirs.iter().map(|(n, _, _)| n.as_str()).collect();
            assert_eq!(dirs, ["subdir"]);

            let meta = repo.load_dirmeta(&csum(ROOT_DIRMETA)).await.unwrap();
            // `ostree ls` shows the root as d00755, owned by 0:0.
            assert_eq!((meta.uid, meta.gid, meta.mode), (0, 0, 0o40755));

            assert!(
                repo.has_object(ObjectType::Commit, &csum(COMMIT))
                    .await
                    .unwrap()
            );
            assert!(
                !repo
                    .has_object(ObjectType::Commit, &csum(&"00".repeat(32)))
                    .await
                    .unwrap()
            );

            // A missing object gives `Error::ObjectNotFound`, a variant of its
            // own. A plain I/O error does not pass this assertion.
            let err = repo
                .load_dirtree(&csum(&"11".repeat(32)))
                .await
                .unwrap_err();
            assert!(matches!(err, ostrya::Error::ObjectNotFound { .. }));

            // `load_variant` returns the dynamic tree of a metadata object.
            let value = repo
                .load_variant(ObjectType::DirMeta, &csum(ROOT_DIRMETA))
                .await
                .unwrap();
            assert!(value.as_tuple().is_some());
        });
    }
}

/// Both commit loads give the `Partial` state of a commit with a
/// `.commitpartial` marker, and the bytes stay the bytes of the object.
#[test]
fn loads_a_partial_commit_with_its_bytes() {
    let tmp = TmpDir::new("read-partial-commit");
    block_on(async {
        let fixture = Repo::open(&repo_path("archive"))
            .await
            .expect("open fixture");
        let key = csum(COMMIT);
        let raw = fixture
            .load_object_bytes(ObjectType::Commit, &key)
            .await
            .unwrap();

        let repo_dir = tmp.path().join("repo");
        let repo = Repo::create(&repo_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .expect("create repo");
        let path = place_sparse_object(&repo_dir, repo.mode(), &key, 0);
        std::fs::write(&path, &raw).expect("copy the commit object");
        mark_partial(&repo, &key);

        let (commit, state) = repo.load_commit(&key).await.unwrap();
        assert_eq!(state, CommitState::Partial);
        let (with_bytes, with_state, bytes) = repo.load_commit_with_bytes(&key).await.unwrap();
        assert_eq!(with_state, CommitState::Partial);
        assert_eq!(with_bytes, commit);
        assert_eq!(bytes, raw);
    });
}

/// Both commit loads refuse an absent commit, bytes that do not parse, and an
/// object larger than the cap, with the same error.
#[test]
fn commit_loads_refuse_with_the_same_error() {
    let tmp = TmpDir::new("read-commit-refusals");
    block_on(async {
        let repo_dir = tmp.path().join("repo");
        let repo = Repo::create(&repo_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .expect("create repo");

        let absent = csum(&"55".repeat(32));
        let garbage = csum(&"66".repeat(32));
        let path = place_sparse_object(&repo_dir, repo.mode(), &garbage, 0);
        std::fs::write(&path, b"not a commit").expect("write the garbage object");
        let oversized = csum(&"77".repeat(32));
        place_sparse_object(&repo_dir, repo.mode(), &oversized, MAX_METADATA_SIZE + 1);

        for key in [absent, garbage, oversized] {
            let err = repo
                .load_commit(&key)
                .await
                .expect_err("load_commit refuses the object");
            let with_bytes = repo
                .load_commit_with_bytes(&key)
                .await
                .expect_err("load_commit_with_bytes refuses the object");
            assert_eq!(with_bytes.to_string(), err.to_string());
            let expected = |e: &ostrya::Error| {
                if key == absent {
                    matches!(e, ostrya::Error::ObjectNotFound { .. })
                } else if key == garbage {
                    matches!(e, ostrya::Error::Core(_))
                } else {
                    matches!(e, ostrya::Error::InvalidFormat(m)
                        if m.ends_with("is larger than its cap of 134217728 bytes"))
                }
            };
            assert!(
                expected(&err),
                "load_commit {key}: unexpected error {err:?}"
            );
            assert!(
                expected(&with_bytes),
                "load_commit_with_bytes {key}: unexpected error {with_bytes:?}"
            );
        }
    });
}

#[test]
fn traverses_the_commit_tree() {
    for mode_dir in ["archive", "bare-user"] {
        block_on(async {
            let repo = Repo::open(&repo_path(mode_dir)).await.expect("open repo");
            let (root, commit) = repo.read_commit("test/main").await.unwrap();
            assert_eq!(commit, csum(COMMIT));
            assert_eq!(root.dirtree_checksum(), &csum(ROOT_DIRTREE));

            // `read_dir` returns the files first, then the directories. Each
            // group is in name order.
            let entries = root.read_dir().await.unwrap();
            let names: Vec<&str> = entries
                .iter()
                .map(|e| match e {
                    TreeEntry::File { name, .. } => name.as_str(),
                    TreeEntry::Dir { name, .. } => name.as_str(),
                })
                .collect();
            assert_eq!(names, ["empty.txt", "hello.txt", "link", "subdir"]);

            // Descend into the subdirectory.
            let TreeEntry::Dir { tree: subdir, .. } = &entries[3] else {
                panic!("subdir entry is not a directory");
            };
            assert_eq!(subdir.dirtree_checksum(), &csum(SUBDIR_DIRTREE));
            let nested = subdir.read_dir().await.unwrap();
            assert_eq!(nested.len(), 1);
            assert!(matches!(&nested[0], TreeEntry::File { name, checksum }
                if name == "nested.txt" && *checksum == csum(NESTED_TXT)));

            // `lookup` resolves files, nested files, directories, and symlinks.
            assert!(matches!(
                root.lookup(Path::new("hello.txt")).await.unwrap(),
                Some(TreeEntry::File { checksum, .. }) if checksum == csum(HELLO_TXT)
            ));
            assert!(matches!(
                root.lookup(Path::new("subdir/nested.txt")).await.unwrap(),
                Some(TreeEntry::File { checksum, .. }) if checksum == csum(NESTED_TXT)
            ));
            assert!(matches!(
                root.lookup(Path::new("subdir")).await.unwrap(),
                Some(TreeEntry::Dir { .. })
            ));
            assert!(matches!(
                root.lookup(Path::new("link")).await.unwrap(),
                Some(TreeEntry::File { checksum, .. }) if checksum == csum(LINK)
            ));
            // A missing entry resolves to `None`. A path through a file also
            // resolves to `None`.
            assert!(root.lookup(Path::new("missing")).await.unwrap().is_none());
            assert!(
                root.lookup(Path::new("hello.txt/x"))
                    .await
                    .unwrap()
                    .is_none()
            );
        });
    }
}

#[test]
fn reads_archive_file_content() {
    block_on(async {
        let repo = Repo::open(&repo_path("archive")).await.expect("open repo");
        assert_eq!(repo.mode(), RepoMode::Archive);

        let hello = repo.load_file(&csum(HELLO_TXT)).await.unwrap();
        assert_eq!(hello.mode, 0o100644);
        assert_eq!(hello.kind, FileKind::Regular { size: 13 });
        assert!(hello.xattrs.is_empty());
        assert_eq!(read_payload(&hello).await, b"hello ostree\n");
        assert_eq!(recomputed_checksum(&hello).await, csum(HELLO_TXT));

        let empty = repo.load_file(&csum(EMPTY_TXT)).await.unwrap();
        assert_eq!(empty.kind, FileKind::Regular { size: 0 });
        assert_eq!(read_payload(&empty).await, b"");
        assert_eq!(recomputed_checksum(&empty).await, csum(EMPTY_TXT));

        let nested = repo.load_file(&csum(NESTED_TXT)).await.unwrap();
        assert_eq!(read_payload(&nested).await, b"nested\n");

        let link = repo.load_file(&csum(LINK)).await.unwrap();
        assert_eq!(link.mode, 0o120777);
        assert_eq!(
            link.kind,
            FileKind::Symlink {
                target: "hello.txt".to_owned()
            }
        );
        assert!(link.is_symlink());
        // A symlink has no payload.
        assert_eq!(read_payload(&link).await, b"");
        assert_eq!(recomputed_checksum(&link).await, csum(LINK));
    });
}

/// If the compressed stream of an archive object is far longer than its
/// payload, the object still reads back whole.
///
/// The test pads the stream of an empty file with empty stored blocks. The
/// stream still inflates to no bytes, and the object keeps its checksum.
#[test]
fn reads_an_archive_object_with_a_padded_stream() {
    let tmp = TmpDir::new("read-archive-padded");
    let root = tmp.path().join("repo");
    block_on(async {
        let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let txn = repo.transaction().await.unwrap();
        let checksum = txn
            .write_content(
                None,
                &ostrya::FileMeta::regular(0, 0, 0o644),
                futures_lite::io::Cursor::new(Vec::new()),
            )
            .await
            .unwrap();
        txn.commit().await.unwrap();

        let path =
            root.join("objects")
                .join(loose_path(&checksum, ObjectType::File, RepoMode::Archive));
        let stored = std::fs::read(&path).unwrap();
        let header_len = u32::from_be_bytes(stored[..4].try_into().unwrap()) as usize;
        let (header, stream) = stored.split_at(8 + header_len);
        // A non-final stored block of no bytes: the block header, then LEN 0
        // and NLEN 0xffff.
        let empty_block = [0x00u8, 0x00, 0x00, 0xff, 0xff];
        let mut padded = header.to_vec();
        for _ in 0..400_000 {
            padded.extend_from_slice(&empty_block);
        }
        padded.extend_from_slice(stream);
        std::fs::remove_file(&path).unwrap();
        std::fs::write(&path, &padded).unwrap();

        let file = repo.load_file(&checksum).await.unwrap();
        assert_eq!(file.kind, FileKind::Regular { size: 0 });
        assert_eq!(read_payload(&file).await, b"");
        assert_eq!(recomputed_checksum(&file).await, checksum);
    });
}

#[test]
fn reads_bare_user_file_content() {
    // The bare-user fixture tarball keeps the `user.ostreemeta` xattr that these
    // objects need, so this cross-check always runs.
    block_on(async {
        let repo = Repo::open(&repo_path("bare-user"))
            .await
            .expect("open repo");
        assert_eq!(repo.mode(), RepoMode::BareUser);

        let hello = repo.load_file(&csum(HELLO_TXT)).await.unwrap();
        assert_eq!(hello.mode, 0o100644);
        assert_eq!(hello.kind, FileKind::Regular { size: 13 });
        assert_eq!(read_payload(&hello).await, b"hello ostree\n");
        assert_eq!(recomputed_checksum(&hello).await, csum(HELLO_TXT));

        let link = repo.load_file(&csum(LINK)).await.unwrap();
        assert_eq!(
            link.kind,
            FileKind::Symlink {
                target: "hello.txt".to_owned()
            }
        );
        assert_eq!(recomputed_checksum(&link).await, csum(LINK));

        let empty = repo.load_file(&csum(EMPTY_TXT)).await.unwrap();
        assert_eq!(empty.kind, FileKind::Regular { size: 0 });
        assert_eq!(read_payload(&empty).await, b"");
    });
}

/// Places a file of `size` bytes at the loose path of a commit object under
/// `repo_dir`, and returns that path.
///
/// `set_len` is `ftruncate`, so the file reads back as zeros and the test writes
/// no payload. As a result, a size at the metadata cap uses no disk space.
fn place_sparse_object(repo_dir: &Path, mode: RepoMode, checksum: &Checksum, size: u64) -> PathBuf {
    let path = repo_dir
        .join("objects")
        .join(loose_path(checksum, ObjectType::Commit, mode));
    std::fs::create_dir_all(
        path.parent()
            .expect("the loose path has a prefix directory"),
    )
    .expect("create the object prefix directory");
    let file = std::fs::File::create(&path).expect("create the loose object");
    file.set_len(size).expect("size the loose object");
    path
}

/// The streaming reader returns exactly the bytes that the buffered loader
/// returns, for each chunk size that the caller reads with.
#[test]
fn streams_a_metadata_object_in_chunks() {
    for mode_dir in ["archive", "bare-user"] {
        block_on(async {
            let repo = Repo::open(&repo_path(mode_dir)).await.expect("open repo");

            let buffered = repo
                .load_object_bytes(ObjectType::Commit, &csum(COMMIT))
                .await
                .expect("load the commit bytes");
            assert!(
                !buffered.is_empty(),
                "{mode_dir}: the commit object carries bytes"
            );

            let mut reader = repo
                .metadata_reader(ObjectType::Commit, &csum(COMMIT))
                .await
                .expect("open the metadata reader");
            // An empty buffer takes no bytes and does not move the position.
            // The reads that follow still return the whole object.
            assert_eq!(
                reader
                    .read(&mut [])
                    .await
                    .expect("read into an empty buffer"),
                0,
                "{mode_dir}: an empty buffer takes nothing"
            );

            // The chunk is far smaller than the object, so the assertion covers
            // many reads and a partial last read.
            let mut chunk = [0u8; 7];
            let mut streamed = Vec::new();
            loop {
                let n = reader.read(&mut chunk).await.expect("read a chunk");
                if n == 0 {
                    break;
                }
                assert!(
                    n <= chunk.len(),
                    "{mode_dir}: a read stays inside the buffer"
                );
                streamed.extend_from_slice(&chunk[..n]);
            }
            assert_eq!(streamed, buffered, "{mode_dir}: streamed commit bytes");

            // A missing object gives the refusal of the buffered loader.
            // `MetadataReader` has no `Debug` implementation, the same as
            // `ContentReader`. `unwrap_err` needs `Debug`, so the test takes the
            // refusal with a `match`.
            let err = match repo
                .metadata_reader(ObjectType::Commit, &csum(&"11".repeat(32)))
                .await
            {
                Ok(_) => panic!("{mode_dir}: a missing object opened a reader"),
                Err(e) => e,
            };
            assert!(
                matches!(err, ostrya::Error::ObjectNotFound { .. }),
                "{mode_dir}: a missing object is ObjectNotFound, got {err:?}"
            );
        });
    }
}

/// If the `statx` of the open measures an object larger than the cap, the open
/// refuses it. The error is the same error that the buffered loader gives for
/// the object.
#[test]
fn metadata_reader_refuses_an_oversized_object_at_the_open() {
    let tmp = TmpDir::new("meta-cap-open");
    block_on(async {
        let repo_dir = tmp.path().join("repo");
        let repo = Repo::create(&repo_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .expect("create repo");
        let key = csum(&"22".repeat(32));
        place_sparse_object(&repo_dir, repo.mode(), &key, MAX_METADATA_SIZE + 1);

        let err = match repo.metadata_reader(ObjectType::Commit, &key).await {
            Ok(_) => panic!("the open accepted an oversized object"),
            Err(e) => e,
        };
        let ostrya::Error::InvalidFormat(message) = &err else {
            panic!("expected an invalid format refusal, got {err:?}");
        };
        assert_eq!(
            message,
            &format!(
                "objects/{} is larger than its cap of 134217728 bytes",
                ostrya::loose_path(&key, ObjectType::Commit, repo.mode())
            )
        );

        // The buffered loader refuses the same object with the same message, so
        // the two paths agree.
        let buffered = repo
            .load_object_bytes(ObjectType::Commit, &key)
            .await
            .expect_err("the buffered loader refuses an oversized object");
        assert_eq!(buffered.to_string(), err.to_string());
    });
}

/// Under the `tokio` backend, the reader also implements the tokio I/O traits.
///
/// The test calls that implementation directly, with `poll_read` over a
/// `ReadBuf`. Each read must move the filled region forward by exactly the bytes
/// that it wrote. If the count is wrong, the stream drops or duplicates bytes,
/// and it differs from the buffered loader.
#[cfg(feature = "tokio")]
#[test]
fn streams_a_metadata_object_through_the_tokio_trait() {
    use ostrya_rt::tokio_io::{AsyncRead, ReadBuf};
    use std::pin::Pin;
    use std::task::Poll;

    block_on(async {
        let repo = Repo::open(&repo_path("archive")).await.expect("open repo");
        let buffered = repo
            .load_object_bytes(ObjectType::Commit, &csum(COMMIT))
            .await
            .expect("load the commit bytes");
        let mut reader = repo
            .metadata_reader(ObjectType::Commit, &csum(COMMIT))
            .await
            .expect("open the metadata reader");

        let mut streamed = Vec::new();
        loop {
            // The chunk is far smaller than the object, so the assertion covers
            // many reads and a partial last read.
            let mut raw = [0u8; 7];
            let taken = futures_lite::future::poll_fn(|cx| {
                // Each poll gets a new `ReadBuf`. A `Pending` poll fills
                // nothing, so the new buffer loses no byte.
                let mut buf = ReadBuf::new(&mut raw);
                match Pin::new(&mut reader).poll_read(cx, &mut buf) {
                    Poll::Ready(Ok(())) => Poll::Ready(Ok(buf.filled().len())),
                    Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
                    Poll::Pending => Poll::Pending,
                }
            })
            .await
            .expect("read a chunk through the tokio trait");
            if taken == 0 {
                break;
            }
            streamed.extend_from_slice(&raw[..taken]);
        }
        assert_eq!(streamed, buffered, "tokio-trait streamed commit bytes");
    });
}

/// An object of exactly `MAX_METADATA_SIZE` bytes is inside the cap.
///
/// The streaming reader returns every byte and then ends at `Ok(0)`. The
/// buffered loader also accepts the object, so the two paths put the bound on
/// the same byte.
#[test]
fn metadata_reader_reads_an_object_at_exactly_the_cap() {
    let tmp = TmpDir::new("meta-cap-exact");
    block_on(async {
        let repo_dir = tmp.path().join("repo");
        let repo = Repo::create(&repo_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .expect("create repo");
        let key = csum(&"44".repeat(32));
        place_sparse_object(&repo_dir, repo.mode(), &key, MAX_METADATA_SIZE);

        let mut reader = repo
            .metadata_reader(ObjectType::Commit, &key)
            .await
            .expect("an object at the cap opens a reader");
        // The chunk size does not divide the cap, so the last read with data
        // is a partial read.
        let mut chunk = vec![0u8; 1024 * 1024 - 1];
        let mut taken: u64 = 0;
        loop {
            let n = reader
                .read(&mut chunk)
                .await
                .expect("an object at the cap reads through");
            if n == 0 {
                break;
            }
            taken += n as u64;
        }
        assert_eq!(
            taken, MAX_METADATA_SIZE,
            "the reader hands over every byte of an object at the cap"
        );
        // The end of file is stable. Each repeated read at the cap finds no
        // more bytes.
        for round in 0..3 {
            assert_eq!(
                reader.read(&mut chunk).await.expect("read past the end"),
                0,
                "read {round} past the end of an object at the cap"
            );
        }

        // The buffered loader accepts the same object, so neither path refuses
        // at the cap itself.
        let buffered = repo
            .load_object_bytes(ObjectType::Commit, &key)
            .await
            .expect("the buffered loader takes an object at the cap");
        assert_eq!(buffered.len() as u64, MAX_METADATA_SIZE);
    });
}

/// If an object grows past the cap while the reader is open, the running total
/// refuses the object.
///
/// The reader returns no more than `MAX_METADATA_SIZE` bytes before the refusal.
#[test]
fn metadata_reader_refuses_an_object_that_grows_past_the_cap() {
    let tmp = TmpDir::new("meta-cap-grow");
    block_on(async {
        let repo_dir = tmp.path().join("repo");
        let repo = Repo::create(&repo_dir, CreateOptions::new(RepoMode::Archive))
            .await
            .expect("create repo");
        let key = csum(&"33".repeat(32));
        // The size is one byte under the cap, so the `statx` at the open passes.
        let path = place_sparse_object(&repo_dir, repo.mode(), &key, MAX_METADATA_SIZE - 1);
        let mut reader = repo
            .metadata_reader(ObjectType::Commit, &key)
            .await
            .expect("open the metadata reader");

        // Grow the object past the cap before the first read. This acts as a
        // writer that races the reader.
        std::fs::OpenOptions::new()
            .write(true)
            .open(&path)
            .expect("reopen the loose object for writing")
            .set_len(MAX_METADATA_SIZE + 1)
            .expect("grow the loose object past the cap");

        // The chunk size does not divide the cap, so the last read before the
        // cap asks for more bytes than the cap leaves. If the reader has no
        // clamp, that read carries the total past the cap. The assertion on
        // each read catches this.
        let mut chunk = vec![0u8; 1024 * 1024 - 1];
        let mut taken: u64 = 0;
        let err = loop {
            match reader.read(&mut chunk).await {
                Ok(0) => panic!("the reader reported end of file after {taken} bytes"),
                Ok(n) => {
                    taken += n as u64;
                    assert!(
                        taken <= MAX_METADATA_SIZE,
                        "the reader handed over {taken} bytes, above the cap"
                    );
                }
                Err(e) => break e,
            }
        };
        let expected = format!(
            "objects/{} is larger than its cap of 134217728 bytes",
            ostrya::loose_path(&key, ObjectType::Commit, repo.mode())
        );
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
        assert_eq!(err.to_string(), expected);
        assert_eq!(
            taken, MAX_METADATA_SIZE,
            "the reader stops at the cap, having handed over every byte up to it"
        );

        // The refusal is terminal. Each later read gives the same error and
        // never a clean end of file. A clean end of file presents the object as
        // an object that ends at the cap.
        for round in 0..3 {
            match reader.read(&mut chunk).await {
                Ok(n) => panic!("read {round} after the refusal returned {n} bytes"),
                Err(again) => {
                    assert_eq!(again.kind(), std::io::ErrorKind::InvalidData);
                    assert_eq!(again.to_string(), expected);
                }
            }
        }
    });
}

#[test]
fn matches_the_tool_cat_and_ls() {
    // If the `ostree` command is on `PATH`, the test compares ostrya with it
    // live. The bytes that ostrya reads from the archive fixture must equal the
    // output of the `ostree` command. The archive fixture needs no xattrs, so
    // this test is self-contained.
    if !ostree_available() {
        eprintln!("skipping tool cross-check: ostree not on PATH");
        return;
    }
    let repo_dir = repo_path("archive");
    let repo_arg = format!("--repo={}", repo_dir.display());

    let cat = |path: &str| -> Vec<u8> {
        let out = std::process::Command::new("ostree")
            .arg(&repo_arg)
            .args(["cat", "test/main", path])
            .output()
            .expect("run ostree cat");
        assert!(out.status.success(), "ostree cat {path} failed");
        out.stdout
    };

    block_on(async {
        let repo = Repo::open(&repo_dir).await.expect("open repo");
        let (root, _) = repo.read_commit("test/main").await.unwrap();

        for path in ["/hello.txt", "/empty.txt", "/subdir/nested.txt"] {
            let entry = root
                .lookup(Path::new(path.trim_start_matches('/')))
                .await
                .unwrap()
                .expect("entry present");
            let TreeEntry::File { checksum, .. } = entry else {
                panic!("{path} is not a file");
            };
            let file = repo.load_file(&checksum).await.unwrap();
            assert_eq!(read_payload(&file).await, cat(path), "content of {path}");
        }

        // The symlink target that `ostree ls` shows matches the target that
        // ostrya reads.
        let link = repo.load_file(&csum(LINK)).await.unwrap();
        let ls = std::process::Command::new("ostree")
            .arg(&repo_arg)
            .args(["ls", "test/main", "/link"])
            .output()
            .expect("run ostree ls");
        let ls = String::from_utf8_lossy(&ls.stdout);
        assert!(ls.contains("-> hello.txt"), "tool ls: {ls}");
        assert_eq!(
            link.kind,
            FileKind::Symlink {
                target: "hello.txt".to_owned()
            }
        );
    });
}