use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufWriter, Read as _, Seek as _, SeekFrom, Write};
use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
use std::path::{Path, PathBuf};
use serde_json::{json, Value as Json};
use sha2::{Digest as _, Sha256};
use stratum_node_core::{NostrSecretKey, PodPath, Sha256Digest, UnixTime};
use crate::client::{self, MAX_RESPONSE_BYTES};
use crate::error::CliError;
use crate::exit;
use crate::gate::{
self, GateClient, Head, Request, Route, ANY, LD_JSON, MAX_LISTING_BYTES, SUSPENDED,
};
use crate::listing::{self, Child};
use crate::origin::GateTarget;
use crate::output::sanitize;
use crate::private_file;
use crate::session::Session;
pub const MAX_EXPORT_ENTRIES: u64 = 100_000;
pub const MAX_EXPORT_BYTES: u64 = 64 * 1024 * 1024 * 1024;
pub const MANIFEST_FORMAT: &str = "stratum-pod-export";
pub const MANIFEST_FORMAT_VERSION: u64 = 1;
pub const MANIFEST_SUFFIX: &str = ".manifest.json";
const ZSTD_LEVEL: i32 = 3;
#[derive(Debug, Clone, Default)]
pub struct ExportOptions {
pub output: PathBuf,
pub force: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Container,
Resource,
Acl,
}
impl Kind {
fn as_str(self) -> &'static str {
match self {
Self::Container => "container",
Self::Resource => "resource",
Self::Acl => "acl",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reason {
Listed,
Beside,
}
#[derive(Debug, Clone)]
struct Entry {
path: PodPath,
kind: Kind,
size: u64,
sha256: Option<Sha256Digest>,
content_type: Option<String>,
etag: Option<String>,
}
impl Entry {
fn to_json(&self) -> Json {
json!({
"path": self.path,
"archive_path": archive_path(&self.path),
"kind": self.kind.as_str(),
"size": self.size,
"sha256": self.sha256,
"content_type": self.content_type,
})
}
}
fn archive_path(path: &PodPath) -> &str {
path.as_str().trim_start_matches('/')
}
#[derive(Debug)]
struct Targets {
archive: PathBuf,
manifest: PathBuf,
directory: PathBuf,
archive_temp: PathBuf,
manifest_temp: PathBuf,
manifest_aside: PathBuf,
spool: PathBuf,
}
impl Targets {
fn new(archive: &Path) -> Result<Self, CliError> {
let name = archive
.file_name()
.and_then(|n| n.to_str())
.filter(|n| !n.is_empty())
.ok_or_else(|| CliError::Usage("-o must name an archive file".to_owned()))?;
let directory = match archive.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent.to_owned(),
_ => PathBuf::from("."),
};
let tag = hex::encode(&client::random_32()?[..6]);
let mut manifest = archive.as_os_str().to_owned();
manifest.push(MANIFEST_SUFFIX);
Ok(Self {
archive: archive.to_owned(),
manifest: PathBuf::from(manifest),
archive_temp: directory.join(format!(".{name}.partial-{tag}")),
manifest_temp: directory.join(format!(".{name}.manifest-{tag}")),
manifest_aside: directory.join(format!(".{name}.manifest-old-{tag}")),
spool: directory.join(format!(".{name}.spool-{tag}")),
directory,
})
}
}
#[derive(Debug, Default)]
struct Cleanup(Vec<PathBuf>);
impl Drop for Cleanup {
fn drop(&mut self) {
for path in &self.0 {
let _removed = fs::remove_file(path);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Access {
Write,
ReadWrite,
}
fn create_private(path: &Path, access: Access) -> Result<File, CliError> {
OpenOptions::new()
.read(access == Access::ReadWrite)
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
.map_err(|err| CliError::Local(format!("creating {} failed: {err}", path.display())))
}
struct Hashing<W> {
inner: W,
hasher: Sha256,
size: u64,
}
impl<W: Write> Write for Hashing<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let written = self.inner.write(buf)?;
self.hasher.update(&buf[..written]);
self.size = self
.size
.saturating_add(u64::try_from(written).unwrap_or(u64::MAX));
Ok(written)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}
type Archive = tar::Builder<zstd::stream::write::Encoder<'static, Hashing<BufWriter<File>>>>;
#[derive(Debug, Clone)]
struct Skipped {
listed_in: Option<PodPath>,
id: String,
reason: String,
}
struct Walk<'a> {
gate: GateClient,
key: &'a NostrSecretKey,
root: PodPath,
archive: Archive,
spool: File,
created_at: UnixTime,
entries: Vec<Entry>,
visited: BTreeSet<PodPath>,
listings: BTreeMap<PodPath, BTreeSet<PodPath>>,
skipped: Vec<Skipped>,
vanished: Vec<PodPath>,
changed: Vec<(PodPath, String)>,
unverified: Vec<(PodPath, u16)>,
total_bytes: u64,
}
impl Walk<'_> {
fn run(&mut self) -> Result<(), CliError> {
let root = self.root.clone();
let root_acl = root
.acl_path()
.ok_or_else(|| CliError::Local("the pod root has no ACL path".to_owned()))?;
self.visited.insert(root.clone());
self.visited.insert(root_acl.clone());
self.fetch(&root_acl, Reason::Beside, None)?;
let mut queue = VecDeque::from([root.clone()]);
while let Some(container) = queue.pop_front() {
let Some(children) = self.list(&container)? else {
continue;
};
self.add_container(&container)?;
if container != root {
if let Some(acl) = container.acl_path() {
if self.visited.insert(acl.clone()) {
self.fetch(&acl, Reason::Beside, Some(&container))?;
}
}
}
let mut accepted = BTreeSet::new();
for child in children {
let path = match child {
Child::Accepted(path) => path,
Child::Refused { id, reason } => {
self.skipped.push(Skipped {
listed_in: Some(container.clone()),
id,
reason,
});
continue;
}
};
accepted.insert(path.clone());
if !self.visited.insert(path.clone()) {
continue;
}
if path.is_container() {
queue.push_back(path);
continue;
}
let present = self.fetch(&path, Reason::Listed, Some(&container))?;
if present {
if let Some(acl) = path.acl_path() {
if self.visited.insert(acl.clone()) {
self.fetch(&acl, Reason::Beside, Some(&container))?;
}
}
}
}
self.listings.insert(container, accepted);
}
Ok(())
}
fn list(&mut self, container: &PodPath) -> Result<Option<Vec<Child>>, CliError> {
let response = self.gate.fetch(
&Request::new("GET", container.as_str(), LD_JSON),
Some(self.key),
MAX_LISTING_BYTES,
)?;
let head = &response.head;
if head.is_success() {
let origin = self.gate.target().origin().clone();
return listing::children(&origin, container, &response.body).map(Some);
}
if *container == self.root {
return Err(response.into_error(Route::Pod));
}
if head.status == 404 {
self.vanished.push(container.clone());
return Ok(None);
}
if head.is_redirect() {
self.skip_redirect(container, None);
return Ok(None);
}
Err(response.into_error(Route::Pod))
}
fn skip_redirect(&mut self, path: &PodPath, listed_in: Option<&PodPath>) {
self.skipped.push(Skipped {
listed_in: listed_in.cloned(),
id: path.to_string(),
reason: "answered with a redirect, which is not followed".to_owned(),
});
}
fn count_entry(&self) -> Result<(), CliError> {
check_entry_limit(u64::try_from(self.entries.len()).unwrap_or(u64::MAX))
}
fn add_container(&mut self, container: &PodPath) -> Result<(), CliError> {
self.count_entry()?;
let mut header = tar::Header::new_gnu();
header.set_entry_type(tar::EntryType::Directory);
header.set_size(0);
header.set_mode(0o700);
header.set_mtime(self.created_at.as_secs());
self.archive
.append_data(&mut header, archive_path(container), io::empty())
.map_err(|err| archive_error(&err))?;
self.entries.push(Entry {
path: container.clone(),
kind: Kind::Container,
size: 0,
sha256: None,
content_type: None,
etag: None,
});
Ok(())
}
fn fetch(
&mut self,
path: &PodPath,
reason: Reason,
listed_in: Option<&PodPath>,
) -> Result<bool, CliError> {
self.count_entry()?;
self.spool
.set_len(0)
.and_then(|()| self.spool.seek(SeekFrom::Start(0)).map(drop))
.map_err(|err| spool_error(&err))?;
let request = Request::new("GET", path.as_str(), ANY);
let (head, outcome) = {
let mut sink = BufWriter::new(&self.spool);
let result =
self.gate
.stream(&request, self.key, &mut sink, gate::MAX_RESOURCE_BYTES)?;
sink.flush().map_err(|err| spool_error(&err))?;
result
};
let streamed = match outcome {
Ok(streamed) => streamed,
Err(body) => {
if head.status == 404 {
if reason == Reason::Listed {
self.vanished.push(path.clone());
}
return Ok(false);
}
if head.is_redirect() {
self.skip_redirect(path, listed_in);
return Ok(false);
}
return Err(gate::error_from(&head, &body, Route::Pod));
}
};
self.total_bytes = self.total_bytes.saturating_add(streamed.size);
check_byte_limit(self.total_bytes)?;
if let Some(tag) = head.etag.as_deref().and_then(sha256_tag) {
if tag != streamed.sha256 {
self.changed.push((
path.clone(),
"the bytes received do not match the entity tag sent with them".to_owned(),
));
}
}
self.spool
.seek(SeekFrom::Start(0))
.map_err(|err| spool_error(&err))?;
let mut header = tar::Header::new_gnu();
header.set_entry_type(tar::EntryType::Regular);
header.set_size(streamed.size);
header.set_mode(0o600);
header.set_mtime(self.created_at.as_secs());
self.archive
.append_data(
&mut header,
archive_path(path),
(&self.spool).take(streamed.size),
)
.map_err(|err| archive_error(&err))?;
let kind = if path.acl_path().is_none() {
Kind::Acl
} else {
Kind::Resource
};
self.entries.push(Entry {
path: path.clone(),
kind,
size: streamed.size,
sha256: Some(streamed.sha256),
content_type: head.content_type.as_deref().map(sanitize),
etag: head.etag,
});
Ok(true)
}
fn abort_if_suspended(&self) -> Result<(), CliError> {
let response = self.gate.fetch(
&Request::new("GET", self.root.as_str(), LD_JSON),
Some(self.key),
MAX_LISTING_BYTES,
)?;
if gate::envelope_code(&response.body).as_deref() == Some(SUSPENDED) {
return Err(response.into_error(Route::Pod));
}
Ok(())
}
fn verify(&mut self) -> Result<(), CliError> {
let files: Vec<Entry> = self
.entries
.iter()
.filter(|entry| entry.kind != Kind::Container)
.cloned()
.collect();
for entry in files {
let response = self.gate.fetch(
&Request::new("HEAD", entry.path.as_str(), ANY),
Some(self.key),
MAX_RESPONSE_BYTES,
)?;
let head: &Head = &response.head;
if head.status == 403 {
self.abort_if_suspended()?;
}
if head.status == 404 {
self.vanished.push(entry.path);
} else if head.is_success() {
if let Some(now) = &head.etag {
let before = entry.etag.as_deref().and_then(sha256_tag).or(entry.sha256);
let differs = match (sha256_tag(now), before) {
(Some(now), Some(before)) => now != before,
_ => entry.etag.as_deref() != Some(now.as_str()),
};
if differs {
self.changed.push((
entry.path,
"its entity tag changed during the export".to_owned(),
));
}
}
} else {
self.unverified.push((entry.path, head.status));
}
}
let listings = std::mem::take(&mut self.listings);
for (container, before) in &listings {
let response = self.gate.fetch(
&Request::new("GET", container.as_str(), LD_JSON),
Some(self.key),
MAX_LISTING_BYTES,
)?;
if response.head.status == 404 {
self.vanished.push(container.clone());
continue;
}
if gate::envelope_code(&response.body).as_deref() == Some(SUSPENDED) {
return Err(response.into_error(Route::Pod));
}
if !response.head.is_success() {
self.unverified
.push((container.clone(), response.head.status));
continue;
}
let origin = self.gate.target().origin().clone();
let now: BTreeSet<PodPath> = listing::children(&origin, container, &response.body)?
.into_iter()
.filter_map(|child| match child {
Child::Accepted(path) => Some(path),
Child::Refused { .. } => None,
})
.collect();
if now != *before {
self.changed.push((
container.clone(),
"its listing changed during the export".to_owned(),
));
}
}
self.listings = listings;
Ok(())
}
}
fn check_entry_limit(held: u64) -> Result<(), CliError> {
if held >= MAX_EXPORT_ENTRIES {
return Err(CliError::Local(format!(
"export stopped: the pod holds more than {MAX_EXPORT_ENTRIES} entries; \
nothing was written"
)));
}
Ok(())
}
fn check_byte_limit(total: u64) -> Result<(), CliError> {
if total > MAX_EXPORT_BYTES {
return Err(CliError::Local(format!(
"export stopped: the pod holds more than {MAX_EXPORT_BYTES} bytes (64 GiB); \
nothing was written"
)));
}
Ok(())
}
fn sha256_tag(etag: &str) -> Option<Sha256Digest> {
let tag = etag.strip_prefix("W/").unwrap_or(etag);
tag.strip_prefix('"')?.strip_suffix('"')?.parse().ok()
}
fn archive_error(err: &io::Error) -> CliError {
CliError::Local(format!("writing the archive failed: {err}"))
}
fn spool_error(err: &io::Error) -> CliError {
CliError::Local(format!("the export's temporary file failed: {err}"))
}
fn check_absent(path: &Path) -> Result<(), CliError> {
if fs::symlink_metadata(path).is_ok() {
return Err(CliError::Local(format!(
"{} already exists; pass --force to replace it",
path.display()
)));
}
Ok(())
}
#[derive(Debug)]
struct Findings {
root: PodPath,
entries: Vec<Entry>,
skipped: Vec<Skipped>,
vanished: Vec<PodPath>,
changed: Vec<(PodPath, String)>,
unverified: Vec<(PodPath, u16)>,
total_bytes: u64,
}
impl Findings {
fn from_walk(walk: Walk<'_>) -> (Archive, Self) {
let findings = Self {
root: walk.root,
entries: walk.entries,
skipped: walk.skipped,
vanished: walk.vanished,
changed: walk.changed,
unverified: walk.unverified,
total_bytes: walk.total_bytes,
};
(walk.archive, findings)
}
fn acls(&self) -> Vec<&PodPath> {
self.entries
.iter()
.filter(|entry| entry.kind == Kind::Acl)
.map(|entry| &entry.path)
.collect()
}
fn is_complete(&self) -> bool {
self.changed.is_empty() && self.vanished.is_empty() && self.skipped.is_empty()
}
fn json_members(&self) -> serde_json::Map<String, Json> {
let mut map = serde_json::Map::new();
map.insert("total_bytes".to_owned(), json!(self.total_bytes));
map.insert("acls".to_owned(), json!(self.acls()));
map.insert(
"changed".to_owned(),
self.changed
.iter()
.map(|(path, why)| json!({"path": path, "reason": why}))
.collect(),
);
map.insert("vanished".to_owned(), json!(self.vanished));
map.insert(
"skipped".to_owned(),
self.skipped
.iter()
.map(|s| json!({"listed_in": s.listed_in, "id": s.id, "reason": s.reason}))
.collect(),
);
map.insert(
"unverified".to_owned(),
self.unverified
.iter()
.map(|(path, status)| json!({"path": path, "status": status}))
.collect(),
);
map
}
}
fn finish_archive(archive: Archive) -> Result<(u64, Sha256Digest), CliError> {
let encoder = archive.into_inner().map_err(|err| archive_error(&err))?;
let mut hashing = encoder.finish().map_err(|err| archive_error(&err))?;
hashing.flush().map_err(|err| archive_error(&err))?;
let size = hashing.size;
let digest: [u8; 32] = hashing.hasher.finalize().into();
let file = hashing
.inner
.into_inner()
.map_err(|err| archive_error(err.error()))?;
file.sync_all().map_err(|err| archive_error(&err))?;
Ok((size, Sha256Digest::from_bytes(digest)))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Existing {
Keep,
Replace,
}
fn install(
targets: &Targets,
manifest: &Json,
existing: Existing,
cleanup: &mut Cleanup,
) -> Result<(), CliError> {
let mut text = serde_json::to_vec_pretty(manifest)
.map_err(|err| CliError::Local(format!("encoding the manifest failed: {err}")))?;
text.push(b'\n');
let mut file = create_private(&targets.manifest_temp, Access::Write)?;
cleanup.0.push(targets.manifest_temp.clone());
file.write_all(&text)
.and_then(|()| file.sync_all())
.map_err(|err| CliError::Local(format!("writing the manifest failed: {err}")))?;
drop(file);
place(targets, existing)
}
fn place(targets: &Targets, existing: Existing) -> Result<(), CliError> {
match existing {
Existing::Keep => place_new(targets)?,
Existing::Replace => place_replacing(targets)?,
}
sync_directory(targets, "the archive and its manifest are in place")
}
fn place_new(targets: &Targets) -> Result<(), CliError> {
let refused = |path: &Path, err: &io::Error| {
if err.kind() == io::ErrorKind::AlreadyExists {
CliError::Local(format!(
"{} already exists; pass --force to replace it",
path.display()
))
} else {
CliError::Local(format!(
"moving {} into place failed: {err}",
path.display()
))
}
};
let ours = fs::symlink_metadata(&targets.archive_temp)
.map_err(|err| refused(&targets.archive, &err))?;
private_file::place_new(&targets.archive_temp, &targets.archive)
.map_err(|err| refused(&targets.archive, &err))?;
if let Err(err) = private_file::place_new(&targets.manifest_temp, &targets.manifest) {
if let Ok(now) = fs::symlink_metadata(&targets.archive) {
if (now.dev(), now.ino()) == (ours.dev(), ours.ino()) {
let _removed = fs::remove_file(&targets.archive);
}
}
return Err(refused(&targets.manifest, &err));
}
Ok(())
}
fn place_replacing(targets: &Targets) -> Result<(), CliError> {
let aside = match fs::rename(&targets.manifest, &targets.manifest_aside) {
Ok(()) => {
sync_directory(targets, "the old manifest is set aside")?;
Some(&targets.manifest_aside)
}
Err(err) if err.kind() == io::ErrorKind::NotFound => None,
Err(err) => {
return Err(CliError::Local(format!(
"moving the old manifest {} aside failed: {err}",
targets.manifest.display()
)))
}
};
if let Err(err) = fs::rename(&targets.archive_temp, &targets.archive) {
let restored = aside.map_or(Ok(()), |old| fs::rename(old, &targets.manifest));
let note = match restored {
Ok(()) => String::new(),
Err(restore) => format!(
"; restoring the old manifest from {} failed: {restore}",
targets.manifest_aside.display()
),
};
return Err(CliError::Local(format!(
"moving the archive into place at {} failed: {err}{note}",
targets.archive.display()
)));
}
if let Some(old) = aside {
let _removed = fs::remove_file(old);
}
fs::rename(&targets.manifest_temp, &targets.manifest).map_err(|err| {
CliError::Local(format!(
"the archive is in place at {}, but moving its manifest into place at {} failed: \
{err}; no manifest is beside it",
targets.archive.display(),
targets.manifest.display()
))
})
}
fn sync_directory(targets: &Targets, done: &str) -> Result<(), CliError> {
File::open(&targets.directory)
.and_then(|dir| dir.sync_all())
.map_err(|err| {
CliError::Local(format!(
"{done}, but syncing {} failed: {err}",
targets.directory.display()
))
})
}
impl Session {
pub fn export(&self, target: &GateTarget, options: &ExportOptions) -> Result<u8, CliError> {
let key = self.key()?;
let me = key.public();
let targets = Targets::new(&options.output)?;
if !options.force {
check_absent(&targets.archive)?;
check_absent(&targets.manifest)?;
}
let mut cleanup = Cleanup::default();
let archive_file = create_private(&targets.archive_temp, Access::Write)?;
cleanup.0.push(targets.archive_temp.clone());
let spool = create_private(&targets.spool, Access::ReadWrite)?;
cleanup.0.push(targets.spool.clone());
let encoder = zstd::stream::write::Encoder::new(
Hashing {
inner: BufWriter::new(archive_file),
hasher: Sha256::new(),
size: 0,
},
ZSTD_LEVEL,
)
.map_err(|err| archive_error(&err))?;
let created_at = client::now()?;
let mut walk = Walk {
gate: GateClient::new(target.clone()).with_busy_retries(*self.output()),
key: &key,
root: PodPath::pod_root(&me),
archive: tar::Builder::new(encoder),
spool,
created_at,
entries: Vec::new(),
visited: BTreeSet::new(),
listings: BTreeMap::new(),
skipped: Vec::new(),
vanished: Vec::new(),
changed: Vec::new(),
unverified: Vec::new(),
total_bytes: 0,
};
self.output()
.note(&format!("exporting {} from {}", walk.root, target.origin()))?;
walk.run()?;
walk.verify()?;
let (archive, findings) = Findings::from_walk(walk);
let (archive_size, archive_sha256) = finish_archive(archive)?;
let archive_name = targets
.archive
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let mut manifest = json!({
"format": MANIFEST_FORMAT,
"format_version": MANIFEST_FORMAT_VERSION,
"origin": target.origin().as_str(),
"owner": me,
"pod_root": findings.root,
"created_at": created_at,
"archive": {"name": archive_name, "size": archive_size, "sha256": archive_sha256},
"entries": findings.entries.iter().map(Entry::to_json).collect::<Vec<_>>(),
});
if let Json::Object(map) = &mut manifest {
map.extend(findings.json_members());
}
let existing = if options.force {
Existing::Replace
} else {
Existing::Keep
};
install(&targets, &manifest, existing, &mut cleanup)?;
drop(cleanup);
self.report_export(&targets, archive_size, archive_sha256, &findings)
}
fn report_export(
&self,
targets: &Targets,
archive_size: u64,
archive_sha256: Sha256Digest,
findings: &Findings,
) -> Result<u8, CliError> {
let mut report = json!({
"archive": targets.archive.display().to_string(),
"manifest": targets.manifest.display().to_string(),
"archive_size": archive_size,
"archive_sha256": archive_sha256,
"entries": findings.entries.len(),
});
if let Json::Object(map) = &mut report {
map.extend(findings.json_members());
}
self.output().json(&report)?;
self.output().line(&format!(
"archive: {} ({archive_size} bytes, sha256 {archive_sha256})",
targets.archive.display()
))?;
self.output()
.line(&format!("manifest: {}", targets.manifest.display()))?;
self.output().line(&format!(
"entries: {} ({} bytes of content, {} ACLs)",
findings.entries.len(),
findings.total_bytes,
findings.acls().len()
))?;
for (path, why) in &findings.changed {
self.output().line(&format!("changed: {path}: {why}"))?;
}
for path in &findings.vanished {
self.output().line(&format!("vanished: {path}"))?;
}
for s in &findings.skipped {
let place = s
.listed_in
.as_ref()
.map(|p| format!(" (listed in {p})"))
.unwrap_or_default();
self.output()
.line(&format!("skipped: {:?}{place}: {}", s.id, s.reason))?;
}
for (path, status) in &findings.unverified {
self.output()
.line(&format!("not rechecked: {path}: HTTP {status}"))?;
}
if findings.is_complete() {
return Ok(exit::OK);
}
Err(CliError::ExportIncomplete(format!(
"the archive is written, but {} entries changed, {} vanished and {} listed children \
were skipped during the walk; the manifest lists them",
findings.changed.len(),
findings.vanished.len(),
findings.skipped.len()
)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn entity_tags_are_read_as_quoted_digests() {
let hex = "ab".repeat(32);
let digest: Sha256Digest = hex.parse().expect("digest");
assert_eq!(sha256_tag(&format!("\"{hex}\"")), Some(digest));
assert_eq!(sha256_tag(&format!("W/\"{hex}\"")), Some(digest));
assert_eq!(sha256_tag(&hex), None);
assert_eq!(sha256_tag("\"abc\""), None);
}
#[test]
fn the_walk_stops_at_the_limits() {
assert!(check_entry_limit(MAX_EXPORT_ENTRIES - 1).is_ok());
let err = check_entry_limit(MAX_EXPORT_ENTRIES).expect_err("the 100,001st entry");
assert!(err.to_string().contains("100000 entries"), "{err}");
assert!(check_byte_limit(MAX_EXPORT_BYTES).is_ok());
let err = check_byte_limit(MAX_EXPORT_BYTES + 1).expect_err("one byte over 64 GiB");
assert!(err.to_string().contains("64 GiB"), "{err}");
assert_eq!(err.exit_code(), exit::FAILURE);
}
#[test]
fn targets_sit_beside_the_archive() {
let targets = Targets::new(Path::new("out/pod.tar.zst")).expect("targets");
assert_eq!(targets.manifest, Path::new("out/pod.tar.zst.manifest.json"));
assert_eq!(targets.directory, Path::new("out"));
assert!(targets
.archive_temp
.to_string_lossy()
.starts_with("out/.pod.tar.zst.partial-"));
let bare = Targets::new(Path::new("pod.tar.zst")).expect("targets");
assert_eq!(bare.directory, Path::new("."));
}
fn staged(archive: &[u8]) -> (tempfile::TempDir, Targets) {
let dir = tempfile::tempdir().expect("tempdir");
let targets = Targets::new(&dir.path().join("pod.tar.zst")).expect("targets");
fs::write(&targets.archive_temp, archive).expect("archive");
fs::write(&targets.manifest_temp, manifest_for(archive)).expect("manifest");
(dir, targets)
}
fn manifest_for(archive: &[u8]) -> Vec<u8> {
json!({"archive": {"sha256": Sha256Digest::of(archive)}})
.to_string()
.into_bytes()
}
fn pair_is_consistent(targets: &Targets) -> bool {
let Ok(manifest) = fs::read(&targets.manifest) else {
return true;
};
let Ok(archive) = fs::read(&targets.archive) else {
return false;
};
let manifest: Json = serde_json::from_slice(&manifest).expect("manifest json");
manifest["archive"]["sha256"] == json!(Sha256Digest::of(&archive))
}
fn names(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(dir)
.expect("read dir")
.map(|entry| {
entry
.expect("entry")
.file_name()
.to_string_lossy()
.into_owned()
})
.collect();
names.sort();
names
}
#[test]
fn an_archive_appearing_after_the_check_is_never_replaced() {
let (_dir, targets) = staged(b"new");
fs::write(&targets.archive, b"theirs").expect("theirs");
let err = place(&targets, Existing::Keep).expect_err("refused");
assert!(err.to_string().contains("already exists"), "{err}");
assert_eq!(
fs::read(&targets.archive).expect("archive"),
b"theirs",
"kept"
);
assert!(
fs::metadata(&targets.manifest).is_err(),
"no manifest beside it"
);
}
#[test]
fn a_manifest_appearing_after_the_check_is_never_replaced() {
let (_dir, targets) = staged(b"new");
fs::write(&targets.manifest, b"theirs").expect("theirs");
let err = place(&targets, Existing::Keep).expect_err("refused");
assert!(err.to_string().contains("already exists"), "{err}");
assert_eq!(
fs::read(&targets.manifest).expect("manifest"),
b"theirs",
"kept"
);
assert!(
fs::metadata(&targets.archive).is_err(),
"the archive placed a moment earlier is withdrawn"
);
}
#[test]
fn a_failed_manifest_step_never_leaves_a_new_archive_beside_an_old_manifest() {
let (dir, targets) = staged(b"new");
fs::write(&targets.archive, b"old").expect("old archive");
fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
fs::remove_file(&targets.manifest_temp).expect("make the manifest step fail");
let err = place(&targets, Existing::Replace).expect_err("the manifest step fails");
assert!(err.to_string().contains("no manifest"), "{err}");
assert!(pair_is_consistent(&targets), "{:?}", names(dir.path()));
let visible: Vec<String> = names(dir.path())
.into_iter()
.filter(|name| !name.starts_with('.'))
.collect();
assert_eq!(
visible,
["pod.tar.zst"],
"the archive alone, with no manifest"
);
}
#[test]
fn a_failed_archive_step_keeps_the_old_pair() {
let (dir, targets) = staged(b"new");
fs::create_dir(&targets.archive).expect("dir");
fs::write(targets.archive.join("x"), b"x").expect("x");
fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
let err = place(&targets, Existing::Replace).expect_err("the archive step fails");
assert!(err.to_string().contains("moving the archive"), "{err}");
assert_eq!(
fs::read(&targets.manifest).expect("manifest"),
manifest_for(b"old"),
"the old manifest is back: {:?}",
names(dir.path())
);
}
#[test]
fn a_forced_export_replaces_the_pair() {
let (dir, targets) = staged(b"new");
fs::write(&targets.archive, b"old").expect("old archive");
fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
place(&targets, Existing::Replace).expect("placed");
assert_eq!(fs::read(&targets.archive).expect("archive"), b"new", "new");
assert!(pair_is_consistent(&targets), "the manifest describes it");
assert_eq!(
names(dir.path()),
["pod.tar.zst", "pod.tar.zst.manifest.json"],
"nothing else is left"
);
}
}