#[cfg(feature = "fs")]
mod directory;
#[cfg(feature = "fs")]
mod traversal;
use std::{
io, mem,
path::{Path, PathBuf},
pin::Pin,
};
use thiserror::Error;
use tokio::io::{AsyncRead, AsyncReadExt};
#[cfg(feature = "fs")]
pub use self::traversal::TraversalError;
use crate::{
NameValidator,
component_tree::{ComponentTree, ROOT_NODE},
name::NameValidation,
};
const FILE_PAYLOAD_CHUNK_BYTES: usize = 2 * 1024 * 1024;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct EntryMetadata {
executable: bool,
}
impl EntryMetadata {
pub fn executable(mut self, executable: bool) -> Self {
self.executable = executable;
self
}
pub fn is_executable(self) -> bool {
self.executable
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct BuilderPolicy {
name_validation: NameValidation,
symlink_policy: SymlinkPolicy,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum SymlinkPolicy {
#[default]
Reject,
Preserve,
}
impl BuilderPolicy {
pub fn name_validator(mut self, validator: Option<NameValidator>) -> Self {
self.name_validation = NameValidation::from_validator(validator);
self
}
pub fn symlink_policy(mut self, policy: SymlinkPolicy) -> Self {
self.symlink_policy = policy;
self
}
}
struct BuilderState {
policy: BuilderPolicy,
entries: BuildEntries,
source_buffer: Vec<u8>,
poisoned: bool,
}
impl BuilderState {
fn new(policy: BuilderPolicy) -> Self {
Self {
policy,
entries: BuildEntries::new(),
source_buffer: Vec::new(),
poisoned: false,
}
}
fn ensure_active<E>(&self) -> Result<(), BuildError<E>> {
if self.poisoned {
return Err(BuildError::Poisoned);
}
Ok(())
}
fn prepare_entry<'a, E>(
&self,
path: &'a impl AsRef<Path>,
entry: ArchivedEntry,
) -> Result<(&'a str, EntryReservation), BuildError<E>> {
self.ensure_active()?;
let archive_path = path.as_ref();
let Some(path) = archive_path.to_str() else {
return Err(BuildError::InvalidArchivePath {
path: archive_path.to_path_buf(),
reason: "path is not valid UTF-8",
});
};
if !self.policy.name_validation.accepts(path) {
return Err(BuildError::NameRejected {
context: "member path",
value: path.to_owned(),
});
}
Ok((path, self.entries.preflight_entry(path, entry)?))
}
fn begin_write(&mut self) {
self.poisoned = true;
}
fn complete_write<E>(
&mut self,
result: Result<(), BuildFailure<E>>,
emitted_entries: bool,
) -> Result<(), BuildError<E>> {
self.poisoned = result
.as_ref()
.is_err_and(|failure| emitted_entries || failure.poisons_builder);
result.map_err(|failure| failure.error)
}
}
pub struct FilePayload<'a> {
size: u64,
started: bool,
inner: FilePayloadInner<'a>,
}
enum FilePayloadInner<'a> {
Buffered(Option<&'a [u8]>),
Reader {
source: Pin<Box<dyn AsyncRead + 'a>>,
filesystem_path: Option<&'a Path>,
buffer: Vec<u8>,
remaining: u64,
filled: usize,
},
}
impl<'a> FilePayload<'a> {
pub fn new<R>(size: u64, source: R) -> Self
where
R: AsyncRead + 'a,
{
Self::streaming(size, source, Vec::new(), None)
}
pub fn size(&self) -> u64 {
self.size
}
pub async fn next_chunk<E>(&mut self) -> Result<Option<&[u8]>, BuildError<E>> {
self.started = true;
match &mut self.inner {
FilePayloadInner::Buffered(bytes) => Ok(bytes.take().filter(|bytes| !bytes.is_empty())),
FilePayloadInner::Reader {
source,
filesystem_path,
buffer,
remaining,
filled,
} => read_streaming_chunk(source, buffer, remaining, filled, *filesystem_path).await,
}
}
fn streaming<R>(
size: u64,
source: R,
buffer: Vec<u8>,
filesystem_path: Option<&'a Path>,
) -> Self
where
R: AsyncRead + 'a,
{
Self {
size,
started: false,
inner: FilePayloadInner::Reader {
source: Box::pin(source),
filesystem_path,
buffer,
remaining: size,
filled: 0,
},
}
}
fn swap_buffer(&mut self, buffer: &mut Vec<u8>) {
if let FilePayloadInner::Reader {
buffer: payload_buffer,
..
} = &mut self.inner
{
mem::swap(payload_buffer, buffer);
}
}
}
impl<'a> From<&'a [u8]> for FilePayload<'a> {
fn from(bytes: &'a [u8]) -> Self {
let size = bytes.len() as u64;
Self {
size,
started: false,
inner: FilePayloadInner::Buffered(Some(bytes)),
}
}
}
async fn read_streaming_chunk<'a, E, R>(
source: &mut R,
buffer: &'a mut Vec<u8>,
remaining: &mut u64,
filled: &mut usize,
filesystem_path: Option<&Path>,
) -> Result<Option<&'a [u8]>, BuildError<E>>
where
R: AsyncRead + Unpin + ?Sized,
{
if *remaining == 0 {
return Ok(None);
}
let chunk_size = (*remaining).min(FILE_PAYLOAD_CHUNK_BYTES as u64);
let chunk_len = usize::try_from(chunk_size)
.map_err(|_| arithmetic_overflow("file payload read buffer size"))?;
buffer.resize(chunk_len, 0);
while *filled < chunk_len {
let read = source
.read(&mut buffer[*filled..])
.await
.map_err(|source| file_payload_read_error(filesystem_path, source))?;
if read == 0 {
return Err(file_payload_read_error(
filesystem_path,
io::Error::new(
io::ErrorKind::UnexpectedEof,
"file payload source ended before its declared size",
),
));
}
*filled += read;
}
*remaining -= chunk_size;
*filled = 0;
Ok(Some(buffer))
}
#[derive(Debug)]
pub struct BuildFailure<E> {
error: BuildError<E>,
poisons_builder: bool,
}
impl<E> BuildFailure<E> {
pub fn recoverable(error: impl Into<BuildError<E>>) -> Self {
Self {
error: error.into(),
poisons_builder: false,
}
}
pub fn poisoned(error: impl Into<BuildError<E>>) -> Self {
Self {
error: error.into(),
poisons_builder: true,
}
}
}
#[expect(
async_fn_in_trait,
reason = "archive writers may be !Send and run on a local executor"
)]
pub trait ArchiveBuilder: Sized {
type Error;
type FileOptions: From<EntryMetadata>;
fn builder(self) -> Builder<Self> {
Builder {
backend: self,
state: BuilderState::new(BuilderPolicy::default()),
}
}
async fn finish_archive(&mut self) -> Result<(), BuildFailure<Self::Error>>;
async fn write_file_member(
&mut self,
path: &str,
payload: &mut FilePayload<'_>,
options: Self::FileOptions,
) -> Result<(), BuildFailure<Self::Error>>;
async fn write_directory_member(&mut self, path: &str)
-> Result<(), BuildFailure<Self::Error>>;
async fn write_symbolic_link_member(
&mut self,
path: &str,
target: &str,
) -> Result<(), BuildFailure<Self::Error>>;
}
pub struct Builder<B> {
backend: B,
state: BuilderState,
}
impl<B: ArchiveBuilder> Builder<B> {
pub fn with_policy(mut self, policy: BuilderPolicy) -> Self {
self.state.policy = policy;
self
}
pub async fn add_file<'a, P>(
&mut self,
path: P,
payload: impl Into<FilePayload<'a>>,
options: impl Into<B::FileOptions>,
) -> Result<(), BuildError<B::Error>>
where
P: AsRef<Path>,
{
let (path, reservation) = self
.state
.prepare_entry(&path, ArchivedEntry::NonDirectory)?;
let mut payload = payload.into();
if payload.started {
return Err(BuildError::FilePayloadAlreadyRead);
}
let options = options.into();
payload.swap_buffer(&mut self.state.source_buffer);
self.state.begin_write();
let result = self
.backend
.write_file_member(path, &mut payload, options)
.await;
payload.swap_buffer(&mut self.state.source_buffer);
self.state.complete_write(result, false)?;
self.state.entries.commit_entry(path, reservation);
Ok(())
}
#[cfg_attr(
feature = "fs",
doc = "",
doc = "Use [`Self::add_directory_all`] to recursively add a filesystem",
doc = "directory and its contents."
)]
pub async fn add_directory<P: AsRef<Path>>(
&mut self,
path: P,
) -> Result<(), BuildError<B::Error>> {
let (path, reservation) = self
.state
.prepare_entry(&path, ArchivedEntry::Directory { explicit: true })?;
self.state.begin_write();
let result = self.backend.write_directory_member(path).await;
self.state.complete_write(result, false)?;
self.state.entries.commit_entry(path, reservation);
Ok(())
}
pub async fn finish(self) -> Result<(), BuildError<B::Error>> {
self.finish_into_inner().await?;
Ok(())
}
pub async fn finish_into_inner(mut self) -> Result<B, BuildError<B::Error>> {
self.state.ensure_active()?;
self.backend
.finish_archive()
.await
.map_err(|failure| failure.error)?;
Ok(self.backend)
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum BuildError<E> {
#[error(transparent)]
Encoder(E),
#[cfg(feature = "fs")]
#[error(transparent)]
Traversal(#[from] TraversalError),
#[error("invalid archive path {path:?}: {reason}")]
InvalidArchivePath {
path: PathBuf,
reason: &'static str,
},
#[error("archive {context} rejected by builder policy: {value:?}")]
NameRejected {
context: &'static str,
value: String,
},
#[error("archive entry collides with existing path {path}")]
PathCollision {
path: String,
},
#[error("file payload was already read before being added to the archive")]
FilePayloadAlreadyRead,
#[error("failed to {operation} {path}: {source}")]
Filesystem {
operation: &'static str,
path: PathBuf,
#[source]
source: io::Error,
},
#[error("failed to read archive file payload source")]
SourceRead {
#[source]
source: io::Error,
},
#[cfg(feature = "fs")]
#[error("failed to complete blocking archive filesystem operation: {0}")]
BlockingTask(#[from] tokio::task::JoinError),
#[error("archive builder is poisoned after a previous partial write")]
Poisoned,
#[error("arithmetic overflow while computing {context}")]
ArithmeticOverflow {
context: &'static str,
},
}
#[derive(Clone, Copy, Debug)]
enum ArchivedEntry {
Directory { explicit: bool },
NonDirectory,
}
#[derive(Debug)]
struct BuildEntries(ComponentTree<Box<str>, ArchivedEntry>);
struct EntryReservation {
entry: ArchivedEntry,
}
impl BuildEntries {
fn new() -> Self {
Self(ComponentTree::new(None))
}
fn preflight_entry<E>(
&self,
path: &str,
entry: ArchivedEntry,
) -> Result<EntryReservation, BuildError<E>> {
let mut parent = ROOT_NODE;
let mut components = archive_path_components(path, entry).peekable();
while let Some((component, prefix)) = components.next() {
let Some(node) = self.0.child(parent, component) else {
return Ok(EntryReservation { entry });
};
if components.peek().is_some() {
match self.0.state(node) {
Some(ArchivedEntry::Directory { .. }) => parent = node,
Some(ArchivedEntry::NonDirectory) => return Err(path_collision(prefix)),
None => return Ok(EntryReservation { entry }),
}
} else {
match (self.0.state(node), entry) {
(
Some(ArchivedEntry::Directory { explicit: false }),
ArchivedEntry::Directory { .. },
)
| (None, _) => return Ok(EntryReservation { entry }),
(Some(_), _) => return Err(path_collision(prefix)),
}
}
}
Ok(EntryReservation { entry })
}
fn commit_entry(&mut self, path: &str, reservation: EntryReservation) {
let mut parent = ROOT_NODE;
let mut components = archive_path_components(path, reservation.entry).peekable();
while let Some((component, _)) = components.next() {
let node = self
.0
.ensure_child_with(parent, component, || component.into());
if components.peek().is_some() {
if self.0.state(node).is_none() {
self.0
.set_state(node, ArchivedEntry::Directory { explicit: false });
}
} else {
self.0.set_state(node, reservation.entry);
}
parent = node;
}
}
#[cfg(test)]
fn node_count(&self) -> usize {
self.0.node_count()
}
#[cfg(test)]
fn component_bytes(&self) -> usize {
self.0.components().map(|component| component.len()).sum()
}
}
fn archive_path_components(path: &str, entry: ArchivedEntry) -> impl Iterator<Item = (&str, &str)> {
let path = match entry {
ArchivedEntry::Directory { .. } => path.trim_end_matches('/'),
ArchivedEntry::NonDirectory => path,
};
let mut component_start = 0;
path.split('/').map(move |component| {
let prefix_end = component_start + component.len();
let prefix = &path[..prefix_end];
component_start = if prefix_end < path.len() {
prefix_end + 1
} else {
prefix_end
};
(component, prefix)
})
}
fn file_payload_read_error<E>(filesystem_path: Option<&Path>, source: io::Error) -> BuildError<E> {
if let Some(path) = filesystem_path {
BuildError::Filesystem {
operation: "read source file",
path: path.to_path_buf(),
source,
}
} else {
BuildError::SourceRead { source }
}
}
fn arithmetic_overflow<E>(context: &'static str) -> BuildError<E> {
BuildError::ArithmeticOverflow { context }
}
fn path_collision<E>(path: &str) -> BuildError<E> {
BuildError::PathCollision {
path: path.to_owned(),
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "fs")]
use std::fs;
#[cfg(feature = "fs")]
use tempfile::tempdir;
use super::*;
#[derive(Debug)]
struct TestError;
#[derive(Default)]
struct NoopArchiveBuilder {
fail_next_file: bool,
fail_next_directory: bool,
}
impl ArchiveBuilder for NoopArchiveBuilder {
type Error = TestError;
type FileOptions = EntryMetadata;
async fn finish_archive(&mut self) -> Result<(), BuildFailure<Self::Error>> {
Ok(())
}
async fn write_file_member(
&mut self,
_path: &str,
payload: &mut FilePayload<'_>,
_options: Self::FileOptions,
) -> Result<(), BuildFailure<Self::Error>> {
if mem::take(&mut self.fail_next_file) {
return Err(BuildFailure::recoverable(BuildError::Encoder(TestError)));
}
loop {
match payload.next_chunk::<TestError>().await {
Ok(Some(_)) => {}
Ok(None) => return Ok(()),
Err(error) => return Err(BuildFailure::recoverable(error)),
}
}
}
async fn write_directory_member(
&mut self,
_path: &str,
) -> Result<(), BuildFailure<Self::Error>> {
if mem::take(&mut self.fail_next_directory) {
return Err(BuildFailure::recoverable(BuildError::Encoder(TestError)));
}
Ok(())
}
async fn write_symbolic_link_member(
&mut self,
_path: &str,
_target: &str,
) -> Result<(), BuildFailure<Self::Error>> {
Ok(())
}
}
#[tokio::test]
async fn deep_manual_entry_uses_linear_component_storage() {
const COMPONENT: &str = "segment";
const DEPTH: usize = 4_096;
let mut path = format!("{COMPONENT}/").repeat(DEPTH);
path.push_str("file");
let mut builder = NoopArchiveBuilder::default().builder();
builder
.add_file(&path, b"".as_slice(), EntryMetadata::default())
.await
.expect("deep manual file should be added");
assert_eq!(builder.state.entries.node_count(), DEPTH + 2);
assert_eq!(
builder.state.entries.component_bytes(),
DEPTH * COMPONENT.len() + "file".len()
);
}
#[tokio::test]
async fn collision_state_preserves_literal_slash_components() {
let mut builder = NoopArchiveBuilder::default().builder();
for path in ["a//b", "a/b", "/absolute", "absolute", ".", ".."] {
builder
.add_file(path, b"".as_slice(), EntryMetadata::default())
.await
.expect("distinct textual path should be added");
}
for (path, collision) in [("a//b", "a//b"), ("a/", "a/"), ("", ""), ("./child", ".")] {
assert!(matches!(
builder
.add_file(
path,
b"".as_slice(),
EntryMetadata::default(),
)
.await,
Err(BuildError::PathCollision { path }) if path == collision
));
}
}
#[tokio::test]
async fn recoverable_write_failure_does_not_commit_reservation() {
let mut builder = NoopArchiveBuilder {
fail_next_file: true,
..Default::default()
}
.builder();
assert!(matches!(
builder
.add_file("parent/file", b"".as_slice(), EntryMetadata::default(),)
.await,
Err(BuildError::Encoder(TestError))
));
builder
.add_file("parent/file", b"".as_slice(), EntryMetadata::default())
.await
.expect("a recoverable failure should not reserve the path");
}
#[tokio::test]
async fn recoverable_directory_write_failure_does_not_commit_reservation() {
let mut builder = NoopArchiveBuilder {
fail_next_directory: true,
..Default::default()
}
.builder();
assert!(matches!(
builder.add_directory("directory").await,
Err(BuildError::Encoder(TestError))
));
assert_eq!(builder.state.entries.node_count(), 1);
builder
.add_directory("directory")
.await
.expect("a recoverable failure should not reserve the directory");
assert_eq!(builder.state.entries.node_count(), 2);
}
#[cfg(feature = "fs")]
#[tokio::test]
async fn repeated_directory_additions_use_linear_component_storage() {
const DIRECTORIES: usize = 256;
let temp = tempdir().expect("temporary directory should be created");
let mut builder = NoopArchiveBuilder::default().builder();
for index in 0..DIRECTORIES {
let source = temp.path().join(format!("directory-{index}"));
fs::create_dir(&source).expect("source directory should be created");
builder
.add_directory_all(&source)
.await
.expect("empty source directory should be added");
}
assert_eq!(builder.state.entries.node_count(), DIRECTORIES + 1);
}
}