ostrya 0.0.1

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
//! The object-store write layer: streaming content ingestion and staging.
//!
//! This module holds the pieces a [`Transaction`](crate::Transaction) uses to
//! ingest objects into its staging directory: the logical metadata a writer
//! consumes ([`FileMeta`]), the push-style streaming primitive
//! ([`ContentWriter`]), and the per-mode on-disk application plus staging
//! syscalls the writers finish with.
//!
//! Ingestion goes into an unnamed temp file (`O_TMPFILE` in the staging
//! directory, materialized with `linkat`) where the filesystem allows it, and a
//! named temp file otherwise. A regular file's payload streams through an
//! `rt::File` in bounded chunks and is hashed on the way down; in archive mode
//! the same pass feeds a raw-DEFLATE encoder. The object identity is the
//! SHA-256 of the framed uncompressed header followed by the raw payload, so it
//! is complete when the stream ends regardless of how the bytes are stored.
//!
//! Per-mode inode application is always by explicit `fchmod`/`fchown`, never the
//! umask, reproducing the modes recovered from the `ostree` tool (see
//! `format-reference.md`, "Write path: loose-object inode modes and
//! durability").

use std::future::poll_fn;
use std::io::{self, SeekFrom};
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::pin::Pin;
use std::task::{Context, Poll};

use async_compression::Level;
use async_compression::futures::write::DeflateEncoder;
use futures_io::{AsyncRead, AsyncSeek, AsyncWrite};
use ostrya_core::filehdr::frame;
use ostrya_core::{Checksum, FileHeader, ObjectType, RepoMode, Xattrs, loose_path};
use ostrya_rt::File as RtFile;
use rustix::fs::{AtFlags, Gid, Mode, OFlags, Uid, XattrFlags};
use sha2::{Digest, Sha256};

use crate::error::{Error, Result};
use crate::transaction::Transaction;

/// The regular-file mode bit.
const S_IFREG: u32 = 0o100000;
/// The symlink mode bit.
const S_IFLNK: u32 = 0o120000;
/// The full symlink `st_mode` a content object records for a symlink.
const SYMLINK_MODE: u32 = S_IFLNK | 0o777;
/// The permission-bit mask of an `st_mode`.
const PERM_MASK: u32 = 0o7777;
/// The fixed inode mode metadata objects and archive/shared content take.
const FIXED_MODE: u32 = 0o644;
/// The chunk size for the streaming copy in [`Transaction::write_content`].
const COPY_CHUNK: usize = 64 * 1024;

/// The logical metadata a content writer applies to an object.
///
/// This is the uid, gid, `st_mode`, and xattr set the object header records.
/// For a regular file the mode carries the `S_IFREG` bits; a symlink's mode is
/// fixed by the object model, so [`Transaction::write_symlink`] ignores
/// `mode` here.
#[derive(Debug, Clone)]
pub struct FileMeta {
    /// The logical owning user id.
    pub uid: u32,
    /// The logical owning group id.
    pub gid: u32,
    /// The full logical `st_mode`.
    pub mode: u32,
    /// The logical extended attributes.
    pub xattrs: Xattrs,
}

impl FileMeta {
    /// Metadata for a regular file with the given owner, permission bits, and
    /// no xattrs. The `S_IFREG` bit is added to `perm`.
    pub fn regular(uid: u32, gid: u32, perm: u32) -> FileMeta {
        FileMeta {
            uid,
            gid,
            mode: S_IFREG | (perm & PERM_MASK),
            xattrs: Xattrs::empty(),
        }
    }

    /// The header for a regular-file content object built from this metadata.
    fn regular_header(&self) -> FileHeader {
        FileHeader {
            uid: self.uid,
            gid: self.gid,
            mode: self.mode,
            symlink_target: String::new(),
            xattrs: self.xattrs.clone(),
        }
    }

    /// The header for a symlink content object with the given target. The mode
    /// is fixed to `S_IFLNK | 0o777` by the object model.
    fn symlink_header(&self, target: &str) -> FileHeader {
        FileHeader {
            uid: self.uid,
            gid: self.gid,
            mode: SYMLINK_MODE,
            symlink_target: target.to_owned(),
            xattrs: self.xattrs.clone(),
        }
    }
}

