ostrya 0.4.0

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
//! The objects of a local repository, as a push session reads them.

use futures_lite::io::Cursor;
use ostrya_core::{Checksum, FileHeader, ObjectName, ObjectType, Value, loose_path};
use ostrya_rt::FileReader;

use crate::error::{Error, Result};
use crate::file::FileKind;
use crate::object;
use crate::pull::DetachedMetadataFilter;
use crate::remote::{BoxFuture, DetachedMetadata, Encoding, ObjectData, ObjectSource};
use crate::repo::Repo;

/// The [`ObjectSource`] over a local repository.
///
/// A metadata object is [`ObjectData::Encoded`] in `raw`. The source reads it
/// whole, because the format caps its size.
///
/// If the encoding is `deflate` and the repository is in `archive` mode, a file
/// object is [`ObjectData::Encoded`] in `deflate`. Its reader is a stream over
/// the stored `.filez` file, byte for byte. Every other file object is
/// [`ObjectData::Content`], with the file header and a stream over its payload.
/// The session encodes it.
///
/// The source holds no file content in memory and keeps no reader between
/// calls. [`content_size`](ObjectSource::content_size) reads the metadata of
/// each file object in one pass on the blocking pool. It reads no payload byte.
///
/// The source applies the filter to the detached metadata of a commit. It
/// gives the detached metadata as [`DetachedMetadata::Encoded`]. If the filter
/// is unset or keeps each property, these are the bytes of the stored
/// `.commitmeta` unchanged, so the session sends them with no parse or
/// serialization of its own. With an unset filter, the source does not parse
/// the `.commitmeta`, and the server checks it.
pub(crate) struct RepoSource {
    repo: Repo,
    filter: DetachedMetadataFilter,
}

impl RepoSource {
    /// Creates the source over `repo`. The detached metadata passes through
    /// `filter`.
    pub(crate) fn new(repo: Repo, filter: DetachedMetadataFilter) -> RepoSource {
        RepoSource { repo, filter }
    }

    async fn load(&self, name: &ObjectName, encoding: Encoding) -> Result<ObjectData> {
        if name.ty != ObjectType::File {
            let bytes = self.repo.load_object_bytes(name.ty, &name.checksum).await?;
            return Ok(ObjectData::Encoded {
                encoding: Encoding::Raw,
                reader: Box::new(Cursor::new(bytes)),
            });
        }
        if encoding == Encoding::Deflate && self.repo.mode().is_archive() {
            return self.stored_filez(&name.checksum).await;
        }
        let (file, reader) = self.repo.open_file(&name.checksum).await?;
        let (size, payload, symlink_target) = match file.kind {
            FileKind::Regular { size } => (size, Some(Box::new(reader) as _), String::new()),
            FileKind::Symlink { target } => (0, None, target),
        };
        Ok(ObjectData::Content {
            header: FileHeader {
                uid: file.uid,
                gid: file.gid,
                mode: file.mode,
                symlink_target,
                xattrs: file.xattrs,
            },
            size,
            payload,
        })
    }

    /// Returns the number of content bytes of the file objects of `names` in
    /// `encoding`. The count runs in one pass on the blocking pool. The pass
    /// mirrors [`load`]: a stored `.filez` counts its size, and each other
    /// object counts the size of its payload.
    ///
    /// [`load`]: RepoSource::load
    async fn content_total(&self, names: &[ObjectName], encoding: Encoding) -> Result<u64> {
        let checksums: Vec<Checksum> = names
            .iter()
            .filter(|n| n.ty == ObjectType::File)
            .map(|n| n.checksum)
            .collect();
        let stored = encoding == Encoding::Deflate && self.repo.mode().is_archive();
        let repo = self.repo.clone();
        ostrya_rt::unblock(move || repo.content_size_blocking(&checksums, stored)).await
    }

