ostrya 0.2.8

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Commit assembly and detached commit metadata.
//!
//! [`Transaction::write_commit`] serializes a commit object over a written root
//! tree and stages it like any other metadata object. The caller supplies the
//! commit's metadata dict, parent, subject, body, and timestamp through
//! [`CommitOptions`]; the well-known binding keys (`ostree.ref-binding`,
//! `ostree.collection-binding`) are ordinary metadata entries the caller
//! provides, so `write_commit` adds nothing of its own beyond `ostree.sizes`.
//!
//! `ostree.sizes` is emitted only when a filesystem ingest requested
//! [`GENERATE_SIZES`](crate::CommitModifierFlags::GENERATE_SIZES) and the
//! repository is archive mode; it is appended as the last metadata entry,
//! matching the tool. Its records cover exactly the objects reachable from the
//! committed root -- the root dirmeta, each dirtree, each subdirectory dirmeta,
//! and each file entry -- and no others, so a transaction that stages more than
//! one commit gives each commit its own reachable-scoped key. The set is
//! recovered by walking the committed tree at commit time. A freshly staged
//! object uses the size record the transaction kept; an object that already
//! existed in `objects/` and deduplicated has its sizes recovered from its loose
//! object, so an incremental commit that reaches pre-existing objects lists them
//! too, matching the tool. The commit object itself is never among them, since
//! the walk starts below it. In every other mode the request is a silent no-op,
//! so a commit's bytes are identical with and without it.
//!
//! Detached metadata ([`read_commit_detached_metadata`](Repo::read_commit_detached_metadata),
//! [`write_commit_detached_metadata`](Repo::write_commit_detached_metadata))
//! is a bare `a{sv}` at the commit's `.commitmeta` loose path, replaced
//! atomically and outside the commit checksum. Writing `None` produces the
//! documented zero-length file.

use std::collections::HashMap;
use std::os::fd::{AsFd, BorrowedFd};

use ostrya_core::sizes::SizeEntry;
use ostrya_core::{
    Checksum, Commit, DirTree, ObjectType, RepoMode, Type, Value, loose_path, to_bytes,
};
use rustix::fs::{AtFlags, Mode, OFlags};
use rustix::io::Errno;

use crate::error::{Error, Result};
use crate::file::FileKind;
use crate::perm;
use crate::repo::Repo;
use crate::transaction::Transaction;
use crate::tree::RepoTree;

/// The metadata dict type string for detached commit metadata and, wrapped in
/// the commit tuple, the commit metadata dict.
const METADATA_SIGNATURE: &str = "a{sv}";
/// The `ostree.sizes` value type: an array of packed byte buffers.
const SIZES_SIGNATURE: &str = "aay";
/// The metadata key `ostree.sizes` is written under.
const SIZES_KEY: &str = "ostree.sizes";
/// The permission bits forced on the `.commitmeta` file, matching the `0644`
/// every metadata object carries.
const COMMITMETA_MODE: u32 = 0o644;

/// Options for [`Transaction::write_commit`].
///
/// Every field is optional. `metadata`, when set, must be an `a{sv}` dict
/// value; its entries appear in the commit in insertion order, which byte
/// identity with a tool commit relies on, so a caller reproducing a tool commit
/// supplies the binding keys in the tool's observed order.
#[derive(Debug, Default, Clone)]
pub struct CommitOptions {
    /// The parent commit, or `None` for a root commit.
    pub parent: Option<Checksum>,
    /// The commit subject; an empty string when `None`.
    pub subject: Option<String>,
    /// The commit body; an empty string when `None`.
    pub body: Option<String>,
    /// The commit timestamp in seconds since the Unix epoch, UTC. When `None`,
    /// `SOURCE_DATE_EPOCH` is used if set, otherwise the current time.
    pub timestamp: Option<u64>,
    /// The `a{sv}` metadata dict, or `None` for an empty dict.
    pub metadata: Option<Value>,
}