/// How a staged temp file is materialized under its final staging name.
#[derive(Debug)]
pub(crate) enum TempKind {
    /// An `O_TMPFILE` anonymous inode, linked into place via `/proc/self/fd`.
    Anonymous,
    /// A named temp file, renamed into place.
    Named(String),
}

/// A writer that streams one regular file's payload into a transaction.
///
/// Bytes written pass through a SHA-256 digester seeded with the framed
/// uncompressed header, so the object identity is complete at
/// [`finish`](ContentWriter::finish). In archive mode the same bytes feed a
/// raw-DEFLATE encoder whose output, prefixed by the framed archive header,
/// becomes the stored `.filez`; the uncompressed size is patched into the
/// reserved header region at finish. Dropping a writer without `finish`
/// abandons the staged temporary, which the transaction reaps.
///
/// Implements [`futures_io::AsyncWrite`] unconditionally and the tokio
/// `AsyncWrite` under the `tokio` feature.
pub struct ContentWriter<'txn> {
    txn: &'txn Transaction,
    hasher: Sha256,
    uncompressed: u64,
    header: FileHeader,
    expected: Option<Checksum>,
    temp: TempKind,
    sink: Sink,
}

/// The disk sink under a [`ContentWriter`].
enum Sink {
    /// The temp file receives the raw payload (bare family).
    Plain(RtFile),
    /// The temp file receives a framed archive header then DEFLATE output.
    Archive(DeflateEncoder<NoClose<RtFile>>),
}

impl ContentWriter<'_> {
    /// Finish the object: finalize the digest, verify it against the caller's
    /// expectation, apply per-mode metadata, and stage it under its loose name.
    /// A dedup hit (the object already in `objects/` or this transaction's
    /// staging set) returns the existing identity without restaging.
    pub async fn finish(self) -> Result<Checksum> {
        let ContentWriter {
            txn,
            hasher,
            uncompressed,
            header,
            expected,
            temp,
            sink,
        } = self;

        let file = match sink {
            Sink::Plain(mut file) => {
                flush(&mut file).await?;
                file
            }
            Sink::Archive(mut enc) => {
                close(&mut enc).await?;
                let mut file = enc.into_inner().into_inner();
                // Patch the reserved uncompressed-size field: the archive header
                // begins after the 4-byte length prefix and 4-byte NUL pad, and
                // its first member is the big-endian `t` size.
                seek(&mut file, SeekFrom::Start(8)).await?;
                write_all(&mut file, &uncompressed.to_be_bytes()).await?;
                flush(&mut file).await?;
                file
            }
        };

        let checksum = Checksum::from_bytes(hasher.finalize().into());
        if let Some(expected) = expected
            && expected != checksum
        {
            return Err(Error::ChecksumMismatch {
                expected,
                actual: checksum,
            });
        }

        let std_file = file.into_std().await;
        txn.stage_regular(checksum, header, std_file, temp, uncompressed)
            .await
    }
}

impl AsyncWrite for ContentWriter<'_> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let me = self.get_mut();
        let n = match &mut me.sink {
            Sink::Plain(file) => std::task::ready!(Pin::new(file).poll_write(cx, buf))?,
            Sink::Archive(enc) => std::task::ready!(Pin::new(enc).poll_write(cx, buf))?,
        };
        me.hasher.update(&buf[..n]);
        me.uncompressed += n as u64;
        Poll::Ready(Ok(n))
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        match &mut self.get_mut().sink {
            Sink::Plain(file) => Pin::new(file).poll_flush(cx),
            Sink::Archive(enc) => Pin::new(enc).poll_flush(cx),
        }
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        // A ContentWriter is finished through `finish`, not by closing the
        // stream; closing just flushes so a stray close does not truncate.
        self.poll_flush(cx)
    }
}

#[cfg(feature = "tokio")]
impl ostrya_rt::tokio_io::AsyncWrite for ContentWriter<'_> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        AsyncWrite::poll_write(self, cx, buf)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        AsyncWrite::poll_flush(self, cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        AsyncWrite::poll_close(self, cx)
    }
}

