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
6#[cfg(feature = "fs")]
7mod directory;
8#[cfg(feature = "fs")]
9mod traversal;
10
11use std::{
12    io, mem,
13    path::{Path, PathBuf},
14    pin::Pin,
15};
16
17use thiserror::Error;
18use tokio::io::{AsyncRead, AsyncReadExt};
19
20#[cfg(feature = "fs")]
21pub use self::traversal::TraversalError;
22use crate::{
23    NameValidator,
24    component_tree::{ComponentTree, ROOT_NODE},
25    name::NameValidation,
26};
27
28const FILE_PAYLOAD_CHUNK_BYTES: usize = 2 * 1024 * 1024;
29
30/// Minimal regular-file metadata accepted by [`Builder`].
31#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
32pub struct EntryMetadata {
33    executable: bool,
34}
35
36impl EntryMetadata {
37    /// Configures whether the regular file carries executable intent.
38    pub fn executable(mut self, executable: bool) -> Self {
39        self.executable = executable;
40        self
41    }
42
43    /// Returns whether this entry carries executable intent.
44    pub fn is_executable(self) -> bool {
45        self.executable
46    }
47}
48
49/// Controls format-neutral archive construction behavior.
50#[derive(Clone, Copy, Debug, Default)]
51pub struct BuilderPolicy {
52    name_validation: NameValidation,
53    symlink_policy: SymlinkPolicy,
54}
55
56/// Controls how source symbolic links are handled during recursive builds.
57#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
58pub enum SymlinkPolicy {
59    /// Reject recursive sources containing symbolic links.
60    #[default]
61    Reject,
62    /// Preserve symbolic links as link members in the resulting archive.
63    Preserve,
64    // TODO: Consider adding some kind of "Dereference" policy in the future,
65    // where symlinks get followed and replaced with their normal file/directory
66    // contents.
67}
68
69impl BuilderPolicy {
70    /// Configures validation for member names and preserved symbolic-link targets.
71    ///
72    /// Passing [`None`] disables configurable name validation. UTF-8 and
73    /// archive-format requirements still apply.
74    pub fn name_validator(mut self, validator: Option<NameValidator>) -> Self {
75        self.name_validation = NameValidation::from_validator(validator);
76        self
77    }
78
79    /// Configures how recursive builds handle source symbolic links.
80    ///
81    /// Symbolic links are **rejected by default**. Use
82    /// [`SymlinkPolicy::Preserve`] to write link members instead.
83    pub fn symlink_policy(mut self, policy: SymlinkPolicy) -> Self {
84        self.symlink_policy = policy;
85        self
86    }
87}
88
89struct BuilderState {
90    policy: BuilderPolicy,
91    entries: BuildEntries,
92    source_buffer: Vec<u8>,
93    poisoned: bool,
94}
95
96impl BuilderState {
97    fn new(policy: BuilderPolicy) -> Self {
98        Self {
99            policy,
100            entries: BuildEntries::new(),
101            source_buffer: Vec::new(),
102            poisoned: false,
103        }
104    }
105
106    fn ensure_active<E>(&self) -> Result<(), BuildError<E>> {
107        if self.poisoned {
108            return Err(BuildError::Poisoned);
109        }
110        Ok(())
111    }
112
113    fn prepare_entry<'a, E>(
114        &self,
115        path: &'a impl AsRef<Path>,
116        entry: ArchivedEntry,
117    ) -> Result<(&'a str, EntryReservation), BuildError<E>> {
118        self.ensure_active()?;
119        let archive_path = path.as_ref();
120        let Some(path) = archive_path.to_str() else {
121            return Err(BuildError::InvalidArchivePath {
122                path: archive_path.to_path_buf(),
123                reason: "path is not valid UTF-8",
124            });
125        };
126        if !self.policy.name_validation.accepts(path) {
127            return Err(BuildError::NameRejected {
128                context: "member path",
129                value: path.to_owned(),
130            });
131        }
132        Ok((path, self.entries.preflight_entry(path, entry)?))
133    }
134
135    // Cancellation can leave partial output. Keep the builder poisoned until
136    // the write returns and we know whether it is safe to continue.
137    fn begin_write(&mut self) {
138        self.poisoned = true;
139    }
140
141    fn complete_write<E>(
142        &mut self,
143        result: Result<(), BuildFailure<E>>,
144        emitted_entries: bool,
145    ) -> Result<(), BuildError<E>> {
146        self.poisoned = result
147            .as_ref()
148            .is_err_and(|failure| emitted_entries || failure.poisons_builder);
149        result.map_err(|failure| failure.error)
150    }
151}
152
153/// A format-neutral, uncompressed file payload supplied to an [`ArchiveBuilder`]
154/// implementation.
155pub struct FilePayload<'a> {
156    size: u64,
157    started: bool,
158    inner: FilePayloadInner<'a>,
159}
160
161enum FilePayloadInner<'a> {
162    /// A pre-buffered payload.
163    ///
164    /// Observe that this is stored as an `Option` so that we can use the `None`
165    /// state to communicate that the payload has been consumed.
166    Buffered(Option<&'a [u8]>),
167    Reader {
168        source: Pin<Box<dyn AsyncRead + Send + 'a>>,
169        filesystem_path: Option<&'a Path>,
170        buffer: Vec<u8>,
171        remaining: u64,
172        filled: usize,
173    },
174}
175
176impl<'a> FilePayload<'a> {
177    /// Creates a payload with a declared logical size and [`AsyncRead`] source.
178    ///
179    /// The builder reads exactly `size` bytes from `source`. Additional bytes
180    /// remain unread, while a source that ends early causes the addition to
181    /// fail.
182    pub fn new<R>(size: u64, source: R) -> Self
183    where
184        R: AsyncRead + Send + 'a,
185    {
186        Self::streaming(size, source, Vec::new(), None)
187    }
188
189    /// Returns the logical, uncompressed source size in bytes.
190    ///
191    /// This is the total number of bytes yielded by [`Self::next_chunk`], not
192    /// necessarily the size ultimately stored by the archive format.
193    pub fn size(&self) -> u64 {
194        self.size
195    }
196
197    /// Returns the next chunk of logical, uncompressed source bytes.
198    ///
199    /// Once this method has been called, the payload cannot be passed to
200    /// [`Builder::add_file`].
201    pub async fn next_chunk<E>(&mut self) -> Result<Option<&[u8]>, BuildError<E>> {
202        self.started = true;
203        match &mut self.inner {
204            FilePayloadInner::Buffered(bytes) => Ok(bytes.take().filter(|bytes| !bytes.is_empty())),
205            FilePayloadInner::Reader {
206                source,
207                filesystem_path,
208                buffer,
209                remaining,
210                filled,
211            } => read_streaming_chunk(source, buffer, remaining, filled, *filesystem_path).await,
212        }
213    }
214
215    fn streaming<R>(
216        size: u64,
217        source: R,
218        buffer: Vec<u8>,
219        filesystem_path: Option<&'a Path>,
220    ) -> Self
221    where
222        R: AsyncRead + Send + 'a,
223    {
224        Self {
225            size,
226            started: false,
227            inner: FilePayloadInner::Reader {
228                source: Box::pin(source),
229                filesystem_path,
230                buffer,
231                remaining: size,
232                filled: 0,
233            },
234        }
235    }
236
237    fn swap_buffer(&mut self, buffer: &mut Vec<u8>) {
238        if let FilePayloadInner::Reader {
239            buffer: payload_buffer,
240            ..
241        } = &mut self.inner
242        {
243            mem::swap(payload_buffer, buffer);
244        }
245    }
246}
247
248impl<'a> From<&'a [u8]> for FilePayload<'a> {
249    fn from(bytes: &'a [u8]) -> Self {
250        let size = bytes.len() as u64;
251        Self {
252            size,
253            started: false,
254            inner: FilePayloadInner::Buffered(Some(bytes)),
255        }
256    }
257}
258
259async fn read_streaming_chunk<'a, E, R>(
260    source: &mut R,
261    buffer: &'a mut Vec<u8>,
262    remaining: &mut u64,
263    filled: &mut usize,
264    filesystem_path: Option<&Path>,
265) -> Result<Option<&'a [u8]>, BuildError<E>>
266where
267    R: AsyncRead + Unpin + ?Sized,
268{
269    if *remaining == 0 {
270        return Ok(None);
271    }
272
273    let chunk_size = (*remaining).min(FILE_PAYLOAD_CHUNK_BYTES as u64);
274    let chunk_len = usize::try_from(chunk_size)
275        .map_err(|_| arithmetic_overflow("file payload read buffer size"))?;
276    buffer.resize(chunk_len, 0);
277    // Progress lives in the payload rather than this future, so cancelling and
278    // retrying `FilePayload::next_chunk` cannot discard completed reads.
279    while *filled < chunk_len {
280        let read = source
281            .read(&mut buffer[*filled..])
282            .await
283            .map_err(|source| file_payload_read_error(filesystem_path, source))?;
284        if read == 0 {
285            return Err(file_payload_read_error(
286                filesystem_path,
287                io::Error::new(
288                    io::ErrorKind::UnexpectedEof,
289                    "file payload source ended before its declared size",
290                ),
291            ));
292        }
293        *filled += read;
294    }
295    *remaining -= chunk_size;
296    *filled = 0;
297    Ok(Some(buffer))
298}
299
300/// A failure returned by an [`ArchiveBuilder`] format hook.
301///
302/// This distinguishes errors known to precede output from errors that may have
303/// left a partial member in the output archive.
304#[derive(Debug)]
305pub struct BuildFailure<E> {
306    error: BuildError<E>,
307    // TODO: Maybe make all failures poisoning?
308    // I'm not sure we really need the distinction here.
309    poisons_builder: bool,
310}
311
312impl<E> BuildFailure<E> {
313    /// Reports a failure that occurred before the hook wrote any output.
314    pub fn recoverable(error: impl Into<BuildError<E>>) -> Self {
315        Self {
316            error: error.into(),
317            poisons_builder: false,
318        }
319    }
320
321    /// Reports a failure that may have left partial output.
322    pub fn poisoned(error: impl Into<BuildError<E>>) -> Self {
323        Self {
324            error: error.into(),
325            poisons_builder: true,
326        }
327    }
328}
329
330/// A format-specific archive writer that can create a stateful [`Builder`].
331///
332/// The asynchronous methods on this trait are implementation hooks for
333/// [`Builder`]. Archive construction callers must not invoke them directly;
334/// doing so bypasses builder policy, collision tracking, and cancellation
335/// poisoning. Use [`Self::builder`] and then the [`Builder`] APIs instead.
336///
337/// Hook implementations must return [`BuildFailure::recoverable`] only when the
338/// failed invocation wrote no output. Any failure after output may have begun
339/// must use [`BuildFailure::poisoned`].
340#[expect(
341    async_fn_in_trait,
342    reason = "archive writers may be !Send and run on a local executor"
343)]
344pub trait ArchiveBuilder: Sized {
345    /// The archive-format error returned while encoding entries.
346    type Error;
347
348    /// Options for one regular file, including format-neutral metadata.
349    ///
350    /// Conversion from [`EntryMetadata`] must preserve the metadata and use
351    /// the writer's configured defaults for format-specific settings.
352    /// Formats without additional settings can use [`EntryMetadata`] directly.
353    type FileOptions: From<EntryMetadata>;
354
355    /// Wraps this format writer in a builder using default policy.
356    ///
357    /// Implementors should not override this default implementation.
358    fn builder(self) -> Builder<Self> {
359        Builder {
360            backend: self,
361            state: BuilderState::new(BuilderPolicy::default()),
362        }
363    }
364
365    /// Writes any format-specific archive terminator or index.
366    async fn finish_archive(&mut self) -> Result<(), BuildFailure<Self::Error>>;
367
368    /// Writes one regular-file member and its complete payload.
369    ///
370    /// Implementations must call [`FilePayload::next_chunk`] through
371    /// completion and classify failures using [`BuildFailure`].
372    async fn write_file_member(
373        &mut self,
374        path: &str,
375        payload: &mut FilePayload<'_>,
376        options: Self::FileOptions,
377    ) -> Result<(), BuildFailure<Self::Error>>;
378
379    /// Writes one directory member.
380    async fn write_directory_member(&mut self, path: &str)
381    -> Result<(), BuildFailure<Self::Error>>;
382
383    /// Writes one symbolic-link member.
384    async fn write_symbolic_link_member(
385        &mut self,
386        path: &str,
387        target: &str,
388    ) -> Result<(), BuildFailure<Self::Error>>;
389}
390
391/// A stateful format-neutral archive construction engine.
392///
393/// Create this wrapper with [`ArchiveBuilder::builder`].
394pub struct Builder<B> {
395    backend: B,
396    state: BuilderState,
397}
398
399impl<B: ArchiveBuilder> Builder<B> {
400    /// Configures the policy used by this builder.
401    ///
402    /// Call before adding any entries.
403    pub fn with_policy(mut self, policy: BuilderPolicy) -> Self {
404        self.state.policy = policy;
405        self
406    }
407
408    /// Adds one regular file from a [`FilePayload`].
409    ///
410    /// Pass [`EntryMetadata`] to use the writer's configured defaults or
411    /// [`ArchiveBuilder::FileOptions`] to configure this file.
412    ///
413    /// If the payload ends before its declared size or returns an error, the
414    /// addition fails and the builder is poisoned if the archive member's
415    /// output may already have begun.
416    ///
417    /// The payload must not have been read through [`FilePayload::next_chunk`]
418    /// before this method is called.
419    pub async fn add_file<'a, P>(
420        &mut self,
421        path: P,
422        payload: impl Into<FilePayload<'a>>,
423        options: impl Into<B::FileOptions>,
424    ) -> Result<(), BuildError<B::Error>>
425    where
426        P: AsRef<Path>,
427    {
428        let (path, reservation) = self
429            .state
430            .prepare_entry(&path, ArchivedEntry::NonDirectory)?;
431        let mut payload = payload.into();
432        if payload.started {
433            return Err(BuildError::FilePayloadAlreadyRead);
434        }
435
436        let options = options.into();
437        payload.swap_buffer(&mut self.state.source_buffer);
438        self.state.begin_write();
439        let result = self
440            .backend
441            .write_file_member(path, &mut payload, options)
442            .await;
443        payload.swap_buffer(&mut self.state.source_buffer);
444        self.state.complete_write(result, false)?;
445
446        self.state.entries.commit_entry(path, reservation);
447        Ok(())
448    }
449
450    /// Adds one directory member without reading from the filesystem.
451    ///
452    /// This creates only the named directory member. It does not add any child
453    /// members. Trailing slashes are ignored for directory collision checks, so
454    /// adding both `dir` and `dir/` returns a [`BuildError::PathCollision`] on
455    /// the second call.
456    #[cfg_attr(
457        feature = "fs",
458        doc = "",
459        doc = "Use [`Self::add_directory_all`] to recursively add a filesystem",
460        doc = "directory and its contents."
461    )]
462    pub async fn add_directory<P: AsRef<Path>>(
463        &mut self,
464        path: P,
465    ) -> Result<(), BuildError<B::Error>> {
466        let (path, reservation) = self
467            .state
468            .prepare_entry(&path, ArchivedEntry::Directory { explicit: true })?;
469        self.state.begin_write();
470        let result = self.backend.write_directory_member(path).await;
471        self.state.complete_write(result, false)?;
472        self.state.entries.commit_entry(path, reservation);
473        Ok(())
474    }
475
476    /// Finalizes and consumes this archive builder.
477    pub async fn finish(self) -> Result<(), BuildError<B::Error>> {
478        self.finish_into_inner().await?;
479        Ok(())
480    }
481
482    /// Finalizes this archive builder and returns its format writer.
483    ///
484    /// This allows callers to recover and finalize an owned output sink after
485    /// the archive terminator has been written.
486    pub async fn finish_into_inner(mut self) -> Result<B, BuildError<B::Error>> {
487        self.state.ensure_active()?;
488        self.backend
489            .finish_archive()
490            .await
491            .map_err(|failure| failure.error)?;
492        Ok(self.backend)
493    }
494}
495
496/// A failure while constructing an archive.
497///
498/// This enum is non-exhaustive because the `fs` feature adds variants.
499#[derive(Debug, Error)]
500#[non_exhaustive]
501pub enum BuildError<E> {
502    /// The archive format encoder failed.
503    #[error(transparent)]
504    Encoder(E),
505    /// Traversing a recursive source failed.
506    #[cfg(feature = "fs")]
507    #[error(transparent)]
508    Traversal(#[from] TraversalError),
509    /// A requested archive path cannot be represented by the UTF-8 builder.
510    #[error("invalid archive path {path:?}: {reason}")]
511    InvalidArchivePath {
512        /// The rejected archive path.
513        path: PathBuf,
514        /// The reason the path cannot be represented.
515        reason: &'static str,
516    },
517    /// An archive name was rejected by the configured [`BuilderPolicy`].
518    #[error("archive {context} rejected by builder policy: {value:?}")]
519    NameRejected {
520        /// The role of the rejected archive text.
521        context: &'static str,
522        /// The rejected UTF-8 value.
523        value: String,
524    },
525    /// An archive path collides with a previously reserved entry.
526    #[error("archive entry collides with existing path {path}")]
527    PathCollision {
528        /// The conflicting normalized archive path.
529        path: String,
530    },
531    /// A file payload was read before it was passed to [`Builder::add_file`].
532    #[error("file payload was already read before being added to the archive")]
533    FilePayloadAlreadyRead,
534    /// A source filesystem operation failed.
535    #[error("failed to {operation} {path}: {source}")]
536    Filesystem {
537        /// The operation that failed.
538        operation: &'static str,
539        /// The affected source filesystem path.
540        path: PathBuf,
541        /// The underlying I/O error.
542        #[source]
543        source: io::Error,
544    },
545    /// Reading an asynchronous file payload source failed.
546    #[error("failed to read archive file payload source")]
547    SourceRead {
548        /// The underlying I/O error.
549        #[source]
550        source: io::Error,
551    },
552    /// A blocking filesystem operation failed to complete.
553    #[cfg(feature = "fs")]
554    #[error("failed to complete blocking archive filesystem operation: {0}")]
555    BlockingTask(#[from] tokio::task::JoinError),
556    /// The builder cannot continue because a prior failure may have written bytes.
557    #[error("archive builder is poisoned after a previous partial write")]
558    Poisoned,
559    /// A size computation exceeded this API's range.
560    #[error("arithmetic overflow while computing {context}")]
561    ArithmeticOverflow {
562        /// The failed computation.
563        context: &'static str,
564    },
565}
566
567#[derive(Clone, Copy, Debug)]
568enum ArchivedEntry {
569    Directory { explicit: bool },
570    NonDirectory,
571}
572
573/// Builder collision state keyed by literal `/`-separated archive components.
574#[derive(Debug)]
575struct BuildEntries(ComponentTree<Box<str>, ArchivedEntry>);
576
577/// Proof that an entry was checked against the current collision state.
578struct EntryReservation {
579    entry: ArchivedEntry,
580}
581
582impl BuildEntries {
583    fn new() -> Self {
584        Self(ComponentTree::new(None))
585    }
586
587    fn preflight_entry<E>(
588        &self,
589        path: &str,
590        entry: ArchivedEntry,
591    ) -> Result<EntryReservation, BuildError<E>> {
592        let mut parent = ROOT_NODE;
593        let mut components = archive_path_components(path, entry).peekable();
594        while let Some((component, prefix)) = components.next() {
595            let Some(node) = self.0.child(parent, component) else {
596                return Ok(EntryReservation { entry });
597            };
598            if components.peek().is_some() {
599                match self.0.state(node) {
600                    Some(ArchivedEntry::Directory { .. }) => parent = node,
601                    Some(ArchivedEntry::NonDirectory) => return Err(path_collision(prefix)),
602                    None => return Ok(EntryReservation { entry }),
603                }
604            } else {
605                match (self.0.state(node), entry) {
606                    (
607                        Some(ArchivedEntry::Directory { explicit: false }),
608                        ArchivedEntry::Directory { .. },
609                    )
610                    | (None, _) => return Ok(EntryReservation { entry }),
611                    (Some(_), _) => return Err(path_collision(prefix)),
612                }
613            }
614        }
615        Ok(EntryReservation { entry })
616    }
617
618    fn commit_entry(&mut self, path: &str, reservation: EntryReservation) {
619        // The builder holds exclusive state access while the backend hook is
620        // awaited, so a successful reservation remains valid until this commit.
621        let mut parent = ROOT_NODE;
622        let mut components = archive_path_components(path, reservation.entry).peekable();
623        while let Some((component, _)) = components.next() {
624            let node = self
625                .0
626                .ensure_child_with(parent, component, || component.into());
627            if components.peek().is_some() {
628                if self.0.state(node).is_none() {
629                    self.0
630                        .set_state(node, ArchivedEntry::Directory { explicit: false });
631                }
632            } else {
633                self.0.set_state(node, reservation.entry);
634            }
635            parent = node;
636        }
637    }
638
639    #[cfg(test)]
640    fn node_count(&self) -> usize {
641        self.0.node_count()
642    }
643
644    #[cfg(test)]
645    fn component_bytes(&self) -> usize {
646        self.0.components().map(|component| component.len()).sum()
647    }
648}
649
650/// Iterates literal components and prefixes, ignoring trailing slashes on directories.
651fn archive_path_components(path: &str, entry: ArchivedEntry) -> impl Iterator<Item = (&str, &str)> {
652    let path = match entry {
653        ArchivedEntry::Directory { .. } => path.trim_end_matches('/'),
654        ArchivedEntry::NonDirectory => path,
655    };
656    let mut component_start = 0;
657    path.split('/').map(move |component| {
658        let prefix_end = component_start + component.len();
659        let prefix = &path[..prefix_end];
660        component_start = if prefix_end < path.len() {
661            prefix_end + 1
662        } else {
663            prefix_end
664        };
665        (component, prefix)
666    })
667}
668
669fn file_payload_read_error<E>(filesystem_path: Option<&Path>, source: io::Error) -> BuildError<E> {
670    if let Some(path) = filesystem_path {
671        BuildError::Filesystem {
672            operation: "read source file",
673            path: path.to_path_buf(),
674            source,
675        }
676    } else {
677        BuildError::SourceRead { source }
678    }
679}
680
681fn arithmetic_overflow<E>(context: &'static str) -> BuildError<E> {
682    BuildError::ArithmeticOverflow { context }
683}
684
685fn path_collision<E>(path: &str) -> BuildError<E> {
686    BuildError::PathCollision {
687        path: path.to_owned(),
688    }
689}
690
691#[cfg(test)]
692mod tests {
693    #[cfg(feature = "fs")]
694    use std::fs;
695
696    #[cfg(feature = "fs")]
697    use tempfile::tempdir;
698
699    use super::*;
700
701    #[derive(Debug)]
702    struct TestError;
703
704    #[derive(Default)]
705    struct NoopArchiveBuilder {
706        fail_next_file: bool,
707        fail_next_directory: bool,
708    }
709
710    impl ArchiveBuilder for NoopArchiveBuilder {
711        type Error = TestError;
712        type FileOptions = EntryMetadata;
713
714        async fn finish_archive(&mut self) -> Result<(), BuildFailure<Self::Error>> {
715            Ok(())
716        }
717
718        async fn write_file_member(
719            &mut self,
720            _path: &str,
721            payload: &mut FilePayload<'_>,
722            _options: Self::FileOptions,
723        ) -> Result<(), BuildFailure<Self::Error>> {
724            if mem::take(&mut self.fail_next_file) {
725                return Err(BuildFailure::recoverable(BuildError::Encoder(TestError)));
726            }
727            loop {
728                match payload.next_chunk::<TestError>().await {
729                    Ok(Some(_)) => {}
730                    Ok(None) => return Ok(()),
731                    Err(error) => return Err(BuildFailure::recoverable(error)),
732                }
733            }
734        }
735
736        async fn write_directory_member(
737            &mut self,
738            _path: &str,
739        ) -> Result<(), BuildFailure<Self::Error>> {
740            if mem::take(&mut self.fail_next_directory) {
741                return Err(BuildFailure::recoverable(BuildError::Encoder(TestError)));
742            }
743            Ok(())
744        }
745
746        async fn write_symbolic_link_member(
747            &mut self,
748            _path: &str,
749            _target: &str,
750        ) -> Result<(), BuildFailure<Self::Error>> {
751            Ok(())
752        }
753    }
754
755    #[tokio::test]
756    async fn deep_manual_entry_uses_linear_component_storage() {
757        const COMPONENT: &str = "segment";
758        const DEPTH: usize = 4_096;
759
760        let mut path = format!("{COMPONENT}/").repeat(DEPTH);
761        path.push_str("file");
762        let mut builder = NoopArchiveBuilder::default().builder();
763        builder
764            .add_file(&path, b"".as_slice(), EntryMetadata::default())
765            .await
766            .expect("deep manual file should be added");
767
768        assert_eq!(builder.state.entries.node_count(), DEPTH + 2);
769        assert_eq!(
770            builder.state.entries.component_bytes(),
771            DEPTH * COMPONENT.len() + "file".len()
772        );
773    }
774
775    #[tokio::test]
776    async fn collision_state_preserves_literal_slash_components() {
777        let mut builder = NoopArchiveBuilder::default().builder();
778        for path in ["a//b", "a/b", "/absolute", "absolute", ".", ".."] {
779            builder
780                .add_file(path, b"".as_slice(), EntryMetadata::default())
781                .await
782                .expect("distinct textual path should be added");
783        }
784
785        for (path, collision) in [("a//b", "a//b"), ("a/", "a/"), ("", ""), ("./child", ".")] {
786            assert!(matches!(
787                builder
788                    .add_file(
789                        path,
790                        b"".as_slice(),
791                        EntryMetadata::default(),
792                    )
793                    .await,
794                Err(BuildError::PathCollision { path }) if path == collision
795            ));
796        }
797    }
798
799    #[tokio::test]
800    async fn recoverable_write_failure_does_not_commit_reservation() {
801        let mut builder = NoopArchiveBuilder {
802            fail_next_file: true,
803            ..Default::default()
804        }
805        .builder();
806        assert!(matches!(
807            builder
808                .add_file("parent/file", b"".as_slice(), EntryMetadata::default(),)
809                .await,
810            Err(BuildError::Encoder(TestError))
811        ));
812        builder
813            .add_file("parent/file", b"".as_slice(), EntryMetadata::default())
814            .await
815            .expect("a recoverable failure should not reserve the path");
816    }
817
818    #[tokio::test]
819    async fn recoverable_directory_write_failure_does_not_commit_reservation() {
820        let mut builder = NoopArchiveBuilder {
821            fail_next_directory: true,
822            ..Default::default()
823        }
824        .builder();
825
826        assert!(matches!(
827            builder.add_directory("directory").await,
828            Err(BuildError::Encoder(TestError))
829        ));
830        assert_eq!(builder.state.entries.node_count(), 1);
831
832        builder
833            .add_directory("directory")
834            .await
835            .expect("a recoverable failure should not reserve the directory");
836        assert_eq!(builder.state.entries.node_count(), 2);
837    }
838
839    #[cfg(feature = "fs")]
840    #[tokio::test]
841    async fn repeated_directory_additions_use_linear_component_storage() {
842        const DIRECTORIES: usize = 256;
843
844        let temp = tempdir().expect("temporary directory should be created");
845        let mut builder = NoopArchiveBuilder::default().builder();
846        for index in 0..DIRECTORIES {
847            let source = temp.path().join(format!("directory-{index}"));
848            fs::create_dir(&source).expect("source directory should be created");
849            builder
850                .add_directory_all(&source)
851                .await
852                .expect("empty source directory should be added");
853        }
854
855        assert_eq!(builder.state.entries.node_count(), DIRECTORIES + 1);
856    }
857}