ostrya-remote 0.11.2

The push and pull protocol of ostrya: the wire codec, the push client session, and the ssh and HTTP transports
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
//! The tree model: the entries of a walk, their checksums, and the source of
//! each object.

use std::io;
use std::ops::Range;
use std::path::{Path, PathBuf};

use futures_lite::io::{AsyncReadExt, Cursor};
use ostrya_core::{
    Checksum, DirMeta, DirTree, FileHeader, MAX_METADATA_SIZE, ObjectName, ObjectType, Xattrs,
};
use ostrya_gvariant::Value;

use super::hash::{FileId, open_regular};
use super::{EntryMeta, ScanOptions, invalid_data, walk};
use crate::error::{Error, Result};
use crate::proto::Encoding;
use crate::session::{BoxFuture, ObjectData, ObjectSource, PushProgress};

/// The result of the hash of one regular file.
#[derive(Debug, Clone, Copy)]
pub(super) struct Hashed {
    /// The content-object checksum.
    pub(super) checksum: Checksum,
    /// The number of payload bytes the hash read.
    pub(super) size: u64,
}

/// The owner, the mode, and the extended attributes of an entry.
struct Meta {
    uid: u32,
    gid: u32,
    mode: u32,
    xattrs: Xattrs,
}

/// What the model keeps of an entry.
enum NodeData {
    /// A directory.
    Dir {
        meta: Meta,
        /// The indices of the kept entries of the directory, which are
        /// contiguous.
        children: Range<u32>,
        /// The dirtree and dirmeta checksums, once the bottom-up pass ran.
        sums: Option<(Checksum, Checksum)>,
    },
    /// A regular file or a symlink.
    Content {
        meta: Meta,
        /// The identity of a regular file, as the walk read it. The open of
        /// the file checks it.
        id: FileId,
        /// The target of a symlink. A regular file has none.
        target: Option<Box<str>>,
        /// The checksum and the payload size, once the entry is hashed.
        hashed: Option<Hashed>,
    },
}

/// One entry of the model.
struct Node {
    /// The index of the parent directory. The root names itself.
    parent: u32,
    /// The name of the entry. The root has the empty name.
    name: Box<str>,
    data: NodeData,
}

/// The model of a local tree that [`TreeModel::scan`] walked and hashed.
///
/// For each entry, the model keeps the name, the metadata, and the index of
/// the parent directory. For each regular file, it also keeps the number of
/// payload bytes that the hash pass read. The model holds no file content, and
/// it serializes a dirtree or a dirmeta object again from its fields on each
/// request. Its memory grows with the number of entries and the length of
/// their names.
///
/// # Object source
///
/// The model is the [`ObjectSource`] of the objects of the tree.
/// [`object_names`](TreeModel::object_names) gives each object of the tree
/// once. The model holds no commit.
///
/// - [`open`](ObjectSource::open) of a regular file opens the file again on
///   the blocking pool, with the open and the checks of the hash pass. These
///   are the type check, and on Unix the identity check. It gives the file as
///   [`ObjectData::Content`], whose `size` is the payload size that the hash
///   pass read.
/// - `open` of a symlink opens no file. `open` of a dirtree or a dirmeta
///   object serializes the object again from the model. Each of the two is
///   [`ObjectData::Encoded`] in the `raw` encoding.
/// - [`content_size`](ObjectSource::content_size) gives the sum of the
///   payload sizes of the hash pass, in each encoding. It reads no file.
/// - [`objects`](ObjectSource::objects) and
///   [`detached_metadata`](ObjectSource::detached_metadata) name a commit,
///   so each call returns [`Error::InvalidInput`].
///
/// When the model sends a file, it gives the payload size of the hash pass and
/// does not hash the file again. If a file changes after the hash pass, the
/// server verifies the object and refuses it.
///
/// If a call names an object that the model does not hold, a commit
/// included, it returns [`Error::InvalidInput`]. If the open of a file fails,
/// the call returns [`Error::Walk`] with the path of the file and one of the
/// kinds that [`scan`](TreeModel::scan) lists. The session returns that error
/// inside [`Error::Source`].
pub struct TreeModel {
    /// The walk root.
    root: PathBuf,
    /// The entries in the order the walk kept them. The root is at 0, and the
    /// kept entries of a directory follow each other.
    nodes: Vec<Node>,
    /// The source entry of each object.
    sources: Sources,
}