impl Transaction {
    /// A streaming writer for one regular-file payload.
    ///
    /// `meta` carries the logical uid/gid/mode/xattrs the object header records;
    /// `mode` must name a regular file. `expected`, when given, is checked
    /// against the computed identity at [`finish`](ContentWriter::finish).
    pub async fn content_writer(
        &self,
        expected: Option<&Checksum>,
        meta: &FileMeta,
    ) -> Result<ContentWriter<'_>> {
        let mode = self.repo().mode();
        if mode == RepoMode::BareSplitXattrs {
            return Err(Error::Unsupported(
                "bare-split-xattrs is read-only; the port does not write it".into(),
            ));
        }
        let header = meta.regular_header();
        // Validate the regular-file mode up front and seed the identity with
        // the framed uncompressed header.
        let framed = frame(&header.serialize()?)?;
        let mut hasher = Sha256::new();
        hasher.update(&framed);

        let staging = self.staging_fd().try_clone_to_owned()?;
        let (fd, temp) = ostrya_rt::unblock(move || open_temp(staging.as_fd())).await?;
        let mut file = RtFile::from(fd);

        let sink = if mode.is_archive() {
            // Reserve the archive header region; the uncompressed size is
            // patched in at finish. Its byte length is independent of the
            // payload, so the length prefix written here is final.
            let placeholder = frame(&header.serialize_archive(0)?)?;
            write_all(&mut file, &placeholder).await?;
            let level = archive_level(self.repo().config().zlib_level()?);
            Sink::Archive(DeflateEncoder::with_quality(NoClose::new(file), level))
        } else {
            Sink::Plain(file)
        };

        Ok(ContentWriter {
            txn: self,
            hasher,
            uncompressed: 0,
            header,
            expected: expected.copied(),
            temp,
            sink,
        })
    }

    /// Stream a regular file's payload from `reader` into a new content object.
    pub async fn write_content(
        &self,
        expected: Option<&Checksum>,
        meta: &FileMeta,
        reader: impl AsyncRead + Unpin,
    ) -> Result<Checksum> {
        let mut writer = self.content_writer(expected, meta).await?;
        copy_stream(reader, &mut writer).await?;
        writer.finish().await
    }

    /// Write a regular file whose content the caller already holds. The general
    /// path is [`write_content`](Transaction::write_content), which streams.
    pub async fn write_regfile_inline(
        &self,
        expected: Option<&Checksum>,
        meta: &FileMeta,
        data: &[u8],
    ) -> Result<Checksum> {
        let mut writer = self.content_writer(expected, meta).await?;
        write_all(&mut writer, data).await?;
        writer.finish().await
    }

    /// Write a symlink content object. The identity is the framed header alone
    /// (no payload); storage follows the repository mode.
    pub async fn write_symlink(
        &self,
        target: &str,
        meta: &FileMeta,
        expected: Option<&Checksum>,
    ) -> Result<Checksum> {
        let mode = self.repo().mode();
        if mode == RepoMode::BareSplitXattrs {
            return Err(Error::Unsupported(
                "bare-split-xattrs is read-only; the port does not write it".into(),
            ));
        }
        let header = meta.symlink_header(target);
        let checksum = Checksum::from_bytes(Sha256::digest(frame(&header.serialize()?)?).into());
        if let Some(expected) = expected
            && *expected != checksum
        {
            return Err(Error::ChecksumMismatch {
                expected: *expected,
                actual: checksum,
            });
        }
        self.stage_symlink(checksum, header).await
    }

    /// Write a metadata object from its normal-form serialized bytes. The
    /// identity is the SHA-256 of those bytes.
    pub async fn write_metadata(
        &self,
        ty: ObjectType,
        expected: Option<&Checksum>,
        bytes: &[u8],
    ) -> 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(),
            ));
        }
        if !ty.is_meta() {
            return Err(Error::Unsupported(format!(
                "write_metadata does not handle {ty:?} objects"
            )));
        }
        let checksum = Checksum::from_bytes(Sha256::digest(bytes).into());
        if let Some(expected) = expected
            && *expected != checksum
        {
            return Err(Error::ChecksumMismatch {
                expected: *expected,
                actual: checksum,
            });
        }
        self.stage_metadata(checksum, ty, bytes.to_vec()).await
    }
}

/// The raw-DEFLATE encoder level for an `[archive] zlib-level` value, clamped to
/// the 1-9 range the tool accepts.
fn archive_level(zlib_level: i64) -> Level {
    Level::Precise(zlib_level.clamp(1, 9) as i32)
}

