Skip to main content

ostrya/
commit.rs

1//! Commit objects and the detached metadata of a commit.
2//!
3//! - [`Transaction::write_commit`] stages a commit object over a root tree,
4//!   with the options in [`CommitOptions`].
5//! - [`Transaction::check_related`] checks the dependencies of a new commit
6//!   before the tree is built, and gives a [`CheckedRelated`].
7//!   [`Transaction::write_commit_checked`] stages the commit with these
8//!   dependencies and does not check them again.
9//! - [`Repo::read_commit_detached_metadata`] and
10//!   [`Repo::write_commit_detached_metadata`] read and write the detached
11//!   metadata of a commit.
12//! - [`Repo::read_commit_related`] reads the related commits of a commit:
13//!   the dependencies and the build sources.
14//! - [`Repo::add_detached_related`] adds a build source to a commit.
15
16use std::collections::HashMap;
17use std::os::fd::{AsFd, BorrowedFd};
18
19use ostrya_core::sizes::SizeEntry;
20use ostrya_core::{
21    Checksum, Commit, DirTree, ObjectType, RepoMode, Type, Value, loose_path, to_bytes,
22};
23use rustix::fs::{Mode, OFlags};
24use rustix::io::Errno;
25
26use crate::error::{Error, Result};
27use crate::file::FileKind;
28use crate::perm;
29use crate::related::{self, CommitRelated, RelatedField};
30use crate::repo::Repo;
31use crate::staging::{META_TEMP_PREFIX, TempEntry, open_tmp_dir};
32use crate::transaction::Transaction;
33use crate::tree::RepoTree;
34
35pub use ostrya_core::commit_metadata;
36
37/// The type string of a metadata dict: the detached metadata, and the commit
38/// metadata inside the commit tuple.
39const METADATA_SIGNATURE: &str = "a{sv}";
40/// The type of the `ostree.sizes` value: an array of packed byte buffers.
41const SIZES_SIGNATURE: &str = "aay";
42/// The metadata key of the size records.
43const SIZES_KEY: &str = "ostree.sizes";
44/// The permission bits of a `.commitmeta` file: the `0644` of each metadata
45/// object.
46const COMMITMETA_MODE: u32 = 0o644;
47
48/// The options of [`Transaction::write_commit`] and
49/// [`Transaction::write_commit_checked`].
50///
51/// Each field is optional. If `metadata` is set, it must be an `a{sv}` dict
52/// value. Its entries appear in the commit in insertion order. A caller that
53/// reproduces a commit of the `ostree` command byte for byte supplies the
54/// binding keys in the observed order of that command.
55#[derive(Debug, Default, Clone)]
56pub struct CommitOptions {
57    /// The parent commit, or `None` for a root commit.
58    pub parent: Option<Checksum>,
59    /// The subject of the commit, or an empty string if `None`.
60    pub subject: Option<String>,
61    /// The body of the commit, or an empty string if `None`.
62    pub body: Option<String>,
63    /// The commit time in seconds since the Unix epoch, UTC.
64    ///
65    /// If the value is `None` and `SOURCE_DATE_EPOCH` is set, the commit uses
66    /// that variable. If both are absent, the commit uses the current time.
67    pub timestamp: Option<u64>,
68    /// The `a{sv}` metadata dict, or `None` for an empty dict.
69    pub metadata: Option<Value>,
70    /// The dependencies of the commit: the name and the checksum of each
71    /// commit that field 2 of the commit object names.
72    ///
73    /// The name has the form `<class>/<name>` by convention, for example
74    /// `container/fe`. The write sorts the entries by name in byte order, so
75    /// one set of entries gives one commit checksum. It refuses an empty name
76    /// and two entries with the same name. Each dependency must be complete
77    /// in the repository or in the writing transaction, and must have no
78    /// dependency of its own. [`Transaction::write_commit`] states the rule.
79    ///
80    /// [`Transaction::write_commit_checked`] refuses a list that is not
81    /// empty. The [`CheckedRelated`] that it takes gives the dependencies.
82    ///
83    /// A local prune keeps the dependencies of each commit that it reaches.
84    /// [`Repo::prune`], "Related commits", states the rules.
85    pub related: Vec<(String, Checksum)>,
86}
87
88/// The dependencies of a new commit, after the checks of
89/// [`Transaction::check_related`].
90///
91/// [`Transaction::check_related`] gives it, and
92/// [`Transaction::write_commit_checked`] takes it. It holds the entries sorted
93/// by name in byte order, and it borrows the transaction that checked them.
94/// A drop writes and removes nothing.
95///
96/// While the value lives, the calls that take the transaction as `&mut self`
97/// or by value do not compile: [`set_fsync`](Transaction::set_fsync),
98/// [`set_per_object_fsync`](Transaction::set_per_object_fsync),
99/// [`set_generate_sizes`](Transaction::set_generate_sizes),
100/// [`commit`](Transaction::commit), and [`abort`](Transaction::abort). Call
101/// the setters before [`check_related`](Transaction::check_related).
102#[must_use = "write_commit_checked takes the checked dependencies"]
103pub struct CheckedRelated<'txn> {
104    txn: &'txn Transaction,
105    /// The entries, sorted by name in byte order.
106    entries: Vec<(String, Checksum)>,
107}
108
109impl std::fmt::Debug for CheckedRelated<'_> {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        f.debug_struct("CheckedRelated")
112            .field("entries", &self.entries)
113            .finish_non_exhaustive()
114    }
115}
116
117/// Methods that write a commit object.
118impl Transaction {
119    /// Stages a commit object over the tree `root` and returns its checksum.
120    ///
121    /// The call stages the commit in the same way as other metadata objects.
122    /// The root dirtree and the root dirmeta come from `root`. The other
123    /// fields come from `opts`.
124    ///
125    /// The metadata dict is `opts.metadata`, or an empty dict if it is `None`.
126    /// The call adds no key of its own except `ostree.sizes`. The binding keys
127    /// `ostree.ref-binding` and `ostree.collection-binding` are normal
128    /// metadata entries that the caller supplies.
129    ///
130    /// # `ostree.sizes`
131    ///
132    /// The commit gets the `ostree.sizes` key if the transaction generates
133    /// sizes and the repository is in archive mode. A file system ingest under
134    /// [`GENERATE_SIZES`](crate::CommitModifierFlags::GENERATE_SIZES) turns
135    /// size generation on. [`set_generate_sizes`](Transaction::set_generate_sizes)
136    /// sets it for the whole transaction.
137    ///
138    /// The key is the last metadata entry, as in a commit of the `ostree`
139    /// command. Its records cover the objects that the committed root reaches,
140    /// and no other objects:
141    ///
142    /// - the root dirmeta
143    /// - each dirtree
144    /// - each subdirectory dirmeta
145    /// - each file entry
146    ///
147    /// The commit object is not in the list, because the walk starts below it.
148    /// If a transaction stages more than one commit, the key of each commit
149    /// holds the objects that this commit reaches. If the caller uses
150    /// [`begin_tree_source`](Transaction::begin_tree_source), the key holds the
151    /// objects of the last tree source and the directory objects.
152    ///
153    /// The call walks the committed tree at commit time. An object that the
154    /// transaction staged uses the size record that the transaction kept. An
155    /// object that deduplicated against `objects/` gets its sizes from its
156    /// loose object. As in a commit of the `ostree` command, an incremental
157    /// commit also lists the objects that existed before.
158    ///
159    /// In each other mode the call writes no key. The bytes of the commit are
160    /// the same with and without the request.
161    ///
162    /// # Composefs image
163    ///
164    /// If the call stages the commit object, it records the commit as
165    /// complete. If `[ex-ostrya] generate-composefs` is `true` and the commit
166    /// carries `ostree.composefs.digest.v0`, [`commit`](Transaction::commit)
167    /// then builds and stores the composefs image of the commit. A commit that
168    /// the repository holds already, complete or partial, is not staged, so it
169    /// gets no image.
170    ///
171    /// # Dependencies
172    ///
173    /// Field 2 of the commit object holds the entries of `opts.related`,
174    /// sorted by name in byte order. The call refuses an entry with an empty
175    /// name and two entries with the same name. It checks nothing else in a
176    /// name.
177    ///
178    /// Each dependency must be complete: this transaction stages its commit
179    /// object or the repository holds it, and the repository holds no
180    /// `state/<checksum>.commitpartial` marker for it. A dependency that this
181    /// transaction writes must be staged before the call that names it. A
182    /// dependency must have no dependency of its own, so a dependency names
183    /// no dependency. It can have a parent and build sources.
184    ///
185    /// The call checks the dependencies as
186    /// [`check_related`](Transaction::check_related) does, after the timestamp
187    /// and before it serializes the commit. On a refusal, it writes nothing
188    /// and the transaction stays open.
189    ///
190    /// A caller that checks the dependencies before it builds the tree calls
191    /// [`check_related`](Transaction::check_related) and then
192    /// [`write_commit_checked`](Transaction::write_commit_checked). Then each
193    /// dependency is checked one time.
194    ///
195    /// # Errors
196    ///
197    /// - [`Error::Unsupported`] if the repository mode is `bare-split-xattrs`.
198    /// - [`Error::InvalidRelated`] if an entry of `opts.related` has an empty
199    ///   name, if two entries have the same name, or if a dependency is
200    ///   absent, partial, or has a dependency of its own.
201    /// - [`Error::Core`] if the commit tuple of a dependency does not frame,
202    ///   or if its field 2 does not decode.
203    /// - [`Error::Unsupported`] if `[ex-integrity] fsverity` is `yes` and the
204    ///   fs-verity seal fails.
205    /// - [`Error::InvalidFormat`] if `opts.timestamp` is `None` and
206    ///   `SOURCE_DATE_EPOCH` is not a count of seconds.
207    /// - [`Error::InvalidFormat`] if the call reads the system clock and the
208    ///   clock is before the Unix epoch.
209    /// - [`Error::InvalidFormat`] if the call adds `ostree.sizes` and
210    ///   `opts.metadata` is not an array value.
211    /// - [`Error::InvalidFormat`] if `[ex-integrity] fsverity` or
212    ///   `[ex-integrity] composefs` in the repository config is malformed.
213    /// - [`Error::Core`] if the commit does not serialize: `opts.metadata` is
214    ///   not an `a{sv}` dict, a string holds an interior NUL byte, or the
215    ///   metadata nests too deep.
216    /// - [`Error::Core`] if `[core] fsync` or `[core] per-object-fsync` in the
217    ///   repository config is malformed.
218    /// - [`Error::Core`] if the call adds `ostree.sizes` and a dirtree that
219    ///   the commit reaches does not parse.
220    /// - [`Error::ObjectNotFound`] if the call adds `ostree.sizes` and an
221    ///   object that the commit reaches is in neither the staging directory
222    ///   nor `objects/`.
223    /// - The errors of [`load_file`](Repo::load_file) if the call adds
224    ///   `ostree.sizes` and a file object from `objects/` does not load.
225    /// - [`Error::InsufficientFreeSpace`] if the commit object needs more
226    ///   space than the free-space budget of the transaction holds.
227    /// - [`Error::Io`] if the call adds `ostree.sizes` and a dirtree that the
228    ///   commit reaches is larger than
229    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE).
230    /// - [`Error::Io`] if a file system operation fails.
231    pub async fn write_commit(&self, mut opts: CommitOptions, root: &RepoTree) -> Result<Checksum> {
232        self.resolve_commit_options(&mut opts)?;
233        let checked = self
234            .check_owned_related(std::mem::take(&mut opts.related))
235            .await?;
236        opts.related = checked.entries;
237        self.write_commit_unchecked(opts, root).await
238    }
239
240    /// Stages a commit object over the tree `root` with the dependencies
241    /// `related`, and returns its checksum.
242    ///
243    /// The call writes the commit as [`write_commit`](Transaction::write_commit)
244    /// does. Field 2 of the commit object holds the entries of `related`,
245    /// sorted by name in byte order. `opts.related` must be empty. For the
246    /// same inputs, the call and `write_commit` give the same commit.
247    ///
248    /// The call records the commit for the composefs image as `write_commit`
249    /// does.
250    ///
251    /// The call does not check the dependencies again.
252    /// [`check_related`](Transaction::check_related) checked them. A process
253    /// outside the transaction can make a dependency partial or absent after
254    /// that check: for example, an fsck, which takes no repository lock, or a
255    /// prune in a repository with `[core] locking=false`. The call does not
256    /// refuse such a dependency, and an fsck reports it.
257    ///
258    /// # Errors
259    ///
260    /// The call checks the origin of `related`, then `opts.related`, then the
261    /// repository mode, then the timestamp. On these refusals, it writes
262    /// nothing and the transaction stays open.
263    ///
264    /// - [`Error::InvalidInput`] if `related` comes from another transaction.
265    /// - [`Error::InvalidInput`] if `opts.related` is not empty.
266    /// - [`Error::Unsupported`] if the repository mode is `bare-split-xattrs`.
267    /// - [`Error::Unsupported`] if `[ex-integrity] fsverity` is `yes` and the
268    ///   fs-verity seal fails.
269    /// - [`Error::InvalidFormat`] if `opts.timestamp` is `None` and
270    ///   `SOURCE_DATE_EPOCH` is not a count of seconds.
271    /// - [`Error::InvalidFormat`] if the call reads the system clock and the
272    ///   clock is before the Unix epoch.
273    /// - [`Error::InvalidFormat`] if the call adds `ostree.sizes` and
274    ///   `opts.metadata` is not an array value.
275    /// - [`Error::InvalidFormat`] if `[ex-integrity] fsverity` or
276    ///   `[ex-integrity] composefs` in the repository config is malformed.
277    /// - [`Error::Core`] if the commit does not serialize: `opts.metadata` is
278    ///   not an `a{sv}` dict, a string holds an interior NUL byte, or the
279    ///   metadata nests too deep.
280    /// - [`Error::Core`] if `[core] fsync` or `[core] per-object-fsync` in the
281    ///   repository config is malformed.
282    /// - [`Error::Core`] if the call adds `ostree.sizes` and a dirtree that
283    ///   the commit reaches does not parse.
284    /// - [`Error::ObjectNotFound`] if the call adds `ostree.sizes` and an
285    ///   object that the commit reaches is in neither the staging directory
286    ///   nor `objects/`.
287    /// - The errors of [`load_file`](Repo::load_file) if the call adds
288    ///   `ostree.sizes` and a file object from `objects/` does not load.
289    /// - [`Error::InsufficientFreeSpace`] if the commit object needs more
290    ///   space than the free-space budget of the transaction holds.
291    /// - [`Error::Io`] if the call adds `ostree.sizes` and a dirtree that the
292    ///   commit reaches is larger than
293    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE).
294    /// - [`Error::Io`] if a file system operation fails.
295    pub async fn write_commit_checked(
296        &self,
297        mut opts: CommitOptions,
298        related: CheckedRelated<'_>,
299        root: &RepoTree,
300    ) -> Result<Checksum> {
301        if !std::ptr::eq(related.txn, self) {
302            return Err(Error::InvalidInput(
303                "the checked dependencies come from another transaction".into(),
304            ));
305        }
306        if !opts.related.is_empty() {
307            return Err(Error::InvalidInput(
308                "the commit options name dependencies; the checked dependencies give them".into(),
309            ));
310        }
311        self.resolve_commit_options(&mut opts)?;
312        opts.related = related.entries;
313        self.write_commit_unchecked(opts, root).await
314    }
315
316    /// Refuses a `bare-split-xattrs` repository and sets `opts.timestamp` to
317    /// the commit time.
318    ///
319    /// [`write_commit`](Transaction::write_commit) and
320    /// [`write_commit_checked`](Transaction::write_commit_checked) make these
321    /// steps before they write.
322    fn resolve_commit_options(&self, opts: &mut CommitOptions) -> Result<()> {
323        if self.repo().mode() == RepoMode::BareSplitXattrs {
324            return Err(Error::Unsupported(
325                "bare-split-xattrs is read-only; the port does not write it".into(),
326            ));
327        }
328        let timestamp = ostrya_core::commit_timestamp(opts.timestamp)
329            .map_err(|e| Error::InvalidFormat(e.to_string()))?;
330        opts.timestamp = Some(timestamp);
331        Ok(())
332    }
333
334    /// Checks the dependencies `related` of a new commit, as
335    /// [`write_commit`](Transaction::write_commit) checks
336    /// [`CommitOptions::related`].
337    ///
338    /// The call refuses an entry with an empty name and two entries with the
339    /// same name. Then it checks each dependency in the byte order of the
340    /// names: the dependency must be complete in the repository or in this
341    /// transaction, and it must have no dependency of its own.
342    /// [`write_commit`](Transaction::write_commit) states the rules and runs
343    /// the same checks. The call does not change `related` and writes
344    /// nothing.
345    ///
346    /// The call reads no tree. A caller can call it before it builds a large
347    /// tree, so that a refused dependency stops the work before the build.
348    ///
349    /// Returns the checked entries, sorted by name in byte order.
350    /// [`write_commit_checked`](Transaction::write_commit_checked) takes them
351    /// and writes the commit with no second check.
352    ///
353    /// # Errors
354    ///
355    /// - [`Error::InvalidRelated`] with no commit, if an entry of `related`
356    ///   has an empty name, if two entries have the same name, or if a
357    ///   dependency is absent, partial, or has a dependency of its own.
358    /// - [`Error::Core`] if the commit tuple of a dependency does not frame,
359    ///   or if its field 2 does not decode.
360    /// - [`Error::Io`] if the commit object of a dependency with no partial
361    ///   marker is larger than [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE),
362    ///   or if a file system operation fails.
363    pub async fn check_related(
364        &self,
365        related: &[(String, Checksum)],
366    ) -> Result<CheckedRelated<'_>> {
367        self.check_owned_related(related.to_vec()).await
368    }
369
370    /// Checks the dependencies `related` as
371    /// [`check_related`](Transaction::check_related) does, and keeps the
372    /// entries in the result with no copy.
373    async fn check_owned_related(
374        &self,
375        related: Vec<(String, Checksum)>,
376    ) -> Result<CheckedRelated<'_>> {
377        let entries = related::sorted_new(related)?;
378        related::check_dependencies(self, None, &entries).await?;
379        Ok(CheckedRelated { txn: self, entries })
380    }
381
382    /// Writes a commit as [`write_commit`](Transaction::write_commit) does,
383    /// with no check of the dependencies.
384    ///
385    /// Field 2 holds the entries of `opts.related` in the given order.
386    /// [`write_commit`](Transaction::write_commit) and
387    /// [`write_commit_checked`](Transaction::write_commit_checked) call it
388    /// with the sorted entries after the check. The anchor commit of a
389    /// summary uses this path, because it has no dependency. A
390    /// `bare-split-xattrs` repository refuses the write in
391    /// [`write_metadata`](Transaction::write_metadata).
392    pub(crate) async fn write_commit_unchecked(
393        &self,
394        opts: CommitOptions,
395        root: &RepoTree,
396    ) -> Result<Checksum> {
397        let timestamp = ostrya_core::commit_timestamp(opts.timestamp)
398            .map_err(|e| Error::InvalidFormat(e.to_string()))?;
399        let mut metadata = opts.metadata.unwrap_or_else(|| Value::Array(Vec::new()));
400
401        if self.generate_sizes() && self.repo().mode().is_archive() {
402            let entries = self.reachable_size_entries(root).await?;
403            let packed = ostrya_core::sizes::pack_sizes(entries);
404            let elements = packed.into_iter().map(Value::Bytes).collect();
405            let sizes_type = Type::parse(SIZES_SIGNATURE).map_err(ostrya_core::Error::from)?;
406            let sizes = Value::variant(sizes_type, Value::Array(elements));
407            append_dict_entry(&mut metadata, SIZES_KEY, sizes)?;
408        }
409
410        let commit = Commit {
411            metadata,
412            parent: opts.parent,
413            related: opts
414                .related
415                .into_iter()
416                .map(|(name, checksum)| (name, checksum.as_bytes().to_vec()))
417                .collect(),
418            subject: opts.subject.unwrap_or_default(),
419            body: opts.body.unwrap_or_default(),
420            timestamp,
421            root_dirtree: *root.dirtree_checksum(),
422            root_dirmeta: *root.dirmeta_checksum(),
423        };
424        let bytes = commit.serialize()?;
425        let checksum = self
426            .write_metadata(ObjectType::Commit, None, &bytes)
427            .await?;
428        // A commit that the repository holds already, complete or partial, is
429        // not staged, and gets no image.
430        if self.is_staged(&checksum, ObjectType::Commit) {
431            self.mark_complete(&checksum);
432        }
433        Ok(checksum)
434    }
435
436    /// Builds the `ostree.sizes` entries for `root`.
437    ///
438    /// The list has one record for each object that the committed root
439    /// reaches. It holds the objects that this transaction staged and the
440    /// objects that deduplicated against `objects/`. A staged object uses the
441    /// size record that the transaction kept. A deduplicated object gets its
442    /// sizes from its loose object. The commit object is not in the list,
443    /// because the walk starts below it.
444    async fn reachable_size_entries(&self, root: &RepoTree) -> Result<Vec<SizeEntry>> {
445        let reachable = self.reachable_objects(root).await?;
446        let staged: HashMap<Checksum, SizeEntry> = self
447            .size_entries()
448            .into_iter()
449            .map(|entry| (entry.checksum, entry))
450            .collect();
451        let mut entries = Vec::with_capacity(reachable.len());
452        for (checksum, ty) in reachable {
453            // If a commit comes from several tree sources, the key holds the
454            // objects of the last source and the directory objects that the
455            // serialization wrote. See `Transaction::begin_tree_source`.
456            if !self.in_size_scope(&checksum) {
457                continue;
458            }
459            match staged.get(&checksum) {
460                Some(entry) => entries.push(entry.clone()),
461                None => entries.push(self.recover_size_entry(checksum, ty).await?),
462            }
463        }
464        Ok(entries)
465    }
466
467    /// Returns the `ostree.sizes` entry of an object that deduplicated against
468    /// `objects/`.
469    ///
470    /// The object has no size record from this transaction. The call serves
471    /// archive mode only. The compressed size is the size of the loose object
472    /// on disk. The unpacked size is:
473    ///
474    /// - the serialized length of a metadata object
475    /// - the uncompressed payload length of a regular file
476    /// - the target length of a symlink
477    async fn recover_size_entry(&self, checksum: Checksum, ty: ObjectType) -> Result<SizeEntry> {
478        let compressed = self.repo().loose_object_size(ty, &checksum).await?;
479        let unpacked = if ty == ObjectType::File {
480            match self.repo().load_file(&checksum).await?.kind {
481                FileKind::Regular { size } => size,
482                FileKind::Symlink { target } => target.len() as u64,
483            }
484        } else {
485            // A metadata object is stored uncompressed, so its unpacked size
486            // is its size on disk.
487            compressed
488        };
489        Ok(SizeEntry {
490            checksum,
491            compressed,
492            unpacked,
493            objtype: Some(ty),
494        })
495    }
496
497    /// Returns the objects that `root` reaches, each with its type.
498    ///
499    /// The map holds the root dirmeta, each dirtree of the committed tree, each
500    /// subdirectory dirmeta, and each file entry. It limits `ostree.sizes` to
501    /// the objects of one commit, also if the transaction stages more than one
502    /// commit.
503    ///
504    /// The walk goes into each subtree, staged or not.
505    /// [`load_reachable_dirtree`](Self::load_reachable_dirtree) reads a dirtree
506    /// from the staging directory of the transaction if it is there. If the
507    /// dirtree deduplicated, it reads the loose object in `objects/`. This
508    /// read order lets the walk visit the objects of an unchanged subtree.
509    async fn reachable_objects(&self, root: &RepoTree) -> Result<HashMap<Checksum, ObjectType>> {
510        let mut reachable: HashMap<Checksum, ObjectType> = HashMap::new();
511        reachable.insert(*root.dirmeta_checksum(), ObjectType::DirMeta);
512        let mut stack = vec![*root.dirtree_checksum()];
513        while let Some(dirtree_checksum) = stack.pop() {
514            if reachable
515                .insert(dirtree_checksum, ObjectType::DirTree)
516                .is_some()
517            {
518                continue;
519            }
520            let dirtree = self.load_reachable_dirtree(&dirtree_checksum).await?;
521            for (_, file_checksum) in dirtree.files {
522                reachable.insert(file_checksum, ObjectType::File);
523            }
524            for (_, subtree, submeta) in dirtree.dirs {
525                reachable.insert(submeta, ObjectType::DirMeta);
526                stack.push(subtree);
527            }
528        }
529        Ok(reachable)
530    }
531
532    /// Loads a dirtree that the committed root reaches.
533    ///
534    /// The call reads the staging directory of the transaction first. If the
535    /// dirtree deduplicated, the call reads the loose object in `objects/`.
536    async fn load_reachable_dirtree(&self, checksum: &Checksum) -> Result<DirTree> {
537        if let Some(dirtree) = self.load_staged_dirtree(checksum).await? {
538            return Ok(dirtree);
539        }
540        self.repo().load_dirtree(checksum).await
541    }
542
543    /// Loads a dirtree from the staging directory of this transaction.
544    ///
545    /// Returns `None` if the dirtree is not there, because it deduplicated
546    /// against `objects/`.
547    async fn load_staged_dirtree(&self, checksum: &Checksum) -> Result<Option<DirTree>> {
548        let name = crate::write::flat_name(checksum, ObjectType::DirTree, self.repo().mode());
549        let staging = self.staging_fd().try_clone_to_owned()?;
550        let res = ostrya_rt::unblock(move || {
551            crate::object::read_meta_object(
552                staging.as_fd(),
553                &name,
554                crate::object::MAX_METADATA_SIZE,
555            )
556        })
557        .await;
558        match res {
559            Ok(bytes) => Ok(Some(DirTree::parse(&bytes)?)),
560            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
561            Err(e) => Err(Error::Io(e)),
562        }
563    }
564}
565
566/// Methods that read and write the detached metadata of a commit.
567impl Repo {
568    /// Returns the detached metadata of a commit, or `None` if it has none.
569    ///
570    /// The detached metadata is an `a{sv}` dict at the `.commitmeta` loose
571    /// path of the commit. It is outside the commit checksum. The call returns
572    /// `None` if the file is absent, or if it is the zero-length file that
573    /// marks no metadata. The call reads and parses the file on the blocking
574    /// pool.
575    ///
576    /// # Errors
577    ///
578    /// - [`Error::Core`] if the file does not parse as an `a{sv}` dict.
579    /// - [`Error::Io`] if the file is larger than
580    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE), or if a file system
581    ///   operation fails.
582    pub async fn read_commit_detached_metadata(
583        &self,
584        checksum: &Checksum,
585    ) -> Result<Option<Value>> {
586        let repo = self.clone();
587        let key = *checksum;
588        ostrya_rt::unblock(move || repo.read_commit_detached_metadata_blocking(&key)).await
589    }
590
591    /// Returns the related commits of the commit `commit`.
592    ///
593    /// The dependencies come from field 2 of the commit object. The build
594    /// sources come from the key `ostrya.related` of the detached metadata.
595    /// If the detached metadata is absent or has no such key, the list of
596    /// build sources is empty. If the key occurs more than one time, the
597    /// first entry gives the value. Each list keeps the stored order.
598    ///
599    /// The call checks the format alone: each entry has a name that is not
600    /// empty and a checksum of 32 bytes, and the value of `ostrya.related`
601    /// is a variant of type `a(say)`. It accepts entries that are not sorted
602    /// and two entries with the same name. It does not check that the
603    /// repository holds a related commit. The checks of the dependencies of
604    /// [`Transaction::write_commit`] apply when a commit is written.
605    ///
606    /// # Errors
607    ///
608    /// - [`Error::ObjectNotFound`] if the repository does not hold the commit
609    ///   object.
610    /// - [`Error::Core`] if the commit tuple does not frame, if field 2 does
611    ///   not decode, or if the detached metadata does not parse.
612    /// - [`Error::InvalidRelated`] with the field and the reason, if an entry
613    ///   of either field has an empty name or a checksum that is not 32
614    ///   bytes, or if the value of `ostrya.related` is not a variant of type
615    ///   `a(say)`.
616    /// - [`Error::Io`] if the commit object or the detached metadata is
617    ///   larger than [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE), or if a
618    ///   file system operation fails.
619    pub async fn read_commit_related(&self, commit: &Checksum) -> Result<CommitRelated> {
620        let repo = self.clone();
621        let commit = *commit;
622        // A commit object can be as large as `MAX_METADATA_SIZE`, so the two
623        // reads and the parse run in one call on the blocking pool. The read
624        // of the commit comes first, then the read of the `.commitmeta`, then
625        // the parse.
626        ostrya_rt::unblock(move || {
627            let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &commit)?;
628            let detached = repo.read_commit_detached_metadata_blocking(&commit)?;
629            let dependencies = related::checked_entries(
630                RelatedField::Dependencies,
631                Some(commit),
632                related::parse_dependencies(&bytes)?,
633            )?;
634            let build_sources = related::build_sources(detached.as_ref())
635                .map_err(|reason| Error::InvalidRelated {
636                    commit: Some(commit),
637                    field: RelatedField::BuildSources,
638                    reason,
639                })?
640                .map(|entries| {
641                    related::checked_entries(RelatedField::BuildSources, Some(commit), entries)
642                })
643                .transpose()?
644                .unwrap_or_default();
645            Ok(CommitRelated {
646                dependencies,
647                build_sources,
648            })
649        })
650        .await
651    }
652
653    /// Runs
654    /// [`read_commit_detached_metadata`](Repo::read_commit_detached_metadata)
655    /// on the calling thread.
656    ///
657    /// The read and the parse block the thread, so an async caller runs this
658    /// call on the blocking pool.
659    pub(crate) fn read_commit_detached_metadata_blocking(
660        &self,
661        checksum: &Checksum,
662    ) -> Result<Option<Value>> {
663        let bytes = match self.load_object_bytes_blocking(ObjectType::CommitMeta, checksum) {
664            Ok(bytes) => bytes,
665            Err(Error::ObjectNotFound { .. }) => return Ok(None),
666            Err(e) => return Err(e),
667        };
668        parse_detached_metadata(&bytes)
669    }
670
671    /// Returns the detached metadata dict of the commit `checksum` if its
672    /// `.commitmeta` can hold build sources, or `None`.
673    ///
674    /// The call reads the file as
675    /// [`read_commit_detached_metadata_blocking`](Repo::read_commit_detached_metadata_blocking)
676    /// does, and parses it with [`parse_build_source_dict`]. So a
677    /// `.commitmeta` that does not hold the key `ostrya.related` gives
678    /// `None`, also if it does not parse. The read and the parse block the
679    /// thread, so an async caller runs this call on the blocking pool.
680    ///
681    /// # Errors
682    ///
683    /// - [`Error::Core`] if the file holds the bytes of the key
684    ///   `ostrya.related` and does not parse as an `a{sv}` dict.
685    /// - [`Error::Io`] if the file is larger than
686    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE), or if a file system
687    ///   operation fails.
688    pub(crate) fn read_build_source_dict_blocking(
689        &self,
690        checksum: &Checksum,
691    ) -> Result<Option<Value>> {
692        let bytes = match self.load_object_bytes_blocking(ObjectType::CommitMeta, checksum) {
693            Ok(bytes) => bytes,
694            Err(Error::ObjectNotFound { .. }) => return Ok(None),
695            Err(e) => return Err(e),
696        };
697        parse_build_source_dict(&bytes)
698    }
699
700    /// Loads the bytes of the commit object `checksum` and its detached
701    /// metadata dict, as
702    /// [`read_build_source_dict_blocking`](Repo::read_build_source_dict_blocking)
703    /// reads it.
704    ///
705    /// The two reads and the parse run in one call on the blocking pool. The
706    /// read of the commit comes first, so a commit that this repository does
707    /// not hold gives [`Error::ObjectNotFound`] before an error of the
708    /// `.commitmeta`.
709    pub(crate) async fn load_commit_and_build_source_dict(
710        &self,
711        checksum: &Checksum,
712    ) -> Result<(Vec<u8>, Option<Value>)> {
713        let repo = self.clone();
714        let key = *checksum;
715        ostrya_rt::unblock(move || {
716            let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &key)?;
717            let detached = repo.read_build_source_dict_blocking(&key)?;
718            Ok((bytes, detached))
719        })
720        .await
721    }
722
723    /// Loads the bytes of the commit object `checksum` and its detached
724    /// metadata, as
725    /// [`read_commit_detached_metadata`](Repo::read_commit_detached_metadata)
726    /// reads it.
727    ///
728    /// The two reads and the parse run in one call on the blocking pool. The
729    /// read of the commit comes first, so a commit that this repository does
730    /// not hold gives [`Error::ObjectNotFound`] before an error of the
731    /// `.commitmeta`.
732    pub(crate) async fn load_commit_and_detached(
733        &self,
734        checksum: &Checksum,
735    ) -> Result<(Vec<u8>, Option<Value>)> {
736        let repo = self.clone();
737        let key = *checksum;
738        ostrya_rt::unblock(move || {
739            let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &key)?;
740            let detached = repo.read_commit_detached_metadata_blocking(&key)?;
741            Ok((bytes, detached))
742        })
743        .await
744    }
745
746    /// Writes or clears the detached metadata of a commit.
747    ///
748    /// If `meta` is `Some`, the call writes the `a{sv}` dict at the
749    /// `.commitmeta` loose path of the commit. If `meta` is `None`, the call
750    /// writes a zero-length file, which marks no metadata. The new file
751    /// replaces the old file atomically and gets mode `0644`. The detached
752    /// metadata is outside the commit checksum.
753    ///
754    /// The call writes a temp file in `tmp/` and renames it over the loose
755    /// path. If `[core] fsync` is on, the call syncs the file before the
756    /// rename and syncs its directory after the rename.
757    ///
758    /// # Locks
759    ///
760    /// The call takes a shared hold of the repository lock
761    /// ([`LockKind`](crate::LockKind)), then the update lock, as
762    /// [`begin_update`](Repo::begin_update) does. It writes under both locks.
763    /// If the caller holds an [`UpdateGuard`](crate::UpdateGuard) of this
764    /// repository, the call waits for that guard.
765    ///
766    /// # Build sources
767    ///
768    /// The key `ostrya.related` holds the build sources of the commit. The
769    /// call checks each entry with this key, also when the key occurs more
770    /// than one time. The value must be a variant of type `a(say)`, and each
771    /// element must have a name that is not empty and a checksum of 32 bytes.
772    /// The call accepts elements that are not sorted, two elements with the
773    /// same name, and a checksum of a commit that the repository does not
774    /// hold. It checks before it takes a lock. On a refusal the `.commitmeta`
775    /// file stays as it was.
776    ///
777    /// # Errors
778    ///
779    /// - [`Error::InvalidRelated`] with `checksum` and
780    ///   [`RelatedField::BuildSources`] if an `ostrya.related` entry of `meta`
781    ///   is not a variant of type `a(say)`, or if one of its elements has an
782    ///   empty name or a checksum that is not 32 bytes.
783    /// - [`Error::LockTimeout`] if the wait for a lock passes `[core]
784    ///   lock-timeout-secs`. Each of the two waits gets the full timeout.
785    /// - [`Error::Core`] if `meta` is not an `a{sv}` dict value.
786    /// - [`Error::Core`] if `[core] fsync` or `[core] locking` is not a
787    ///   boolean, or if `[core] lock-timeout-secs` is not an integer.
788    /// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` is less than
789    ///   `-1`.
790    /// - [`Error::Io`] with `EXDEV` if `tmp/` and `objects/` are on different
791    ///   file systems.
792    /// - [`Error::Io`] if another file system operation fails.
793    pub async fn write_commit_detached_metadata(
794        &self,
795        checksum: &Checksum,
796        meta: Option<&Value>,
797    ) -> Result<()> {
798        if let Some(meta) = meta {
799            related::check_detached(checksum, meta)?;
800        }
801        let bytes = match meta {
802            Some(value) => {
803                let ty = Type::parse(METADATA_SIGNATURE).map_err(ostrya_core::Error::from)?;
804                to_bytes(&ty, value).map_err(ostrya_core::Error::from)?
805            }
806            None => Vec::new(),
807        };
808        let fsync = self.config().fsync()?;
809        let repo_mode = self.mode();
810        let dest = loose_path(checksum, ObjectType::CommitMeta, repo_mode);
811        self.write_locked(move |repo| {
812            let tmp_fd = open_tmp_dir(repo.repo_fd(), repo_mode)?;
813            write_detached_blocking(
814                tmp_fd.as_fd(),
815                repo.objects_fd(),
816                &dest,
817                &bytes,
818                fsync,
819                repo_mode,
820            )
821        })
822        .await
823    }
824
825    /// Adds the build source `name` with the checksum `source` to the commit
826    /// `commit`.
827    ///
828    /// The build sources of a commit are the entries of the key
829    /// `ostrya.related` in its detached metadata, a variant of type `a(say)`.
830    /// Each entry is a name and the checksum of a commit. The name has the
831    /// form `<class>/<name>` by convention, for example `layer/base`. The
832    /// call checks nothing else in the name. It does not check that the
833    /// repository holds `source`. A build source can name build sources of
834    /// its own, and the add can make a cycle.
835    ///
836    /// The call edits the first `ostrya.related` entry of the detached
837    /// metadata. It removes each element with the name `name`, also when two
838    /// or more elements have that name. Then it adds the new element and
839    /// sorts the elements by name in byte order. If the detached metadata has
840    /// no such entry, the call appends one after the other entries. If the
841    /// commit has no detached metadata, the call writes a new dict with the
842    /// one entry. Each other entry stays as it is. The new file replaces the
843    /// old file atomically.
844    ///
845    /// A local prune keeps the build sources of each commit that it reaches.
846    /// [`Repo::prune`], "Related commits", states the rules.
847    ///
848    /// # Locks
849    ///
850    /// The call takes the repository lock as
851    /// [`Shared`](crate::LockKind::Shared) and the update lock, as
852    /// [`sign_commit`](Repo::sign_commit) does. Under both locks, it checks
853    /// that the repository holds the commit object, reads the dict, adds the
854    /// entry, and writes the file. A prune takes the repository lock as
855    /// [`Exclusive`](crate::LockKind::Exclusive), so it cannot delete the
856    /// commit between the check and the write. If the caller holds an
857    /// [`UpdateGuard`](crate::UpdateGuard) of this repository, the call waits
858    /// for that guard.
859    ///
860    /// # Errors
861    ///
862    /// - [`Error::InvalidRelated`] with `commit` and
863    ///   [`RelatedField::BuildSources`] if `name` is empty. The call refuses
864    ///   it before it reads anything.
865    /// - [`Error::ObjectNotFound`] if the repository does not hold the commit
866    ///   object. The call writes no file.
867    /// - [`Error::InvalidRelated`] with `commit` and
868    ///   [`RelatedField::BuildSources`] if the stored value of the first
869    ///   `ostrya.related` entry is not a variant of type `a(say)`, or if one
870    ///   of its elements has an empty name or a checksum that is not 32
871    ///   bytes. The `.commitmeta` file stays as it was.
872    /// - [`Error::LockTimeout`] if the wait for a lock passes `[core]
873    ///   lock-timeout-secs`. Each of the two waits gets the full timeout.
874    /// - [`Error::Core`] if `[core] fsync` or `[core] locking` is not a
875    ///   boolean, or if `[core] lock-timeout-secs` is not an integer.
876    /// - [`Error::Core`] if the `.commitmeta` file does not parse as an
877    ///   `a{sv}` dict.
878    /// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` is less than
879    ///   `-1`.
880    /// - [`Error::Io`] if the `.commitmeta` file is larger than
881    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE).
882    /// - [`Error::Io`] with `EXDEV` if `tmp/` and `objects/` are on different
883    ///   file systems.
884    /// - [`Error::Io`] if another file system operation fails.
885    pub async fn add_detached_related(
886        &self,
887        commit: &Checksum,
888        name: &str,
889        source: &Checksum,
890    ) -> Result<()> {
891        if name.is_empty() {
892            return Err(empty_build_source_name(commit));
893        }
894        let fsync = self.config().fsync()?;
895        let repo_mode = self.mode();
896        let checksum = *commit;
897        let related = vec![(name.to_owned(), *source)];
898        self.write_locked(move |repo| {
899            // A prune takes the exclusive lock, so the commit stays until the
900            // write ends.
901            if !repo.has_object_blocking(ObjectType::Commit, &checksum)? {
902                return Err(Error::ObjectNotFound {
903                    checksum,
904                    ty: ObjectType::Commit,
905                });
906            }
907            let tmp_fd = open_tmp_dir(repo.repo_fd(), repo_mode)?;
908            merge_detached_blocking(
909                tmp_fd.as_fd(),
910                repo.objects_fd(),
911                &checksum,
912                None,
913                None,
914                related,
915                Vec::new(),
916                fsync,
917                repo_mode,
918            )
919        })
920        .await
921    }
922}
923
924/// Returns the refusal of a build source with an empty name, for the commit
925/// `commit`.
926pub(crate) fn empty_build_source_name(commit: &Checksum) -> Error {
927    Error::InvalidRelated {
928        commit: Some(*commit),
929        field: RelatedField::BuildSources,
930        reason: "the new entry has an empty name".into(),
931    }
932}
933
934/// Parses `bytes`, the contents of a `.commitmeta` file, as detached
935/// metadata.
936///
937/// Returns `None` for a zero-length file. Such a file marks deleted
938/// metadata. It is not an empty dict. The parse blocks the thread, so an
939/// async caller runs it on the blocking pool.
940///
941/// # Errors
942///
943/// [`Error::Core`] if `bytes` does not parse as an `a{sv}` dict.
944pub(crate) fn parse_detached_metadata(bytes: &[u8]) -> Result<Option<Value>> {
945    crate::summary::parse_signature_dict(bytes)
946}
947
948/// Parses `bytes`, the contents of a `.commitmeta` file, as detached
949/// metadata only if they can hold build sources.
950///
951/// Returns `None` with no parse if
952/// [`may_hold_build_sources`](related::may_hold_build_sources) does not
953/// accept `bytes`. Else the result is the result of
954/// [`parse_detached_metadata`]. The parse blocks the thread, so an async
955/// caller runs it on the blocking pool.
956///
957/// # Errors
958///
959/// [`Error::Core`] if `bytes` hold the bytes of the key `ostrya.related` and
960/// do not parse as an `a{sv}` dict.
961pub(crate) fn parse_build_source_dict(bytes: &[u8]) -> Result<Option<Value>> {
962    if !related::may_hold_build_sources(bytes) {
963        return Ok(None);
964    }
965    parse_detached_metadata(bytes)
966}
967
968/// Appends one entry to an `a{sv}` dict value, after its existing entries.
969pub(crate) fn append_dict_entry(metadata: &mut Value, key: &str, value: Value) -> Result<()> {
970    match metadata {
971        Value::Array(entries) => {
972            entries.push(Value::Tuple(vec![Value::Str(key.to_owned()), value]));
973            Ok(())
974        }
975        _ => Err(Error::InvalidFormat(
976            "commit metadata must be an a{sv} dict".into(),
977        )),
978    }
979}
980
981/// Applies one edit of the detached metadata at the `.commitmeta` loose path
982/// of a commit.
983///
984/// The call runs on the blocking pool. The edit starts from a base dict:
985///
986/// - `replace`, if it is `Some`, in place of the dict of the file
987/// - else the dict that the file holds
988/// - else an empty dict, if the file is absent or is the zero-length marker
989///
990/// If `merge` is given, it holds a serialized `a{sv}` dict and a list of
991/// keys. The call merges that dict into the base dict with a union of each
992/// signature list. The listed keys keep the value that the base dict holds.
993/// Next, the call adds the entries of `build_sources` to the first
994/// `ostrya.related` entry in one step. The result is the same as one add of
995/// each entry, in order, as [`Repo::add_detached_related`] states.
996/// Then each entry of `appends` appends one signature to the `aay` array of
997/// its engine, in order. The result replaces the file atomically. If a step
998/// fails, the file stays as it was.
999///
1000/// The read, the merge, and the write run as one step under
1001/// [`DETACHED_MERGE`], for this edit only. Because the guard covers one edit,
1002/// a caller can apply several edits in one call on the blocking pool. The
1003/// caller holds the update lock.
1004#[allow(clippy::too_many_arguments)]
1005pub(crate) fn merge_detached_blocking(
1006    tmp_fd: BorrowedFd<'_>,
1007    objects_fd: BorrowedFd<'_>,
1008    checksum: &Checksum,
1009    replace: Option<Value>,
1010    merge: Option<(Vec<u8>, Vec<String>)>,
1011    build_sources: Vec<(String, Checksum)>,
1012    appends: Vec<(String, Vec<u8>)>,
1013    fsync: bool,
1014    repo_mode: RepoMode,
1015) -> Result<()> {
1016    let dest = loose_path(checksum, ObjectType::CommitMeta, repo_mode);
1017    edit_detached_blocking(tmp_fd, objects_fd, &dest, fsync, repo_mode, |read| {
1018        let base = match replace {
1019            Some(dict) => Some(dict),
1020            None => read()?,
1021        };
1022        // Only a receiving session queues a merge.
1023        let mut dict = match merge {
1024            #[cfg(feature = "receive")]
1025            Some((incoming, keep)) => match crate::summary::parse_signature_dict(&incoming)? {
1026                Some(incoming) => crate::receive::merge_detached(base, incoming, &keep)?,
1027                None => base.unwrap_or_else(|| Value::Array(Vec::new())),
1028            },
1029            _ => base.unwrap_or_else(|| Value::Array(Vec::new())),
1030        };
1031        related::add_build_sources(&mut dict, checksum, build_sources)?;
1032        for (key, signature) in appends {
1033            crate::sign::append_signature(&mut dict, &key, signature)?;
1034        }
1035        Ok((DetachedWrite::Dict(dict), ()))
1036    })
1037}
1038
1039/// Removes signatures at the `.commitmeta` loose path of a commit.
1040///
1041/// The call runs on the blocking pool. `remove(payload, blob)` decides for
1042/// each blob under `metadata_key`. `payload` is the canonical bytes of the
1043/// commit. The read, the removal, and the write run as one step under
1044/// [`DETACHED_MERGE`], as in [`merge_detached_blocking`]. The caller holds the
1045/// update lock.
1046///
1047/// Returns the number of blobs removed. If the count is zero, the file stays
1048/// as it is. If the removal empties the dict, the call writes the zero-length
1049/// "no metadata" marker.
1050#[allow(clippy::too_many_arguments)]
1051pub(crate) fn prune_detached_signatures_blocking(
1052    tmp_fd: BorrowedFd<'_>,
1053    objects_fd: BorrowedFd<'_>,
1054    checksum: &Checksum,
1055    metadata_key: &str,
1056    payload: &[u8],
1057    remove: &mut dyn FnMut(&[u8], &[u8]) -> bool,
1058    fsync: bool,
1059    repo_mode: RepoMode,
1060) -> Result<usize> {
1061    let dest = loose_path(checksum, ObjectType::CommitMeta, repo_mode);
1062    edit_detached_blocking(tmp_fd, objects_fd, &dest, fsync, repo_mode, |read| {
1063        let Some(mut dict) = read()? else {
1064            return Ok((DetachedWrite::Keep, 0));
1065        };
1066        let removed = crate::sign::remove_signatures(&mut dict, metadata_key, payload, remove)?;
1067        if removed == 0 {
1068            return Ok((DetachedWrite::Keep, 0));
1069        }
1070        let empty = matches!(&dict, Value::Array(entries) if entries.is_empty());
1071        let write = if empty {
1072            DetachedWrite::Marker
1073        } else {
1074            DetachedWrite::Dict(dict)
1075        };
1076        Ok((write, removed))
1077    })
1078}
1079
1080/// Writes detached metadata to the file `name` in a staging directory.
1081///
1082/// [`install_detached_blocking`] moves the file into `objects/` at the
1083/// transaction commit. The file gets the `0644` of each metadata object. If a
1084/// file exists at `name`, the call replaces it. The call syncs nothing,
1085/// because the transaction commit makes the file durable before the install.
1086pub(crate) fn stage_detached_blocking(
1087    staging_fd: BorrowedFd<'_>,
1088    name: &str,
1089    bytes: &[u8],
1090) -> Result<()> {
1091    use std::io::Write;
1092
1093    let fd = rustix::fs::openat(
1094        staging_fd,
1095        name,
1096        OFlags::WRONLY | OFlags::CREATE | OFlags::TRUNC | OFlags::CLOEXEC | OFlags::NOFOLLOW,
1097        Mode::from_raw_mode(COMMITMETA_MODE),
1098    )?;
1099    let mut file = std::fs::File::from(fd);
1100    file.write_all(bytes)?;
1101    file.flush()?;
1102    rustix::fs::fchmod(file.as_fd(), Mode::from_raw_mode(COMMITMETA_MODE))?;
1103    Ok(())
1104}
1105
1106/// Renames each staged file in `staged` over the `.commitmeta` loose path of
1107/// its commit.
1108///
1109/// The call runs under [`DETACHED_MERGE`]. It creates each fanout directory
1110/// on demand, as [`write_detached_blocking`] does. If fsync is on, the call
1111/// runs `fsync` once on each fanout directory that got a file, after the last
1112/// rename. It also runs `fsync` once on `objects/` if it created a fanout
1113/// directory.
1114///
1115/// The caller holds the update lock. If fsync is on, the staged files are
1116/// durable before the call.
1117pub(crate) fn install_detached_blocking(
1118    staging_fd: BorrowedFd<'_>,
1119    staged: &[(&Checksum, &str)],
1120    objects_fd: BorrowedFd<'_>,
1121    fsync: bool,
1122    repo_mode: RepoMode,
1123) -> Result<()> {
1124    let _guard = DETACHED_MERGE.lock().unwrap_or_else(|err| err.into_inner());
1125    // Each fanout directory that got a file, and `true` if this call created
1126    // it.
1127    let mut fanouts = std::collections::BTreeMap::<String, bool>::new();
1128    for (checksum, name) in staged {
1129        let dest = loose_path(checksum, ObjectType::CommitMeta, repo_mode);
1130        let fanout = &dest[..2];
1131        let created = create_fanout(objects_fd, fanout, repo_mode)?;
1132        rustix::fs::renameat(staging_fd, *name, objects_fd, dest.as_str())?;
1133        *fanouts.entry(fanout.to_owned()).or_default() |= created;
1134    }
1135    if fsync {
1136        for fanout in fanouts.keys() {
1137            sync_fanout(objects_fd, fanout, false)?;
1138        }
1139        if fanouts.values().any(|&created| created) {
1140            rustix::fs::fsync(objects_fd)?;
1141        }
1142    }
1143    Ok(())
1144}
1145
1146/// The process-wide mutex of each edit of a `.commitmeta` file.
1147///
1148/// It serializes the read-modify-write cycle of [`edit_detached_blocking`]
1149/// and the install of a staged file. The section holds one small read, one
1150/// serialization, and one atomic rename. It holds no await, so it cannot
1151/// block a task.
1152///
1153/// Each edit of a `.commitmeta` also runs under the update lock. That lock
1154/// excludes other processes and the other writers of this process. If two
1155/// processes sign one commit at the same time, both signatures stay. The
1156/// mutex guards only a caller of this process that edits without the update
1157/// lock.
1158static DETACHED_MERGE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1159
1160/// The result of one guarded edit at a `.commitmeta` loose path.
1161enum DetachedWrite {
1162    /// The bytes of this `a{sv}` dict replace the file.
1163    Dict(Value),
1164    /// The zero-length "no metadata" marker replaces the file.
1165    Marker,
1166    /// The file stays as it is.
1167    Keep,
1168}
1169
1170/// Runs one read-modify-write of a `.commitmeta` loose path under
1171/// [`DETACHED_MERGE`].
1172///
1173/// `edit` receives a reader of the stored dict. The reader returns the
1174/// `a{sv}` dict of the file, or `None` if the file is absent or is the
1175/// zero-length marker. `edit` returns what to leave at the path and the value
1176/// for the caller. The reader, `edit`, and the write all run inside the guard,
1177/// so no other edit of this process occurs between them.
1178fn edit_detached_blocking<T>(
1179    tmp_fd: BorrowedFd<'_>,
1180    objects_fd: BorrowedFd<'_>,
1181    dest: &str,
1182    fsync: bool,
1183    repo_mode: RepoMode,
1184    edit: impl FnOnce(&dyn Fn() -> Result<Option<Value>>) -> Result<(DetachedWrite, T)>,
1185) -> Result<T> {
1186    let ty = Type::parse(METADATA_SIGNATURE).map_err(ostrya_core::Error::from)?;
1187    let _guard = DETACHED_MERGE.lock().unwrap_or_else(|err| err.into_inner());
1188    let (write, value) = edit(&|| read_detached_blocking(objects_fd, dest, &ty))?;
1189    match write {
1190        DetachedWrite::Dict(dict) => {
1191            let bytes = to_bytes(&ty, &dict).map_err(ostrya_core::Error::from)?;
1192            write_detached_blocking(tmp_fd, objects_fd, dest, &bytes, fsync, repo_mode)?;
1193        }
1194        DetachedWrite::Marker => {
1195            write_detached_blocking(tmp_fd, objects_fd, dest, &[], fsync, repo_mode)?
1196        }
1197        DetachedWrite::Keep => {}
1198    }
1199    Ok(value)
1200}
1201
1202/// Reads the `a{sv}` dict at a `.commitmeta` loose path.
1203///
1204/// Returns `None` if the file is absent or is the zero-length "no metadata"
1205/// marker.
1206fn read_detached_blocking(
1207    objects_fd: BorrowedFd<'_>,
1208    dest: &str,
1209    ty: &Type,
1210) -> Result<Option<Value>> {
1211    let bytes =
1212        match crate::object::read_meta_object(objects_fd, dest, crate::object::MAX_METADATA_SIZE) {
1213            Ok(bytes) => bytes,
1214            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1215            Err(err) => return Err(Error::Io(err)),
1216        };
1217    if bytes.is_empty() {
1218        return Ok(None);
1219    }
1220    Ok(Some(
1221        ostrya_core::from_bytes(ty, &bytes).map_err(ostrya_core::Error::from)?,
1222    ))
1223}
1224
1225/// Writes metadata bytes to a loose path atomically.
1226///
1227/// The detached metadata writers use it for a `.commitmeta` file. The prune
1228/// sweep uses it for a `.tombstone-commit` file. Both objects get the `0644`
1229/// of each metadata object. `tmp_fd` is the open `tmp/` directory of the
1230/// repository. The steps are:
1231///
1232/// 1. The call creates the fanout directory if it is absent, with `0777`
1233///    reduced by the umask. If the call creates it in a `bare-user-shared`
1234///    repository, the mode is [`perm::SHARED_DIR_MODE`].
1235/// 2. The call writes the bytes to a temp file in `tmp/` and runs `fchmod`
1236///    0644. If fsync is on, it runs `fdatasync` on the file.
1237/// 3. The call renames the temp file over the target. If `tmp/` is on another
1238///    file system, the rename fails with `EXDEV` and the temp file is removed.
1239/// 4. If fsync is on, the call runs `fsync` on the fanout directory, so the
1240///    new name survives a crash. If the call created the fanout directory, it
1241///    also runs `fsync` on `objects/`.
1242///
1243/// The object publication path gives the same durability.
1244pub(crate) fn write_detached_blocking(
1245    tmp_fd: BorrowedFd<'_>,
1246    objects_fd: BorrowedFd<'_>,
1247    dest: &str,
1248    bytes: &[u8],
1249    fsync: bool,
1250    repo_mode: RepoMode,
1251) -> Result<()> {
1252    use std::io::Write;
1253
1254    let fanout = &dest[..2];
1255    let fanout_created = create_fanout(objects_fd, fanout, repo_mode)?;
1256
1257    let (temp, fd) = TempEntry::create_file(tmp_fd, META_TEMP_PREFIX, COMMITMETA_MODE)?;
1258    let mut file = std::fs::File::from(fd);
1259    file.write_all(bytes)?;
1260    file.flush()?;
1261    rustix::fs::fchmod(file.as_fd(), Mode::from_raw_mode(COMMITMETA_MODE))?;
1262    if fsync {
1263        rustix::fs::fdatasync(file.as_fd())?;
1264    }
1265    drop(file);
1266    temp.rename_into(objects_fd, dest)?;
1267    if fsync {
1268        sync_fanout(objects_fd, fanout, fanout_created)?;
1269    }
1270    Ok(())
1271}
1272
1273/// Creates the fanout directory `fanout` under `objects/` if it is absent.
1274///
1275/// The directory gets `0777` reduced by the umask. In a `bare-user-shared`
1276/// repository, its mode is [`perm::SHARED_DIR_MODE`]. Returns `true` if this
1277/// call created the directory.
1278fn create_fanout(objects_fd: BorrowedFd<'_>, fanout: &str, repo_mode: RepoMode) -> Result<bool> {
1279    match rustix::fs::mkdirat(objects_fd, fanout, Mode::from_raw_mode(0o777)) {
1280        Ok(()) => {
1281            perm::force_created_dir(objects_fd, fanout, repo_mode)?;
1282            Ok(true)
1283        }
1284        Err(Errno::EXIST) => Ok(false),
1285        Err(e) => Err(e.into()),
1286    }
1287}
1288
1289/// Makes a directory entry renamed into `fanout` durable.
1290///
1291/// The call runs `fsync` on the fanout directory. If `created` is `true`, the
1292/// fanout directory is new, and the call also runs `fsync` on `objects/`.
1293fn sync_fanout(objects_fd: BorrowedFd<'_>, fanout: &str, created: bool) -> Result<()> {
1294    let dir = rustix::fs::openat(
1295        objects_fd,
1296        fanout,
1297        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
1298        Mode::empty(),
1299    )?;
1300    rustix::fs::fsync(&dir)?;
1301    if created {
1302        rustix::fs::fsync(objects_fd)?;
1303    }
1304    Ok(())
1305}