/// The source entry of each object: the first entry, in walk order, that
/// gives it. Each list holds one entry for each distinct object of its type,
/// sorted by the checksum of the object.
#[derive(Default)]
struct Sources {
    files: Vec<u32>,
    dirtrees: Vec<u32>,
    dirmetas: Vec<u32>,
}

impl TreeModel {
    /// Walks the directory `root` and hashes each object of its tree.
    ///
    /// The scan gives the checksum of each object of the tree: a content
    /// object for each regular file and symlink, and a dirtree and a dirmeta
    /// object for each directory.
    ///
    /// # Walk
    ///
    /// - The walk does not follow symlinks. The walk root must be a directory.
    /// - The walk holds one directory open at a time. It reads a listing to its
    ///   end and closes the directory before it enters a subdirectory.
    /// - While it reads a listing, the walk reads the metadata of each entry
    ///   with `DirEntry::metadata` and the target of each symlink. It reads
    ///   only the walk root with `symlink_metadata`.
    /// - Each name must be valid UTF-8 and must pass the dirtree name rule of
    ///   `ostrya-core`. Each symlink target must be valid UTF-8.
    /// - The walk takes regular files, directories, and symlinks. Any other
    ///   entry stops the walk before the entry filter runs, so the filter never
    ///   sees it. Other entries are device nodes, fifos, sockets, and Windows
    ///   reparse points that are not symlinks.
    /// - After the walk closes a directory, it runs the
    ///   [`EntryFilter`](super::EntryFilter) on each entry in the order of the
    ///   listing. Then it enters each kept subdirectory in turn, depth first.
    /// - The filter sees the root first, with the empty path.
    /// - [`EntryAction::Skip`](super::EntryAction::Skip) leaves out an entry,
    ///   and for a directory its whole subtree. The walk does not open a
    ///   skipped entry. `Skip` on the root stops the walk.
    /// - If a file has more than one hard link in the tree, the walk reads and
    ///   hashes the file once for each of its paths.
    ///
    /// # Hash pass
    ///
    /// - The pass reads each kept regular file once, on the blocking pool of
    ///   the runtime. It hashes the file over its file header and its payload.
    /// - The pass starts each file as soon as the filter keeps it, in the order
    ///   of the walk, with at most [`ScanOptions::hash_jobs`] files in flight.
    /// - A job reads its file in chunks of at most 64 KiB. Before each chunk,
    ///   it checks the stop flag of the pass.
    /// - At the first error of the walk or of a job, the pass sets the stop flag
    ///   and starts no new job. It returns the error after each job in flight
    ///   stops, so no file of the pass is open when the scan returns.
    /// - If the future of the scan is dropped, the pass sets the stop flag.
    ///   Each job in flight then stops at its next chunk.
    /// - On Unix, a job opens its file with `O_NOFOLLOW | O_NONBLOCK`. On
    ///   Windows, it opens the file with
    ///   `FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS`.
    /// - One metadata read of the open file must show a regular file. On Unix,
    ///   the device and inode numbers must also equal those that the walk
    ///   read. If a parent directory of the file becomes a symlink after the
    ///   walk, the open can reach another file, and this check refuses it.
    ///   Windows has no identity check.
    /// - The model records the number of payload bytes that each job read.
    /// - After the walk and the jobs end, the scan hashes each directory bottom
    ///   up: its dirtree object, with the entries sorted by name, and its
    ///   dirmeta object.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if [`ScanOptions::hash_jobs`] is `Some(0)`.
    ///   The walk does not start.
    /// - [`Error::Walk`] for each failure of the walk and of the hash pass. The
    ///   error names the entry on the local filesystem, the walk root
    ///   included. It keeps one of these `io::ErrorKind` values:
    ///   - the kind of the call that failed, for example `PermissionDenied` or
    ///     `NotFound`
    ///   - `InvalidInput` if the walk root is not a directory, or if the filter
    ///     returns `Skip` for the root
    ///   - `Unsupported` for an entry that is not a regular file, a directory,
    ///     or a symlink, and on Windows for a symlink whose target `std` cannot
    ///     read
    ///   - `InvalidData` for a name that is not valid UTF-8 or that fails the
    ///     name rule, and for a symlink target that is not valid UTF-8
    ///   - `InvalidData` for a change by the filter that [`EntryMeta`] does not
    ///     allow, and for a file header that `ostrya-core` refuses, for example
    ///     a symlink target with a NUL byte
    ///   - `InvalidData` on Windows for a symlink target that holds `\` or
    ///     starts with a drive prefix, also if no filter runs
    ///   - `InvalidData` for a file whose type or identity changed after the
    ///     walk read it
    ///   - `InvalidData` for a dirtree or a dirmeta object of more than
    ///     [`MAX_METADATA_SIZE`] bytes, and for a tree of more than `u32::MAX`
    ///     kept entries
    ///
    /// If more than one entry fails, the error names one of the failing paths.
    /// If more than one hash job runs, the order of the failures is not fixed.
    pub async fn scan(root: &Path, options: ScanOptions) -> Result<TreeModel> {
        walk::scan(root, options, None).await
    }