/// Open an ingestion temp file in the staging directory: `O_TMPFILE` where the
/// filesystem allows it, a named temp file otherwise. Reused by the checkout
/// copy path, which opens its temporaries in the destination directory the same
/// way.
pub(crate) fn open_temp(staging_fd: BorrowedFd<'_>) -> Result<(OwnedFd, TempKind)> {
    match rustix::fs::openat(
        staging_fd,
        ".",
        OFlags::WRONLY | OFlags::TMPFILE | OFlags::CLOEXEC,
        Mode::from_raw_mode(FIXED_MODE),
    ) {
        Ok(fd) => Ok((fd, TempKind::Anonymous)),
        // Any failure of the O_TMPFILE attempt falls back to a named temp; a
        // genuine error (ENOSPC and the like) resurfaces from that open.
        Err(_) => {
            let name = temp_name();
            let fd = rustix::fs::openat(
                staging_fd,
                name.as_str(),
                OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC | OFlags::NOFOLLOW,
                Mode::from_raw_mode(FIXED_MODE),
            )?;
            Ok((fd, TempKind::Named(name)))
        }
    }
}

/// A per-process-unique ingestion temp file name.
fn temp_name() -> String {
    format!(".ostrya-tmp-{}-{}", std::process::id(), unique())
}

/// A per-process-unique counter value for temp file names. Every temp-name
/// helper in the crate draws from this single counter, so the suffixes they
/// format stay unique within the process.
pub(crate) fn unique() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    COUNTER.fetch_add(1, Ordering::Relaxed)
}

/// The shared context for the blocking staging helpers: the directory fds, the
/// repository mode, and the durability settings.
pub(crate) struct StageCtx<'a> {
    /// The repository `objects/` directory, for the dedup check and fanout.
    pub(crate) objects_fd: BorrowedFd<'a>,
    /// The transaction's staging directory, where objects are ingested.
    pub(crate) staging_fd: BorrowedFd<'a>,
    /// The repository storage mode.
    pub(crate) mode: RepoMode,
    /// Whether durability syncs run at all.
    pub(crate) fsync: bool,
    /// Whether each object is fsynced individually at ingest.
    pub(crate) per_object_fsync: bool,
}

/// The outcome of staging one object.
pub(crate) struct StageOutcome {
    /// Whether the object was already present in `objects/` (a dedup hit).
    pub(crate) deduped: bool,
    /// The staged file's on-disk size in bytes, when freshly staged. In archive
    /// mode this is the compressed `.filez` storage size.
    pub(crate) on_disk_size: u64,
    /// The logical (unpacked) content size in bytes: a regular file's
    /// pre-compression payload length, a symlink's target length, and zero for
    /// a metadata object (whose size the caller fills from `on_disk_size`).
    /// This is the `st_size` the tool records for the object in `ostree.sizes`.
    /// Carried into the archive size map.
    pub(crate) unpacked: u64,
    /// The flat staging name the object was linked under, when freshly staged.
    pub(crate) staging_name: String,
    /// The loose path the object publishes to, when freshly staged.
    pub(crate) dest: String,
}

/// Apply per-mode metadata to a content object's inode and materialize it into
/// the staging directory under its flat loose name. Runs synchronous syscalls.
pub(crate) fn stage_content_blocking(
    ctx: &StageCtx<'_>,
    checksum: &Checksum,
    header: &FileHeader,
    file: std::fs::File,
    temp: TempKind,
    unpacked: u64,
) -> Result<StageOutcome> {
    let dest = loose_path(checksum, ObjectType::File, ctx.mode);
    if crate::object::object_exists(ctx.objects_fd, &dest)? {
        cleanup_temp(ctx.staging_fd, &temp);
        return Ok(dedup(dest));
    }

    apply_content_metadata(file.as_fd(), ctx.mode, header)?;
    if ctx.fsync && ctx.per_object_fsync {
        rustix::fs::fsync(file.as_fd())?;
    }
    let on_disk_size = size_of(file.as_fd())?;
    let staging_name = flat_name(checksum, ObjectType::File, ctx.mode);
    materialize(ctx.staging_fd, &file, &temp, &staging_name)?;
    drop(file);
    Ok(StageOutcome {
        deduped: false,
        on_disk_size,
        unpacked,
        staging_name,
        dest,
    })
}