    /// Opens a stream over the stored `.filez` file of the file object
    /// `checksum`.
    async fn stored_filez(&self, checksum: &Checksum) -> Result<ObjectData> {
        let path = loose_path(checksum, ObjectType::File, self.repo.mode());
        let repo = self.repo.clone();
        // The size bounds the read-ahead. The `fstat` runs on the pool
        // thread of the open.
        let opened = ostrya_rt::unblock(move || {
            let file = object::open_content_file(repo.objects_fd(), &path, 0)?;
            let len = file.metadata()?.len();
            Ok::<_, std::io::Error>((file, len))
        })
        .await;
        let (file, len) = match opened {
            Ok(opened) => opened,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Err(Error::ObjectNotFound {
                    checksum: *checksum,
                    ty: ObjectType::File,
                });
            }
            Err(e) => return Err(Error::Io(e)),
        };
        Ok(ObjectData::Encoded {
            encoding: Encoding::Deflate,
            reader: Box::new(FileReader::with_len_hint(file, len)),
        })
    }

    /// Returns the detached metadata of `commit` that the filter allows. If the
    /// commit has none or the filter allows no property, returns `None`.
    ///
    /// The read, the parse, and the filter run in one call on the blocking
    /// pool.
    async fn detached(&self, commit: &Checksum) -> Result<Option<Value>> {
        let repo = self.repo.clone();
        let filter = self.filter.clone();
        let commit = *commit;
        ostrya_rt::unblock(
            move || match repo.read_commit_detached_metadata_blocking(&commit)? {
                Some(dict) => filter.apply_value(&commit, dict),
                None => Ok(None),
            },
        )
        .await
    }

    /// Returns the bytes of the detached metadata of `commit` that the filter
    /// allows. If the commit has none or the filter allows no property,
    /// returns `None`.
    ///
    /// An unset filter gives the bytes of the stored `.commitmeta` unchanged,
    /// and the call does not parse them. So a `.commitmeta` that is not an
    /// `a{sv}` dict goes to the server as it is, and the server refuses it
    /// with the code `protocol`. A set filter parses the file: a filter that
    /// keeps each property gives the bytes unchanged, and a filter that keeps
    /// some of the properties gives their normal form. With a set filter, a
    /// `.commitmeta` that is not an `a{sv}` dict gives [`Error::Core`], as
    /// [`detached`](RepoSource::detached) does. The read, the parse, the
    /// filter, and the serialization of a partial result run in one call on
    /// the blocking pool.
    async fn detached_bytes(&self, commit: &Checksum) -> Result<Option<Vec<u8>>> {
        let repo = self.repo.clone();
        let filter = self.filter.clone();
        let commit = *commit;
        ostrya_rt::unblock(move || {
            let bytes = match repo.load_object_bytes_blocking(ObjectType::CommitMeta, &commit) {
                Ok(bytes) => bytes,
                Err(Error::ObjectNotFound { .. }) => return Ok(None),
                Err(e) => return Err(e),
            };
            // A zero-length file marks no metadata, so the session sends
            // nothing for it.
            if bytes.is_empty() {
                return Ok(None);
            }
            filter.apply(&commit, bytes)
        })
        .await
    }
}

fn source_error(e: Error) -> crate::remote::Error {
    crate::remote::Error::Source(Box::new(e))
}

impl ObjectSource for RepoSource {
    fn objects<'a>(
        &'a self,
        commit: &'a Checksum,
    ) -> BoxFuture<'a, crate::remote::Result<Vec<ObjectName>>> {
        Box::pin(async move {
            let names = self
                .repo
                .traverse_commit(commit, 0)
                .await
                .map_err(source_error)?;
            Ok(names.into_iter().collect())
        })
    }

    fn open<'a>(
        &'a self,
        name: &'a ObjectName,
        encoding: Encoding,
    ) -> BoxFuture<'a, crate::remote::Result<ObjectData>> {
        Box::pin(async move { self.load(name, encoding).await.map_err(source_error) })
    }

    fn detached_metadata<'a>(
        &'a self,
        commit: &'a Checksum,
    ) -> BoxFuture<'a, crate::remote::Result<Option<Value>>> {
        Box::pin(async move { self.detached(commit).await.map_err(source_error) })
    }

    fn detached_metadata_encoded<'a>(
        &'a self,
        commit: &'a Checksum,
    ) -> BoxFuture<'a, crate::remote::Result<Option<DetachedMetadata>>> {
        Box::pin(async move {
            self.detached_bytes(commit)
                .await
                .map(|bytes| bytes.map(DetachedMetadata::Encoded))
                .map_err(source_error)
        })
    }

    fn content_size<'a>(
        &'a self,
        names: &'a [ObjectName],
        encoding: Encoding,
    ) -> BoxFuture<'a, crate::remote::Result<Option<u64>>> {
        Box::pin(async move {
            self.content_total(names, encoding)
                .await
                .map(Some)
                .map_err(source_error)
        })
    }
}