    /// Runs [`scan`](TreeModel::scan) and sets the phases of the scan in
    /// `progress`: [`Scanning`](crate::PushPhase::Scanning) during the walk,
    /// and [`Hashing`](crate::PushPhase::Hashing) after it.
    ///
    /// The scan sets `Scanning` with
    /// [`start_phase`](crate::PushProgress::start_phase), so the hook of
    /// `progress` gets one call before the walk, also on a new handle.
    pub(crate) async fn scan_with(
        root: &Path,
        options: ScanOptions,
        progress: Option<&PushProgress>,
    ) -> Result<TreeModel> {
        walk::scan(root, options, progress).await
    }

    /// Returns the dirtree checksum of the walk root.
    pub fn root_dirtree(&self) -> Checksum {
        self.dir_sums(0).0
    }

    /// Returns the dirmeta checksum of the walk root.
    pub fn root_dirmeta(&self) -> Checksum {
        self.dir_sums(0).1
    }

    /// Returns the name of each object of the tree, once each.
    ///
    /// The list holds the content object of each regular file and symlink,
    /// and the dirtree and dirmeta objects of each directory. It holds no
    /// commit object. The order is the order in which the walk reached the
    /// first source of each object.
    pub fn object_names(&self) -> Vec<ObjectName> {
        let Sources {
            files,
            dirtrees,
            dirmetas,
        } = &self.sources;
        let mut names = Vec::with_capacity(files.len() + dirtrees.len() + dirmetas.len());
        for (index, node) in (0u32..).zip(&self.nodes) {
            for name in node_names(node).into_iter().flatten() {
                if self.source(&name) == Some(index) {
                    names.push(name);
                }
            }
        }
        names
    }

    /// Returns the path on the local filesystem of the entry that gives the
    /// object `name`, or `None` for an object that the tree does not give.
    ///
    /// The entry is the first one in walk order that gives the object. The
    /// call reads no file.
    pub fn source_path(&self, name: &ObjectName) -> Option<PathBuf> {
        self.source(name).map(|index| self.os_path(index))
    }

    /// An empty model of the walk root `root`.
    pub(super) fn new(root: &Path) -> TreeModel {
        TreeModel {
            root: root.to_path_buf(),
            nodes: Vec::new(),
            sources: Sources::default(),
        }
    }

    /// The walk root.
    pub(super) fn root(&self) -> &Path {
        &self.root
    }

    /// The index the next entry gets.
    pub(super) fn next_index(&self) -> io::Result<u32> {
        u32::try_from(self.nodes.len())
            .map_err(|_| invalid_data("the tree holds more entries than the model can index"))
    }

    /// Adds the walk root, with the metadata the filter left.
    pub(super) fn push_root(&mut self, meta: EntryMeta, id: FileId) {
        self.push(0, String::new(), meta, id);
    }