/// Stage a symlink content object: a real symlink in the bare family, a regular
/// file holding the target plus a NUL in the bare-user family, and a payloadless
/// framed archive header in archive mode.
pub(crate) fn stage_symlink_blocking(
    ctx: &StageCtx<'_>,
    checksum: &Checksum,
    header: &FileHeader,
) -> Result<StageOutcome> {
    let staging_fd = ctx.staging_fd;
    let dest = loose_path(checksum, ObjectType::File, ctx.mode);
    if crate::object::object_exists(ctx.objects_fd, &dest)? {
        return Ok(dedup(dest));
    }
    let staging_name = flat_name(checksum, ObjectType::File, ctx.mode);
    let target = &header.symlink_target;
    let do_fsync = ctx.fsync && ctx.per_object_fsync;

    let on_disk_size = match ctx.mode {
        RepoMode::Bare => {
            // A concurrent writer of the identical symlink may win the race; its
            // content is the same, so an existing entry is not an error.
            if stage_symlink_inode(staging_fd, target, &staging_name)? {
                rustix::fs::chownat(
                    staging_fd,
                    staging_name.as_str(),
                    Some(uid(header.uid)),
                    Some(gid(header.gid)),
                    AtFlags::SYMLINK_NOFOLLOW,
                )?;
                for (name, value) in header.xattrs.iter() {
                    set_link_xattr(staging_fd, &staging_name, name, value)?;
                }
            }
            target.len() as u64
        }
        RepoMode::BareUserOnly => {
            stage_symlink_inode(staging_fd, target, &staging_name)?;
            target.len() as u64
        }
        RepoMode::BareUser | RepoMode::BareUserShared => {
            // Stored as a regular file: content is the target plus one NUL, the
            // logical metadata lives in user.ostreemeta, and the inode is 0644.
            let mut content = target.clone().into_bytes();
            content.push(0);
            stage_named_regular(
                staging_fd,
                &staging_name,
                &content,
                FIXED_MODE,
                Some(&header.serialize_stat_metadata()?),
                do_fsync,
            )?
        }
        RepoMode::Archive => {
            // A payloadless framed archive header.
            let body = frame(&header.serialize_archive(0)?)?;
            stage_named_regular(staging_fd, &staging_name, &body, FIXED_MODE, None, do_fsync)?
        }
        RepoMode::BareSplitXattrs => {
            return Err(Error::Unsupported(
                "bare-split-xattrs is read-only; the port does not write it".into(),
            ));
        }
    };
    Ok(StageOutcome {
        deduped: false,
        on_disk_size,
        // The logical (unpacked) size of a symlink object is its target length,
        // matching the `st_size` the tool records for it in `ostree.sizes`.
        unpacked: target.len() as u64,
        staging_name,
        dest,
    })
}

/// Stage a metadata object: write the bytes to a temp file, `fchmod` 0644, and
/// materialize under the flat loose name.
pub(crate) fn stage_metadata_blocking(
    ctx: &StageCtx<'_>,
    checksum: &Checksum,
    ty: ObjectType,
    bytes: &[u8],
) -> Result<StageOutcome> {
    let dest = loose_path(checksum, ty, ctx.mode);
    if crate::object::object_exists(ctx.objects_fd, &dest)? {
        return Ok(dedup(dest));
    }
    let staging_name = flat_name(checksum, ty, ctx.mode);
    let on_disk_size = stage_named_regular(
        ctx.staging_fd,
        &staging_name,
        bytes,
        FIXED_MODE,
        None,
        ctx.fsync && ctx.per_object_fsync,
    )?;
    Ok(StageOutcome {
        deduped: false,
        on_disk_size,
        unpacked: 0,
        staging_name,
        dest,
    })
}

