use crate::{
artifact::{self, Artifact, Hash, Kind, Tree},
fs_safety::{self, Scratch, invalid, node_md},
};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::{
collections::HashSet,
fs,
io::{self, Read},
path::{Path, PathBuf},
};
mod packed;
#[derive(Debug, Deserialize, Serialize)]
struct Envelope {
action: Hash,
checksum: Hash,
outputs: Vec<Tree>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pack: Option<packed::Descriptor>,
}
pub(crate) struct Cache {
blobs: PathBuf,
actions: PathBuf,
packs: PathBuf,
use_packs: bool,
verify_local_hit_payload: bool,
}
impl Cache {
pub(crate) fn new(
root: &Path,
use_packs: bool,
verify_local_hit_payload: bool,
) -> io::Result<Self> {
let parent = fs_safety::absolute(root)?;
let packs = if use_packs {
fs_safety::private_dir(&parent, "packs")?
} else {
parent.join("packs")
};
Ok(Self {
blobs: fs_safety::private_dir(&parent, "blobs")?,
actions: fs_safety::private_dir(&parent, "actions")?,
packs,
use_packs,
verify_local_hit_payload,
})
}
pub(crate) fn capture(
&self,
workspace: &Path,
outputs: &[Artifact],
action: Hash,
pool: Option<&rayon::ThreadPool>,
) -> io::Result<Vec<Tree>> {
let (trees, pack) =
if self.use_packs && outputs.iter().any(|output| output.kind == Kind::Directory) {
let (trees, descriptor) = packed::capture(self, workspace, outputs)?;
(trees, Some(descriptor))
} else {
let trees = outputs
.iter()
.map(|out| {
artifact::process_tree(workspace, out, pool, |buffer, source| {
self.store(source, buffer)
})
})
.collect::<io::Result<Vec<_>>>()?;
(trees, None)
};
let signature = checksum(&trees, pack.as_ref())?;
let envelope = Envelope {
action,
checksum: signature,
outputs: trees.clone(),
pack,
};
let name = self.actions.join(artifact::text(&action));
let staged = Scratch::new(&self.actions)?;
let entry = staged.0.join("manifest");
let mut file = create(&entry)?;
serde_json::to_writer(&mut file, &envelope)?;
file.sync_all()?;
drop(file);
match fs::hard_link(&entry, &name) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
match self.read(action, outputs) {
Ok(previous) if previous.outputs == trees => {}
Ok(_) => {
return Err(invalid(
"deterministic action published conflicting outputs",
));
}
Err(e) if e.kind() == io::ErrorKind::InvalidData => {
replace_regular(&entry, &name)?
}
Err(e) => return Err(e),
}
}
Err(e) => return Err(e),
}
Ok(trees)
}
fn read(&self, action: Hash, outputs: &[Artifact]) -> io::Result<Envelope> {
let path = self.actions.join(artifact::text(&action));
let md = node_md(&path)?;
if !md.is_file() || md.len() > 32 * 1024 * 1024 {
return Err(invalid("invalid or oversized action manifest"));
}
let file = fs::File::open(&path)?;
let envelope: Envelope =
serde_json::from_reader(io::BufReader::new(file.take(32 * 1024 * 1024)))
.map_err(invalid)?;
if envelope.action != action
|| checksum(&envelope.outputs, envelope.pack.as_ref())? != envelope.checksum
|| envelope.outputs.len() != outputs.len()
|| (envelope.pack.is_some() && !self.use_packs)
{
return Err(invalid("action manifest does not match the requested key"));
}
for (tree, declared) in envelope.outputs.iter().zip(outputs) {
validate_tree(tree, declared)?;
}
Ok(envelope)
}
fn store(&self, source: &Path, buffer: &mut [u8]) -> io::Result<Hash> {
let staged = Scratch::new(&self.blobs)?;
let entry = staged.0.join("blob");
let mut writer = create(&entry)?;
let digest = artifact::copy_hash_buffered(source, &mut writer, buffer)?;
writer.sync_all()?;
drop(writer);
let destination = self.blobs.join(artifact::text(&digest));
match fs::hard_link(&entry, &destination) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
if artifact::copy_hash_buffered(&destination, io::sink(), buffer)? != digest {
replace_regular(&entry, &destination)?;
}
}
Err(e) => return Err(e),
}
Ok(digest)
}
pub(crate) fn restore(
&self,
workspace: &Path,
scratch_root: &Path,
action: Hash,
outputs: &[Artifact],
pool: Option<&rayon::ThreadPool>,
) -> io::Result<(Vec<Tree>, Vec<String>, bool)> {
let Envelope {
outputs: trees,
pack,
..
} = self.read(action, outputs)?;
let checked_local = !self.verify_local_hit_payload && outputs.len() == 1;
if checked_local {
match artifact::hash_tree(workspace, &outputs[0], pool) {
Ok(local) if local == trees[0] => return Ok((trees, Vec::new(), false)),
Ok(_) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
}
let mut reader = pack
.as_ref()
.map(|descriptor| packed::Reader::open(self, descriptor, &trees))
.transpose()?;
let mut staged = None;
let mut restores = Vec::new();
let mut restored = Vec::new();
let mut recovery = Vec::new();
for (index, (tree, declaration)) in trees.iter().zip(outputs).enumerate() {
let destination = fs_safety::path(workspace, &tree.path, true)?;
let same = if checked_local {
false
} else {
match artifact::hash_tree(workspace, declaration, pool) {
Ok(existing) => existing == *tree,
Err(e) if e.kind() == io::ErrorKind::NotFound => false,
Err(e) => return Err(e),
}
};
if same {
if let (Some(reader), Some(descriptor)) = (&mut reader, &pack) {
reader.verify(tree, descriptor.sizes(index), None, pool)?;
} else {
self.verify(tree, None, pool)?;
}
} else {
if staged.is_none() {
staged = Some(Scratch::new(scratch_root)?);
}
let stage = &staged.as_ref().unwrap().0;
let new = stage.join(format!("new-{index}"));
for dir in tree.entries.iter().filter(|entry| entry.file.is_none()) {
fs::create_dir(if dir.name.is_empty() {
new.clone()
} else {
new.join(&dir.name)
})?;
}
if let (Some(reader), Some(descriptor)) = (&mut reader, &pack) {
reader.verify(tree, descriptor.sizes(index), Some(&new), pool)?;
} else {
self.verify(tree, Some(&new), pool)?;
}
for dir in tree
.entries
.iter()
.rev()
.filter(|entry| entry.file.is_none())
{
artifact::permissions(&new.join(&dir.name), dir.permissions)?;
}
restores.push(Restore {
new,
destination,
backup: stage.join(format!("old-{index}")),
has_backup: false,
installed: false,
});
restored.push(tree.path.clone());
recovery.push((index, tree.path.as_str()));
}
}
if let Some(stage) = &staged {
crate::recovery::prepare(&stage.0, workspace, recovery.into_iter())?;
}
let result = apply(workspace, &mut restores).and_then(|()| {
if let Some(stage) = &staged {
crate::recovery::commit(&stage.0)?;
}
Ok(())
});
if let Err(primary) = result {
if let Err(recovery) = rollback(&mut restores) {
let location = staged.unwrap().persist().display().to_string();
return Err(io::Error::other(format!(
"{primary}; rollback failed: {recovery}. Backups at {location}"
)));
}
return Err(primary);
}
Ok((trees, restored, true))
}
fn verify(
&self,
tree: &Tree,
target: Option<&Path>,
pool: Option<&rayon::ThreadPool>,
) -> io::Result<()> {
let run = |buffer: &mut Vec<u8>, entry: &artifact::Entry| {
let Some(hash) = entry.file else {
return Ok(());
};
let source = self.blobs.join(artifact::text(&hash));
let actual = match target {
Some(dir) => {
let path = if entry.name.is_empty() {
dir.to_owned()
} else {
dir.join(&entry.name)
};
let digest = artifact::copy_hash_buffered(&source, create(&path)?, buffer)?;
artifact::permissions(&path, entry.permissions)?;
Ok(digest)
}
None => artifact::copy_hash_buffered(&source, io::sink(), buffer),
}
.map_err(|e| {
if e.kind() == io::ErrorKind::NotFound {
invalid(format!("blob {} is missing", artifact::text(&hash)))
} else {
e
}
})?;
if actual != hash {
return Err(invalid(format!(
"blob {} is corrupt",
artifact::text(&hash)
)));
}
Ok(())
};
if let Some(pool) = pool.filter(|_| tree.entries.len() >= 64) {
pool.install(|| {
tree.entries
.par_iter()
.with_min_len(16)
.try_for_each_init(|| vec![0; 128 * 1024], run)
})
} else {
let mut buffer = vec![0; 128 * 1024];
tree.entries
.iter()
.try_for_each(|entry| run(&mut buffer, entry))
}
}
}
fn checksum(trees: &[Tree], pack: Option<&packed::Descriptor>) -> io::Result<Hash> {
let bytes = match pack {
Some(pack) => serde_json::to_vec(&(trees, pack))?,
None => serde_json::to_vec(trees)?,
};
Ok(artifact::sha(&bytes))
}
fn validate_tree(tree: &Tree, declaration: &Artifact) -> io::Result<()> {
if tree.path != declaration.path || tree.entries.is_empty() {
return Err(invalid("cache manifest names undeclared outputs"));
}
let root = &tree.entries[0];
if !root.name.is_empty() || root.file.is_some() != (declaration.kind == Kind::File) {
return Err(invalid("cache artifact root has the wrong type"));
}
let mut all = HashSet::new();
all.insert(String::new());
let mut dirs = HashSet::new();
if root.file.is_none() {
dirs.insert(String::new());
}
for entry in tree.entries.iter().skip(1) {
fs_safety::relative(&entry.name, false)?;
let identity = fs_safety::identity(&entry.name);
let parent = identity.rsplit_once('/').map_or("", |(parent, _)| parent);
if !dirs.contains(parent) || !all.insert(identity.clone()) {
return Err(invalid("cache manifest has a duplicate or missing parent"));
}
if entry.file.is_none() {
dirs.insert(identity);
}
}
Ok(())
}
fn replace_regular(source: &Path, destination: &Path) -> io::Result<()> {
if !node_md(destination)?.is_file() {
return Err(invalid("cache entry is not a regular file"));
}
fs::rename(source, destination)
}
fn create(path: &Path) -> io::Result<fs::File> {
fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
}
struct Restore {
new: PathBuf,
destination: PathBuf,
backup: PathBuf,
has_backup: bool,
installed: bool,
}
fn apply(workspace: &Path, changes: &mut [Restore]) -> io::Result<()> {
for item in changes {
let parent = item
.destination
.parent()
.ok_or_else(|| invalid("missing output parent"))?;
let local = parent.strip_prefix(workspace).map_err(invalid)?;
let key = local
.iter()
.map(|p| p.to_str().unwrap_or_default())
.collect::<Vec<_>>()
.join("/");
fs_safety::path(workspace, if key.is_empty() { "." } else { &key }, true)?;
fs::create_dir_all(parent)?;
match node_md(&item.destination) {
Ok(_) => {
fs::rename(&item.destination, &item.backup)?;
item.has_backup = true;
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
fs::rename(&item.new, &item.destination)?;
item.installed = true;
}
Ok(())
}
fn rollback(changes: &mut [Restore]) -> io::Result<()> {
for item in changes.iter_mut().rev() {
if item.installed {
fs::rename(&item.destination, &item.new)?;
}
if item.has_backup {
fs::rename(&item.backup, &item.destination)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use artifact::Entry;
fn entry(name: &str, file: bool) -> Entry {
Entry {
name: name.into(),
file: file.then_some([1; 32]),
permissions: 0o755,
}
}
fn directory() -> Artifact {
Artifact {
path: "out/tree".into(),
kind: Kind::Directory,
}
}
#[test]
fn reject_paths_and_invalid_manifest_trees() {
let declaration = directory();
for entries in [
vec![entry("", false), entry("../sibling", true)],
vec![entry("", false), entry("child/leaf", true)],
vec![
entry("", false),
entry("child", true),
entry("child/leaf", true),
],
vec![entry("", false), entry("child", true), entry("child", true)],
vec![entry("", true), entry("child", true)],
vec![entry("", false), entry("alternate:stream", true)],
vec![entry("", false), entry("COM¹.log", true)],
] {
assert!(
validate_tree(
&Tree {
path: declaration.path.clone(),
entries
},
&declaration
)
.is_err()
);
}
let foreign = Tree {
path: "out/foreign".into(),
entries: vec![entry("", false)],
};
assert!(validate_tree(&foreign, &declaration).is_err());
}
#[test]
fn restore_nested_tree_and_repair_missing_blob() -> io::Result<()> {
let root = Scratch::new(&std::env::temp_dir())?;
let cache = Cache::new(&fs_safety::private_dir(&root.0, "cas")?, false, true)?;
let workspace = fs_safety::private_dir(&root.0, "workspace")?;
let stage = fs_safety::private_dir(&workspace, ".rustsy-process")?;
let output = workspace.join("out/tree");
fs::create_dir_all(output.join("empty"))?;
fs::write(output.join("value"), b"value")?;
let sibling = workspace.join("out/sibling");
fs::write(&sibling, b"keep")?;
let action = artifact::sha(b"tree");
let outputs = [directory()];
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(4)
.build()
.unwrap();
cache.capture(&workspace, &outputs, action, Some(&pool))?;
fs::rename(&output, stage.join("previous"))?;
assert_eq!(
cache
.restore(&workspace, &stage, action, &outputs, Some(&pool))?
.1,
["out/tree"]
);
assert_eq!(fs::read(output.join("value"))?, b"value");
assert!(output.join("empty").is_dir());
assert_eq!(fs::read(&sibling)?, b"keep");
fs::remove_file(cache.blobs.join(artifact::text(&artifact::sha(b"value"))))?;
assert_eq!(
cache
.restore(&workspace, &stage, action, &outputs, Some(&pool))
.unwrap_err()
.kind(),
io::ErrorKind::InvalidData
);
cache.capture(&workspace, &outputs, action, Some(&pool))?;
assert!(
cache
.restore(&workspace, &stage, action, &outputs, Some(&pool))?
.1
.is_empty()
);
#[cfg(unix)]
{
fs::rename(workspace.join("out"), stage.join("dir"))?;
std::os::unix::fs::symlink(stage.join("dir"), workspace.join("out"))?;
assert!(
cache
.restore(&workspace, &stage, action, &outputs, Some(&pool))
.is_err()
);
assert_eq!(fs::read(stage.join("dir/sibling"))?, b"keep");
}
Ok(())
}
#[test]
fn stage_a_parallel_tree_with_one_shared_blob() -> io::Result<()> {
let root = Scratch::new(&std::env::temp_dir())?;
let cache = Cache::new(&fs_safety::private_dir(&root.0, "cas")?, false, true)?;
let work = fs_safety::private_dir(&root.0, "work")?;
let stage = fs_safety::private_dir(&work, ".rustsy-process")?;
let dir = work.join("out/tree");
fs::create_dir_all(&dir)?;
for n in 0..144 {
fs::write(dir.join(n.to_string()), b"same")?;
}
let key = artifact::sha(b"work");
let outputs = [directory()];
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(8)
.build()
.unwrap();
cache.capture(&work, &outputs, key, Some(&pool))?;
assert_eq!(fs::read_dir(&cache.blobs)?.count(), 1);
fs::rename(&dir, stage.join("old"))?;
let restored = cache.restore(&work, &stage, key, &outputs, Some(&pool))?;
assert_eq!(restored.1, ["out/tree"]);
assert_eq!(fs::read_dir(&dir)?.count(), 144);
assert_eq!(fs::read(dir.join("143"))?, b"same");
Ok(())
}
#[test]
fn packed_tree_preserves_members_and_rejects_corruption_before_promotion() -> io::Result<()> {
let root = Scratch::new(&std::env::temp_dir())?;
let path = fs_safety::private_dir(&root.0, "cas")?;
let cache = Cache::new(&path, true, true)?;
let work = fs_safety::private_dir(&root.0, "work")?;
let stage = fs_safety::private_dir(&work, ".rustsy-process")?;
let dir = work.join("out/tree");
fs::create_dir_all(dir.join("empty"))?;
for n in 0..144 {
fs::write(dir.join(n.to_string()), vec![n as u8; n])?;
}
fs::write(work.join("out/extra"), b"outside the declared directory")?;
let key = artifact::sha(b"packed work");
let outputs = [directory()];
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(8)
.build()
.unwrap();
let expected = cache.capture(&work, &outputs, key, Some(&pool))?;
assert_eq!(fs::read_dir(&cache.blobs)?.count(), 0);
assert_eq!(fs::read_dir(&cache.packs)?.count(), 1);
let pack = fs::read_dir(&cache.packs)?.next().unwrap()?.path();
fs::rename(&dir, stage.join("previous"))?;
let restored = cache.restore(&work, &stage, key, &outputs, Some(&pool))?;
assert_eq!(restored.0, expected);
assert_eq!(restored.1, ["out/tree"]);
assert_eq!(fs::read(dir.join("143"))?, vec![143; 143]);
assert!(dir.join("empty").is_dir());
let mut data = fs::read(&pack)?;
data[0] ^= 1;
fs::write(&pack, data)?;
let verify_local_only = Cache::new(&path, true, false)?;
assert!(
!verify_local_only
.restore(&work, &stage, key, &outputs, Some(&pool))?
.2
);
assert!(
cache
.restore(&work, &stage, key, &outputs, Some(&pool))
.is_err()
);
fs::rename(&dir, stage.join("restored"))?;
assert_eq!(
verify_local_only
.restore(&work, &stage, key, &outputs, Some(&pool))
.unwrap_err()
.kind(),
io::ErrorKind::InvalidData
);
assert!(!dir.exists());
assert_eq!(
fs::read(work.join("out/extra"))?,
b"outside the declared directory"
);
fs::rename(stage.join("previous"), &dir)?;
cache.capture(&work, &outputs, key, Some(&pool))?;
assert!(
cache
.restore(&work, &stage, key, &outputs, Some(&pool))?
.1
.is_empty()
);
Ok(())
}
}