    /// Adds an entry under the directory `parent`, with the metadata the filter
    /// left and the identity the walk read. The caller checked the index with
    /// [`next_index`](TreeModel::next_index).
    pub(super) fn push(&mut self, parent: u32, name: String, meta: EntryMeta, id: FileId) {
        let EntryMeta {
            kind,
            uid,
            gid,
            mode,
            xattrs,
            symlink_target,
        } = meta;
        let meta = Meta {
            uid,
            gid,
            mode,
            xattrs,
        };
        let data = match kind {
            super::EntryKind::Dir => NodeData::Dir {
                meta,
                children: 0..0,
                sums: None,
            },
            super::EntryKind::File | super::EntryKind::Symlink => NodeData::Content {
                meta,
                id,
                target: symlink_target.map(String::into_boxed_str),
                hashed: None,
            },
        };
        self.nodes.push(Node {
            parent,
            name: name.into_boxed_str(),
            data,
        });
    }

    /// Records the hash of the symlink `index`, whose content object has no
    /// payload.
    pub(super) fn hash_symlink(&mut self, index: u32) -> io::Result<()> {
        let checksum = ostrya_core::ContentHasher::new(&self.header(index))
            .map_err(|e| invalid_data(e.to_string()))?
            .finish();
        self.set_hashed(index, Hashed { checksum, size: 0 });
        Ok(())
    }

    /// Records the kept entries of the directory `dir`.
    pub(super) fn set_children(&mut self, dir: u32, range: Range<u32>) {
        if let NodeData::Dir { children, .. } = &mut self.node_mut(dir).data {
            *children = range;
        }
    }

    /// The kept entries of the directory `dir`.
    pub(super) fn children(&self, dir: u32) -> Range<u32> {
        match &self.node(dir).data {
            NodeData::Dir { children, .. } => children.clone(),
            NodeData::Content { .. } => 0..0,
        }
    }

    /// Returns `true` if the entry `index` is a directory.
    pub(super) fn is_dir(&self, index: u32) -> bool {
        matches!(self.node(index).data, NodeData::Dir { .. })
    }

    /// The path of the entry `index` relative to the walk root, joined with
    /// `/`, written into `out`.
    pub(super) fn rel_path(&self, index: u32, out: &mut String) {
        out.clear();
        for i in self.chain(index) {
            if !out.is_empty() {
                out.push('/');
            }
            out.push_str(&self.node(i).name);
        }
    }

    /// The path of the entry `index` on the local filesystem.
    pub(super) fn os_path(&self, index: u32) -> PathBuf {
        let mut path = self.root.clone();
        for i in self.chain(index) {
            path.push(&*self.node(i).name);
        }
        path
    }

    /// The identity of the regular file `index`, as the walk read it.
    pub(super) fn file_id(&self, index: u32) -> FileId {
        match &self.node(index).data {
            NodeData::Content { id, .. } => *id,
            NodeData::Dir { .. } => unreachable!("a directory is not opened as a file"),
        }
    }

    /// The file header of the regular file or symlink `index`.
    pub(super) fn header(&self, index: u32) -> FileHeader {
        match &self.node(index).data {
            NodeData::Content { meta, target, .. } => FileHeader {
                uid: meta.uid,
                gid: meta.gid,
                mode: meta.mode,
                symlink_target: target.as_deref().unwrap_or_default().to_owned(),
                xattrs: meta.xattrs.clone(),
            },
            NodeData::Dir { .. } => unreachable!("a directory has no file header"),
        }
    }