/// Publish staged objects into `objects/` per the durability contract: with
/// fsync on, `syncfs` the repository, rename each object into `objects/<xx>/`,
/// then `fsync` each touched fanout directory and `objects/` itself.
pub(crate) fn publish_blocking(
    repo_fd: BorrowedFd<'_>,
    objects_fd: BorrowedFd<'_>,
    staging_fd: BorrowedFd<'_>,
    objects: &[(String, String)],
    fsync: bool,
) -> Result<()> {
    if fsync {
        rustix::fs::syncfs(repo_fd)?;
    }
    let mut fanouts: Vec<String> = Vec::new();
    for (staging_name, dest) in objects {
        let fanout = &dest[..2];
        ensure_fanout(objects_fd, fanout)?;
        rustix::fs::renameat(staging_fd, staging_name.as_str(), objects_fd, dest.as_str())?;
        if !fanouts.iter().any(|f| f == fanout) {
            fanouts.push(fanout.to_owned());
        }
    }
    if fsync {
        for fanout in &fanouts {
            let dir = rustix::fs::openat(
                objects_fd,
                fanout.as_str(),
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
                Mode::empty(),
            )?;
            rustix::fs::fsync(&dir)?;
        }
        rustix::fs::fsync(objects_fd)?;
    }
    Ok(())
}

/// Create a fanout directory `objects/<xx>/` on demand, ignoring a race that
/// already created it. The request mode is `0777` reduced by the umask. A
/// group-shared repository is arranged at the filesystem level, not here: an
/// operator sets the repository directory setgid `2775` with a default group
/// ACL (`setfacl -d -m g::rwx`) before `init`, and the OS propagates the group,
/// setgid bit, and permissions to every directory created underneath.
fn ensure_fanout(objects_fd: BorrowedFd<'_>, fanout: &str) -> Result<()> {
    match rustix::fs::mkdirat(objects_fd, fanout, Mode::from_raw_mode(0o777)) {
        Ok(()) | Err(rustix::io::Errno::EXIST) => Ok(()),
        Err(e) => Err(e.into()),
    }
}

/// A [`StageOutcome`] for an object already present in `objects/`.
fn dedup(dest: String) -> StageOutcome {
    StageOutcome {
        deduped: true,
        on_disk_size: 0,
        unpacked: 0,
        staging_name: String::new(),
        dest,
    }
}

/// The flat staging name for an object: its full hex checksum plus the loose
/// extension, holding the whole object in one staging-directory entry.
pub(crate) fn flat_name(checksum: &Checksum, ty: ObjectType, mode: RepoMode) -> String {
    format!("{}.{}", checksum.to_hex(), ty.extension(mode))
}

/// Apply the per-mode inode metadata of a regular-file content object.
fn apply_content_metadata(fd: BorrowedFd<'_>, mode: RepoMode, header: &FileHeader) -> Result<()> {
    let perm = header.mode & PERM_MASK;
    match mode {
        RepoMode::Bare => {
            rustix::fs::fchown(fd, Some(uid(header.uid)), Some(gid(header.gid)))?;
            rustix::fs::fchmod(fd, Mode::from_raw_mode(perm))?;
            for (name, value) in header.xattrs.iter() {
                set_inode_xattr(fd, name, value)?;
            }
        }
        RepoMode::BareUser => {
            rustix::fs::fchmod(fd, Mode::from_raw_mode((perm & 0o775) | 0o400))?;
            set_ostreemeta(fd, header)?;
        }
        RepoMode::BareUserShared => {
            rustix::fs::fchmod(fd, Mode::from_raw_mode(FIXED_MODE))?;
            set_ostreemeta(fd, header)?;
        }
        RepoMode::BareUserOnly => {
            // Canonical mode: owner bits preserved, group- and other-write
            // dropped (recovered by observation, see format-reference.md).
            rustix::fs::fchmod(fd, Mode::from_raw_mode(perm & 0o755))?;
        }
        RepoMode::Archive => {
            rustix::fs::fchmod(fd, Mode::from_raw_mode(FIXED_MODE))?;
        }
        RepoMode::BareSplitXattrs => {
            return Err(Error::Unsupported(
                "bare-split-xattrs is read-only; the port does not write it".into(),
            ));
        }
    }
    Ok(())
}

/// Write the `user.ostreemeta` xattr holding the logical `(uuua(ayay))`.
fn set_ostreemeta(fd: BorrowedFd<'_>, header: &FileHeader) -> Result<()> {
    let meta = header.serialize_stat_metadata()?;
    rustix::fs::fsetxattr(fd, "user.ostreemeta", &meta, XattrFlags::empty())?;
    Ok(())
}

