Skip to main content

archive_trait/
builder.rs

1//! Format-neutral archive construction.
2//!
3//! Archive formats implement [`ArchiveBuilder`] and wrap the resulting writer
4//! in a stateful [`Builder`] to use the format-neutral construction APIs.
5
6mod traversal;
7
8use std::{
9    collections::VecDeque,
10    io::{self, Read},
11    mem,
12    ops::Range,
13    path::{Path, PathBuf},
14    pin::Pin,
15};
16
17use thiserror::Error;
18use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt};
19
20pub use self::traversal::TraversalError;
21use self::traversal::{TraversalEntry, TraversalKind, TraversalStream, stream_directory_entries};
22use crate::{
23    NameValidator,
24    component_tree::{ComponentTree, ROOT_NODE},
25    name::NameValidation,
26};
27
28const BUFFERED_SOURCE_FILE_BYTES: usize = 1024 * 1024;
29const FILE_PAYLOAD_CHUNK_BYTES: usize = 2 * 1024 * 1024;
30// A preparation batch may exceed this target by one buffered file, so its
31// payload storage remains below twice this value.
32const SOURCE_FILE_PREPARATION_BATCH_BYTES: usize = BUFFERED_SOURCE_FILE_BYTES;
33
34/// Minimal regular-file metadata accepted by [`Builder::add_file`].
35#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
36pub struct EntryMetadata {
37    executable: bool,
38}
39
40impl EntryMetadata {
41    /// Configures whether the regular file carries executable intent.
42    pub fn executable(mut self, executable: bool) -> Self {
43        self.executable = executable;
44        self
45    }
46
47    /// Returns whether this entry carries executable intent.
48    pub fn is_executable(self) -> bool {
49        self.executable
50    }
51}
52
53/// Controls format-neutral archive construction behavior.
54#[derive(Clone, Copy, Debug, Default)]
55pub struct BuilderPolicy {
56    name_validation: NameValidation,
57    symlink_policy: SymlinkPolicy,
58}
59
60/// Controls how source symbolic links are handled during recursive builds.
61#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
62pub enum SymlinkPolicy {
63    /// Reject recursive sources containing symbolic links.
64    #[default]
65    Reject,
66    /// Preserve symbolic links as link members in the resulting archive.
67    Preserve,
68    // TODO: Consider adding some kind of "Dereference" policy in the future,
69    // where symlinks get followed and replaced with their normal file/directory
70    // contents.
71}
72
73impl BuilderPolicy {
74    /// Configures validation for member names and preserved symbolic-link targets.
75    ///
76    /// Passing [`None`] disables configurable name validation. UTF-8 and
77    /// archive-format requirements still apply.
78    pub fn name_validator(mut self, validator: Option<NameValidator>) -> Self {
79        self.name_validation = NameValidation::from_validator(validator);
80        self
81    }
82
83    /// Configures how recursive builds handle source symbolic links.
84    ///
85    /// Symbolic links are **rejected by default**. Use
86    /// [`SymlinkPolicy::Preserve`] to write link members instead.
87    pub fn symlink_policy(mut self, policy: SymlinkPolicy) -> Self {
88        self.symlink_policy = policy;
89        self
90    }
91}
92
93struct BuilderState {
94    policy: BuilderPolicy,
95    entries: BuildEntries,
96    source_buffer: Vec<u8>,
97    poisoned: bool,
98}
99
100impl BuilderState {
101    fn new(policy: BuilderPolicy) -> Self {
102        Self {
103            policy,
104            entries: BuildEntries::new(),
105            source_buffer: Vec::new(),
106            poisoned: false,
107        }
108    }
109
110    fn ensure_active<E>(&self) -> Result<(), BuildError<E>> {
111        if self.poisoned {
112            return Err(BuildError::Poisoned);
113        }
114        Ok(())
115    }
116
117    // Cancellation can leave partial output. Keep the builder poisoned until
118    // the write returns and we know whether it is safe to continue.
119    fn begin_write(&mut self) {
120        self.poisoned = true;
121    }
122
123    fn complete_write<E>(
124        &mut self,
125        result: Result<(), BuildFailure<E>>,
126        emitted_entries: bool,
127    ) -> Result<(), BuildError<E>> {
128        self.poisoned = result
129            .as_ref()
130            .is_err_and(|failure| emitted_entries || failure.poisons_builder);
131        result.map_err(|failure| failure.error)
132    }
133}
134
135/// A format-neutral, uncompressed file payload supplied to an [`ArchiveBuilder`]
136/// implementation.
137pub struct FilePayload<'a> {
138    size: u64,
139    started: bool,
140    inner: FilePayloadInner<'a>,
141}
142
143enum FilePayloadInner<'a> {
144    /// A pre-buffered payload.
145    ///
146    /// Observe that this is stored as an `Option` so that we can use the `None`
147    /// state to communicate that the payload has been consumed.
148    Buffered(Option<&'a [u8]>),
149    Reader {
150        source: Pin<Box<dyn AsyncRead + 'a>>,
151        filesystem_path: Option<&'a Path>,
152        buffer: Vec<u8>,
153        remaining: u64,
154        filled: usize,
155    },
156}
157
158impl<'a> FilePayload<'a> {
159    /// Creates a payload with a declared logical size and [`AsyncRead`] source.
160    ///
161    /// The builder reads exactly `size` bytes from `source`. Additional bytes
162    /// remain unread, while a source that ends early causes the addition to
163    /// fail.
164    pub fn new<R>(size: u64, source: R) -> Self
165    where
166        R: AsyncRead + 'a,
167    {
168        Self::streaming(size, source, Vec::new(), None)
169    }
170
171    /// Returns the logical, uncompressed source size in bytes.
172    ///
173    /// This is the total number of bytes yielded by [`Self::next_chunk`], not
174    /// necessarily the size ultimately stored by the archive format.
175    pub fn size(&self) -> u64 {
176        self.size
177    }
178
179    /// Returns the next chunk of logical, uncompressed source bytes.
180    ///
181    /// Once this method has been called, the payload cannot be passed to
182    /// [`Builder::add_file`].
183    pub async fn next_chunk<E>(&mut self) -> Result<Option<&[u8]>, BuildError<E>> {
184        self.started = true;
185        match &mut self.inner {
186            FilePayloadInner::Buffered(bytes) => Ok(bytes.take().filter(|bytes| !bytes.is_empty())),
187            FilePayloadInner::Reader {
188                source,
189                filesystem_path,
190                buffer,
191                remaining,
192                filled,
193            } => read_streaming_chunk(source, buffer, remaining, filled, *filesystem_path).await,
194        }
195    }
196
197    fn streaming<R>(
198        size: u64,
199        source: R,
200        buffer: Vec<u8>,
201        filesystem_path: Option<&'a Path>,
202    ) -> Self
203    where
204        R: AsyncRead + 'a,
205    {
206        Self {
207            size,
208            started: false,
209            inner: FilePayloadInner::Reader {
210                source: Box::pin(source),
211                filesystem_path,
212                buffer,
213                remaining: size,
214                filled: 0,
215            },
216        }
217    }
218
219    fn swap_buffer(&mut self, buffer: &mut Vec<u8>) {
220        if let FilePayloadInner::Reader {
221            buffer: payload_buffer,
222            ..
223        } = &mut self.inner
224        {
225            mem::swap(payload_buffer, buffer);
226        }
227    }
228}
229
230impl FilePayload<'static> {
231    /// Opens `path` and creates a payload from the complete regular file.
232    pub async fn from_path<P: AsRef<Path>>(path: P) -> io::Result<Self> {
233        let file = tokio::fs::File::open(path).await?;
234        Self::from_file(file).await
235    }
236
237    /// Creates a payload from a [`tokio::fs::File`], starting at the position
238    /// reported by the handle and ending at EOF.
239    ///
240    /// This constructor rejects filesystem objects that are not regular files.
241    pub async fn from_file(mut file: tokio::fs::File) -> io::Result<Self> {
242        let metadata = file.metadata().await?;
243        if !metadata.is_file() {
244            return Err(io::Error::other(
245                "file payload source is not a regular file",
246            ));
247        }
248        let position = file.stream_position().await?;
249        Ok(Self::new(metadata.len().saturating_sub(position), file))
250    }
251}
252
253impl<'a> From<&'a [u8]> for FilePayload<'a> {
254    fn from(bytes: &'a [u8]) -> Self {
255        let size = bytes.len() as u64;
256        Self {
257            size,
258            started: false,
259            inner: FilePayloadInner::Buffered(Some(bytes)),
260        }
261    }
262}
263
264async fn read_streaming_chunk<'a, E, R>(
265    source: &mut R,
266    buffer: &'a mut Vec<u8>,
267    remaining: &mut u64,
268    filled: &mut usize,
269    filesystem_path: Option<&Path>,
270) -> Result<Option<&'a [u8]>, BuildError<E>>
271where
272    R: AsyncRead + Unpin + ?Sized,
273{
274    if *remaining == 0 {
275        return Ok(None);
276    }
277
278    let chunk_size = (*remaining).min(FILE_PAYLOAD_CHUNK_BYTES as u64);
279    let chunk_len = usize::try_from(chunk_size)
280        .map_err(|_| arithmetic_overflow("file payload read buffer size"))?;
281    buffer.resize(chunk_len, 0);
282    // Progress lives in the payload rather than this future, so cancelling and
283    // retrying `FilePayload::next_chunk` cannot discard completed reads.
284    while *filled < chunk_len {
285        let read = source
286            .read(&mut buffer[*filled..])
287            .await
288            .map_err(|source| file_payload_read_error(filesystem_path, source))?;
289        if read == 0 {
290            return Err(file_payload_read_error(
291                filesystem_path,
292                io::Error::new(
293                    io::ErrorKind::UnexpectedEof,
294                    "file payload source ended before its declared size",
295                ),
296            ));
297        }
298        *filled += read;
299    }
300    *remaining -= chunk_size;
301    *filled = 0;
302    Ok(Some(buffer))
303}
304
305/// A failure returned by an [`ArchiveBuilder`] format hook.
306///
307/// This distinguishes errors known to precede output from errors that may have
308/// left a partial member in the output archive.
309#[derive(Debug)]
310pub struct BuildFailure<E> {
311    error: BuildError<E>,
312    // TODO: Maybe make all failures poisoning?
313    // I'm not sure we really need the distinction here.
314    poisons_builder: bool,
315}
316
317impl<E> BuildFailure<E> {
318    /// Reports a failure that occurred before the hook wrote any output.
319    pub fn recoverable(error: BuildError<E>) -> Self {
320        Self {
321            error,
322            poisons_builder: false,
323        }
324    }
325
326    /// Reports a failure that may have left partial output.
327    pub fn poisoned(error: BuildError<E>) -> Self {
328        Self {
329            error,
330            poisons_builder: true,
331        }
332    }
333}
334
335/// A format-specific archive writer that can create a stateful [`Builder`].
336///
337/// The asynchronous methods on this trait are implementation hooks for
338/// [`Builder`]. Archive construction callers must not invoke them directly;
339/// doing so bypasses builder policy, collision tracking, and cancellation
340/// poisoning. Use [`Self::builder`] and then the [`Builder`] APIs instead.
341///
342/// Hook implementations must return [`BuildFailure::recoverable`] only when the
343/// failed invocation wrote no output. Any failure after output may have begun
344/// must use [`BuildFailure::poisoned`].
345#[expect(
346    async_fn_in_trait,
347    reason = "archive writers may be !Send and run on a local executor"
348)]
349pub trait ArchiveBuilder: Sized {
350    /// The archive-format error returned while encoding entries.
351    type Error;
352
353    /// Wraps this format writer in a builder using default policy.
354    ///
355    /// Implementors should not override this default implementation.
356    fn builder(self) -> Builder<Self> {
357        Builder {
358            backend: self,
359            state: BuilderState::new(BuilderPolicy::default()),
360        }
361    }
362
363    /// Writes any format-specific archive terminator or index.
364    async fn finish_archive(&mut self) -> Result<(), BuildFailure<Self::Error>>;
365
366    /// Writes one regular-file member and its complete payload.
367    ///
368    /// Implementations must call [`FilePayload::next_chunk`] through
369    /// completion and classify failures using [`BuildFailure`].
370    async fn write_file_member(
371        &mut self,
372        path: &str,
373        payload: &mut FilePayload<'_>,
374        metadata: EntryMetadata,
375    ) -> Result<(), BuildFailure<Self::Error>>;
376
377    /// Writes one directory member.
378    async fn write_directory_member(&mut self, path: &str)
379    -> Result<(), BuildFailure<Self::Error>>;
380
381    /// Writes one symbolic-link member.
382    async fn write_symbolic_link_member(
383        &mut self,
384        path: &str,
385        target: &str,
386    ) -> Result<(), BuildFailure<Self::Error>>;
387}
388
389/// A stateful format-neutral archive construction engine.
390///
391/// Create this wrapper with [`ArchiveBuilder::builder`].
392pub struct Builder<B> {
393    backend: B,
394    state: BuilderState,
395}
396
397impl<B: ArchiveBuilder> Builder<B> {
398    /// Configures the policy used by this builder.
399    ///
400    /// Call before adding any entries.
401    pub fn with_policy(mut self, policy: BuilderPolicy) -> Self {
402        self.state.policy = policy;
403        self
404    }
405
406    /// Adds one regular file from a [`FilePayload`].
407    ///
408    /// If the payload ends before its declared size or returns an error, the
409    /// addition fails and the builder is poisoned if the archive member's
410    /// output may already have begun.
411    ///
412    /// The payload must not have been read through [`FilePayload::next_chunk`]
413    /// before this method is called.
414    pub async fn add_file<'a, P>(
415        &mut self,
416        path: P,
417        payload: impl Into<FilePayload<'a>>,
418        metadata: EntryMetadata,
419    ) -> Result<(), BuildError<B::Error>>
420    where
421        P: AsRef<Path>,
422    {
423        self.state.ensure_active()?;
424        let archive_path = path.as_ref();
425        let Some(path) = archive_path.to_str() else {
426            return Err(BuildError::InvalidArchivePath {
427                path: archive_path.to_path_buf(),
428                reason: "path is not valid UTF-8",
429            });
430        };
431        if !self.state.policy.name_validation.accepts(path) {
432            return Err(BuildError::NameRejected {
433                context: "member path",
434                value: path.to_owned(),
435            });
436        }
437        let path = path.to_owned();
438        let reservation = self
439            .state
440            .entries
441            .preflight_entry(&path, ArchivedEntry::NonDirectory)?;
442        let mut payload = payload.into();
443        if payload.started {
444            return Err(BuildError::FilePayloadAlreadyRead);
445        }
446        payload.swap_buffer(&mut self.state.source_buffer);
447        self.state.begin_write();
448        let result = self
449            .backend
450            .write_file_member(&path, &mut payload, metadata)
451            .await;
452        payload.swap_buffer(&mut self.state.source_buffer);
453        self.state.complete_write(result, false)?;
454        self.state.entries.commit_entry(&path, reservation);
455        Ok(())
456    }
457
458    /// Adds one directory member without reading from the filesystem.
459    ///
460    /// This creates only the named directory member. It does not add any child
461    /// members; use [`Self::add_directory_all`] to recursively add a filesystem
462    /// directory and its contents.
463    pub async fn add_directory<P: AsRef<Path>>(
464        &mut self,
465        path: P,
466    ) -> Result<(), BuildError<B::Error>> {
467        self.state.ensure_active()?;
468        let archive_path = path.as_ref();
469        let Some(path) = archive_path.to_str() else {
470            return Err(BuildError::InvalidArchivePath {
471                path: archive_path.to_path_buf(),
472                reason: "path is not valid UTF-8",
473            });
474        };
475        if !self.state.policy.name_validation.accepts(path) {
476            return Err(BuildError::NameRejected {
477                context: "member path",
478                value: path.to_owned(),
479            });
480        }
481        let path = path.to_owned();
482        let reservation = self
483            .state
484            .entries
485            .preflight_entry(&path, ArchivedEntry::Directory { explicit: true })?;
486        self.state.begin_write();
487        let result = self.backend.write_directory_member(&path).await;
488        self.state.complete_write(result, false)?;
489        self.state.entries.commit_entry(&path, reservation);
490        Ok(())
491    }
492
493    /// Recursively adds a filesystem directory beneath its UTF-8 basename.
494    ///
495    /// Entries are visited in deterministic sorted order and files are streamed
496    /// with bounded memory. Source symbolic links are rejected by default;
497    /// [`BuilderPolicy::symlink_policy`] can instead preserve them. A late
498    /// traversal or validation failure may leave partial output and poison
499    /// this builder.
500    pub async fn add_directory_all<P: AsRef<Path>>(
501        &mut self,
502        source: P,
503    ) -> Result<(), BuildError<B::Error>> {
504        self.state.ensure_active()?;
505        let source = source.as_ref().to_path_buf();
506        let mut entries = stream_directory_entries(
507            source,
508            self.state.policy.name_validation,
509            self.state.policy.symlink_policy,
510        )
511        .map_err(BuildError::Traversal)?;
512        self.state.begin_write();
513        let mut traversal = DirectoryBuild {
514            entries: &mut self.state.entries,
515            source_buffer: mem::take(&mut self.state.source_buffer),
516            emitted: false,
517        };
518        let write_result =
519            write_directory_entries(&mut self.backend, &mut entries, &mut traversal).await;
520        let traversal_result = entries
521            .finish()
522            .await
523            .map_err(BuildError::Traversal)
524            .map_err(BuildFailure::recoverable);
525        let emitted = traversal.emitted;
526        self.state.source_buffer = traversal.source_buffer;
527        self.state
528            .complete_write(write_result.and(traversal_result), emitted)
529    }
530
531    /// Finalizes and consumes this archive builder.
532    pub async fn finish(self) -> Result<(), BuildError<B::Error>> {
533        self.finish_into_inner().await?;
534        Ok(())
535    }
536
537    /// Finalizes this archive builder and returns its format writer.
538    ///
539    /// This allows callers to recover and finalize an owned output sink after
540    /// the archive terminator has been written.
541    pub async fn finish_into_inner(mut self) -> Result<B, BuildError<B::Error>> {
542        self.state.ensure_active()?;
543        self.backend
544            .finish_archive()
545            .await
546            .map_err(|failure| failure.error)?;
547        Ok(self.backend)
548    }
549}
550
551async fn write_directory_entries<B: ArchiveBuilder>(
552    builder: &mut B,
553    entries: &mut TraversalStream,
554    traversal: &mut DirectoryBuild<'_>,
555) -> Result<(), BuildFailure<B::Error>> {
556    while let Some(entries) = entries.recv().await {
557        let mut entries = VecDeque::from(entries);
558        while !entries.is_empty() {
559            let buffer = mem::take(&mut traversal.source_buffer);
560            let (prepared, remaining) = prepare_directory_entries(entries, buffer)
561                .await
562                .map_err(SourceError::into_build_error)
563                .map_err(BuildFailure::recoverable)?;
564            entries = remaining;
565            let PreparedDirectoryBatch {
566                entries: prepared_entries,
567                mut buffer,
568            } = prepared;
569            let result =
570                write_prepared_directory_entries(builder, prepared_entries, &mut buffer, traversal)
571                    .await;
572            traversal.source_buffer = buffer;
573            result?;
574        }
575    }
576    Ok(())
577}
578
579async fn write_prepared_directory_entries<B: ArchiveBuilder>(
580    builder: &mut B,
581    entries: Vec<PreparedTraversalEntry>,
582    buffer: &mut Vec<u8>,
583    traversal: &mut DirectoryBuild<'_>,
584) -> Result<(), BuildFailure<B::Error>> {
585    for entry in entries {
586        let reservation = traversal
587            .entries
588            .preflight_entry(
589                &entry.archive_path,
590                if matches!(&entry.kind, PreparedTraversalKind::Directory) {
591                    ArchivedEntry::Directory { explicit: true }
592                } else {
593                    ArchivedEntry::NonDirectory
594                },
595            )
596            .map_err(BuildFailure::recoverable)?;
597        match entry.kind {
598            PreparedTraversalKind::Directory => {
599                builder.write_directory_member(&entry.archive_path).await?;
600            }
601            PreparedTraversalKind::BufferedFile { range, executable } => {
602                let data = buffer.get(range).ok_or_else(|| {
603                    BuildFailure::recoverable(arithmetic_overflow(
604                        "prepared source file buffer range",
605                    ))
606                })?;
607                let mut payload = FilePayload::from(data);
608                builder
609                    .write_file_member(
610                        &entry.archive_path,
611                        &mut payload,
612                        EntryMetadata::default().executable(executable),
613                    )
614                    .await?;
615            }
616            PreparedTraversalKind::StreamingFile {
617                file,
618                path,
619                size,
620                executable,
621            } => {
622                let mut file = tokio::fs::File::from_std(file);
623                file.set_max_buf_size(FILE_PAYLOAD_CHUNK_BYTES);
624                let mut payload =
625                    FilePayload::streaming(size, file, mem::take(buffer), Some(path.as_path()));
626                let result = builder
627                    .write_file_member(
628                        &entry.archive_path,
629                        &mut payload,
630                        EntryMetadata::default().executable(executable),
631                    )
632                    .await;
633                payload.swap_buffer(buffer);
634                result?;
635            }
636            PreparedTraversalKind::SymbolicLink { target } => {
637                builder
638                    .write_symbolic_link_member(&entry.archive_path, &target)
639                    .await?;
640            }
641        }
642        traversal
643            .entries
644            .commit_entry(&entry.archive_path, reservation);
645        traversal.emitted = true;
646    }
647    Ok(())
648}
649
650struct DirectoryBuild<'entries> {
651    entries: &'entries mut BuildEntries,
652    source_buffer: Vec<u8>,
653    emitted: bool,
654}
655
656struct PreparedDirectoryBatch {
657    entries: Vec<PreparedTraversalEntry>,
658    buffer: Vec<u8>,
659}
660
661struct PreparedTraversalEntry {
662    archive_path: String,
663    kind: PreparedTraversalKind,
664}
665
666enum PreparedTraversalKind {
667    Directory,
668    BufferedFile {
669        range: Range<usize>,
670        executable: bool,
671    },
672    StreamingFile {
673        file: std::fs::File,
674        path: PathBuf,
675        size: u64,
676        executable: bool,
677    },
678    SymbolicLink {
679        target: String,
680    },
681}
682
683async fn prepare_directory_entries(
684    mut entries: VecDeque<TraversalEntry>,
685    mut buffer: Vec<u8>,
686) -> Result<(PreparedDirectoryBatch, VecDeque<TraversalEntry>), SourceError> {
687    tokio::task::spawn_blocking(move || {
688        buffer.clear();
689        let mut prepared = Vec::with_capacity(entries.len());
690        while let Some(entry) = entries.pop_front() {
691            let TraversalEntry {
692                source,
693                archive_path,
694                kind,
695            } = entry;
696            let (kind, batch_complete) = match kind {
697                TraversalKind::Directory => (PreparedTraversalKind::Directory, false),
698                TraversalKind::Regular => prepare_regular_file(source, &mut buffer)?,
699                TraversalKind::SymbolicLink { target } => {
700                    (PreparedTraversalKind::SymbolicLink { target }, false)
701                }
702            };
703            prepared.push(PreparedTraversalEntry { archive_path, kind });
704            if batch_complete {
705                break;
706            }
707        }
708        Ok((
709            PreparedDirectoryBatch {
710                entries: prepared,
711                buffer,
712            },
713            entries,
714        ))
715    })
716    .await
717    .map_err(SourceError::BlockingTask)?
718}
719
720fn prepare_regular_file(
721    path: PathBuf,
722    buffer: &mut Vec<u8>,
723) -> Result<(PreparedTraversalKind, bool), SourceError> {
724    let file = std::fs::File::open(&path)
725        .map_err(|source| SourceError::filesystem("open source file", &path, source))?;
726    let metadata = file
727        .metadata()
728        .map_err(|source| SourceError::filesystem("inspect source file", &path, source))?;
729    if !metadata.is_file() {
730        return Err(SourceError::filesystem(
731            "inspect source file",
732            &path,
733            io::Error::other("source is not a regular file"),
734        ));
735    }
736    let size = metadata.len();
737    let executable = is_executable(&metadata);
738    if size > BUFFERED_SOURCE_FILE_BYTES as u64 {
739        return Ok((
740            PreparedTraversalKind::StreamingFile {
741                file,
742                path,
743                size,
744                executable,
745            },
746            true,
747        ));
748    }
749    let payload_size = usize::try_from(size).map_err(|_| SourceError::ArithmeticOverflow {
750        context: "buffered source file size",
751    })?;
752    let start = buffer.len();
753    let end = start
754        .checked_add(payload_size)
755        .ok_or(SourceError::ArithmeticOverflow {
756            context: "buffered source batch size",
757        })?;
758    buffer.resize(end, 0);
759    (&file)
760        .read_exact(&mut buffer[start..end])
761        .map_err(|source| SourceError::filesystem("read source file", &path, source))?;
762    Ok((
763        PreparedTraversalKind::BufferedFile {
764            range: start..end,
765            executable,
766        },
767        buffer.len() >= SOURCE_FILE_PREPARATION_BATCH_BYTES,
768    ))
769}
770
771enum SourceError {
772    Filesystem {
773        operation: &'static str,
774        path: PathBuf,
775        source: io::Error,
776    },
777    BlockingTask(tokio::task::JoinError),
778    ArithmeticOverflow {
779        context: &'static str,
780    },
781}
782
783impl SourceError {
784    fn filesystem(operation: &'static str, path: &Path, source: io::Error) -> Self {
785        Self::Filesystem {
786            operation,
787            path: path.to_path_buf(),
788            source,
789        }
790    }
791
792    fn into_build_error<E>(self) -> BuildError<E> {
793        match self {
794            Self::Filesystem {
795                operation,
796                path,
797                source,
798            } => BuildError::Filesystem {
799                operation,
800                path,
801                source,
802            },
803            Self::BlockingTask(error) => BuildError::BlockingTask(error),
804            Self::ArithmeticOverflow { context } => BuildError::ArithmeticOverflow { context },
805        }
806    }
807}
808
809/// A failure while constructing an archive.
810#[derive(Debug, Error)]
811pub enum BuildError<E> {
812    /// The archive format encoder failed.
813    #[error(transparent)]
814    Encoder(E),
815    /// Traversing a recursive source failed.
816    #[error(transparent)]
817    Traversal(#[from] TraversalError),
818    /// A requested archive path cannot be represented by the UTF-8 builder.
819    #[error("invalid archive path {path:?}: {reason}")]
820    InvalidArchivePath {
821        /// The rejected archive path.
822        path: PathBuf,
823        /// The reason the path cannot be represented.
824        reason: &'static str,
825    },
826    /// An archive name was rejected by the configured [`BuilderPolicy`].
827    #[error("archive {context} rejected by builder policy: {value:?}")]
828    NameRejected {
829        /// The role of the rejected archive text.
830        context: &'static str,
831        /// The rejected UTF-8 value.
832        value: String,
833    },
834    /// An archive path collides with a previously reserved entry.
835    #[error("archive entry collides with existing path {path}")]
836    PathCollision {
837        /// The conflicting normalized archive path.
838        path: String,
839    },
840    /// A file payload was read before it was passed to [`Builder::add_file`].
841    #[error("file payload was already read before being added to the archive")]
842    FilePayloadAlreadyRead,
843    /// A source filesystem operation failed.
844    #[error("failed to {operation} {path}: {source}")]
845    Filesystem {
846        /// The operation that failed.
847        operation: &'static str,
848        /// The affected source filesystem path.
849        path: PathBuf,
850        /// The underlying I/O error.
851        #[source]
852        source: io::Error,
853    },
854    /// Reading an asynchronous file payload source failed.
855    #[error("failed to read archive file payload source")]
856    SourceRead {
857        /// The underlying I/O error.
858        #[source]
859        source: io::Error,
860    },
861    /// A blocking filesystem operation failed to complete.
862    #[error("failed to complete blocking archive filesystem operation: {0}")]
863    BlockingTask(#[from] tokio::task::JoinError),
864    /// The builder cannot continue because a prior failure may have written bytes.
865    #[error("archive builder is poisoned after a previous partial write")]
866    Poisoned,
867    /// A size computation exceeded this API's range.
868    #[error("arithmetic overflow while computing {context}")]
869    ArithmeticOverflow {
870        /// The failed computation.
871        context: &'static str,
872    },
873}
874
875#[derive(Clone, Copy, Debug)]
876enum ArchivedEntry {
877    Directory { explicit: bool },
878    NonDirectory,
879}
880
881/// Builder collision state keyed by literal `/`-separated archive components.
882#[derive(Debug)]
883struct BuildEntries(ComponentTree<Box<str>, ArchivedEntry>);
884
885/// Proof that an entry was checked against the current collision state.
886struct EntryReservation {
887    entry: ArchivedEntry,
888}
889
890impl BuildEntries {
891    fn new() -> Self {
892        Self(ComponentTree::new(None))
893    }
894
895    fn preflight_entry<E>(
896        &self,
897        path: &str,
898        entry: ArchivedEntry,
899    ) -> Result<EntryReservation, BuildError<E>> {
900        let mut parent = ROOT_NODE;
901        let mut components = archive_path_components(path).peekable();
902        while let Some((component, prefix)) = components.next() {
903            let Some(node) = self.0.child(parent, component) else {
904                return Ok(EntryReservation { entry });
905            };
906            if components.peek().is_some() {
907                match self.0.state(node) {
908                    Some(ArchivedEntry::Directory { .. }) => parent = node,
909                    Some(ArchivedEntry::NonDirectory) => return Err(path_collision(prefix)),
910                    None => return Ok(EntryReservation { entry }),
911                }
912            } else {
913                match (self.0.state(node), entry) {
914                    (
915                        Some(ArchivedEntry::Directory { explicit: false }),
916                        ArchivedEntry::Directory { .. },
917                    )
918                    | (None, _) => return Ok(EntryReservation { entry }),
919                    (Some(_), _) => return Err(path_collision(prefix)),
920                }
921            }
922        }
923        Ok(EntryReservation { entry })
924    }
925
926    fn commit_entry(&mut self, path: &str, reservation: EntryReservation) {
927        // The builder holds exclusive state access while the backend hook is
928        // awaited, so a successful reservation remains valid until this commit.
929        let mut parent = ROOT_NODE;
930        let mut components = archive_path_components(path).peekable();
931        while let Some((component, _)) = components.next() {
932            let node = self
933                .0
934                .ensure_child_with(parent, component, || component.into());
935            if components.peek().is_some() {
936                if self.0.state(node).is_none() {
937                    self.0
938                        .set_state(node, ArchivedEntry::Directory { explicit: false });
939                }
940            } else {
941                self.0.set_state(node, reservation.entry);
942            }
943            parent = node;
944        }
945    }
946
947    #[cfg(test)]
948    fn node_count(&self) -> usize {
949        self.0.node_count()
950    }
951
952    #[cfg(test)]
953    fn component_bytes(&self) -> usize {
954        self.0.components().map(|component| component.len()).sum()
955    }
956}
957
958/// Iterates the exact textual component and prefix at each `/` boundary.
959fn archive_path_components(path: &str) -> impl Iterator<Item = (&str, &str)> {
960    let mut component_start = 0;
961    path.split('/').map(move |component| {
962        let prefix_end = component_start + component.len();
963        let prefix = &path[..prefix_end];
964        component_start = if prefix_end < path.len() {
965            prefix_end + 1
966        } else {
967            prefix_end
968        };
969        (component, prefix)
970    })
971}
972
973fn file_payload_read_error<E>(filesystem_path: Option<&Path>, source: io::Error) -> BuildError<E> {
974    if let Some(path) = filesystem_path {
975        BuildError::Filesystem {
976            operation: "read source file",
977            path: path.to_path_buf(),
978            source,
979        }
980    } else {
981        BuildError::SourceRead { source }
982    }
983}
984
985fn arithmetic_overflow<E>(context: &'static str) -> BuildError<E> {
986    BuildError::ArithmeticOverflow { context }
987}
988
989fn path_collision<E>(path: &str) -> BuildError<E> {
990    BuildError::PathCollision {
991        path: path.to_owned(),
992    }
993}
994
995#[cfg(unix)]
996fn is_executable(metadata: &std::fs::Metadata) -> bool {
997    use std::os::unix::fs::PermissionsExt;
998
999    metadata.permissions().mode() & 0o111 != 0
1000}
1001
1002#[cfg(not(unix))]
1003fn is_executable(_metadata: &std::fs::Metadata) -> bool {
1004    false
1005}
1006
1007#[cfg(test)]
1008mod tests {
1009    use std::fs;
1010
1011    use tempfile::tempdir;
1012
1013    use super::*;
1014
1015    #[derive(Debug)]
1016    struct TestError;
1017
1018    #[derive(Default)]
1019    struct NoopArchiveBuilder {
1020        fail_next_file: bool,
1021        fail_next_directory: bool,
1022    }
1023
1024    impl ArchiveBuilder for NoopArchiveBuilder {
1025        type Error = TestError;
1026
1027        async fn finish_archive(&mut self) -> Result<(), BuildFailure<Self::Error>> {
1028            Ok(())
1029        }
1030
1031        async fn write_file_member(
1032            &mut self,
1033            _path: &str,
1034            payload: &mut FilePayload<'_>,
1035            _metadata: EntryMetadata,
1036        ) -> Result<(), BuildFailure<Self::Error>> {
1037            if mem::take(&mut self.fail_next_file) {
1038                return Err(BuildFailure::recoverable(BuildError::Encoder(TestError)));
1039            }
1040            loop {
1041                match payload.next_chunk::<TestError>().await {
1042                    Ok(Some(_)) => {}
1043                    Ok(None) => return Ok(()),
1044                    Err(error) => return Err(BuildFailure::recoverable(error)),
1045                }
1046            }
1047        }
1048
1049        async fn write_directory_member(
1050            &mut self,
1051            _path: &str,
1052        ) -> Result<(), BuildFailure<Self::Error>> {
1053            if mem::take(&mut self.fail_next_directory) {
1054                return Err(BuildFailure::recoverable(BuildError::Encoder(TestError)));
1055            }
1056            Ok(())
1057        }
1058
1059        async fn write_symbolic_link_member(
1060            &mut self,
1061            _path: &str,
1062            _target: &str,
1063        ) -> Result<(), BuildFailure<Self::Error>> {
1064            Ok(())
1065        }
1066    }
1067
1068    #[tokio::test]
1069    async fn deep_manual_entry_uses_linear_component_storage() {
1070        const COMPONENT: &str = "segment";
1071        const DEPTH: usize = 4_096;
1072
1073        let mut path = format!("{COMPONENT}/").repeat(DEPTH);
1074        path.push_str("file");
1075        let mut builder = NoopArchiveBuilder::default().builder();
1076        builder
1077            .add_file(&path, b"".as_slice(), EntryMetadata::default())
1078            .await
1079            .expect("deep manual file should be added");
1080
1081        assert_eq!(builder.state.entries.node_count(), DEPTH + 2);
1082        assert_eq!(
1083            builder.state.entries.component_bytes(),
1084            DEPTH * COMPONENT.len() + "file".len()
1085        );
1086    }
1087
1088    #[tokio::test]
1089    async fn collision_state_preserves_literal_slash_components() {
1090        let mut builder = NoopArchiveBuilder::default().builder();
1091        for path in ["a//b", "a/b", "/absolute", "absolute", ".", ".."] {
1092            builder
1093                .add_file(path, b"".as_slice(), EntryMetadata::default())
1094                .await
1095                .expect("distinct textual path should be added");
1096        }
1097
1098        for (path, collision) in [("a//b", "a//b"), ("a/", "a/"), ("", ""), ("./child", ".")] {
1099            assert!(matches!(
1100                builder
1101                    .add_file(
1102                        path,
1103                        b"".as_slice(),
1104                        EntryMetadata::default(),
1105                    )
1106                    .await,
1107                Err(BuildError::PathCollision { path }) if path == collision
1108            ));
1109        }
1110    }
1111
1112    #[tokio::test]
1113    async fn recoverable_write_failure_does_not_commit_reservation() {
1114        let mut builder = NoopArchiveBuilder {
1115            fail_next_file: true,
1116            ..Default::default()
1117        }
1118        .builder();
1119        assert!(matches!(
1120            builder
1121                .add_file("parent/file", b"".as_slice(), EntryMetadata::default(),)
1122                .await,
1123            Err(BuildError::Encoder(TestError))
1124        ));
1125        builder
1126            .add_file("parent/file", b"".as_slice(), EntryMetadata::default())
1127            .await
1128            .expect("a recoverable failure should not reserve the path");
1129    }
1130
1131    #[tokio::test]
1132    async fn recoverable_directory_write_failure_does_not_commit_reservation() {
1133        let mut builder = NoopArchiveBuilder {
1134            fail_next_directory: true,
1135            ..Default::default()
1136        }
1137        .builder();
1138
1139        assert!(matches!(
1140            builder.add_directory("directory").await,
1141            Err(BuildError::Encoder(TestError))
1142        ));
1143        assert_eq!(builder.state.entries.node_count(), 1);
1144
1145        builder
1146            .add_directory("directory")
1147            .await
1148            .expect("a recoverable failure should not reserve the directory");
1149        assert_eq!(builder.state.entries.node_count(), 2);
1150    }
1151
1152    #[tokio::test]
1153    async fn repeated_directory_additions_use_linear_component_storage() {
1154        const DIRECTORIES: usize = 256;
1155
1156        let temp = tempdir().expect("temporary directory should be created");
1157        let mut builder = NoopArchiveBuilder::default().builder();
1158        for index in 0..DIRECTORIES {
1159            let source = temp.path().join(format!("directory-{index}"));
1160            fs::create_dir(&source).expect("source directory should be created");
1161            builder
1162                .add_directory_all(&source)
1163                .await
1164                .expect("empty source directory should be added");
1165        }
1166
1167        assert_eq!(builder.state.entries.node_count(), DIRECTORIES + 1);
1168    }
1169}