Merge branch 't3/plain-folder-backups': a backup is a plain folder; git leaves the program (D-91, D-92)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 20:23:15 -07:00
commit e6d722372e
84 files changed
+14087 -7326

No files matched your search

+980
View File
@@ -0,0 +1,980 @@
//! Backups in plain folders (WB-backup-1 to WB-backup-9): what a backup
//! is, that it only grows, that a restore of any whole manifest is a
//! prefix of the books, that two writers do not corrupt one destination,
//! that a program that dies at any write leaves a destination that proves
//! whole at its previous manifest, that a flipped or cut piece is never
//! restored, and that a wrong passphrase never yields books.
use ledger_core::{AccountType, Currency, Money, Side};
use ledger_store::Store;
use ledger_store::backup::{
BackupError, BackupKey, Ctx, Cut, Destination, find, save_file, verify_found, write_destination,
};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
fn usd(s: &str) -> Money {
Money::new(s.parse().unwrap(), Currency::USD)
}
/// A book with a few entries and a stored file.
fn book(dir: &Path) -> Store {
let mut s = Store::create(dir, Currency::USD).unwrap();
let cash = s
.add_account("1000", "Cash", AccountType::Asset, None, false)
.unwrap();
let cap = s
.add_account("3000", "Capital", AccountType::Equity, None, false)
.unwrap();
let e = s
.create_entry(
chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(),
"Start",
)
.unwrap();
s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap();
s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap();
s.post_entry(e).unwrap();
s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None)
.unwrap();
s
}
/// One more write to the books: an account and a stored file.
fn more(s: &mut Store, n: usize) {
s.add_account(
&format!("{}", 6000 + n),
&format!("Expense {n}"),
AccountType::Expense,
None,
false,
)
.unwrap();
s.attach_receipt(
None,
&format!("f{n}.txt"),
"text/plain",
format!("receipt number {n}").as_bytes(),
None,
)
.unwrap();
}
fn cut(dir: &Path, s: &Store) -> Cut {
Cut::take("acme", dir, s.head()).unwrap()
}
fn plain(folder: &Path) -> Destination {
Destination {
folder: folder.to_path_buf(),
key: None,
}
}
/// Every file under `root`, by relative path, with its bytes.
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for e in std::fs::read_dir(dir).unwrap() {
let p = e.unwrap().path();
if p.is_dir() {
walk(base, &p, out);
} else {
let rel = p
.strip_prefix(base)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
out.insert(rel, std::fs::read(&p).unwrap());
}
}
}
let mut out = BTreeMap::new();
if root.is_dir() {
walk(root, root, &mut out);
}
out
}
/// Prove the backup at `source` and give the books it holds, built in a
/// scratch folder next to `root`.
fn prove(
source: &Path,
pass: Option<&str>,
root: &Path,
name: &str,
) -> Result<ledger_store::backup::Verified, BackupError> {
let found = find(source, pass, &Ctx::new())?;
verify_found(&found, &root.join(name), &Ctx::new())
}
#[test]
fn a_backup_is_the_book_and_proves_whole() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new);
assert_eq!(w.number, 1);
assert_eq!(w.head, s.head());
// The form on disk: a folder for the books, a read-me, one manifest,
// the journal as a segment, the stored file under its hash.
let t = tree(&disk);
let names: Vec<&String> = t.keys().collect();
assert!(
names.iter().any(|n| *n == "wanderbooks-acme/READ-ME.txt"),
"{names:?}"
);
assert!(
names
.iter()
.any(|n| *n == "wanderbooks-acme/manifests/000001.json")
);
assert!(
names
.iter()
.any(|n| n.starts_with("wanderbooks-acme/journal/000001-"))
);
assert!(
names
.iter()
.any(|n| n.starts_with("wanderbooks-acme/files/"))
);
assert!(!names.iter().any(|n| n.contains(".git")));
// Nothing new: no manifest.
let again = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(!again.new);
assert_eq!(again.number, 1);
assert_eq!(tree(&disk), t);
// Proven, and the books it holds are the book.
let v = prove(&disk, None, dir.path(), "v1").unwrap();
assert_eq!(v.head, s.head());
assert_eq!(v.blobs, 1);
assert_eq!(v.book.as_deref(), Some("acme"));
assert_eq!(
std::fs::read(v.tree.join("journal.jsonl")).unwrap(),
std::fs::read(b.join("journal.jsonl")).unwrap()
);
// More writes: a new manifest and new pieces; the old ones untouched.
more(&mut s, 1);
let w2 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert_eq!(w2.number, 2);
let t2 = tree(&disk);
for (name, bytes) in &t {
assert_eq!(t2.get(name), Some(bytes), "{name} must not change");
}
assert!(t2.len() > t.len());
let v2 = prove(&disk, None, dir.path(), "v2").unwrap();
assert_eq!(v2.head, s.head());
assert_eq!(v2.blobs, 2);
// No scratch file of ours is left behind.
assert!(!t2.keys().any(|n| n.contains(".wb-tmp-")));
}
#[test]
fn a_destination_of_other_books_or_another_history_is_never_written() {
let dir = tempfile::tempdir().unwrap();
let (b1, b2) = (dir.path().join("one"), dir.path().join("two"));
let (mut s1, s2) = (book(&b1), book(&b2));
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap();
let before = tree(&disk);
// The same id, another history (a different journal from the start).
assert_eq!(
write_destination(&plain(&disk), &cut(&b2, &s2), true, &Ctx::new()).unwrap_err(),
BackupError::Elsewhere
);
assert_eq!(tree(&disk), before);
// Books behind the destination: said, nothing written.
more(&mut s1, 1);
write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap();
let ahead = tree(&disk);
let b1_old = dir.path().join("one-old");
let _old = book(&b1_old);
let err =
write_destination(&plain(&disk), &cut(&b1_old, &_old), true, &Ctx::new()).unwrap_err();
assert!(
matches!(err, BackupError::Ahead(..) | BackupError::Elsewhere),
"{err:?}"
);
assert_eq!(tree(&disk), ahead);
}
#[test]
fn a_disk_that_is_gone_is_never_made_again_where_it_should_be() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let missing = dir.path().join("nodisk");
assert_eq!(
write_destination(&plain(&missing), &cut(&b, &s), true, &Ctx::new()).unwrap_err(),
BackupError::NoFolder
);
// A mount point with nothing on it: the folder is there, the books'
// backup is not, and the caller says it never made one here.
let mount = dir.path().join("mount");
std::fs::create_dir(&mount).unwrap();
assert_eq!(
write_destination(&plain(&mount), &cut(&b, &s), false, &Ctx::new()).unwrap_err(),
BackupError::NoBackupThere
);
assert!(tree(&mount).is_empty());
}
#[test]
fn a_stopped_backup_leaves_what_proved_whole_before() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
more(&mut s, 1);
let stop = Arc::new(std::sync::atomic::AtomicBool::new(true));
let err = write_destination(
&plain(&disk),
&cut(&b, &s),
true,
&Ctx::new().with_stop(stop),
)
.unwrap_err();
assert!(matches!(err, BackupError::Cancelled(_)), "{err:?}");
let v = prove(&disk, None, dir.path(), "v").unwrap();
assert_eq!(v.number, 1);
}
// --- the passphrase --------------------------------------------------
const PASS: &str = "correct horse battery staple";
#[test]
fn a_sealed_backup_gives_away_counts_and_sizes_only() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let key = BackupKey::generate(PASS).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(key),
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
for (name, bytes) in tree(&disk) {
for word in [
"acme", "journal", "access", "vault", "keys", "blobs", "files", "receipt", "Cash",
] {
// The read-me is plain words and says nothing of the books;
// nothing else carries a word of them, in its name or in it.
if !name.ends_with("READ-ME.txt") {
assert!(!name.contains(word), "{name} names {word}");
assert!(
!String::from_utf8_lossy(&bytes).contains(word)
|| name.ends_with("header.json"),
"{name} holds {word}"
);
}
}
assert!(!bytes.windows(8).any(|w| w == b"PDF-1.4 "), "{name}");
}
// Opened with the passphrase: the same books.
let v = prove(&disk, Some(PASS), dir.path(), "v").unwrap();
assert_eq!(v.head, s.head());
assert!(v.key.is_some());
}
#[test]
fn a_wrong_passphrase_never_yields_books_and_is_told_from_damage() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(matches!(
find(&disk, None, &Ctx::new()),
Err(BackupError::NeedsPassphrase)
));
assert!(matches!(
find(&disk, Some("not the right words at all"), &Ctx::new()),
Err(BackupError::WrongPassphrase)
));
// A damaged header is damage, not a wrong passphrase.
let set = std::fs::read_dir(&disk)
.unwrap()
.flatten()
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
.unwrap()
.path();
let header = set.join("header.json");
let mut bytes = std::fs::read(&header).unwrap();
bytes[40] ^= 1;
std::fs::write(&header, &bytes).unwrap();
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
assert!(
matches!(err, BackupError::Damaged(_) | BackupError::NotABackup),
"{err:?}"
);
assert!(!dir.path().join("v").exists());
}
#[test]
fn a_changed_passphrase_is_a_new_set_beside_the_old_which_is_untouched() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let first = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
write_destination(&first, &cut(&b, &s), true, &Ctx::new()).unwrap();
let before = tree(&disk);
more(&mut s, 1);
// Another passphrase: found no set of its own, so (the caller says it
// may) a new one is made; the first is not touched.
let second = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate("an entirely different phrase").unwrap()),
};
write_destination(&second, &cut(&b, &s), true, &Ctx::new()).unwrap();
let after = tree(&disk);
for (name, bytes) in &before {
assert_eq!(after.get(name), Some(bytes), "{name}");
}
let sets: Vec<_> = std::fs::read_dir(&disk).unwrap().flatten().collect();
assert_eq!(sets.len(), 2);
// The old passphrase still opens the old set only when it is alone;
// with two sets, a passphrase opens the one that is its own.
let v = prove(&disk, Some("an entirely different phrase"), dir.path(), "v").unwrap();
assert_eq!(v.head, s.head());
}
#[test]
fn the_key_is_kept_privately_and_only_there() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let key = BackupKey::generate(PASS).unwrap();
key.store(&b).unwrap();
let loaded = BackupKey::load(&b).unwrap().expect("kept");
assert!(key.same_as(&loaded));
let file = b.join("local").join("backup-key.json");
let text = std::fs::read_to_string(&file).unwrap();
assert!(!text.contains(PASS));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let dir_mode = std::fs::metadata(file.parent().unwrap())
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(dir_mode, 0o700);
}
// Never in a backup: not the journal, not the folder of the backup.
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let raw = text
.lines()
.find(|l| l.contains("master"))
.unwrap()
.to_string();
let master = raw.split('"').nth(3).unwrap().to_string();
for (name, bytes) in tree(&disk) {
assert!(!String::from_utf8_lossy(&bytes).contains(&master), "{name}");
}
BackupKey::forget(&b).unwrap();
assert!(BackupKey::load(&b).unwrap().is_none());
}
// --- the single file -------------------------------------------------
#[test]
fn a_single_file_holds_the_same_backup_plain_or_sealed() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
for (pass, name) in [(None, "plain.wbbackup"), (Some(PASS), "sealed.wbbackup")] {
let key = pass.map(|p| BackupKey::generate(p).unwrap());
let file = dir.path().join(name);
let w = save_file(&file, &cut(&b, &s), key.as_ref(), &Ctx::new()).unwrap();
assert_eq!(w.head, s.head());
let v = prove(&file, pass, dir.path(), &format!("v-{name}")).unwrap();
assert_eq!(v.head, s.head());
assert_eq!(v.blobs, 1);
// A file by that name is not written over.
assert!(save_file(&file, &cut(&b, &s), key.as_ref(), &Ctx::new()).is_err());
}
assert!(matches!(
find(&dir.path().join("sealed.wbbackup"), None, &Ctx::new()),
Err(BackupError::NeedsPassphrase)
));
assert!(matches!(
find(
&dir.path().join("sealed.wbbackup"),
Some("a wrong passphrase here"),
&Ctx::new()
),
Err(BackupError::WrongPassphrase)
));
// Not a backup at all.
let junk = dir.path().join("junk.wbbackup");
std::fs::write(&junk, b"not a zip").unwrap();
assert!(matches!(
find(&junk, None, &Ctx::new()),
Err(BackupError::NotABackup)
));
}
// --- damage ------------------------------------------------------------
/// Every piece a manifest names, as paths under the set.
fn pieces(set: &Path) -> Vec<PathBuf> {
tree(set)
.keys()
.filter(|n| {
!n.starts_with("manifests/")
&& !n.starts_with("proofs/")
&& !n.ends_with("READ-ME.txt")
&& !n.ends_with("header.json")
})
.map(|n| set.join(n))
.collect()
}
#[test]
fn a_flipped_or_cut_piece_is_found_and_never_restored() {
for sealed in [false, true] {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let key = sealed.then(|| BackupKey::generate(PASS).unwrap());
let dest = Destination {
folder: disk.clone(),
key,
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
let pass = sealed.then_some(PASS);
// Found once (a sealed backup's key takes a moment to derive).
let found = find(&disk, pass, &Ctx::new()).unwrap();
let prove = |_: &Path, _: Option<&str>, root: &Path, name: &str| {
verify_found(&found, &root.join(name), &Ctx::new())
};
let set = std::fs::read_dir(&disk)
.unwrap()
.flatten()
.next()
.unwrap()
.path();
for piece in pieces(&set) {
let original = std::fs::read(&piece).unwrap();
for damage in 0..3 {
let mut bytes = original.clone();
match damage {
0 => {
let at = bytes.len() / 2;
bytes[at] ^= 0x01;
}
1 => bytes.truncate(bytes.len().saturating_sub(1)),
_ => bytes.clear(),
}
std::fs::write(&piece, &bytes).unwrap();
let scratch = format!("v-{damage}");
let got = prove(&disk, pass, dir.path(), &scratch);
assert!(
got.is_err(),
"{} damage {damage} of {piece:?} was restored",
if sealed { "sealed" } else { "plain" }
);
assert!(!dir.path().join(&scratch).exists(), "scratch left");
}
std::fs::write(&piece, &original).unwrap();
}
// Whole again once put back.
prove(&disk, pass, dir.path(), "ok").unwrap();
// A manifest cut short or changed is no manifest.
let manifest = tree(&set)
.keys()
.find(|n| n.starts_with("manifests/"))
.cloned()
.unwrap();
let mpath = set.join(&manifest);
let original = std::fs::read(&mpath).unwrap();
std::fs::write(&mpath, &original[..original.len() / 2]).unwrap();
assert!(prove(&disk, pass, dir.path(), "cut").is_err());
std::fs::write(&mpath, &original).unwrap();
}
}
#[test]
fn a_damaged_newest_backup_falls_back_to_the_one_before_and_says_so() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let first_head = s.head();
more(&mut s, 1);
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
// Flip a byte in the second journal segment.
let seg = tree(&disk.join("wanderbooks-acme"))
.keys()
.filter(|n| n.starts_with("journal/"))
.max()
.cloned()
.unwrap();
let path = disk.join("wanderbooks-acme").join(&seg);
let mut bytes = std::fs::read(&path).unwrap();
bytes[3] ^= 1;
std::fs::write(&path, bytes).unwrap();
let v = prove(&disk, None, dir.path(), "v").unwrap();
assert_eq!(v.number, 1);
assert_eq!(v.passed_over, 1);
assert_eq!(v.head, first_head);
}
// --- death at every write point --------------------------------------
#[test]
fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let base_disk = dir.path().join("base");
std::fs::create_dir(&base_disk).unwrap();
write_destination(
&plain(&base_disk),
&cut(&b, &s),
true,
&Ctx::new().with_proof_skipped(),
)
.unwrap();
let first_head = s.head();
more(&mut s, 1);
let c = cut(&b, &s);
// How many write points a whole second backup has.
let counted = Arc::new(AtomicUsize::new(0));
let probe = {
let disk = dir.path().join("probe");
copy_tree(&base_disk, &disk);
let n = counted.clone();
let ctx = Ctx::new()
.with_proof_skipped()
.with_faults(Arc::new(move |_, _| {
n.fetch_add(1, Ordering::SeqCst);
false
}));
write_destination(&plain(&disk), &c, true, &ctx).unwrap();
counted.load(Ordering::SeqCst)
};
assert!(probe >= 6, "a second backup has several writes: {probe}");
for die_at in 0..probe {
let disk = dir.path().join(format!("died-{die_at}"));
copy_tree(&base_disk, &disk);
let n = Arc::new(AtomicUsize::new(0));
let ctx = {
let n = n.clone();
Ctx::new()
.with_proof_skipped()
.with_faults(Arc::new(move |_, _| {
n.fetch_add(1, Ordering::SeqCst) == die_at
}))
};
let err = write_destination(&plain(&disk), &c, true, &ctx).unwrap_err();
assert_eq!(err, BackupError::Died, "point {die_at}");
// What is left proves whole at the previous manifest, never a
// half-written one (before the manifest was in place), or at the
// new one (after).
let v = prove(&disk, None, dir.path(), &format!("r-{die_at}")).unwrap();
assert!(
v.head == first_head || v.head == s.head(),
"point {die_at}: head {:?}",
v.head
);
// A restore from what is left is a prefix of the books.
let restored = std::fs::read(v.tree.join("journal.jsonl")).unwrap();
let live = std::fs::read(b.join("journal.jsonl")).unwrap();
assert!(live.starts_with(&restored), "point {die_at}");
// And the next run goes on from it (proven again at some points:
// each proof replays the books).
let w =
write_destination(&plain(&disk), &c, true, &Ctx::new().with_proof_skipped()).unwrap();
assert_eq!(w.head, s.head());
if die_at % 6 == 0 {
let again = prove(&disk, None, dir.path(), &format!("again-{die_at}")).unwrap();
assert_eq!(again.head, s.head());
}
}
}
fn copy_tree(from: &Path, to: &Path) {
for (rel, bytes) in tree(from) {
let p = to.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, bytes).unwrap();
}
std::fs::create_dir_all(to).unwrap();
}
// --- two writers -------------------------------------------------------
#[test]
fn two_programs_writing_one_destination_do_not_corrupt_it() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
for round in 0..3 {
more(&mut s, round);
let c = cut(&b, &s);
let results: Vec<_> = std::thread::scope(|scope| {
let handles: Vec<_> = (0..3)
.map(|_| {
let (c, disk) = (c.clone(), disk.clone());
scope.spawn(move || write_destination(&plain(&disk), &c, true, &Ctx::new()))
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
for r in &results {
let w = r
.as_ref()
.unwrap_or_else(|e| panic!("round {round}: {e:?}"));
assert_eq!(w.head, s.head());
}
// However they interleaved: whole, at these books, and every
// manifest there stands alone.
let v = prove(&disk, None, dir.path(), &format!("v{round}")).unwrap();
assert_eq!(v.head, s.head());
let set = disk.join("wanderbooks-acme");
for n in std::fs::read_dir(set.join("manifests")).unwrap().flatten() {
assert!(n.file_name().to_string_lossy().ends_with(".json"));
}
}
}
#[test]
fn a_loser_of_a_manifest_number_goes_on_from_the_winner() {
// Another program takes the next number between this one's look and its
// write: this one looks again and finds nothing left to write.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let c = cut(&b, &s);
let rival_disk = disk.clone();
let rival_cut = c.clone();
let done = Arc::new(AtomicUsize::new(0));
let ctx = {
let done = done.clone();
Ctx::new().with_faults(Arc::new(move |kind, rel| {
// Just before this writer's manifest, the rival writes its own.
if kind == "create"
&& rel.starts_with("manifests/")
&& done.fetch_add(1, Ordering::SeqCst) == 0
{
write_destination(&plain(&rival_disk), &rival_cut, true, &Ctx::new()).unwrap();
}
false
}))
};
let w = write_destination(&plain(&disk), &c, true, &ctx).unwrap();
assert_eq!(w.head, s.head());
assert!(!w.new, "the winner's manifest already says it");
assert_eq!(
std::fs::read_dir(disk.join("wanderbooks-acme/manifests"))
.unwrap()
.count(),
1
);
prove(&disk, None, dir.path(), "v").unwrap();
}
// --- what the store reads of a backup -----------------------------------
#[test]
fn the_text_read_from_a_stored_file_is_a_stored_file_too() {
// The store's own verification reads the text an extraction recorded as
// a stored file; a backup that left it out would not prove whole, so it
// is carried and proven with the rest.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let (attachment, _, _) = s
.attach_receipt(
None,
"words.txt",
"text/plain",
b"a receipt with words",
None,
)
.unwrap();
s.extract_attachment(attachment).unwrap();
let text_sha = s
.extraction(attachment)
.unwrap()
.and_then(|x| x.text_sha256)
.expect("the text is a stored file");
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let v = prove(&disk, None, dir.path(), "v").unwrap();
assert!(
v.tree
.join("blobs")
.join(&text_sha[0..2])
.join(&text_sha[2..4])
.join(&text_sha)
.is_file()
);
assert_eq!(v.head, s.head());
}
// --- what the removed tests of the old form protected ------------------------
#[test]
fn a_purged_vault_leaves_the_next_backup_and_not_the_earlier_ones() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
std::fs::create_dir_all(b.join("vault")).unwrap();
std::fs::write(b.join("vault").join("tin-1.bin"), b"sealed record").unwrap();
std::fs::create_dir_all(b.join("keys")).unwrap();
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
// The vault is purged to nothing: the next backup holds none, the
// earlier one still does (nothing in a destination is deleted).
std::fs::remove_file(b.join("vault").join("tin-1.bin")).unwrap();
std::fs::remove_dir(b.join("vault")).unwrap();
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new && w.number == 2, "{w:?}");
let now = prove(&disk, None, dir.path(), "now").unwrap();
assert!(!now.tree.join("vault").exists());
assert_eq!(
std::fs::read_to_string(now.tree.join("keys").join("legacy.key")).unwrap(),
"ab".repeat(32)
);
let then = dir.path().join("then");
copy_tree(&disk, &then);
std::fs::remove_file(then.join("wanderbooks-acme/manifests/000002.json")).unwrap();
let old = prove(&then, None, dir.path(), "old").unwrap();
assert_eq!(
std::fs::read(old.tree.join("vault").join("tin-1.bin")).unwrap(),
b"sealed record"
);
}
#[test]
fn a_scratch_file_left_by_a_dead_program_never_stops_the_next_backup() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
// What a program that died leaves: a scratch file, a short manifest at
// the next number (its number is spent), a piece cut short.
let set = disk.join("wanderbooks-acme");
std::fs::write(set.join("manifests").join(".wb-tmp-9-abcdef"), b"half").unwrap();
std::fs::write(
set.join("manifests").join("000002.json"),
b"{\"format\":\"wan",
)
.unwrap();
more(&mut s, 1);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new && w.number == 3, "{w:?}");
let v = prove(&disk, None, dir.path(), "v").unwrap();
assert_eq!(v.head, s.head());
}
#[test]
fn a_stored_file_that_does_not_match_its_name_is_refused_and_nothing_is_written() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let sha = ledger_store::journal::sha256_hex(b"%PDF-1.4 r");
let blob = b.join("blobs").join(&sha[0..2]).join(&sha[2..4]).join(&sha);
std::fs::write(&blob, b"changed under its name").unwrap();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let err = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err();
assert!(matches!(err, BackupError::Damaged(_)), "{err:?}");
// No manifest: nothing there is a backup.
assert!(
!tree(&disk)
.keys()
.any(|n| n.contains("manifests/") && n.ends_with(".json"))
);
}
#[test]
fn a_drill_proves_this_books_history_only() {
use ledger_store::backup::drill;
let dir = tempfile::tempdir().unwrap();
let (b1, b2) = (dir.path().join("one"), dir.path().join("two"));
let (mut s1, s2) = (book(&b1), book(&b2));
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap();
let head = s1.head();
// The books move on: the backup is the beginning of their journal.
more(&mut s1, 1);
let got = drill(
&plain(&disk),
"acme",
&b1.join("journal.jsonl"),
&dir.path().join("d1"),
None,
&Ctx::new(),
)
.unwrap();
assert_eq!(got, head);
assert!(!dir.path().join("d1").exists(), "the scratch is removed");
// Another book's history under the same name: not this book's.
let err = drill(
&plain(&disk),
"acme",
&b2.join("journal.jsonl"),
&dir.path().join("d2"),
None,
&Ctx::new(),
)
.unwrap_err();
assert!(
matches!(err, BackupError::Damaged(_)),
"{err:?} {:?}",
s2.head()
);
assert!(!dir.path().join("d2").exists());
}
#[test]
fn the_local_backup_proves_to_hold_the_book_as_it_is_keys_and_all() {
use ledger_store::backup::{prove_local, write_local};
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
std::fs::create_dir_all(b.join("keys")).unwrap();
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
let scratch = dir.path().join("check");
let c = cut(&b, &s);
write_local(&b, &c, &Ctx::new()).unwrap();
assert_eq!(
prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).unwrap(),
1
);
assert!(!scratch.exists(), "the scratch folder is removed");
// A changed key, a changed vault record, an extra one, books that moved
// on, each refused.
std::fs::write(b.join("keys").join("legacy.key"), "cd".repeat(32)).unwrap();
assert!(prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).is_err());
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
std::fs::create_dir_all(b.join("vault")).unwrap();
std::fs::write(b.join("vault").join("tin-2.bin"), b"extra").unwrap();
assert!(prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).is_err());
std::fs::remove_file(b.join("vault").join("tin-2.bin")).unwrap();
more(&mut s, 1);
assert!(prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).is_err());
// Written again, it proves the books as they are now.
write_local(&b, &cut(&b, &s), &Ctx::new()).unwrap();
prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).unwrap();
assert!(!scratch.exists());
}
#[cfg(unix)]
#[test]
fn a_link_in_a_backup_is_never_followed() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
// The journal's piece replaced by a link to a file elsewhere with the
// same bytes: it is no piece of the backup.
let set = disk.join("wanderbooks-acme");
let piece = std::fs::read_dir(set.join("journal"))
.unwrap()
.next()
.unwrap()
.unwrap()
.path();
let elsewhere = dir.path().join("elsewhere");
std::fs::copy(&piece, &elsewhere).unwrap();
std::fs::remove_file(&piece).unwrap();
std::os::unix::fs::symlink(&elsewhere, &piece).unwrap();
assert!(prove(&disk, None, dir.path(), "v").is_err());
}
#[test]
fn a_drill_stops_inside_the_phase_it_is_told_to_stop_in() {
use ledger_store::backup::drill;
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
// The phases a drill goes through; a stop asked as each begins ends the
// drill there (the observer sees no later phase), scratch removed.
let phases = ["fetch", "replay", "verify", "blobs", "vault", "prefix"];
for stop_at in phases {
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let ctx = {
let (stop, seen) = (stop.clone(), seen.clone());
Ctx::new()
.with_stop(stop.clone())
.with_phase_watch(Arc::new(move |p: &str| {
seen.lock().unwrap().push(p.to_string());
if p == stop_at {
stop.store(true, Ordering::SeqCst);
}
}))
};
let scratch = dir.path().join(format!("d-{stop_at}"));
let got = drill(
&plain(&disk),
"acme",
&b.join("journal.jsonl"),
&scratch,
None,
&ctx,
);
assert!(
matches!(got, Err(BackupError::Cancelled(_))),
"{stop_at}: {got:?}"
);
let seen = seen.lock().unwrap().clone();
assert_eq!(seen.last().map(String::as_str), Some(stop_at), "{seen:?}");
assert!(!scratch.exists(), "{stop_at}: scratch left");
}
}
+473
View File
@@ -0,0 +1,473 @@
//! Backups onto the disks people really have (WB-backup-18 to WB-backup-22):
//! a disk that makes no hard links (FAT or exFAT on a stick), sealed pieces
//! in folders a small disk can hold, a header that asks for more than it
//! should, and a folder a sync service has not finished putting on this
//! computer.
use ledger_core::{AccountType, Currency, Money, Side};
use ledger_store::Store;
use ledger_store::backup::{
BackupError, BackupKey, Ctx, Cut, Destination, Options, find, key_derivations, verify_found,
write_destination, write_destination_with,
};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
fn usd(s: &str) -> Money {
Money::new(s.parse().unwrap(), Currency::USD)
}
fn book(dir: &Path) -> Store {
let mut s = Store::create(dir, Currency::USD).unwrap();
let cash = s
.add_account("1000", "Cash", AccountType::Asset, None, false)
.unwrap();
let cap = s
.add_account("3000", "Capital", AccountType::Equity, None, false)
.unwrap();
let e = s
.create_entry(
chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(),
"Start",
)
.unwrap();
s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap();
s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap();
s.post_entry(e).unwrap();
s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None)
.unwrap();
s
}
fn more(s: &mut Store, n: usize) {
s.add_account(
&format!("{}", 6000 + n),
&format!("Expense {n}"),
AccountType::Expense,
None,
false,
)
.unwrap();
s.attach_receipt(
None,
&format!("f{n}.txt"),
"text/plain",
format!("receipt number {n}").as_bytes(),
None,
)
.unwrap();
}
fn cut(dir: &Path, s: &Store) -> Cut {
Cut::take("acme", dir, s.head()).unwrap()
}
fn plain(folder: &Path) -> Destination {
Destination {
folder: folder.to_path_buf(),
key: None,
}
}
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for e in std::fs::read_dir(dir).unwrap() {
let p = e.unwrap().path();
if p.is_dir() {
walk(base, &p, out);
} else {
let rel = p
.strip_prefix(base)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
out.insert(rel, std::fs::read(&p).unwrap());
}
}
}
let mut out = BTreeMap::new();
if root.is_dir() {
walk(root, root, &mut out);
}
out
}
fn prove(
source: &Path,
pass: Option<&str>,
root: &Path,
name: &str,
) -> ledger_store::backup::Verified {
let found = find(source, pass, &Ctx::new()).unwrap();
verify_found(&found, &root.join(name), &Ctx::new()).unwrap()
}
// --- a disk that makes no hard links ---------------------------------------
#[test]
fn a_disk_that_makes_no_links_takes_whole_backups_and_only_grows() {
for ctx in [
Ctx::new().with_no_hard_links(),
// And one whose move cannot refuse to replace either: exclusive
// create and copy.
Ctx::new().with_no_exclusive_move(),
] {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let mut before = BTreeMap::new();
for n in 0..3 {
more(&mut s, n);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap();
assert!(w.new && w.repaired.is_empty(), "{w:?}");
let now = tree(&disk);
for (name, bytes) in &before {
assert_eq!(now.get(name), Some(bytes), "{name} must not change");
}
assert!(!now.keys().any(|n| n.contains(".wb-tmp-")), "scratch left");
before = now;
}
let v = prove(&disk, None, dir.path(), "v");
assert_eq!(v.head, s.head());
assert_eq!(v.passed_over, 0);
}
}
#[test]
fn two_writers_racing_on_a_disk_that_makes_no_links_do_not_corrupt_it() {
for exclusive_move_missing in [false, true] {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
for round in 0..3 {
more(&mut s, round);
let c = cut(&b, &s);
let results: Vec<_> = std::thread::scope(|scope| {
let handles: Vec<_> = (0..3)
.map(|_| {
let (c, disk) = (c.clone(), disk.clone());
scope.spawn(move || {
let ctx = if exclusive_move_missing {
Ctx::new().with_no_exclusive_move()
} else {
Ctx::new().with_no_hard_links()
};
write_destination(&plain(&disk), &c, true, &ctx)
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
for r in &results {
let w = r
.as_ref()
.unwrap_or_else(|e| panic!("round {round}: {e:?}"));
assert_eq!(w.head, s.head());
}
let v = prove(&disk, None, dir.path(), &format!("v{round}"));
assert_eq!(v.head, s.head());
assert_eq!(v.passed_over, 0, "round {round}");
assert!(
!tree(&disk).keys().any(|n| n.contains(".wb-tmp-")),
"scratch left"
);
}
}
}
#[test]
fn a_taken_number_or_name_is_never_replaced_on_a_disk_that_makes_no_links() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let ctx = Ctx::new().with_no_hard_links();
write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap();
let set = disk.join("wanderbooks-acme");
// A rival's manifest 2 is already in place when this one comes to put
// its own as number 2.
more(&mut s, 1);
let rival = disk.join("rival");
std::fs::create_dir(&rival).unwrap();
let c = cut(&b, &s);
let taken = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let hook = {
let (set, taken) = (set.clone(), taken.clone());
Ctx::new()
.with_no_hard_links()
.with_faults(std::sync::Arc::new(move |kind, rel| {
if kind == "create"
&& rel.starts_with("manifests/")
&& taken.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0
{
std::fs::write(set.join("manifests/000002.json"), b"a rival's, whole").unwrap();
}
false
}))
};
let _ = write_destination(&plain(&disk), &c, true, &hook);
assert_eq!(
std::fs::read(set.join("manifests/000002.json")).unwrap(),
b"a rival's, whole",
"the manifest that was there is never replaced"
);
}
// --- sealed pieces in folders a small disk can hold --------------------------
const PASS: &str = "correct horse battery staple";
/// The count of derived keys is the process's: the tests that read it, and
/// every test that derives one, take turns.
static KEYS: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn one_at_a_time() -> std::sync::MutexGuard<'static, ()> {
KEYS.lock().unwrap_or_else(|e| e.into_inner())
}
#[test]
fn sealed_pieces_are_spread_over_folders_as_the_plain_form_does() {
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
for n in 0..30 {
more(&mut s, n);
}
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
let set = std::fs::read_dir(&disk)
.unwrap()
.flatten()
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
.unwrap()
.path();
let mut in_folders = 0usize;
for entry in std::fs::read_dir(set.join("pieces")).unwrap().flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
assert!(
entry.path().is_dir(),
"{name}: a piece sits in a flat folder"
);
assert_eq!(name.len(), 2, "{name}");
for piece in std::fs::read_dir(entry.path()).unwrap().flatten() {
assert!(
piece.file_name().to_string_lossy().starts_with(&name),
"a piece is in the folder of its name's first two digits"
);
in_folders += 1;
}
}
assert!(in_folders > 30, "{in_folders}");
let v = prove(&disk, Some(PASS), dir.path(), "v");
assert_eq!(v.head, s.head());
}
// --- a header that is read from a folder anyone may have written -------------
/// The sealed set's folder in `disk`.
fn sealed_set(disk: &Path) -> PathBuf {
std::fs::read_dir(disk)
.unwrap()
.flatten()
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
.unwrap()
.path()
}
/// Rewrite the header's key settings and make its own check line right
/// again (what a person who meant to would do).
fn set_header(header: &Path, edit: impl Fn(&mut serde_json::Value)) {
let text = std::fs::read_to_string(header).unwrap();
let body = text.lines().next().unwrap();
let mut v: serde_json::Value = serde_json::from_str(body).unwrap();
edit(&mut v);
let body = serde_json::to_string(&v).unwrap();
let check = hex::encode(Sha256::digest(body.as_bytes()));
std::fs::write(
header,
format!("{body}\nwanderbooks-header-sha256 {check}\n"),
)
.unwrap();
}
#[test]
fn a_header_cannot_ask_for_more_than_a_few_times_what_this_program_spends() {
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
let header = sealed_set(&disk).join("header.json");
let original = std::fs::read(&header).unwrap();
for (what, value) in [
("m", serde_json::json!(4_000_000u32)),
("m", serde_json::json!(64 * 1024 * 5)),
("t", serde_json::json!(13)),
("p", serde_json::json!(5)),
] {
set_header(&header, |v| v["kdf"][what] = value.clone());
let derived = key_derivations();
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
// Refused as damage before any key is derived: no memory spent.
assert!(
matches!(err, BackupError::Damaged(_) | BackupError::NotABackup),
"{what}: {err:?}"
);
assert_eq!(key_derivations(), derived, "{what}: a key was derived");
}
std::fs::write(&header, &original).unwrap();
let v = prove(&disk, Some(PASS), dir.path(), "v");
assert_eq!(v.head, s.head());
}
#[test]
fn a_header_that_was_changed_reads_as_damage_and_not_as_a_wrong_passphrase() {
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
let header = sealed_set(&disk).join("header.json");
// A setting changed in the file as a bad sector or a bad sync would:
// the header's own check line no longer matches.
let text = std::fs::read_to_string(&header).unwrap();
let changed = text.replacen("\"t\":3", "\"t\":4", 1);
assert_ne!(text, changed, "the header names its passes");
std::fs::write(&header, changed).unwrap();
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
assert!(
matches!(err, BackupError::Damaged(_) | BackupError::NotABackup),
"{err:?}"
);
// Changed on purpose and made consistent again: the key comes out
// different and opens nothing (the safe way to fail), and no
// passphrase is guessed any faster.
std::fs::write(&header, &text).unwrap();
set_header(&header, |v| v["kdf"]["t"] = serde_json::json!(4));
assert!(matches!(
find(&disk, Some(PASS), &Ctx::new()),
Err(BackupError::WrongPassphrase)
));
}
#[test]
fn a_folder_of_sealed_sets_costs_one_key_derivation_per_setting_not_one_per_set() {
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate(PASS).unwrap()),
};
let c = cut(&b, &s);
write_destination(&dest, &c, true, &Ctx::new()).unwrap();
for _ in 0..2 {
write_destination_with(
&dest,
&c,
Options {
may_create: true,
new_set: true,
},
&Ctx::new(),
)
.unwrap();
}
let sets = std::fs::read_dir(&disk)
.unwrap()
.flatten()
.filter(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
.count();
assert_eq!(sets, 3);
let derived = key_derivations();
// Three sets of one book: it asks which, after one derivation.
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
assert!(matches!(err, BackupError::Several(_)), "{err:?}");
assert_eq!(key_derivations() - derived, 1);
}
// --- files a sync service has not downloaded ---------------------------------
#[test]
fn a_file_that_is_not_downloaded_yet_reads_as_such_and_never_as_damage_or_absence() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let set = disk.join("wanderbooks-acme");
let before = tree(&disk);
// A piece of the newest backup that iCloud has left as a stand-in
// (`.name.icloud`) in its place.
let manifest = std::fs::read_to_string(set.join("manifests/000001.json")).unwrap();
let m: serde_json::Value = serde_json::from_str(manifest.lines().next().unwrap()).unwrap();
let seg = set.join(m["journal"]["segments"][0]["file"].as_str().unwrap());
let stand_in = seg.with_file_name(format!(
".{}.icloud",
seg.file_name().unwrap().to_string_lossy()
));
let held = std::fs::read(&seg).unwrap();
std::fs::rename(&seg, &stand_in).unwrap();
let found = find(&disk, None, &Ctx::new());
// Nothing says "damaged", nothing says "not a backup": it is waiting.
assert_eq!(found.err(), Some(BackupError::NotDownloaded));
more(&mut s, 1);
assert_eq!(
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err(),
BackupError::NotDownloaded
);
assert!(
BackupError::NotDownloaded
.to_string()
.contains("not downloaded to this computer yet")
);
// Downloaded: all as it was.
std::fs::rename(&stand_in, &seg).unwrap();
assert_eq!(std::fs::read(&seg).unwrap(), held);
assert_eq!(tree(&disk), before);
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
// The newest manifest as a stand-in: the folder is listed with it, and
// the writer will not make a manifest under its number.
let newest = set.join("manifests/000002.json");
let stand = set.join("manifests/.000002.json.icloud");
std::fs::rename(&newest, &stand).unwrap();
more(&mut s, 2);
assert_eq!(
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err(),
BackupError::NotDownloaded
);
assert_eq!(
find(&disk, None, &Ctx::new()).err(),
Some(BackupError::NotDownloaded)
);
}
+341
View File
@@ -0,0 +1,341 @@
//! Backups as properties (WB-backup-1 to WB-backup-7): random books and
//! random sequences of backups, interleavings of two writers, damage to any
//! piece, and passphrases that are not the right one. Each case builds a
//! book, which is the cost; the cases are few and the oracles are the laws.
use ledger_core::{AccountType, Currency};
use ledger_store::Store;
use ledger_store::backup::{
BackupError, BackupKey, Ctx, Cut, Destination, find, verify_found, write_destination,
};
use proptest::prelude::*;
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
/// One thing that happens to the books between backups.
#[derive(Clone, Debug)]
enum Op {
/// A new account.
Account,
/// A stored file of these bytes (the same bytes twice are one file).
File(Vec<u8>),
/// A backup.
Backup,
}
fn ops() -> impl Strategy<Value = Vec<Op>> {
prop::collection::vec(
prop_oneof![
2 => Just(Op::Account),
2 => prop::collection::vec(any::<u8>(), 1..40).prop_map(Op::File),
3 => Just(Op::Backup),
],
2..9,
)
}
/// A context for tests of logic, not of durability: nothing is synced.
fn fast() -> Ctx {
// The proof after a backup has tests of its own (backup_repair.rs); the
// properties here prove what they make by restoring it.
Ctx::new().with_no_sync().with_proof_skipped()
}
fn plain(folder: &Path) -> Destination {
Destination {
folder: folder.to_path_buf(),
key: None,
}
}
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for e in std::fs::read_dir(dir).unwrap() {
let p = e.unwrap().path();
if p.is_dir() {
walk(base, &p, out);
} else {
let rel = p
.strip_prefix(base)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
out.insert(rel, std::fs::read(&p).unwrap());
}
}
}
let mut out = BTreeMap::new();
if root.is_dir() {
walk(root, root, &mut out);
}
out
}
fn copy_tree(from: &Path, to: &Path) {
std::fs::create_dir_all(to).unwrap();
for (rel, bytes) in tree(from) {
let p = to.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, bytes).unwrap();
}
}
/// A book with one account, and a way to apply [`Op`]s to it.
struct Books {
store: Store,
dir: std::path::PathBuf,
n: usize,
}
impl Books {
fn new(dir: &Path) -> Self {
let mut store = Store::create(dir, Currency::USD).unwrap();
store
.add_account("1000", "Cash", AccountType::Asset, None, false)
.unwrap();
Self {
store,
dir: dir.to_path_buf(),
n: 0,
}
}
fn apply(&mut self, op: &Op) {
match op {
Op::Account => {
self.n += 1;
self.store
.add_account(
&format!("{}", 6000 + self.n),
&format!("Expense {}", self.n),
AccountType::Expense,
None,
false,
)
.unwrap();
}
Op::File(bytes) => {
self.store
.attach_receipt(None, "f.bin", "application/octet-stream", bytes, None)
.unwrap();
}
Op::Backup => {}
}
}
fn cut(&self) -> Cut {
Cut::take("acme", &self.dir, self.store.head()).unwrap()
}
}
fn prove(
folder: &Path,
pass: Option<&str>,
scratch: &Path,
) -> Result<ledger_store::backup::Verified, BackupError> {
let found = find(folder, pass, &Ctx::new())?;
verify_found(&found, scratch, &Ctx::new())
}
fn config() -> ProptestConfig {
ProptestConfig {
cases: 5,
max_shrink_iters: 4,
failure_persistence: None,
..ProptestConfig::default()
}
}
proptest! {
#![proptest_config(config())]
/// WB-backup-1: whatever the books do and whenever they are backed up,
/// every file the destination held is still there, byte for byte.
#[test]
fn a_destination_only_grows(ops in ops()) {
let dir = tempfile::tempdir().unwrap();
let mut books = Books::new(&dir.path().join("book"));
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let mut before = tree(&disk);
for op in &ops {
books.apply(op);
if matches!(op, Op::Backup) {
write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
let after = tree(&disk);
for (name, bytes) in &before {
prop_assert_eq!(after.get(name), Some(bytes), "{} changed or went", name);
}
prop_assert!(!after.keys().any(|n| n.contains(".wb-tmp-")));
before = after;
}
}
}
/// WB-backup-3: the destination as of any of its manifests restores to
/// books whose journal is byte-identical to the beginning of the
/// books' journal now, and whose head is the one that manifest names.
#[test]
fn any_whole_manifest_restores_a_prefix_of_the_books(ops in ops()) {
let dir = tempfile::tempdir().unwrap();
let mut books = Books::new(&dir.path().join("book"));
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let mut heads = Vec::new();
for op in &ops {
books.apply(op);
if matches!(op, Op::Backup) {
let w = write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
if w.new {
heads.push((w.number, w.head));
}
}
}
// (A last backup, so there is at least one.)
let w = write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
if w.new {
heads.push((w.number, w.head));
}
let live = std::fs::read(dir.path().join("book").join("journal.jsonl")).unwrap();
for (number, head) in &heads {
// The destination as it was when that manifest was the newest.
let then = dir.path().join(format!("then-{number}"));
copy_tree(&disk, &then);
for (name, _) in tree(&then) {
if let Some(n) = name
.strip_prefix("wanderbooks-acme/manifests/")
.and_then(|r| r.strip_suffix(".json"))
.and_then(|r| r.parse::<u64>().ok())
&& n > *number
{
std::fs::remove_file(then.join(&name)).unwrap();
}
}
let v = prove(&then, None, &dir.path().join(format!("v-{number}"))).unwrap();
prop_assert_eq!(&v.head, head);
let restored = std::fs::read(v.tree.join("journal.jsonl")).unwrap();
prop_assert!(live.starts_with(&restored));
}
}
/// WB-backup-5: a writer that finds another writer's backup appear at
/// any of its write points (the other with books a little behind or a
/// little ahead) leaves a destination that proves whole, at the head
/// of one of them, restoring to a prefix of the longer books.
#[test]
fn random_interleavings_of_two_writers_leave_a_whole_backup(
files in prop::collection::vec(prop::collection::vec(any::<u8>(), 1..20), 1..3),
rival_after in 0usize..3,
at in 0usize..14,
) {
let dir = tempfile::tempdir().unwrap();
let mut books = Books::new(&dir.path().join("book"));
for f in &files {
books.apply(&Op::File(f.clone()));
}
let first = books.cut();
for _ in 0..rival_after {
books.apply(&Op::Account);
}
let second = books.cut();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
// The writer of `first` is met, at its `at`th write point, by a
// complete write of `second`.
let count = Arc::new(AtomicUsize::new(0));
let rival = {
let (disk, second, count) = (disk.clone(), second.clone(), count.clone());
fast().with_faults(Arc::new(move |_, _| {
if count.fetch_add(1, Ordering::SeqCst) == at {
write_destination(
&plain(&disk),
&second,
true,
&fast(),
)
.unwrap();
}
false
}))
};
let mine = write_destination(&plain(&disk), &first, true, &rival);
match mine {
Ok(_) | Err(BackupError::Ahead(..)) | Err(BackupError::Elsewhere) => {}
Err(e) => prop_assert!(false, "{e:?}"),
}
let v = prove(&disk, None, &dir.path().join("v")).unwrap();
prop_assert!(v.head == *first.head() || v.head == *second.head());
let live = std::fs::read(dir.path().join("book").join("journal.jsonl")).unwrap();
prop_assert!(live.starts_with(&std::fs::read(v.tree.join("journal.jsonl")).unwrap()));
}
/// WB-backup-6: a piece with one byte flipped, or cut anywhere, is
/// found: the backup that names it is not restored.
#[test]
fn any_flipped_or_cut_piece_is_found_never_restored(
ops in ops(),
pick in any::<prop::sample::Index>(),
at in any::<prop::sample::Index>(),
cut in any::<bool>(),
) {
let dir = tempfile::tempdir().unwrap();
let mut books = Books::new(&dir.path().join("book"));
books.apply(&Op::File(vec![1, 2, 3, 4]));
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
for op in &ops {
books.apply(op);
}
write_destination(
&plain(&disk),
&books.cut(),
true,
&fast(),
)
.unwrap();
let set = disk.join("wanderbooks-acme");
let pieces: Vec<String> = tree(&set)
.into_keys()
.filter(|n| {
!n.starts_with("manifests/") && !n.starts_with("proofs/") && n != "READ-ME.txt"
})
.collect();
let name = &pieces[pick.index(pieces.len())];
let path = set.join(name);
let mut bytes = std::fs::read(&path).unwrap();
prop_assume!(!bytes.is_empty());
let i = at.index(bytes.len());
if cut {
bytes.truncate(i);
} else {
bytes[i] ^= 0x01;
}
std::fs::write(&path, &bytes).unwrap();
let scratch = dir.path().join("v");
prop_assert!(prove(&disk, None, &scratch).is_err(), "{name} damaged was restored");
prop_assert!(!scratch.exists());
}
/// WB-backup-7: no passphrase but the right one gives books.
#[test]
fn a_wrong_passphrase_never_yields_books(wrong in "[a-zA-Z0-9 ]{1,30}") {
prop_assume!(wrong != "the right words, exactly");
let dir = tempfile::tempdir().unwrap();
let books = Books::new(&dir.path().join("book"));
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let dest = Destination {
folder: disk.clone(),
key: Some(BackupKey::generate("the right words, exactly").unwrap()),
};
write_destination(&dest, &books.cut(), true, &fast()).unwrap();
let scratch = dir.path().join("v");
let got = prove(&disk, Some(&wrong), &scratch);
prop_assert!(matches!(got, Err(BackupError::WrongPassphrase)), "{got:?}");
prop_assert!(!scratch.exists());
let none = prove(&disk, None, &scratch);
prop_assert!(matches!(none, Err(BackupError::NeedsPassphrase)));
}
}
+790
View File
@@ -0,0 +1,790 @@
//! A backup that restores old or wrong books while reporting good is the
//! worst defect this product can have (WB-backup-12 to WB-backup-17): a
//! damaged piece must not be reused by later backups, the drill must not
//! prove an older backup and say ok, a damaged piece must be found by the
//! proof after the backup and written again beside the damaged file, books
//! that are behind a destination must be told from books that have
//! diverged, and a restore must say when it is not of the newest backup.
use ledger_core::{AccountType, Currency, Money, Role, Side, TinFacts, TinType};
use ledger_store::Store;
use ledger_store::backup::{
BackupError, Ctx, Cut, Destination, Options, drill, find, verify_found, write_destination,
write_destination_with,
};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
fn usd(s: &str) -> Money {
Money::new(s.parse().unwrap(), Currency::USD)
}
fn book(dir: &Path) -> Store {
let mut s = Store::create(dir, Currency::USD).unwrap();
let cash = s
.add_account("1000", "Cash", AccountType::Asset, None, false)
.unwrap();
let cap = s
.add_account("3000", "Capital", AccountType::Equity, None, false)
.unwrap();
let e = s
.create_entry(
chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(),
"Start",
)
.unwrap();
s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap();
s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap();
s.post_entry(e).unwrap();
s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None)
.unwrap();
s
}
fn more(s: &mut Store, n: usize) {
s.add_account(
&format!("{}", 6000 + n),
&format!("Expense {n}"),
AccountType::Expense,
None,
false,
)
.unwrap();
s.attach_receipt(
None,
&format!("f{n}.txt"),
"text/plain",
format!("receipt number {n}").as_bytes(),
None,
)
.unwrap();
}
fn cut(dir: &Path, s: &Store) -> Cut {
Cut::take("acme", dir, s.head()).unwrap()
}
fn plain(folder: &Path) -> Destination {
Destination {
folder: folder.to_path_buf(),
key: None,
}
}
fn set_of(disk: &Path) -> PathBuf {
disk.join("wanderbooks-acme")
}
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for e in std::fs::read_dir(dir).unwrap() {
let p = e.unwrap().path();
if p.is_dir() {
walk(base, &p, out);
} else {
let rel = p
.strip_prefix(base)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
out.insert(rel, std::fs::read(&p).unwrap());
}
}
}
let mut out = BTreeMap::new();
if root.is_dir() {
walk(root, root, &mut out);
}
out
}
fn copy_tree(from: &Path, to: &Path) {
std::fs::create_dir_all(to).unwrap();
for e in std::fs::read_dir(from).unwrap() {
let e = e.unwrap();
let (src, dst) = (e.path(), to.join(e.file_name()));
if src.is_dir() {
copy_tree(&src, &dst);
} else {
std::fs::copy(&src, &dst).unwrap();
}
}
}
/// Flip one byte in the middle of a file, as a bad sector or a bad sync
/// would; the file keeps its length.
fn flip(path: &Path) {
let mut bytes = std::fs::read(path).unwrap();
let at = bytes.len() / 2;
bytes[at] ^= 0x55;
std::fs::write(path, bytes).unwrap();
}
/// The manifest `n` of the set, as JSON.
fn manifest(set: &Path, n: u64) -> serde_json::Value {
let text = std::fs::read_to_string(set.join(format!("manifests/{n:06}.json"))).unwrap();
serde_json::from_str(text.lines().next().unwrap()).unwrap()
}
/// The newest journal segment a manifest names (the one its backup added).
fn newest_journal_segment(set: &Path, n: u64) -> String {
manifest(set, n)["journal"]["segments"]
.as_array()
.unwrap()
.last()
.unwrap()["file"]
.as_str()
.unwrap()
.to_string()
}
fn sha(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
#[test]
fn one_damaged_segment_is_found_by_the_next_backup_and_the_drill_does_not_hide_it() {
// The reviewer's sequence: a byte flips in the segment backup 2 wrote;
// backups go on; a drill runs; a restore is made. Before: every later
// backup reused the damaged segment and was recorded good, the drill
// proved backup 1 and said ok, and a restore returned books from long
// ago.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let first_head = s.head();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
more(&mut s, 1);
let w2 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert_eq!(w2.number, 2);
assert!(w2.repaired.is_empty());
let seg = newest_journal_segment(&set_of(&disk), 2);
let damaged = set_of(&disk).join(&seg);
flip(&damaged);
let flipped = std::fs::read(&damaged).unwrap();
// The very next backup finds it (its proof re-hashes every journal
// segment its manifest names) and writes the piece again beside it.
more(&mut s, 2);
let w3 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w3.new);
assert_eq!(w3.repaired, vec![seg.clone()], "{w3:?}");
assert_eq!(
std::fs::read(&damaged).unwrap(),
flipped,
"the damaged file is left exactly where it is"
);
let again = set_of(&disk).join(format!("{seg}.g1"));
assert!(
again.is_file(),
"the piece is written again as generation 1"
);
assert_eq!(sha(&std::fs::read(&again).unwrap()), {
let m = manifest(&set_of(&disk), 2);
m["journal"]["segments"].as_array().unwrap().last().unwrap()["sha256"]
.as_str()
.unwrap()
.to_string()
});
// Many more backups: none reuses the damaged file, none finds more.
for n in 3..8 {
more(&mut s, n);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new && w.repaired.is_empty(), "{n}: {w:?}");
}
let last = s.head();
// The drill proves the newest backup, which reaches the live head.
let got = drill(
&plain(&disk),
"acme",
&b.join("journal.jsonl"),
&dir.path().join("drill"),
Some(&last),
&Ctx::new(),
)
.unwrap();
assert_eq!(got, last);
// A restore gives the newest books, not backup 1's.
let found = find(&disk, None, &Ctx::new()).unwrap();
let v = verify_found(&found, &dir.path().join("restore"), &Ctx::new()).unwrap();
assert_eq!(v.head, last);
assert_ne!(v.head, first_head);
assert_eq!(v.passed_over, 0);
// Manifests 1, 2, 3, the repair's (4) and the five after it.
assert_eq!(v.number, 9);
}
#[test]
fn a_drill_never_passes_on_an_older_backup() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
more(&mut s, 1);
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let second_head = s.head();
more(&mut s, 2);
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let newest_head = s.head();
// The newest backup's own segment is damaged after it was made, and no
// backup comes after it to find that.
flip(&set_of(&disk).join(newest_journal_segment(&set_of(&disk), 3)));
// The drill is a failure that says so, with the date of the older one.
let err = drill(
&plain(&disk),
"acme",
&b.join("journal.jsonl"),
&dir.path().join("drill"),
Some(&newest_head),
&Ctx::new(),
)
.unwrap_err();
let words = err.to_string();
match &err {
BackupError::NewestDamaged {
number,
older_from,
newest_from,
} => {
assert_eq!(*number, 3);
assert!(older_from.is_some() && newest_from.is_some(), "{err:?}");
}
other => panic!("{other:?}"),
}
assert!(words.contains("the newest backup (number 3"), "{words}");
assert!(words.contains("is damaged; an older one from "), "{words}");
assert!(!dir.path().join("drill").exists());
// A restore passes over it, and the preview can say so: both dates and
// how many it passes over.
let found = find(&disk, None, &Ctx::new()).unwrap();
let v = verify_found(&found, &dir.path().join("restore"), &Ctx::new()).unwrap();
assert_eq!(v.number, 2);
assert_eq!(v.head, second_head);
assert_eq!(v.passed_over, 1);
assert!(v.newest_written.is_some() && !v.written.is_empty());
// Everything damaged: no older one proves whole either, and it says so.
for n in [1u64, 2] {
flip(&set_of(&disk).join(newest_journal_segment(&set_of(&disk), n)));
}
let err = drill(
&plain(&disk),
"acme",
&b.join("journal.jsonl"),
&dir.path().join("drill2"),
None,
&Ctx::new(),
)
.unwrap_err();
assert!(
err.to_string().contains("no older one proves whole either"),
"{err}"
);
}
#[test]
fn a_drill_needs_the_newest_backup_to_reach_the_last_one_recorded_good() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let have = s.head();
more(&mut s, 1);
let recorded = s.head();
// A backup was recorded good through `recorded`, but the folder's
// newest stops at `have` (a manifest lost to a sync conflict, say).
let err = drill(
&plain(&disk),
"acme",
&b.join("journal.jsonl"),
&dir.path().join("d"),
Some(&recorded),
&Ctx::new(),
)
.unwrap_err();
assert!(
err.to_string()
.contains("a backup that was made is not there"),
"{err}"
);
// The same head with another hash is no better.
let other = (have.0, "0".repeat(64));
assert!(
drill(
&plain(&disk),
"acme",
&b.join("journal.jsonl"),
&dir.path().join("d"),
Some(&other),
&Ctx::new(),
)
.is_err()
);
// And it passes when it reaches what was recorded.
assert_eq!(
drill(
&plain(&disk),
"acme",
&b.join("journal.jsonl"),
&dir.path().join("d"),
Some(&have),
&Ctx::new(),
)
.unwrap(),
have
);
}
#[test]
fn a_damaged_stored_file_is_found_by_the_rotation_and_the_next_backup_repairs_it() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
// Stored files, until one is in the share backup number 2 re-reads
// (the share a file belongs to is its hash's first four digits modulo
// 16: every stored file is re-read within 16 backups).
let mut chosen: Option<(String, Vec<u8>)> = None;
for n in 0..400 {
let bytes = format!("a stored file, number {n}").into_bytes();
s.attach_receipt(None, &format!("s{n}.txt"), "text/plain", &bytes, None)
.unwrap();
let h = sha(&bytes);
if chosen.is_none() && u64::from_str_radix(&h[..4], 16).unwrap() % 16 == 2 {
chosen = Some((h, bytes));
}
if chosen.is_some() && n > 5 {
break;
}
}
let (h, bytes) = chosen.expect("some file is in the share");
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let rel = format!("files/{}/{h}", &h[..2]);
let piece = set_of(&disk).join(&rel);
flip(&piece);
let flipped = std::fs::read(&piece).unwrap();
more(&mut s, 1);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert_eq!(w.number, 2);
assert_eq!(w.repaired, vec![rel.clone()], "{w:?}");
assert_eq!(std::fs::read(&piece).unwrap(), flipped, "left where it is");
let again = set_of(&disk).join(format!("{rel}.g1"));
assert_eq!(std::fs::read(&again).unwrap(), bytes);
// Every manifest of the set restores with the file whole (the reader
// takes the generation that hashes right).
let found = find(&disk, None, &Ctx::new()).unwrap();
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
assert_eq!(v.passed_over, 0);
assert_eq!(v.head, s.head());
let restored = v.tree.join("blobs").join(&h[..2]).join(&h[2..4]).join(&h);
assert_eq!(std::fs::read(restored).unwrap(), bytes);
// And the next backup carries on without finding it again.
more(&mut s, 2);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new && w.repaired.is_empty(), "{w:?}");
}
#[test]
fn a_piece_damaged_as_it_is_written_is_repaired_in_the_same_backup() {
// A piece that is there under its name but is not what its name says
// (a copy that died half way on a disk that takes no links, a bad
// sector) is taken as the piece by a put; the proof finds it.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let set = set_of(&disk);
let flipped_once = Arc::new(Mutex::new(false));
let ctx = {
let (set, done) = (set.clone(), flipped_once.clone());
Ctx::new().with_faults(Arc::new(move |kind, rel| {
if kind == "published" && rel.starts_with("files/") {
let mut d = done.lock().unwrap();
if !*d {
flip(&set.join(rel));
*d = true;
}
}
false
}))
};
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap();
assert!(w.new);
assert_eq!(w.repaired.len(), 1, "{w:?}");
assert!(set.join(format!("{}.g1", w.repaired[0])).is_file());
let found = find(&disk, None, &Ctx::new()).unwrap();
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
assert_eq!(v.head, s.head());
}
#[test]
fn a_damaged_vault_record_and_an_index_segment_are_written_again_too() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let vault_bytes = b"a sealed vault record".to_vec();
std::fs::create_dir_all(b.join("vault")).unwrap();
std::fs::write(b.join("vault").join("tin-1.bin"), &vault_bytes).unwrap();
std::fs::create_dir_all(b.join("keys")).unwrap();
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let set = set_of(&disk);
flip(&set.join(format!("vault/{}", sha(&vault_bytes))));
let index = manifest(&set, 1)["files"]["segments"][0]["file"]
.as_str()
.unwrap()
.to_string();
flip(&set.join(&index));
more(&mut s, 1);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new, "{w:?}");
assert_eq!(w.repaired.len(), 2, "{w:?}");
// The newest manifest names the new generations; the restore proves.
let found = find(&disk, None, &Ctx::new()).unwrap();
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
assert_eq!(v.head, s.head());
assert_eq!(v.passed_over, 0);
assert_eq!(
std::fs::read(v.tree.join("vault").join("tin-1.bin")).unwrap(),
vault_bytes
);
}
#[test]
fn books_behind_the_destination_are_ahead_and_other_books_are_diverged() {
let dir = tempfile::tempdir().unwrap();
let (b, old, other) = (
dir.path().join("book"),
dir.path().join("old"),
dir.path().join("other"),
);
let mut s = book(&b);
// The books as they were: a copy of the folder at this point.
copy_tree(&b, &old);
more(&mut s, 1);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let before = tree(&disk);
// Restored from an older backup: the live journal is the beginning of
// the destination's. That is ahead, and the words say what to do.
let old_store = Store::open(&old).unwrap();
let err = write_destination(
&plain(&disk),
&Cut::take("acme", &old, old_store.head()).unwrap(),
true,
&Ctx::new(),
)
.unwrap_err();
assert!(matches!(err, BackupError::Ahead(..)), "{err:?}");
let words = err.to_string();
assert!(words.contains("a longer history of these books"), "{words}");
assert!(words.contains("start a new backup set"), "{words}");
assert_eq!(tree(&disk), before, "nothing was written");
// Another history under the same id is diverged, said as such (not
// ahead, whichever is longer).
let other_store = book(&other);
let err = write_destination(
&plain(&disk),
&Cut::take("acme", &other, other_store.head()).unwrap(),
true,
&Ctx::new(),
)
.unwrap_err();
assert_eq!(err, BackupError::Elsewhere);
assert!(err.to_string().contains("diverged"), "{err}");
let mut longer = other_store;
for n in 0..4 {
more(&mut longer, n);
}
let err = write_destination(
&plain(&disk),
&Cut::take("acme", &other, longer.head()).unwrap(),
true,
&Ctx::new(),
)
.unwrap_err();
assert_eq!(err, BackupError::Elsewhere);
assert_eq!(tree(&disk), before);
}
#[test]
fn a_new_set_begins_beside_the_old_at_the_persons_request_and_the_old_is_never_touched() {
let dir = tempfile::tempdir().unwrap();
let (b, old) = (dir.path().join("book"), dir.path().join("old"));
let mut s = book(&b);
copy_tree(&b, &old);
more(&mut s, 1);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
let before = tree(&disk);
let mut old_store = Store::open(&old).unwrap();
let old_cut = Cut::take("acme", &old, old_store.head()).unwrap();
assert!(matches!(
write_destination(&plain(&disk), &old_cut, true, &Ctx::new()),
Err(BackupError::Ahead(..))
));
// At the person's request: a new set, `.2`, beside it.
let w = write_destination_with(
&plain(&disk),
&old_cut,
Options {
may_create: true,
new_set: true,
},
&Ctx::new(),
)
.unwrap();
assert_eq!((w.number, w.new), (1, true));
assert!(
disk.join("wanderbooks-acme.2/manifests/000001.json")
.is_file()
);
let after = tree(&disk);
for (name, bytes) in &before {
assert_eq!(
after.get(name),
Some(bytes),
"{name}: the old set is untouched"
);
}
// The next ordinary backup goes to the new set, which grows; the old
// one stays as it was.
more(&mut old_store, 9);
let w = write_destination(
&plain(&disk),
&Cut::take("acme", &old, old_store.head()).unwrap(),
true,
&Ctx::new(),
)
.unwrap();
assert_eq!(w.number, 2);
assert!(
disk.join("wanderbooks-acme.2/manifests/000002.json")
.is_file()
);
let after = tree(&disk);
for (name, bytes) in &before {
assert_eq!(after.get(name), Some(bytes), "{name}");
}
// A drill takes the newest set too.
assert_eq!(
drill(
&plain(&disk),
"acme",
&old.join("journal.jsonl"),
&dir.path().join("d"),
Some(&old_store.head()),
&Ctx::new(),
)
.unwrap(),
old_store.head()
);
// The folder now holds two sets of the same books: a restore from it
// asks which (the sets are listed with their dates), never guesses.
assert!(matches!(
find(&disk, None, &Ctx::new()),
Err(BackupError::Several(_))
));
let listed = ledger_store::backup::list(&disk);
assert_eq!(listed.len(), 2);
assert!(
listed
.iter()
.all(|c| c.through_seq.is_some() && c.written.is_some())
);
}
#[test]
fn a_set_folder_is_a_legal_name_whatever_the_books_are_called() {
let dir = tempfile::tempdir().unwrap();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
for id in ["con", "nul", "aux", "prn", "com1", "lpt9"] {
let b = dir.path().join(format!("book-{id}"));
let s = book(&b);
write_destination(
&plain(&disk),
&Cut::take(id, &b, s.head()).unwrap(),
true,
&Ctx::new(),
)
.unwrap();
assert!(
disk.join(format!("wanderbooks-{id}/manifests/000001.json"))
.is_file(),
"{id}"
);
assert!(!disk.join(id).exists(), "{id}: no reserved name is made");
}
}
#[test]
fn only_the_newest_backup_is_tried_in_the_good_case() {
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
for n in 0..6 {
more(&mut s, n);
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
}
// Each backup added one segment, and each manifest names only its own.
let segments: usize = (1..=6)
.map(|n| {
manifest(&set_of(&disk), n)["journal"]["segments"]
.as_array()
.unwrap()
.len()
})
.sum();
assert_eq!(segments, 6);
let probes = Arc::new(Mutex::new(0usize));
let ctx = {
let probes = probes.clone();
Ctx::new().with_trace(Arc::new(move |kind, rel| {
if kind == "len" && rel.starts_with("journal/") {
*probes.lock().unwrap() += 1;
}
}))
};
let found = find(&disk, None, &ctx).unwrap();
let v = verify_found(&found, &dir.path().join("v"), &ctx).unwrap();
assert_eq!(v.number, 6);
// One look at each journal segment of the newest manifest to find the
// set's book, one to prove it: never the segments of the five older
// manifests, which reading every manifest first would have measured
// too (1 + 2 + ... + 6 more).
assert_eq!(*probes.lock().unwrap(), 2 * segments);
}
#[test]
fn a_backup_cut_while_the_vault_is_being_written_restores_a_vault_that_matches_the_journal() {
// ledger-vault stages a record as `NAME.staged-TAG` and sets the old one
// aside as `NAME.purging-TAG` while a call is between its first step and
// its last. A backup taken then must hold the vault as the journal says
// it is: the staged record is not the books' yet, and the set-aside one
// still is.
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
let record = b"sealed tin record, party one".to_vec();
let party = s.add_party("Mo", &[Role::Member]).unwrap();
s.set_party_tin(
party,
Some(TinFacts {
tin_type: TinType::Ssn,
last4: "4915".into(),
vault_record: Some(sha(&record)),
purged: None,
}),
)
.unwrap();
std::fs::create_dir_all(b.join("vault")).unwrap();
std::fs::create_dir_all(b.join("keys")).unwrap();
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
// The purge of party 1's record is staged: set aside, not yet journaled.
let tag = "0123456789abcdef";
std::fs::write(
b.join("vault").join(format!("tin-1.purging-{tag}")),
&record,
)
.unwrap();
// And a new record for party 2 is staged, not the books'.
std::fs::write(
b.join("vault").join(format!("tin-2.staged-{tag}")),
b"staged, not committed",
)
.unwrap();
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(w.new && w.repaired.is_empty(), "{w:?}");
let found = find(&disk, None, &Ctx::new()).unwrap();
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
let held: Vec<String> = std::fs::read_dir(v.tree.join("vault"))
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert_eq!(held, vec!["tin-1.bin".to_string()], "{held:?}");
assert_eq!(
std::fs::read(v.tree.join("vault").join("tin-1.bin")).unwrap(),
record
);
// No scratch name of the vault is anywhere in the destination.
assert!(
!tree(&disk)
.keys()
.any(|n| n.contains(".staged-") || n.contains(".purging-"))
);
}
#[test]
fn a_proof_cut_short_by_a_close_ends_cleanly_and_is_made_again_by_the_next_backup() {
use std::sync::atomic::{AtomicBool, Ordering};
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
let disk = dir.path().join("disk");
std::fs::create_dir(&disk).unwrap();
// The books close while the backup's proof is under way (here: as it
// replays the chain).
let stop = Arc::new(AtomicBool::new(false));
let ctx = {
let stop = stop.clone();
Ctx::new()
.with_stop(stop.clone())
.with_phase_watch(Arc::new(move |p: &str| {
if p == "replay" {
stop.store(true, Ordering::SeqCst);
}
}))
};
let err = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap_err();
assert!(matches!(err, BackupError::Cancelled(_)), "{err:?}");
// Nothing of the proof is left behind in the books' folder, and the
// manifest that was written is there but is not marked proven.
let left: Vec<_> = std::fs::read_dir(b.join("ops"))
.map(|d| {
d.flatten()
.filter(|e| e.file_name().to_string_lossy().starts_with("proof-"))
.collect()
})
.unwrap_or_default();
assert!(left.is_empty(), "scratch books left: {left:?}");
let set = set_of(&disk);
assert!(set.join("manifests/000001.json").is_file());
assert!(!set.join("proofs/000001").exists());
// The next backup has nothing new to write, and still proves it: it
// never says good of a backup that was not proven.
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert_eq!(w.number, 1);
assert!(!w.new, "{w:?}");
assert!(set.join("proofs/000001").is_file());
// Once proven, a backup with nothing new is only looked at.
let before = tree(&disk);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(!w.new);
assert_eq!(tree(&disk), before);
}
+27 -23
View File
@@ -1338,34 +1338,39 @@ fn books_that_changed_since_the_preview_are_not_adopted() {
assert_eq!(report.source_head, now);
}
/// A backup of `store`'s books (in `dir`) in a folder target under
/// `home`: its address.
fn backed_up(home: &Path, dir: &Path, store: &Store) -> Option<String> {
use ledger_store::backup::{self, Git, Target};
let git = Git::find().ok()?;
backup::commit(&git, dir, "acme", store.head()).unwrap();
/// A backup of `store`'s books (in `dir`) in a folder under `home`: the
/// folder.
fn backed_up(home: &Path, dir: &Path, store: &Store) -> std::path::PathBuf {
use ledger_store::backup::{Ctx, Cut, Destination, write_destination};
let folder = home.join("disk");
std::fs::create_dir_all(&folder).unwrap();
let target = Target::Folder(folder);
backup::push(&git, dir, "acme", &target, true).unwrap();
Some(target.source("acme"))
let cut = Cut::take("acme", dir, store.head()).unwrap();
write_destination(
&Destination {
folder: folder.clone(),
key: None,
},
&cut,
true,
&Ctx::new(),
)
.unwrap();
folder
}
#[test]
fn a_restore_never_moves_books_something_holds() {
use ledger_store::backup::Git;
let home = tmp("restore-held");
let (root, _) = Root::setup(home.path(), None, None).unwrap();
let acme = id("acme");
let held = root.create_book(&acme, Currency::USD).unwrap();
let dir = root.book_dir(&acme);
let source = backed_up(home.path(), &dir, &held).expect("git is installed");
let git = Git::find().unwrap();
let preview = root.restore_preview(&git, &source, &acme).unwrap();
let source = backed_up(home.path(), &dir, &held);
let preview = root.restore_preview(&source, None, &acme).unwrap();
assert!(preview.exists);
// Open (its writer lock held): refused, nothing moved.
let e = root
.restore(&git, &source, &acme, &preview.head, true)
.restore(&source, None, &acme, &preview.head, true)
.unwrap_err();
assert!(e.to_string().contains("are open"), "{e}");
assert!(dir.join(JOURNAL_FILE).is_file());
@@ -1378,17 +1383,17 @@ fn a_restore_never_moves_books_something_holds() {
);
// Not over books without --replace; nothing to replace that isn't.
let e = root
.restore(&git, &source, &acme, &preview.head, false)
.restore(&source, None, &acme, &preview.head, false)
.unwrap_err();
assert!(matches!(e, RootError::Exists(_)), "{e}");
let e = root
.restore(&git, &source, &id("nobody"), &preview.head, true)
.restore(&source, None, &id("nobody"), &preview.head, true)
.unwrap_err();
assert!(e.to_string().contains("no books called"), "{e}");
// Let go: replaced, the old kept whole.
drop(held);
let r = root
.restore(&git, &source, &acme, &preview.head, true)
.restore(&source, None, &acme, &preview.head, true)
.unwrap();
let kept = root.path().join("legacy").join(r.replaced.unwrap());
assert!(kept.join(JOURNAL_FILE).is_file());
@@ -1831,17 +1836,16 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i
// restore, over books that exist: they stay as they are.
let dir = root.book_dir(&id("adopted"));
let store = Store::open(&dir).unwrap();
let source = backed_up(home.path(), &dir, &store).expect("git is installed");
let source = backed_up(home.path(), &dir, &store);
drop(store);
let git = ledger_store::backup::Git::find().unwrap();
let preview = root.restore_preview(&git, &source, &id("adopted")).unwrap();
let preview = root.restore_preview(&source, None, &id("adopted")).unwrap();
let phases = ["start", "fetch", "copy", "file", "open", "verify", "place"];
for phase in phases {
let before = root_files(&root);
let (stop, seen) = stopping_at(phase);
let e = refused(root.restore_stoppable(
&git,
&source,
None,
&id("adopted"),
&preview.head,
true,
@@ -1858,7 +1862,7 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i
// The preview too: stopped, nothing left of its clone.
let before = root_files(&root);
let (stop, _) = stopping_at("fetch");
let e = refused(root.restore_preview_stoppable(&git, &source, &id("adopted"), &stop));
let e = refused(root.restore_preview_stoppable(&source, None, &id("adopted"), &stop));
assert!(matches!(e, RootError::Stopped(_)), "{e:?}");
assert_eq!(root_files(&root), before);
// Never stopped, a restore asks `place` last and goes through.
@@ -1868,7 +1872,7 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i
std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string()))
});
let r = root
.restore_stoppable(&git, &source, &id("adopted"), &preview.head, true, &stop)
.restore_stoppable(&source, None, &id("adopted"), &preview.head, true, &stop)
.unwrap();
assert!(r.replaced.is_some());
assert_eq!(