feat: the window and the server say each new state in words; a proof cut short is made again; the proof does not mistake the books' own recovery for a changed head
- books ahead of the folder (as after a restore from an older backup) offer a new backup set beside the old one, at the person's request: books.back_up_now new_set, back-up --new-set, a button in the Backups window - a key file lost from a sealed destination stops backups and asks for the passphrase; plain is written only after an explicit removal, which the record keeps (a damaged record falls back to what the folder itself holds) - a restore that is not of the newest backup says so first, in the warning colour, with both dates and how many backups it passes over - a folder a sync service keeps (or may) is said in plain words at set-up and in the window: one computer only, kept offline, a second computer its own - a drill that finds only an older whole backup fails in words - a manifest whose proof was cut short is marked unproven and proven by the next backup, even one with nothing new; a saved backup file is proven whole before it is given its name - the proof compares the journal its pieces make with the head the manifest records before the books open, and lets opening add only after it - the restore tests are split from backups.rs to keep each under a minute; the clone-of-an-old-git-backup test builds the working tree without git Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
9ac47a3f10
commit
344b3b4abe
21 files changed
+2346
-690
No files matched your search
@@ -299,7 +299,11 @@ impl ledger_gui::owner::Owner for ViewerOwner {
|
||||
}
|
||||
|
||||
fn back_up_now(&self, book: &str) -> Result<Vec<String>, String> {
|
||||
ledger_host::commands::back_up_now(&self.common, book, false)
|
||||
ledger_host::commands::back_up_now(&self.common, book, false, false)
|
||||
}
|
||||
|
||||
fn start_new_backup_set(&self, book: &str) -> Result<Vec<String>, String> {
|
||||
ledger_host::commands::back_up_now(&self.common, book, false, true)
|
||||
}
|
||||
|
||||
fn backup_state(&self, book: &str) -> Result<ledger_gui::owner::BackupState, String> {
|
||||
@@ -308,6 +312,7 @@ impl ledger_gui::owner::Owner for ViewerOwner {
|
||||
lines: ledger_host::commands::backup_words(&s),
|
||||
folder: s.folder.clone(),
|
||||
sealed: s.sealed,
|
||||
ahead: s.error_kind.as_deref() == Some("ahead"),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! the INVARIANTS of ledger-mcp backup.rs and ledger-store backup, and
|
||||
//! plan 3.7's named tests.
|
||||
#![cfg(unix)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
use ledger_mcp::admin::{self, Request, Response};
|
||||
use ledger_store::backup::{Ctx, find, verify_found};
|
||||
@@ -637,171 +638,6 @@ fn files_below(dir: &Path, prefix: &str) -> Vec<PathBuf> {
|
||||
all
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn restore_beside_existing_books_and_on_a_clean_install() {
|
||||
let home = Home::new("beside");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let (folder, want) = backed_up_acme(&home).await;
|
||||
// Beside: its own books, the same figures and head.
|
||||
let r = restore(&home, "acme-copy", &folder, false).unwrap();
|
||||
assert_eq!(r.replaced, None);
|
||||
assert_eq!(r.head, live_head(&home, "acme"));
|
||||
let copy = connect(
|
||||
&home,
|
||||
"acme-copy",
|
||||
home.token("acme-copy", &["read", "admin"]),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(figures(©).await, want);
|
||||
// Its own backups carry on in the same folder, under its own name; the
|
||||
// original's stay as they were.
|
||||
let orig = proven(&home, &folder.join("wanderbooks-acme"), "orig-before");
|
||||
let s = call(©, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
assert_eq!(
|
||||
proven(&home, &folder.join("wanderbooks-acme-copy"), "copy"),
|
||||
live_head(&home, "acme-copy")
|
||||
);
|
||||
assert_eq!(
|
||||
proven(&home, &folder.join("wanderbooks-acme"), "orig-after"),
|
||||
orig
|
||||
);
|
||||
drop(copy);
|
||||
assert!(server.close().success());
|
||||
// restore_on_clean_install: another computer's root, nothing in it.
|
||||
let other = Home::new("clean");
|
||||
let server = Server::start(&other, Duration::from_secs(3600));
|
||||
assert_eq!(books_held(&other), Vec::<String>::new());
|
||||
let r = restore(&other, "acme", &folder.join("wanderbooks-acme"), false).unwrap();
|
||||
assert_eq!(r.head, live_head(&home, "acme"));
|
||||
let c = connect(&other, "acme", other.token("acme", &["read"])).await;
|
||||
assert_eq!(figures(&c).await, want);
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn restore_never_overwrites_and_replacing_keeps_the_old_books() {
|
||||
let home = Home::new("replace");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let (folder, want) = backed_up_acme(&home).await;
|
||||
let at_backup = live_head(&home, "acme");
|
||||
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||
post_one(&c, 6).await;
|
||||
let moved_on = live_head(&home, "acme");
|
||||
assert!(moved_on.0 > at_backup.0);
|
||||
// Not over them.
|
||||
let refused = restore(&home, "acme", &folder, false).unwrap_err();
|
||||
assert!(refused.contains("already books called"), "{refused}");
|
||||
assert_eq!(live_head(&home, "acme"), moved_on);
|
||||
// Replacing books that aren't there is refused too.
|
||||
let refused = restore(&home, "nobody", &folder, true).unwrap_err();
|
||||
assert!(refused.contains("no books called"), "{refused}");
|
||||
// Replacing: the old books kept whole in legacy/, the backup in place.
|
||||
let r = restore(&home, "acme", &folder, true).unwrap();
|
||||
let fresh = connect(&home, "acme", home.token("acme", &["read"])).await;
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let s = call(&fresh, "books.backup", json!({})).await.unwrap();
|
||||
if s["targets"][0]["last_ok_at"].is_string() {
|
||||
break;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"the restored books weren't backed up: {s}"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
drop(fresh);
|
||||
let kept = home.root().join("legacy").join(r.replaced.clone().unwrap());
|
||||
let old = ledger_store::Snapshot::load(&kept).unwrap();
|
||||
assert_eq!((old.journal_seq(), old.head_hash().to_string()), moved_on);
|
||||
assert_eq!(live_head(&home, "acme"), at_backup);
|
||||
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||
assert_eq!(figures(&c).await, want);
|
||||
// And it is written to and backed up as before: the folder's backup of
|
||||
// these books goes on from where it was.
|
||||
post_one(&c, 7).await;
|
||||
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
assert_eq!(proven(&home, &folder, "after"), live_head(&home, "acme"));
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn restore_refuses_a_damaged_backup_and_writes_nothing() {
|
||||
let home = Home::new("damaged");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let (folder, _) = backed_up_acme(&home).await;
|
||||
let before = books_held(&home);
|
||||
let books = home.root().join("books");
|
||||
let names = || {
|
||||
let mut v: Vec<String> = std::fs::read_dir(&books)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
let listed = names();
|
||||
// Each damage in a copy of its own, made from the good one.
|
||||
type Spoil<'a> = (&'a str, &'a dyn Fn(&Path));
|
||||
let damage: [Spoil; 5] = [
|
||||
("flipped", &|set: &Path| {
|
||||
let j = &files_below(set, "journal/")[0];
|
||||
let mut b = std::fs::read(j).unwrap();
|
||||
let mid = b.len() / 2;
|
||||
b[mid] ^= 1;
|
||||
std::fs::write(j, b).unwrap();
|
||||
}),
|
||||
("no-files", &|set: &Path| {
|
||||
for f in files_below(set, "files/") {
|
||||
std::fs::remove_file(f).unwrap();
|
||||
}
|
||||
}),
|
||||
("cut", &|set: &Path| {
|
||||
let j = &files_below(set, "journal/")[0];
|
||||
let mut b = std::fs::read(j).unwrap();
|
||||
b.truncate(b.len() - 10);
|
||||
std::fs::write(j, b).unwrap();
|
||||
}),
|
||||
("manifest-cut", &|set: &Path| {
|
||||
for f in files_below(set, "manifests/") {
|
||||
let b = std::fs::read(&f).unwrap();
|
||||
std::fs::write(&f, &b[..b.len() / 2]).unwrap();
|
||||
}
|
||||
}),
|
||||
("no-manifest", &|set: &Path| {
|
||||
for f in files_below(set, "manifests/") {
|
||||
std::fs::remove_file(f).unwrap();
|
||||
}
|
||||
}),
|
||||
];
|
||||
for (tag, spoil) in damage {
|
||||
let copy = home.outside(&format!("bad-{tag}"));
|
||||
copy_dir(&folder.join("wanderbooks-acme"), ©);
|
||||
spoil(©);
|
||||
let why = restore(&home, "acme-bad", ©, false).unwrap_err();
|
||||
assert!(why.contains("can't be restored"), "{tag}: {why}");
|
||||
assert!(
|
||||
!why.contains(&home.root().display().to_string()),
|
||||
"{tag}: {why}"
|
||||
);
|
||||
assert!(!why.contains(©.display().to_string()), "{tag}: {why}");
|
||||
assert_eq!(books_held(&home), before, "{tag}");
|
||||
assert_eq!(names(), listed, "{tag}");
|
||||
}
|
||||
// A place that isn't a backup: said, nothing written.
|
||||
let why = restore(&home, "acme-bad", &home.outside("nothing-here"), false).unwrap_err();
|
||||
assert!(!why.contains("nothing-here"), "{why}");
|
||||
assert_eq!(names(), listed);
|
||||
assert!(server.close().success());
|
||||
}
|
||||
|
||||
fn copy_dir(from: &Path, to: &Path) {
|
||||
std::fs::create_dir_all(to).unwrap();
|
||||
for e in std::fs::read_dir(from).unwrap() {
|
||||
@@ -902,187 +738,6 @@ async fn a_write_waits_for_the_quiet_before_it_is_backed_up() {
|
||||
assert!(server.close().success());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_restore_is_of_the_backup_previewed_only() {
|
||||
let home = Home::new("previewed");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let (folder, _) = backed_up_acme(&home).await;
|
||||
let request = |expect_head: Option<(u64, String)>, confirmed| Request::Restore {
|
||||
id: "copy".into(),
|
||||
source: folder.display().to_string(),
|
||||
replace: false,
|
||||
confirmed,
|
||||
expect_head,
|
||||
passphrase: None,
|
||||
};
|
||||
// A preview leaves nothing behind in the books' folder, and clears
|
||||
// what a restore that never finished left.
|
||||
let books = home.root().join("books");
|
||||
std::fs::create_dir(books.join(".restore-junk")).unwrap();
|
||||
let previewed = match home.admin(request(None, false)) {
|
||||
Response::RestorePreview(p) => p.head,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let dotted: Vec<_> = std::fs::read_dir(&books)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.starts_with('.'))
|
||||
.collect();
|
||||
assert!(dotted.is_empty(), "{dotted:?}");
|
||||
// Confirmed with no head: refused.
|
||||
match home.admin(request(None, true)) {
|
||||
Response::Refused(why) => assert!(why.contains("preview first"), "{why}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// The backup moves on after the preview: refused, nothing written.
|
||||
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||
post_one(&c, 9).await;
|
||||
call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||
match home.admin(request(Some(previewed), true)) {
|
||||
Response::Refused(why) => assert!(why.contains("isn't the one previewed"), "{why}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert_eq!(books_held(&home), vec!["acme".to_string()]);
|
||||
assert!(!home.root().join("books").join("copy").exists());
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_restore_brings_the_vault_and_its_key() {
|
||||
let home = Home::new("vault");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||
call(
|
||||
&c,
|
||||
"books.add_party",
|
||||
json!({"name": "Mo", "roles": ["member"]}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
call(
|
||||
&c,
|
||||
"books.set_tin",
|
||||
json!({"party": "Mo", "tin": "12-3456789", "tin_type": "ein"}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (folder, want) = backed_up_acme(&home).await;
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
let other = Home::new("vault-clean");
|
||||
let server = Server::start(&other, Duration::from_secs(3600));
|
||||
let request = |expect_head: Option<(u64, String)>| Request::Restore {
|
||||
id: "acme".into(),
|
||||
source: folder.display().to_string(),
|
||||
replace: false,
|
||||
confirmed: expect_head.is_some(),
|
||||
expect_head,
|
||||
passphrase: None,
|
||||
};
|
||||
let preview = match other.admin(request(None)) {
|
||||
Response::RestorePreview(p) => p,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert_eq!(preview.vault_files, 1);
|
||||
let r = match other.admin(request(Some(preview.head))) {
|
||||
Response::Restored(r) => r,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert_eq!(r.vault_files, 1);
|
||||
// The record and its key, byte for byte.
|
||||
let files = |h: &Home, sub: &str| {
|
||||
let mut v: Vec<(String, Vec<u8>)> = std::fs::read_dir(h.book_dir("acme").join(sub))
|
||||
.unwrap()
|
||||
.map(|e| {
|
||||
let e = e.unwrap();
|
||||
(
|
||||
e.file_name().to_string_lossy().into_owned(),
|
||||
std::fs::read(e.path()).unwrap(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
for sub in ["vault", "keys"] {
|
||||
assert!(!files(&home, sub).is_empty(), "{sub}");
|
||||
assert_eq!(files(&other, sub), files(&home, sub), "{sub}");
|
||||
}
|
||||
let c = connect(&other, "acme", other.token("acme", &["read"])).await;
|
||||
assert_eq!(figures(&c).await, want);
|
||||
let party = call(&c, "books.party", json!({"party": "Mo"}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(party["party"]["tin"]["in_vault"], true, "{party}");
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
// A backup missing the vault's key, or the TIN record the books name,
|
||||
// is not whole: refused, nothing restored.
|
||||
let third = Home::new("vault-short");
|
||||
let server = Server::start(&third, Duration::from_secs(3600));
|
||||
for gone in ["keys/", "vault/"] {
|
||||
let copy = home.outside(&format!("no-{}", gone.trim_end_matches('/')));
|
||||
copy_dir(&folder.join("wanderbooks-acme"), ©);
|
||||
for f in files_below(©, gone) {
|
||||
std::fs::remove_file(f).unwrap();
|
||||
}
|
||||
let why = restore(&third, "acme", ©, false).unwrap_err();
|
||||
assert!(why.contains("can't be restored"), "{gone}: {why}");
|
||||
assert_eq!(books_held(&third), Vec::<String>::new());
|
||||
}
|
||||
assert!(server.close().success());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_replacing_restore_that_fails_leaves_the_books_open() {
|
||||
let home = Home::new("replace-bad");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let (folder, want) = backed_up_acme(&home).await;
|
||||
let before = live_head(&home, "acme");
|
||||
let bad = home.outside("bad");
|
||||
copy_dir(&folder.join("wanderbooks-acme"), &bad);
|
||||
let j = &files_below(&bad, "journal/")[0];
|
||||
let mut b = std::fs::read(j).unwrap();
|
||||
let mid = b.len() / 2;
|
||||
b[mid] ^= 1;
|
||||
std::fs::write(j, b).unwrap();
|
||||
// Its preview is refused; so is a confirm (sent without one), which
|
||||
// lets the books go first, then fails: they are open again, as they
|
||||
// were, nothing moved to legacy.
|
||||
assert!(restore(&home, "acme", &bad, true).is_err());
|
||||
let why = match home.admin(Request::Restore {
|
||||
id: "acme".into(),
|
||||
source: bad.display().to_string(),
|
||||
replace: true,
|
||||
confirmed: true,
|
||||
expect_head: Some(before.clone()),
|
||||
passphrase: None,
|
||||
}) {
|
||||
Response::Refused(why) => why,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert!(why.contains("can't be"), "{why}");
|
||||
match home.admin(Request::List) {
|
||||
Response::Books(b) => {
|
||||
assert_eq!(b.len(), 1);
|
||||
assert!(b[0].open, "{b:?}");
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert_eq!(live_head(&home, "acme"), before);
|
||||
let legacy = home.root().join("legacy");
|
||||
assert!(!legacy.exists() || std::fs::read_dir(&legacy).unwrap().count() == 0);
|
||||
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||
assert_eq!(figures(&c).await, want);
|
||||
post_one(&c, 3).await;
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
}
|
||||
|
||||
/// The book's backup record (the test's own data root).
|
||||
fn records(home: &Home, book: &str) -> Vec<Value> {
|
||||
std::fs::read_to_string(home.book_dir(book).join("ops").join("backup.jsonl"))
|
||||
@@ -1092,44 +747,6 @@ fn records(home: &Home, book: &str) -> Vec<Value> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn restored_books_never_make_their_backup_folder_again() {
|
||||
let home = Home::new("restore-mount");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let (folder, _) = backed_up_acme(&home).await;
|
||||
assert!(server.close().success());
|
||||
// On another computer, its backup disk not mounted (the mount point
|
||||
// there, empty): restored from a copy of the backup.
|
||||
let copy = home.outside("copy-of-disk");
|
||||
copy_dir(&folder, ©);
|
||||
std::fs::rename(folder.join("wanderbooks-acme"), home.outside("unmounted")).unwrap();
|
||||
let other = Home::new("restore-mount-new");
|
||||
let server = Server::start(&other, Duration::from_secs(3600));
|
||||
restore(&other, "acme", ©, false).unwrap();
|
||||
let c = connect(&other, "acme", other.token("acme", &["read", "admin"])).await;
|
||||
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert!(
|
||||
s["targets"][0]["last_error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("holds no backup"),
|
||||
"{s}"
|
||||
);
|
||||
assert!(
|
||||
!folder.join("wanderbooks-acme").exists(),
|
||||
"made on the wrong disk"
|
||||
);
|
||||
// The human says it's a new disk: begun there again.
|
||||
let s = call(&c, "books.back_up_now", json!({"new_disk": true}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
assert!(folder.join("wanderbooks-acme").join("manifests").is_dir());
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_damaged_backup_record_never_keeps_the_books_shut() {
|
||||
let home = Home::new("damaged-record");
|
||||
@@ -1250,28 +867,14 @@ async fn old_settings_and_an_old_backup_history_are_left_alone_and_said() {
|
||||
|
||||
/// docs/backups.md, "A backup made with an older version": a person who
|
||||
/// still has a backup made with git clones it themselves (git is their own
|
||||
/// tool now) and adopts the plain folder. This makes such a backup the way
|
||||
/// an older version did (a repository whose one commit is the books'
|
||||
/// files), clones it as the docs say, and adopts the clone with its vault
|
||||
/// and key as the docs say.
|
||||
/// tool now) and adopts the plain folder. What a clone leaves is a working
|
||||
/// tree: the books' files as the older version committed them, beside a
|
||||
/// `.git` folder. This builds that working tree from the books' files and
|
||||
/// adopts it with its vault and key as the docs say. It needs no git on
|
||||
/// the machine, so it never skips: the adoption is of a folder, and a
|
||||
/// folder is all there is to it.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_clone_of_an_old_git_backup_is_adopted_as_a_plain_folder() {
|
||||
let git = |dir: &Path, args: &[&str]| {
|
||||
let out = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(dir)
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t.invalid"])
|
||||
.args(args)
|
||||
.output();
|
||||
match out {
|
||||
Ok(o) => {
|
||||
assert!(o.status.success(), "{args:?}: {o:?}");
|
||||
true
|
||||
}
|
||||
// No git on this machine: the path is the person's own tool's.
|
||||
Err(_) => false,
|
||||
}
|
||||
};
|
||||
let home = Home::new("old-backup");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
@@ -1293,41 +896,28 @@ async fn a_clone_of_an_old_git_backup_is_adopted_as_a_plain_folder() {
|
||||
let (folder, want) = backed_up_acme(&home).await;
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
// The old backup: the books' files, committed, in a bare repository.
|
||||
// The working tree of a clone of the old backup: the books' files, and
|
||||
// the repository's own folder beside them (a few of the files git
|
||||
// keeps there, which adoption must leave out).
|
||||
let book = home.book_dir("acme");
|
||||
let work = home.outside("old-work");
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
let clone = home.outside("acme-old");
|
||||
std::fs::create_dir_all(&clone).unwrap();
|
||||
for part in ["journal.jsonl", "blobs", "vault", "keys", "access.jsonl"] {
|
||||
let from = book.join(part);
|
||||
if from.is_dir() {
|
||||
copy_dir(&from, &work.join(part));
|
||||
copy_dir(&from, &clone.join(part));
|
||||
} else if from.is_file() {
|
||||
std::fs::copy(&from, work.join(part)).unwrap();
|
||||
std::fs::copy(&from, clone.join(part)).unwrap();
|
||||
}
|
||||
}
|
||||
if !git(&work, &["init", "-q", "-b", "main"]) {
|
||||
return;
|
||||
}
|
||||
git(&work, &["add", "-A", "-f"]);
|
||||
git(&work, &["commit", "-q", "-m", "seq 1 head x\n\nbook acme"]);
|
||||
let bare = home.outside("acme.git");
|
||||
let out = Command::new("git")
|
||||
.args(["clone", "-q", "--bare"])
|
||||
.arg(&work)
|
||||
.arg(&bare)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
// The person's steps: clone it, then adopt the folder with its vault
|
||||
// and key.
|
||||
let clone = home.outside("acme-old");
|
||||
let out = Command::new("git")
|
||||
.args(["clone", "-q"])
|
||||
.arg(&bare)
|
||||
.arg(&clone)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
std::fs::create_dir_all(clone.join(".git/refs/heads")).unwrap();
|
||||
std::fs::write(clone.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
|
||||
std::fs::write(
|
||||
clone.join(".git/config"),
|
||||
"[core]\n\trepositoryformatversion = 0\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(clone.join("journal.jsonl").is_file() && clone.join("vault").is_dir());
|
||||
let other = Home::new("old-backup-new");
|
||||
let server = Server::start(&other, Duration::from_secs(3600));
|
||||
let request = |confirmed: bool, expect_head: Option<(u64, String)>| Request::Adopt {
|
||||
@@ -1362,154 +952,3 @@ async fn a_clone_of_an_old_git_backup_is_adopted_as_a_plain_folder() {
|
||||
assert!(server.close().success());
|
||||
let _ = folder;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_passphrase_seals_the_backups_and_a_restore_asks_for_it() {
|
||||
// D-92 from the window's side: set up through the admin socket, a backup
|
||||
// made sealed, the status said, a restore on another computer asking for
|
||||
// the passphrase, a wrong one refused, a saved file sealed too, and the
|
||||
// passphrase taken off.
|
||||
const PASS: &str = "correct horse battery staple";
|
||||
let home = Home::new("sealed");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let folder = home.outside("disk");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let said = |r: Response| match r {
|
||||
Response::Said { lines } => lines.join(" "),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
// A folder that isn't there, or is inside the books, is refused in words.
|
||||
match home.admin(Request::BackupSetup {
|
||||
id: "acme".into(),
|
||||
folder: Some(home.outside("nowhere").display().to_string()),
|
||||
passphrase: None,
|
||||
remove_passphrase: false,
|
||||
}) {
|
||||
Response::Refused(why) => assert!(why.contains("isn't there"), "{why}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let words = said(home.admin(Request::BackupSetup {
|
||||
id: "acme".into(),
|
||||
folder: Some(folder.display().to_string()),
|
||||
passphrase: Some(admin::Passphrase(PASS.into())),
|
||||
remove_passphrase: false,
|
||||
}));
|
||||
assert!(words.contains("cannot be recovered"), "{words}");
|
||||
assert!(!words.contains(PASS));
|
||||
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||
post_one(&c, 3).await;
|
||||
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
assert_eq!(s["targets"][0]["sealed"], true, "{s}");
|
||||
match home.admin(Request::BackupStatus { id: "acme".into() }) {
|
||||
Response::BackupStatus(st) => {
|
||||
assert!(st.sealed && st.last_ok_at.is_some(), "{st:?}");
|
||||
assert_eq!(
|
||||
st.folder.as_deref(),
|
||||
Some(folder.display().to_string().as_str())
|
||||
);
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// What is in the folder says nothing of the books.
|
||||
let names: Vec<String> = files_below(&folder, "")
|
||||
.into_iter()
|
||||
.map(|p| {
|
||||
p.strip_prefix(&folder)
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
!names
|
||||
.iter()
|
||||
.any(|n| n.contains("acme") || n.contains("journal")),
|
||||
"{names:?}"
|
||||
);
|
||||
// Nothing of the passphrase or its key is in the backup record, the
|
||||
// access log or the journal.
|
||||
let book = home.book_dir("acme");
|
||||
for file in ["ops/backup.jsonl", "access.jsonl", "journal.jsonl"] {
|
||||
let text = std::fs::read_to_string(book.join(file)).unwrap_or_default();
|
||||
assert!(!text.contains(PASS), "{file}");
|
||||
}
|
||||
let key = std::fs::read_to_string(book.join("local").join("backup-key.json")).unwrap();
|
||||
let master = key
|
||||
.split('"')
|
||||
.nth(key.split('"').position(|p| p == "master").unwrap() + 2)
|
||||
.unwrap()
|
||||
.to_string();
|
||||
for file in ["ops/backup.jsonl", "access.jsonl", "journal.jsonl"] {
|
||||
let text = std::fs::read_to_string(book.join(file)).unwrap_or_default();
|
||||
assert!(!text.contains(&master), "{file}");
|
||||
}
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
// Another computer: the passphrase is asked for, and a wrong one refused.
|
||||
let other = Home::new("sealed-new");
|
||||
let server = Server::start(&other, Duration::from_secs(3600));
|
||||
let why = restore(&other, "acme", &folder, false).unwrap_err();
|
||||
assert!(why.contains("passphrase"), "{why}");
|
||||
let why = restore_with(
|
||||
&other,
|
||||
"acme",
|
||||
&folder,
|
||||
false,
|
||||
Some("not the right words at all"),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(why.contains("isn't the passphrase"), "{why}");
|
||||
assert_eq!(books_held(&other), Vec::<String>::new());
|
||||
let r = restore_with(&other, "acme", &folder, false, Some(PASS)).unwrap();
|
||||
assert_eq!(r.head, live_head(&home, "acme"));
|
||||
// The restored books keep backing up sealed, with no question asked.
|
||||
assert!(
|
||||
other
|
||||
.book_dir("acme")
|
||||
.join("local")
|
||||
.join("backup-key.json")
|
||||
.is_file()
|
||||
);
|
||||
// Saved as one file: sealed too, and restorable from.
|
||||
let file = other.outside("acme.wbbackup");
|
||||
let words = said(other.admin(Request::BackupSave {
|
||||
id: "acme".into(),
|
||||
path: file.display().to_string(),
|
||||
}));
|
||||
assert!(words.contains("protected by the passphrase"), "{words}");
|
||||
assert!(server.close().success());
|
||||
let third = Home::new("sealed-file");
|
||||
let server = Server::start(&third, Duration::from_secs(3600));
|
||||
assert!(restore(&third, "acme", &file, false).is_err());
|
||||
let r = restore_with(&third, "acme", &file, false, Some(PASS)).unwrap();
|
||||
assert_eq!(r.head, live_head(&home, "acme"));
|
||||
assert!(server.close().success());
|
||||
// The passphrase taken off: the next backup is plain, in the old plain
|
||||
// folder, and the sealed one is untouched.
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
let sealed_before: Vec<_> = files_below(&folder, "sealed-");
|
||||
let bytes_before: Vec<Vec<u8>> = sealed_before
|
||||
.iter()
|
||||
.map(|p| std::fs::read(p).unwrap())
|
||||
.collect();
|
||||
said(home.admin(Request::BackupSetup {
|
||||
id: "acme".into(),
|
||||
folder: None,
|
||||
passphrase: None,
|
||||
remove_passphrase: true,
|
||||
}));
|
||||
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert_eq!(s["targets"][0]["sealed"], false, "{s}");
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
assert!(folder.join("wanderbooks-acme").join("manifests").is_dir());
|
||||
let bytes_after: Vec<Vec<u8>> = sealed_before
|
||||
.iter()
|
||||
.map(|p| std::fs::read(p).unwrap())
|
||||
.collect();
|
||||
assert_eq!(bytes_before, bytes_after);
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,797 @@
|
||||
//! What a person is told when their backups are in trouble (WB-backup-13 to
|
||||
//! WB-backup-16): the key file lost from a sealed destination, books behind
|
||||
//! the folder's (a new set at their request), a newest backup that is
|
||||
//! damaged while an older one is whole, and a folder a sync service keeps.
|
||||
#![cfg(unix)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
use ledger_mcp::admin::{self, Request, Response};
|
||||
use ledger_store::backup::{Ctx, find, verify_found};
|
||||
use ledger_store::root::{BookId, Root};
|
||||
use rmcp::ServiceExt;
|
||||
use rmcp::model::{CallToolRequestParams, ClientConfig};
|
||||
use rmcp::service::{RoleClient, RunningService};
|
||||
use rmcp::transport::StreamableHttpClientTransport;
|
||||
use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
|
||||
use serde_json::{Value, json};
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
type Client = RunningService<RoleClient, ClientConfig>;
|
||||
|
||||
/// A home with a data root made by `wanderbooks setup`, and a place for
|
||||
/// the backups beside it.
|
||||
struct Home {
|
||||
dir: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Home {
|
||||
fn new(tag: &str) -> Self {
|
||||
let dir = tempfile::Builder::new()
|
||||
.prefix(&format!("wb-bk-{tag}-"))
|
||||
.tempdir()
|
||||
.unwrap();
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_wanderbooks"))
|
||||
.args(["setup", "--home"])
|
||||
.arg(dir.path())
|
||||
.env_remove("XDG_DATA_HOME")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
Self { dir }
|
||||
}
|
||||
|
||||
fn root(&self) -> PathBuf {
|
||||
ledger_store::root::default_root(self.dir.path())
|
||||
}
|
||||
|
||||
fn book_dir(&self, book: &str) -> PathBuf {
|
||||
Root::open(&self.root())
|
||||
.unwrap()
|
||||
.book_dir(&BookId::parse(book).unwrap())
|
||||
}
|
||||
|
||||
fn admin(&self, request: Request) -> Response {
|
||||
admin::call(&self.root().join("run/admin.sock"), request).unwrap()
|
||||
}
|
||||
|
||||
fn create(&self, id: &str) {
|
||||
match self.admin(Request::Create {
|
||||
id: id.into(),
|
||||
currency: "USD".into(),
|
||||
}) {
|
||||
Response::Created { problem: None, .. } => {}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn token(&self, book: &str, scopes: &[&str]) -> String {
|
||||
match self.admin(Request::TokenCreate {
|
||||
book: book.into(),
|
||||
name: format!("test-{}", scopes.join("-")),
|
||||
scopes: scopes.iter().map(|s| s.to_string()).collect(),
|
||||
replace: true,
|
||||
}) {
|
||||
Response::TokenCreated { text, .. } => text.0,
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A place outside the data root (a folder on "another disk").
|
||||
fn outside(&self, name: &str) -> PathBuf {
|
||||
let p = self.dir.path().join("elsewhere").join(name);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
/// A running `wanderbooks server`, ended (kill) when dropped.
|
||||
struct Server {
|
||||
child: Child,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Start one, backing up after `quiet` of no writing (a drill first
|
||||
/// looked for after the server's own wait: a minute, past any test).
|
||||
fn start(home: &Home, quiet: Duration) -> Self {
|
||||
Self::start_with(home, quiet, None)
|
||||
}
|
||||
|
||||
/// [`Self::start`], a drill first looked for `drill_first` after books
|
||||
/// are seen open.
|
||||
fn start_with(home: &Home, quiet: Duration, drill_first: Option<Duration>) -> Self {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_wanderbooks"));
|
||||
command
|
||||
.arg("server")
|
||||
.arg("--root")
|
||||
.arg(home.root())
|
||||
.arg("--backup-quiet")
|
||||
.arg(quiet.as_millis().to_string());
|
||||
if let Some(d) = drill_first {
|
||||
command.arg("--drill-first").arg(d.as_millis().to_string());
|
||||
}
|
||||
let mut child = command
|
||||
.env_clear()
|
||||
.env("PATH", "/usr/bin:/bin")
|
||||
.env("HOME", home.dir.path())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(child.stdout.take().unwrap())
|
||||
.read_line(&mut line)
|
||||
.unwrap();
|
||||
assert_eq!(line, "ready\n", "the server didn't say ready");
|
||||
Self { child }
|
||||
}
|
||||
|
||||
/// Close it as the host does (stdin ends) and wait for it to exit.
|
||||
fn close(mut self) -> std::process::ExitStatus {
|
||||
drop(self.child.stdin.take());
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
if let Some(status) = self.child.try_wait().unwrap() {
|
||||
return status;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "the server didn't close");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Server {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// A session with one book, and what it takes to send the book a file as
|
||||
/// an agent does (D-46: a file comes only by upload).
|
||||
struct Agent {
|
||||
client: Client,
|
||||
http: reqwest::Client,
|
||||
book: String,
|
||||
token: String,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Agent {
|
||||
type Target = Client;
|
||||
fn deref(&self) -> &Client {
|
||||
&self.client
|
||||
}
|
||||
}
|
||||
|
||||
impl Agent {
|
||||
/// Upload `bytes` as `wanderbooks upload` does: books.begin_upload,
|
||||
/// then the bytes PUT with this session's token. The upload_id.
|
||||
async fn upload(&self, bytes: &[u8], file_name: &str, mime_type: &str) -> String {
|
||||
let begun = call(
|
||||
self,
|
||||
"books.begin_upload",
|
||||
json!({"sha256": ledger_store::journal::sha256_hex(bytes), "size": bytes.len(),
|
||||
"mime_type": mime_type, "file_name": file_name, "purpose": "receipt"}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let id = begun["upload_id"].as_str().unwrap().to_string();
|
||||
let r = self
|
||||
.http
|
||||
.put(format!("http://localhost/b/{}/u/{id}", self.book))
|
||||
.bearer_auth(&self.token)
|
||||
.body(bytes.to_vec())
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.status().as_u16(), 200);
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect(home: &Home, book: &str, token: String) -> Agent {
|
||||
// The short path is good in this process only, while it lives: kept.
|
||||
let short = ledger_store::root::SocketPath::new(&home.root().join("run"), "mcp.sock").unwrap();
|
||||
let path = short.path().to_path_buf();
|
||||
std::mem::forget(short);
|
||||
let http = reqwest::Client::builder()
|
||||
.unix_socket(path)
|
||||
.build()
|
||||
.unwrap();
|
||||
let config =
|
||||
StreamableHttpClientTransportConfig::with_uri(format!("http://localhost/b/{book}/mcp"))
|
||||
.auth_header(token.clone());
|
||||
let client = ClientConfig::default()
|
||||
.serve(StreamableHttpClientTransport::with_client(
|
||||
http.clone(),
|
||||
config,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
Agent {
|
||||
client,
|
||||
http,
|
||||
book: book.to_string(),
|
||||
token,
|
||||
}
|
||||
}
|
||||
|
||||
/// Call a tool: Ok(structured result) or Err(the error text).
|
||||
/// Call a tool the way an agent confirms (plan P4, D-50): a call with
|
||||
/// `confirmed: true` and no `preview` is made first without `confirmed`,
|
||||
/// then with the `preview` it returned. A refused preview is the answer.
|
||||
async fn call(c: &Client, tool: &str, mut args: Value) -> Result<Value, String> {
|
||||
if args.get("confirmed") == Some(&json!(true)) && args.get("preview").is_none() {
|
||||
let mut first = args.clone();
|
||||
first["confirmed"] = json!(false);
|
||||
let seen = call_once(c, tool, first).await?;
|
||||
if let Some(digest) = seen.get("preview").and_then(Value::as_str) {
|
||||
args["preview"] = json!(digest);
|
||||
}
|
||||
}
|
||||
call_once(c, tool, args).await
|
||||
}
|
||||
|
||||
async fn call_once(c: &Client, tool: &str, args: Value) -> Result<Value, String> {
|
||||
let mut args = args.as_object().cloned().unwrap_or_default();
|
||||
// The key every write call carries (D-88).
|
||||
static NEXT_KEY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
args.entry("request_key").or_insert_with(|| {
|
||||
let n = NEXT_KEY.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
json!(format!("backups-key-{}-{n}", std::process::id()))
|
||||
});
|
||||
let r = tokio::time::timeout(
|
||||
Duration::from_secs(60),
|
||||
c.call_tool(CallToolRequestParams::new(tool.to_string()).with_arguments(args)),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| "no answer".to_string())?
|
||||
.map_err(|e| format!("protocol: {e}"))?;
|
||||
let text = r
|
||||
.content
|
||||
.iter()
|
||||
.find_map(|c| c.as_text().map(|t| t.text.clone()))
|
||||
.unwrap_or_default();
|
||||
if r.is_error == Some(true) {
|
||||
Err(text)
|
||||
} else {
|
||||
Ok(r.structured_content
|
||||
.unwrap_or_else(|| serde_json::from_str(&text).unwrap_or(Value::String(text))))
|
||||
}
|
||||
}
|
||||
|
||||
async fn head(c: &Client) -> u64 {
|
||||
call(c, "books.start", json!({})).await.unwrap()["head"]["seq"]
|
||||
.as_u64()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Name the backup folder in the book's settings.
|
||||
async fn set_folder(c: &Client, folder: &Path) {
|
||||
call(
|
||||
c,
|
||||
"books.set_setting",
|
||||
json!({"changes": [{"key": "backup.folder", "value": folder.display().to_string()}],
|
||||
"decided_by": "Test Owner", "note": "Backups."}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Draft, receipt and post one $n entry.
|
||||
async fn post_one(c: &Agent, n: u64) {
|
||||
for (code, name, ty) in [("1000", "Cash", "asset"), ("6000", "Supplies", "expense")] {
|
||||
let _ = call(
|
||||
c,
|
||||
"books.add_account",
|
||||
json!({"code": code, "name": name, "account_type": ty}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let e = call(
|
||||
c,
|
||||
"books.draft_entry",
|
||||
json!({"date": "2026-03-01", "description": format!("entry {n}")}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let id = e["entry_id"].as_u64().unwrap();
|
||||
for (account, side) in [("6000", "debit"), ("1000", "credit")] {
|
||||
call(
|
||||
c,
|
||||
"books.add_line",
|
||||
json!({"entry_id": id, "account": account, "side": side, "amount": format!("{n}.00")}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
// Bytes of each entry's own: the same bytes stored already would be
|
||||
// named for linking, not uploaded again.
|
||||
let upload = c
|
||||
.upload(
|
||||
format!("receipt {n}").as_bytes(),
|
||||
&format!("r{n}.txt"),
|
||||
"text/plain",
|
||||
)
|
||||
.await;
|
||||
call(
|
||||
c,
|
||||
"books.attach_receipt",
|
||||
json!({"entry_id": id, "upload_id": upload}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
call(
|
||||
c,
|
||||
"books.post_entry",
|
||||
json!({"entry_id": id, "confirmed": true, "no_party_reason": "test"}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Long enough for the server's backup loop (which looks every 2 s) to
|
||||
/// have seen books just made, before they name any target: what it does
|
||||
/// on first seeing them (a backup, a drill) is then done.
|
||||
async fn settle() {
|
||||
tokio::time::sleep(Duration::from_millis(4500)).await;
|
||||
}
|
||||
|
||||
/// Wait until every target holds the books' head (or `within` passes).
|
||||
async fn backed_up(c: &Client, within: Duration) -> Value {
|
||||
let deadline = Instant::now() + within;
|
||||
loop {
|
||||
let s = call(c, "books.backup", json!({})).await.unwrap();
|
||||
let head = s["head_seq"].as_u64().unwrap();
|
||||
let targets = s["targets"].as_array().unwrap();
|
||||
if !targets.is_empty()
|
||||
&& targets
|
||||
.iter()
|
||||
.all(|t| t["through_seq"].as_u64() == Some(head))
|
||||
{
|
||||
return s;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "not backed up in time: {s}");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Prove the backup at `source` (a destination folder, a set's folder, or a
|
||||
/// file) whole; its head.
|
||||
fn proven(home: &Home, source: &Path, tag: &str) -> (u64, String) {
|
||||
let scratch = home.outside(&format!("scratch-{tag}"));
|
||||
let found = find(source, None, &Ctx::new()).unwrap_or_else(|e| panic!("{tag}: {e}"));
|
||||
verify_found(&found, &scratch, &Ctx::new())
|
||||
.unwrap_or_else(|e| panic!("{tag}: {e}"))
|
||||
.head
|
||||
}
|
||||
|
||||
fn live_head(home: &Home, book: &str) -> (u64, String) {
|
||||
let s = ledger_store::Snapshot::load(&home.book_dir(book)).unwrap();
|
||||
(s.journal_seq(), s.head_hash().to_string())
|
||||
}
|
||||
|
||||
const ALL: [&str; 4] = ["read", "write", "post", "admin"];
|
||||
|
||||
/// Restore `source` as `id`: the preview, then (if it was one) the
|
||||
/// restore confirmed against its head. Ok(what was restored) or Err(why).
|
||||
fn restore(home: &Home, id: &str, source: &Path, replace: bool) -> Result<admin::Restored, String> {
|
||||
restore_with(home, id, source, replace, None)
|
||||
}
|
||||
|
||||
fn restore_with(
|
||||
home: &Home,
|
||||
id: &str,
|
||||
source: &Path,
|
||||
replace: bool,
|
||||
passphrase: Option<&str>,
|
||||
) -> Result<admin::Restored, String> {
|
||||
let request = |expect_head: Option<(u64, String)>| Request::Restore {
|
||||
id: id.into(),
|
||||
source: source.display().to_string(),
|
||||
replace,
|
||||
confirmed: expect_head.is_some(),
|
||||
expect_head,
|
||||
passphrase: passphrase.map(|p| admin::Passphrase(p.to_string())),
|
||||
};
|
||||
let preview = match home.admin(request(None)) {
|
||||
Response::RestorePreview(p) => p,
|
||||
Response::Refused(why) => return Err(why),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
match home.admin(request(Some(preview.head.clone()))) {
|
||||
Response::Restored(r) => {
|
||||
assert_eq!(r.head, preview.head);
|
||||
assert_eq!(r.problem, None);
|
||||
Ok(r)
|
||||
}
|
||||
Response::Refused(why) => Err(why),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn books_held(home: &Home) -> Vec<String> {
|
||||
match home.admin(Request::List) {
|
||||
Response::Books(b) => b.into_iter().map(|b| b.id).collect(),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the books say, for comparing two that should be the same.
|
||||
async fn figures(c: &Client) -> Value {
|
||||
json!({
|
||||
"tb": call(c, "books.trial_balance", json!({})).await.unwrap(),
|
||||
"receipts": call(c, "books.list_receipts", json!({})).await.unwrap(),
|
||||
"settings": call(c, "books.settings", json!({})).await.unwrap()["settings"].clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A backup of acme (two entries, a receipt each) in the folder.
|
||||
async fn backed_up_acme(home: &Home) -> (PathBuf, Value) {
|
||||
settle().await;
|
||||
let folder = home.outside("disk");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let c = connect(home, "acme", home.token("acme", &ALL)).await;
|
||||
set_folder(&c, &folder).await;
|
||||
post_one(&c, 4).await;
|
||||
post_one(&c, 5).await;
|
||||
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
(folder, figures(&c).await)
|
||||
}
|
||||
|
||||
/// The files under `dir` whose path (below it) starts with `prefix`.
|
||||
fn files_below(dir: &Path, prefix: &str) -> Vec<PathBuf> {
|
||||
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
for e in std::fs::read_dir(dir).unwrap() {
|
||||
let p = e.unwrap().path();
|
||||
if p.is_dir() {
|
||||
walk(&p, out);
|
||||
} else {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut all = Vec::new();
|
||||
walk(dir, &mut all);
|
||||
all.retain(|p| {
|
||||
p.strip_prefix(dir)
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/")
|
||||
.starts_with(prefix)
|
||||
});
|
||||
all.sort();
|
||||
all
|
||||
}
|
||||
|
||||
fn copy_dir(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 target = to.join(e.file_name());
|
||||
if e.path().is_dir() {
|
||||
copy_dir(&e.path(), &target);
|
||||
} else {
|
||||
std::fs::copy(e.path(), target).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait until the folder's backup has been drilled.
|
||||
async fn drilled(c: &Client) -> Value {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let s = call(c, "books.backup", json!({})).await.unwrap();
|
||||
let targets = s["targets"].as_array().unwrap();
|
||||
if !targets.is_empty() && targets.iter().all(|t| t["last_drill_at"].is_string()) {
|
||||
return s;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "no drill: {s}");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
const PASS: &str = "correct horse battery staple";
|
||||
|
||||
fn said(r: Response) -> String {
|
||||
match r {
|
||||
Response::Said { lines } => lines.join(" "),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_lost_key_file_never_makes_backups_plain() {
|
||||
let home = Home::new("lost-key");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let folder = home.outside("disk");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
said(home.admin(Request::BackupSetup {
|
||||
id: "acme".into(),
|
||||
folder: Some(folder.display().to_string()),
|
||||
passphrase: Some(admin::Passphrase(PASS.into())),
|
||||
remove_passphrase: false,
|
||||
}));
|
||||
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||
post_one(&c, 1).await;
|
||||
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
assert_eq!(s["targets"][0]["sealed"], true);
|
||||
// The key file is lost from this computer (a restored home folder, a
|
||||
// cleaned `local/`).
|
||||
let key = home.book_dir("acme").join("local").join("backup-key.json");
|
||||
std::fs::remove_file(&key).unwrap();
|
||||
let before: Vec<_> = files_below(&folder, "");
|
||||
post_one(&c, 2).await;
|
||||
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||
let t = &s["targets"][0];
|
||||
// Told in words, and nothing was written: no plain copy of the books.
|
||||
let why = t["last_error"].as_str().unwrap_or_default();
|
||||
assert!(why.contains("no longer has its key"), "{s}");
|
||||
assert!(why.contains("remove the passphrase"), "{s}");
|
||||
assert_eq!(t["error_kind"], "key_missing", "{s}");
|
||||
assert_eq!(files_below(&folder, ""), before, "nothing was written");
|
||||
assert!(!folder.join("wanderbooks-acme").exists());
|
||||
// The words a person reads in the window.
|
||||
let standing = match home.admin(Request::BackupStatus { id: "acme".into() }) {
|
||||
Response::BackupStatus(st) => st,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let words = ledger_host::commands::backup_words(&standing).join(" | ");
|
||||
assert!(words.contains("no longer has its key"), "{words}");
|
||||
assert!(
|
||||
words.contains("Enter the backup passphrase again"),
|
||||
"{words}"
|
||||
);
|
||||
|
||||
// Even with the backup record gone (set aside as damaged at the next
|
||||
// open), the folder itself says its backups are sealed.
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
std::fs::write(
|
||||
home.book_dir("acme").join("ops").join("backup.jsonl"),
|
||||
b"not a record\n",
|
||||
)
|
||||
.unwrap();
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||
let s = call(&c, "books.back_up_now", json!({"new_disk": true}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(s["targets"][0]["error_kind"], "key_missing", "{s}");
|
||||
assert!(!folder.join("wanderbooks-acme").exists());
|
||||
|
||||
// Plain is written only after an explicit "remove the passphrase".
|
||||
said(home.admin(Request::BackupSetup {
|
||||
id: "acme".into(),
|
||||
folder: None,
|
||||
passphrase: None,
|
||||
remove_passphrase: true,
|
||||
}));
|
||||
let s = call(&c, "books.back_up_now", json!({"new_disk": true}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
assert_eq!(s["targets"][0]["sealed"], false);
|
||||
assert!(folder.join("wanderbooks-acme").join("manifests").is_dir());
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn books_restored_from_an_older_backup_are_ahead_and_a_new_set_begins_at_their_request() {
|
||||
// Books A back up twice to a folder; books C are restored from a copy of
|
||||
// the folder as it was after the first, and then pointed at the folder
|
||||
// that holds more.
|
||||
let a = Home::new("ahead-a");
|
||||
let server_a = Server::start(&a, Duration::from_secs(3600));
|
||||
a.create("acme");
|
||||
settle().await;
|
||||
let folder = a.outside("disk");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let ca = connect(&a, "acme", a.token("acme", &ALL)).await;
|
||||
set_folder(&ca, &folder).await;
|
||||
post_one(&ca, 1).await;
|
||||
let s = call(&ca, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
let older = a.outside("older");
|
||||
copy_dir(&folder, &older);
|
||||
post_one(&ca, 2).await;
|
||||
let s = call(&ca, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
let longer = live_head(&a, "acme");
|
||||
drop(ca);
|
||||
assert!(server_a.close().success());
|
||||
|
||||
let c_home = Home::new("ahead-c");
|
||||
let server_c = Server::start(&c_home, Duration::from_secs(3600));
|
||||
let restored = restore(&c_home, "acme", &older.join("wanderbooks-acme"), false).unwrap();
|
||||
assert!(restored.head.0 < longer.0);
|
||||
let cc = connect(&c_home, "acme", c_home.token("acme", &ALL)).await;
|
||||
set_folder(&cc, &folder).await;
|
||||
let before = files_below(&folder, "");
|
||||
let bytes: Vec<Vec<u8>> = before.iter().map(|p| std::fs::read(p).unwrap()).collect();
|
||||
let s = call(&cc, "books.back_up_now", json!({})).await.unwrap();
|
||||
let t = &s["targets"][0];
|
||||
// Told as ahead (not diverged), in words that say what to do.
|
||||
assert_eq!(t["error_kind"], "ahead", "{s}");
|
||||
let why = t["last_error"].as_str().unwrap();
|
||||
assert!(why.contains("a longer history of these books"), "{why}");
|
||||
assert!(why.contains("start a new backup set"), "{why}");
|
||||
assert_eq!(files_below(&folder, ""), before, "nothing was written");
|
||||
let standing = match c_home.admin(Request::BackupStatus { id: "acme".into() }) {
|
||||
Response::BackupStatus(st) => st,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let words = ledger_host::commands::backup_words(&standing).join(" | ");
|
||||
assert!(words.contains("start a new backup set"), "{words}");
|
||||
|
||||
// At the person's request: a new set beside the old, which is
|
||||
// untouched; and the backups go on there.
|
||||
match c_home.admin(Request::BackUpNewSet { id: "acme".into() }) {
|
||||
Response::BackedUp { targets, .. } => {
|
||||
assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}");
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(folder.join("wanderbooks-acme.2").join("manifests").is_dir());
|
||||
for (p, b) in before.iter().zip(&bytes) {
|
||||
assert_eq!(&std::fs::read(p).unwrap(), b, "{}", p.display());
|
||||
}
|
||||
post_one(&cc, 9).await;
|
||||
let s = call(&cc, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
assert_eq!(s["targets"][0]["error_kind"], Value::Null, "{s}");
|
||||
assert_eq!(
|
||||
proven(&c_home, &folder.join("wanderbooks-acme.2"), "new").0,
|
||||
live_head(&c_home, "acme").0
|
||||
);
|
||||
// The old set, still whole, still holds the longer history.
|
||||
assert_eq!(
|
||||
proven(&c_home, &folder.join("wanderbooks-acme"), "old"),
|
||||
longer
|
||||
);
|
||||
drop(cc);
|
||||
assert!(server_c.close().success());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_drill_that_finds_only_an_older_backup_is_a_failure_in_words_and_never_ok() {
|
||||
let home = Home::new("older-only");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let (folder, _) = backed_up_acme(&home).await;
|
||||
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||
post_one(&c, 6).await;
|
||||
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
// The newest backup's own segment is damaged after the fact; the one
|
||||
// before it is whole.
|
||||
let set = folder.join("wanderbooks-acme");
|
||||
let newest = files_below(&set, "manifests/").pop().unwrap();
|
||||
let text = std::fs::read_to_string(&newest).unwrap();
|
||||
let m: Value = serde_json::from_str(text.lines().next().unwrap()).unwrap();
|
||||
// Whatever the newest manifest itself adds: a journal, access or index
|
||||
// segment (a manifest names only what is new).
|
||||
let seg = ["journal", "access", "files"]
|
||||
.iter()
|
||||
.find_map(|k| m[*k]["segments"].as_array()?.last().cloned())
|
||||
.expect("the newest manifest adds a segment");
|
||||
let seg = set.join(seg["file"].as_str().unwrap());
|
||||
let mut b = std::fs::read(&seg).unwrap();
|
||||
let mid = b.len() / 2;
|
||||
b[mid] ^= 1;
|
||||
std::fs::write(&seg, b).unwrap();
|
||||
let server = Server::start_with(
|
||||
&home,
|
||||
Duration::from_secs(3600),
|
||||
Some(Duration::from_millis(300)),
|
||||
);
|
||||
let c = connect(&home, "acme", home.token("acme", &["read", "admin"])).await;
|
||||
let s = drilled(&c).await;
|
||||
let t = &s["targets"][0];
|
||||
let why = t["drill_error"].as_str().unwrap_or_default();
|
||||
assert!(why.contains("the newest backup"), "{s}");
|
||||
assert!(why.contains("is damaged; an older one from"), "{s}");
|
||||
assert_eq!(t["error_kind"], "newest_damaged", "{s}");
|
||||
let standing = match home.admin(Request::BackupStatus { id: "acme".into() }) {
|
||||
Response::BackupStatus(st) => st,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let words = ledger_host::commands::backup_words(&standing).join(" | ");
|
||||
assert!(words.contains("failed"), "{words}");
|
||||
assert!(words.contains("older books"), "{words}");
|
||||
assert!(!words.contains("Proven restorable"), "{words}");
|
||||
// A restore from the folder says so before anything else, with both
|
||||
// dates and how many backups it passes over. (The books' own next
|
||||
// backup would find the damage and write the piece again, so the
|
||||
// damage is made again, after the books are closed.)
|
||||
drop(c);
|
||||
assert!(server.close().success());
|
||||
let newest = files_below(&set, "manifests/").pop().unwrap();
|
||||
let text = std::fs::read_to_string(&newest).unwrap();
|
||||
let m: Value = serde_json::from_str(text.lines().next().unwrap()).unwrap();
|
||||
let seg = ["journal", "access", "files"]
|
||||
.iter()
|
||||
.find_map(|k| m[*k]["segments"].as_array()?.last().cloned())
|
||||
.expect("the newest manifest adds a segment");
|
||||
let seg = set.join(seg["file"].as_str().unwrap());
|
||||
let mut b = std::fs::read(&seg).unwrap();
|
||||
let mid = b.len() / 2;
|
||||
b[mid] ^= 1;
|
||||
std::fs::write(&seg, b).unwrap();
|
||||
let other = Home::new("older-only-new");
|
||||
let server = Server::start(&other, Duration::from_secs(3600));
|
||||
match other.admin(Request::Restore {
|
||||
id: "acme".into(),
|
||||
source: folder.display().to_string(),
|
||||
replace: false,
|
||||
confirmed: false,
|
||||
expect_head: None,
|
||||
passphrase: None,
|
||||
}) {
|
||||
Response::RestorePreview(p) => {
|
||||
assert!(p.passed_over >= 1, "{p:?}");
|
||||
assert!(p.written.is_some() && p.newest_written.is_some(), "{p:?}");
|
||||
let words = ledger_host::commands::older_backup_words(&p);
|
||||
assert!(words.starts_with("NOT THE NEWEST BACKUP"), "{words}");
|
||||
assert!(words.contains("passes over "), "{words}");
|
||||
assert!(words.contains(" newer backup"), "{words}");
|
||||
assert!(words.contains("This backup is from"), "{words}");
|
||||
assert!(
|
||||
words.contains("the newest in the folder is from"),
|
||||
"{words}"
|
||||
);
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(server.close().success());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_folder_a_sync_service_keeps_is_said_in_plain_words_at_set_up() {
|
||||
let home = Home::new("sync");
|
||||
let server = Server::start(&home, Duration::from_secs(3600));
|
||||
home.create("acme");
|
||||
let dropbox = home.outside("Dropbox/Backups");
|
||||
std::fs::create_dir_all(&dropbox).unwrap();
|
||||
let words = said(home.admin(Request::BackupSetup {
|
||||
id: "acme".into(),
|
||||
folder: Some(dropbox.display().to_string()),
|
||||
passphrase: None,
|
||||
remove_passphrase: false,
|
||||
}));
|
||||
assert!(words.contains("kept in sync by Dropbox"), "{words}");
|
||||
assert!(words.contains("one computer only"), "{words}");
|
||||
assert!(words.contains("available offline"), "{words}");
|
||||
assert!(words.contains("a folder of its own"), "{words}");
|
||||
// A folder no service is known to keep still gets the general words.
|
||||
let plain = home.outside("a-usb-stick");
|
||||
std::fs::create_dir_all(&plain).unwrap();
|
||||
let words = said(home.admin(Request::BackupSetup {
|
||||
id: "acme".into(),
|
||||
folder: Some(plain.display().to_string()),
|
||||
passphrase: None,
|
||||
remove_passphrase: false,
|
||||
}));
|
||||
assert!(
|
||||
words.contains("If this folder is kept in sync by a service"),
|
||||
"{words}"
|
||||
);
|
||||
assert!(words.contains("one computer only"), "{words}");
|
||||
// And the window shows the same, under the status.
|
||||
let standing = match home.admin(Request::BackupStatus { id: "acme".into() }) {
|
||||
Response::BackupStatus(st) => st,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let lines = ledger_host::commands::backup_words(&standing).join(" | ");
|
||||
assert!(lines.contains("one computer only"), "{lines}");
|
||||
assert!(server.close().success());
|
||||
}
|
||||
@@ -157,6 +157,10 @@ pub struct BackupState {
|
||||
pub folder: Option<String>,
|
||||
/// Protected by a passphrase.
|
||||
pub sealed: bool,
|
||||
/// The folder holds a longer history of these books than they have
|
||||
/// now (the books were restored from an older backup): a new backup set
|
||||
/// can be started beside the old one.
|
||||
pub ahead: bool,
|
||||
}
|
||||
|
||||
/// A restore previewed: what it would do, and what it is of (INVARIANT 3).
|
||||
@@ -465,6 +469,12 @@ pub trait Owner: Send + Sync {
|
||||
fn new_books(&self, id: &str, currency: &str) -> Result<String, String>;
|
||||
/// Back the books `book` up now.
|
||||
fn back_up_now(&self, book: &str) -> Result<Vec<String>, String>;
|
||||
/// Start a new backup set beside the old one in the backup folder and
|
||||
/// back the books up to it (their history is the beginning of the old
|
||||
/// set's): the old set is never touched.
|
||||
fn start_new_backup_set(&self, _book: &str) -> Result<Vec<String>, String> {
|
||||
Err("not here".into())
|
||||
}
|
||||
/// How the books `book`'s backups stand. Blocks.
|
||||
fn backup_state(&self, _book: &str) -> Result<BackupState, String> {
|
||||
Err("not here".into())
|
||||
@@ -677,6 +687,10 @@ impl Drop for BackupForm {
|
||||
|
||||
/// The words a person is told when setting a passphrase: what it does, and
|
||||
/// that it cannot be recovered (D-92).
|
||||
/// What the first line of a restore that is not of the newest backup begins
|
||||
/// with (ledger-host `older_backup_words`): the window shows it prominently.
|
||||
pub const OLDER_BACKUP: &str = "NOT THE NEWEST BACKUP";
|
||||
|
||||
pub const PASSPHRASE_WARNING: &str = "Every file in the backup folder is sealed: only this passphrase opens it, and the files say nothing about your books but how many and how big. Your computer keeps the key so backups stay automatic. A forgotten passphrase cannot be recovered, by anyone, and backups made without it before this stay as they were. Write it down somewhere safe.";
|
||||
|
||||
/// The format upgrade's dialog (INVARIANT 5).
|
||||
@@ -1344,7 +1358,16 @@ impl OwnerMenu {
|
||||
if let Some(plan) = &form.plan {
|
||||
ui.separator();
|
||||
for line in &plan.lines {
|
||||
ui.label(line);
|
||||
// A restore that is not of the newest backup
|
||||
// says so first and in the warning colour.
|
||||
if line.starts_with(OLDER_BACKUP) {
|
||||
ui.colored_label(
|
||||
crate::theme::pal(ui.ctx()).warning,
|
||||
egui::RichText::new(line).strong(),
|
||||
);
|
||||
} else {
|
||||
ui.label(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
@@ -1476,6 +1499,20 @@ fn backups_dialog(
|
||||
for line in &state.lines {
|
||||
ui.label(line);
|
||||
}
|
||||
if state.ahead
|
||||
&& ui
|
||||
.button("Start a new backup set here")
|
||||
.on_hover_text("The old set stays in the folder, untouched; these books back up to a new one beside it")
|
||||
.clicked()
|
||||
{
|
||||
let (o, b) = (owner.clone(), book.to_string());
|
||||
*run = Some((
|
||||
"Backups".into(),
|
||||
Effect::Changes("Starting a new backup set"),
|
||||
Box::new(move || o.start_new_backup_set(&b)),
|
||||
));
|
||||
*close = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let sealed = matches!(&form.state, Some(Ok(s)) if s.sealed);
|
||||
|
||||
@@ -77,6 +77,7 @@ impl Owner for Fake {
|
||||
],
|
||||
folder: None,
|
||||
sealed: false,
|
||||
ahead: false,
|
||||
})
|
||||
}
|
||||
fn set_up_backups(
|
||||
|
||||
@@ -749,7 +749,7 @@ fn books_usage(prog: &str) {
|
||||
" {prog} adopt DATA-DIR --id ID [--toml FILE] [--config-json FILE] [--vault DIR --vault-key FILE | --no-vault] [--skip-unknown] [--yes]"
|
||||
);
|
||||
eprintln!(" {prog} restore BACKUP [--id ID] [--replace] [--yes]");
|
||||
eprintln!(" {prog} back-up ID [--new-disk]");
|
||||
eprintln!(" {prog} back-up ID [--new-disk | --new-set]");
|
||||
eprintln!(" {prog} backup-status ID");
|
||||
eprintln!(
|
||||
" {prog} backup-setup ID [--folder FOLDER] [--passphrase | --remove-passphrase]"
|
||||
@@ -772,7 +772,7 @@ fn books_usage(prog: &str) {
|
||||
eprintln!(" create start new, empty books (base currency USD unless given)");
|
||||
eprintln!(" adopt copy existing books in, verified; the original is left as it was");
|
||||
eprintln!(
|
||||
" back-up back the books up now to every backup their settings name (--new-disk: the backup folder's disk is new)"
|
||||
" back-up back the books up now to every backup their settings name (--new-disk: the backup folder's disk is new; --new-set: the folder holds a longer history of these books, as after a restore from an older backup, so begin a new set beside it)"
|
||||
);
|
||||
eprintln!(
|
||||
" restore bring back a backup (your backup folder, the folder of one set of books in it, or a backup file), proven whole first: as new books, or replacing books (kept in legacy/)"
|
||||
@@ -806,6 +806,7 @@ pub fn books(
|
||||
let mut yes = false;
|
||||
let mut replace = false;
|
||||
let mut new_disk = false;
|
||||
let mut new_set = false;
|
||||
let mut folder: Option<String> = None;
|
||||
let mut ask_passphrase = false;
|
||||
let mut remove_passphrase = false;
|
||||
@@ -829,6 +830,7 @@ pub fn books(
|
||||
"--skip-unknown" => skip_unknown = true,
|
||||
"--replace" => replace = true,
|
||||
"--new-disk" => new_disk = true,
|
||||
"--new-set" => new_set = true,
|
||||
"--yes" => yes = true,
|
||||
"--help" | "-h" => {
|
||||
books_usage(prog);
|
||||
@@ -983,7 +985,7 @@ pub fn books(
|
||||
};
|
||||
}
|
||||
["back-up", book] => {
|
||||
return match back_up_now(&common, book, new_disk) {
|
||||
return match back_up_now(&common, book, new_disk, new_set) {
|
||||
Ok(lines) => {
|
||||
for line in lines {
|
||||
println!("{line}");
|
||||
@@ -1225,14 +1227,23 @@ fn database_line(b: &admin::BookStatus) -> Option<String> {
|
||||
|
||||
/// Back the books `book` up now (the server does it): what came of it, a
|
||||
/// line each; Err when it couldn't be done, or a target didn't take it.
|
||||
pub fn back_up_now(common: &Common, book: &str, new_disk: bool) -> Result<Vec<String>, String> {
|
||||
match with_server(
|
||||
common,
|
||||
pub fn back_up_now(
|
||||
common: &Common,
|
||||
book: &str,
|
||||
new_disk: bool,
|
||||
new_set: bool,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let request = if new_set {
|
||||
Request::BackUpNewSet {
|
||||
id: book.to_string(),
|
||||
}
|
||||
} else {
|
||||
Request::BackUpNow {
|
||||
id: book.to_string(),
|
||||
new_disk,
|
||||
},
|
||||
)? {
|
||||
}
|
||||
};
|
||||
match with_server(common, request)? {
|
||||
Response::BackedUp { head_seq, targets } => {
|
||||
let lines = backed_up_lines(head_seq, &targets);
|
||||
if targets.is_empty() || targets.iter().any(|t| t.problem.is_some()) {
|
||||
@@ -1298,6 +1309,25 @@ fn when(utc: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// What a restore says before anything else when it is not of the newest
|
||||
/// backup there is: both dates, and how many backups it passes over.
|
||||
pub fn older_backup_words(p: &admin::RestorePreview) -> String {
|
||||
let day = |at: &Option<String>| at.as_deref().map(when);
|
||||
let (this, newest) = (day(&p.written), day(&p.newest_written));
|
||||
let dates = match (this, newest) {
|
||||
(Some(a), Some(b)) => format!(
|
||||
" This backup is from {a}; the newest in the folder is from {b} and is not whole."
|
||||
),
|
||||
(Some(a), None) => format!(" This backup is from {a}."),
|
||||
_ => String::new(),
|
||||
};
|
||||
format!(
|
||||
"NOT THE NEWEST BACKUP: this restore passes over {} newer backup{} that did not prove whole, and brings back older books than the folder holds.{dates} Anything written after this backup is not in it.",
|
||||
p.passed_over,
|
||||
if p.passed_over == 1 { "" } else { "s" }
|
||||
)
|
||||
}
|
||||
|
||||
/// The words for a backup standing, as an ordinary person reads them.
|
||||
pub fn backup_words(s: &admin::BackupStanding) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
@@ -1309,6 +1339,19 @@ pub fn backup_words(s: &admin::BackupStanding) -> Vec<String> {
|
||||
lines.push("The disk with the backup is not connected: connect it, and the next backup goes there. If it is a new disk, say so when you back up now.".into());
|
||||
} else if let Some(why) = &s.last_error {
|
||||
lines.push(format!("The last backup didn't work: {why}"));
|
||||
match s.error_kind.as_deref() {
|
||||
Some("ahead") => lines.push("This usually means the books were restored from an older backup. To carry on with these books, start a new backup set: the old one stays in the folder, untouched.".into()),
|
||||
Some("elsewhere") => lines.push("Nothing was written there. If these are the right books, choose another backup folder.".into()),
|
||||
Some("key_missing") => lines.push("Enter the backup passphrase again in the backup settings to carry on, or remove the passphrase there to back up without one.".into()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !s.damaged_files.is_empty() {
|
||||
lines.push(format!(
|
||||
"{} file(s) in the backup folder were found damaged and were written again; the damaged ones are left where they are (nothing in the folder is ever deleted), and you may delete them yourself: {}",
|
||||
s.damaged_files.len(),
|
||||
s.damaged_files.join(", ")
|
||||
));
|
||||
}
|
||||
match (&s.last_ok_at, s.through_seq) {
|
||||
(Some(at), Some(seq)) => lines.push(format!(
|
||||
@@ -1326,9 +1369,16 @@ pub fn backup_words(s: &admin::BackupStanding) -> Vec<String> {
|
||||
_ => lines.push("No backup has been made there yet.".into()),
|
||||
}
|
||||
match (&s.last_drill_at, &s.drill_error) {
|
||||
(_, Some(why)) => lines.push(format!(
|
||||
"The weekly check that the backup can be restored failed: {why}"
|
||||
)),
|
||||
(_, Some(why)) => {
|
||||
lines.push(format!(
|
||||
"The weekly check that the backup can be restored failed: {why}"
|
||||
));
|
||||
if s.error_kind.as_deref() == Some("newest_damaged")
|
||||
|| why.contains("newest backup")
|
||||
{
|
||||
lines.push("Back up again now: a restore from this folder would give older books until a backup after the damage is made.".into());
|
||||
}
|
||||
}
|
||||
(Some(at), None) => lines.push(format!("Proven restorable {at} (checked weekly).")),
|
||||
(None, None) if s.through_seq.is_some() => {
|
||||
lines.push("Not yet proven restorable: it is checked weekly.".into())
|
||||
@@ -1340,6 +1390,9 @@ pub fn backup_words(s: &admin::BackupStanding) -> Vec<String> {
|
||||
} else {
|
||||
"Not protected by a passphrase.".into()
|
||||
});
|
||||
if let Some(sync) = &s.sync {
|
||||
lines.push(sync.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(note) = &s.note {
|
||||
@@ -2903,10 +2956,9 @@ pub fn plan_restore(
|
||||
preview.vault_files
|
||||
)];
|
||||
if preview.passed_over > 0 {
|
||||
lines.push(format!(
|
||||
"{} newer backup(s) in it were damaged and passed over: this is the newest that is whole.",
|
||||
preview.passed_over
|
||||
));
|
||||
// First, before anything else: books older than the newest backup
|
||||
// there is are not what a person expects to get.
|
||||
lines.insert(0, older_backup_words(&preview));
|
||||
}
|
||||
if preview.sealed {
|
||||
lines.push(
|
||||
@@ -4375,6 +4427,9 @@ mod tests {
|
||||
drill_error: None,
|
||||
disconnected: false,
|
||||
note: None,
|
||||
error_kind: None,
|
||||
damaged_files: Vec::new(),
|
||||
sync: None,
|
||||
};
|
||||
let say = |s: &admin::BackupStanding| backup_words(s).join(" | ");
|
||||
assert_eq!(say(&base), "Not backed up: no backup folder is chosen yet.");
|
||||
|
||||
@@ -147,6 +147,14 @@ pub enum Request {
|
||||
#[serde(default)]
|
||||
new_disk: bool,
|
||||
},
|
||||
/// Begin a new backup set beside the old one in the backup folder, and
|
||||
/// back the books up to it (the books are behind the folder's: as
|
||||
/// after a restore from an older backup): only at the person's
|
||||
/// request; the old set is never touched.
|
||||
BackUpNewSet {
|
||||
/// The books.
|
||||
id: String,
|
||||
},
|
||||
/// Set up a book's backups (D-91, D-92): the folder, and the
|
||||
/// passphrase.
|
||||
BackupSetup {
|
||||
@@ -696,9 +704,16 @@ pub struct RestorePreview {
|
||||
/// Whether it is protected by a passphrase.
|
||||
#[serde(default)]
|
||||
pub sealed: bool,
|
||||
/// Newer backups in it that were not whole and were passed over.
|
||||
/// Newer backups in it that were not whole or were damaged and were
|
||||
/// passed over: not zero means this is not the newest backup there is.
|
||||
#[serde(default)]
|
||||
pub passed_over: u64,
|
||||
/// When this backup was made (UTC), as its manifest says.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub written: Option<String>,
|
||||
/// When the newest backup there is was made (UTC), if it can be read.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub newest_written: Option<String>,
|
||||
}
|
||||
|
||||
/// What a restore did.
|
||||
@@ -770,6 +785,17 @@ pub struct BackupStanding {
|
||||
/// What to know or do: none set up, an older kind no longer used.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub note: Option<String>,
|
||||
/// What kind of trouble the last backup or check had (`ahead`,
|
||||
/// `elsewhere`, `key_missing`, `not_downloaded`, `newest_damaged`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub error_kind: Option<String>,
|
||||
/// Files in the backup folder found damaged and written again; each is
|
||||
/// left where it is.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub damaged_files: Vec<String>,
|
||||
/// What to tell a person of a folder a sync service keeps (or may).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub sync: Option<String>,
|
||||
}
|
||||
|
||||
/// The server's answer.
|
||||
@@ -947,7 +973,7 @@ pub fn call_within(
|
||||
Request::Create { .. } | Request::Adopt { .. } | Request::Restore { .. } => {
|
||||
Some("`wanderbooks books list` shows the books there are")
|
||||
}
|
||||
Request::BackUpNow { .. } => {
|
||||
Request::BackUpNow { .. } | Request::BackUpNewSet { .. } => {
|
||||
Some("`wanderbooks books back-up` again backs up whatever it didn't")
|
||||
}
|
||||
Request::TokenCreate { .. } | Request::TokenRevoke { .. } => {
|
||||
@@ -1162,6 +1188,8 @@ mod tests {
|
||||
origin: Some("acme".into()),
|
||||
sealed: false,
|
||||
passed_over: 0,
|
||||
written: None,
|
||||
newest_written: None,
|
||||
}),
|
||||
Response::Restored(Restored {
|
||||
id: "acme".into(),
|
||||
|
||||
@@ -317,21 +317,36 @@ pub const OLD_ARCHIVE: &str = "An older backup folder from an earlier version is
|
||||
/// push that was made sealed or plain), with the key's fingerprint, which
|
||||
/// opens nothing.
|
||||
fn sealed_before(records: &[Map<String, Value>]) -> Option<(bool, Option<String>)> {
|
||||
records.iter().rev().find_map(|r| {
|
||||
let says = |r: &Map<String, Value>| -> Option<bool> {
|
||||
if is(r, "setup") {
|
||||
match r.get("passphrase").and_then(Value::as_str) {
|
||||
Some("set") => Some((true, text(r, "fp"))),
|
||||
Some("removed") => Some((false, None)),
|
||||
Some("set") => Some(true),
|
||||
Some("removed") => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
} else if is(r, "push") {
|
||||
r.get("sealed")
|
||||
.and_then(Value::as_bool)
|
||||
.map(|sealed| (sealed, text(r, "fp")))
|
||||
r.get("sealed").and_then(Value::as_bool)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
};
|
||||
let (at, sealed) = records
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find_map(|(i, r)| says(r).map(|s| (i, s)))?;
|
||||
// The fingerprint of the key the backups were sealed with: the newest
|
||||
// record that was made with one (a push that couldn't be made says
|
||||
// none).
|
||||
let fp = sealed
|
||||
.then(|| {
|
||||
records[..=at]
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|r| says(r).filter(|s| *s).and_then(|_| text(r, "fp")))
|
||||
})
|
||||
.flatten();
|
||||
Some((sealed, fp))
|
||||
}
|
||||
|
||||
/// The records of a book's backup log, if it can be read.
|
||||
|
||||
@@ -1614,42 +1614,8 @@ impl Books {
|
||||
Err(why) => Response::Refused(self.hide(why)),
|
||||
}
|
||||
}
|
||||
Request::BackUpNow { id, new_disk } => {
|
||||
let id = match BookId::parse(&id) {
|
||||
Ok(id) => id,
|
||||
Err(e) => return refused(e),
|
||||
};
|
||||
let backups = match self.held().get(id.as_str()) {
|
||||
Some(Book::Open { backups, .. }) => backups.clone(),
|
||||
Some(Book::Failed(why)) => {
|
||||
return Response::Refused(format!("those books didn't open: {why}"));
|
||||
}
|
||||
Some(Book::Closed) => return Response::Refused(self.not_open(&id)),
|
||||
None => {
|
||||
return Response::Refused(format!(
|
||||
"there are no books called {:?}",
|
||||
id.as_str()
|
||||
));
|
||||
}
|
||||
};
|
||||
let rt = tokio::runtime::Handle::current();
|
||||
match rt.block_on(backups.run_with("asked", new_disk)) {
|
||||
Ok(status) => Response::BackedUp {
|
||||
head_seq: status.head_seq,
|
||||
targets: status
|
||||
.targets
|
||||
.into_iter()
|
||||
.map(|t| admin::BackedUpTarget {
|
||||
target: t.target,
|
||||
at: t.at,
|
||||
through_seq: t.through_seq,
|
||||
problem: t.last_error,
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
Err(why) => Response::Refused(self.hide(why)),
|
||||
}
|
||||
}
|
||||
Request::BackUpNewSet { id } => self.back_up_response(&id, false, true),
|
||||
Request::BackUpNow { id, new_disk } => self.back_up_response(&id, new_disk, false),
|
||||
Request::BackupSetup {
|
||||
id,
|
||||
folder,
|
||||
@@ -1685,6 +1651,9 @@ impl Books {
|
||||
drill_error: t.and_then(|t| t.drill_error.clone()),
|
||||
disconnected: t.is_some_and(|t| t.disconnected),
|
||||
note: s.status.note,
|
||||
error_kind: t.and_then(|t| t.error_kind.clone()),
|
||||
damaged_files: t.map(|t| t.damaged_files.clone()).unwrap_or_default(),
|
||||
sync: s.sync,
|
||||
})
|
||||
}
|
||||
Err(r) => *r,
|
||||
@@ -2225,6 +2194,42 @@ impl Books {
|
||||
|
||||
/// The backups of the open book `id`, or the refusal to give a request
|
||||
/// that needs them.
|
||||
/// Back the books `id` up now (`new_disk`: their disk is new; `new_set`:
|
||||
/// begin a new set beside the old one), what came of it.
|
||||
fn back_up_response(&self, id: &str, new_disk: bool, new_set: bool) -> Response {
|
||||
let id = match BookId::parse(id) {
|
||||
Ok(id) => id,
|
||||
Err(e) => return Response::Refused(e.to_string()),
|
||||
};
|
||||
let backups = match self.held().get(id.as_str()) {
|
||||
Some(Book::Open { backups, .. }) => backups.clone(),
|
||||
Some(Book::Failed(why)) => {
|
||||
return Response::Refused(format!("those books didn't open: {why}"));
|
||||
}
|
||||
Some(Book::Closed) => return Response::Refused(self.not_open(&id)),
|
||||
None => {
|
||||
return Response::Refused(format!("there are no books called {:?}", id.as_str()));
|
||||
}
|
||||
};
|
||||
let rt = tokio::runtime::Handle::current();
|
||||
match rt.block_on(backups.run_with_set("asked", new_disk, new_set)) {
|
||||
Ok(status) => Response::BackedUp {
|
||||
head_seq: status.head_seq,
|
||||
targets: status
|
||||
.targets
|
||||
.into_iter()
|
||||
.map(|t| admin::BackedUpTarget {
|
||||
target: t.target,
|
||||
at: t.at,
|
||||
through_seq: t.through_seq,
|
||||
problem: t.last_error,
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
Err(why) => Response::Refused(self.hide(why)),
|
||||
}
|
||||
}
|
||||
|
||||
fn backups_of(&self, id: &str) -> Result<Arc<crate::backup::Backups>, Box<Response>> {
|
||||
let refused = |text: String| Box::new(Response::Refused(self.hide(text)));
|
||||
let id = BookId::parse(id).map_err(|e| refused(e.to_string()))?;
|
||||
@@ -2287,6 +2292,8 @@ impl Books {
|
||||
origin: p.origin,
|
||||
sealed: p.sealed,
|
||||
passed_over: p.passed_over,
|
||||
written: p.written,
|
||||
newest_written: p.newest_written,
|
||||
}),
|
||||
Err(e) => said(e.to_string()),
|
||||
};
|
||||
|
||||
@@ -25,6 +25,12 @@ pub struct BackUpNowParams {
|
||||
/// should hold one is otherwise a disk not connected.
|
||||
#[serde(default)]
|
||||
pub new_disk: bool,
|
||||
/// The backup folder holds a longer history of these books than they
|
||||
/// have now (a restore from an older backup): begin a new backup set
|
||||
/// beside the old one, which is never touched. Only when the human
|
||||
/// says so.
|
||||
#[serde(default)]
|
||||
pub new_set: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
@@ -39,6 +45,16 @@ pub struct TargetOut {
|
||||
pub through_seq: Option<u64>,
|
||||
/// More than a day without the books' latest: tell the human.
|
||||
pub stale: bool,
|
||||
/// What kind of trouble the last backup or check had: `ahead` (the
|
||||
/// folder holds a longer history of these books: offer new_set),
|
||||
/// `elsewhere` (other or diverged books), `key_missing` (the backups
|
||||
/// are sealed and this computer lost the key: ask the human for the
|
||||
/// passphrase), `not_downloaded` (files a sync service has not put here
|
||||
/// yet), `newest_damaged` (a restore would give older books).
|
||||
pub error_kind: Option<String>,
|
||||
/// Files in the backup folder found damaged and written again (each is
|
||||
/// left where it is): tell the human.
|
||||
pub damaged_files: Vec<String>,
|
||||
/// Why its last backup failed, if it did.
|
||||
pub last_error: Option<String>,
|
||||
/// When its backup was last proven restorable (UTC), if ever: each
|
||||
@@ -76,6 +92,8 @@ impl From<crate::backup::Status> for BackupOut {
|
||||
last_ok_at: t.last_ok_at,
|
||||
through_seq: t.through_seq,
|
||||
stale: t.stale,
|
||||
error_kind: t.error_kind,
|
||||
damaged_files: t.damaged_files,
|
||||
last_error: t.last_error,
|
||||
last_drill_at: t.last_drill_at,
|
||||
drill_error: t.drill_error,
|
||||
@@ -102,7 +120,7 @@ impl BooksServer {
|
||||
#[tool(
|
||||
name = "books.back_up_now",
|
||||
title = "Back up now",
|
||||
description = "Back the books up now to the backup folder the settings name, and answer how it went (as books.backup). new_disk: true only when the human says the backup folder's disk is new: the books' backup is then begun there again. Needs books:admin.",
|
||||
description = "Back the books up now to the backup folder the settings name, and answer how it went (as books.backup). new_disk: true only when the human says the backup folder's disk is new: the books' backup is then begun there again. new_set: true only when the human says so after a backup failed because the folder holds a longer history of these books (error_kind ahead): a new set begins beside the old one. Needs books:admin.",
|
||||
annotations(
|
||||
read_only_hint = false,
|
||||
destructive_hint = false,
|
||||
@@ -116,7 +134,11 @@ impl BooksServer {
|
||||
) -> Result<Json<BackupOut>, String> {
|
||||
// Stopped by a close (backup.rs INVARIANT 11): said so, and on
|
||||
// record as stopped, not as an answer it gave.
|
||||
match self.backups.run_with("asked", params.0.new_disk).await {
|
||||
match self
|
||||
.backups
|
||||
.run_with_set("asked", params.0.new_disk, params.0.new_set)
|
||||
.await
|
||||
{
|
||||
Ok(status) => Ok(Json(status.into())),
|
||||
Err(why) if why.starts_with(crate::server::STOPPED_BY_CLOSE_WORDS) => {
|
||||
crate::server::stopped_by_close();
|
||||
|
||||
@@ -19,6 +19,10 @@ pub(crate) const VERSION: u32 = 1;
|
||||
pub(crate) const SET_PREFIX: &str = "wanderbooks-";
|
||||
/// The folder of manifests in a set.
|
||||
pub(crate) const MANIFESTS: &str = "manifests";
|
||||
/// The folder of proof marks in a set: one tiny file per manifest whose
|
||||
/// proof (write.rs) came out whole, so a manifest whose proof was cut short
|
||||
/// is proven by the next backup, even one with nothing new to write.
|
||||
pub(crate) const PROOFS: &str = "proofs";
|
||||
/// The words a person can open.
|
||||
pub(crate) const READ_ME: &str = "READ-ME.txt";
|
||||
/// The sealed form's header: how to derive the key.
|
||||
@@ -210,6 +214,11 @@ pub(crate) fn manifest_path(number: u64, sealed: bool) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The mark that manifest `number` was proven whole.
|
||||
pub(crate) fn proof_path(number: u64) -> String {
|
||||
format!("{PROOFS}/{number:06}")
|
||||
}
|
||||
|
||||
/// The number a manifest file name carries, if it is one.
|
||||
pub(crate) fn manifest_number(name: &str, sealed: bool) -> Option<u64> {
|
||||
let digits = if sealed {
|
||||
|
||||
@@ -228,6 +228,10 @@ pub struct Ctx {
|
||||
/// Tests: nothing is synced to disk (a destination of thousands of
|
||||
/// backups is made quickly; a real one never is).
|
||||
no_sync: bool,
|
||||
/// Tests: the proof after a backup is left out (for the tests that make
|
||||
/// many backups only to see what is written, which prove what they
|
||||
/// made themselves).
|
||||
no_proof: bool,
|
||||
/// Tests: told each read and length look at a file of the set.
|
||||
trace: Option<Trace>,
|
||||
}
|
||||
@@ -297,6 +301,18 @@ impl Ctx {
|
||||
self
|
||||
}
|
||||
|
||||
/// The proof after a backup is left out (tests that make many backups
|
||||
/// only to see what is written; the proof has tests of its own).
|
||||
#[doc(hidden)]
|
||||
pub fn with_proof_skipped(mut self) -> Self {
|
||||
self.no_proof = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn skips_proof(&self) -> bool {
|
||||
self.no_proof
|
||||
}
|
||||
|
||||
pub(crate) fn syncs(&self) -> bool {
|
||||
!self.no_sync
|
||||
}
|
||||
|
||||
@@ -200,6 +200,11 @@ impl Set {
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Whether the proof after a backup came out whole for manifest `n`.
|
||||
pub(crate) fn proven(&self, n: u64) -> bool {
|
||||
matches!(self.io.len(&proof_path(n)), Ok(Some(_)))
|
||||
}
|
||||
|
||||
fn read_small(&self, rel: &str) -> Result<Vec<u8>, BackupError> {
|
||||
match self.io.len(rel)? {
|
||||
Some(len) if len <= SMALL_MAX => {}
|
||||
@@ -547,6 +552,18 @@ pub struct Found {
|
||||
pub sealed: bool,
|
||||
}
|
||||
|
||||
impl Found {
|
||||
/// A set already open (a backup file just written), to be proven.
|
||||
pub(crate) fn of(set: Set, key: Option<BackupKey>, book: &str) -> Found {
|
||||
Found {
|
||||
sealed: set.sealed(),
|
||||
set,
|
||||
key,
|
||||
book: Some(book.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One set of books in a folder, as listed for a person to choose from.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Candidate {
|
||||
@@ -727,6 +744,9 @@ pub struct Verified {
|
||||
pub number: u64,
|
||||
/// When it was made (UTC), as its manifest says.
|
||||
pub written: String,
|
||||
/// The journal's length in the backup: the books built from it hold
|
||||
/// the journal as it was, and may carry the books' own recovery after.
|
||||
pub journal_bytes: u64,
|
||||
/// How many newer backups there are that were passed over: not whole,
|
||||
/// or damaged. Not zero means this is not the newest backup there is.
|
||||
pub passed_over: usize,
|
||||
@@ -922,15 +942,23 @@ fn prove_books(
|
||||
) -> Result<(u64, (u64, String)), BackupError> {
|
||||
ctx.phase("replay");
|
||||
let _stoppable = ctx.stop_flag().map(crate::cancel::scope);
|
||||
if matches!(depth, Depth::Chain) {
|
||||
// The hash chain, up to the head, before the books are opened.
|
||||
let lines = crate::journal::read_and_verify_journal(&scratch.join(crate::JOURNAL_FILE))?;
|
||||
let last = lines.last().map(|l| l.seq).unwrap_or(0);
|
||||
if last != m.head.seq {
|
||||
return Err(BackupError::Damaged(format!(
|
||||
"its journal ends at event {last}, but the backup records another head"
|
||||
)));
|
||||
}
|
||||
// The hash chain, up to the head, before the books are opened: the
|
||||
// journal the pieces make ends at the head the manifest records. (A
|
||||
// backup taken while a call is under way ends with the call's lines
|
||||
// unfinished: opening the books settles it by appending a line, which
|
||||
// is the books' recovery and not the backup's head.)
|
||||
let lines = crate::journal::read_and_verify_journal(&scratch.join(crate::JOURNAL_FILE))?;
|
||||
let (last_seq, last_hash) = match lines.last() {
|
||||
Some(l) => (
|
||||
l.seq,
|
||||
crate::journal::sha256_hex(l.to_canonical().as_bytes()),
|
||||
),
|
||||
None => (0, String::new()),
|
||||
};
|
||||
if last_seq != m.head.seq || (last_seq > 0 && last_hash != m.head.hash) {
|
||||
return Err(BackupError::Damaged(format!(
|
||||
"its journal ends at event {last_seq}, but the backup records another head"
|
||||
)));
|
||||
}
|
||||
let mut store = crate::Store::open(scratch)?;
|
||||
if matches!(depth, Depth::Whole) {
|
||||
@@ -949,7 +977,7 @@ fn prove_books(
|
||||
Depth::Whole => store.verify_blobs()?,
|
||||
Depth::Chain => audit.files_read,
|
||||
};
|
||||
let head = store.head();
|
||||
let opened = store.head();
|
||||
let tins: Vec<String> = store
|
||||
.ledger()
|
||||
.parties()
|
||||
@@ -982,13 +1010,14 @@ fn prove_books(
|
||||
));
|
||||
}
|
||||
}
|
||||
if head.0 != m.head.seq || head.1 != m.head.hash {
|
||||
// Opening may only have added the books' own recovery after the head.
|
||||
if opened.0 < m.head.seq {
|
||||
return Err(BackupError::Damaged(format!(
|
||||
"its journal ends at event {}, but the backup records another head",
|
||||
head.0
|
||||
opened.0
|
||||
)));
|
||||
}
|
||||
Ok((blobs, head))
|
||||
Ok((blobs, (m.head.seq, m.head.hash.clone())))
|
||||
}
|
||||
|
||||
/// The books built from manifest `m` into `scratch` and proven, whole.
|
||||
@@ -1102,6 +1131,7 @@ fn verify_one(
|
||||
book: Some(m.book.clone()),
|
||||
number: m.number,
|
||||
written: m.written.clone(),
|
||||
journal_bytes: m.journal.bytes,
|
||||
passed_over: passed,
|
||||
newest_written: if n == newest {
|
||||
Some(m.written.clone())
|
||||
@@ -1153,9 +1183,9 @@ pub fn verify_found(found: &Found, scratch: &Path, ctx: &Ctx) -> Result<Verified
|
||||
|
||||
/// Whether the journal at `backup` is a byte prefix of the one at `live`
|
||||
/// (a drill: the backup holds the book's history, nothing else).
|
||||
pub fn is_prefix(live: &Path, backup: &Path, ctx: &Ctx) -> Result<bool, BackupError> {
|
||||
pub fn is_prefix(live: &Path, backup: &Path, len: u64, ctx: &Ctx) -> Result<bool, BackupError> {
|
||||
let mut a = std::fs::File::open(live)?;
|
||||
let mut b = std::fs::File::open(backup)?;
|
||||
let mut b = std::io::Read::take(std::fs::File::open(backup)?, len);
|
||||
let (mut x, mut y) = (vec![0u8; 64 * 1024], vec![0u8; 64 * 1024]);
|
||||
loop {
|
||||
ctx.check("comparing journals")?;
|
||||
@@ -1228,7 +1258,12 @@ pub fn drill(
|
||||
v.head.0, e.0
|
||||
)))
|
||||
} else {
|
||||
match is_prefix(live, &v.tree.join(crate::JOURNAL_FILE), ctx) {
|
||||
match is_prefix(
|
||||
live,
|
||||
&v.tree.join(crate::JOURNAL_FILE),
|
||||
v.journal_bytes,
|
||||
ctx,
|
||||
) {
|
||||
Ok(true) => Ok(v.head),
|
||||
Ok(false) => Err(BackupError::Damaged(
|
||||
"its journal isn't this book's history".into(),
|
||||
@@ -1301,9 +1336,9 @@ pub fn prove_local(
|
||||
}
|
||||
ctx.phase("compare");
|
||||
ctx.check("comparing")?;
|
||||
if std::fs::read(book_dir.join(crate::JOURNAL_FILE)).unwrap_or_default()
|
||||
!= std::fs::read(v.tree.join(crate::JOURNAL_FILE))?
|
||||
{
|
||||
let held = std::fs::read(v.tree.join(crate::JOURNAL_FILE))?;
|
||||
let held = &held[..(v.journal_bytes as usize).min(held.len())];
|
||||
if std::fs::read(book_dir.join(crate::JOURNAL_FILE)).unwrap_or_default() != held {
|
||||
return Err(BackupError::Damaged(
|
||||
"its journal isn't the books' own, byte for byte".into(),
|
||||
));
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
|
||||
use super::cut::Cut;
|
||||
use super::io::{Fill, Put, PutKind, SetIo};
|
||||
use super::read::Set;
|
||||
use super::write::{Written, write_into_set};
|
||||
use super::read::{Found, Set, verify_found};
|
||||
use super::write::{Written, proof_scratch, write_into_set};
|
||||
use super::{BackupError, Ctx};
|
||||
use std::collections::BTreeSet;
|
||||
use std::io::Read;
|
||||
@@ -173,6 +173,19 @@ pub fn save_file(
|
||||
.finish()
|
||||
.map_err(|e| BackupError::Io(std::io::Error::other(e).kind()))?;
|
||||
file.sync_all()?;
|
||||
// Read back as a restore would read it, and proven whole (every
|
||||
// piece re-hashed, the chain replayed, the books opened), before it
|
||||
// is given its name: a file by that name is a backup that proved.
|
||||
let reader = Set {
|
||||
io: open(&aside, ctx)?,
|
||||
keys: key.map(|k| k.keys()),
|
||||
ctx: ctx.clone(),
|
||||
};
|
||||
let found = Found::of(reader, key.cloned(), cut.book());
|
||||
let scratch = proof_scratch(cut)?;
|
||||
let proven = verify_found(&found, &scratch, ctx);
|
||||
let _ = std::fs::remove_dir_all(&scratch);
|
||||
proven?;
|
||||
Ok(written)
|
||||
});
|
||||
match result {
|
||||
|
||||
@@ -804,14 +804,38 @@ fn put_manifest(
|
||||
|
||||
/// A folder for the proof's scratch books: private, in the book's own
|
||||
/// `ops/`, named for this call.
|
||||
fn proof_scratch(cut: &Cut) -> Result<PathBuf, BackupError> {
|
||||
let ops = crate::root::private_book_folder(cut.dir(), crate::ops::OPS_DIR)
|
||||
.map_err(|e| BackupError::Damaged(e.to_string()))?;
|
||||
pub(crate) fn proof_scratch(cut: &Cut) -> Result<PathBuf, BackupError> {
|
||||
let ops = cut.dir().join(crate::ops::OPS_DIR);
|
||||
if !ops.is_dir() {
|
||||
// Made private by the one that makes it; one that lost a race to
|
||||
// make it finds it there.
|
||||
let made = crate::root::private_book_folder(cut.dir(), crate::ops::OPS_DIR);
|
||||
if !ops.is_dir() {
|
||||
return Err(BackupError::Damaged(
|
||||
made.err().map(|e| e.to_string()).unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut r = [0u8; 6];
|
||||
let _ = getrandom::getrandom(&mut r);
|
||||
getrandom::getrandom(&mut r).map_err(|e| BackupError::Io(std::io::Error::from(e).kind()))?;
|
||||
Ok(ops.join(format!("proof-{}", hex::encode(r))))
|
||||
}
|
||||
|
||||
/// Mark manifest `number` as proven whole: a tiny file put once. A mark
|
||||
/// that can't be made (a full disk) costs only a proof again at the next
|
||||
/// backup; a stop is a stop.
|
||||
fn mark_proven(set: &Set, number: u64) -> Result<(), BackupError> {
|
||||
match set.io.put(&proof_path(number), PutKind::Once, &mut |w| {
|
||||
w.write_all(b"proven whole\n")
|
||||
}) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => match uncarry(e) {
|
||||
stop @ (BackupError::Died | BackupError::Cancelled(_)) => Err(stop),
|
||||
_ => Ok(()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The most times a backup is written again to repair what its own proof
|
||||
/// found damaged.
|
||||
const REPAIR_ROUNDS: usize = 2;
|
||||
@@ -835,6 +859,7 @@ fn prove_and_repair(
|
||||
ctx.check("proving the backup")?;
|
||||
let proof = super::read::prove_written(set, number, &added, &proof_scratch(cut)?)?;
|
||||
if proof.damaged.is_empty() {
|
||||
mark_proven(set, number)?;
|
||||
return Ok(Written {
|
||||
number,
|
||||
head: cut.head().clone(),
|
||||
@@ -893,6 +918,7 @@ pub(crate) fn write_into_set(
|
||||
prove: bool,
|
||||
) -> Result<Written, BackupError> {
|
||||
ensure_markers(set)?;
|
||||
let prove = prove && !ctx.skips_proof();
|
||||
for _ in 0..ATTEMPTS {
|
||||
ctx.check("backing up")?;
|
||||
let numbers = set.numbers()?;
|
||||
@@ -903,6 +929,15 @@ pub(crate) fn write_into_set(
|
||||
if let Some(p) = &prev
|
||||
&& manifest.same_content(p)
|
||||
{
|
||||
// Nothing new. But a manifest whose proof was cut short (a
|
||||
// close, a stop, a death) is not yet known whole: proven now.
|
||||
if prove && !set.proven(p.number) {
|
||||
let w = prove_and_repair(set, cut, p.number, BTreeSet::new(), Vec::new(), ctx)?;
|
||||
return Ok(Written {
|
||||
new: w.number != p.number,
|
||||
..w
|
||||
});
|
||||
}
|
||||
return Ok(Written {
|
||||
number: p.number,
|
||||
head: cut.head().clone(),
|
||||
|
||||
@@ -1148,8 +1148,13 @@ pub struct RestorePreview {
|
||||
pub origin: Option<String>,
|
||||
/// Whether it is protected by a passphrase.
|
||||
pub sealed: bool,
|
||||
/// Newer backups in it that were not whole and were passed over.
|
||||
/// Newer backups in it that were not whole or were damaged and were
|
||||
/// passed over: not zero means this is not the newest backup there is.
|
||||
pub passed_over: u64,
|
||||
/// When this backup was made (UTC).
|
||||
pub written: Option<String>,
|
||||
/// When the newest backup there is was made (UTC), if it can be read.
|
||||
pub newest_written: Option<String>,
|
||||
}
|
||||
|
||||
/// What [`Root::restore`] did.
|
||||
@@ -1258,6 +1263,8 @@ impl Root {
|
||||
origin: v.book,
|
||||
sealed: v.key.is_some(),
|
||||
passed_over: v.passed_over as u64,
|
||||
written: Some(v.written.clone()),
|
||||
newest_written: v.newest_written.clone(),
|
||||
})
|
||||
})()
|
||||
.map_err(|e| self.hide(e))
|
||||
|
||||
@@ -452,6 +452,7 @@ fn pieces(set: &Path) -> Vec<PathBuf> {
|
||||
.keys()
|
||||
.filter(|n| {
|
||||
!n.starts_with("manifests/")
|
||||
&& !n.starts_with("proofs/")
|
||||
&& !n.ends_with("READ-ME.txt")
|
||||
&& !n.ends_with("header.json")
|
||||
})
|
||||
@@ -562,7 +563,13 @@ fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
|
||||
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()).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);
|
||||
@@ -573,10 +580,12 @@ fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
|
||||
let disk = dir.path().join("probe");
|
||||
copy_tree(&base_disk, &disk);
|
||||
let n = counted.clone();
|
||||
let ctx = Ctx::new().with_faults(Arc::new(move |_, _| {
|
||||
n.fetch_add(1, Ordering::SeqCst);
|
||||
false
|
||||
}));
|
||||
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)
|
||||
};
|
||||
@@ -588,9 +597,11 @@ fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
|
||||
let n = Arc::new(AtomicUsize::new(0));
|
||||
let ctx = {
|
||||
let n = n.clone();
|
||||
Ctx::new().with_faults(Arc::new(move |_, _| {
|
||||
n.fetch_add(1, Ordering::SeqCst) == die_at
|
||||
}))
|
||||
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}");
|
||||
@@ -609,7 +620,8 @@ fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
|
||||
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()).unwrap();
|
||||
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();
|
||||
|
||||
@@ -223,8 +223,17 @@ fn a_taken_number_or_name_is_never_replaced_on_a_disk_that_makes_no_links() {
|
||||
|
||||
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);
|
||||
@@ -295,6 +304,7 @@ fn set_header(header: &Path, edit: impl Fn(&mut serde_json::Value)) {
|
||||
|
||||
#[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);
|
||||
@@ -330,6 +340,7 @@ fn a_header_cannot_ask_for_more_than_a_few_times_what_this_program_spends() {
|
||||
|
||||
#[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);
|
||||
@@ -365,6 +376,7 @@ fn a_header_that_was_changed_reads_as_damage_and_not_as_a_wrong_passphrase() {
|
||||
|
||||
#[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);
|
||||
|
||||
@@ -36,6 +36,13 @@ fn ops() -> impl Strategy<Value = Vec<Op>> {
|
||||
)
|
||||
}
|
||||
|
||||
/// 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(),
|
||||
@@ -156,7 +163,7 @@ proptest! {
|
||||
for op in &ops {
|
||||
books.apply(op);
|
||||
if matches!(op, Op::Backup) {
|
||||
write_destination(&plain(&disk), &books.cut(), true, &Ctx::new()).unwrap();
|
||||
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);
|
||||
@@ -180,14 +187,14 @@ proptest! {
|
||||
for op in &ops {
|
||||
books.apply(op);
|
||||
if matches!(op, Op::Backup) {
|
||||
let w = write_destination(&plain(&disk), &books.cut(), true, &Ctx::new()).unwrap();
|
||||
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, &Ctx::new()).unwrap();
|
||||
let w = write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
|
||||
if w.new {
|
||||
heads.push((w.number, w.head));
|
||||
}
|
||||
@@ -240,9 +247,15 @@ proptest! {
|
||||
let count = Arc::new(AtomicUsize::new(0));
|
||||
let rival = {
|
||||
let (disk, second, count) = (disk.clone(), second.clone(), count.clone());
|
||||
Ctx::new().with_faults(Arc::new(move |_, _| {
|
||||
fast().with_faults(Arc::new(move |_, _| {
|
||||
if count.fetch_add(1, Ordering::SeqCst) == at {
|
||||
write_destination(&plain(&disk), &second, true, &Ctx::new()).unwrap();
|
||||
write_destination(
|
||||
&plain(&disk),
|
||||
&second,
|
||||
true,
|
||||
&fast(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
false
|
||||
}))
|
||||
@@ -275,11 +288,19 @@ proptest! {
|
||||
for op in &ops {
|
||||
books.apply(op);
|
||||
}
|
||||
write_destination(&plain(&disk), &books.cut(), true, &Ctx::new()).unwrap();
|
||||
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 != "READ-ME.txt")
|
||||
.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);
|
||||
@@ -309,7 +330,7 @@ proptest! {
|
||||
folder: disk.clone(),
|
||||
key: Some(BackupKey::generate("the right words, exactly").unwrap()),
|
||||
};
|
||||
write_destination(&dest, &books.cut(), true, &Ctx::new()).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:?}");
|
||||
|
||||
@@ -739,3 +739,52 @@ fn a_backup_cut_while_the_vault_is_being_written_restores_a_vault_that_matches_t
|
||||
.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);
|
||||
}
|
||||
Reference in new issue
Block a user