impl Transaction {
    /// Assemble a commit object over `root` and stage it, returning its
    /// checksum.
    ///
    /// The commit's metadata dict comes from `opts.metadata` (empty when
    /// unset); `ostree.sizes` is appended when the transaction was marked for
    /// size generation and the repository is archive mode. The timestamp
    /// resolves from `opts.timestamp`, else `SOURCE_DATE_EPOCH`, else the
    /// current time. The root dirtree and dirmeta come from `root`.
    pub async fn write_commit(&self, opts: CommitOptions, root: &RepoTree) -> Result<Checksum> {
        if self.repo().mode() == RepoMode::BareSplitXattrs {
            return Err(Error::Unsupported(
                "bare-split-xattrs is read-only; the port does not write it".into(),
            ));
        }

        let timestamp = resolve_timestamp(opts.timestamp)?;
        let mut metadata = opts.metadata.unwrap_or_else(|| Value::Array(Vec::new()));

        if self.generate_sizes() && self.repo().mode().is_archive() {
            let entries = self.reachable_size_entries(root).await?;
            let packed = ostrya_core::sizes::pack_sizes(entries);
            let elements = packed.into_iter().map(Value::Bytes).collect();
            let sizes_type = Type::parse(SIZES_SIGNATURE).map_err(ostrya_core::Error::from)?;
            let sizes = Value::variant(sizes_type, Value::Array(elements));
            append_dict_entry(&mut metadata, SIZES_KEY, sizes)?;
        }

        let commit = Commit {
            metadata,
            parent: opts.parent,
            related: Vec::new(),
            subject: opts.subject.unwrap_or_default(),
            body: opts.body.unwrap_or_default(),
            timestamp,
            root_dirtree: *root.dirtree_checksum(),
            root_dirmeta: *root.dirmeta_checksum(),
        };
        let bytes = commit.serialize()?;
        self.write_metadata(ObjectType::Commit, None, &bytes).await
    }

    /// Build the `ostree.sizes` entries for `root`: one record per object
    /// reachable from the committed root, covering both the objects this
    /// transaction freshly staged and the objects that already existed in
    /// `objects/` and deduplicated. A freshly staged object uses the size record
    /// the transaction kept; a deduplicated object has its sizes recovered from
    /// its loose object. The commit object itself is never among them, since the
    /// walk starts below it.
    async fn reachable_size_entries(&self, root: &RepoTree) -> Result<Vec<SizeEntry>> {
        let reachable = self.reachable_objects(root).await?;
        let staged: HashMap<Checksum, SizeEntry> = self
            .size_entries()
            .into_iter()
            .map(|entry| (entry.checksum, entry))
            .collect();
        let mut entries = Vec::with_capacity(reachable.len());
        for (checksum, ty) in reachable {
            // A commit composed from several tree sources scopes the key to the
            // objects the last source contributed plus the directory objects the
            // serialization wrote; see
            // [`begin_tree_source`](Transaction::begin_tree_source).
            if !self.in_size_scope(&checksum) {
                continue;
            }
            match staged.get(&checksum) {
                Some(entry) => entries.push(entry.clone()),
                None => entries.push(self.recover_size_entry(checksum, ty).await?),
            }
        }
        Ok(entries)
    }

    /// Recover the `ostree.sizes` entry for a reachable object that deduplicated
    /// against `objects/`, so has no freshly staged size record. Archive mode
    /// only. The compressed size is the loose object's on-disk size; the
    /// unpacked size is a metadata object's serialized byte length, a regular
    /// file's uncompressed payload length, or a symlink's target length.
    async fn recover_size_entry(&self, checksum: Checksum, ty: ObjectType) -> Result<SizeEntry> {
        let compressed = self.repo().loose_object_size(ty, &checksum).await?;
        let unpacked = if ty == ObjectType::File {
            match self.repo().load_file(&checksum).await?.kind {
                FileKind::Regular { size } => size,
                FileKind::Symlink { target } => target.len() as u64,
            }
        } else {
            // A metadata object is stored uncompressed, so its unpacked size
            // equals its on-disk size.
            compressed
        };
        Ok(SizeEntry {
            checksum,
            compressed,
            unpacked,
            objtype: Some(ty),
        })
    }