/// Set one inode xattr, stripping the stored name's terminating NUL. Reused by
/// the checkout copy path to apply a file object's logical xattrs.
pub(crate) fn set_inode_xattr(fd: BorrowedFd<'_>, name: &[u8], value: &[u8]) -> Result<()> {
    let name = name.strip_suffix(&[0]).unwrap_or(name);
    let name = std::str::from_utf8(name)
        .map_err(|_| Error::InvalidFormat("xattr name is not valid UTF-8".into()))?;
    rustix::fs::fsetxattr(fd, name, value, XattrFlags::empty())?;
    Ok(())
}

/// Set one xattr on a staged symlink inode, stripping the stored name's
/// terminating NUL. A symlink cannot be opened for an fd, so the attribute is
/// set no-follow through the `/proc/self/fd` path of the directory. Reused by
/// the checkout path to apply a symlink object's link xattrs.
pub(crate) fn set_link_xattr(
    dir: BorrowedFd<'_>,
    staging_name: &str,
    name: &[u8],
    value: &[u8],
) -> Result<()> {
    let name = name.strip_suffix(&[0]).unwrap_or(name);
    let name = std::str::from_utf8(name)
        .map_err(|_| Error::InvalidFormat("xattr name is not valid UTF-8".into()))?;
    let link = format!("/proc/self/fd/{}/{}", dir.as_raw_fd(), staging_name);
    rustix::fs::lsetxattr(link.as_str(), name, value, XattrFlags::empty())?;
    Ok(())
}

/// Write `content` into a fresh named temp file, `fchmod` it, optionally set
/// `user.ostreemeta`, optionally fsync it, and rename it to `staging_name`.
/// Returns the on-disk size. Used for small caller-held bodies (symlinks and
/// metadata objects).
fn stage_named_regular(
    staging_fd: BorrowedFd<'_>,
    staging_name: &str,
    content: &[u8],
    perm: u32,
    ostreemeta: Option<&[u8]>,
    do_fsync: bool,
) -> Result<u64> {
    use std::io::Write;

    let tmp = temp_name();
    let fd = rustix::fs::openat(
        staging_fd,
        tmp.as_str(),
        OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC | OFlags::NOFOLLOW,
        Mode::from_raw_mode(perm),
    )?;
    let mut file = std::fs::File::from(fd);
    file.write_all(content)?;
    file.flush()?;
    rustix::fs::fchmod(file.as_fd(), Mode::from_raw_mode(perm))?;
    if let Some(meta) = ostreemeta {
        rustix::fs::fsetxattr(file.as_fd(), "user.ostreemeta", meta, XattrFlags::empty())?;
    }
    if do_fsync {
        rustix::fs::fsync(file.as_fd())?;
    }
    let size = size_of(file.as_fd())?;
    drop(file);
    match rustix::fs::renameat(staging_fd, tmp.as_str(), staging_fd, staging_name) {
        Ok(()) => {}
        Err(e) => {
            let _ = rustix::fs::unlinkat(staging_fd, tmp.as_str(), AtFlags::empty());
            return Err(e.into());
        }
    }
    Ok(size)
}

/// Materialize an ingestion temp file under `staging_name` in the staging
/// directory: link the anonymous inode into place, or rename the named temp.
fn materialize(
    staging_fd: BorrowedFd<'_>,
    file: &std::fs::File,
    temp: &TempKind,
    staging_name: &str,
) -> Result<()> {
    match temp {
        TempKind::Anonymous => {
            let proc_path = format!("/proc/self/fd/{}", file.as_raw_fd());
            match rustix::fs::linkat(
                rustix::fs::CWD,
                proc_path.as_str(),
                staging_fd,
                staging_name,
                AtFlags::SYMLINK_FOLLOW,
            ) {
                // A concurrent writer of the identical object linked it first;
                // the bytes are the same, so treat it as staged.
                Ok(()) | Err(rustix::io::Errno::EXIST) => Ok(()),
                Err(e) => Err(e.into()),
            }
        }
        TempKind::Named(name) => {
            rustix::fs::renameat(staging_fd, name.as_str(), staging_fd, staging_name)?;
            Ok(())
        }
    }
}