    /// Hashes each directory bottom-up, once each regular file is hashed, and
    /// records the source of each object.
    pub(super) fn finish(&mut self) -> Result<()> {
        // The entries of a directory come after it, so the reverse order
        // hashes each directory after all of its subdirectories.
        for index in (0..self.next_index_unchecked()).rev() {
            if !self.is_dir(index) {
                continue;
            }
            let sums = self.hash_dir(index).map_err(|source| Error::Walk {
                path: self.os_path(index),
                source,
            })?;
            if let NodeData::Dir { sums: slot, .. } = &mut self.node_mut(index).data {
                *slot = Some(sums);
            }
        }
        let mut sources = Sources::default();
        for (index, node) in (0u32..).zip(&self.nodes) {
            match node.data {
                NodeData::Content { .. } => sources.files.push(index),
                NodeData::Dir { .. } => {
                    sources.dirtrees.push(index);
                    sources.dirmetas.push(index);
                }
            }
        }
        for (list, ty) in [
            (&mut sources.files, ObjectType::File),
            (&mut sources.dirtrees, ObjectType::DirTree),
            (&mut sources.dirmetas, ObjectType::DirMeta),
        ] {
            // The sort is stable, so the first entry of each run of equal
            // checksums is the first in walk order, and the dedup keeps it.
            list.sort_by_key(|&index| self.object_checksum(index, ty));
            list.dedup_by_key(|index| self.object_checksum(*index, ty));
            list.shrink_to_fit();
        }
        self.sources = sources;
        Ok(())
    }

    /// The source entry of the object `name`, or `None` for an object the
    /// tree does not give.
    fn source(&self, name: &ObjectName) -> Option<u32> {
        let list = match name.ty {
            ObjectType::File => &self.sources.files,
            ObjectType::DirTree => &self.sources.dirtrees,
            ObjectType::DirMeta => &self.sources.dirmetas,
            _ => return None,
        };
        list.binary_search_by_key(&name.checksum, |&index| {
            self.object_checksum(index, name.ty)
        })
        .ok()
        .map(|k| list[k])
    }

    /// The checksum of the object of type `ty` that the hashed entry `index`
    /// gives.
    fn object_checksum(&self, index: u32, ty: ObjectType) -> Checksum {
        match (&self.node(index).data, ty) {
            (
                NodeData::Content {
                    hashed: Some(hashed),
                    ..
                },
                ObjectType::File,
            ) => hashed.checksum,
            (NodeData::Dir { .. }, ObjectType::DirTree) => self.dir_sums(index).0,
            (NodeData::Dir { .. }, ObjectType::DirMeta) => self.dir_sums(index).1,
            _ => unreachable!("each source entry is hashed and gives an object of its type"),
        }
    }

    /// The dirtree object of the directory `dir`.
    fn dirtree(&self, dir: u32) -> DirTree {
        let mut tree = DirTree::default();
        for index in self.children(dir) {
            let node = self.node(index);
            let name = node.name.to_string();
            match &node.data {
                NodeData::Content { hashed, .. } => {
                    let hashed = hashed.expect("each kept file is hashed before its directory");
                    tree.files.push((name, hashed.checksum));
                }
                NodeData::Dir { .. } => {
                    let (dirtree, dirmeta) = self.dir_sums(index);
                    tree.dirs.push((name, dirtree, dirmeta));
                }
            }
        }
        tree.files.sort_unstable_by(|a, b| a.0.cmp(&b.0));
        tree.dirs.sort_unstable_by(|a, b| a.0.cmp(&b.0));
        tree
    }

    /// The dirmeta object of the directory `dir`.
    fn dirmeta(&self, dir: u32) -> DirMeta {
        match &self.node(dir).data {
            NodeData::Dir { meta, .. } => DirMeta {
                uid: meta.uid,
                gid: meta.gid,
                mode: meta.mode,
                xattrs: meta.xattrs.clone(),
            },
            NodeData::Content { .. } => unreachable!("a file has no dirmeta"),
        }
    }

    /// The dirtree and dirmeta checksums of the directory `dir`.
    fn hash_dir(&self, dir: u32) -> io::Result<(Checksum, Checksum)> {
        let dirtree = self
            .dirtree(dir)
            .serialize()
            .map_err(|e| invalid_data(e.to_string()))?;
        check_metadata_size(&dirtree, "dirtree", MAX_METADATA_SIZE)?;
        let dirmeta = self
            .dirmeta(dir)
            .serialize()
            .map_err(|e| invalid_data(e.to_string()))?;
        check_metadata_size(&dirmeta, "dirmeta", MAX_METADATA_SIZE)?;
        Ok((Checksum::sha256(&dirtree), Checksum::sha256(&dirmeta)))
    }

