1#[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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
32pub struct EntryMetadata {
33 executable: bool,
34}
35
36impl EntryMetadata {
37 pub fn executable(mut self, executable: bool) -> Self {
39 self.executable = executable;
40 self
41 }
42
43 pub fn is_executable(self) -> bool {
45 self.executable
46 }
47}
48
49#[derive(Clone, Copy, Debug, Default)]
51pub struct BuilderPolicy {
52 name_validation: NameValidation,
53 symlink_policy: SymlinkPolicy,
54}
55
56#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
58pub enum SymlinkPolicy {
59 #[default]
61 Reject,
62 Preserve,
64 }
68
69impl BuilderPolicy {
70 pub fn name_validator(mut self, validator: Option<NameValidator>) -> Self {
75 self.name_validation = NameValidation::from_validator(validator);
76 self
77 }
78
79 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 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
153pub struct FilePayload<'a> {
156 size: u64,
157 started: bool,
158 inner: FilePayloadInner<'a>,
159}
160
161enum FilePayloadInner<'a> {
162 Buffered(Option<&'a [u8]>),
167 Reader {
168 source: Pin<Box<dyn AsyncRead + '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 pub fn new<R>(size: u64, source: R) -> Self
183 where
184 R: AsyncRead + 'a,
185 {
186 Self::streaming(size, source, Vec::new(), None)
187 }
188
189 pub fn size(&self) -> u64 {
194 self.size
195 }
196
197 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 + '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 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#[derive(Debug)]
305pub struct BuildFailure<E> {
306 error: BuildError<E>,
307 poisons_builder: bool,
310}
311
312impl<E> BuildFailure<E> {
313 pub fn recoverable(error: impl Into<BuildError<E>>) -> Self {
315 Self {
316 error: error.into(),
317 poisons_builder: false,
318 }
319 }
320
321 pub fn poisoned(error: impl Into<BuildError<E>>) -> Self {
323 Self {
324 error: error.into(),
325 poisons_builder: true,
326 }
327 }
328}
329
330#[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 type Error;
347
348 type FileOptions: From<EntryMetadata>;
354
355 fn builder(self) -> Builder<Self> {
359 Builder {
360 backend: self,
361 state: BuilderState::new(BuilderPolicy::default()),
362 }
363 }
364
365 async fn finish_archive(&mut self) -> Result<(), BuildFailure<Self::Error>>;
367
368 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 async fn write_directory_member(&mut self, path: &str)
381 -> Result<(), BuildFailure<Self::Error>>;
382
383 async fn write_symbolic_link_member(
385 &mut self,
386 path: &str,
387 target: &str,
388 ) -> Result<(), BuildFailure<Self::Error>>;
389}
390
391pub struct Builder<B> {
395 backend: B,
396 state: BuilderState,
397}
398
399impl<B: ArchiveBuilder> Builder<B> {
400 pub fn with_policy(mut self, policy: BuilderPolicy) -> Self {
404 self.state.policy = policy;
405 self
406 }
407
408 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 #[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 pub async fn finish(self) -> Result<(), BuildError<B::Error>> {
478 self.finish_into_inner().await?;
479 Ok(())
480 }
481
482 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#[derive(Debug, Error)]
500#[non_exhaustive]
501pub enum BuildError<E> {
502 #[error(transparent)]
504 Encoder(E),
505 #[cfg(feature = "fs")]
507 #[error(transparent)]
508 Traversal(#[from] TraversalError),
509 #[error("invalid archive path {path:?}: {reason}")]
511 InvalidArchivePath {
512 path: PathBuf,
514 reason: &'static str,
516 },
517 #[error("archive {context} rejected by builder policy: {value:?}")]
519 NameRejected {
520 context: &'static str,
522 value: String,
524 },
525 #[error("archive entry collides with existing path {path}")]
527 PathCollision {
528 path: String,
530 },
531 #[error("file payload was already read before being added to the archive")]
533 FilePayloadAlreadyRead,
534 #[error("failed to {operation} {path}: {source}")]
536 Filesystem {
537 operation: &'static str,
539 path: PathBuf,
541 #[source]
543 source: io::Error,
544 },
545 #[error("failed to read archive file payload source")]
547 SourceRead {
548 #[source]
550 source: io::Error,
551 },
552 #[cfg(feature = "fs")]
554 #[error("failed to complete blocking archive filesystem operation: {0}")]
555 BlockingTask(#[from] tokio::task::JoinError),
556 #[error("archive builder is poisoned after a previous partial write")]
558 Poisoned,
559 #[error("arithmetic overflow while computing {context}")]
561 ArithmeticOverflow {
562 context: &'static str,
564 },
565}
566
567#[derive(Clone, Copy, Debug)]
568enum ArchivedEntry {
569 Directory { explicit: bool },
570 NonDirectory,
571}
572
573#[derive(Debug)]
575struct BuildEntries(ComponentTree<Box<str>, ArchivedEntry>);
576
577struct 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 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
650fn 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}