/// Pins at compile time that the source and its filter are `Send` and `Sync`,
/// so they can move across tasks and threads.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<RepoSource>();
    assert_send_sync::<DetachedMetadataFilter>();
};

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use futures_lite::AsyncReadExt;
    use ostrya_core::{DictBuilder, RepoMode};

    use super::super::test_repo::{Scratch, commit_tree};
    use super::*;

    /// Creates a repository of `mode` with one commit on `main`. Returns the
    /// scratch directory, the repository, and the commit.
    async fn fixture(label: &str, mode: RepoMode) -> (Scratch, Repo, Checksum) {
        let scratch = Scratch::new(label);
        let repo = scratch.create(mode).await;
        let commit = commit_tree(&repo, &scratch, "main", None, b"file content\n").await;
        (scratch, repo, commit)
    }

    /// Returns the file objects of `commit`: the regular file and the symlink.
    async fn file_objects(repo: &Repo, commit: &Checksum) -> (ObjectName, ObjectName) {
        let mut regular = None;
        let mut symlink = None;
        for name in repo.traverse_commit(commit, 0).await.unwrap() {
            if name.ty != ObjectType::File {
                continue;
            }
            match repo.load_file(&name.checksum).await.unwrap().kind {
                FileKind::Regular { .. } => regular = Some(name),
                FileKind::Symlink { .. } => symlink = Some(name),
            }
        }
        (regular.unwrap(), symlink.unwrap())
    }

    fn stored(scratch: &Scratch, repo: &Repo, name: &ObjectName) -> Vec<u8> {
        let path = loose_path(&name.checksum, name.ty, repo.mode());
        std::fs::read(scratch.path().join("repo/objects").join(path)).unwrap()
    }

    async fn read_all(mut reader: Box<dyn crate::remote::ObjectReader>) -> Vec<u8> {
        let mut out = Vec::new();
        reader.read_to_end(&mut out).await.unwrap();
        out
    }

    fn source(repo: &Repo) -> RepoSource {
        RepoSource::new(repo.clone(), DetachedMetadataFilter::default())
    }

    fn keys(dict: &Value) -> Vec<&str> {
        dict.as_array()
            .unwrap()
            .iter()
            .map(|entry| entry.as_tuple().unwrap()[0].as_str().unwrap())
            .collect()
    }

    #[test]
    fn the_objects_are_the_commit_and_its_tree() {
        ostrya_rt::block_on(async {
            let (scratch, repo, first) = fixture("objects", RepoMode::Archive).await;
            let commit = commit_tree(&repo, &scratch, "main", Some(first), b"other\n").await;
            let (loaded, _) = repo.load_commit(&commit).await.unwrap();
            assert_eq!(loaded.parent, Some(first));
            let tree = repo.load_dirtree(&loaded.root_dirtree).await.unwrap();
            assert!(tree.dirs.is_empty());
            let names: Vec<&str> = tree.files.iter().map(|(name, _)| name.as_str()).collect();
            assert_eq!(names, ["file", "link"]);

            let name = |checksum, ty| ObjectName { checksum, ty };
            let mut expected = HashSet::from([
                name(commit, ObjectType::Commit),
                name(loaded.root_dirtree, ObjectType::DirTree),
                name(loaded.root_dirmeta, ObjectType::DirMeta),
            ]);
            expected.extend(tree.files.iter().map(|(_, c)| name(*c, ObjectType::File)));
            assert_eq!(expected.len(), 5);

            let got = source(&repo).objects(&commit).await.unwrap();
            assert_eq!(got.len(), 5, "{got:?}");
            // The list does not hold the parent commit.
            assert_eq!(got.into_iter().collect::<HashSet<_>>(), expected);
        });
    }

    #[test]
    fn a_metadata_object_is_its_stored_bytes_in_raw() {
        ostrya_rt::block_on(async {
            let (scratch, repo, commit) = fixture("metadata", RepoMode::Archive).await;
            let src = source(&repo);
            let names = repo.traverse_commit(&commit, 0).await.unwrap();
            let meta: Vec<_> = names.iter().filter(|n| n.ty != ObjectType::File).collect();
            assert_eq!(meta.len(), 3, "a commit, a dirtree, and a dirmeta");
            for name in meta {
                // The encoding that the session asks for does not change a
                // metadata object.
                for encoding in [Encoding::Raw, Encoding::Deflate] {
                    match src.open(name, encoding).await.unwrap() {
                        ObjectData::Encoded {
                            encoding: Encoding::Raw,
                            reader,
                        } => assert_eq!(read_all(reader).await, stored(&scratch, &repo, name)),
                        other => panic!("{name:?}: {other:?}"),
                    }
                }
            }
        });
    }

    #[test]
    fn an_archive_file_object_in_deflate_is_the_stored_filez() {
        ostrya_rt::block_on(async {
            let (scratch, repo, commit) = fixture("filez", RepoMode::Archive).await;
            let src = source(&repo);
            let (regular, symlink) = file_objects(&repo, &commit).await;
            for name in [regular, symlink] {
                match src.open(&name, Encoding::Deflate).await.unwrap() {
                    ObjectData::Encoded {
                        encoding: Encoding::Deflate,
                        reader,
                    } => assert_eq!(read_all(reader).await, stored(&scratch, &repo, &name)),
                    other => panic!("{name:?}: {other:?}"),
                }
            }
        });
    }

    #[test]
    fn a_file_object_in_raw_is_content() {
        ostrya_rt::block_on(async {
            let (_scratch, repo, commit) = fixture("archive-raw", RepoMode::Archive).await;
            let (regular, _) = file_objects(&repo, &commit).await;
            let loaded = repo.load_file(&regular.checksum).await.unwrap();
            match source(&repo).open(&regular, Encoding::Raw).await.unwrap() {
                ObjectData::Content {
                    header,
                    size,
                    payload: Some(payload),
                } => {
                    assert_eq!(header, loaded.header());
                    assert_eq!(size, 13);
                    assert_eq!(read_all(payload).await, b"file content\n");
                }
                other => panic!("{other:?}"),
            }
        });
    }

    #[test]
    fn a_bare_file_object_is_content_in_every_encoding() {
        ostrya_rt::block_on(async {
            let (_scratch, repo, commit) = fixture("bare-user", RepoMode::BareUser).await;
            let (regular, _) = file_objects(&repo, &commit).await;
            let loaded = repo.load_file(&regular.checksum).await.unwrap();
            for encoding in [Encoding::Raw, Encoding::Deflate] {
                match source(&repo).open(&regular, encoding).await.unwrap() {
                    ObjectData::Content {
                        header,
                        size,
                        payload: Some(payload),
                    } => {
                        assert_eq!(header, loaded.header());
                        assert_eq!(size, 13);
                        assert_eq!(read_all(payload).await, b"file content\n");
                    }
                    other => panic!("{encoding:?}: {other:?}"),
                }
            }
        });
    }

    #[test]
    fn a_symlink_is_content_with_no_payload() {
        ostrya_rt::block_on(async {
            for (label, mode, encoding) in [
                ("symlink-bare-user", RepoMode::BareUser, Encoding::Deflate),
                ("symlink-archive", RepoMode::Archive, Encoding::Raw),
            ] {
                let (_scratch, repo, commit) = fixture(label, mode).await;
                let (_, symlink) = file_objects(&repo, &commit).await;
                match source(&repo).open(&symlink, encoding).await.unwrap() {
                    ObjectData::Content {
                        header,
                        size: 0,
                        payload: None,
                    } => assert_eq!(header.symlink_target, "file"),
                    other => panic!("{label}: {other:?}"),
                }
            }
        });
    }

    #[test]
    fn a_missing_object_is_object_not_found() {
        ostrya_rt::block_on(async {
            for (label, mode) in [
                ("missing-archive", RepoMode::Archive),
                ("missing-bare-user", RepoMode::BareUser),
                ("missing-bare-user-only", RepoMode::BareUserOnly),
            ] {
                check_missing_object(label, mode).await;
            }
        });
    }

    /// Checks that each absent object of a repository of `mode` gives
    /// `ObjectNotFound`.
    async fn check_missing_object(label: &str, mode: RepoMode) {
        let (_scratch, repo, _) = fixture(label, mode).await;
        let src = source(&repo);
        let absent = Checksum::from_bytes([7; 32]);
        for (ty, encoding) in [
            (ObjectType::Commit, Encoding::Raw),
            (ObjectType::DirTree, Encoding::Raw),
            (ObjectType::File, Encoding::Deflate),
            (ObjectType::File, Encoding::Raw),
        ] {
            let name = ObjectName {
                checksum: absent,
                ty,
            };
            let err = src.open(&name, encoding).await.unwrap_err();
            let crate::remote::Error::Source(inner) = err else {
                panic!("{label} {ty:?} {encoding:?}: {err:?}");
            };
            assert!(
                matches!(
                    inner.downcast_ref::<Error>(),
                    Some(Error::ObjectNotFound { checksum, ty: t })
                        if *checksum == absent && *t == ty
                ),
                "{label} {ty:?} {encoding:?}: {inner:?}"
            );
        }
        // A commit that is absent has no objects to list.
        assert!(matches!(
            src.objects(&absent).await,
            Err(crate::remote::Error::Source(_))
        ));
    }

    #[test]
    fn the_payload_streamed_is_the_stored_content() {
        ostrya_rt::block_on(async {
            let content: Vec<u8> = (0..300_000u32).map(|i| (i % 251) as u8).collect();
            for (label, mode) in [
                ("stream-archive", RepoMode::Archive),
                ("stream-bare-user", RepoMode::BareUser),
                ("stream-bare-user-only", RepoMode::BareUserOnly),
            ] {
                let scratch = Scratch::new(label);
                let repo = scratch.create(mode).await;
                let commit = commit_tree(&repo, &scratch, "main", None, &content).await;
                let (regular, _) = file_objects(&repo, &commit).await;
                let loaded = repo.load_file(&regular.checksum).await.unwrap();
                match source(&repo).open(&regular, Encoding::Raw).await.unwrap() {
                    ObjectData::Content {
                        header,
                        size,
                        payload: Some(payload),
                    } => {
                        assert_eq!(header, loaded.header(), "{label}");
                        assert_eq!(size, content.len() as u64, "{label}");
                        assert!(read_all(payload).await == content, "{label}");
                    }
                    other => panic!("{label}: {other:?}"),
                }
            }
        });
    }

    /// In each mode and each encoding, the content size of the file objects is
    /// the number of bytes that their readers give. `raw` is also the encoding
    /// of a session with a server that does not list `deflate`.
    #[test]
    fn the_content_size_is_the_bytes_the_readers_give() {
        ostrya_rt::block_on(async {
            let content: Vec<u8> = (0..300_000u32).map(|i| (i % 251) as u8).collect();
            for (label, mode) in [
                ("size-archive", RepoMode::Archive),
                ("size-bare-user", RepoMode::BareUser),
                ("size-bare-user-only", RepoMode::BareUserOnly),
            ] {
                let scratch = Scratch::new(label);
                let repo = scratch.create(mode).await;
                let commit = commit_tree(&repo, &scratch, "main", None, &content).await;
                let names = repo.traverse_commit(&commit, 0).await.unwrap();
                let names: Vec<ObjectName> = names.into_iter().collect();
                let src = source(&repo);
                for encoding in [Encoding::Raw, Encoding::Deflate] {
                    let mut read = 0u64;
                    for name in names.iter().filter(|n| n.ty == ObjectType::File) {
                        read += match src.open(name, encoding).await.unwrap() {
                            ObjectData::Content { payload, .. } => match payload {
                                Some(payload) => read_all(payload).await.len() as u64,
                                None => 0,
                            },
                            ObjectData::Encoded { reader, .. } => {
                                read_all(reader).await.len() as u64
                            }
                        };
                    }
                    let size = src.content_size(&names, encoding).await.unwrap();
                    assert_eq!(size, Some(read), "{label} {encoding:?}");
                    if !(mode.is_archive() && encoding == Encoding::Deflate) {
                        assert_eq!(read, content.len() as u64, "{label} {encoding:?}");
                    }
                }
            }
        });
    }

    /// If the fan-out directory of an object is a symlink, the size pass and the
    /// load reach the object the same way. Both succeed with the same bytes, or
    /// both fail.
    #[test]
    fn the_content_size_and_the_load_agree_on_a_symlinked_fan_out() {
        ostrya_rt::block_on(async {
            for (label, mode) in [
                ("fanout-archive", RepoMode::Archive),
                ("fanout-bare-user", RepoMode::BareUser),
                ("fanout-bare-user-only", RepoMode::BareUserOnly),
            ] {
                let (scratch, repo, commit) = fixture(label, mode).await;
                let (regular, _) = file_objects(&repo, &commit).await;
                let path = loose_path(&regular.checksum, ObjectType::File, mode);
                let fanout = path.split_once('/').unwrap().0;
                let objects = scratch.path().join("repo/objects");
                let moved = scratch.path().join("moved-fanout");
                std::fs::rename(objects.join(fanout), &moved).unwrap();
                std::os::unix::fs::symlink(&moved, objects.join(fanout)).unwrap();
                let src = source(&repo);
                let names = [regular];
                for encoding in [Encoding::Raw, Encoding::Deflate] {
                    let loaded = match src.open(&regular, encoding).await {
                        Ok(ObjectData::Content { payload, .. }) => {
                            Ok(read_all(payload.unwrap()).await.len() as u64)
                        }
                        Ok(ObjectData::Encoded { reader, .. }) => {
                            Ok(read_all(reader).await.len() as u64)
                        }
                        Err(e) => Err(e.to_string()),
                    };
                    let sized = src
                        .content_size(&names, encoding)
                        .await
                        .map(Option::unwrap)
                        .map_err(|e| e.to_string());
                    assert_eq!(loaded.is_ok(), sized.is_ok(), "{label} {encoding:?}");
                    if let (Ok(loaded), Ok(sized)) = (loaded, sized) {
                        assert_eq!(loaded, sized, "{label} {encoding:?}");
                    }
                }
            }
        });
    }

    #[test]
    fn detached_metadata_comes_with_the_filter_applied() {
        ostrya_rt::block_on(async {
            let (_scratch, repo, commit) = fixture("detached", RepoMode::Archive).await;
            // No detached metadata.
            assert!(
                source(&repo)
                    .detached_metadata(&commit)
                    .await
                    .unwrap()
                    .is_none()
            );

            let mut dict = DictBuilder::new();
            dict.insert_str("xa.keep", "kept");
            dict.insert_str("xa.drop", "dropped");
            dict.insert_str("xa.other", "kept too");
            repo.write_commit_detached_metadata(&commit, Some(&dict.build()))
                .await
                .unwrap();

            let all = source(&repo)
                .detached_metadata(&commit)
                .await
                .unwrap()
                .unwrap();
            assert_eq!(keys(&all), ["xa.keep", "xa.drop", "xa.other"]);

            let filtered =
                RepoSource::new(repo.clone(), DetachedMetadataFilter::excluding(["xa.drop"]));
            let kept = filtered.detached_metadata(&commit).await.unwrap().unwrap();
            assert_eq!(keys(&kept), ["xa.keep", "xa.other"]);

            // A filter that allows no property sends no detached metadata.
            let none = RepoSource::new(
                repo.clone(),
                DetachedMetadataFilter::excluding(["xa.keep", "xa.drop", "xa.other"]),
            );
            assert!(none.detached_metadata(&commit).await.unwrap().is_none());
        });
    }

    /// Returns the bytes of an `Encoded` result, `None` for `None`, and fails
    /// for a `Dict`.
    async fn encoded(src: &RepoSource, commit: &Checksum) -> Option<Vec<u8>> {
        match src.detached_metadata_encoded(commit).await.unwrap() {
            Some(DetachedMetadata::Encoded(bytes)) => Some(bytes),
            Some(DetachedMetadata::Dict(dict)) => panic!("a dict: {dict:?}"),
            None => None,
        }
    }

    /// The source gives the bytes of the stored `.commitmeta` unchanged for an
    /// unset filter and for a filter that keeps each property. A partial
    /// filter gives the normal form of the kept properties. An absent file,
    /// the zero-length marker, and a filter that allows no property give
    /// `None`. An unset filter does not parse the file, so a file that is not
    /// an `a{sv}` dict goes as it is. A set filter refuses that file.
    #[test]
    fn encoded_detached_metadata_is_the_stored_file_if_the_filter_keeps_each_property() {
        ostrya_rt::block_on(async {
            let (scratch, repo, commit) = fixture("detached-encoded", RepoMode::Archive).await;
            let name = ObjectName::new(commit, ObjectType::CommitMeta);
            assert_eq!(encoded(&source(&repo), &commit).await, None);

            repo.write_commit_detached_metadata(&commit, None)
                .await
                .unwrap();
            assert!(stored(&scratch, &repo, &name).is_empty());
            assert_eq!(encoded(&source(&repo), &commit).await, None);

            let mut dict = DictBuilder::new();
            dict.insert_str("xa.keep", "kept");
            dict.insert_str("xa.drop", "dropped");
            let dict = dict.build();
            repo.write_commit_detached_metadata(&commit, Some(&dict))
                .await
                .unwrap();
            let file = stored(&scratch, &repo, &name);

            assert_eq!(encoded(&source(&repo), &commit).await.as_ref(), Some(&file));
            let keep_all = RepoSource::new(
                repo.clone(),
                DetachedMetadataFilter::excluding(["xa.absent"]),
            );
            assert_eq!(encoded(&keep_all, &commit).await.as_ref(), Some(&file));

            let partial =
                RepoSource::new(repo.clone(), DetachedMetadataFilter::excluding(["xa.drop"]));
            let kept: Vec<Value> = dict
                .as_array()
                .unwrap()
                .iter()
                .filter(|entry| entry.as_tuple().unwrap()[0].as_str() != Some("xa.drop"))
                .cloned()
                .collect();
            assert_eq!(
                encoded(&partial, &commit).await,
                Some(crate::summary::serialize_signature_dict(&Value::Array(kept)).unwrap())
            );

            let none = RepoSource::new(
                repo.clone(),
                DetachedMetadataFilter::excluding(["xa.keep", "xa.drop"]),
            );
            assert_eq!(encoded(&none, &commit).await, None);

            let corrupt = b"\x01\x02\x03\x04\x05".to_vec();
            let path = loose_path(&commit, ObjectType::CommitMeta, repo.mode());
            std::fs::write(scratch.path().join("repo/objects").join(path), &corrupt).unwrap();
            assert_eq!(encoded(&source(&repo), &commit).await, Some(corrupt));
            let Err(crate::remote::Error::Source(inner)) =
                keep_all.detached_metadata_encoded(&commit).await
            else {
                panic!("a set filter passed a corrupt .commitmeta");
            };
            assert!(
                matches!(inner.downcast_ref::<Error>(), Some(Error::Core(_))),
                "{inner:?}"
            );
        });
    }
}