    /// The data of the object `name` for the send pass.
    async fn open_object(&self, name: &ObjectName) -> Result<ObjectData> {
        let index = self.source(name).ok_or_else(|| {
            Error::InvalidInput(format!(
                "object {} of type {:?} is not in the tree model",
                name.checksum, name.ty
            ))
        })?;
        let bytes = match name.ty {
            ObjectType::File => return self.open_content(index).await,
            ObjectType::DirTree => self.dirtree(index).serialize(),
            ObjectType::DirMeta => self.dirmeta(index).serialize(),
            _ => unreachable!("the model is the source of three object types alone"),
        };
        let bytes = bytes.map_err(|e| Error::Walk {
            path: self.os_path(index),
            source: invalid_data(e.to_string()),
        })?;
        Ok(encoded(bytes))
    }

    /// The payload bytes of the file objects of `names`, as the hash pass
    /// read them. A symlink counts 0. A file object that the model does not
    /// hold is [`Error::InvalidInput`].
    fn content_bytes(&self, names: &[ObjectName]) -> Result<u64> {
        let mut total = 0u64;
        for name in names.iter().filter(|n| n.ty == ObjectType::File) {
            let hashed = self
                .source(name)
                .and_then(|index| match &self.node(index).data {
                    NodeData::Content { hashed, .. } => *hashed,
                    NodeData::Dir { .. } => None,
                });
            let Some(hashed) = hashed else {
                return Err(Error::InvalidInput(format!(
                    "object {} of type {:?} is not in the tree model",
                    name.checksum, name.ty
                )));
            };
            total = total.saturating_add(hashed.size);
        }
        Ok(total)
    }

    /// The content object of the regular file or symlink `index`. A regular
    /// file is opened again, on the blocking pool, with the open of the hash
    /// pass, and its payload stops after the size of the hash pass plus one
    /// byte. A symlink opens nothing.
    async fn open_content(&self, index: u32) -> Result<ObjectData> {
        let NodeData::Content {
            target,
            hashed: Some(hashed),
            ..
        } = &self.node(index).data
        else {
            unreachable!("each source of a content object is a hashed file or symlink");
        };
        let header = self.header(index);
        if target.is_some() {
            return Ok(ObjectData::Content {
                header,
                size: 0,
                payload: None,
            });
        }
        let path = self.os_path(index);
        let id = self.file_id(index);
        let open_path = path.clone();
        let (file, _len) = ostrya_rt::unblock(move || open_regular(&open_path, &id))
            .await
            .map_err(|source| Error::Walk { path, source })?;
        Ok(ObjectData::Content {
            header,
            size: hashed.size,
            // One byte past the size of the hash pass lets the server see a
            // file that grew, and stops the read there.
            payload: Some(Box::new(
                ostrya_rt::FileReader::with_len_hint(file, hashed.size)
                    .take(hashed.size.saturating_add(1)),
            )),
        })
    }

    /// The dirtree and dirmeta checksums of the hashed directory `dir`.
    fn dir_sums(&self, dir: u32) -> (Checksum, Checksum) {
        match &self.node(dir).data {
            NodeData::Dir {
                sums: Some(sums), ..
            } => *sums,
            _ => unreachable!("each directory is hashed after its subdirectories"),
        }
    }

    /// Records the hash of the regular file or symlink `index`.
    pub(super) fn set_hashed(&mut self, index: u32, result: Hashed) {
        if let NodeData::Content { hashed, .. } = &mut self.node_mut(index).data {
            *hashed = Some(result);
        }
    }

    /// Returns the number of entries. The walk checks each index with
    /// [`next_index`](TreeModel::next_index), so the number fits in a `u32`.
    fn next_index_unchecked(&self) -> u32 {
        self.nodes.len() as u32
    }

    /// The indices of the entries from the root down to `index`, the root
    /// left out.
    fn chain(&self, mut index: u32) -> Vec<u32> {
        let mut chain = Vec::new();
        while index != 0 {
            chain.push(index);
            index = self.node(index).parent;
        }
        chain.reverse();
        chain
    }