    /// Collect the objects reachable from `root`, each mapped to its type: the
    /// root dirmeta, every dirtree in the committed tree, each subdirectory
    /// dirmeta, and each file entry. Used to scope `ostree.sizes` to one commit's
    /// objects even when the transaction stages more than one commit.
    ///
    /// The walk descends into every subtree, whether freshly staged or
    /// pre-existing: [`load_reachable_dirtree`](Self::load_reachable_dirtree)
    /// reads a dirtree from the transaction's staging directory when present, and
    /// falls back to the published `objects/` loose object when it deduplicated,
    /// so an unchanged subtree's objects are visited instead of being skipped.
    async fn reachable_objects(&self, root: &RepoTree) -> Result<HashMap<Checksum, ObjectType>> {
        let mut reachable: HashMap<Checksum, ObjectType> = HashMap::new();
        reachable.insert(*root.dirmeta_checksum(), ObjectType::DirMeta);
        let mut stack = vec![*root.dirtree_checksum()];
        while let Some(dirtree_checksum) = stack.pop() {
            if reachable
                .insert(dirtree_checksum, ObjectType::DirTree)
                .is_some()
            {
                continue;
            }
            let dirtree = self.load_reachable_dirtree(&dirtree_checksum).await?;
            for (_, file_checksum) in dirtree.files {
                reachable.insert(file_checksum, ObjectType::File);
            }
            for (_, subtree, submeta) in dirtree.dirs {
                reachable.insert(submeta, ObjectType::DirMeta);
                stack.push(subtree);
            }
        }
        Ok(reachable)
    }

    /// Load a dirtree reachable from the committed root: from the transaction's
    /// staging directory when freshly staged, else from the published `objects/`
    /// loose object when it deduplicated.
    async fn load_reachable_dirtree(&self, checksum: &Checksum) -> Result<DirTree> {
        if let Some(dirtree) = self.load_staged_dirtree(checksum).await? {
            return Ok(dirtree);
        }
        self.repo().load_dirtree(checksum).await
    }

    /// Load a dirtree staged in this transaction, or `None` when it is not in
    /// the staging directory because it deduplicated against `objects/`.
    async fn load_staged_dirtree(&self, checksum: &Checksum) -> Result<Option<DirTree>> {
        let name = crate::write::flat_name(checksum, ObjectType::DirTree, self.repo().mode());
        let staging = self.staging_fd().try_clone_to_owned()?;
        let res = ostrya_rt::unblock(move || {
            crate::object::read_meta_object(
                staging.as_fd(),
                &name,
                crate::object::MAX_METADATA_SIZE,
            )
        })
        .await;
        match res {
            Ok(bytes) => Ok(Some(DirTree::parse(&bytes)?)),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(Error::Io(e)),
        }
    }
}

impl Repo {
    /// Read a commit's detached metadata, or `None` when absent or stored as
    /// the zero-length "no metadata" file.
    pub async fn read_commit_detached_metadata(
        &self,
        checksum: &Checksum,
    ) -> Result<Option<Value>> {
        let bytes = match self
            .load_object_bytes(ObjectType::CommitMeta, checksum)
            .await
        {
            Ok(bytes) => bytes,
            Err(Error::ObjectNotFound { .. }) => return Ok(None),
            Err(e) => return Err(e),
        };
        // A zero-length file is the documented deletion marker, not an empty
        // dict.
        if bytes.is_empty() {
            return Ok(None);
        }
        let ty = Type::parse(METADATA_SIGNATURE).map_err(ostrya_core::Error::from)?;
        Ok(Some(
            ostrya_core::from_bytes(&ty, &bytes).map_err(ostrya_core::Error::from)?,
        ))
    }