/// Create a real symlink object in the staging directory. Returns whether it
/// was freshly created; an existing entry (a concurrent writer of the identical
/// symlink) is not an error, since the content is the same.
fn stage_symlink_inode(
    staging_fd: BorrowedFd<'_>,
    target: &str,
    staging_name: &str,
) -> Result<bool> {
    match rustix::fs::symlinkat(target, staging_fd, staging_name) {
        Ok(()) => Ok(true),
        Err(rustix::io::Errno::EXIST) => Ok(false),
        Err(e) => Err(e.into()),
    }
}

/// Discard an ingestion temp file after a dedup hit: an anonymous inode
/// vanishes when its fd closes, a named temp is unlinked.
fn cleanup_temp(staging_fd: BorrowedFd<'_>, temp: &TempKind) {
    if let TempKind::Named(name) = temp {
        let _ = rustix::fs::unlinkat(staging_fd, name.as_str(), AtFlags::empty());
    }
}

/// The on-disk size of an open file.
fn size_of(fd: BorrowedFd<'_>) -> Result<u64> {
    Ok(rustix::fs::fstat(fd)?.st_size.max(0) as u64)
}

fn uid(value: u32) -> Uid {
    Uid::from_raw(value)
}

fn gid(value: u32) -> Gid {
    Gid::from_raw(value)
}

/// A writer wrapper whose `poll_close` only flushes, so an inner file survives
/// the DEFLATE encoder finalizing its stream and can be recovered for the
/// header size-patch.
struct NoClose<W> {
    inner: W,
}

impl<W> NoClose<W> {
    fn new(inner: W) -> NoClose<W> {
        NoClose { inner }
    }

    fn into_inner(self) -> W {
        self.inner
    }
}

impl<W: AsyncWrite + Unpin> AsyncWrite for NoClose<W> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_flush(cx)
    }
}

// --- minimal poll_fn combinators, so the write path needs no futures-lite ---

async fn write_all<W: AsyncWrite + Unpin>(w: &mut W, mut buf: &[u8]) -> io::Result<()> {
    poll_fn(move |cx| {
        while !buf.is_empty() {
            match Pin::new(&mut *w).poll_write(cx, buf) {
                Poll::Ready(Ok(0)) => {
                    return Poll::Ready(Err(io::Error::new(
                        io::ErrorKind::WriteZero,
                        "write returned zero",
                    )));
                }
                Poll::Ready(Ok(n)) => buf = &buf[n..],
                Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                Poll::Pending => return Poll::Pending,
            }
        }
        Poll::Ready(Ok(()))
    })
    .await
}

pub(crate) async fn flush<W: AsyncWrite + Unpin>(w: &mut W) -> io::Result<()> {
    poll_fn(|cx| Pin::new(&mut *w).poll_flush(cx)).await
}

async fn close<W: AsyncWrite + Unpin>(w: &mut W) -> io::Result<()> {
    poll_fn(|cx| Pin::new(&mut *w).poll_close(cx)).await
}

async fn seek<S: AsyncSeek + Unpin>(s: &mut S, pos: SeekFrom) -> io::Result<u64> {
    poll_fn(|cx| Pin::new(&mut *s).poll_seek(cx, pos)).await
}

async fn read_some<R: AsyncRead + Unpin>(r: &mut R, buf: &mut [u8]) -> io::Result<usize> {
    poll_fn(|cx| Pin::new(&mut *r).poll_read(cx, buf)).await
}

/// Stream `reader` into `writer` in bounded chunks; no whole blob is buffered.
/// Reused by the checkout copy path to stream a file object's payload into a
/// destination temp file.
pub(crate) async fn copy_stream<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
    mut reader: R,
    writer: &mut W,
) -> io::Result<()> {
    let mut buf = vec![0u8; COPY_CHUNK];
    loop {
        let n = read_some(&mut reader, &mut buf).await?;
        if n == 0 {
            break;
        }
        write_all(writer, &buf[..n]).await?;
    }
    Ok(())
}

/// `ContentWriter` moves freely across tasks and threads.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<ContentWriter<'static>>();
    assert_send_sync::<FileMeta>();
};

#[cfg(feature = "tokio")]
const _: fn() = || {
    fn assert_tokio_write<T: ostrya_rt::tokio_io::AsyncWrite>() {}
    assert_tokio_write::<ContentWriter<'static>>();
};