    fn node(&self, index: u32) -> &Node {
        &self.nodes[index as usize]
    }

    fn node_mut(&mut self, index: u32) -> &mut Node {
        &mut self.nodes[index as usize]
    }
}

/// The objects an entry gives: the content object of a regular file or a
/// symlink, and the dirtree and dirmeta objects of a directory.
fn node_names(node: &Node) -> [Option<ObjectName>; 2] {
    match &node.data {
        NodeData::Content { hashed, .. } => [
            hashed.map(|h| ObjectName::new(h.checksum, ObjectType::File)),
            None,
        ],
        NodeData::Dir { sums, .. } => match sums {
            Some((dirtree, dirmeta)) => [
                Some(ObjectName::new(*dirtree, ObjectType::DirTree)),
                Some(ObjectName::new(*dirmeta, ObjectType::DirMeta)),
            ],
            None => [None, None],
        },
    }
}

impl ObjectSource for TreeModel {
    fn objects<'a>(&'a self, commit: &'a Checksum) -> BoxFuture<'a, Result<Vec<ObjectName>>> {
        Box::pin(async move { Err(no_commit(commit)) })
    }

    fn open<'a>(
        &'a self,
        name: &'a ObjectName,
        _encoding: Encoding,
    ) -> BoxFuture<'a, Result<ObjectData>> {
        Box::pin(self.open_object(name))
    }

    fn detached_metadata<'a>(
        &'a self,
        commit: &'a Checksum,
    ) -> BoxFuture<'a, Result<Option<Value>>> {
        Box::pin(async move { Err(no_commit(commit)) })
    }

    fn content_size<'a>(
        &'a self,
        names: &'a [ObjectName],
        _encoding: Encoding,
    ) -> BoxFuture<'a, Result<Option<u64>>> {
        Box::pin(async move { self.content_bytes(names).map(Some) })
    }
}

/// The error of a call that names the commit `commit`, which the model does
/// not hold.
fn no_commit(commit: &Checksum) -> Error {
    Error::InvalidInput(format!(
        "commit {commit} is not in the tree model, which holds no commit"
    ))
}

/// Metadata object bytes, given as they are in `raw`.
fn encoded(bytes: Vec<u8>) -> ObjectData {
    ObjectData::Encoded {
        encoding: Encoding::Raw,
        reader: Box::new(Cursor::new(bytes)),
    }
}

/// Refuses a metadata object of more than `limit` bytes.
fn check_metadata_size(bytes: &[u8], what: &str, limit: u64) -> io::Result<()> {
    if bytes.len() as u64 > limit {
        return Err(invalid_data(format!(
            "the {what} object of the directory is {} bytes, over the limit of {limit}",
            bytes.len()
        )));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_limit(bytes: &[u8], what: &str) {
        let len = bytes.len() as u64;
        check_metadata_size(bytes, what, len).unwrap();
        let err = check_metadata_size(bytes, what, len - 1).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        assert!(err.to_string().contains(what), "{err}");
    }

    #[test]
    fn a_dirtree_one_byte_over_the_limit_is_invalid_data() {
        let dirtree = DirTree {
            files: ["a", "b", "c"]
                .into_iter()
                .map(|name| (name.to_owned(), Checksum::sha256(name.as_bytes())))
                .collect(),
            dirs: vec![(
                "d".to_owned(),
                Checksum::sha256(b"dirtree"),
                Checksum::sha256(b"dirmeta"),
            )],
        };
        assert_limit(&dirtree.serialize().unwrap(), "dirtree");
    }

    #[test]
    fn a_dirmeta_one_byte_over_the_limit_is_invalid_data() {
        let dirmeta = DirMeta {
            uid: 0,
            gid: 0,
            mode: 0o40755,
            xattrs: Xattrs::new([(b"user.test\0".to_vec(), vec![7; 100])]).unwrap(),
        };
        assert_limit(&dirmeta.serialize().unwrap(), "dirmeta");
    }
}