    /// Write (or clear) a commit's detached metadata at its `.commitmeta` loose
    /// path, replaced atomically. `Some(meta)` serializes the `a{sv}` dict;
    /// `None` writes the documented zero-length file.
    pub async fn write_commit_detached_metadata(
        &self,
        checksum: &Checksum,
        meta: Option<&Value>,
    ) -> Result<()> {
        let bytes = match meta {
            Some(value) => {
                let ty = Type::parse(METADATA_SIGNATURE).map_err(ostrya_core::Error::from)?;
                to_bytes(&ty, value).map_err(ostrya_core::Error::from)?
            }
            None => Vec::new(),
        };
        let fsync = self.config().fsync()?;
        self.write_commit_detached_bytes(checksum, bytes, fsync)
            .await
    }

    /// Apply one detached-metadata edit at a commit's `.commitmeta` loose path.
    ///
    /// `replace` is the dict that stands in for whatever the file holds; with
    /// `None` the edit starts from the file's own dict, or from an empty dict
    /// where the file is absent or is the zero-length marker. Each entry of
    /// `appends` then appends one signature to its engine's `aay` array, in
    /// order, and the result replaces the file atomically.
    ///
    /// The read, the merge and the replacing write run as one step under
    /// [`DETACHED_MERGE`], a guard the whole process shares, so two signers of
    /// one commit both reach the file whichever transactions they belong to.
    /// The same guard covers the other read-modify-write paths of this crate,
    /// [`Repo::sign_commit`] and [`Repo::delete_signatures`]. Two writers stand
    /// outside it: a caller that replaces the file through
    /// [`write_commit_detached_metadata`](Repo::write_commit_detached_metadata),
    /// and a second process, since the guard lives in this process alone.
    pub(crate) async fn merge_commit_detached_metadata(
        &self,
        checksum: &Checksum,
        replace: Option<Value>,
        appends: Vec<(String, Vec<u8>)>,
        fsync: bool,
    ) -> Result<()> {
        let repo_mode = self.mode();
        let dest = loose_path(checksum, ObjectType::CommitMeta, repo_mode);
        let objects_fd = self.objects_fd().try_clone_to_owned()?;
        ostrya_rt::unblock(move || {
            edit_detached_blocking(objects_fd.as_fd(), &dest, fsync, repo_mode, |read| {
                let mut dict = match replace {
                    Some(dict) => dict,
                    None => read()?.unwrap_or_else(|| Value::Array(Vec::new())),
                };
                for (key, signature) in appends {
                    crate::sign::append_signature(&mut dict, &key, signature)?;
                }
                Ok((DetachedWrite::Dict(dict), ()))
            })
        })
        .await
    }

    /// Remove signatures at a commit's `.commitmeta` loose path.
    ///
    /// `remove(payload, blob)` decides each blob stored under `metadata_key`,
    /// where `payload` is the commit's canonical bytes. The read, the removal
    /// and the replacing write run as one step under [`DETACHED_MERGE`], the
    /// guard [`merge_commit_detached_metadata`](Repo::merge_commit_detached_metadata)
    /// takes, so a signer that runs at the same time in this process keeps its
    /// signature. Returns the number of blobs removed: zero leaves the file as
    /// it stands, and a dict the removal empties is written as the zero-length
    /// "no metadata" marker.
    pub(crate) async fn prune_commit_detached_signatures(
        &self,
        checksum: &Checksum,
        metadata_key: String,
        payload: Vec<u8>,
        mut remove: impl FnMut(&[u8], &[u8]) -> bool + Send + 'static,
        fsync: bool,
    ) -> Result<usize> {
        let repo_mode = self.mode();
        let dest = loose_path(checksum, ObjectType::CommitMeta, repo_mode);
        let objects_fd = self.objects_fd().try_clone_to_owned()?;
        ostrya_rt::unblock(move || {
            edit_detached_blocking(objects_fd.as_fd(), &dest, fsync, repo_mode, |read| {
                let Some(mut dict) = read()? else {
                    return Ok((DetachedWrite::Keep, 0));
                };
                let removed = crate::sign::remove_signatures(
                    &mut dict,
                    &metadata_key,
                    &payload,
                    &mut remove,
                )?;
                if removed == 0 {
                    return Ok((DetachedWrite::Keep, 0));
                }
                let empty = matches!(&dict, Value::Array(entries) if entries.is_empty());
                let write = if empty {
                    DetachedWrite::Marker
                } else {
                    DetachedWrite::Dict(dict)
                };
                Ok((write, removed))
            })
        })
        .await
    }

