use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io::SeekFrom;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use async_compression::Level;
use async_compression::futures::write::XzEncoder;
use futures_lite::AsyncWriteExt;
use ostrya_core::{
Checksum, ObjectType, Type, Value, Xattrs, choose_offset_size, from_bytes, to_bytes, varint,
write_offset,
};
use ostrya_rt::File as RtFile;
use sha2::{Digest, Sha256};
use crate::commit::append_dict_entry;
use crate::delta::{
Blob, COMMIT_SIG, COMPRESSION_XZ, DeltaEndianness, ENDIANNESS_BIG, ENDIANNESS_KEY,
ENDIANNESS_LITTLE, IO_CHUNK, MAX_SUPERBLOCK, MAX_TABLE_BYTES, MMAP_THRESHOLD, OP_BSPATCH,
OP_CLOSE, OP_OPEN, OP_OPEN_SPLICE_CLOSE, OP_SET_READ_SOURCE, OP_UNSET_READ_SOURCE, OP_WRITE,
SIGNED_MAGIC, SIGNED_SIG, SUPERBLOCK_SIG, dir_child_names, open_rw_temp, read_capped,
spill_to_blob,
};
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject};
use crate::hashing::HashingWriter;
use crate::repo::Repo;
use crate::rollsum::{self, Run};
use crate::sign::{Signer, append_signature};
const PART_VERSION: u32 = 0;
const PART_XZ_LEVEL: i32 = 8;
const BSDIFF_CONTENT_LIMIT: u64 = rollsum::MAX_CHUNK as u64;
pub(crate) const SUPERBLOCK_FILE: &str = "superblock";
const DELTAS_DIR: &str = "deltas";
const DELTA_INDEXES_DIR: &str = "delta-indexes";
const INDEX_SUFFIX: &str = ".index";
pub(crate) const STATIC_DELTAS_KEY: &str = "ostree.static-deltas";
const DELTA_FILE_MODE: u32 = 0o644;
const DELTA_DIR_MODE: u32 = 0o755;
#[derive(Clone)]
pub struct DeltaOptions {
pub min_fallback_size: u64,
pub max_bsdiff_size: u64,
pub max_chunk_size: u64,
pub bsdiff: bool,
pub timestamp: Option<u64>,
pub output_dir: Option<PathBuf>,
pub superblock_file: Option<PathBuf>,
pub signers: Vec<Arc<dyn Signer>>,
pub inline: bool,
pub endianness: DeltaEndianness,
}
impl std::fmt::Debug for DeltaOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let signers: Vec<&str> = self.signers.iter().map(|signer| signer.name()).collect();
f.debug_struct("DeltaOptions")
.field("min_fallback_size", &self.min_fallback_size)
.field("max_bsdiff_size", &self.max_bsdiff_size)
.field("max_chunk_size", &self.max_chunk_size)
.field("bsdiff", &self.bsdiff)
.field("timestamp", &self.timestamp)
.field("output_dir", &self.output_dir)
.field("superblock_file", &self.superblock_file)
.field("signers", &signers)
.field("inline", &self.inline)
.field("endianness", &self.endianness)
.finish()
}
}
impl Default for DeltaOptions {
fn default() -> Self {
DeltaOptions {
min_fallback_size: 4_000_000,
max_bsdiff_size: 64_000_000,
max_chunk_size: 32_000_000,
bsdiff: true,
timestamp: None,
output_dir: None,
superblock_file: None,
signers: Vec::new(),
inline: false,
endianness: DeltaEndianness::Little,
}
}
}
impl Repo {
pub async fn generate_static_delta(
&self,
from: Option<&Checksum>,
to: &Checksum,
opts: &DeltaOptions,
) -> Result<PathBuf> {
self.generate_static_delta_under(from, to, opts, MAX_SUPERBLOCK)
.await
}
async fn generate_static_delta_under(
&self,
from: Option<&Checksum>,
to: &Checksum,
opts: &DeltaOptions,
ceiling: u64,
) -> Result<PathBuf> {
if opts.max_chunk_size == 0 {
return Err(Error::InvalidFormat(
"static delta max chunk size must be positive".to_owned(),
));
}
if opts.output_dir.is_some() && opts.superblock_file.is_some() {
return Err(Error::InvalidFormat(
"static delta output_dir and superblock_file cannot both be set".to_owned(),
));
}
let commit_bytes = self.load_object_bytes(ObjectType::Commit, to).await?;
let detached = self.read_commit_detached_metadata(to).await?;
let commit = Target {
bytes: &commit_bytes,
detached: detached.as_ref(),
};
if let Some(from) = from
&& !self.has_object(ObjectType::Commit, from).await?
{
return Err(Error::ObjectNotFound {
checksum: *from,
ty: ObjectType::Commit,
});
}
let superblock_target = match &opts.superblock_file {
Some(file) => {
let target = file.clone();
let (fd, name) =
ostrya_rt::unblock(move || open_superblock_parent_blocking(&target)).await?;
Some((file.clone(), fd, name))
}
None => None,
};
let selection = self.select_objects(from, to, opts).await?;
let (dir_path, dir_fd, superblock_name) = match superblock_target {
Some(target) => target,
None => {
let (path, fd) = self.open_delta_dir(from, to, opts).await?;
(path, fd, SUPERBLOCK_FILE.to_owned())
}
};
let tmp_fd = self.open_tmp_dir().await?;
let fsync = self.config().fsync()?;
if opts.superblock_file.is_none() && !opts.inline {
remove_superblock(&dir_fd).await?;
}
let mut target = if opts.inline {
let fixed = commit_bytes
.len()
.saturating_add(selection.packed.len().saturating_mul(1 + 32))
.saturating_add(selection.fallbacks.len().saturating_mul(1 + 32 + 8 + 8));
PartTarget::Inline {
budget: usize::try_from(ceiling)
.unwrap_or(usize::MAX)
.saturating_sub(fixed),
}
} else {
PartTarget::File(&dir_fd)
};
let mut entries: Vec<PartEntry> = Vec::new();
let mut part = Part::default();
for item in &selection.packed {
if !part.is_empty() && part.payload_len() + item.content_size > opts.max_chunk_size {
entries.push(write_part(&mut target, entries.len(), part, fsync).await?);
part = Part::default();
}
self.add_object(&mut part, item, opts, tmp_fd.as_fd())
.await?;
}
if !part.is_empty() {
entries.push(write_part(&mut target, entries.len(), part, fsync).await?);
}
let part_files = if opts.inline { 0 } else { entries.len() };
let mut superblock =
self.build_superblock(from, to, &commit, &mut entries, &selection, opts)?;
drop(entries);
if !opts.signers.is_empty() {
let signers: Vec<&dyn Signer> = opts.signers.iter().map(|s| s.as_ref()).collect();
superblock = sign_superblock(superblock, Value::Array(Vec::new()), &signers).await?;
}
write_delta_file(&dir_fd, &superblock_name, &superblock, fsync).await?;
if opts.output_dir.is_none() && opts.superblock_file.is_none() {
clean_delta_dir(&dir_fd, part_files).await?;
}
Ok(dir_path)
}
pub async fn sign_static_delta(&self, dir: &Path, signer: &dyn Signer) -> Result<()> {
let bytes = read_capped(dir.join(SUPERBLOCK_FILE)).await?;
let (payload, signatures) = split_envelope(bytes)?;
let encoded = sign_superblock(payload, signatures, &[signer]).await?;
let dir_fd = open_dir_path(dir).await?;
let fsync = self.config().fsync()?;
write_delta_file(&dir_fd, SUPERBLOCK_FILE, &encoded, fsync).await
}
pub async fn reindex_static_deltas(&self) -> Result<()> {
let mut by_target: BTreeMap<Checksum, BTreeMap<String, Checksum>> = BTreeMap::new();
for entry in self.static_delta_digests().await? {
by_target
.entry(entry.to)
.or_default()
.insert(entry.name, entry.digest);
}
let fsync = self.config().fsync()?;
let mut written: BTreeSet<String> = BTreeSet::new();
for (to, deltas) in &by_target {
self.write_delta_index(to, deltas, fsync).await?;
let (fanout, name) = delta_index_parts(to);
written.insert(format!("{fanout}/{name}"));
}
self.prune_delta_indexes(written).await
}
pub async fn reindex_static_deltas_to(&self, to: &Checksum) -> Result<()> {
let deltas: BTreeMap<String, Checksum> = self
.static_delta_digests_of(Some(to))
.await?
.into_iter()
.map(|entry| (entry.name, entry.digest))
.collect();
if deltas.is_empty() {
let repo = self.clone();
let relative = delta_index_relative_path(to);
return ostrya_rt::unblock(move || {
remove_delta_index_blocking(repo.repo_fd(), &relative)
})
.await;
}
let fsync = self.config().fsync()?;
self.write_delta_index(to, &deltas, fsync).await
}
async fn write_delta_index(
&self,
to: &Checksum,
deltas: &BTreeMap<String, Checksum>,
fsync: bool,
) -> Result<()> {
let (fanout, name) = delta_index_parts(to);
let dir_fd = self
.open_repo_subdir(&format!("{DELTA_INDEXES_DIR}/{fanout}"))
.await?;
let index = index_value(deltas)?;
write_delta_file(&dir_fd, &name, &index, fsync).await
}
pub(crate) async fn static_delta_digests(&self) -> Result<Vec<DeltaDigest>> {
self.static_delta_digests_of(None).await
}
async fn static_delta_digests_of(&self, to: Option<&Checksum>) -> Result<Vec<DeltaDigest>> {
let mut out = Vec::new();
for (from, target) in self.list_static_delta_targets().await? {
if to.is_some_and(|to| *to != target) {
continue;
}
let relative = format!(
"{}/{SUPERBLOCK_FILE}",
delta_relative_dir(from.as_ref(), &target)
);
let Some(bytes) = self.read_repo_file(&relative).await? else {
continue;
};
out.push(DeltaDigest {
name: delta_name(from.as_ref(), &target),
to: target,
digest: Checksum::sha256(&bytes),
});
}
out.sort_by(|a, b| a.name.cmp(&b.name));
Ok(out)
}
pub(crate) async fn static_deltas_summary_value(&self) -> Result<Option<Value>> {
let entries = self.static_delta_digests().await?;
if entries.is_empty() {
return Ok(None);
}
let map = delta_map_value(
entries
.iter()
.map(|entry| (entry.name.as_str(), &entry.digest)),
)?;
let map_ty = Type::parse("a{sv}").map_err(ostrya_core::Error::from)?;
Ok(Some(Value::variant(map_ty, map)))
}
pub async fn list_static_delta_indexes(&self) -> Result<Vec<Checksum>> {
let repo = self.clone();
ostrya_rt::unblock(move || list_delta_indexes_blocking(repo.repo_fd())).await
}
async fn prune_delta_indexes(&self, written: BTreeSet<String>) -> Result<()> {
let repo = self.clone();
ostrya_rt::unblock(move || prune_delta_indexes_blocking(repo.repo_fd(), &written)).await
}
async fn select_objects(
&self,
from: Option<&Checksum>,
to: &Checksum,
opts: &DeltaOptions,
) -> Result<Selection> {
let mut needed = self.traverse_commit(to, 0).await?;
if let Some(from) = from {
for name in self.traverse_commit(from, 0).await? {
needed.remove(&name);
}
}
let mut metadata: Vec<(ObjectType, Checksum)> = Vec::new();
let mut content: Vec<Checksum> = Vec::new();
for name in needed {
match name.ty {
ObjectType::Commit => {}
ty if ty.is_meta() => metadata.push((ty, name.checksum)),
_ => content.push(name.checksum),
}
}
metadata.sort_by_key(|(ty, checksum)| (ty.as_u32(), *checksum));
content.sort();
let sources = match from {
Some(from) => self.pair_by_path(from, to).await?,
None => HashMap::new(),
};
let mut selection = Selection::default();
for (ty, checksum) in metadata {
selection.packed.push(PackItem {
objtype: ty,
checksum,
content_size: self.loose_object_size(ty, &checksum).await?,
source: None,
file: None,
});
}
for checksum in content {
let file = self.load_file(&checksum).await?;
let content_size = content_size(&file);
if opts.min_fallback_size != 0 && stream_size(&file)? >= opts.min_fallback_size {
selection.fallbacks.push(FallbackItem {
checksum,
compressed_size: self.loose_object_size(ObjectType::File, &checksum).await?,
content_size,
});
continue;
}
let source = match sources.get(&checksum) {
Some(source) if self.has_object(ObjectType::File, source).await? => Some(*source),
_ => None,
};
selection.packed.push(PackItem {
objtype: ObjectType::File,
checksum,
content_size,
source,
file: Some(file),
});
}
Ok(selection)
}
async fn pair_by_path(
&self,
from: &Checksum,
to: &Checksum,
) -> Result<HashMap<Checksum, Checksum>> {
let old = self.file_paths(from).await?;
let mut sources = HashMap::new();
for (path, new_checksum) in self.file_paths(to).await? {
if let Some(&old_checksum) = old.get(&path)
&& old_checksum != new_checksum
{
sources.entry(new_checksum).or_insert(old_checksum);
}
}
Ok(sources)
}
async fn file_paths(&self, commit: &Checksum) -> Result<BTreeMap<String, Checksum>> {
let (commit, _) = self.load_commit(commit).await?;
let mut paths = BTreeMap::new();
let mut stack = vec![(String::new(), commit.root_dirtree)];
while let Some((prefix, dirtree)) = stack.pop() {
let dirtree = self.load_dirtree(&dirtree).await?;
for (name, checksum) in dirtree.files {
paths.insert(format!("{prefix}/{name}"), checksum);
}
for (name, subtree, _) in dirtree.dirs {
stack.push((format!("{prefix}/{name}"), subtree));
}
}
Ok(paths)
}
async fn add_object(
&self,
part: &mut Part,
item: &PackItem,
opts: &DeltaOptions,
tmp: BorrowedFd<'_>,
) -> Result<()> {
let Some(file) = &item.file else {
let bytes = self.load_object_bytes(item.objtype, &item.checksum).await?;
let offset = part.blob.append(&bytes, tmp).await?;
part.push_op(OP_OPEN_SPLICE_CLOSE, &[bytes.len() as u64, offset]);
part.finish_object(item.objtype, item.checksum, bytes.len() as u64);
return Ok(());
};
let mode_index = part.mode_index(file.uid, file.gid, file.mode);
let xattr_index = part.xattr_index(&file.xattrs);
if let FileKind::Symlink { target } = &file.kind {
let offset = part.blob.append(target.as_bytes(), tmp).await?;
part.push_op(
OP_OPEN_SPLICE_CLOSE,
&[mode_index, xattr_index, target.len() as u64, offset],
);
part.finish_object(item.objtype, item.checksum, target.len() as u64);
return Ok(());
}
let Some(source) = item.source else {
let reader = file.reader().await?;
let (offset, len) = part.blob.append_reader(reader, tmp).await?;
part.push_op(
OP_OPEN_SPLICE_CLOSE,
&[mode_index, xattr_index, len, offset],
);
part.finish_object(item.objtype, item.checksum, len);
return Ok(());
};
let target_blob = self.load_content_blob(file, tmp).await?;
let source_blob = self
.load_content_blob(&self.load_file(&source).await?, tmp)
.await?;
let (plan, source_blob, target_blob) = ostrya_rt::unblock(move || {
let plan = rollsum::plan(source_blob.as_slice(), target_blob.as_slice());
(plan, source_blob, target_blob)
})
.await;
let output_size = target_blob.as_slice().len() as u64;
if plan.copied > 0 {
part.push_op(OP_OPEN, &[mode_index, xattr_index, output_size]);
let source_offset = part.blob.append(source.as_bytes(), tmp).await?;
for run in &plan.runs {
match *run {
Run::Copy {
source_offset: from,
length,
} => {
part.push_op(OP_SET_READ_SOURCE, &[source_offset]);
part.push_op(OP_WRITE, &[length, from]);
part.push_op(OP_UNSET_READ_SOURCE, &[]);
}
Run::Payload {
target_offset,
length,
} => {
let start = target_offset as usize;
let end = start + length as usize;
let offset = part
.blob
.append(&target_blob.as_slice()[start..end], tmp)
.await?;
part.push_op(OP_WRITE, &[length, offset]);
}
}
}
part.push_op(OP_CLOSE, &[]);
part.finish_object(item.objtype, item.checksum, output_size);
return Ok(());
}
let mut target_blob = target_blob;
let limit = BSDIFF_CONTENT_LIMIT.min(opts.max_bsdiff_size);
let source_size = source_blob.as_slice().len() as u64;
if opts.bsdiff && output_size <= limit && source_size <= limit {
let (stream, returned) = bsdiff_stream(source_blob, target_blob).await?;
target_blob = returned;
if patch_beats_splicing(&stream, output_size) {
part.push_op(OP_OPEN, &[mode_index, xattr_index, output_size]);
let source_offset = part.blob.append(source.as_bytes(), tmp).await?;
let stream_offset = part.blob.append(&stream, tmp).await?;
part.push_op(OP_SET_READ_SOURCE, &[source_offset]);
part.push_op(OP_BSPATCH, &[stream_offset, stream.len() as u64]);
part.push_op(OP_UNSET_READ_SOURCE, &[]);
part.push_op(OP_CLOSE, &[]);
part.finish_object(item.objtype, item.checksum, output_size);
return Ok(());
}
}
let offset = part.blob.append(target_blob.as_slice(), tmp).await?;
part.push_op(
OP_OPEN_SPLICE_CLOSE,
&[mode_index, xattr_index, output_size, offset],
);
part.finish_object(item.objtype, item.checksum, output_size);
Ok(())
}
async fn load_content_blob(&self, file: &FileObject, tmp: BorrowedFd<'_>) -> Result<Blob> {
let reader = file.reader().await?;
let owned = tmp.try_clone_to_owned()?;
spill_to_blob(reader, &owned, None).await
}
fn build_superblock(
&self,
from: Option<&Checksum>,
to: &Checksum,
target: &Target<'_>,
entries: &mut [PartEntry],
selection: &Selection,
opts: &DeltaOptions,
) -> Result<Vec<u8>> {
let (byte, big_endian) = match opts.endianness {
DeltaEndianness::Little => (ENDIANNESS_LITTLE, false),
DeltaEndianness::Big => (ENDIANNESS_BIG, true),
};
let host = |value: u64| {
if big_endian {
value.swap_bytes()
} else {
value
}
};
let mut metadata = Value::Array(Vec::new());
crate::commit::append_dict_entry(
&mut metadata,
ENDIANNESS_KEY,
Value::variant(
Type::parse("y").map_err(ostrya_core::Error::from)?,
Value::Byte(byte),
),
)?;
let inline_ty = Type::parse("(yay)").map_err(ostrya_core::Error::from)?;
for (index, entry) in entries.iter_mut().enumerate() {
let Some((compression, body)) = entry.inline.take() else {
continue;
};
crate::commit::append_dict_entry(
&mut metadata,
&format!("{}/{index}", delta_relative_dir(from, to)),
Value::variant(
inline_ty.clone(),
Value::Tuple(vec![Value::Byte(compression), Value::Bytes(body)]),
),
)?;
}
if let Some(detached) = target.detached {
crate::commit::append_dict_entry(
&mut metadata,
&format!("{}/commitmeta", delta_relative_dir(from, to)),
Value::variant(
Type::parse("a{sv}").map_err(ostrya_core::Error::from)?,
detached.clone(),
),
)?;
}
let commit_ty = Type::parse(COMMIT_SIG).map_err(ostrya_core::Error::from)?;
let commit = from_bytes(&commit_ty, target.bytes).map_err(ostrya_core::Error::from)?;
let meta_entries = entries
.iter()
.map(|entry| {
Value::Tuple(vec![
Value::U32(PART_VERSION),
Value::Bytes(entry.checksum.as_bytes().to_vec()),
Value::U64(host(entry.size)),
Value::U64(host(entry.uncompressed_size)),
Value::Bytes(object_array(&entry.objects)),
])
})
.collect();
let fallbacks = selection
.fallbacks
.iter()
.map(|fallback| {
Value::Tuple(vec![
Value::Byte(ObjectType::File.as_u32() as u8),
Value::Bytes(fallback.checksum.as_bytes().to_vec()),
Value::U64(host(fallback.compressed_size)),
Value::U64(host(fallback.content_size)),
])
})
.collect();
let superblock = Value::Tuple(vec![
metadata,
Value::U64(resolve_timestamp(opts.timestamp)?.swap_bytes()),
Value::Bytes(from.map_or_else(Vec::new, |from| from.as_bytes().to_vec())),
Value::Bytes(to.as_bytes().to_vec()),
commit,
Value::Bytes(Vec::new()),
Value::Array(meta_entries),
Value::Array(fallbacks),
]);
let ty = Type::parse(SUPERBLOCK_SIG).map_err(ostrya_core::Error::from)?;
let bytes = to_bytes(&ty, &superblock).map_err(ostrya_core::Error::from)?;
check_superblock_size(bytes.len())?;
Ok(bytes)
}
async fn list_static_delta_targets(&self) -> Result<Vec<(Option<Checksum>, Checksum)>> {
let repo = self.clone();
ostrya_rt::unblock(move || crate::delta::list_delta_targets(repo.repo_fd())).await
}
async fn read_repo_file(&self, relative: &str) -> Result<Option<Vec<u8>>> {
use std::io::Read;
let repo = self.clone();
let relative = relative.to_owned();
ostrya_rt::unblock(move || {
let fd = match rustix::fs::openat(
repo.repo_fd(),
relative.as_str(),
rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
) {
Ok(fd) => fd,
Err(rustix::io::Errno::NOENT) => return Ok(None),
Err(e) => return Err(Error::Io(e.into())),
};
let mut file = std::fs::File::from(fd);
if file.metadata().map_err(Error::Io)?.len() > MAX_SUPERBLOCK {
return Err(Error::Io(std::io::Error::other(format!(
"static delta file {relative} exceeds the size ceiling"
))));
}
let mut bytes = Vec::new();
file.read_to_end(&mut bytes).map_err(Error::Io)?;
Ok(Some(bytes))
})
.await
}
async fn open_repo_subdir(&self, relative: &str) -> Result<OwnedFd> {
let repo = self.clone();
let relative = relative.to_owned();
ostrya_rt::unblock(move || open_subdir_blocking(repo.repo_fd(), &relative)).await
}
pub(crate) async fn open_tmp_dir(&self) -> Result<OwnedFd> {
self.open_repo_subdir("tmp").await
}
async fn open_delta_dir(
&self,
from: Option<&Checksum>,
to: &Checksum,
opts: &DeltaOptions,
) -> Result<(PathBuf, OwnedFd)> {
match &opts.output_dir {
Some(dir) => {
let path = dir.clone();
let target = path.clone();
let fd = ostrya_rt::unblock(move || create_dir_path_blocking(&target)).await?;
Ok((path, fd))
}
None => {
let relative = delta_relative_dir(from, to);
let fd = self.open_repo_subdir(&relative).await?;
Ok((PathBuf::from(relative), fd))
}
}
}
}
struct Target<'a> {
bytes: &'a [u8],
detached: Option<&'a Value>,
}
#[derive(Default)]
struct Selection {
packed: Vec<PackItem>,
fallbacks: Vec<FallbackItem>,
}
struct PackItem {
objtype: ObjectType,
checksum: Checksum,
content_size: u64,
source: Option<Checksum>,
file: Option<FileObject>,
}
struct FallbackItem {
checksum: Checksum,
compressed_size: u64,
content_size: u64,
}
struct PartEntry {
checksum: Checksum,
size: u64,
uncompressed_size: u64,
objects: Vec<(ObjectType, Checksum)>,
inline: Option<(u8, Vec<u8>)>,
}
enum PartTarget<'a> {
File(&'a OwnedFd),
Inline { budget: usize },
}
#[derive(Default)]
struct Part {
modes: Vec<(u32, u32, u32)>,
mode_slots: HashMap<(u32, u32, u32), u64>,
xattrs: Vec<Xattrs>,
xattr_slots: HashMap<Xattrs, u64>,
blob: Spill,
ops: Vec<u8>,
objects: Vec<(ObjectType, Checksum)>,
uncompressed_size: u64,
}
impl Part {
fn is_empty(&self) -> bool {
self.objects.is_empty()
}
fn payload_len(&self) -> u64 {
self.blob.len() + self.ops.len() as u64
}
fn push_op(&mut self, opcode: u8, operands: &[u64]) {
self.ops.push(opcode);
for &operand in operands {
varint::encode(operand, &mut self.ops);
}
}
fn finish_object(&mut self, objtype: ObjectType, checksum: Checksum, payload: u64) {
self.objects.push((objtype, checksum));
self.uncompressed_size += payload;
}
fn mode_index(&mut self, uid: u32, gid: u32, mode: u32) -> u64 {
let triple = (uid, gid, mode);
if let Some(&index) = self.mode_slots.get(&triple) {
return index;
}
let index = self.modes.len() as u64;
self.modes.push(triple);
self.mode_slots.insert(triple, index);
index
}
fn xattr_index(&mut self, xattrs: &Xattrs) -> u64 {
if let Some(&index) = self.xattr_slots.get(xattrs) {
return index;
}
let index = self.xattrs.len() as u64;
self.xattrs.push(xattrs.clone());
self.xattr_slots.insert(xattrs.clone(), index);
index
}
}
enum Spill {
Ram(Vec<u8>),
File { file: RtFile, len: u64 },
}
impl Default for Spill {
fn default() -> Self {
Spill::Ram(Vec::new())
}
}
impl Spill {
fn len(&self) -> u64 {
match self {
Spill::Ram(buf) => buf.len() as u64,
Spill::File { len, .. } => *len,
}
}
async fn append(&mut self, bytes: &[u8], tmp: BorrowedFd<'_>) -> Result<u64> {
let offset = self.len();
if let Spill::Ram(buf) = self
&& buf.len() + bytes.len() > MMAP_THRESHOLD
{
self.spill(tmp).await?;
}
match self {
Spill::Ram(buf) => buf.extend_from_slice(bytes),
Spill::File { file, len } => {
file.write_all(bytes).await.map_err(Error::Io)?;
*len += bytes.len() as u64;
}
}
Ok(offset)
}
async fn append_reader<R: futures_io::AsyncRead + Unpin>(
&mut self,
mut reader: R,
tmp: BorrowedFd<'_>,
) -> Result<(u64, u64)> {
use futures_lite::AsyncReadExt;
let offset = self.len();
let mut chunk = vec![0u8; IO_CHUNK];
let mut total = 0u64;
loop {
let n = reader.read(&mut chunk).await.map_err(Error::Io)?;
if n == 0 {
break;
}
self.append(&chunk[..n], tmp).await?;
total += n as u64;
}
Ok((offset, total))
}
async fn spill(&mut self, tmp: BorrowedFd<'_>) -> Result<()> {
let Spill::Ram(buf) = self else {
return Ok(());
};
let owned = tmp.try_clone_to_owned()?;
let fd = ostrya_rt::unblock(move || open_rw_temp(owned.as_fd())).await?;
let mut file = RtFile::from(fd);
file.write_all(buf).await.map_err(Error::Io)?;
let len = buf.len() as u64;
*self = Spill::File { file, len };
Ok(())
}
async fn into_blocking(self) -> Result<BlockingSpill> {
match self {
Spill::Ram(buf) => Ok(BlockingSpill::Ram(buf)),
Spill::File { mut file, len } => {
file.flush().await.map_err(Error::Io)?;
let mut file = file.into_std().await;
std::io::Seek::seek(&mut file, SeekFrom::Start(0)).map_err(Error::Io)?;
Ok(BlockingSpill::File { file, len })
}
}
}
}
enum BlockingSpill {
Ram(Vec<u8>),
File { file: std::fs::File, len: u64 },
}
impl BlockingSpill {
async fn write_into<W: futures_io::AsyncWrite + Unpin>(self, out: &mut W) -> Result<()> {
match self {
BlockingSpill::Ram(buf) => out.write_all(&buf).await.map_err(Error::Io),
BlockingSpill::File { mut file, len } => {
let mut chunk = vec![0u8; IO_CHUNK];
let mut streamed = 0u64;
loop {
let n = match std::io::Read::read(&mut file, &mut chunk) {
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
result => result.map_err(Error::Io)?,
};
if n == 0 {
break;
}
out.write_all(&chunk[..n]).await.map_err(Error::Io)?;
streamed += n as u64;
}
if streamed != len {
return Err(Error::InvalidFormat(format!(
"static delta part data source holds {streamed} bytes, not the \
{len} its framing counts"
)));
}
Ok(())
}
}
}
}
async fn write_part(
target: &mut PartTarget<'_>,
index: usize,
part: Part,
fsync: bool,
) -> Result<PartEntry> {
let modes = mode_table(&part.modes);
let xattrs = xattr_table(&part.xattrs)?;
check_table_size(modes.len() + xattrs.len())?;
let blob_len = part.blob.len();
let ops_len = part.ops.len() as u64;
let body = modes.len() as u64 + xattrs.len() as u64 + blob_len + ops_len;
let body =
usize::try_from(body).map_err(|_| Error::InvalidFormat("part payload too large".into()))?;
let width = choose_offset_size(body, 3);
let mut offsets = Vec::with_capacity(3 * width);
write_offset(
&mut offsets,
modes.len() + xattrs.len() + blob_len as usize,
width,
);
write_offset(&mut offsets, modes.len() + xattrs.len(), width);
write_offset(&mut offsets, modes.len(), width);
let dir_fd = match target {
PartTarget::File(dir_fd) => *dir_fd,
PartTarget::Inline { budget } => {
let limit = *budget;
let blob = part.blob.into_blocking().await?;
let ops = part.ops;
let (checksum, size, inline) = ostrya_rt::unblock(move || {
let mut capped = CappedBuf::new(limit);
match compress_part(&mut capped, &modes, &xattrs, blob, &ops, &offsets) {
Ok((checksum, size)) => Ok((checksum, size, capped.into_parts())),
Err(_) if capped.len() == limit => Err(inline_ceiling_error()),
Err(err) => Err(err),
}
})
.await?;
*budget -= 1 + inline.1.len();
return Ok(PartEntry {
checksum,
size,
uncompressed_size: part.uncompressed_size,
objects: part.objects,
inline: Some(inline),
});
}
};
let name = index.to_string();
let temp = TempFile::create(dir_fd, &name);
let fd = {
let owned = dir_fd.try_clone()?;
let temp = temp.name().to_owned();
ostrya_rt::unblock(move || create_file_blocking(owned.as_fd(), &temp)).await?
};
let blob = part.blob.into_blocking().await?;
let ops = part.ops;
let (checksum, size) = ostrya_rt::unblock(move || {
let file = std::fs::File::from(fd);
compress_part(file, &modes, &xattrs, blob, &ops, &offsets)
})
.await?;
finish_file(dir_fd, temp.name(), &name, fsync).await?;
temp.keep();
Ok(PartEntry {
checksum,
size,
uncompressed_size: part.uncompressed_size,
objects: part.objects,
inline: None,
})
}
struct CappedBuf {
compression: Option<u8>,
body: Vec<u8>,
limit: usize,
}
impl CappedBuf {
fn new(limit: usize) -> CappedBuf {
CappedBuf {
compression: None,
body: Vec::new(),
limit,
}
}
fn len(&self) -> usize {
usize::from(self.compression.is_some()) + self.body.len()
}
fn into_parts(self) -> (u8, Vec<u8>) {
(self.compression.unwrap_or(0), self.body)
}
}
impl std::io::Write for CappedBuf {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
let room = self.limit - self.len();
if room == 0 && !bytes.is_empty() {
return Err(std::io::Error::other(
"static delta inline part passes the superblock ceiling",
));
}
let n = bytes.len().min(room);
let mut taken = &bytes[..n];
if self.compression.is_none()
&& let Some((&first, rest)) = taken.split_first()
{
self.compression = Some(first);
taken = rest;
}
self.body.extend_from_slice(taken);
Ok(n)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn inline_ceiling_error() -> Error {
Error::InvalidFormat(format!(
"static delta inline parts pass the {MAX_SUPERBLOCK}-byte superblock ceiling"
))
}
fn compress_part<W: std::io::Write + Unpin>(
out: W,
modes: &[u8],
xattrs: &[u8],
blob: BlockingSpill,
ops: &[u8],
offsets: &[u8],
) -> Result<(Checksum, u64)> {
let mut hashing = HashingWriter::new(Sha256::new(), SyncWriter(out));
futures_lite::future::block_on(async {
hashing
.write_all(&[COMPRESSION_XZ])
.await
.map_err(Error::Io)?;
let mut encoder = XzEncoder::with_quality(&mut hashing, Level::Precise(PART_XZ_LEVEL));
encoder.write_all(modes).await.map_err(Error::Io)?;
encoder.write_all(xattrs).await.map_err(Error::Io)?;
blob.write_into(&mut encoder).await?;
encoder.write_all(ops).await.map_err(Error::Io)?;
encoder.write_all(offsets).await.map_err(Error::Io)?;
encoder.close().await.map_err(Error::Io)?;
drop(encoder);
hashing.flush().await.map_err(Error::Io)
})?;
Ok(hashing.finalize())
}
struct SyncWriter<W>(W);
impl<W: std::io::Write + Unpin> futures_io::AsyncWrite for SyncWriter<W> {
fn poll_write(
self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
let file = &mut self.get_mut().0;
loop {
match std::io::Write::write(file, buf) {
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
result => return Poll::Ready(result),
}
}
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Poll::Ready(std::io::Write::flush(&mut self.get_mut().0))
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
self.poll_flush(cx)
}
}
fn mode_table(modes: &[(u32, u32, u32)]) -> Vec<u8> {
let mut out = Vec::with_capacity(modes.len() * 12);
for &(uid, gid, mode) in modes {
out.extend_from_slice(&uid.to_be_bytes());
out.extend_from_slice(&gid.to_be_bytes());
out.extend_from_slice(&mode.to_be_bytes());
}
out
}
fn xattr_table(xattrs: &[Xattrs]) -> Result<Vec<u8>> {
let entries = xattrs
.iter()
.map(|set| {
Value::Array(
set.iter()
.map(|(name, value)| {
Value::Tuple(vec![
Value::Bytes(name.to_vec()),
Value::Bytes(value.to_vec()),
])
})
.collect(),
)
})
.collect();
let ty = Type::parse("aa(ayay)").map_err(ostrya_core::Error::from)?;
Ok(to_bytes(&ty, &Value::Array(entries)).map_err(ostrya_core::Error::from)?)
}
fn object_array(objects: &[(ObjectType, Checksum)]) -> Vec<u8> {
let mut out = Vec::with_capacity(objects.len() * 33);
for (objtype, checksum) in objects {
out.push(objtype.as_u32() as u8);
out.extend_from_slice(checksum.as_bytes());
}
out
}
async fn bsdiff_stream(source: Blob, target: Blob) -> Result<(Vec<u8>, Blob)> {
ostrya_rt::unblock(move || {
let mut stream = Vec::new();
bsdiff::diff(source.as_slice(), target.as_slice(), &mut stream).map_err(Error::Io)?;
Ok((stream, target))
})
.await
}
fn novel_bytes(stream: &[u8]) -> u64 {
stream.iter().filter(|&&byte| byte != 0).count() as u64
}
fn patch_beats_splicing(stream: &[u8], output_size: u64) -> bool {
novel_bytes(stream) * 2 < output_size
}
const FALLBACK_FRAMING: u64 = 7;
fn stream_size(file: &FileObject) -> Result<u64> {
let header = file.header();
Ok(FALLBACK_FRAMING + header.serialize()?.len() as u64 + content_size(file))
}
fn content_size(file: &FileObject) -> u64 {
match &file.kind {
FileKind::Regular { size } => *size,
FileKind::Symlink { target } => target.len() as u64,
}
}
fn split_envelope(bytes: Vec<u8>) -> Result<(Vec<u8>, Value)> {
if !bytes.starts_with(SIGNED_MAGIC) {
return Ok((bytes, Value::Array(Vec::new())));
}
let ty = Type::parse(SIGNED_SIG).map_err(ostrya_core::Error::from)?;
let value = from_bytes(&ty, &bytes).map_err(ostrya_core::Error::from)?;
let fields = crate::delta::tuple(&value)?;
let payload = crate::delta::bytes_field(&fields[1], "signed superblock payload")?.to_vec();
Ok((payload, fields[2].clone()))
}
async fn sign_superblock(
payload: Vec<u8>,
mut signatures: Value,
signers: &[&dyn Signer],
) -> Result<Vec<u8>> {
for signer in signers {
let signature = signer.sign(&payload).await?;
append_signature(&mut signatures, signer.metadata_key(), signature)?;
}
let envelope = Value::Tuple(vec![
Value::U64(u64::from_le_bytes(*SIGNED_MAGIC)),
Value::Bytes(payload),
signatures,
]);
let ty = Type::parse(SIGNED_SIG).map_err(ostrya_core::Error::from)?;
let encoded = to_bytes(&ty, &envelope).map_err(ostrya_core::Error::from)?;
check_superblock_size(encoded.len())?;
Ok(encoded)
}
pub(crate) struct DeltaDigest {
pub(crate) name: String,
pub(crate) to: Checksum,
pub(crate) digest: Checksum,
}
fn delta_map_value<'a>(deltas: impl Iterator<Item = (&'a str, &'a Checksum)>) -> Result<Value> {
let ay = Type::parse("ay").map_err(ostrya_core::Error::from)?;
let mut map = Value::Array(Vec::new());
for (name, digest) in deltas {
append_dict_entry(
&mut map,
name,
Value::variant(ay.clone(), Value::Bytes(digest.as_bytes().to_vec())),
)?;
}
Ok(map)
}
fn index_value(deltas: &BTreeMap<String, Checksum>) -> Result<Vec<u8>> {
let map = delta_map_value(deltas.iter().map(|(name, digest)| (name.as_str(), digest)))?;
let mut dict = Value::Array(Vec::new());
let map_ty = Type::parse("a{sv}").map_err(ostrya_core::Error::from)?;
append_dict_entry(
&mut dict,
STATIC_DELTAS_KEY,
Value::variant(map_ty.clone(), map),
)?;
Ok(to_bytes(&map_ty, &dict).map_err(ostrya_core::Error::from)?)
}
pub(crate) fn delta_name(from: Option<&Checksum>, to: &Checksum) -> String {
match from {
Some(from) => format!("{}-{}", from.to_hex(), to.to_hex()),
None => to.to_hex(),
}
}
fn delta_index_parts(to: &Checksum) -> (String, String) {
let b64 = to.to_base64_modified();
let (fanout, rest) = b64.split_at(2);
(fanout.to_owned(), format!("{rest}{INDEX_SUFFIX}"))
}
pub(crate) fn delta_index_relative_path(to: &Checksum) -> String {
let (fanout, name) = delta_index_parts(to);
format!("{DELTA_INDEXES_DIR}/{fanout}/{name}")
}
pub fn static_delta_relative_dir(from: Option<&Checksum>, to: &Checksum) -> String {
delta_relative_dir(from, to)
}
pub(crate) fn delta_relative_dir(from: Option<&Checksum>, to: &Checksum) -> String {
let to_b64 = to.to_base64_modified();
match from {
Some(from) => {
let from_b64 = from.to_base64_modified();
let (fanout, rest) = from_b64.split_at(2);
format!("{DELTAS_DIR}/{fanout}/{rest}-{to_b64}")
}
None => {
let (fanout, rest) = to_b64.split_at(2);
format!("{DELTAS_DIR}/{fanout}/{rest}")
}
}
}
fn resolve_timestamp(explicit: Option<u64>) -> Result<u64> {
match explicit {
Some(timestamp) => Ok(timestamp),
None => unix_seconds(),
}
}
async fn write_delta_file(dir_fd: &OwnedFd, name: &str, bytes: &[u8], fsync: bool) -> Result<()> {
let temp = TempFile::create(dir_fd, name);
let fd = {
let owned = dir_fd.try_clone()?;
let temp = temp.name().to_owned();
ostrya_rt::unblock(move || create_file_blocking(owned.as_fd(), &temp)).await?
};
let mut file = RtFile::from(fd);
file.write_all(bytes).await.map_err(Error::Io)?;
file.flush().await.map_err(Error::Io)?;
drop(file);
finish_file(dir_fd, temp.name(), name, fsync).await?;
temp.keep();
Ok(())
}
struct TempFile<'a> {
dir: &'a OwnedFd,
name: String,
armed: bool,
}
impl<'a> TempFile<'a> {
fn create(dir: &'a OwnedFd, name: &str) -> TempFile<'a> {
TempFile {
dir,
name: temp_name(name),
armed: true,
}
}
fn name(&self) -> &str {
&self.name
}
fn keep(mut self) {
self.armed = false;
}
}
impl Drop for TempFile<'_> {
fn drop(&mut self) {
if self.armed {
let _ = rustix::fs::unlinkat(
self.dir.as_fd(),
self.name.as_str(),
rustix::fs::AtFlags::empty(),
);
}
}
}
async fn finish_file(dir_fd: &OwnedFd, temp: &str, name: &str, fsync: bool) -> Result<()> {
let owned = dir_fd.try_clone()?;
let temp_owned = temp.to_owned();
let name = name.to_owned();
ostrya_rt::unblock(move || {
use rustix::fs::{Mode, OFlags, openat, renameat};
if fsync {
let fd = openat(
owned.as_fd(),
temp_owned.as_str(),
OFlags::RDONLY,
Mode::empty(),
)
.map_err(|e| Error::Io(e.into()))?;
rustix::fs::fdatasync(fd.as_fd()).map_err(|e| Error::Io(e.into()))?;
}
renameat(
owned.as_fd(),
temp_owned.as_str(),
owned.as_fd(),
name.as_str(),
)
.map_err(|e| Error::Io(e.into()))?;
if fsync {
rustix::fs::fsync(owned.as_fd()).map_err(|e| Error::Io(e.into()))?;
}
Ok(())
})
.await
}
async fn remove_superblock(dir_fd: &OwnedFd) -> Result<()> {
let owned = dir_fd.try_clone()?;
ostrya_rt::unblock(move || {
match rustix::fs::unlinkat(owned.as_fd(), SUPERBLOCK_FILE, rustix::fs::AtFlags::empty()) {
Ok(()) | Err(rustix::io::Errno::NOENT) => Ok(()),
Err(e) => Err(Error::Io(e.into())),
}
})
.await
}
async fn clean_delta_dir(dir_fd: &OwnedFd, count: usize) -> Result<()> {
let owned = dir_fd.try_clone()?;
let now = unix_seconds()?;
ostrya_rt::unblock(move || {
for name in dir_child_names(&owned)? {
let remove = match name.parse::<usize>() {
Ok(index) => index >= count,
Err(_) => is_temp_name(&name) && temp_is_stale(owned.as_fd(), &name, now),
};
if !remove {
continue;
}
match rustix::fs::unlinkat(owned.as_fd(), name.as_str(), rustix::fs::AtFlags::empty()) {
Ok(()) | Err(rustix::io::Errno::NOENT) => {}
Err(e) => return Err(Error::Io(e.into())),
}
}
Ok(())
})
.await
}
const TEMP_STALE_SECS: u64 = 60 * 60;
fn temp_is_stale(dir: BorrowedFd<'_>, name: &str, now: u64) -> bool {
let Ok(stat) = rustix::fs::statat(dir, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) else {
return false;
};
let Ok(mtime) = u64::try_from(stat.st_mtime) else {
return false;
};
now.saturating_sub(mtime) >= TEMP_STALE_SECS
}
fn unix_seconds() -> Result<u64> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|_| Error::InvalidFormat("the system clock is before the Unix epoch".into()))?;
Ok(now.as_secs())
}
fn check_superblock_size(len: usize) -> Result<()> {
if len as u64 > MAX_SUPERBLOCK {
return Err(Error::InvalidFormat(format!(
"static delta superblock is {len} bytes, over the {MAX_SUPERBLOCK}-byte ceiling"
)));
}
Ok(())
}
fn check_table_size(len: usize) -> Result<()> {
if len > MAX_TABLE_BYTES {
return Err(Error::InvalidFormat(format!(
"static delta part mode and xattr tables are {len} bytes, over the \
{MAX_TABLE_BYTES}-byte ceiling"
)));
}
Ok(())
}
fn prune_delta_indexes_blocking(repo_fd: BorrowedFd<'_>, written: &BTreeSet<String>) -> Result<()> {
use rustix::fs::{AtFlags, Mode, OFlags, openat, unlinkat};
let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC;
let indexes = match openat(repo_fd, DELTA_INDEXES_DIR, flags, Mode::empty()) {
Ok(fd) => fd,
Err(rustix::io::Errno::NOENT) => return Ok(()),
Err(e) => return Err(Error::Io(e.into())),
};
for fanout in dir_child_names(&indexes)? {
let fan_fd = openat(&indexes, fanout.as_str(), flags, Mode::empty())
.map_err(|e| Error::Io(e.into()))?;
for name in dir_child_names(&fan_fd)? {
if !name.ends_with(INDEX_SUFFIX) || written.contains(&format!("{fanout}/{name}")) {
continue;
}
unlinkat(&fan_fd, name.as_str(), AtFlags::empty()).map_err(|e| Error::Io(e.into()))?;
}
}
Ok(())
}
fn remove_delta_index_blocking(repo_fd: BorrowedFd<'_>, relative: &str) -> Result<()> {
use rustix::fs::{AtFlags, unlinkat};
match unlinkat(repo_fd, relative, AtFlags::empty()) {
Ok(()) | Err(rustix::io::Errno::NOENT) => Ok(()),
Err(e) => Err(Error::Io(e.into())),
}
}
fn list_delta_indexes_blocking(repo_fd: BorrowedFd<'_>) -> Result<Vec<Checksum>> {
use rustix::fs::{Dir, FileType, Mode, OFlags, openat};
let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC;
let indexes = match openat(repo_fd, DELTA_INDEXES_DIR, flags, Mode::empty()) {
Ok(fd) => fd,
Err(rustix::io::Errno::NOENT) => return Ok(Vec::new()),
Err(e) => return Err(Error::Io(e.into())),
};
let mut indexes = Dir::new(indexes).map_err(|e| Error::Io(e.into()))?;
let mut out = Vec::new();
for fanout in entries_of_type(&mut indexes, FileType::Directory)? {
if fanout.len() != 2 {
continue;
}
let fan_fd = openat(
indexes.fd().map_err(|e| Error::Io(e.into()))?,
fanout.as_slice(),
flags | OFlags::NOFOLLOW,
Mode::empty(),
)
.map_err(|e| Error::Io(e.into()))?;
let mut fan_dir = Dir::new(fan_fd).map_err(|e| Error::Io(e.into()))?;
for name in entries_of_type(&mut fan_dir, FileType::RegularFile)? {
let Some(rest) = name.strip_suffix(INDEX_SUFFIX.as_bytes()) else {
continue;
};
if rest.len() != 41 {
continue;
}
let mut b64 = fanout.clone();
b64.extend_from_slice(rest);
let Ok(b64) = std::str::from_utf8(&b64) else {
continue;
};
if let Ok(to) = Checksum::from_base64_modified(b64) {
out.push(to);
}
}
}
out.sort();
Ok(out)
}
fn entries_of_type(dir: &mut rustix::fs::Dir, ty: rustix::fs::FileType) -> Result<Vec<Vec<u8>>> {
use rustix::fs::{AtFlags, FileType, statat};
let mut out = Vec::new();
while let Some(entry) = dir.next() {
let entry = entry.map_err(|e| Error::Io(e.into()))?;
let name = entry.file_name();
if matches!(name.to_bytes(), b"." | b"..") {
continue;
}
let entry_ty = match entry.file_type() {
FileType::Unknown => match statat(
dir.fd().map_err(|e| Error::Io(e.into()))?,
name,
AtFlags::SYMLINK_NOFOLLOW,
) {
Ok(stat) => FileType::from_raw_mode(stat.st_mode),
Err(rustix::io::Errno::NOENT) => continue,
Err(e) => return Err(Error::Io(e.into())),
},
known => known,
};
if entry_ty == ty {
out.push(name.to_bytes().to_vec());
}
}
Ok(out)
}
fn temp_name(name: &str) -> String {
format!(
".{name}.tmp-{}-{}",
std::process::id(),
crate::write::unique()
)
}
fn is_temp_name(name: &str) -> bool {
name.starts_with('.') && name.contains(".tmp-")
}
fn create_file_blocking(dir: BorrowedFd<'_>, name: &str) -> Result<OwnedFd> {
use rustix::fs::{Mode, OFlags, fchmod, openat};
let _ = rustix::fs::unlinkat(dir, name, rustix::fs::AtFlags::empty());
let fd = openat(
dir,
name,
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::from_raw_mode(DELTA_FILE_MODE),
)
.map_err(|e| Error::Io(e.into()))?;
fchmod(&fd, Mode::from_raw_mode(DELTA_FILE_MODE)).map_err(|e| Error::Io(e.into()))?;
Ok(fd)
}
fn open_subdir_blocking(base: BorrowedFd<'_>, relative: &str) -> Result<OwnedFd> {
use rustix::fs::{Mode, OFlags, mkdirat, openat};
let mut current = base.try_clone_to_owned()?;
for component in relative.split('/').filter(|part| !part.is_empty()) {
match mkdirat(
current.as_fd(),
component,
Mode::from_raw_mode(DELTA_DIR_MODE),
) {
Ok(()) | Err(rustix::io::Errno::EXIST) => {}
Err(e) => return Err(Error::Io(e.into())),
}
current = openat(
current.as_fd(),
component,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(|e| Error::Io(e.into()))?;
}
Ok(current)
}
fn create_dir_path_blocking(path: &Path) -> Result<OwnedFd> {
use std::os::unix::fs::DirBuilderExt;
std::fs::DirBuilder::new()
.recursive(true)
.mode(DELTA_DIR_MODE)
.create(path)
.map_err(Error::Io)?;
open_dir_blocking(path)
}
fn open_superblock_parent_blocking(path: &Path) -> Result<(OwnedFd, String)> {
use std::os::unix::ffi::OsStrExt;
let is_dir = || Error::Io(rustix::io::Errno::ISDIR.into());
let bytes = path.as_os_str().as_bytes();
let (parent, name) = match bytes.iter().rposition(|b| *b == b'/') {
Some(slash) => (&bytes[..slash], &bytes[slash + 1..]),
None => (&b""[..], bytes),
};
if matches!(name, b"" | b"." | b"..") {
return Err(is_dir());
}
let name = std::str::from_utf8(name).map_err(|_| {
Error::InvalidFormat(format!(
"static delta superblock file name {} is not UTF-8",
path.display()
))
})?;
if name
.parse::<usize>()
.is_ok_and(|index| index.to_string() == name)
{
return Err(Error::InvalidFormat(format!(
"static delta superblock file name {name} is a part file name"
)));
}
let parent = match parent {
b"" if bytes.first() == Some(&b'/') => Path::new("/"),
b"" => Path::new("."),
parent => Path::new(std::ffi::OsStr::from_bytes(parent)),
};
let fd = open_dir_blocking(parent)?;
match rustix::fs::statat(&fd, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat)
if rustix::fs::FileType::from_raw_mode(stat.st_mode)
== rustix::fs::FileType::Directory =>
{
return Err(is_dir());
}
Ok(_) | Err(rustix::io::Errno::NOENT) => {}
Err(e) => return Err(Error::Io(e.into())),
}
Ok((fd, name.to_owned()))
}
fn open_dir_blocking(path: &Path) -> Result<OwnedFd> {
use rustix::fs::{Mode, OFlags, open};
open(
path,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(|e| Error::Io(e.into()))
}
async fn open_dir_path(path: &Path) -> Result<OwnedFd> {
let path = path.to_owned();
ostrya_rt::unblock(move || open_dir_blocking(&path)).await
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<DeltaOptions>();
assert_send_sync::<crate::delta::DeltaSuperblock>();
};
#[cfg(test)]
mod tests {
use super::*;
fn checksum(byte: u8) -> Checksum {
Checksum::from_bytes([byte; 32])
}
#[test]
fn delta_paths_take_the_base64_fanout() {
let to = checksum(0x11);
let from = checksum(0x22);
let to_b64 = to.to_base64_modified();
let from_b64 = from.to_base64_modified();
assert_eq!(
delta_relative_dir(None, &to),
format!("deltas/{}/{}", &to_b64[..2], &to_b64[2..])
);
assert_eq!(
delta_relative_dir(Some(&from), &to),
format!("deltas/{}/{}-{to_b64}", &from_b64[..2], &from_b64[2..])
);
assert_eq!(
delta_index_relative_path(&to),
format!("delta-indexes/{}/{}.index", &to_b64[..2], &to_b64[2..])
);
}
#[test]
fn delta_names_are_hex() {
let to = checksum(0x11);
let from = checksum(0x22);
assert_eq!(delta_name(None, &to), to.to_hex());
assert_eq!(
delta_name(Some(&from), &to),
format!("{}-{}", from.to_hex(), to.to_hex())
);
}
#[test]
fn the_superblock_ceiling_names_the_size_it_rejects() {
let over = MAX_SUPERBLOCK as usize + 1;
check_superblock_size(MAX_SUPERBLOCK as usize).unwrap();
let err = check_superblock_size(over).unwrap_err();
let Error::InvalidFormat(message) = err else {
panic!("an oversized superblock must be an InvalidFormat error: {err}");
};
assert!(
message.contains(&over.to_string()),
"the error does not name the size: {message}"
);
}
#[test]
fn the_table_ceiling_names_the_size_it_rejects() {
check_table_size(MAX_TABLE_BYTES).unwrap();
let over = MAX_TABLE_BYTES + 1;
let err = check_table_size(over).unwrap_err();
let Error::InvalidFormat(message) = err else {
panic!("oversized part tables must be an InvalidFormat error: {err}");
};
assert!(
message.contains(&over.to_string()),
"the error does not name the size: {message}"
);
}
#[test]
fn a_patch_of_unrelated_content_loses_to_splicing() {
let output_size = 4_096u64;
let stream: Vec<u8> = (0..output_size)
.map(|i| if i % 256 == 0 { 0 } else { 0xa5 })
.collect();
assert!(novel_bytes(&stream) < output_size);
assert!(
!patch_beats_splicing(&stream, output_size),
"a patch counting {} novel bytes of {output_size} was kept",
novel_bytes(&stream)
);
}
#[test]
fn a_patch_of_a_small_edit_beats_splicing() {
let mut stream = vec![0u8; 4_096];
stream[100] = 0x01;
stream[101] = 0x02;
assert!(patch_beats_splicing(&stream, 4_096));
}
#[test]
fn an_empty_target_never_keeps_a_patch() {
assert!(!patch_beats_splicing(&[], 0));
}
fn scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"ostrya-deltagen-{tag}-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn a_deferred_spill_write_error_fails_the_handover() {
let dir = scratch("spill-error");
let path = dir.join("target");
std::fs::write(&path, b"").unwrap();
let file = std::fs::File::open(&path).unwrap();
let spill_dir = std::fs::File::open(&dir).unwrap();
let outcome = ostrya_rt::block_on(async {
let mut spill = Spill::File {
file: RtFile::from(file),
len: 0,
};
spill
.append(b"data source bytes", spill_dir.as_fd())
.await?;
spill.into_blocking().await.map(|_| ())
});
let _ = std::fs::remove_dir_all(&dir);
outcome.expect_err("a failed spill write must fail the handover");
}
#[test]
fn a_short_data_source_fails_the_part() {
let dir = scratch("short-source");
let path = dir.join("source");
std::fs::write(&path, b"seven!!").unwrap();
let file = std::fs::File::open(&path).unwrap();
let outcome = ostrya_rt::block_on(async {
let spill = BlockingSpill::File { file, len: 9 };
let mut sink: Vec<u8> = Vec::new();
spill.write_into(&mut sink).await
});
let _ = std::fs::remove_dir_all(&dir);
let err = outcome.expect_err("a short data source must fail the part");
let Error::InvalidFormat(message) = err else {
panic!("a short data source must be an InvalidFormat error: {err}");
};
assert!(
message.contains('7') && message.contains('9'),
"the error does not name both lengths: {message}"
);
}
#[test]
fn a_failed_part_write_leaves_no_temp_file_behind() {
let root = scratch("part-temp-leak");
let path = root.join("source");
std::fs::write(&path, b"seven!!").unwrap();
let dir = root.join("delta");
std::fs::create_dir(&dir).unwrap();
let dir_fd = open_dir_blocking(&dir).unwrap();
let outcome = ostrya_rt::block_on(async {
let mut part = Part {
blob: Spill::File {
file: RtFile::from(std::fs::File::open(&path).unwrap()),
len: 9,
},
..Part::default()
};
part.finish_object(ObjectType::File, Checksum::sha256(b"x"), 9);
write_part(&mut PartTarget::File(&dir_fd), 0, part, false).await
});
let leftovers = dir_child_names(&dir_fd).unwrap();
let _ = std::fs::remove_dir_all(&root);
assert!(outcome.is_err(), "a short data source must fail the part");
assert!(
leftovers.is_empty(),
"the failed part left files behind: {leftovers:?}"
);
}
async fn noise_commit(root: &Path, files: usize, size: usize) -> (Repo, Checksum) {
use crate::{
CommitModifier, CommitModifierFlags, CommitOptions, CreateOptions, MutableTree,
};
let tree = root.join("tree");
std::fs::create_dir_all(&tree).unwrap();
let mut state = 0x2545_f491_4f6c_dd1du64;
for i in 0..files {
let bytes: Vec<u8> = (0..size)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state as u8
})
.collect();
std::fs::write(tree.join(format!("f{i}")), bytes).unwrap();
}
let repo = Repo::create(
&root.join("repo"),
CreateOptions::new(ostrya_core::RepoMode::Archive),
)
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
let dfd = std::fs::File::open(&tree).unwrap();
let mut modifier = Some(CommitModifier::new(
CommitModifierFlags::CANONICAL_PERMISSIONS | CommitModifierFlags::SKIP_XATTRS,
));
let mut mtree = MutableTree::new();
txn.write_dfd_to_mtree(dfd.as_fd(), Path::new("."), &mut mtree, modifier.as_mut())
.await
.unwrap();
let root_tree = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn
.write_commit(
CommitOptions {
timestamp: Some(1_700_000_000),
..CommitOptions::default()
},
&root_tree,
)
.await
.unwrap();
txn.commit().await.unwrap();
(repo, commit)
}
#[test]
fn an_inline_generation_over_the_ceiling_keeps_the_earlier_delta() {
let root = scratch("inline-ceiling");
let out = root.join("out");
std::fs::create_dir_all(&out).unwrap();
let outcome = ostrya_rt::block_on(async {
let (repo, commit) = noise_commit(&root, 3, 200_000).await;
let files = DeltaOptions {
timestamp: Some(1_700_000_000),
min_fallback_size: 0,
max_chunk_size: 150_000,
..DeltaOptions::default()
};
let relative = repo
.generate_static_delta(None, &commit, &files)
.await
.unwrap();
let delta = root.join("repo").join(&relative);
let before = dir_child_names(&open_dir_blocking(&delta).unwrap()).unwrap();
let superblock = std::fs::read(delta.join(SUPERBLOCK_FILE)).unwrap();
let listed = repo.list_static_deltas().await.unwrap();
assert_eq!(listed.len(), 1);
let inline = DeltaOptions {
inline: true,
..files
};
let err = repo
.generate_static_delta_under(None, &commit, &inline, 100_000)
.await
.unwrap_err();
let Error::InvalidFormat(message) = err else {
panic!("the ceiling refusal is an invalid-format error: {err}");
};
assert!(message.contains("superblock ceiling"), "{message}");
let mut after = dir_child_names(&open_dir_blocking(&delta).unwrap()).unwrap();
let mut before = before;
before.sort();
after.sort();
assert_eq!(after, before);
assert_eq!(
std::fs::read(delta.join(SUPERBLOCK_FILE)).unwrap(),
superblock
);
assert_eq!(repo.list_static_deltas().await.unwrap(), listed);
let err = repo
.generate_static_delta_under(
None,
&commit,
&DeltaOptions {
output_dir: Some(out.clone()),
..inline
},
100_000,
)
.await
.unwrap_err();
assert!(matches!(err, Error::InvalidFormat(_)), "{err}");
dir_child_names(&open_dir_blocking(&out).unwrap()).unwrap()
});
let _ = std::fs::remove_dir_all(&root);
assert!(outcome.is_empty(), "{outcome:?}");
}
#[test]
fn the_capped_part_buffer_refuses_past_its_limit() {
use std::io::Write;
let mut capped = CappedBuf::new(4);
assert_eq!(capped.write(b"abc").unwrap(), 3);
assert_eq!(capped.write(b"de").unwrap(), 1);
assert!(capped.write(b"f").is_err());
assert_eq!(capped.write(b"").unwrap(), 0);
assert_eq!(capped.len(), 4);
assert_eq!(capped.into_parts(), (b'a', b"bcd".to_vec()));
let root = scratch("capped-part");
let tmp = open_dir_blocking(&root).unwrap();
let outcome = ostrya_rt::block_on(async {
let mut part = Part::default();
part.blob.append(&[7u8; 4096], tmp.as_fd()).await?;
part.finish_object(ObjectType::File, Checksum::sha256(b"x"), 4096);
write_part(&mut PartTarget::Inline { budget: 16 }, 0, part, false).await
});
let Err(Error::InvalidFormat(message)) = outcome else {
panic!("an inline part past the budget must be refused");
};
assert!(message.contains("superblock ceiling"), "{message}");
let mut budget = PartTarget::Inline { budget: 1 << 20 };
let entry = ostrya_rt::block_on(async {
let mut part = Part::default();
part.blob.append(&[7u8; 4096], tmp.as_fd()).await?;
part.finish_object(ObjectType::File, Checksum::sha256(b"x"), 4096);
write_part(&mut budget, 0, part, false).await
})
.unwrap();
let (compression, body) = entry.inline.expect("an inline part keeps its bytes");
let mut bytes = vec![compression];
bytes.extend_from_slice(&body);
assert_eq!(bytes.len() as u64, entry.size);
assert_eq!(compression, COMPRESSION_XZ);
assert_eq!(Checksum::sha256(&bytes), entry.checksum);
let PartTarget::Inline { budget } = budget else {
unreachable!();
};
assert_eq!(budget, (1 << 20) - bytes.len());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn temp_names_are_recognized_and_part_names_are_not() {
assert!(is_temp_name(&temp_name("0")));
assert!(is_temp_name(&temp_name(SUPERBLOCK_FILE)));
assert!(!is_temp_name("0"));
assert!(!is_temp_name(SUPERBLOCK_FILE));
}
}