    /// Write a commit's detached metadata from its serialized bytes, replaced
    /// atomically, syncing it where `fsync` is set. Used by the pull path,
    /// which copies a source repository's `.commitmeta` verbatim rather than
    /// re-serializing a decoded dict, under its transaction's fsync policy.
    pub(crate) async fn write_commit_detached_bytes(
        &self,
        checksum: &Checksum,
        bytes: Vec<u8>,
        fsync: bool,
    ) -> Result<()> {
        let repo_mode = self.mode();
        let dest = loose_path(checksum, ObjectType::CommitMeta, repo_mode);
        let objects_fd = self.objects_fd().try_clone_to_owned()?;
        ostrya_rt::unblock(move || {
            write_detached_blocking(objects_fd.as_fd(), &dest, &bytes, fsync, repo_mode)
        })
        .await
    }
}

/// Resolve a commit timestamp: an explicit value, else `SOURCE_DATE_EPOCH`,
/// else the current time. A malformed `SOURCE_DATE_EPOCH` is an error rather
/// than a silent fallback, matching the reproducible-build convention.
fn resolve_timestamp(explicit: Option<u64>) -> Result<u64> {
    if let Some(timestamp) = explicit {
        return Ok(timestamp);
    }
    if let Ok(raw) = std::env::var("SOURCE_DATE_EPOCH") {
        return raw.trim().parse::<u64>().map_err(|_| {
            Error::InvalidFormat(format!(
                "SOURCE_DATE_EPOCH is not a Unix timestamp: {raw:?}"
            ))
        });
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|_| Error::InvalidFormat("the system clock is before the Unix epoch".into()))?;
    Ok(now.as_secs())
}

/// Append one entry to an `a{sv}` dict value, preserving insertion order.
pub(crate) fn append_dict_entry(metadata: &mut Value, key: &str, value: Value) -> Result<()> {
    match metadata {
        Value::Array(entries) => {
            entries.push(Value::Tuple(vec![Value::Str(key.to_owned()), value]));
            Ok(())
        }
        _ => Err(Error::InvalidFormat(
            "commit metadata must be an a{sv} dict".into(),
        )),
    }
}

/// Serializes the read-modify-write cycle behind
/// [`edit_detached_blocking`] across the whole process. The section holds one
/// small read, one serialize and one atomic rename, and it holds no await, so
/// it cannot block a task. It reaches this process alone: two processes that
/// sign one commit at the same time can still lose a signature, which is what
/// the `ostree` tool does.
static DETACHED_MERGE: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// What one guarded edit leaves at a `.commitmeta` loose path.
enum DetachedWrite {
    /// Replace the file with this `a{sv}` dict's bytes.
    Dict(Value),
    /// Replace the file with the zero-length "no metadata" marker.
    Marker,
    /// Leave the file as it stands.
    Keep,
}

/// Run one read-modify-write of a `.commitmeta` loose path under
/// [`DETACHED_MERGE`].
///
/// `edit` receives a reader for the stored dict -- the `a{sv}` the file holds,
/// or `None` where the file is absent or is the zero-length marker -- and
/// returns what to leave at the path together with the value the caller wants
/// back. The reader, `edit` and the write all run inside the guard, so no other
/// edit of this process lands between them.
fn edit_detached_blocking<T>(
    objects_fd: BorrowedFd<'_>,
    dest: &str,
    fsync: bool,
    repo_mode: RepoMode,
    edit: impl FnOnce(&dyn Fn() -> Result<Option<Value>>) -> Result<(DetachedWrite, T)>,
) -> Result<T> {
    let ty = Type::parse(METADATA_SIGNATURE).map_err(ostrya_core::Error::from)?;
    let _guard = DETACHED_MERGE.lock().unwrap_or_else(|err| err.into_inner());
    let (write, value) = edit(&|| read_detached_blocking(objects_fd, dest, &ty))?;
    match write {
        DetachedWrite::Dict(dict) => {
            let bytes = to_bytes(&ty, &dict).map_err(ostrya_core::Error::from)?;
            write_detached_blocking(objects_fd, dest, &bytes, fsync, repo_mode)?;
        }
        DetachedWrite::Marker => write_detached_blocking(objects_fd, dest, &[], fsync, repo_mode)?,
        DetachedWrite::Keep => {}
    }
    Ok(value)
}

/// Read the `a{sv}` dict at a `.commitmeta` loose path, or `None` where the
/// file is absent or is the zero-length "no metadata" marker.
fn read_detached_blocking(
    objects_fd: BorrowedFd<'_>,
    dest: &str,
    ty: &Type,
) -> Result<Option<Value>> {
    let bytes =
        match crate::object::read_meta_object(objects_fd, dest, crate::object::MAX_METADATA_SIZE) {
            Ok(bytes) => bytes,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(err) => return Err(Error::Io(err)),
        };
    if bytes.is_empty() {
        return Ok(None);
    }
    Ok(Some(
        ostrya_core::from_bytes(ty, &bytes).map_err(ostrya_core::Error::from)?,
    ))
}

/// Write metadata bytes to a loose path atomically. The detached-metadata
/// writers reach it for a `.commitmeta`, and the prune sweep reaches it for a
/// `.tombstone-commit`; both objects carry the `0644` every metadata object
/// carries. The fanout directory is created on demand (`0777` reduced by the umask, and
/// forced to [`perm::SHARED_DIR_MODE`] where this call creates it in a
/// `bare-user-shared` repository), the bytes go to a temp file (`fchmod` 0644,
/// `fdatasync` when fsync is on), and the temp is renamed over the target. When
/// fsync is on, the fanout directory is fsynced after the rename so the new name
/// survives a crash, and `objects/` is fsynced too when the fanout directory was
/// newly created, matching the durability the object publication path honors.
pub(crate) fn write_detached_blocking(
    objects_fd: BorrowedFd<'_>,
    dest: &str,
    bytes: &[u8],
    fsync: bool,
    repo_mode: RepoMode,
) -> Result<()> {
    use std::io::Write;

    let fanout = &dest[..2];
    let fanout_created = match rustix::fs::mkdirat(objects_fd, fanout, Mode::from_raw_mode(0o777)) {
        Ok(()) => {
            perm::force_created_dir(objects_fd, fanout, repo_mode)?;
            true
        }
        Err(Errno::EXIST) => false,
        Err(e) => return Err(e.into()),
    };

    let tmp = format!(
        "{dest}.tmp-{}-{}",
        std::process::id(),
        crate::write::unique()
    );
    let fd = rustix::fs::openat(
        objects_fd,
        tmp.as_str(),
        OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC | OFlags::NOFOLLOW,
        Mode::from_raw_mode(COMMITMETA_MODE),
    )?;
    let write_and_rename = || -> Result<()> {
        let mut file = std::fs::File::from(fd);
        file.write_all(bytes)?;
        file.flush()?;
        rustix::fs::fchmod(file.as_fd(), Mode::from_raw_mode(COMMITMETA_MODE))?;
        if fsync {
            rustix::fs::fdatasync(file.as_fd())?;
        }
        drop(file);
        rustix::fs::renameat(objects_fd, tmp.as_str(), objects_fd, dest)?;
        if fsync {
            // Make the renamed-in directory entry durable: fsync the fanout
            // directory, and `objects/` too when the fanout was newly created.
            let dir = rustix::fs::openat(
                objects_fd,
                fanout,
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
                Mode::empty(),
            )?;
            rustix::fs::fsync(&dir)?;
            if fanout_created {
                rustix::fs::fsync(objects_fd)?;
            }
        }
        Ok(())
    };
    write_and_rename().inspect_err(|_| {
        let _ = rustix::fs::unlinkat(objects_fd, tmp.as_str(), AtFlags::empty());
    })
}