refactor: the server, restore and the window's seams on the plain-folder backup; git removed from the store
Restore reads a destination folder, a set's folder, or a backup file with an optional passphrase; the server cuts the books under the store's lock and writes the folder outside it; the format upgrade proves a local backup in the book's folder (the same form) before it moves the format. The old backup (git processes, their locks, the output drain) and every test of it are gone; what each test protected is held by the new form's tests (table in the report). Old settings and an old history in a book's folder are said in the status and left alone. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
9f4529b078
commit
a6cd89d2a6
35 files changed
+1150
-6636
No files matched your search
@@ -307,10 +307,17 @@ impl ledger_gui::owner::Owner for ViewerOwner {
|
|||||||
source: &str,
|
source: &str,
|
||||||
id: Option<String>,
|
id: Option<String>,
|
||||||
replace: bool,
|
replace: bool,
|
||||||
|
passphrase: Option<ledger_gui::owner::Secret>,
|
||||||
) -> Result<ledger_gui::owner::RestorePlan, String> {
|
) -> Result<ledger_gui::owner::RestorePlan, String> {
|
||||||
let p = ledger_host::commands::plan_restore(&self.common, source, id, replace, false)?;
|
let pass = passphrase.map(|p| ledger_mcp::admin::Passphrase(p.0.clone()));
|
||||||
|
let p =
|
||||||
|
ledger_host::commands::plan_restore(&self.common, source, id, replace, false, pass)?;
|
||||||
Ok(ledger_gui::owner::RestorePlan {
|
Ok(ledger_gui::owner::RestorePlan {
|
||||||
source: p.source,
|
source: p.source,
|
||||||
|
passphrase: p
|
||||||
|
.passphrase
|
||||||
|
.as_ref()
|
||||||
|
.map(|p| ledger_gui::owner::Secret(p.0.clone())),
|
||||||
id: p.id,
|
id: p.id,
|
||||||
replace: p.replace,
|
replace: p.replace,
|
||||||
head: p.head,
|
head: p.head,
|
||||||
@@ -323,6 +330,10 @@ impl ledger_gui::owner::Owner for ViewerOwner {
|
|||||||
&self.common,
|
&self.common,
|
||||||
&ledger_host::commands::RestorePlan {
|
&ledger_host::commands::RestorePlan {
|
||||||
source: plan.source.clone(),
|
source: plan.source.clone(),
|
||||||
|
passphrase: plan
|
||||||
|
.passphrase
|
||||||
|
.as_ref()
|
||||||
|
.map(|p| ledger_mcp::admin::Passphrase(p.0.clone())),
|
||||||
id: plan.id.clone(),
|
id: plan.id.clone(),
|
||||||
replace: plan.replace,
|
replace: plan.replace,
|
||||||
head: plan.head.clone(),
|
head: plan.head.clone(),
|
||||||
|
|||||||
+300
-529
File diff suppressed because it is too large.
Load diff
@@ -377,41 +377,6 @@ fn agent(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the server's git commands did, from the file it was told to write
|
|
||||||
/// them to (`WANDERBOOKS_GIT_TIMINGS`): the slowest ten by how long the
|
|
||||||
/// command ran plus how long its pipes took to close, then every line of the
|
|
||||||
/// last hundred. Each line: when (ms since the server's first git), the
|
|
||||||
/// command, its exit, how many git commands were running as it began,
|
|
||||||
/// `spawn` (how long starting it took, including waiting its turn),
|
|
||||||
/// `ran` (start to exit), `pipes` (exit until what it wrote was in hand),
|
|
||||||
/// and for each of stdout and stderr how that wait ended (`eof`: the pipe
|
|
||||||
/// closed; `held-open`: another process still held it, nothing was left in
|
|
||||||
/// it; `limit`: 10 s passed) and how many bytes.
|
|
||||||
fn say_git_timings(file: &std::path::Path) {
|
|
||||||
let text = std::fs::read_to_string(file).unwrap_or_default();
|
|
||||||
let lines: Vec<&str> = text.lines().collect();
|
|
||||||
let ms = |line: &str, key: &str| -> u64 {
|
|
||||||
line.split_whitespace()
|
|
||||||
.find_map(|w| w.strip_prefix(key))
|
|
||||||
.and_then(|v| v.trim_end_matches("ms").parse().ok())
|
|
||||||
.unwrap_or(0)
|
|
||||||
};
|
|
||||||
let mut slow: Vec<&&str> = lines.iter().collect();
|
|
||||||
slow.sort_by_key(|l| std::cmp::Reverse(ms(l, "ran=") + ms(l, "pipes=") + ms(l, "spawn=")));
|
|
||||||
eprintln!(
|
|
||||||
"git commands of the server: {} lines in {}; the slowest:",
|
|
||||||
lines.len(),
|
|
||||||
file.display()
|
|
||||||
);
|
|
||||||
for l in slow.iter().take(10) {
|
|
||||||
eprintln!(" {l}");
|
|
||||||
}
|
|
||||||
eprintln!("the last {}:", lines.len().min(100));
|
|
||||||
for l in &lines[lines.len().saturating_sub(100)..] {
|
|
||||||
eprintln!(" {l}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Many agents call two books (journaled drafts and reads) while one book
|
/// Many agents call two books (journaled drafts and reads) while one book
|
||||||
/// is closed and opened again, over and over. Afterwards both journals are
|
/// is closed and opened again, over and over. Afterwards both journals are
|
||||||
/// replayed and checked: every acknowledged draft is in its book's journal
|
/// replayed and checked: every acknowledged draft is in its book's journal
|
||||||
@@ -428,14 +393,9 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() {
|
|||||||
// Every timer of the server runs every few milliseconds, and the
|
// Every timer of the server runs every few milliseconds, and the
|
||||||
// hammered book has a backup target, which backs it up and drills it
|
// hammered book has a backup target, which backs it up and drills it
|
||||||
// as it is written: the writers a close must stop are all at work.
|
// as it is written: the writers a close must stop are all at work.
|
||||||
// Every git command the server runs is written here as it ends (how
|
|
||||||
// long it ran, how long its pipes took to close after it ended): the
|
|
||||||
// portable jobs run this on machines nobody can look at, and a close
|
|
||||||
// that is slow there is told with these lines, not guessed at.
|
|
||||||
let timings = home.dir.path().join("git-timings.log");
|
|
||||||
let server = Server::start_full(
|
let server = Server::start_full(
|
||||||
&home,
|
&home,
|
||||||
&[("WANDERBOOKS_GIT_TIMINGS", timings.as_path())],
|
&[],
|
||||||
&[
|
&[
|
||||||
"--timers",
|
"--timers",
|
||||||
"10",
|
"10",
|
||||||
@@ -532,9 +492,6 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() {
|
|||||||
let closed = close_book(&home, A);
|
let closed = close_book(&home, A);
|
||||||
let took = began.elapsed();
|
let took = began.elapsed();
|
||||||
eprintln!("cycle {cycle}: the close took {took:?}");
|
eprintln!("cycle {cycle}: the close took {took:?}");
|
||||||
if closed != CloseOutcome::Closed || took > Duration::from_secs(10) {
|
|
||||||
say_git_timings(&timings);
|
|
||||||
}
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
closed,
|
closed,
|
||||||
CloseOutcome::Closed,
|
CloseOutcome::Closed,
|
||||||
@@ -1181,73 +1138,43 @@ fn a_call_whose_answer_was_never_read_is_on_record_as_having_run() {
|
|||||||
assert!(server.close().success());
|
assert!(server.close().success());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A stand-in `git` for the server's PATH: it runs the real one, unless
|
/// The test knob that holds a backup at each phase, as a slow disk would:
|
||||||
/// the test has said otherwise with a file beside it: `stall` (it waits,
|
/// while this file is in the book's `ops/` (and the server was given
|
||||||
/// recording itself in `stalled`, until the file is gone, then in
|
/// `--slow-steps`), a backup waits until the stop it runs under is asked
|
||||||
/// `resumed`), which is how a backup is made slow.
|
/// for. Each wait is a line of [`reached`].
|
||||||
#[cfg(unix)]
|
fn stall_file(home: &Home, id: &str) -> PathBuf {
|
||||||
fn shim_git(home: &Home) -> PathBuf {
|
home.book_dir(id).join("ops").join("slow-backup")
|
||||||
use std::os::unix::fs::PermissionsExt;
|
|
||||||
let dir = home.dir.path().join("shim");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
let real = ["/usr/bin/git", "/bin/git", "/usr/local/bin/git"]
|
|
||||||
.into_iter()
|
|
||||||
.find(|p| std::path::Path::new(p).is_file())
|
|
||||||
.expect("git is installed");
|
|
||||||
let exe = dir.join("git");
|
|
||||||
std::fs::write(
|
|
||||||
&exe,
|
|
||||||
format!(
|
|
||||||
"#!/bin/sh\ndir=\"$(dirname \"$0\")\"\necho \"$$ $*\" >> \"$dir/calls\"\nif [ -e \"$dir/stall\" ]; then\n echo $$ >> \"$dir/stalled\"\n while [ -e \"$dir/stall\" ]; do sleep 0.05; done\n echo $$ >> \"$dir/resumed\"\nfi\nexec {real} \"$@\"\n"
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether process `pid` is still there.
|
/// How many times a backup of `id` has reached a phase and waited.
|
||||||
#[cfg(unix)]
|
fn reached(home: &Home, id: &str) -> usize {
|
||||||
fn alive(pid: u32) -> bool {
|
std::fs::read_to_string(home.book_dir(id).join("ops").join("slow-backup-reached"))
|
||||||
// `ps` on Linux and macOS alike (there is no /proc on macOS, where a
|
.unwrap_or_default()
|
||||||
// test of "is it gone" would pass whatever the server had done): its
|
.lines()
|
||||||
// state is empty for a process that isn't there, and starts with Z for
|
.count()
|
||||||
// one that has ended and is not yet reaped.
|
|
||||||
let out = std::process::Command::new("ps")
|
|
||||||
.args(["-o", "stat=", "-p", &pid.to_string()])
|
|
||||||
.output()
|
|
||||||
.expect("ps runs");
|
|
||||||
let state = String::from_utf8_lossy(&out.stdout);
|
|
||||||
let state = state.trim();
|
|
||||||
!state.is_empty() && !state.starts_with('Z')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The server, with the stand-in git first on its PATH.
|
/// The folder a backup of `id` to `disk` lives in, proven whole: its head.
|
||||||
#[cfg(unix)]
|
fn proven_head(home: &Home, disk: &std::path::Path, tag: &str) -> (u64, String) {
|
||||||
fn server_with_shim(home: &Home, shim: &std::path::Path, args: &[&str]) -> Server {
|
use ledger_store::backup::{Ctx, find, verify_found};
|
||||||
let path = std::env::join_paths([
|
let scratch = home.dir.path().join(format!("scratch-{tag}"));
|
||||||
shim,
|
let found = find(disk, None, &Ctx::new()).unwrap_or_else(|e| panic!("{tag}: {e}"));
|
||||||
std::path::Path::new("/usr/bin"),
|
verify_found(&found, &scratch, false, &Ctx::new())
|
||||||
std::path::Path::new("/bin"),
|
.unwrap_or_else(|e| panic!("{tag}: {e}"))
|
||||||
])
|
.head
|
||||||
.unwrap();
|
|
||||||
let path: PathBuf = path.into();
|
|
||||||
Server::start_full(home, &[("PATH", path.as_path())], args)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A book with a backup target whose backup is slow: the close is not
|
/// A book with a backup folder whose backup is slow: the close is not
|
||||||
/// answered while the backup's work runs. Its bound lapses, git is
|
/// answered while the backup's work runs. Its bound lapses, the copy is
|
||||||
/// stopped (with all it started), the close waits for that to be done,
|
/// stopped at its next piece, the close waits for that to be done, and
|
||||||
/// and says the backup wasn't whole. Nothing of the backup runs after the
|
/// says the backup wasn't whole. The folder still proves whole at the
|
||||||
/// answer, though the stall is lifted: a git left running would go on.
|
/// backup before, and nothing of the backup runs after the answer, though
|
||||||
#[cfg(unix)]
|
/// the stall is lifted: a copy left running would go on.
|
||||||
#[test]
|
#[test]
|
||||||
fn a_close_is_not_answered_while_its_backup_still_runs() {
|
fn a_close_is_not_answered_while_its_backup_still_runs() {
|
||||||
let home = Home::new("close-slow-backup");
|
let home = Home::new("close-slow-backup");
|
||||||
let shim = shim_git(&home);
|
let server = Server::start_with(
|
||||||
let server = server_with_shim(
|
|
||||||
&home,
|
&home,
|
||||||
&shim,
|
|
||||||
&[
|
&[
|
||||||
"--close-backup",
|
"--close-backup",
|
||||||
"1200",
|
"1200",
|
||||||
@@ -1255,6 +1182,8 @@ fn a_close_is_not_answered_while_its_backup_still_runs() {
|
|||||||
"3600000",
|
"3600000",
|
||||||
"--timers",
|
"--timers",
|
||||||
"20",
|
"20",
|
||||||
|
"--slow-steps",
|
||||||
|
"600000",
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
home.create(A, "USD");
|
home.create(A, "USD");
|
||||||
@@ -1263,10 +1192,19 @@ fn a_close_is_not_answered_while_its_backup_still_runs() {
|
|||||||
let mut w = Wire::new(&home, A);
|
let mut w = Wire::new(&home, A);
|
||||||
w.initialize("owner");
|
w.initialize("owner");
|
||||||
set_backup_folder(&mut w, &disk);
|
set_backup_folder(&mut w, &disk);
|
||||||
|
draft(&mut w, "kept");
|
||||||
|
match home.admin(Request::BackUpNow {
|
||||||
|
id: A.into(),
|
||||||
|
new_disk: false,
|
||||||
|
}) {
|
||||||
|
Response::BackedUp { targets, .. } => assert!(targets[0].problem.is_none(), "{targets:?}"),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
let kept = proven_head(&home, &disk, "before");
|
||||||
draft(&mut w, "moves the head past the last backup");
|
draft(&mut w, "moves the head past the last backup");
|
||||||
w.end();
|
w.end();
|
||||||
// From here every git waits.
|
// From here every backup waits.
|
||||||
std::fs::write(shim.join("stall"), b"").unwrap();
|
std::fs::write(stall_file(&home, A), b"").unwrap();
|
||||||
let started = std::time::Instant::now();
|
let started = std::time::Instant::now();
|
||||||
let outcome = close_book(&home, A);
|
let outcome = close_book(&home, A);
|
||||||
let took = started.elapsed();
|
let took = started.elapsed();
|
||||||
@@ -1282,36 +1220,24 @@ fn a_close_is_not_answered_while_its_backup_still_runs() {
|
|||||||
}
|
}
|
||||||
other => panic!("a stopped backup was answered as {other:?}"),
|
other => panic!("a stopped backup was answered as {other:?}"),
|
||||||
}
|
}
|
||||||
// Answered: the git that was stalled is gone, with what it started.
|
assert!(reached(&home, A) > 0, "the backup never reached a phase");
|
||||||
let stalled: Vec<u32> = std::fs::read_to_string(shim.join("stalled"))
|
// The folder proves whole at the backup before.
|
||||||
.unwrap_or_default()
|
assert_eq!(proven_head(&home, &disk, "after"), kept);
|
||||||
.lines()
|
|
||||||
.filter_map(|l| l.trim().parse().ok())
|
|
||||||
.collect();
|
|
||||||
assert!(!stalled.is_empty(), "the backup never reached git");
|
|
||||||
for pid in &stalled {
|
|
||||||
assert!(
|
|
||||||
!alive(*pid),
|
|
||||||
"git {pid} still runs after the close was answered"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let at_close = tree_of(&home.book_dir(A));
|
let at_close = tree_of(&home.book_dir(A));
|
||||||
|
let in_folder = tree_of(&disk);
|
||||||
// The stall is lifted: anything that had survived would go on now.
|
// The stall is lifted: anything that had survived would go on now.
|
||||||
std::fs::remove_file(shim.join("stall")).unwrap();
|
std::fs::remove_file(stall_file(&home, A)).unwrap();
|
||||||
stands_still(
|
stands_still(
|
||||||
&home,
|
&home,
|
||||||
A,
|
A,
|
||||||
Duration::from_millis(500),
|
Duration::from_millis(500),
|
||||||
"after the close was answered",
|
"after the close was answered",
|
||||||
);
|
);
|
||||||
assert!(
|
|
||||||
!shim.join("resumed").exists(),
|
|
||||||
"a git went on after the close was answered"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
moved(&at_close, &tree_of(&home.book_dir(A))),
|
moved(&at_close, &tree_of(&home.book_dir(A))),
|
||||||
Vec::<String>::new()
|
Vec::<String>::new()
|
||||||
);
|
);
|
||||||
|
assert_eq!(moved(&in_folder, &tree_of(&disk)), Vec::<String>::new());
|
||||||
// Opened again, the book's backup record is a whole chain, and it
|
// Opened again, the book's backup record is a whole chain, and it
|
||||||
// backs up (nothing of the old backups is in its way).
|
// backs up (nothing of the old backups is in its way).
|
||||||
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
|
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
|
||||||
@@ -1331,23 +1257,12 @@ fn a_close_is_not_answered_while_its_backup_still_runs() {
|
|||||||
/// A backup that fails (its disk isn't there) closes the book all the same,
|
/// A backup that fails (its disk isn't there) closes the book all the same,
|
||||||
/// quickly, and says so: never a plain "closed" for a backup that wasn't
|
/// quickly, and says so: never a plain "closed" for a backup that wasn't
|
||||||
/// made; and nothing runs after.
|
/// made; and nothing runs after.
|
||||||
#[cfg(unix)]
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() {
|
fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() {
|
||||||
let home = Home::new("close-failing-backup");
|
let home = Home::new("close-failing-backup");
|
||||||
let shim = shim_git(&home);
|
|
||||||
// The timers look once an hour, so none runs a backup of its own: the
|
// The timers look once an hour, so none runs a backup of its own: the
|
||||||
// first look is at the server's start, before any book is made here. A
|
// first look is at the server's start, before any book is made here.
|
||||||
// timer's backup that a close hurried could have its git miss the
|
let server = Server::start_with(&home, &["--backup-quiet", "3600000", "--timers", "3600000"]);
|
||||||
// terminate grace under heavy load, be killed, and leave a lock in the
|
|
||||||
// target's folder, which the close's own backup would then truthfully
|
|
||||||
// fail against (`ClosedBackupIncomplete`): the plain `Closed` asserted
|
|
||||||
// below is of the close's backup alone.
|
|
||||||
let server = server_with_shim(
|
|
||||||
&home,
|
|
||||||
&shim,
|
|
||||||
&["--backup-quiet", "3600000", "--timers", "3600000"],
|
|
||||||
);
|
|
||||||
home.create(A, "USD");
|
home.create(A, "USD");
|
||||||
let unplugged = home.dir.path().join("elsewhere").join("unplugged");
|
let unplugged = home.dir.path().join("elsewhere").join("unplugged");
|
||||||
std::fs::create_dir_all(unplugged.parent().unwrap()).unwrap();
|
std::fs::create_dir_all(unplugged.parent().unwrap()).unwrap();
|
||||||
@@ -1369,10 +1284,6 @@ fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() {
|
|||||||
}
|
}
|
||||||
assert_eq!(listed(&home, A), (false, true, None));
|
assert_eq!(listed(&home, A), (false, true, None));
|
||||||
let at_close = tree_of(&home.book_dir(A));
|
let at_close = tree_of(&home.book_dir(A));
|
||||||
let calls = std::fs::read_to_string(shim.join("calls"))
|
|
||||||
.unwrap_or_default()
|
|
||||||
.lines()
|
|
||||||
.count();
|
|
||||||
stands_still(
|
stands_still(
|
||||||
&home,
|
&home,
|
||||||
A,
|
A,
|
||||||
@@ -1383,14 +1294,6 @@ fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() {
|
|||||||
moved(&at_close, &tree_of(&home.book_dir(A))),
|
moved(&at_close, &tree_of(&home.book_dir(A))),
|
||||||
Vec::<String>::new()
|
Vec::<String>::new()
|
||||||
);
|
);
|
||||||
assert_eq!(
|
|
||||||
std::fs::read_to_string(shim.join("calls"))
|
|
||||||
.unwrap_or_default()
|
|
||||||
.lines()
|
|
||||||
.count(),
|
|
||||||
calls,
|
|
||||||
"git was run after the close was answered"
|
|
||||||
);
|
|
||||||
// The same book, backed up fine, is answered plainly.
|
// The same book, backed up fine, is answered plainly.
|
||||||
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
|
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
|
||||||
std::fs::create_dir(&unplugged).unwrap();
|
std::fs::create_dir(&unplugged).unwrap();
|
||||||
@@ -1788,7 +1691,7 @@ fn a_running_call_is_never_cut_when_the_grace_runs_out() {
|
|||||||
assert!(server.close().success());
|
assert!(server.close().success());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A backup of `id`, taken now to its folder target; the repository.
|
/// A backup of `id`, taken now to its folder; the folder of its set.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn backed_up_to_folder(home: &Home, w: &mut Wire, id: &str) -> PathBuf {
|
fn backed_up_to_folder(home: &Home, w: &mut Wire, id: &str) -> PathBuf {
|
||||||
let disk = home.dir.path().join("disk");
|
let disk = home.dir.path().join("disk");
|
||||||
@@ -1802,7 +1705,7 @@ fn backed_up_to_folder(home: &Home, w: &mut Wire, id: &str) -> PathBuf {
|
|||||||
Response::BackedUp { targets, .. } => assert!(targets[0].problem.is_none(), "{targets:?}"),
|
Response::BackedUp { targets, .. } => assert!(targets[0].problem.is_none(), "{targets:?}"),
|
||||||
other => panic!("{other:?}"),
|
other => panic!("{other:?}"),
|
||||||
}
|
}
|
||||||
disk.join(format!("{id}.git"))
|
disk.join(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A restore over an open book lets go of it as a close does: what is
|
/// A restore over an open book lets go of it as a close does: what is
|
||||||
@@ -1840,6 +1743,7 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() {
|
|||||||
replace: true,
|
replace: true,
|
||||||
confirmed: false,
|
confirmed: false,
|
||||||
expect_head: None,
|
expect_head: None,
|
||||||
|
passphrase: None,
|
||||||
}) {
|
}) {
|
||||||
Response::RestorePreview(p) => p,
|
Response::RestorePreview(p) => p,
|
||||||
other => panic!("{other:?}"),
|
other => panic!("{other:?}"),
|
||||||
@@ -1855,6 +1759,7 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() {
|
|||||||
replace: true,
|
replace: true,
|
||||||
confirmed: true,
|
confirmed: true,
|
||||||
expect_head: Some(preview.head),
|
expect_head: Some(preview.head),
|
||||||
|
passphrase: None,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -1961,6 +1866,7 @@ fn a_restore_over_an_open_book_is_not_held_by_a_stalled_upload() {
|
|||||||
replace: true,
|
replace: true,
|
||||||
confirmed: false,
|
confirmed: false,
|
||||||
expect_head: None,
|
expect_head: None,
|
||||||
|
passphrase: None,
|
||||||
}) {
|
}) {
|
||||||
Response::RestorePreview(p) => p,
|
Response::RestorePreview(p) => p,
|
||||||
other => panic!("{other:?}"),
|
other => panic!("{other:?}"),
|
||||||
@@ -1972,6 +1878,7 @@ fn a_restore_over_an_open_book_is_not_held_by_a_stalled_upload() {
|
|||||||
replace: true,
|
replace: true,
|
||||||
confirmed: true,
|
confirmed: true,
|
||||||
expect_head: Some(preview.head),
|
expect_head: Some(preview.head),
|
||||||
|
passphrase: None,
|
||||||
}) {
|
}) {
|
||||||
Response::Restored(r) => r,
|
Response::Restored(r) => r,
|
||||||
other => panic!("{other:?}"),
|
other => panic!("{other:?}"),
|
||||||
@@ -2458,7 +2365,7 @@ fn a_close_stops_a_slow_drill_instead_of_waiting_for_it() {
|
|||||||
"the last backup waited behind the drill"
|
"the last backup waited behind the drill"
|
||||||
);
|
);
|
||||||
// The stated bound, as a sum of its parts: the grace, the answers'
|
// The stated bound, as a sum of its parts: the grace, the answers'
|
||||||
// grace, the last backup's bound, and the stop of a step (git's kill
|
// grace, the last backup's bound, and the stop of a step (the copy's stop
|
||||||
// and its group's end, 2 s; its pipes, 10 s; the lock settling, 1.5 s).
|
// and its group's end, 2 s; its pipes, 10 s; the lock settling, 1.5 s).
|
||||||
let bound = Duration::from_millis(2 * grace + last_backup) + Duration::from_millis(13_500);
|
let bound = Duration::from_millis(2 * grace + last_backup) + Duration::from_millis(13_500);
|
||||||
assert!(took < bound, "{took:?} past the stated bound {bound:?}");
|
assert!(took < bound, "{took:?} past the stated bound {bound:?}");
|
||||||
@@ -2486,229 +2393,6 @@ fn a_close_stops_a_slow_drill_instead_of_waiting_for_it() {
|
|||||||
.expect("the backup record is a whole chain");
|
.expect("the backup record is a whole chain");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A stand-in `git` that is the real one with a hooks folder of its own
|
|
||||||
/// (every `core.hooksPath=/dev/null` it is given, in its arguments and in
|
|
||||||
/// the `--receive-pack` command of a push to a folder, names it instead),
|
|
||||||
/// where a `reference-transaction` hook waits, while `slow-commit` (for the
|
|
||||||
/// book's archive) or `slow-push` (for any other repository) exists in the
|
|
||||||
/// shim folder, at the point where git holds its ref locks. `hooked` has a
|
|
||||||
/// line per hook that waited. A real git, killed inside real work. While
|
|
||||||
/// `deaf` exists in the shim folder when a git begins, that git (and all it
|
|
||||||
/// starts) has SIGTERM blocked, a mask every child inherits: the signal stays
|
|
||||||
/// pending and only the kill ends it (a stopped process is not enough:
|
|
||||||
/// macOS acts on a SIGTERM sent to one, where Linux holds it).
|
|
||||||
#[cfg(unix)]
|
|
||||||
fn slow_real_git(home: &Home) -> PathBuf {
|
|
||||||
use std::os::unix::fs::PermissionsExt;
|
|
||||||
let dir = home.dir.path().join("slow-shim");
|
|
||||||
let hooks = dir.join("hooks");
|
|
||||||
std::fs::create_dir_all(&hooks).unwrap();
|
|
||||||
let real = ["/usr/bin/git", "/bin/git", "/usr/local/bin/git"]
|
|
||||||
.into_iter()
|
|
||||||
.find(|p| std::path::Path::new(p).is_file())
|
|
||||||
.expect("git is installed");
|
|
||||||
let hook = hooks.join("reference-transaction");
|
|
||||||
std::fs::write(
|
|
||||||
&hook,
|
|
||||||
"#!/bin/sh\ncat >/dev/null\n[ \"$1\" = prepared ] || exit 0\nd=\"$(dirname \"$0\")/..\"\ncase \"$GIT_DIR $PWD\" in *archive.git*) f=slow-commit ;; *) f=slow-push ;; esac\nif [ -e \"$d/$f\" ]; then\n echo $$ >> \"$d/hooked\"\n while [ -e \"$d/$f\" ]; do sleep 0.05; done\nfi\nexit 0\n",
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
|
|
||||||
let exe = dir.join("git");
|
|
||||||
std::fs::write(
|
|
||||||
&exe,
|
|
||||||
format!(
|
|
||||||
"#!/bin/sh\nn=$#\nwhile [ $n -gt 0 ]; do\n a=\"$1\"; shift\n case \"$a\" in\n *core.hooksPath=/dev/null*) a=$(printf '%s' \"$a\" | sed 's|core.hooksPath=/dev/null|core.hooksPath={}|g') ;;\n esac\n set -- \"$@\" \"$a\"\n n=$((n-1))\ndone\nif [ -e '{dir}/deaf' ]; then exec perl -MPOSIX -e 'sigprocmask(SIG_BLOCK, POSIX::SigSet->new(SIGTERM)) or die; exec @ARGV or die' {real} \"$@\"; fi\nexec {real} \"$@\"\n",
|
|
||||||
hooks.display(),
|
|
||||||
dir = dir.display(),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every `*.lock` file under a bare repository.
|
|
||||||
#[cfg(unix)]
|
|
||||||
fn locks_under(repo: &std::path::Path) -> Vec<String> {
|
|
||||||
tree_of(repo)
|
|
||||||
.into_keys()
|
|
||||||
.filter(|k| k.ends_with(".lock"))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
fn fsck_of(repo: &std::path::Path) {
|
|
||||||
let out = std::process::Command::new("git")
|
|
||||||
.arg(format!("--git-dir={}", repo.display()))
|
|
||||||
.args(["fsck", "--strict"])
|
|
||||||
.output()
|
|
||||||
.unwrap();
|
|
||||||
assert!(
|
|
||||||
out.status.success(),
|
|
||||||
"{} isn't whole: {}",
|
|
||||||
repo.display(),
|
|
||||||
String::from_utf8_lossy(&out.stderr)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A close that stops real git inside a commit, and inside a push to a
|
|
||||||
/// folder, leaves no lock for anyone to remove: git is sent SIGTERM and
|
|
||||||
/// removes its own locks, so there is nothing for the server to clean up
|
|
||||||
/// (the backup's record holds no `lock_removed` or `lock_left`), the book
|
|
||||||
/// opened again at once backs up with no step by hand, and both
|
|
||||||
/// repositories pass `git fsck` (ledger_store::backup INVARIANT 5).
|
|
||||||
#[cfg(unix)]
|
|
||||||
#[test]
|
|
||||||
fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds() {
|
|
||||||
let home = Home::new("close-git-locks");
|
|
||||||
let shim = slow_real_git(&home);
|
|
||||||
// The close's bound lapses with git held inside its ref update, and
|
|
||||||
// what the test proves needs git to have got there first: the bound is
|
|
||||||
// long enough for the slowest machine to run every git before the
|
|
||||||
// update (a push, on a macOS runner, comes after a dozen of them and
|
|
||||||
// took longer than 1.5 s), as in the test of a lock a kill leaves. The
|
|
||||||
// hook holds git until the bound ends it, so each close takes the bound.
|
|
||||||
let server = server_with_shim(
|
|
||||||
&home,
|
|
||||||
&shim,
|
|
||||||
&[
|
|
||||||
"--close-backup",
|
|
||||||
"8000",
|
|
||||||
"--backup-quiet",
|
|
||||||
"3600000",
|
|
||||||
"--timers",
|
|
||||||
"20",
|
|
||||||
],
|
|
||||||
);
|
|
||||||
home.create(A, "USD");
|
|
||||||
let disk = home.dir.path().join("disk");
|
|
||||||
std::fs::create_dir_all(&disk).unwrap();
|
|
||||||
let mut w = Wire::new(&home, A);
|
|
||||||
w.initialize("owner");
|
|
||||||
set_backup_folder(&mut w, &disk);
|
|
||||||
draft(&mut w, "to be backed up inside a commit");
|
|
||||||
w.end();
|
|
||||||
let archive = home.book_dir(A).join("archive.git");
|
|
||||||
let target = disk.join(format!("{A}.git"));
|
|
||||||
let record = || {
|
|
||||||
std::fs::read_to_string(home.book_dir(A).join("ops").join("backup.jsonl"))
|
|
||||||
.unwrap_or_default()
|
|
||||||
};
|
|
||||||
// 0. Inside the making of the archive itself (`git init`): a lock in
|
|
||||||
// a repository that isn't one yet stops every later `init`.
|
|
||||||
std::fs::write(shim.join("slow-commit"), b"").unwrap();
|
|
||||||
let outcome = close_book(&home, A);
|
|
||||||
assert!(
|
|
||||||
matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)),
|
|
||||||
"{outcome:?}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
shim.join("hooked").exists(),
|
|
||||||
"git never reached its ref update before the close's bound ran out: {outcome:?}"
|
|
||||||
);
|
|
||||||
assert_eq!(locks_under(&archive), Vec::<String>::new());
|
|
||||||
assert!(
|
|
||||||
!record().contains("lock_removed") && !record().contains("lock_left"),
|
|
||||||
"git removed its own locks: nothing was cleaned up here: {}",
|
|
||||||
record()
|
|
||||||
);
|
|
||||||
std::fs::remove_file(shim.join("slow-commit")).unwrap();
|
|
||||||
std::fs::remove_file(shim.join("hooked")).unwrap();
|
|
||||||
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
|
|
||||||
let mut w = Wire::new(&home, A);
|
|
||||||
w.initialize("owner");
|
|
||||||
draft(&mut w, "to be backed up inside a commit");
|
|
||||||
w.end();
|
|
||||||
match home.admin(Request::BackUpNow {
|
|
||||||
id: A.into(),
|
|
||||||
new_disk: false,
|
|
||||||
}) {
|
|
||||||
Response::BackedUp { targets, .. } => {
|
|
||||||
assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}");
|
|
||||||
}
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
}
|
|
||||||
let mut w = Wire::new(&home, A);
|
|
||||||
w.initialize("owner");
|
|
||||||
draft(&mut w, "to be committed inside a commit");
|
|
||||||
w.end();
|
|
||||||
// 1. Inside the commit's ref update.
|
|
||||||
std::fs::write(shim.join("slow-commit"), b"").unwrap();
|
|
||||||
let outcome = close_book(&home, A);
|
|
||||||
assert!(
|
|
||||||
matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)),
|
|
||||||
"{outcome:?}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
shim.join("hooked").exists(),
|
|
||||||
"git never reached its ref update before the close's bound ran out: {outcome:?}"
|
|
||||||
);
|
|
||||||
assert_eq!(locks_under(&archive), Vec::<String>::new());
|
|
||||||
assert!(
|
|
||||||
!record().contains("lock_removed") && !record().contains("lock_left"),
|
|
||||||
"git removed its own locks: nothing was cleaned up here: {}",
|
|
||||||
record()
|
|
||||||
);
|
|
||||||
std::fs::remove_file(shim.join("slow-commit")).unwrap();
|
|
||||||
std::fs::remove_file(shim.join("hooked")).unwrap();
|
|
||||||
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
|
|
||||||
let status = home.admin(Request::BackUpNow {
|
|
||||||
id: A.into(),
|
|
||||||
new_disk: false,
|
|
||||||
});
|
|
||||||
match &status {
|
|
||||||
Response::BackedUp { targets, .. } => {
|
|
||||||
assert!(targets.iter().all(|t| t.problem.is_none()), "{status:?}");
|
|
||||||
}
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
}
|
|
||||||
fsck_of(&archive);
|
|
||||||
fsck_of(&target);
|
|
||||||
// 2. Inside the push's ref update at the folder.
|
|
||||||
let mut w = Wire::new(&home, A);
|
|
||||||
w.initialize("owner");
|
|
||||||
draft(&mut w, "to be pushed inside a push");
|
|
||||||
w.end();
|
|
||||||
std::fs::write(shim.join("slow-push"), b"").unwrap();
|
|
||||||
let outcome = close_book(&home, A);
|
|
||||||
assert!(
|
|
||||||
matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)),
|
|
||||||
"{outcome:?}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
shim.join("hooked").exists(),
|
|
||||||
"git never reached its ref update before the close's bound ran out: {outcome:?}"
|
|
||||||
);
|
|
||||||
assert_eq!(locks_under(&target), Vec::<String>::new());
|
|
||||||
assert_eq!(locks_under(&archive), Vec::<String>::new());
|
|
||||||
assert!(
|
|
||||||
!record().contains("lock_removed") && !record().contains("lock_left"),
|
|
||||||
"git removed its own locks: nothing was cleaned up here: {}",
|
|
||||||
record()
|
|
||||||
);
|
|
||||||
std::fs::remove_file(shim.join("slow-push")).unwrap();
|
|
||||||
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
|
|
||||||
let status = home.admin(Request::BackUpNow {
|
|
||||||
id: A.into(),
|
|
||||||
new_disk: false,
|
|
||||||
});
|
|
||||||
match &status {
|
|
||||||
Response::BackedUp { targets, .. } => {
|
|
||||||
assert!(targets.iter().all(|t| t.problem.is_none()), "{status:?}");
|
|
||||||
}
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
}
|
|
||||||
fsck_of(&archive);
|
|
||||||
fsck_of(&target);
|
|
||||||
ledger_store::chain::read(
|
|
||||||
&home.book_dir(A).join("ops").join("backup.jsonl"),
|
|
||||||
"wanderbooks-backup-v1",
|
|
||||||
)
|
|
||||||
.expect("the backup record is a whole chain");
|
|
||||||
assert!(server.close().success());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A tool call sent on `w`'s session, its whole body written and its answer
|
/// A tool call sent on `w`'s session, its whole body written and its answer
|
||||||
/// not yet read: the connection it went out on.
|
/// not yet read: the connection it went out on.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
@@ -2734,24 +2418,6 @@ fn call_unanswered(home: &Home, w: &Wire, id: u64, tool: &str, args: Value) -> r
|
|||||||
raw
|
raw
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Hold every process of the group `pid` leads still (SIGSTOP), so that none
|
|
||||||
/// goes on while the stop is being asked for. That git can't end on SIGTERM,
|
|
||||||
/// holding its locks, is made on purpose by the shim's `deaf` file, not by
|
|
||||||
/// this: macOS acts on a SIGTERM sent to a stopped process.
|
|
||||||
#[cfg(unix)]
|
|
||||||
fn freeze_group_of(pid: u32) {
|
|
||||||
let out = std::process::Command::new("ps")
|
|
||||||
.args(["-o", "pgid=", "-p", &pid.to_string()])
|
|
||||||
.output()
|
|
||||||
.unwrap();
|
|
||||||
let group: i32 = String::from_utf8_lossy(&out.stdout)
|
|
||||||
.trim()
|
|
||||||
.parse()
|
|
||||||
.expect("ps names the group");
|
|
||||||
// SAFETY: stopping the group of a git this test's server started.
|
|
||||||
assert_eq!(unsafe { libc::kill(-group, libc::SIGSTOP) }, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The most a close may take in these tests where what it stops would
|
/// The most a close may take in these tests where what it stops would
|
||||||
/// otherwise run for ever (a stall that is never lifted): a guard against a
|
/// otherwise run for ever (a stall that is never lifted): a guard against a
|
||||||
/// hang, not a measure of speed. That the close ends at all, with the stall
|
/// hang, not a measure of speed. That the close ends at all, with the stall
|
||||||
@@ -2770,21 +2436,19 @@ fn backup_record_of(home: &Home, id: &str) -> Vec<serde_json::Map<String, Value>
|
|||||||
.records
|
.records
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A backup call that is running (git stalled) when a close begins is
|
/// A backup call that is running (its copy stalled) when a close begins is
|
||||||
/// STOPPED by it, not waited for: the call is answered, while git is still
|
/// STOPPED by it, not waited for: the call is answered, while the copy is
|
||||||
/// stalled, that it was stopped because the books are closing; its access
|
/// still stalled, that it was stopped because the books are closing; its
|
||||||
/// record says `refused: stopped_by_close`; the backup records `stopped`
|
/// access record says `refused: stopped_by_close`; the backup records
|
||||||
/// and no result of the run's own (nothing it was doing is recorded as
|
/// `stopped` and no result of the run's own (nothing it was doing is
|
||||||
/// done); git and all it started are gone; and the close's own last
|
/// recorded as done); the folder still proves whole at the backup before;
|
||||||
/// backup is made as always (local.rs INVARIANT 10).
|
/// and the close's own last backup is made as always (local.rs INVARIANT
|
||||||
#[cfg(unix)]
|
/// 10).
|
||||||
#[test]
|
#[test]
|
||||||
fn a_close_stops_a_running_backup_call_and_says_so() {
|
fn a_close_stops_a_running_backup_call_and_says_so() {
|
||||||
let home = Home::new("close-stops-backup-call");
|
let home = Home::new("close-stops-backup-call");
|
||||||
let shim = shim_git(&home);
|
let server = Server::start_with(
|
||||||
let server = server_with_shim(
|
|
||||||
&home,
|
&home,
|
||||||
&shim,
|
|
||||||
&[
|
&[
|
||||||
"--close-backup",
|
"--close-backup",
|
||||||
"20000",
|
"20000",
|
||||||
@@ -2792,6 +2456,8 @@ fn a_close_stops_a_running_backup_call_and_says_so() {
|
|||||||
"3600000",
|
"3600000",
|
||||||
"--timers",
|
"--timers",
|
||||||
"20",
|
"20",
|
||||||
|
"--slow-steps",
|
||||||
|
"600000",
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
home.create(A, "USD");
|
home.create(A, "USD");
|
||||||
@@ -2800,18 +2466,27 @@ fn a_close_stops_a_running_backup_call_and_says_so() {
|
|||||||
let mut w = Wire::new(&home, A);
|
let mut w = Wire::new(&home, A);
|
||||||
w.initialize("owner");
|
w.initialize("owner");
|
||||||
set_backup_folder(&mut w, &disk);
|
set_backup_folder(&mut w, &disk);
|
||||||
|
draft(&mut w, "kept");
|
||||||
|
match home.admin(Request::BackUpNow {
|
||||||
|
id: A.into(),
|
||||||
|
new_disk: false,
|
||||||
|
}) {
|
||||||
|
Response::BackedUp { targets, .. } => assert!(targets[0].problem.is_none(), "{targets:?}"),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
let kept = proven_head(&home, &disk, "before");
|
||||||
draft(&mut w, "moves the head");
|
draft(&mut w, "moves the head");
|
||||||
std::fs::write(shim.join("stall"), b"").unwrap();
|
std::fs::write(stall_file(&home, A), b"").unwrap();
|
||||||
let mut call = call_unanswered(&home, &w, 4, "books.back_up_now", json!({}));
|
let mut call = call_unanswered(&home, &w, 5, "books.back_up_now", json!({}));
|
||||||
wait_for("the call reached git", Duration::from_secs(60), || {
|
wait_for("the call reached a phase", Duration::from_secs(60), || {
|
||||||
shim.join("stalled").exists()
|
reached(&home, A) > 0
|
||||||
});
|
});
|
||||||
let started = std::time::Instant::now();
|
let started = std::time::Instant::now();
|
||||||
let closing = std::thread::spawn({
|
let closing = std::thread::spawn({
|
||||||
let admin = home.run().join("admin.sock");
|
let admin = home.run().join("admin.sock");
|
||||||
move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap()
|
move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap()
|
||||||
});
|
});
|
||||||
// Answered with git still stalled: stopped by the close, not let go.
|
// Answered with the copy still stalled: stopped by the close, not let go.
|
||||||
let (status, said) = call.answer();
|
let (status, said) = call.answer();
|
||||||
assert_eq!(status, 200, "{said}");
|
assert_eq!(status, 200, "{said}");
|
||||||
assert!(
|
assert!(
|
||||||
@@ -2819,22 +2494,17 @@ fn a_close_stops_a_running_backup_call_and_says_so() {
|
|||||||
&& said.contains("nothing it was doing is recorded as done"),
|
&& said.contains("nothing it was doing is recorded as done"),
|
||||||
"{said}"
|
"{said}"
|
||||||
);
|
);
|
||||||
assert!(shim.join("stall").exists(), "the stall was lifted first");
|
assert!(stall_file(&home, A).exists(), "the stall was lifted first");
|
||||||
// Lifted now, so the close's own last backup can run.
|
// Lifted now, so the close's own last backup can run.
|
||||||
std::fs::remove_file(shim.join("stall")).unwrap();
|
std::fs::remove_file(stall_file(&home, A)).unwrap();
|
||||||
match closing.join().unwrap() {
|
match closing.join().unwrap() {
|
||||||
Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed),
|
Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed),
|
||||||
other => panic!("{other:?}"),
|
other => panic!("{other:?}"),
|
||||||
}
|
}
|
||||||
assert!(started.elapsed() < NEVER_LONGER);
|
assert!(started.elapsed() < NEVER_LONGER);
|
||||||
let stalled: Vec<u32> = std::fs::read_to_string(shim.join("stalled"))
|
// The close's own backup made the last head whole; before it the stopped
|
||||||
.unwrap_or_default()
|
// one had left the folder at `kept`, which it was proven to be above.
|
||||||
.lines()
|
assert!(proven_head(&home, &disk, "after").0 >= kept.0);
|
||||||
.filter_map(|l| l.trim().parse().ok())
|
|
||||||
.collect();
|
|
||||||
for pid in &stalled {
|
|
||||||
assert!(!alive(*pid), "git {pid} still runs");
|
|
||||||
}
|
|
||||||
let records = access_of(&home, A);
|
let records = access_of(&home, A);
|
||||||
let mine = records
|
let mine = records
|
||||||
.iter()
|
.iter()
|
||||||
@@ -3130,6 +2800,7 @@ impl Jobs {
|
|||||||
replace: false,
|
replace: false,
|
||||||
confirmed: false,
|
confirmed: false,
|
||||||
expect_head: None,
|
expect_head: None,
|
||||||
|
passphrase: None,
|
||||||
}) {
|
}) {
|
||||||
Response::RestorePreview(p) => p.head,
|
Response::RestorePreview(p) => p.head,
|
||||||
other => panic!("{other:?}"),
|
other => panic!("{other:?}"),
|
||||||
@@ -3172,6 +2843,7 @@ impl Jobs {
|
|||||||
replace,
|
replace,
|
||||||
confirmed: true,
|
confirmed: true,
|
||||||
expect_head: Some(self.restore_head.clone()),
|
expect_head: Some(self.restore_head.clone()),
|
||||||
|
passphrase: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3424,7 +3096,7 @@ fn finished<T>(what: &str, thread: std::thread::JoinHandle<T>) -> T {
|
|||||||
/// phase, by the server's test knob; they make books one at a time, so the
|
/// phase, by the server's test knob; they make books one at a time, so the
|
||||||
/// second and third wait for their turn, not yet held, until the one before
|
/// second and third wait for their turn, not yet held, until the one before
|
||||||
/// is let go), and `acme` is closed and opened again while each is: its
|
/// is let go), and `acme` is closed and opened again while each is: its
|
||||||
/// close is made slow (its backup's git stalls), and during it another book
|
/// close is made slow (its backup's copy stalls), and during it another book
|
||||||
/// (`cedar`) is opened and closed and answers at once, while the close of
|
/// (`cedar`) is opened and closed and answers at once, while the close of
|
||||||
/// `acme` is still not answered. All three jobs finish correctly, none
|
/// `acme` is still not answered. All three jobs finish correctly, none
|
||||||
/// stopped, none told of any error.
|
/// stopped, none told of any error.
|
||||||
@@ -3432,23 +3104,17 @@ fn finished<T>(what: &str, thread: std::thread::JoinHandle<T>) -> T {
|
|||||||
#[test]
|
#[test]
|
||||||
fn closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_jobs() {
|
fn closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_jobs() {
|
||||||
let home = Home::new("close-spares-other-jobs");
|
let home = Home::new("close-spares-other-jobs");
|
||||||
let shim = shim_git(&home);
|
|
||||||
let mut args = JOB_ARGS.to_vec();
|
let mut args = JOB_ARGS.to_vec();
|
||||||
args.extend(["--close-backup", "120000"]);
|
args.extend(["--close-backup", "120000", "--slow-steps", "600000"]);
|
||||||
let server = server_with_shim(&home, &shim, &args);
|
let server = Server::start_with(&home, &args);
|
||||||
let jobs = Jobs::new(&home);
|
let jobs = Jobs::new(&home);
|
||||||
home.create(B, "USD");
|
home.create(B, "USD");
|
||||||
let run = home.run();
|
let run = home.run();
|
||||||
let stalled = || {
|
let stalled = || reached(&home, A);
|
||||||
std::fs::read_to_string(shim.join("stalled"))
|
|
||||||
.unwrap_or_default()
|
|
||||||
.lines()
|
|
||||||
.count()
|
|
||||||
};
|
|
||||||
// One close and reopening of `acme`, while the jobs are held.
|
// One close and reopening of `acme`, while the jobs are held.
|
||||||
let cycle = |why: &str| {
|
let cycle = |why: &str| {
|
||||||
let before = stalled();
|
let before = stalled();
|
||||||
std::fs::write(shim.join("stall"), b"").unwrap();
|
std::fs::write(stall_file(&home, A), b"").unwrap();
|
||||||
let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() });
|
let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() });
|
||||||
wait_for(
|
wait_for(
|
||||||
&format!("{why}: the close of {A} is in its backup"),
|
&format!("{why}: the close of {A} is in its backup"),
|
||||||
@@ -3487,7 +3153,7 @@ fn closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_j
|
|||||||
"{why}"
|
"{why}"
|
||||||
);
|
);
|
||||||
assert!(!closing.is_finished(), "{why}: the close was answered");
|
assert!(!closing.is_finished(), "{why}: the close was answered");
|
||||||
std::fs::remove_file(shim.join("stall")).unwrap();
|
std::fs::remove_file(stall_file(&home, A)).unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
finished(&format!("{why}: the close of {A}"), closing),
|
finished(&format!("{why}: the close of {A}"), closing),
|
||||||
Response::CloseBook {
|
Response::CloseBook {
|
||||||
@@ -3599,177 +3265,6 @@ fn job_server_again(home: &Home) -> Server {
|
|||||||
Server::start_with(home, &args)
|
Server::start_with(home, &args)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A git that can't end on SIGTERM (its group frozen here, so the signal
|
|
||||||
/// stays pending) is killed once the grace has run out, and the lock it
|
|
||||||
/// leaves in a backup FOLDER is the owner's: the server never removes it. It
|
|
||||||
/// is recorded with its whole path, the target's backup is marked failed with
|
|
||||||
/// words naming the file and saying when it may be removed, the close says
|
|
||||||
/// its last backup wasn't whole, and the status (`books.backup`) says the
|
|
||||||
/// same after the book is opened again. The next backup, meeting the lock,
|
|
||||||
/// fails by git's own words and leaves the file; once the owner removes it
|
|
||||||
/// the backup goes on, and both repositories pass `git fsck`.
|
|
||||||
#[cfg(unix)]
|
|
||||||
#[test]
|
|
||||||
fn a_lock_a_kill_leaves_in_the_backup_folder_is_reported_and_never_removed_by_the_server() {
|
|
||||||
let home = Home::new("close-lock-left");
|
|
||||||
let shim = slow_real_git(&home);
|
|
||||||
// A bound long enough that the test freezes git before the close's own
|
|
||||||
// bound runs out: the freeze is made on the condition that git is
|
|
||||||
// inside the push, not on a guess at how long that takes.
|
|
||||||
let server = server_with_shim(
|
|
||||||
&home,
|
|
||||||
&shim,
|
|
||||||
&[
|
|
||||||
"--close-backup",
|
|
||||||
"8000",
|
|
||||||
"--backup-quiet",
|
|
||||||
"3600000",
|
|
||||||
"--timers",
|
|
||||||
"20",
|
|
||||||
],
|
|
||||||
);
|
|
||||||
home.create(A, "USD");
|
|
||||||
let disk = home.dir.path().join("disk");
|
|
||||||
std::fs::create_dir_all(&disk).unwrap();
|
|
||||||
let mut w = Wire::new(&home, A);
|
|
||||||
w.initialize("owner");
|
|
||||||
set_backup_folder(&mut w, &disk);
|
|
||||||
draft(&mut w, "the first backup");
|
|
||||||
match home.admin(Request::BackUpNow {
|
|
||||||
id: A.into(),
|
|
||||||
new_disk: false,
|
|
||||||
}) {
|
|
||||||
Response::BackedUp { targets, .. } => {
|
|
||||||
assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}");
|
|
||||||
}
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
}
|
|
||||||
draft(&mut w, "to be pushed inside a push");
|
|
||||||
let target = disk.join(format!("{A}.git"));
|
|
||||||
let lock = target.join("refs").join("heads").join("main.lock");
|
|
||||||
// Another writer's lock, there before our push: never touched, never
|
|
||||||
// named.
|
|
||||||
let another = target.join("refs").join("heads").join("another.lock");
|
|
||||||
std::fs::write(&another, b"").unwrap();
|
|
||||||
std::fs::write(shim.join("deaf"), b"").unwrap();
|
|
||||||
std::fs::write(shim.join("slow-push"), b"").unwrap();
|
|
||||||
let closing = std::thread::spawn({
|
|
||||||
let admin = home.run().join("admin.sock");
|
|
||||||
move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap()
|
|
||||||
});
|
|
||||||
wait_for("git is inside the push", Duration::from_secs(60), || {
|
|
||||||
shim.join("hooked").exists() && lock.exists()
|
|
||||||
});
|
|
||||||
let hooked: u32 = std::fs::read_to_string(shim.join("hooked"))
|
|
||||||
.unwrap()
|
|
||||||
.lines()
|
|
||||||
.next()
|
|
||||||
.unwrap()
|
|
||||||
.trim()
|
|
||||||
.parse()
|
|
||||||
.unwrap();
|
|
||||||
freeze_group_of(hooked);
|
|
||||||
let outcome = match closing.join().unwrap() {
|
|
||||||
Response::CloseBook { outcome, .. } => outcome,
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
};
|
|
||||||
let why = match outcome {
|
|
||||||
CloseOutcome::ClosedBackupIncomplete(why) => why,
|
|
||||||
other => panic!("a backup that left a lock was answered as {other:?}"),
|
|
||||||
};
|
|
||||||
let lock_text = lock.display().to_string();
|
|
||||||
// Every lock git left in the folder, the HEAD lock beside the branch's
|
|
||||||
// own (git locks HEAD as well when it moves the branch HEAD names; a
|
|
||||||
// newer git goes on past a stale one, an older one refuses the push
|
|
||||||
// with "cannot lock ref 'HEAD'", as on macOS): each is named in the
|
|
||||||
// words, and the owner removes those, as the words say, and no other.
|
|
||||||
let left: Vec<PathBuf> = locks_under(&target)
|
|
||||||
.into_iter()
|
|
||||||
.filter(|l| l != "refs/heads/another.lock")
|
|
||||||
.map(|l| target.join(l))
|
|
||||||
.collect();
|
|
||||||
assert!(left.contains(&lock), "{left:?}");
|
|
||||||
for file in &left {
|
|
||||||
assert!(
|
|
||||||
why.contains(&file.display().to_string()),
|
|
||||||
"{} isn't named in: {why}",
|
|
||||||
file.display()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert!(why.contains(&lock_text), "{why}");
|
|
||||||
assert!(
|
|
||||||
why.contains("nothing else is using the backup folder"),
|
|
||||||
"{why}"
|
|
||||||
);
|
|
||||||
assert!(!why.contains("another.lock"), "{why}");
|
|
||||||
assert!(!why.contains(&home.root().display().to_string()), "{why}");
|
|
||||||
// Left where it was: the server deleted nothing in the owner's folder.
|
|
||||||
assert!(lock.exists(), "a file in the owner's folder was deleted");
|
|
||||||
assert!(another.exists());
|
|
||||||
let record = backup_record_of(&home, A);
|
|
||||||
assert!(
|
|
||||||
record
|
|
||||||
.iter()
|
|
||||||
.any(|r| r.get("kind") == Some(&json!("lock_left"))
|
|
||||||
&& r.get("repo") == Some(&json!("folder"))
|
|
||||||
&& r.get("path") == Some(&json!(lock_text))),
|
|
||||||
"{record:?}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
!record
|
|
||||||
.iter()
|
|
||||||
.any(|r| r.get("kind") == Some(&json!("lock_removed"))
|
|
||||||
&& r.get("repo") == Some(&json!("folder"))),
|
|
||||||
"{record:?}"
|
|
||||||
);
|
|
||||||
// Opened again, the status says it, in words that name the file.
|
|
||||||
std::fs::remove_file(shim.join("slow-push")).unwrap();
|
|
||||||
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
|
|
||||||
let mut w = Wire::new(&home, A);
|
|
||||||
w.initialize("owner");
|
|
||||||
let status = w.call("books.backup", json!({}));
|
|
||||||
let shown = status["result"]["structuredContent"]["targets"][0]["last_error"]
|
|
||||||
.as_str()
|
|
||||||
.unwrap_or_else(|| panic!("the status names no failure: {status}"))
|
|
||||||
.to_string();
|
|
||||||
assert!(shown.contains(&lock_text), "{shown}");
|
|
||||||
assert!(
|
|
||||||
shown.contains("nothing else is using the backup folder"),
|
|
||||||
"{shown}"
|
|
||||||
);
|
|
||||||
// With the lock still there the next backup fails (git's own words) and
|
|
||||||
// the file stays; once the owner removes it, it goes on.
|
|
||||||
match home.admin(Request::BackUpNow {
|
|
||||||
id: A.into(),
|
|
||||||
new_disk: false,
|
|
||||||
}) {
|
|
||||||
Response::BackedUp { targets, .. } => {
|
|
||||||
assert!(targets.iter().any(|t| t.problem.is_some()), "{targets:?}");
|
|
||||||
}
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
}
|
|
||||||
assert!(
|
|
||||||
left.iter().all(|f| f.exists()),
|
|
||||||
"a later backup removed one of {left:?}"
|
|
||||||
);
|
|
||||||
for file in &left {
|
|
||||||
std::fs::remove_file(file).unwrap();
|
|
||||||
}
|
|
||||||
match home.admin(Request::BackUpNow {
|
|
||||||
id: A.into(),
|
|
||||||
new_disk: false,
|
|
||||||
}) {
|
|
||||||
Response::BackedUp { targets, .. } => {
|
|
||||||
assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}");
|
|
||||||
}
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
}
|
|
||||||
assert!(another.exists());
|
|
||||||
fsck_of(&home.book_dir(A).join("archive.git"));
|
|
||||||
fsck_of(&target);
|
|
||||||
assert!(server.close().success());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `thread` finished within `within`, never hanging the test.
|
/// Whether `thread` finished within `within`, never hanging the test.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn finishes_within<T>(thread: &std::thread::JoinHandle<T>, within: Duration) -> bool {
|
fn finishes_within<T>(thread: &std::thread::JoinHandle<T>, within: Duration) -> bool {
|
||||||
@@ -3801,6 +3296,7 @@ fn a_close_is_answered_while_a_restore_preview_of_its_book_is_still_running() {
|
|||||||
replace: false,
|
replace: false,
|
||||||
confirmed: false,
|
confirmed: false,
|
||||||
expect_head: None,
|
expect_head: None,
|
||||||
|
passphrase: None,
|
||||||
};
|
};
|
||||||
let previewing = job_held_in(&home, "restore:fetch", &preview, "restore:fetch");
|
let previewing = job_held_in(&home, "restore:fetch", &preview, "restore:fetch");
|
||||||
let closing = admin_in_thread(&home, Request::CloseBook { id: A.to_string() });
|
let closing = admin_in_thread(&home, Request::CloseBook { id: A.to_string() });
|
||||||
|
|||||||
@@ -130,11 +130,30 @@ pub enum AgentStart {
|
|||||||
Missing(Installer),
|
Missing(Installer),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A passphrase typed into the window: never shown by `Debug`, wiped from
|
||||||
|
/// memory when dropped.
|
||||||
|
#[derive(Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct Secret(pub String);
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Secret {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("Secret(…)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Secret {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
zeroize::Zeroize::zeroize(&mut self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A restore previewed: what it would do, and what it is of (INVARIANT 3).
|
/// A restore previewed: what it would do, and what it is of (INVARIANT 3).
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct RestorePlan {
|
pub struct RestorePlan {
|
||||||
/// The backup, as the server is told it.
|
/// The backup, as the server is told it: a folder or a file.
|
||||||
pub source: String,
|
pub source: String,
|
||||||
|
/// Its passphrase when it has one: never shown, wiped when dropped.
|
||||||
|
pub passphrase: Option<Secret>,
|
||||||
/// The books' id it comes back as.
|
/// The books' id it comes back as.
|
||||||
pub id: String,
|
pub id: String,
|
||||||
/// Whether it replaces the books of that id (kept in legacy/).
|
/// Whether it replaces the books of that id (kept in legacy/).
|
||||||
@@ -441,6 +460,7 @@ pub trait Owner: Send + Sync {
|
|||||||
source: &str,
|
source: &str,
|
||||||
id: Option<String>,
|
id: Option<String>,
|
||||||
replace: bool,
|
replace: bool,
|
||||||
|
passphrase: Option<Secret>,
|
||||||
) -> Result<RestorePlan, String>;
|
) -> Result<RestorePlan, String>;
|
||||||
/// Restore as `plan` previewed it.
|
/// Restore as `plan` previewed it.
|
||||||
fn restore(&self, plan: &RestorePlan) -> Result<Vec<String>, String>;
|
fn restore(&self, plan: &RestorePlan) -> Result<Vec<String>, String>;
|
||||||
@@ -632,6 +652,9 @@ struct RestoreForm {
|
|||||||
source: String,
|
source: String,
|
||||||
id: String,
|
id: String,
|
||||||
replace: bool,
|
replace: bool,
|
||||||
|
/// The backup's passphrase, if it has one (wiped when the form is
|
||||||
|
/// dropped).
|
||||||
|
passphrase: String,
|
||||||
/// A check under way, and what it was asked (a result for anything
|
/// A check under way, and what it was asked (a result for anything
|
||||||
/// since edited is dropped).
|
/// since edited is dropped).
|
||||||
planning: Option<Checking>,
|
planning: Option<Checking>,
|
||||||
@@ -639,6 +662,13 @@ struct RestoreForm {
|
|||||||
problem: Option<String>,
|
problem: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Drop for RestoreForm {
|
||||||
|
/// What was typed and not handed over is wiped from memory.
|
||||||
|
fn drop(&mut self) {
|
||||||
|
zeroize::Zeroize::zeroize(&mut self.passphrase);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The menu's state: a dialog, the job under way, and the last outcome.
|
/// The menu's state: a dialog, the job under way, and the last outcome.
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct OwnerMenu {
|
pub struct OwnerMenu {
|
||||||
@@ -1114,7 +1144,7 @@ impl OwnerMenu {
|
|||||||
egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-restore")).show(ctx, |ui| {
|
egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-restore")).show(ctx, |ui| {
|
||||||
ui.set_max_width(520.0);
|
ui.set_max_width(520.0);
|
||||||
ui.heading("Restore books");
|
ui.heading("Restore books");
|
||||||
ui.label("The backup: its repository's address, or its folder (the books' .git folder in your backup folder).");
|
ui.label("The backup: your backup folder, the folder of one set of books in it, or a backup file (.wbbackup).");
|
||||||
// Not changed while it is being checked.
|
// Not changed while it is being checked.
|
||||||
let open = form.planning.is_none();
|
let open = form.planning.is_none();
|
||||||
let edited = ui
|
let edited = ui
|
||||||
@@ -1122,9 +1152,21 @@ impl OwnerMenu {
|
|||||||
open,
|
open,
|
||||||
egui::TextEdit::singleline(&mut form.source)
|
egui::TextEdit::singleline(&mut form.source)
|
||||||
.desired_width(f32::INFINITY)
|
.desired_width(f32::INFINITY)
|
||||||
.hint_text("/media/backup/acme.git, or git@host:you/books.git"),
|
.hint_text("/media/backup, or /home/you/acme.wbbackup"),
|
||||||
)
|
)
|
||||||
.changed();
|
.changed();
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label("Passphrase, if the backup has one");
|
||||||
|
if ui
|
||||||
|
.add_enabled(
|
||||||
|
open,
|
||||||
|
egui::TextEdit::singleline(&mut form.passphrase).password(true),
|
||||||
|
)
|
||||||
|
.changed()
|
||||||
|
{
|
||||||
|
form.plan = None;
|
||||||
|
}
|
||||||
|
});
|
||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
ui.label("As the books");
|
ui.label("As the books");
|
||||||
let id_edited = ui
|
let id_edited = ui
|
||||||
@@ -1164,6 +1206,8 @@ impl OwnerMenu {
|
|||||||
if ui.add_enabled(ready, egui::Button::new("Check it")).clicked() {
|
if ui.add_enabled(ready, egui::Button::new("Check it")).clicked() {
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
let (o, s, r) = (owner.clone(), form.source.clone(), form.replace);
|
let (o, s, r) = (owner.clone(), form.source.clone(), form.replace);
|
||||||
|
let pass = Some(Secret(form.passphrase.clone()))
|
||||||
|
.filter(|p| !p.0.is_empty());
|
||||||
let id = Some(form.id.trim().to_string()).filter(|i| !i.is_empty());
|
let id = Some(form.id.trim().to_string()).filter(|i| !i.is_empty());
|
||||||
let ctx = ui.ctx().clone();
|
let ctx = ui.ctx().clone();
|
||||||
// Only reads the backup: stopped with its tab.
|
// Only reads the backup: stopped with its tab.
|
||||||
@@ -1174,7 +1218,7 @@ impl OwnerMenu {
|
|||||||
if stop.requested() {
|
if stop.requested() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let _ = tx.send(o.plan_restore(&s, id, r));
|
let _ = tx.send(o.plan_restore(&s, id, r, pass));
|
||||||
ctx.request_repaint();
|
ctx.request_repaint();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -264,7 +264,13 @@ impl Owner for Fake {
|
|||||||
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
|
fn plan_restore(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<String>,
|
||||||
|
_: bool,
|
||||||
|
_: Option<ledger_gui::owner::Secret>,
|
||||||
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
||||||
|
|||||||
@@ -34,7 +34,13 @@ impl Owner for Fake {
|
|||||||
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
|
fn plan_restore(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<String>,
|
||||||
|
_: bool,
|
||||||
|
_: Option<ledger_gui::owner::Secret>,
|
||||||
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
||||||
|
|||||||
@@ -91,6 +91,7 @@ impl Owner for Fake {
|
|||||||
_source: &str,
|
_source: &str,
|
||||||
_id: Option<String>,
|
_id: Option<String>,
|
||||||
_replace: bool,
|
_replace: bool,
|
||||||
|
_passphrase: Option<ledger_gui::owner::Secret>,
|
||||||
) -> Result<RestorePlan, String> {
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not in these tests".into())
|
Err("not in these tests".into())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -80,7 +80,13 @@ impl Owner for Held {
|
|||||||
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
|
fn plan_restore(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<String>,
|
||||||
|
_: bool,
|
||||||
|
_: Option<ledger_gui::owner::Secret>,
|
||||||
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
||||||
|
|||||||
@@ -48,11 +48,13 @@ impl Owner for Fake {
|
|||||||
source: &str,
|
source: &str,
|
||||||
id: Option<String>,
|
id: Option<String>,
|
||||||
replace: bool,
|
replace: bool,
|
||||||
|
passphrase: Option<ledger_gui::owner::Secret>,
|
||||||
) -> Result<RestorePlan, String> {
|
) -> Result<RestorePlan, String> {
|
||||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||||
self.said(format!("plan {source} {id:?} {replace}"));
|
self.said(format!("plan {source} {id:?} {replace}"));
|
||||||
Ok(RestorePlan {
|
Ok(RestorePlan {
|
||||||
source: source.to_string(),
|
source: source.to_string(),
|
||||||
|
passphrase,
|
||||||
id: id.unwrap_or_else(|| "acme".into()),
|
id: id.unwrap_or_else(|| "acme".into()),
|
||||||
replace,
|
replace,
|
||||||
head: (7, "ab".repeat(32)),
|
head: (7, "ab".repeat(32)),
|
||||||
@@ -220,7 +222,7 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() {
|
|||||||
h.get_all_by_role(egui::accesskit::Role::TextInput)
|
h.get_all_by_role(egui::accesskit::Role::TextInput)
|
||||||
.nth(page_fields)
|
.nth(page_fields)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.type_text("/media/disk/acme.git");
|
.type_text("/media/disk/backups");
|
||||||
h.run_steps(2);
|
h.run_steps(2);
|
||||||
assert!(
|
assert!(
|
||||||
h.query_by_label("Restore it").is_none(),
|
h.query_by_label("Restore it").is_none(),
|
||||||
@@ -230,7 +232,7 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() {
|
|||||||
settle(&mut h, &f, start + 3);
|
settle(&mut h, &f, start + 3);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
f.asked.lock().unwrap()[start + 2],
|
f.asked.lock().unwrap()[start + 2],
|
||||||
"plan /media/disk/acme.git None false"
|
"plan /media/disk/backups None false"
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
h.query_by_label_contains("is whole: through event 7")
|
h.query_by_label_contains("is whole: through event 7")
|
||||||
@@ -240,7 +242,7 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() {
|
|||||||
settle(&mut h, &f, start + 4);
|
settle(&mut h, &f, start + 4);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
f.asked.lock().unwrap()[start + 3],
|
f.asked.lock().unwrap()[start + 3],
|
||||||
"restore /media/disk/acme.git acme 7"
|
"restore /media/disk/backups acme 7"
|
||||||
);
|
);
|
||||||
|
|
||||||
// There is no "Close the books": a company's tab, or the window, closes
|
// There is no "Close the books": a company's tab, or the window, closes
|
||||||
@@ -307,7 +309,7 @@ fn nothing_is_changed_while_it_is_at_work() {
|
|||||||
h.get_all_by_role(egui::accesskit::Role::TextInput)
|
h.get_all_by_role(egui::accesskit::Role::TextInput)
|
||||||
.nth(page_fields)
|
.nth(page_fields)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.type_text("/media/disk/acme.git");
|
.type_text("/media/disk/backups");
|
||||||
h.run_steps(2);
|
h.run_steps(2);
|
||||||
h.get_by_label("Check it").click();
|
h.get_by_label("Check it").click();
|
||||||
h.run_steps(2);
|
h.run_steps(2);
|
||||||
@@ -390,7 +392,7 @@ fn screenshots() {
|
|||||||
h.get_all_by_role(egui::accesskit::Role::TextInput)
|
h.get_all_by_role(egui::accesskit::Role::TextInput)
|
||||||
.nth(page_fields)
|
.nth(page_fields)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.type_text("/media/disk/acme.git");
|
.type_text("/media/disk/backups");
|
||||||
shot(&mut h, "restore-ask");
|
shot(&mut h, "restore-ask");
|
||||||
h.get_by_label("Check it").click();
|
h.get_by_label("Check it").click();
|
||||||
let n = f.asked.lock().unwrap().len();
|
let n = f.asked.lock().unwrap().len();
|
||||||
|
|||||||
@@ -179,7 +179,13 @@ impl Owner for Fake {
|
|||||||
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
|
fn plan_restore(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<String>,
|
||||||
|
_: bool,
|
||||||
|
_: Option<ledger_gui::owner::Secret>,
|
||||||
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
||||||
@@ -464,7 +470,13 @@ fn a_window_with_no_server_asks_nothing_of_any() {
|
|||||||
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
|
fn plan_restore(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<String>,
|
||||||
|
_: bool,
|
||||||
|
_: Option<ledger_gui::owner::Secret>,
|
||||||
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
||||||
|
|||||||
@@ -42,7 +42,13 @@ impl Owner for Quiet {
|
|||||||
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
|
fn plan_restore(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<String>,
|
||||||
|
_: bool,
|
||||||
|
_: Option<ledger_gui::owner::Secret>,
|
||||||
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
||||||
|
|||||||
@@ -585,7 +585,13 @@ impl Owner for Agentic {
|
|||||||
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
|
fn plan_restore(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<String>,
|
||||||
|
_: bool,
|
||||||
|
_: Option<ledger_gui::owner::Secret>,
|
||||||
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
||||||
@@ -2105,9 +2111,11 @@ impl Owner for Gated {
|
|||||||
source: &str,
|
source: &str,
|
||||||
id: Option<String>,
|
id: Option<String>,
|
||||||
replace: bool,
|
replace: bool,
|
||||||
|
passphrase: Option<ledger_gui::owner::Secret>,
|
||||||
) -> Result<RestorePlan, String> {
|
) -> Result<RestorePlan, String> {
|
||||||
Ok(RestorePlan {
|
Ok(RestorePlan {
|
||||||
source: source.to_string(),
|
source: source.to_string(),
|
||||||
|
passphrase,
|
||||||
id: id.unwrap_or_else(|| "alpha".into()),
|
id: id.unwrap_or_else(|| "alpha".into()),
|
||||||
replace,
|
replace,
|
||||||
head: (7, "ab".repeat(32)),
|
head: (7, "ab".repeat(32)),
|
||||||
|
|||||||
@@ -40,7 +40,13 @@ impl Owner for Fake {
|
|||||||
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
||||||
Err("not in these tests".into())
|
Err("not in these tests".into())
|
||||||
}
|
}
|
||||||
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
|
fn plan_restore(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<String>,
|
||||||
|
_: bool,
|
||||||
|
_: Option<ledger_gui::owner::Secret>,
|
||||||
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not in these tests".into())
|
Err("not in these tests".into())
|
||||||
}
|
}
|
||||||
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
||||||
|
|||||||
@@ -183,6 +183,7 @@ impl Owner for Web {
|
|||||||
_source: &str,
|
_source: &str,
|
||||||
_id: Option<String>,
|
_id: Option<String>,
|
||||||
_replace: bool,
|
_replace: bool,
|
||||||
|
_passphrase: Option<ledger_gui::owner::Secret>,
|
||||||
) -> Result<RestorePlan, String> {
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,7 +47,13 @@ impl Owner for Fake {
|
|||||||
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
fn back_up_now(&self, _: &str) -> Result<Vec<String>, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn plan_restore(&self, _: &str, _: Option<String>, _: bool) -> Result<RestorePlan, String> {
|
fn plan_restore(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<String>,
|
||||||
|
_: bool,
|
||||||
|
_: Option<ledger_gui::owner::Secret>,
|
||||||
|
) -> Result<RestorePlan, String> {
|
||||||
Err("not here".into())
|
Err("not here".into())
|
||||||
}
|
}
|
||||||
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
fn restore(&self, _: &RestorePlan) -> Result<Vec<String>, String> {
|
||||||
|
|||||||
@@ -2493,14 +2493,17 @@ fn make_token(
|
|||||||
Ok(info)
|
Ok(info)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The id a backup is restored as when none is given: its repository's
|
/// The id a backup is restored as when none is given and the backup does
|
||||||
/// name (`acme.git` → `acme`).
|
/// not say whose it is: the name of its folder or file (`acme` or
|
||||||
|
/// `acme.wbbackup` → `acme`).
|
||||||
fn restore_id(source: &str) -> Option<String> {
|
fn restore_id(source: &str) -> Option<String> {
|
||||||
let last = source
|
let last = source
|
||||||
.trim_end_matches('/')
|
.trim_end_matches(['/', '\\'])
|
||||||
.rsplit(['/', ':'])
|
.rsplit(['/', '\\'])
|
||||||
.next()?
|
.next()?;
|
||||||
.trim_end_matches(".git");
|
let last = last
|
||||||
|
.strip_suffix(&format!(".{}", ledger_store::backup::FILE_EXTENSION))
|
||||||
|
.unwrap_or(last);
|
||||||
ledger_store::root::BookId::parse(last)
|
ledger_store::root::BookId::parse(last)
|
||||||
.ok()
|
.ok()
|
||||||
.map(|id| id.to_string())
|
.map(|id| id.to_string())
|
||||||
@@ -2524,6 +2527,9 @@ fn confirmed(question: &str, yes: bool) -> Result<bool, String> {
|
|||||||
Ok(matches!(answer.trim(), "y" | "Y" | "yes" | "Yes"))
|
Ok(matches!(answer.trim(), "y" | "Y" | "yes" | "Yes"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What the server says of a backup that needs its passphrase.
|
||||||
|
const NEEDS_PASSPHRASE: &str = "needs the passphrase it was made with";
|
||||||
|
|
||||||
/// `wanderbooks books restore` (INVARIANT 3).
|
/// `wanderbooks books restore` (INVARIANT 3).
|
||||||
fn restore(
|
fn restore(
|
||||||
common: &Common,
|
common: &Common,
|
||||||
@@ -2536,7 +2542,20 @@ fn restore(
|
|||||||
eprintln!("error: {why}");
|
eprintln!("error: {why}");
|
||||||
Err(exit(1))
|
Err(exit(1))
|
||||||
};
|
};
|
||||||
let plan = match plan_restore(common, source, id, replace, true) {
|
let mut plan = plan_restore(common, source, id.clone(), replace, true, None);
|
||||||
|
// A backup protected by a passphrase (D-92): asked for at a terminal,
|
||||||
|
// unechoed, once; never taken from the command line, where a shell
|
||||||
|
// would keep it.
|
||||||
|
if matches!(&plan, Err(why) if why.contains(NEEDS_PASSPHRASE)) {
|
||||||
|
match rpassword::prompt_password("This backup is protected by a passphrase. Passphrase: ") {
|
||||||
|
Ok(typed) if !typed.is_empty() => {
|
||||||
|
let typed = ledger_mcp::admin::Passphrase(typed);
|
||||||
|
plan = plan_restore(common, source, id, replace, true, Some(typed));
|
||||||
|
}
|
||||||
|
_ => return fail("the backup needs its passphrase: nothing was restored".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let plan = match plan {
|
||||||
Ok(plan) => plan,
|
Ok(plan) => plan,
|
||||||
Err(why) => return fail(why),
|
Err(why) => return fail(why),
|
||||||
};
|
};
|
||||||
@@ -2566,8 +2585,11 @@ fn restore(
|
|||||||
/// what it would do, a line each (INVARIANT 3: shown before it is done).
|
/// what it would do, a line each (INVARIANT 3: shown before it is done).
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct RestorePlan {
|
pub struct RestorePlan {
|
||||||
/// The backup, as the server is told it (a folder by its full path).
|
/// The backup, as the server is told it (a folder or a file by its
|
||||||
|
/// full path).
|
||||||
pub source: String,
|
pub source: String,
|
||||||
|
/// Its passphrase, if it has one (never shown, wiped when dropped).
|
||||||
|
pub passphrase: Option<ledger_mcp::admin::Passphrase>,
|
||||||
/// The books' id it comes back as.
|
/// The books' id it comes back as.
|
||||||
pub id: String,
|
pub id: String,
|
||||||
/// Whether it replaces the books of that id (kept in legacy/).
|
/// Whether it replaces the books of that id (kept in legacy/).
|
||||||
@@ -2590,15 +2612,16 @@ pub fn plan_restore(
|
|||||||
id: Option<String>,
|
id: Option<String>,
|
||||||
replace: bool,
|
replace: bool,
|
||||||
flags: bool,
|
flags: bool,
|
||||||
|
passphrase: Option<ledger_mcp::admin::Passphrase>,
|
||||||
) -> Result<RestorePlan, String> {
|
) -> Result<RestorePlan, String> {
|
||||||
// A folder is named to the server by its full path (the server's
|
// A folder or a file is named to the server by its full path (the
|
||||||
// working folder isn't this one); anything else is an address.
|
// server's working folder isn't this one).
|
||||||
let source = match Path::new(source) {
|
let source = match Path::new(source.trim()) {
|
||||||
p if p.exists() => std::path::absolute(p)
|
p if p.exists() => std::path::absolute(p)
|
||||||
.unwrap_or_else(|_| p.to_path_buf())
|
.unwrap_or_else(|_| p.to_path_buf())
|
||||||
.display()
|
.display()
|
||||||
.to_string(),
|
.to_string(),
|
||||||
_ => source.trim().to_string(),
|
_ => return Err(format!("there is no backup at {}", source.trim())),
|
||||||
};
|
};
|
||||||
// One preview (under the id given, or any: it only reports), then the
|
// One preview (under the id given, or any: it only reports), then the
|
||||||
// id.
|
// id.
|
||||||
@@ -2614,6 +2637,7 @@ pub fn plan_restore(
|
|||||||
replace,
|
replace,
|
||||||
confirmed: false,
|
confirmed: false,
|
||||||
expect_head: None,
|
expect_head: None,
|
||||||
|
passphrase: passphrase.clone(),
|
||||||
},
|
},
|
||||||
)? {
|
)? {
|
||||||
Response::RestorePreview(p) => p,
|
Response::RestorePreview(p) => p,
|
||||||
@@ -2662,6 +2686,18 @@ pub fn plan_restore(
|
|||||||
preview.blobs,
|
preview.blobs,
|
||||||
preview.vault_files
|
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
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if preview.sealed {
|
||||||
|
lines.push(
|
||||||
|
"It is protected by a passphrase: the restored books keep backing up protected by it, from this computer."
|
||||||
|
.into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
if let Some(origin) = &preview.origin {
|
if let Some(origin) = &preview.origin {
|
||||||
lines.push(format!("It is a backup of the books \"{origin}\"."));
|
lines.push(format!("It is a backup of the books \"{origin}\"."));
|
||||||
}
|
}
|
||||||
@@ -2672,19 +2708,16 @@ pub fn plan_restore(
|
|||||||
} else {
|
} else {
|
||||||
format!("It comes back as new books \"{id}\", beside any others.")
|
format!("It comes back as new books \"{id}\", beside any others.")
|
||||||
});
|
});
|
||||||
match preview.origin.as_deref() {
|
if let Some(o) = preview.origin.as_deref()
|
||||||
Some(o) if o == id => {}
|
&& o != id
|
||||||
Some(o) => lines.push(format!(
|
{
|
||||||
"Under a name other than its books' (\"{o}\"), they won't back up to the private repository those books back up to (that would stop theirs): if these are those books, restore them as \"{o}\"{}; else name a repository of their own.",
|
lines.push(format!(
|
||||||
flag(&format!("--id {o}"))
|
"They were backed up as \"{o}\"; they come back as \"{id}\" and back up to their own folder in the backup folder."
|
||||||
)),
|
));
|
||||||
None => lines.push(
|
|
||||||
"It doesn't say whose books it holds: they won't back up to the private repository their settings name until one of their own is named."
|
|
||||||
.into(),
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
Ok(RestorePlan {
|
Ok(RestorePlan {
|
||||||
source,
|
source,
|
||||||
|
passphrase,
|
||||||
id,
|
id,
|
||||||
replace,
|
replace,
|
||||||
head: preview.head,
|
head: preview.head,
|
||||||
@@ -2702,6 +2735,7 @@ pub fn carry_out_restore(common: &Common, plan: &RestorePlan) -> Result<Vec<Stri
|
|||||||
replace: plan.replace,
|
replace: plan.replace,
|
||||||
confirmed: true,
|
confirmed: true,
|
||||||
expect_head: Some(plan.head.clone()),
|
expect_head: Some(plan.head.clone()),
|
||||||
|
passphrase: plan.passphrase.clone(),
|
||||||
};
|
};
|
||||||
match with_server(common, request)? {
|
match with_server(common, request)? {
|
||||||
Response::Restored(r) => {
|
Response::Restored(r) => {
|
||||||
@@ -4109,15 +4143,14 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_backup_is_restored_under_its_repository_name() {
|
fn a_backup_is_restored_under_its_folders_or_files_name() {
|
||||||
for (source, want) in [
|
for (source, want) in [
|
||||||
("/media/disk/backups/acme.git", Some("acme")),
|
("/media/disk/backups/acme", Some("acme")),
|
||||||
("/media/disk/backups/acme.git/", Some("acme")),
|
("/media/disk/backups/acme/", Some("acme")),
|
||||||
("git@host:owner/acme-books.git", Some("acme-books")),
|
("/media/disk/acme-books.wbbackup", Some("acme-books")),
|
||||||
("ssh://host/owner/acme", Some("acme")),
|
(r"C:\Backups\acme.wbbackup", Some("acme")),
|
||||||
("https://host/owner/acme.git", Some("acme")),
|
("acme", Some("acme")),
|
||||||
("acme.git", Some("acme")),
|
("/media/disk/Backups/Acme", None),
|
||||||
("/media/disk/Backups/Acme.git", None),
|
|
||||||
("/", None),
|
("/", None),
|
||||||
("", None),
|
("", None),
|
||||||
] {
|
] {
|
||||||
|
|||||||
@@ -121,8 +121,8 @@ pub enum Request {
|
|||||||
Restore {
|
Restore {
|
||||||
/// The books' id.
|
/// The books' id.
|
||||||
id: String,
|
id: String,
|
||||||
/// The backup: a git repository's address, or its folder
|
/// The backup: a backup folder, the folder of one set of books in
|
||||||
/// (`<book>.git` in the backup folder).
|
/// it, or a backup file (`.wbbackup`), by its full path.
|
||||||
source: String,
|
source: String,
|
||||||
/// Replace the books called `id`.
|
/// Replace the books called `id`.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -133,8 +133,12 @@ pub enum Request {
|
|||||||
/// The head the preview read: restored only if still so.
|
/// The head the preview read: restored only if still so.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
expect_head: Option<(u64, String)>,
|
expect_head: Option<(u64, String)>,
|
||||||
|
/// The backup's passphrase, when it is protected by one (D-92):
|
||||||
|
/// never shown, never kept.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
passphrase: Option<Passphrase>,
|
||||||
},
|
},
|
||||||
/// Back books up now (plan 3.7): to every target their settings name.
|
/// Back books up now (plan 3.7): to the folder their settings name.
|
||||||
BackUpNow {
|
BackUpNow {
|
||||||
/// The books.
|
/// The books.
|
||||||
id: String,
|
id: String,
|
||||||
@@ -660,6 +664,12 @@ pub struct RestorePreview {
|
|||||||
/// The id of the books it holds, as they were backed up.
|
/// The id of the books it holds, as they were backed up.
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub origin: Option<String>,
|
pub origin: Option<String>,
|
||||||
|
/// Whether it is protected by a passphrase.
|
||||||
|
#[serde(default)]
|
||||||
|
pub sealed: bool,
|
||||||
|
/// Newer backups in it that were not whole and were passed over.
|
||||||
|
#[serde(default)]
|
||||||
|
pub passed_over: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a restore did.
|
/// What a restore did.
|
||||||
@@ -687,7 +697,7 @@ pub struct Restored {
|
|||||||
/// How one backup target took a backup now.
|
/// How one backup target took a backup now.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct BackedUpTarget {
|
pub struct BackedUpTarget {
|
||||||
/// "repository" or "folder".
|
/// "folder".
|
||||||
pub target: String,
|
pub target: String,
|
||||||
/// Where (no path in the data root).
|
/// Where (no path in the data root).
|
||||||
pub at: String,
|
pub at: String,
|
||||||
@@ -988,17 +998,18 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn a_restore_request_is_a_preview_unless_confirmed() {
|
fn a_restore_request_is_a_preview_unless_confirmed() {
|
||||||
let r: Envelope = serde_json::from_value(
|
let r: Envelope = serde_json::from_value(
|
||||||
json!({"proto": 1, "op": "restore", "id": "acme", "source": "/backups/acme.git"}),
|
json!({"proto": 1, "op": "restore", "id": "acme", "source": "/backups/acme"}),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
r.request,
|
r.request,
|
||||||
Request::Restore {
|
Request::Restore {
|
||||||
id: "acme".into(),
|
id: "acme".into(),
|
||||||
source: "/backups/acme.git".into(),
|
source: "/backups/acme".into(),
|
||||||
replace: false,
|
replace: false,
|
||||||
confirmed: false,
|
confirmed: false,
|
||||||
expect_head: None,
|
expect_head: None,
|
||||||
|
passphrase: None,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1075,6 +1086,8 @@ mod tests {
|
|||||||
vault_files: 1,
|
vault_files: 1,
|
||||||
exists: true,
|
exists: true,
|
||||||
origin: Some("acme".into()),
|
origin: Some("acme".into()),
|
||||||
|
sealed: false,
|
||||||
|
passed_over: 0,
|
||||||
}),
|
}),
|
||||||
Response::Restored(Restored {
|
Response::Restored(Restored {
|
||||||
id: "acme".into(),
|
id: "acme".into(),
|
||||||
|
|||||||
+372
-439
File diff suppressed because it is too large.
Load diff
@@ -1585,7 +1585,8 @@ impl Books {
|
|||||||
replace,
|
replace,
|
||||||
confirmed,
|
confirmed,
|
||||||
expect_head,
|
expect_head,
|
||||||
} => self.restore(id, source, replace, confirmed, expect_head),
|
passphrase,
|
||||||
|
} => self.restore(id, source, replace, confirmed, expect_head, passphrase),
|
||||||
Request::UpgradeFormat { id, passphrase } => self.upgrade_format(id, &passphrase),
|
Request::UpgradeFormat { id, passphrase } => self.upgrade_format(id, &passphrase),
|
||||||
Request::OpenBook { id } => self.open_one(id),
|
Request::OpenBook { id } => self.open_one(id),
|
||||||
Request::CloseBook { id } => self.close_one(id),
|
Request::CloseBook { id } => self.close_one(id),
|
||||||
@@ -2092,19 +2093,11 @@ impl Books {
|
|||||||
};
|
};
|
||||||
// A run still going is stopped, and waited for: nothing of the
|
// A run still going is stopped, and waited for: nothing of the
|
||||||
// backups runs once this returns.
|
// backups runs once this returns.
|
||||||
let left = backups.shut().await;
|
backups.shut().await;
|
||||||
access.close();
|
access.close();
|
||||||
uploads.close();
|
uploads.close();
|
||||||
exports.close();
|
exports.close();
|
||||||
store.let_go().await;
|
store.let_go().await;
|
||||||
// A git stopped at its bound that left locks in the owner's folder:
|
|
||||||
// said with the file, as the standing says it (ledger_store backup
|
|
||||||
// INVARIANT 5b), not only that the backup took too long.
|
|
||||||
let problem = match (problem, left.is_empty()) {
|
|
||||||
(problem, true) => problem,
|
|
||||||
(None, false) => Some(left.join("; ")),
|
|
||||||
(Some(why), false) => Some(format!("{why}; {}", left.join("; "))),
|
|
||||||
};
|
|
||||||
problem.map(|why| self.hide(why))
|
problem.map(|why| self.hide(why))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2203,8 +2196,9 @@ impl Books {
|
|||||||
replace: bool,
|
replace: bool,
|
||||||
confirmed: bool,
|
confirmed: bool,
|
||||||
expect_head: Option<(u64, String)>,
|
expect_head: Option<(u64, String)>,
|
||||||
|
passphrase: Option<admin::Passphrase>,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
// admin INVARIANT 3: never the root, nor the address given.
|
// admin INVARIANT 3: never the root, nor the place given.
|
||||||
let said = |text: String| {
|
let said = |text: String| {
|
||||||
let text = if source.chars().count() > 1 {
|
let text = if source.chars().count() > 1 {
|
||||||
text.replace(&source, "the backup given")
|
text.replace(&source, "the backup given")
|
||||||
@@ -2217,26 +2211,23 @@ impl Books {
|
|||||||
Ok(id) => id,
|
Ok(id) => id,
|
||||||
Err(e) => return said(e.to_string()),
|
Err(e) => return said(e.to_string()),
|
||||||
};
|
};
|
||||||
let git = match ledger_store::backup::Git::find() {
|
let from = std::path::PathBuf::from(&source);
|
||||||
Ok(git) => git,
|
let pass = passphrase.as_ref().map(|p| p.0.as_str());
|
||||||
Err(e) => return said(e.to_string()),
|
|
||||||
};
|
|
||||||
// A preview only reports (whether books of that id exist among
|
// A preview only reports (whether books of that id exist among
|
||||||
// what it says), so it changes nothing and takes no book's turn: a
|
// what it says), so it changes nothing and takes no book's turn: a
|
||||||
// close of this id never waits behind its clone and its queue for
|
// close of this id never waits behind its clone and its queue for
|
||||||
// the books lock (INVARIANT 10). Only the server's close stops it.
|
// the books lock (INVARIANT 10). Only the server's close stops it.
|
||||||
if !confirmed {
|
if !confirmed {
|
||||||
let stop = self.job("restore", &self.server_stop);
|
let stop = self.job("restore", &self.server_stop);
|
||||||
return match self
|
return match self.root.restore_preview_stoppable(&from, pass, &id, &stop) {
|
||||||
.root
|
|
||||||
.restore_preview_stoppable(&git, &source, &id, &stop)
|
|
||||||
{
|
|
||||||
Ok(p) => Response::RestorePreview(admin::RestorePreview {
|
Ok(p) => Response::RestorePreview(admin::RestorePreview {
|
||||||
head: p.head,
|
head: p.head,
|
||||||
blobs: p.blobs,
|
blobs: p.blobs,
|
||||||
vault_files: p.vault_files,
|
vault_files: p.vault_files,
|
||||||
exists: p.exists,
|
exists: p.exists,
|
||||||
origin: p.origin,
|
origin: p.origin,
|
||||||
|
sealed: p.sealed,
|
||||||
|
passed_over: p.passed_over,
|
||||||
}),
|
}),
|
||||||
Err(e) => said(e.to_string()),
|
Err(e) => said(e.to_string()),
|
||||||
};
|
};
|
||||||
@@ -2291,7 +2282,7 @@ impl Books {
|
|||||||
}
|
}
|
||||||
match self
|
match self
|
||||||
.root
|
.root
|
||||||
.restore_stoppable(&git, &source, &id, &expect_head, replace, &stop)
|
.restore_stoppable(&from, pass, &id, &expect_head, replace, &stop)
|
||||||
{
|
{
|
||||||
Ok(r) => {
|
Ok(r) => {
|
||||||
// Restored: kept whether or not it opens; its backups told
|
// Restored: kept whether or not it opens; its backups told
|
||||||
@@ -4319,24 +4310,19 @@ fn backup_due(
|
|||||||
after(s.target_failed_at).then_some("retry")
|
after(s.target_failed_at).then_some("retry")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a run's every target holds the books: a target paused for
|
/// Whether a run's every target holds the books: none failed, so none is
|
||||||
/// these books (restored as a copy of others) is no failure to try again.
|
/// to be tried again.
|
||||||
fn every_target_held(status: &crate::backup::Status) -> bool {
|
fn every_target_held(status: &crate::backup::Status) -> bool {
|
||||||
status
|
status.targets.iter().all(|t| t.last_error.is_none())
|
||||||
.targets
|
|
||||||
.iter()
|
|
||||||
.all(|t| t.paused || t.last_error.is_none())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Why the last backup at a close wasn't whole, if it wasn't: a target
|
/// Why the last backup at a close wasn't whole, if it wasn't: a target
|
||||||
/// that failed, or lacks the books' head (a target paused for books
|
/// that failed, or lacks the books' head. None when there is nothing to
|
||||||
/// restored as a copy of others is no failure). None when there is
|
/// say, or no target.
|
||||||
/// nothing to say, or no target.
|
|
||||||
fn backup_incomplete(status: &crate::backup::Status) -> Option<String> {
|
fn backup_incomplete(status: &crate::backup::Status) -> Option<String> {
|
||||||
let lacking: Vec<String> = status
|
let lacking: Vec<String> = status
|
||||||
.targets
|
.targets
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|t| !t.paused)
|
|
||||||
.filter_map(|t| match (&t.last_error, t.through_seq) {
|
.filter_map(|t| match (&t.last_error, t.through_seq) {
|
||||||
(Some(why), _) => Some(format!("{} failed: {why}", t.at)),
|
(Some(why), _) => Some(format!("{} failed: {why}", t.at)),
|
||||||
(None, through) if through != Some(status.head_seq) => {
|
(None, through) if through != Some(status.head_seq) => {
|
||||||
@@ -4510,9 +4496,9 @@ mod tests {
|
|||||||
w.backed = Some(5);
|
w.backed = Some(5);
|
||||||
assert_eq!(backup_due(Some(&w), 5, at(9 + retry - 1), quiet), None);
|
assert_eq!(backup_due(Some(&w), 5, at(9 + retry - 1), quiet), None);
|
||||||
assert_eq!(backup_due(Some(&w), 5, at(9 + retry), quiet), Some("retry"));
|
assert_eq!(backup_due(Some(&w), 5, at(9 + retry), quiet), Some("retry"));
|
||||||
// A paused target is no failure; another's error is.
|
// A target's error is a failure to try again.
|
||||||
let target = |paused: bool, error: Option<&str>| crate::backup::TargetStatus {
|
let target = |error: Option<&str>| crate::backup::TargetStatus {
|
||||||
target: "repository".into(),
|
target: "folder".into(),
|
||||||
at: "x".into(),
|
at: "x".into(),
|
||||||
last_ok_at: None,
|
last_ok_at: None,
|
||||||
through_seq: None,
|
through_seq: None,
|
||||||
@@ -4520,20 +4506,18 @@ mod tests {
|
|||||||
last_error: error.map(str::to_string),
|
last_error: error.map(str::to_string),
|
||||||
last_drill_at: None,
|
last_drill_at: None,
|
||||||
drill_error: None,
|
drill_error: None,
|
||||||
paused,
|
sealed: false,
|
||||||
|
disconnected: false,
|
||||||
};
|
};
|
||||||
let status = |targets| crate::backup::Status {
|
let status = |targets| crate::backup::Status {
|
||||||
head_seq: 5,
|
head_seq: 5,
|
||||||
targets,
|
targets,
|
||||||
note: None,
|
note: None,
|
||||||
};
|
};
|
||||||
assert!(every_target_held(&status(vec![
|
assert!(every_target_held(&status(vec![target(None), target(None)])));
|
||||||
target(true, Some("paused")),
|
|
||||||
target(false, None)
|
|
||||||
])));
|
|
||||||
assert!(!every_target_held(&status(vec![
|
assert!(!every_target_held(&status(vec![
|
||||||
target(false, Some("no")),
|
target(Some("no")),
|
||||||
target(false, None)
|
target(None)
|
||||||
])));
|
])));
|
||||||
assert!(every_target_held(&status(vec![])));
|
assert!(every_target_held(&status(vec![])));
|
||||||
w.ran(5, Some(true), at(9 + retry));
|
w.ran(5, Some(true), at(9 + retry));
|
||||||
@@ -5193,19 +5177,15 @@ mod tests {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// git, on the books' own archive: what it said.
|
/// The books' own local backup, proven whole and built in a scratch
|
||||||
fn archive_git(dir: &Path, args: &[&str]) -> String {
|
/// folder: the books as they were backed up.
|
||||||
let out = std::process::Command::new("git")
|
fn local_backup(dir: &Path, tag: &str) -> ledger_store::backup::Verified {
|
||||||
.arg(format!(
|
let scratch = dir.join(format!("scratch-{tag}"));
|
||||||
"--git-dir={}",
|
let ctx = ledger_store::backup::Ctx::new();
|
||||||
// A canonical path on Windows carries `\\?\`, which git refuses.
|
let found =
|
||||||
ledger_store::root::plain_path(&dir.join("archive.git")).display()
|
ledger_store::backup::find(&dir.join(ledger_store::backup::LOCAL_DIR), None, &ctx)
|
||||||
))
|
.expect("a local backup is there");
|
||||||
.args(args)
|
ledger_store::backup::verify_found(&found, &scratch, true, &ctx).expect("it proves whole")
|
||||||
.output()
|
|
||||||
.unwrap();
|
|
||||||
assert!(out.status.success(), "{out:?}");
|
|
||||||
String::from_utf8(out.stdout).unwrap()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// plan/served.md 3.9's `format_upgrade_waits_for_consent`, the
|
/// plan/served.md 3.9's `format_upgrade_waits_for_consent`, the
|
||||||
@@ -5258,7 +5238,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
assert_eq!(journal(), before);
|
assert_eq!(journal(), before);
|
||||||
assert!(
|
assert!(
|
||||||
!dir.join("archive.git").exists(),
|
!dir.join(ledger_store::backup::LOCAL_DIR).exists(),
|
||||||
"no backup before consent"
|
"no backup before consent"
|
||||||
);
|
);
|
||||||
assert!(listed(&books, "acme").format_upgrade.is_some());
|
assert!(listed(&books, "acme").format_upgrade.is_some());
|
||||||
@@ -5296,20 +5276,15 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert_eq!(done.head.0, backup.head.0 + 1);
|
assert_eq!(done.head.0, backup.head.0 + 1);
|
||||||
// The backup: the books as they were, keys and all, the latest
|
// The backup: the books as they were, keys and all, the latest
|
||||||
// commit of their archive.
|
// of their local backup.
|
||||||
|
assert_eq!(backup.commit, "local backup 1");
|
||||||
|
let kept = local_backup(&dir, "kept");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
archive_git(&dir, &["rev-parse", "HEAD"]).trim(),
|
std::fs::read(kept.tree.join(ledger_store::JOURNAL_FILE)).unwrap(),
|
||||||
backup.commit
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.commit)]).as_bytes(),
|
|
||||||
before.as_slice()
|
before.as_slice()
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
archive_git(
|
std::fs::read_to_string(kept.tree.join("keys").join("legacy.key")).unwrap(),
|
||||||
&dir,
|
|
||||||
&["show", &format!("{}:keys/legacy.key", backup.commit)]
|
|
||||||
),
|
|
||||||
"ab".repeat(32)
|
"ab".repeat(32)
|
||||||
);
|
);
|
||||||
// Both on the backup record.
|
// Both on the backup record.
|
||||||
@@ -5333,7 +5308,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
assert_eq!(journal(), after);
|
assert_eq!(journal(), after);
|
||||||
// Books this version made wait for nothing, and asking for their
|
// Books this version made wait for nothing, and asking for their
|
||||||
// upgrade changes nothing of them: not even a backup repository.
|
// upgrade changes nothing of them: not even a local backup.
|
||||||
create(&books, "beta");
|
create(&books, "beta");
|
||||||
assert_eq!(listed(&books, "beta").format_upgrade, None);
|
assert_eq!(listed(&books, "beta").format_upgrade, None);
|
||||||
let beta = books.root.book_dir(&BookId::parse("beta").unwrap());
|
let beta = books.root.book_dir(&BookId::parse("beta").unwrap());
|
||||||
@@ -5343,18 +5318,18 @@ mod tests {
|
|||||||
}
|
}
|
||||||
other => panic!("{other:?}"),
|
other => panic!("{other:?}"),
|
||||||
}
|
}
|
||||||
assert!(!beta.join("archive.git").exists(), "nothing was changed");
|
assert!(
|
||||||
|
!beta.join(ledger_store::backup::LOCAL_DIR).exists(),
|
||||||
|
"nothing was changed"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The backup is trusted only once proven, and only the one just made:
|
/// The backup is trusted only once proven: a local backup that was
|
||||||
/// an archive whose head names a branch other than the one a backup's
|
/// written and then damaged proves nothing whole, so nothing is
|
||||||
/// clone takes (a damaged archive) takes the new commit where no
|
/// upgraded, and it is recorded. Once it is right, its latest (which
|
||||||
/// clone finds it, so what is proven isn't what was made: nothing is
|
/// already holds the books) is proven and the upgrade made.
|
||||||
/// upgraded, and it is recorded. Once the archive is right, its latest
|
|
||||||
/// commit (which already holds the books) is proven and the upgrade
|
|
||||||
/// made.
|
|
||||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
async fn no_upgrade_unless_the_backup_just_made_is_proven() {
|
async fn no_upgrade_unless_the_backup_is_proven() {
|
||||||
let home = tempfile::tempdir().unwrap();
|
let home = tempfile::tempdir().unwrap();
|
||||||
let books = books_in(home.path());
|
let books = books_in(home.path());
|
||||||
let dir = old_books(&books, "acme");
|
let dir = old_books(&books, "acme");
|
||||||
@@ -5366,17 +5341,27 @@ mod tests {
|
|||||||
};
|
};
|
||||||
let (d, s) = (dir.clone(), store.clone());
|
let (d, s) = (dir.clone(), store.clone());
|
||||||
let first = tokio::task::spawn_blocking(move || {
|
let first = tokio::task::spawn_blocking(move || {
|
||||||
let git = ledger_store::backup::Git::find().unwrap();
|
|
||||||
let head = s.with_store(|s| s.head()).unwrap();
|
let head = s.with_store(|s| s.head()).unwrap();
|
||||||
ledger_store::backup::commit(&git, &d, "acme", head).unwrap()
|
let cut = ledger_store::backup::Cut::take("acme", &d, head).unwrap();
|
||||||
|
ledger_store::backup::write_local(&d, &cut, &ledger_store::backup::Ctx::new()).unwrap()
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
|
.unwrap();
|
||||||
|
// Its journal piece is damaged, one byte.
|
||||||
|
let piece = std::fs::read_dir(
|
||||||
|
dir.join(ledger_store::backup::LOCAL_DIR)
|
||||||
|
.join("acme")
|
||||||
|
.join("journal"),
|
||||||
|
)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.expect("a first backup");
|
.next()
|
||||||
archive_git(&dir, &["symbolic-ref", "HEAD", "refs/heads/elsewhere"]);
|
.unwrap()
|
||||||
// A second later: the commit made now, of the same files, isn't
|
.unwrap()
|
||||||
// byte for byte the first (git dates commits to the second).
|
.path();
|
||||||
tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
|
let good = std::fs::read(&piece).unwrap();
|
||||||
|
let mut bad = good.clone();
|
||||||
|
bad[3] ^= 1;
|
||||||
|
std::fs::write(&piece, &bad).unwrap();
|
||||||
let before = std::fs::read(dir.join(ledger_store::JOURNAL_FILE)).unwrap();
|
let before = std::fs::read(dir.join(ledger_store::JOURNAL_FILE)).unwrap();
|
||||||
match upgrade(&books, "acme", PASS).await {
|
match upgrade(&books, "acme", PASS).await {
|
||||||
Response::Refused(why) => {
|
Response::Refused(why) => {
|
||||||
@@ -5394,18 +5379,13 @@ mod tests {
|
|||||||
std::fs::read_to_string(ledger_store::ops::ops_dir(&dir).join(crate::backup::LOG_FILE))
|
std::fs::read_to_string(ledger_store::ops::ops_dir(&dir).join(crate::backup::LOG_FILE))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
};
|
};
|
||||||
assert!(
|
|
||||||
record().contains(r#""why":"format_upgrade""#),
|
|
||||||
"the commit made: {}",
|
|
||||||
record()
|
|
||||||
);
|
|
||||||
assert!(record().contains(r#""ok":false"#), "{}", record());
|
assert!(record().contains(r#""ok":false"#), "{}", record());
|
||||||
// The archive put right: its latest commit holds the books.
|
// The piece put right: the backup proves, and the upgrade is made.
|
||||||
archive_git(&dir, &["symbolic-ref", "HEAD", "refs/heads/main"]);
|
std::fs::write(&piece, &good).unwrap();
|
||||||
match upgrade(&books, "acme", PASS).await {
|
match upgrade(&books, "acme", PASS).await {
|
||||||
Response::FormatUpgraded(u) => {
|
Response::FormatUpgraded(u) => {
|
||||||
let b = u.backup.clone().expect("proven");
|
let b = u.backup.clone().expect("proven");
|
||||||
assert_eq!(b.commit, first.commit, "{u:?}");
|
assert_eq!(b.commit, format!("local backup {}", first.number), "{u:?}");
|
||||||
assert_eq!(b.head, first.head);
|
assert_eq!(b.head, first.head);
|
||||||
assert_eq!(u.head.0, first.head.0 + 1);
|
assert_eq!(u.head.0, first.head.0 + 1);
|
||||||
}
|
}
|
||||||
@@ -5422,8 +5402,9 @@ mod tests {
|
|||||||
let books = books_in(home.path());
|
let books = books_in(home.path());
|
||||||
let dir = old_books(&books, "acme");
|
let dir = old_books(&books, "acme");
|
||||||
ledger_store::passphrase::set(&books.root.auth_dir().unwrap(), PASS, None).unwrap();
|
ledger_store::passphrase::set(&books.root.auth_dir().unwrap(), PASS, None).unwrap();
|
||||||
// A file no book keeps: the backup refuses it.
|
// A file where the local backup's folder goes: the backup can't be
|
||||||
std::fs::write(dir.join(".gitattributes"), "* -text\n").unwrap();
|
// made.
|
||||||
|
std::fs::write(dir.join(ledger_store::backup::LOCAL_DIR), "x").unwrap();
|
||||||
let before = std::fs::read(dir.join(ledger_store::JOURNAL_FILE)).unwrap();
|
let before = std::fs::read(dir.join(ledger_store::JOURNAL_FILE)).unwrap();
|
||||||
match upgrade(&books, "acme", PASS).await {
|
match upgrade(&books, "acme", PASS).await {
|
||||||
Response::Refused(why) => {
|
Response::Refused(why) => {
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
//! `books.backup` and `books.back_up_now` (plan 3.7, D-30): the books'
|
//! `books.backup` and `books.back_up_now` (plan 3.7, D-91): the books'
|
||||||
//! backups as they stand, and one made now.
|
//! backups as they stand, and one made now.
|
||||||
//!
|
//!
|
||||||
//! ```text
|
//! ```text
|
||||||
//! GOAL: the agent can tell the human whether the books are backed up,
|
//! GOAL: the agent can tell the human whether the books are backed up,
|
||||||
//! and back them up now when asked.
|
//! and back them up now when asked.
|
||||||
//! SOURCE: plan 3.7 ("books.backup {status|run} reports it": two tools,
|
//! SOURCE: plan 3.7 ("books.backup {status|run} reports it": two tools,
|
||||||
//! one read-only), D-30.
|
//! one read-only), D-91.
|
||||||
//! INVARIANTS:
|
//! INVARIANTS:
|
||||||
//! 1. A status reads the backup record only; a run makes and pushes a
|
//! 1. A status reads the backup record only; a run makes and pushes a
|
||||||
//! backup (backup.rs) and answers the status after it.
|
//! backup (backup.rs) and answers the status after it.
|
||||||
@@ -29,7 +29,7 @@ pub struct BackUpNowParams {
|
|||||||
|
|
||||||
#[derive(Debug, Serialize, JsonSchema)]
|
#[derive(Debug, Serialize, JsonSchema)]
|
||||||
pub struct TargetOut {
|
pub struct TargetOut {
|
||||||
/// "repository" (the private repository) or "folder".
|
/// "folder".
|
||||||
pub target: String,
|
pub target: String,
|
||||||
/// Where it is.
|
/// Where it is.
|
||||||
pub at: String,
|
pub at: String,
|
||||||
@@ -42,12 +42,14 @@ pub struct TargetOut {
|
|||||||
/// Why its last backup failed, if it did.
|
/// Why its last backup failed, if it did.
|
||||||
pub last_error: Option<String>,
|
pub last_error: Option<String>,
|
||||||
/// When its backup was last proven restorable (UTC), if ever: each
|
/// When its backup was last proven restorable (UTC), if ever: each
|
||||||
/// is cloned and checked weekly.
|
/// is rebuilt and checked weekly.
|
||||||
pub last_drill_at: Option<String>,
|
pub last_drill_at: Option<String>,
|
||||||
/// Why that check failed, if it did: tell the human.
|
/// Why that check failed, if it did: tell the human.
|
||||||
pub drill_error: Option<String>,
|
pub drill_error: Option<String>,
|
||||||
/// Not backed up there: these books were restored as a copy of others.
|
/// Protected by a passphrase.
|
||||||
pub paused: bool,
|
pub sealed: bool,
|
||||||
|
/// Its disk isn't connected: tell the human to connect it.
|
||||||
|
pub disconnected: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, JsonSchema)]
|
#[derive(Debug, Serialize, JsonSchema)]
|
||||||
@@ -77,7 +79,8 @@ impl From<crate::backup::Status> for BackupOut {
|
|||||||
last_error: t.last_error,
|
last_error: t.last_error,
|
||||||
last_drill_at: t.last_drill_at,
|
last_drill_at: t.last_drill_at,
|
||||||
drill_error: t.drill_error,
|
drill_error: t.drill_error,
|
||||||
paused: t.paused,
|
sealed: t.sealed,
|
||||||
|
disconnected: t.disconnected,
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
}
|
}
|
||||||
@@ -89,7 +92,7 @@ impl BooksServer {
|
|||||||
#[tool(
|
#[tool(
|
||||||
name = "books.backup",
|
name = "books.backup",
|
||||||
title = "Backups",
|
title = "Backups",
|
||||||
description = "Whether the books are backed up: each backup target the settings name (backup.git_remote, a private repository; backup.folder, a folder on another disk), when it last took the books, through which journal seq, and why it failed if it did. stale: it lacks the latest, and the first try to back that up was more than a day ago: tell the human. The books back themselves up a little after each change, when they open and before they close; books.back_up_now makes one now.",
|
description = "Whether the books are backed up: the backup folder the settings name (backup.folder: a folder on another disk, or one a sync service keeps), when it last took the books, through which journal seq, when it was last proven restorable, and why it failed if it did. stale: it lacks the latest, and the first try to back that up was more than a day ago: tell the human. disconnected: its disk isn't there. The books back themselves up a little after each change, when they open and before they close; books.back_up_now makes one now.",
|
||||||
annotations(read_only_hint = true, open_world_hint = false)
|
annotations(read_only_hint = true, open_world_hint = false)
|
||||||
)]
|
)]
|
||||||
async fn backup(&self, _params: Parameters<BackupParams>) -> Result<Json<BackupOut>, String> {
|
async fn backup(&self, _params: Parameters<BackupParams>) -> Result<Json<BackupOut>, String> {
|
||||||
@@ -99,7 +102,7 @@ impl BooksServer {
|
|||||||
#[tool(
|
#[tool(
|
||||||
name = "books.back_up_now",
|
name = "books.back_up_now",
|
||||||
title = "Back up now",
|
title = "Back up now",
|
||||||
description = "Back the books up now to every target the settings name, and answer how each 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. Needs books:admin.",
|
||||||
annotations(
|
annotations(
|
||||||
read_only_hint = false,
|
read_only_hint = false,
|
||||||
destructive_hint = false,
|
destructive_hint = false,
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
|
|||||||
//! Where a backup's files live, behind one seam: a folder on a disk
|
//! Where a backup's files live, behind one seam: a folder on a disk
|
||||||
//! ([`DirSet`]), or the one-file form ([`crate::backups::single`]).
|
//! ([`DirSet`]), or the one-file form ([`crate::backup::single`]).
|
||||||
//!
|
//!
|
||||||
//! The only operations a backup needs of a place are four: list a folder,
|
//! The only operations a backup needs of a place are four: list a folder,
|
||||||
//! ask how long a file is, read a file, and put a file there that was not
|
//! ask how long a file is, read a file, and put a file there that was not
|
||||||
File renamed without changes.
File renamed without changes.
@@ -137,6 +137,13 @@ impl BackupKey {
|
|||||||
self.kdf.salt == other.kdf.salt && bool::from(self.master.ct_eq(&*other.master))
|
self.kdf.salt == other.kdf.salt && bool::from(self.master.ct_eq(&*other.master))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A short, public name for this key: what the salt it was derived
|
||||||
|
/// with hashes to. Said in a record to tell one passphrase's backups
|
||||||
|
/// from another's; it opens nothing.
|
||||||
|
pub fn fingerprint(&self) -> String {
|
||||||
|
sha_hex(self.kdf.salt.as_bytes())[..12].to_string()
|
||||||
|
}
|
||||||
|
|
||||||
/// Keep it, privately, in the book's folder (INVARIANT: owner-only).
|
/// Keep it, privately, in the book's folder (INVARIANT: owner-only).
|
||||||
pub fn store(&self, book_dir: &Path) -> Result<(), BackupError> {
|
pub fn store(&self, book_dir: &Path) -> Result<(), BackupError> {
|
||||||
let dir = crate::root::private_book_folder(book_dir, LOCAL_DIR)
|
let dir = crate::root::private_book_folder(book_dir, LOCAL_DIR)
|
||||||
File renamed without changes.
File renamed without changes.
@@ -1,370 +0,0 @@
|
|||||||
//! Reading what a child process says, without waiting on a pipe it doesn't
|
|
||||||
//! hold (P11c, found on Windows in the open/close hammer).
|
|
||||||
//!
|
|
||||||
//! ```text
|
|
||||||
//! GOAL: the output of a child that has ended is in hand once everything
|
|
||||||
//! it wrote has been read, however long some other process keeps the
|
|
||||||
//! other end of its pipe open.
|
|
||||||
//! SOURCE: the standard library's `Command` (Windows: `CreateProcessW` with
|
|
||||||
//! `bInheritHandles`, the child's end of each pipe inheritable from
|
|
||||||
//! the moment it is made until the parent closes it, so a process
|
|
||||||
//! started by another thread in that moment holds a copy and the
|
|
||||||
//! pipe has no end-of-file until that process ends too); found by
|
|
||||||
//! the open/close hammer on Windows (plan/p15-app-and-relay.md
|
|
||||||
//! 3.1, D-77).
|
|
||||||
//! INVARIANTS:
|
|
||||||
//! 1. Nothing a child wrote is lost: bytes already in the pipe when the
|
|
||||||
//! child ended are read before the reader is let go (the pipe is asked
|
|
||||||
//! what it holds; the reader is let go only when it is blocked in its
|
|
||||||
//! read with nothing in the pipe, for QUIET together).
|
|
||||||
//! 2. The reader is let go when the pipe reaches its end (every writer
|
|
||||||
//! gone), or when it is idle as in 1, or after `limit`, whichever is
|
|
||||||
//! first; which one is reported ([`Closed`]).
|
|
||||||
//! 3. A reader let go while still blocked ends by itself when the last
|
|
||||||
//! holder of the pipe's other end lets go; it holds nothing else.
|
|
||||||
//! ```
|
|
||||||
|
|
||||||
use std::io::Read;
|
|
||||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
|
|
||||||
/// How long a reader must be seen blocked in its read, with nothing in the
|
|
||||||
/// pipe, before it is let go (INVARIANT 1): longer than any thread waits to
|
|
||||||
/// run after it has been handed a byte.
|
|
||||||
pub(crate) const QUIET: Duration = Duration::from_millis(100);
|
|
||||||
|
|
||||||
/// How long a reader in its read, with no read returning, is waited for when
|
|
||||||
/// the pipe can't say whether it holds anything.
|
|
||||||
const BLIND: Duration = Duration::from_millis(1500);
|
|
||||||
|
|
||||||
/// How the wait for a pipe ended.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub(crate) enum Closed {
|
|
||||||
/// The pipe reached its end: every writer was gone.
|
|
||||||
Eof,
|
|
||||||
/// Something else still held the pipe's other end, and nothing was left
|
|
||||||
/// in it to read.
|
|
||||||
Idle,
|
|
||||||
/// The limit passed first; what had been read is what is returned.
|
|
||||||
Limit,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Closed {
|
|
||||||
pub(crate) fn word(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Closed::Eof => "eof",
|
|
||||||
Closed::Idle => "held-open",
|
|
||||||
Closed::Limit => "limit",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A pipe being read on its own thread.
|
|
||||||
pub(crate) struct Drain {
|
|
||||||
bytes: Arc<Mutex<Vec<u8>>>,
|
|
||||||
/// True while the pipe is open (its reader hasn't ended): guards the
|
|
||||||
/// raw descriptor or handle asked about below.
|
|
||||||
open: Arc<Mutex<bool>>,
|
|
||||||
/// True from just before the reader calls `read` until it returns.
|
|
||||||
reading: Arc<AtomicBool>,
|
|
||||||
/// How many reads have returned.
|
|
||||||
reads: Arc<AtomicU64>,
|
|
||||||
raw: usize,
|
|
||||||
cap: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The raw descriptor (Unix) or handle (Windows) of a pipe, as a number.
|
|
||||||
pub(crate) trait Raw {
|
|
||||||
fn raw(&self) -> usize;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
impl<T: std::os::unix::io::AsRawFd> Raw for T {
|
|
||||||
fn raw(&self) -> usize {
|
|
||||||
self.as_raw_fd() as usize
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(windows)]
|
|
||||||
impl<T: std::os::windows::io::AsRawHandle> Raw for T {
|
|
||||||
fn raw(&self) -> usize {
|
|
||||||
self.as_raw_handle() as usize
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many bytes `pipe` holds now, if that can be asked: `None` when it
|
|
||||||
/// can't (the pipe is at its end, or the question failed), which is never
|
|
||||||
/// taken as "nothing".
|
|
||||||
fn pending(raw: usize) -> Option<usize> {
|
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
let mut fd = libc::pollfd {
|
|
||||||
fd: raw as libc::c_int,
|
|
||||||
events: libc::POLLIN,
|
|
||||||
revents: 0,
|
|
||||||
};
|
|
||||||
// SAFETY: one valid pollfd, and no wait.
|
|
||||||
let ready = unsafe { libc::poll(&mut fd, 1, 0) };
|
|
||||||
// Anything else is readable, or hung up (end of file), or failed:
|
|
||||||
// never "nothing".
|
|
||||||
if ready == 0 { Some(0) } else { None }
|
|
||||||
}
|
|
||||||
#[cfg(windows)]
|
|
||||||
{
|
|
||||||
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
|
|
||||||
let mut available: u32 = 0;
|
|
||||||
// SAFETY: `raw` is a pipe handle that stays open while `open` is
|
|
||||||
// held (the reader closes it only under that lock); no buffer is
|
|
||||||
// asked for, only the count.
|
|
||||||
let ok = unsafe {
|
|
||||||
PeekNamedPipe(
|
|
||||||
raw as *mut core::ffi::c_void,
|
|
||||||
std::ptr::null_mut(),
|
|
||||||
0,
|
|
||||||
std::ptr::null_mut(),
|
|
||||||
&mut available,
|
|
||||||
std::ptr::null_mut(),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
if ok == 0 {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(available as usize)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drain {
|
|
||||||
/// Start reading `pipe` (if any) on a thread of its own, keeping the
|
|
||||||
/// last `cap` bytes; `heard` is set to the milliseconds since `started`
|
|
||||||
/// whenever a byte arrives.
|
|
||||||
pub(crate) fn start<P>(
|
|
||||||
pipe: Option<P>,
|
|
||||||
cap: usize,
|
|
||||||
started: Instant,
|
|
||||||
heard: Arc<AtomicU64>,
|
|
||||||
) -> Drain
|
|
||||||
where
|
|
||||||
P: Read + Raw + Send + 'static,
|
|
||||||
{
|
|
||||||
let bytes = Arc::new(Mutex::new(Vec::new()));
|
|
||||||
let open = Arc::new(Mutex::new(pipe.is_some()));
|
|
||||||
let reading = Arc::new(AtomicBool::new(false));
|
|
||||||
let reads = Arc::new(AtomicU64::new(0));
|
|
||||||
let raw = pipe.as_ref().map_or(0, Raw::raw);
|
|
||||||
let (b, o, r, n_reads) = (bytes.clone(), open.clone(), reading.clone(), reads.clone());
|
|
||||||
if let Some(mut p) = pipe {
|
|
||||||
std::thread::spawn(move || {
|
|
||||||
let mut buf = [0u8; 8192];
|
|
||||||
loop {
|
|
||||||
r.store(true, Ordering::SeqCst);
|
|
||||||
let got = p.read(&mut buf);
|
|
||||||
r.store(false, Ordering::SeqCst);
|
|
||||||
n_reads.fetch_add(1, Ordering::SeqCst);
|
|
||||||
match got {
|
|
||||||
Ok(0) => break,
|
|
||||||
Ok(n) => {
|
|
||||||
heard.store(started.elapsed().as_millis() as u64, Ordering::Relaxed);
|
|
||||||
// Bounded: a git that says this much is kept
|
|
||||||
// only in part, its last part (where its
|
|
||||||
// errors are).
|
|
||||||
let mut bytes = b.lock().unwrap_or_else(|e| e.into_inner());
|
|
||||||
bytes.extend_from_slice(&buf[..n]);
|
|
||||||
if bytes.len() > cap.saturating_mul(2) {
|
|
||||||
let cut = bytes.len() - cap;
|
|
||||||
bytes.drain(..cut);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
|
|
||||||
Err(_) => break,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Closed under the lock the question above is asked under,
|
|
||||||
// so a descriptor that is gone is never asked about.
|
|
||||||
let mut open = o.lock().unwrap_or_else(|e| e.into_inner());
|
|
||||||
*open = false;
|
|
||||||
drop(p);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Drain {
|
|
||||||
bytes,
|
|
||||||
open,
|
|
||||||
reading,
|
|
||||||
reads,
|
|
||||||
raw,
|
|
||||||
cap,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the pipe has reached its end.
|
|
||||||
fn ended(&self) -> bool {
|
|
||||||
!*self.open.lock().unwrap_or_else(|e| e.into_inner())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the reader is blocked in its read with nothing in the pipe;
|
|
||||||
/// when the pipe can't say what it holds, whether the reader is in its
|
|
||||||
/// read (`None` is returned for the caller to weigh against time).
|
|
||||||
fn idle(&self) -> Option<bool> {
|
|
||||||
let open = self.open.lock().unwrap_or_else(|e| e.into_inner());
|
|
||||||
if !*open || !self.reading.load(Ordering::SeqCst) {
|
|
||||||
return Some(false);
|
|
||||||
}
|
|
||||||
pending(self.raw).map(|n| n == 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What has been read, in whole (the last `cap` bytes of it).
|
|
||||||
fn taken(&self) -> Vec<u8> {
|
|
||||||
let mut bytes = self.bytes.lock().unwrap_or_else(|e| e.into_inner());
|
|
||||||
if bytes.len() > self.cap {
|
|
||||||
let cut = bytes.len() - self.cap;
|
|
||||||
bytes.drain(..cut);
|
|
||||||
}
|
|
||||||
std::mem::take(&mut *bytes)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wait, until `limit` after `since`, for every one of `drains` to reach
|
|
||||||
/// its end or to be idle (INVARIANT 1 and 2), then take what each read: the
|
|
||||||
/// bytes, and how its wait ended.
|
|
||||||
pub(crate) fn finish<const N: usize>(
|
|
||||||
drains: [&Drain; N],
|
|
||||||
since: Instant,
|
|
||||||
limit: Duration,
|
|
||||||
) -> [(Vec<u8>, Closed); N] {
|
|
||||||
// When each reader was first seen blocked in its read (with nothing in
|
|
||||||
// the pipe, or the pipe unable to say), and the reads it had made then.
|
|
||||||
let mut idle_since: [Option<Instant>; N] = [None; N];
|
|
||||||
let mut blind_since: [Option<(Instant, u64)>; N] = [None; N];
|
|
||||||
let mut how: [Option<Closed>; N] = [None; N];
|
|
||||||
loop {
|
|
||||||
let now = Instant::now();
|
|
||||||
for (i, d) in drains.iter().enumerate() {
|
|
||||||
if how[i].is_some() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if d.ended() {
|
|
||||||
how[i] = Some(Closed::Eof);
|
|
||||||
} else {
|
|
||||||
match d.idle() {
|
|
||||||
Some(true) => {
|
|
||||||
let since = *idle_since[i].get_or_insert(now);
|
|
||||||
if now.duration_since(since) >= QUIET {
|
|
||||||
how[i] = Some(Closed::Idle);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(false) => {
|
|
||||||
idle_since[i] = None;
|
|
||||||
blind_since[i] = None;
|
|
||||||
}
|
|
||||||
// The pipe can't say what it holds: the reader in its
|
|
||||||
// read, with no read returning for BLIND, is idle (a
|
|
||||||
// reader is never kept from a byte for that long).
|
|
||||||
None => {
|
|
||||||
let reads = d.reads.load(Ordering::SeqCst);
|
|
||||||
let (since, was) = *blind_since[i].get_or_insert((now, reads));
|
|
||||||
if was != reads {
|
|
||||||
blind_since[i] = Some((now, reads));
|
|
||||||
} else if now.duration_since(since) >= BLIND {
|
|
||||||
how[i] = Some(Closed::Idle);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if how.iter().all(Option::is_some) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if now.duration_since(since) >= limit {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
std::thread::sleep(Duration::from_millis(2));
|
|
||||||
}
|
|
||||||
// An end reached in the instant before this is read: its last bytes
|
|
||||||
// are in, the reader having stored them before it ended.
|
|
||||||
std::array::from_fn(|i| (drains[i].taken(), how[i].unwrap_or(Closed::Limit)))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(all(test, unix))]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use std::process::{Command, Stdio};
|
|
||||||
|
|
||||||
fn drained(child: &mut std::process::Child) -> (Drain, Drain) {
|
|
||||||
let heard = Arc::new(AtomicU64::new(0));
|
|
||||||
let now = Instant::now();
|
|
||||||
(
|
|
||||||
Drain::start(child.stdout.take(), usize::MAX, now, heard.clone()),
|
|
||||||
Drain::start(child.stderr.take(), 1 << 20, now, heard),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// INVARIANT 1 and 2. A child that ends, leaving a grandchild that
|
|
||||||
/// still holds its pipes (the Windows leak, made by hand), has its
|
|
||||||
/// whole output read, and the wait ends in far less than the limit.
|
|
||||||
#[test]
|
|
||||||
fn a_pipe_another_process_still_holds_is_read_in_whole_without_waiting_for_it() {
|
|
||||||
let mut child = Command::new("sh")
|
|
||||||
.arg("-c")
|
|
||||||
.arg("echo out-one; echo err-one >&2; (sleep 5 </dev/null) & echo out-two")
|
|
||||||
.stdin(Stdio::null())
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.stderr(Stdio::piped())
|
|
||||||
.spawn()
|
|
||||||
.unwrap();
|
|
||||||
let status = child.wait().unwrap();
|
|
||||||
assert!(status.success());
|
|
||||||
let (out, err) = drained(&mut child);
|
|
||||||
let began = Instant::now();
|
|
||||||
let got = finish([&out, &err], began, Duration::from_secs(4));
|
|
||||||
let took = began.elapsed();
|
|
||||||
assert_eq!(String::from_utf8_lossy(&got[0].0), "out-one\nout-two\n");
|
|
||||||
assert_eq!(String::from_utf8_lossy(&got[1].0), "err-one\n");
|
|
||||||
assert_eq!(got[0].1, Closed::Idle, "held open, nothing left to read");
|
|
||||||
assert_eq!(got[1].1, Closed::Idle);
|
|
||||||
assert!(took < Duration::from_secs(2), "took {took:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// INVARIANT 2. With nobody else holding the pipe, the end is the
|
|
||||||
/// pipe's own, at once.
|
|
||||||
#[test]
|
|
||||||
fn a_pipe_nobody_holds_ends_at_its_end() {
|
|
||||||
let mut child = Command::new("sh")
|
|
||||||
.arg("-c")
|
|
||||||
.arg("echo said")
|
|
||||||
.stdin(Stdio::null())
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.stderr(Stdio::piped())
|
|
||||||
.spawn()
|
|
||||||
.unwrap();
|
|
||||||
child.wait().unwrap();
|
|
||||||
let (out, err) = drained(&mut child);
|
|
||||||
let began = Instant::now();
|
|
||||||
let got = finish([&out, &err], began, Duration::from_secs(4));
|
|
||||||
assert_eq!(String::from_utf8_lossy(&got[0].0), "said\n");
|
|
||||||
assert_eq!((got[0].1, got[1].1), (Closed::Eof, Closed::Eof));
|
|
||||||
assert!(began.elapsed() < QUIET * 5, "took {:?}", began.elapsed());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// INVARIANT 1. A lot of output, written and the writer gone before the
|
|
||||||
/// reader is looked at, is read in whole.
|
|
||||||
#[test]
|
|
||||||
fn a_lot_of_output_is_read_in_whole() {
|
|
||||||
let mut child = Command::new("sh")
|
|
||||||
.arg("-c")
|
|
||||||
.arg("i=0; while [ $i -lt 20000 ]; do echo line-$i; i=$((i+1)); done; (sleep 3 </dev/null) &")
|
|
||||||
.stdin(Stdio::null())
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.stderr(Stdio::null())
|
|
||||||
.spawn()
|
|
||||||
.unwrap();
|
|
||||||
let heard = Arc::new(AtomicU64::new(0));
|
|
||||||
let out = Drain::start(child.stdout.take(), usize::MAX, Instant::now(), heard);
|
|
||||||
child.wait().unwrap();
|
|
||||||
let got = finish([&out], Instant::now(), Duration::from_secs(4));
|
|
||||||
let text = String::from_utf8_lossy(&got[0].0).to_string();
|
|
||||||
assert_eq!(text.lines().count(), 20000);
|
|
||||||
assert_eq!(text.lines().last(), Some("line-19999"));
|
|
||||||
assert_eq!(got[0].1, Closed::Idle);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,554 +0,0 @@
|
|||||||
//! The lock files a git leaves in a repository, found and (only where it
|
|
||||||
//! is ours to) removed through a directory handle (ledger-store `backup`
|
|
||||||
//! INVARIANT 5).
|
|
||||||
//!
|
|
||||||
//! ```text
|
|
||||||
//! GOAL: a lock file a stopped git left can be seen, and removed from the
|
|
||||||
//! one repository this program owns, without ever touching anything
|
|
||||||
//! a swapped folder or link points to.
|
|
||||||
//! SOURCE: the books server's close (ledger-mcp local.rs INVARIANT 10, 13:
|
|
||||||
//! a close is answered with no git of ours still working, and
|
|
||||||
//! leaves nothing a person must clean up); git's own lock files
|
|
||||||
//! (git-config, gitrepository-layout: `HEAD.lock`, `index.lock`,
|
|
||||||
//! `<ref>.lock`, `packed-refs.lock`, `shallow.lock`,
|
|
||||||
//! `config.lock`).
|
|
||||||
//! INVARIANTS:
|
|
||||||
//! 1. A repository is opened once (`RepoDir::open`, `open_in`): a
|
|
||||||
//! directory that is not a link, the folder it was found in kept as
|
|
||||||
//! the book's own. Every look and every removal after that goes
|
|
||||||
//! through that handle: the folders below it (`refs/`, and those
|
|
||||||
//! under it) are each opened from the one above with links refused,
|
|
||||||
//! so a folder swapped for a link, or the repository's own path swapped
|
|
||||||
//! for one, after the handle was opened, sends nothing anywhere: the
|
|
||||||
//! handle still names the folder that was opened.
|
|
||||||
//! 2. Only a regular file is ever removed (never a link, never a folder,
|
|
||||||
//! never a file whose type changed), and only one named as git names
|
|
||||||
//! its locks, in the places git puts them (`is_lock`). A name that
|
|
||||||
//! isn't one is refused.
|
|
||||||
//! 3. Where there is no directory handle to be had (not Unix) each step
|
|
||||||
//! looks at the path itself and refuses a link: the same rules,
|
|
||||||
//! without the guarantee against a swap in between. Nothing else
|
|
||||||
//! about the platform's behaviour is designed here.
|
|
||||||
//! ```
|
|
||||||
|
|
||||||
use std::io;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::time::SystemTime;
|
|
||||||
|
|
||||||
/// Locks git makes in a repository's own folder.
|
|
||||||
const TOP: [&str; 5] = [
|
|
||||||
"HEAD.lock",
|
|
||||||
"index.lock",
|
|
||||||
"config.lock",
|
|
||||||
"packed-refs.lock",
|
|
||||||
"shallow.lock",
|
|
||||||
];
|
|
||||||
/// Locks git makes below it, outside `refs/`.
|
|
||||||
const BELOW: [&str; 2] = [
|
|
||||||
"objects/info/commit-graph.lock",
|
|
||||||
"objects/pack/multi-pack-index.lock",
|
|
||||||
];
|
|
||||||
/// How deep under `refs/` a lock is looked for.
|
|
||||||
const REFS_DEPTH: usize = 12;
|
|
||||||
|
|
||||||
/// Whether `rel` (a path in a repository, with `/` between its parts) is
|
|
||||||
/// named as git names a lock, in a place git puts one (INVARIANT 2).
|
|
||||||
pub fn is_lock(rel: &str) -> bool {
|
|
||||||
if TOP.contains(&rel) || BELOW.contains(&rel) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
let Some(under) = rel.strip_prefix("refs/") else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let parts: Vec<&str> = under.split('/').collect();
|
|
||||||
parts.len() <= REFS_DEPTH
|
|
||||||
&& parts
|
|
||||||
.iter()
|
|
||||||
.all(|p| !p.is_empty() && *p != "." && *p != "..")
|
|
||||||
&& parts
|
|
||||||
.last()
|
|
||||||
.is_some_and(|name| name.len() > ".lock".len() && name.ends_with(".lock"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A lock found: its path in the repository, and when it was last written.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct Found {
|
|
||||||
/// `index.lock`, `refs/heads/main.lock`.
|
|
||||||
pub lock: String,
|
|
||||||
/// Its modification time, when the system said.
|
|
||||||
pub modified: Option<SystemTime>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A repository's folder, opened once (INVARIANT 1).
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct RepoDir {
|
|
||||||
path: PathBuf,
|
|
||||||
inner: imp::Dir,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RepoDir {
|
|
||||||
/// The folder at `path`, which must not itself be a link.
|
|
||||||
pub fn open(path: &Path) -> io::Result<RepoDir> {
|
|
||||||
Ok(RepoDir {
|
|
||||||
path: path.to_path_buf(),
|
|
||||||
inner: imp::open(path)?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The folder `name` inside the folder `parent` (the book's own folder
|
|
||||||
/// holding its archive): `name` must not be a link.
|
|
||||||
pub fn open_in(parent: &Path, name: &str) -> io::Result<RepoDir> {
|
|
||||||
Ok(RepoDir {
|
|
||||||
path: parent.join(name),
|
|
||||||
inner: imp::open_in(parent, name)?,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The path it was opened by (for words, never for an operation).
|
|
||||||
pub fn path(&self) -> &Path {
|
|
||||||
&self.path
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The locks in it, sorted: regular files named as git names its locks.
|
|
||||||
pub fn locks(&self) -> Vec<Found> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
for rel in TOP.iter().chain(BELOW.iter()) {
|
|
||||||
if let Some(modified) = self.inner.regular(rel) {
|
|
||||||
out.push(Found {
|
|
||||||
lock: (*rel).to_string(),
|
|
||||||
modified,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.inner.refs(&mut out, REFS_DEPTH);
|
|
||||||
out.sort_by(|a, b| a.lock.cmp(&b.lock));
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Remove the lock `rel` (INVARIANTS 1, 2): Ok(true) if a regular file
|
|
||||||
/// of that name was removed, Ok(false) if there was none (or it was
|
|
||||||
/// not a regular file: nothing was done), Err if the name isn't a
|
|
||||||
/// lock's or the system refused.
|
|
||||||
pub fn remove(&self, rel: &str) -> io::Result<bool> {
|
|
||||||
if !is_lock(rel) {
|
|
||||||
return Err(io::Error::new(
|
|
||||||
io::ErrorKind::InvalidInput,
|
|
||||||
"not a name git gives a lock",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
self.inner.remove(rel)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
mod imp {
|
|
||||||
use super::{Found, SystemTime};
|
|
||||||
use std::ffi::{CStr, CString, OsStr};
|
|
||||||
use std::io;
|
|
||||||
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
|
|
||||||
use std::os::unix::ffi::OsStrExt;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Dir(OwnedFd);
|
|
||||||
|
|
||||||
const FLAGS: libc::c_int = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC;
|
|
||||||
|
|
||||||
fn c(text: &OsStr) -> io::Result<CString> {
|
|
||||||
CString::new(text.as_bytes())
|
|
||||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "a name with a NUL"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn owned(fd: libc::c_int) -> io::Result<OwnedFd> {
|
|
||||||
if fd < 0 {
|
|
||||||
Err(io::Error::last_os_error())
|
|
||||||
} else {
|
|
||||||
// SAFETY: a file descriptor just returned by the system, owned
|
|
||||||
// by no one else.
|
|
||||||
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn open(path: &Path) -> io::Result<Dir> {
|
|
||||||
let path = c(path.as_os_str())?;
|
|
||||||
// SAFETY: a NUL-ended path; the flags refuse a link at its end.
|
|
||||||
owned(unsafe { libc::open(path.as_ptr(), FLAGS | libc::O_NOFOLLOW) }).map(Dir)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn open_in(parent: &Path, name: &str) -> io::Result<Dir> {
|
|
||||||
let parent = c(parent.as_os_str())?;
|
|
||||||
// SAFETY: as in `open`; the parent may be reached through links (it
|
|
||||||
// is the book's own folder), only `name` may not be one.
|
|
||||||
let parent = owned(unsafe { libc::open(parent.as_ptr(), FLAGS) })?;
|
|
||||||
sub(parent.as_raw_fd(), name).map(Dir)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The folder `name` of `dir`, a link refused.
|
|
||||||
fn sub(dir: RawFd, name: &str) -> io::Result<OwnedFd> {
|
|
||||||
let name = c(OsStr::new(name))?;
|
|
||||||
// SAFETY: `dir` is open for the call; the name is NUL-ended.
|
|
||||||
owned(unsafe { libc::openat(dir, name.as_ptr(), FLAGS | libc::O_NOFOLLOW) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `name` in `dir` as it is (a link is not followed): its stat.
|
|
||||||
fn stat(dir: RawFd, name: &str) -> io::Result<libc::stat> {
|
|
||||||
let name = c(OsStr::new(name))?;
|
|
||||||
// SAFETY: zeroed stat is a valid out-parameter; `dir` is open.
|
|
||||||
let mut st: libc::stat = unsafe { std::mem::zeroed() };
|
|
||||||
let found =
|
|
||||||
unsafe { libc::fstatat(dir, name.as_ptr(), &mut st, libc::AT_SYMLINK_NOFOLLOW) };
|
|
||||||
if found == 0 {
|
|
||||||
Ok(st)
|
|
||||||
} else {
|
|
||||||
Err(io::Error::last_os_error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_regular(st: &libc::stat) -> bool {
|
|
||||||
(st.st_mode & libc::S_IFMT) == libc::S_IFREG
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_dir(st: &libc::stat) -> bool {
|
|
||||||
(st.st_mode & libc::S_IFMT) == libc::S_IFDIR
|
|
||||||
}
|
|
||||||
|
|
||||||
fn modified(st: &libc::stat) -> Option<SystemTime> {
|
|
||||||
let secs = u64::try_from(st.st_mtime).ok()?;
|
|
||||||
let nanos = u32::try_from(st.st_mtime_nsec).ok()?;
|
|
||||||
Some(SystemTime::UNIX_EPOCH + std::time::Duration::new(secs, nanos))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The names in the folder `dir` (a fresh look each time).
|
|
||||||
fn names(dir: RawFd) -> Vec<String> {
|
|
||||||
// SAFETY: a duplicate of an open descriptor, handed to fdopendir,
|
|
||||||
// which owns it from then on (closedir closes it).
|
|
||||||
let copy = unsafe { libc::dup(dir) };
|
|
||||||
if copy < 0 {
|
|
||||||
return Vec::new();
|
|
||||||
}
|
|
||||||
let stream = unsafe { libc::fdopendir(copy) };
|
|
||||||
if stream.is_null() {
|
|
||||||
// SAFETY: fdopendir didn't take it.
|
|
||||||
unsafe { libc::close(copy) };
|
|
||||||
return Vec::new();
|
|
||||||
}
|
|
||||||
let mut out = Vec::new();
|
|
||||||
// SAFETY: `stream` is a live directory stream until closedir; each
|
|
||||||
// entry's name is a NUL-ended string valid until the next readdir.
|
|
||||||
unsafe {
|
|
||||||
libc::rewinddir(stream);
|
|
||||||
loop {
|
|
||||||
let entry = libc::readdir(stream);
|
|
||||||
if entry.is_null() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
let name = CStr::from_ptr((*entry).d_name.as_ptr());
|
|
||||||
if let Ok(name) = name.to_str()
|
|
||||||
&& name != "."
|
|
||||||
&& name != ".."
|
|
||||||
{
|
|
||||||
out.push(name.to_string());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
libc::closedir(stream);
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Dir {
|
|
||||||
/// The folder holding `rel`, opened step by step from this one
|
|
||||||
/// with a link refused at each, and `rel`'s last part.
|
|
||||||
fn parent_of<'a>(&self, rel: &'a str) -> io::Result<(OwnedFd, &'a str)> {
|
|
||||||
let mut parts: Vec<&str> = rel.split('/').collect();
|
|
||||||
let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?;
|
|
||||||
// SAFETY: a duplicate of the open descriptor, owned here.
|
|
||||||
let mut here = owned(unsafe { libc::dup(self.0.as_raw_fd()) })?;
|
|
||||||
for part in parts {
|
|
||||||
here = sub(here.as_raw_fd(), part)?;
|
|
||||||
}
|
|
||||||
Ok((here, last))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A regular file at `rel`: its modification time (when known).
|
|
||||||
pub fn regular(&self, rel: &str) -> Option<Option<SystemTime>> {
|
|
||||||
let (parent, name) = self.parent_of(rel).ok()?;
|
|
||||||
let st = stat(parent.as_raw_fd(), name).ok()?;
|
|
||||||
is_regular(&st).then(|| modified(&st))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The locks under `refs/`, in `out`.
|
|
||||||
pub fn refs(&self, out: &mut Vec<Found>, depth: usize) {
|
|
||||||
let Ok(refs) = sub(self.0.as_raw_fd(), "refs") else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
fn walk(dir: RawFd, prefix: &str, depth: usize, out: &mut Vec<Found>) {
|
|
||||||
for name in names(dir) {
|
|
||||||
let Ok(st) = stat(dir, &name) else { continue };
|
|
||||||
let rel = format!("{prefix}{name}");
|
|
||||||
if is_regular(&st) {
|
|
||||||
if super::is_lock(&rel) {
|
|
||||||
out.push(Found {
|
|
||||||
lock: rel,
|
|
||||||
modified: modified(&st),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else if is_dir(&st)
|
|
||||||
&& depth > 0
|
|
||||||
&& let Ok(inner) = sub(dir, &name)
|
|
||||||
{
|
|
||||||
walk(inner.as_raw_fd(), &format!("{rel}/"), depth - 1, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
walk(refs.as_raw_fd(), "refs/", depth, out);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove(&self, rel: &str) -> io::Result<bool> {
|
|
||||||
let (parent, name) = match self.parent_of(rel) {
|
|
||||||
Ok(found) => found,
|
|
||||||
// A folder that isn't there (or is a link): nothing to remove.
|
|
||||||
Err(_) => return Ok(false),
|
|
||||||
};
|
|
||||||
match stat(parent.as_raw_fd(), name) {
|
|
||||||
Ok(st) if is_regular(&st) => {}
|
|
||||||
_ => return Ok(false),
|
|
||||||
}
|
|
||||||
let name = c(OsStr::new(name))?;
|
|
||||||
// SAFETY: the parent is open; the name is NUL-ended and relative
|
|
||||||
// to it, and names a regular file just looked at.
|
|
||||||
let removed = unsafe { libc::unlinkat(parent.as_raw_fd(), name.as_ptr(), 0) };
|
|
||||||
if removed == 0 {
|
|
||||||
Ok(true)
|
|
||||||
} else {
|
|
||||||
let e = io::Error::last_os_error();
|
|
||||||
if e.kind() == io::ErrorKind::NotFound {
|
|
||||||
Ok(false)
|
|
||||||
} else {
|
|
||||||
Err(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(unix))]
|
|
||||||
mod imp {
|
|
||||||
use super::{Found, SystemTime};
|
|
||||||
use std::io;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Dir(PathBuf);
|
|
||||||
|
|
||||||
fn plain(path: &Path) -> io::Result<()> {
|
|
||||||
let meta = std::fs::symlink_metadata(path)?;
|
|
||||||
if meta.file_type().is_symlink() || !meta.is_dir() {
|
|
||||||
return Err(io::Error::new(
|
|
||||||
io::ErrorKind::InvalidInput,
|
|
||||||
"not a plain folder",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn open(path: &Path) -> io::Result<Dir> {
|
|
||||||
plain(path)?;
|
|
||||||
Ok(Dir(path.to_path_buf()))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn open_in(parent: &Path, name: &str) -> io::Result<Dir> {
|
|
||||||
open(&parent.join(name))
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Dir {
|
|
||||||
fn at(&self, rel: &str) -> io::Result<PathBuf> {
|
|
||||||
let mut path = self.0.clone();
|
|
||||||
let mut parts: Vec<&str> = rel.split('/').collect();
|
|
||||||
let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?;
|
|
||||||
for part in parts {
|
|
||||||
path.push(part);
|
|
||||||
plain(&path)?;
|
|
||||||
}
|
|
||||||
path.push(last);
|
|
||||||
Ok(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn regular(&self, rel: &str) -> Option<Option<SystemTime>> {
|
|
||||||
let path = self.at(rel).ok()?;
|
|
||||||
let meta = std::fs::symlink_metadata(path).ok()?;
|
|
||||||
meta.file_type().is_file().then(|| meta.modified().ok())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refs(&self, out: &mut Vec<Found>, depth: usize) {
|
|
||||||
fn walk(dir: &Path, prefix: &str, depth: usize, out: &mut Vec<Found>) {
|
|
||||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
for e in entries.flatten() {
|
|
||||||
let Ok(meta) = std::fs::symlink_metadata(e.path()) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let rel = format!("{prefix}{}", e.file_name().to_string_lossy());
|
|
||||||
if meta.file_type().is_file() {
|
|
||||||
if super::is_lock(&rel) {
|
|
||||||
out.push(Found {
|
|
||||||
lock: rel,
|
|
||||||
modified: meta.modified().ok(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else if meta.is_dir() && !meta.file_type().is_symlink() && depth > 0 {
|
|
||||||
walk(&e.path(), &format!("{rel}/"), depth - 1, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let refs = self.0.join("refs");
|
|
||||||
if plain(&refs).is_ok() {
|
|
||||||
walk(&refs, "refs/", depth, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove(&self, rel: &str) -> io::Result<bool> {
|
|
||||||
let Ok(path) = self.at(rel) else {
|
|
||||||
return Ok(false);
|
|
||||||
};
|
|
||||||
match std::fs::symlink_metadata(&path) {
|
|
||||||
Ok(meta) if meta.file_type().is_file() => std::fs::remove_file(path).map(|()| true),
|
|
||||||
_ => Ok(false),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn repo(dir: &Path) -> PathBuf {
|
|
||||||
let repo = dir.join("repo.git");
|
|
||||||
std::fs::create_dir_all(repo.join("refs/heads")).unwrap();
|
|
||||||
std::fs::create_dir_all(repo.join("objects/pack")).unwrap();
|
|
||||||
std::fs::create_dir_all(repo.join("objects/info")).unwrap();
|
|
||||||
repo
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn only_the_names_git_gives_its_locks_are_locks() {
|
|
||||||
for yes in [
|
|
||||||
"HEAD.lock",
|
|
||||||
"index.lock",
|
|
||||||
"config.lock",
|
|
||||||
"packed-refs.lock",
|
|
||||||
"shallow.lock",
|
|
||||||
"refs/heads/main.lock",
|
|
||||||
"refs/heads/feature/x.lock",
|
|
||||||
"refs/tags/v1.lock",
|
|
||||||
"objects/info/commit-graph.lock",
|
|
||||||
"objects/pack/multi-pack-index.lock",
|
|
||||||
] {
|
|
||||||
assert!(is_lock(yes), "{yes}");
|
|
||||||
}
|
|
||||||
for no in [
|
|
||||||
"",
|
|
||||||
".lock",
|
|
||||||
"refs/.lock",
|
|
||||||
"refs/heads/",
|
|
||||||
"refs/heads/main",
|
|
||||||
"refs/heads/../../x.lock",
|
|
||||||
"refs//x.lock",
|
|
||||||
"refs/heads/./x.lock",
|
|
||||||
"other.lock",
|
|
||||||
"objects/pack/pack-1.pack",
|
|
||||||
"objects/other.lock",
|
|
||||||
"../index.lock",
|
|
||||||
"/etc/x.lock",
|
|
||||||
"hooks/pre-commit.lock",
|
|
||||||
"refs",
|
|
||||||
] {
|
|
||||||
assert!(!is_lock(no), "{no:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn locks_are_found_and_only_regular_files_are_removed() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let repo = repo(dir.path());
|
|
||||||
std::fs::write(repo.join("index.lock"), b"").unwrap();
|
|
||||||
std::fs::write(repo.join("refs/heads/main.lock"), b"").unwrap();
|
|
||||||
// Named like locks, but not files: neither is listed nor removed.
|
|
||||||
std::fs::create_dir(repo.join("HEAD.lock")).unwrap();
|
|
||||||
std::fs::write(dir.path().join("elsewhere"), b"").unwrap();
|
|
||||||
#[cfg(unix)]
|
|
||||||
std::os::unix::fs::symlink(dir.path().join("elsewhere"), repo.join("config.lock")).unwrap();
|
|
||||||
// Not a lock's name.
|
|
||||||
std::fs::write(repo.join("refs/heads/main"), b"").unwrap();
|
|
||||||
let handle = RepoDir::open(&repo).unwrap();
|
|
||||||
let found: Vec<String> = handle.locks().into_iter().map(|f| f.lock).collect();
|
|
||||||
assert_eq!(found, ["index.lock", "refs/heads/main.lock"]);
|
|
||||||
assert!(handle.locks().iter().all(|f| f.modified.is_some()));
|
|
||||||
assert!(handle.remove("index.lock").unwrap());
|
|
||||||
assert!(!handle.remove("index.lock").unwrap(), "already gone");
|
|
||||||
assert!(!handle.remove("HEAD.lock").unwrap(), "a folder stays");
|
|
||||||
assert!(repo.join("HEAD.lock").is_dir());
|
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
assert!(!handle.remove("config.lock").unwrap(), "a link stays");
|
|
||||||
assert!(repo.join("config.lock").is_symlink());
|
|
||||||
assert!(dir.path().join("elsewhere").exists());
|
|
||||||
}
|
|
||||||
assert!(handle.remove("refs/heads/main").is_err(), "not a lock");
|
|
||||||
assert!(repo.join("refs/heads/main").exists());
|
|
||||||
assert!(handle.remove("../elsewhere.lock").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// INVARIANT 1: a folder (or the repository's own path) swapped for a
|
|
||||||
/// link after the handle was opened sends nothing anywhere.
|
|
||||||
#[cfg(unix)]
|
|
||||||
#[test]
|
|
||||||
fn a_folder_swapped_for_a_link_after_the_handle_was_opened_touches_nothing_outside() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let outside = dir.path().join("outside");
|
|
||||||
std::fs::create_dir_all(outside.join("refs/heads")).unwrap();
|
|
||||||
for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] {
|
|
||||||
std::fs::write(outside.join(lock), b"theirs").unwrap();
|
|
||||||
}
|
|
||||||
// `refs` swapped for a link to a folder holding a lock of that name.
|
|
||||||
let repo_path = repo(dir.path());
|
|
||||||
std::fs::write(repo_path.join("refs/heads/main.lock"), b"ours").unwrap();
|
|
||||||
let handle = RepoDir::open(&repo_path).unwrap();
|
|
||||||
std::fs::rename(repo_path.join("refs"), dir.path().join("refs-moved")).unwrap();
|
|
||||||
std::os::unix::fs::symlink(outside.join("refs"), repo_path.join("refs")).unwrap();
|
|
||||||
assert!(!handle.remove("refs/heads/main.lock").unwrap());
|
|
||||||
assert!(handle.locks().is_empty(), "a link is not looked through");
|
|
||||||
assert_eq!(
|
|
||||||
std::fs::read(outside.join("refs/heads/main.lock")).unwrap(),
|
|
||||||
b"theirs"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
std::fs::read(dir.path().join("refs-moved/heads/main.lock")).unwrap(),
|
|
||||||
b"ours",
|
|
||||||
"nor was the folder it moved to touched through the link"
|
|
||||||
);
|
|
||||||
// The repository's own path swapped for a link: the handle still
|
|
||||||
// names the folder it opened (moved aside), and the link's target
|
|
||||||
// is never touched.
|
|
||||||
let second = dir.path().join("second.git");
|
|
||||||
std::fs::create_dir_all(second.join("refs")).unwrap();
|
|
||||||
std::fs::write(second.join("index.lock"), b"ours").unwrap();
|
|
||||||
let handle = RepoDir::open(&second).unwrap();
|
|
||||||
std::fs::rename(&second, dir.path().join("second-moved.git")).unwrap();
|
|
||||||
std::os::unix::fs::symlink(&outside, &second).unwrap();
|
|
||||||
assert!(handle.remove("index.lock").unwrap());
|
|
||||||
assert!(!dir.path().join("second-moved.git/index.lock").exists());
|
|
||||||
assert_eq!(
|
|
||||||
std::fs::read(outside.join("index.lock")).unwrap(),
|
|
||||||
b"theirs",
|
|
||||||
"the link's target was touched"
|
|
||||||
);
|
|
||||||
assert_eq!(std::fs::read(outside.join("HEAD.lock")).unwrap(), b"theirs");
|
|
||||||
// And a repository that is a link when the handle is opened is
|
|
||||||
// refused, with the archive's own `open_in` too.
|
|
||||||
assert!(RepoDir::open(&second).is_err());
|
|
||||||
assert!(RepoDir::open_in(dir.path(), "second.git").is_err());
|
|
||||||
assert!(RepoDir::open_in(dir.path(), "second-moved.git").is_ok());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -21,17 +21,14 @@
|
|||||||
pub mod access;
|
pub mod access;
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod backup;
|
pub mod backup;
|
||||||
pub mod backups;
|
|
||||||
pub mod blob;
|
pub mod blob;
|
||||||
pub mod cancel;
|
pub mod cancel;
|
||||||
pub mod chain;
|
pub mod chain;
|
||||||
pub mod describe;
|
pub mod describe;
|
||||||
mod drain;
|
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod exports;
|
pub mod exports;
|
||||||
pub mod form1099;
|
pub mod form1099;
|
||||||
pub mod format;
|
pub mod format;
|
||||||
pub mod git_locks;
|
|
||||||
pub mod journal;
|
pub mod journal;
|
||||||
pub mod lock;
|
pub mod lock;
|
||||||
pub mod meta;
|
pub mod meta;
|
||||||
|
|||||||
@@ -1146,6 +1146,10 @@ pub struct RestorePreview {
|
|||||||
pub exists: bool,
|
pub exists: bool,
|
||||||
/// The id of the books it holds, as they were backed up.
|
/// The id of the books it holds, as they were backed up.
|
||||||
pub origin: Option<String>,
|
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.
|
||||||
|
pub passed_over: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What [`Root::restore`] did.
|
/// What [`Root::restore`] did.
|
||||||
@@ -1166,21 +1170,22 @@ pub struct RestoreReport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Root {
|
impl Root {
|
||||||
/// Clone the backup at `source` (a git repository's address, or its
|
/// Find the backup at `source` (a destination folder, one set's own
|
||||||
/// folder: `<book>.git` in a backup folder) into a scratch folder in `books/` and prove it
|
/// folder, or a backup file), prove it whole (backup INVARIANT 3), and
|
||||||
/// whole (backup.rs INVARIANT 3); the caller holds the books lock and
|
/// build its books in a scratch folder in `books/`, with every stored
|
||||||
/// removes the folder.
|
/// file when `with_files`; the caller holds the books lock and removes
|
||||||
|
/// the folder.
|
||||||
fn fetch_backup(
|
fn fetch_backup(
|
||||||
&self,
|
&self,
|
||||||
git: &crate::backup::Git,
|
source: &Path,
|
||||||
source: &str,
|
passphrase: Option<&str>,
|
||||||
books: &Path,
|
books: &Path,
|
||||||
id: &BookId,
|
id: &BookId,
|
||||||
stop: &JobStop,
|
stop: &JobStop,
|
||||||
|
with_files: bool,
|
||||||
) -> Result<(PathBuf, crate::backup::Verified), RootError> {
|
) -> Result<(PathBuf, crate::backup::Verified), RootError> {
|
||||||
stop.at("fetch", "restored")?;
|
stop.at("fetch", "restored")?;
|
||||||
// git, and the verification's own phases and loops, look at the stop.
|
let ctx = crate::backup::Ctx::new().with_stop(stop.flag());
|
||||||
let git = git.clone().with_cancel(stop.flag());
|
|
||||||
// Anything left from one that never finished goes first: none is
|
// Anything left from one that never finished goes first: none is
|
||||||
// in progress (each holds the books lock).
|
// in progress (each holds the books lock).
|
||||||
for entry in std::fs::read_dir(books)? {
|
for entry in std::fs::read_dir(books)? {
|
||||||
@@ -1194,7 +1199,9 @@ impl Root {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let scratch = books.join(format!("{RESTORE_PREFIX}{id}-{}", std::process::id()));
|
let scratch = books.join(format!("{RESTORE_PREFIX}{id}-{}", std::process::id()));
|
||||||
match crate::backup::verify(&git, source, &scratch) {
|
let proven = crate::backup::find(source, passphrase, &ctx)
|
||||||
|
.and_then(|found| crate::backup::verify_found(&found, &scratch, with_files, &ctx));
|
||||||
|
match proven {
|
||||||
Ok(v) => Ok((scratch, v)),
|
Ok(v) => Ok((scratch, v)),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
// What the verification wrote goes with it (a stop leaves the
|
// What the verification wrote goes with it (a stop leaves the
|
||||||
@@ -1214,19 +1221,19 @@ impl Root {
|
|||||||
/// proven as [`Self::restore`] proves it, adding nothing to the root.
|
/// proven as [`Self::restore`] proves it, adding nothing to the root.
|
||||||
pub fn restore_preview(
|
pub fn restore_preview(
|
||||||
&self,
|
&self,
|
||||||
git: &crate::backup::Git,
|
source: &Path,
|
||||||
source: &str,
|
passphrase: Option<&str>,
|
||||||
id: &BookId,
|
id: &BookId,
|
||||||
) -> Result<RestorePreview, RootError> {
|
) -> Result<RestorePreview, RootError> {
|
||||||
self.restore_preview_stoppable(git, source, id, &JobStop::never())
|
self.restore_preview_stoppable(source, passphrase, id, &JobStop::never())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [`Self::restore_preview`], stopped if `stop` asks: the clone is
|
/// [`Self::restore_preview`], stopped if `stop` asks: the clone is
|
||||||
/// removed and nothing is left.
|
/// removed and nothing is left.
|
||||||
pub fn restore_preview_stoppable(
|
pub fn restore_preview_stoppable(
|
||||||
&self,
|
&self,
|
||||||
git: &crate::backup::Git,
|
source: &Path,
|
||||||
source: &str,
|
passphrase: Option<&str>,
|
||||||
id: &BookId,
|
id: &BookId,
|
||||||
stop: &JobStop,
|
stop: &JobStop,
|
||||||
) -> Result<RestorePreview, RootError> {
|
) -> Result<RestorePreview, RootError> {
|
||||||
@@ -1234,7 +1241,7 @@ impl Root {
|
|||||||
(|| {
|
(|| {
|
||||||
let _lock = self.books_lock(stop, "restored")?;
|
let _lock = self.books_lock(stop, "restored")?;
|
||||||
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
||||||
let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?;
|
let (scratch, v) = self.fetch_backup(source, passphrase, &books, id, stop, false)?;
|
||||||
let vault = scratch.join(VAULT_DIR);
|
let vault = scratch.join(VAULT_DIR);
|
||||||
let vault_files = if vault.is_dir() {
|
let vault_files = if vault.is_dir() {
|
||||||
std::fs::read_dir(&vault)
|
std::fs::read_dir(&vault)
|
||||||
@@ -1250,6 +1257,8 @@ impl Root {
|
|||||||
vault_files,
|
vault_files,
|
||||||
exists: std::fs::symlink_metadata(books.join(id.as_str())).is_ok(),
|
exists: std::fs::symlink_metadata(books.join(id.as_str())).is_ok(),
|
||||||
origin: v.book,
|
origin: v.book,
|
||||||
|
sealed: v.key.is_some(),
|
||||||
|
passed_over: v.passed_over as u64,
|
||||||
})
|
})
|
||||||
})()
|
})()
|
||||||
.map_err(|e| self.hide(e))
|
.map_err(|e| self.hide(e))
|
||||||
@@ -1264,13 +1273,20 @@ impl Root {
|
|||||||
/// first, kept whole; refused while anything holds them open.
|
/// first, kept whole; refused while anything holds them open.
|
||||||
pub fn restore(
|
pub fn restore(
|
||||||
&self,
|
&self,
|
||||||
git: &crate::backup::Git,
|
source: &Path,
|
||||||
source: &str,
|
passphrase: Option<&str>,
|
||||||
id: &BookId,
|
id: &BookId,
|
||||||
expect_head: &(u64, String),
|
expect_head: &(u64, String),
|
||||||
replace: bool,
|
replace: bool,
|
||||||
) -> Result<RestoreReport, RootError> {
|
) -> Result<RestoreReport, RootError> {
|
||||||
self.restore_stoppable(git, source, id, expect_head, replace, &JobStop::never())
|
self.restore_stoppable(
|
||||||
|
source,
|
||||||
|
passphrase,
|
||||||
|
id,
|
||||||
|
expect_head,
|
||||||
|
replace,
|
||||||
|
&JobStop::never(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [`Self::restore`], stopped if `stop` asks at any phase before the
|
/// [`Self::restore`], stopped if `stop` asks at any phase before the
|
||||||
@@ -1280,14 +1296,14 @@ impl Root {
|
|||||||
/// finishes: two renames and two directory syncs.
|
/// finishes: two renames and two directory syncs.
|
||||||
pub fn restore_stoppable(
|
pub fn restore_stoppable(
|
||||||
&self,
|
&self,
|
||||||
git: &crate::backup::Git,
|
source: &Path,
|
||||||
source: &str,
|
passphrase: Option<&str>,
|
||||||
id: &BookId,
|
id: &BookId,
|
||||||
expect_head: &(u64, String),
|
expect_head: &(u64, String),
|
||||||
replace: bool,
|
replace: bool,
|
||||||
stop: &JobStop,
|
stop: &JobStop,
|
||||||
) -> Result<RestoreReport, RootError> {
|
) -> Result<RestoreReport, RootError> {
|
||||||
self.restore_inner(git, source, id, expect_head, replace, stop)
|
self.restore_inner(source, passphrase, id, expect_head, replace, stop)
|
||||||
.map_err(|e| match e {
|
.map_err(|e| match e {
|
||||||
// The copy's checks are the adoption's: said as a restore.
|
// The copy's checks are the adoption's: said as a restore.
|
||||||
RootError::Adopt(text) => {
|
RootError::Adopt(text) => {
|
||||||
@@ -1300,8 +1316,8 @@ impl Root {
|
|||||||
|
|
||||||
fn restore_inner(
|
fn restore_inner(
|
||||||
&self,
|
&self,
|
||||||
git: &crate::backup::Git,
|
source: &Path,
|
||||||
source: &str,
|
passphrase: Option<&str>,
|
||||||
id: &BookId,
|
id: &BookId,
|
||||||
expect_head: &(u64, String),
|
expect_head: &(u64, String),
|
||||||
replace: bool,
|
replace: bool,
|
||||||
@@ -1337,7 +1353,7 @@ impl Root {
|
|||||||
};
|
};
|
||||||
stop.at("start", "restored")?;
|
stop.at("start", "restored")?;
|
||||||
let _scope = crate::cancel::scope(stop.flag());
|
let _scope = crate::cancel::scope(stop.flag());
|
||||||
let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?;
|
let (scratch, v) = self.fetch_backup(source, passphrase, &books, id, stop, true)?;
|
||||||
let staging = books.join(format!("{RESTORE_PREFIX}{id}-{}-book", std::process::id()));
|
let staging = books.join(format!("{RESTORE_PREFIX}{id}-{}-book", std::process::id()));
|
||||||
let built = (|| -> Result<RestoreReport, RootError> {
|
let built = (|| -> Result<RestoreReport, RootError> {
|
||||||
stop.at("copy", "restored")?;
|
stop.at("copy", "restored")?;
|
||||||
@@ -1377,11 +1393,12 @@ impl Root {
|
|||||||
&std::fs::read(&access)?,
|
&std::fs::read(&access)?,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
// Its backup history: the next backup carries on from it.
|
// A sealed backup keeps its key: the restored books carry on
|
||||||
std::fs::rename(
|
// backing up sealed, to the same place, with no question asked.
|
||||||
scratch.join(".git"),
|
if let Some(key) = &v.key {
|
||||||
staging.join(crate::backup::ARCHIVE_DIR),
|
key.store(&staging)
|
||||||
)?;
|
.map_err(|e| RootError::Adopt(format!("that backup can't be restored: {e}")))?;
|
||||||
|
}
|
||||||
// Whose books they were, placed with them.
|
// Whose books they were, placed with them.
|
||||||
crate::ops::prepare(&staging)?;
|
crate::ops::prepare(&staging)?;
|
||||||
write_private_file(
|
write_private_file(
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
use ledger_core::{AccountType, Currency, Money, Side};
|
use ledger_core::{AccountType, Currency, Money, Side};
|
||||||
use ledger_store::Store;
|
use ledger_store::Store;
|
||||||
use ledger_store::backups::{
|
use ledger_store::backup::{
|
||||||
BackupError, BackupKey, Ctx, Cut, Destination, find, save_file, verify_found, write_destination,
|
BackupError, BackupKey, Ctx, Cut, Destination, find, save_file, verify_found, write_destination,
|
||||||
};
|
};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
@@ -104,7 +104,7 @@ fn prove(
|
|||||||
pass: Option<&str>,
|
pass: Option<&str>,
|
||||||
root: &Path,
|
root: &Path,
|
||||||
name: &str,
|
name: &str,
|
||||||
) -> Result<ledger_store::backups::Verified, BackupError> {
|
) -> Result<ledger_store::backup::Verified, BackupError> {
|
||||||
let found = find(source, pass, &Ctx::new())?;
|
let found = find(source, pass, &Ctx::new())?;
|
||||||
verify_found(&found, &root.join(name), true, &Ctx::new())
|
verify_found(&found, &root.join(name), true, &Ctx::new())
|
||||||
}
|
}
|
||||||
@@ -1338,34 +1338,39 @@ fn books_that_changed_since_the_preview_are_not_adopted() {
|
|||||||
assert_eq!(report.source_head, now);
|
assert_eq!(report.source_head, now);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A backup of `store`'s books (in `dir`) in a folder target under
|
/// A backup of `store`'s books (in `dir`) in a folder under `home`: the
|
||||||
/// `home`: its address.
|
/// folder.
|
||||||
fn backed_up(home: &Path, dir: &Path, store: &Store) -> Option<String> {
|
fn backed_up(home: &Path, dir: &Path, store: &Store) -> std::path::PathBuf {
|
||||||
use ledger_store::backup::{self, Git, Target};
|
use ledger_store::backup::{Ctx, Cut, Destination, write_destination};
|
||||||
let git = Git::find().ok()?;
|
|
||||||
backup::commit(&git, dir, "acme", store.head()).unwrap();
|
|
||||||
let folder = home.join("disk");
|
let folder = home.join("disk");
|
||||||
std::fs::create_dir_all(&folder).unwrap();
|
std::fs::create_dir_all(&folder).unwrap();
|
||||||
let target = Target::Folder(folder);
|
let cut = Cut::take("acme", dir, store.head()).unwrap();
|
||||||
backup::push(&git, dir, "acme", &target, true).unwrap();
|
write_destination(
|
||||||
Some(target.source("acme"))
|
&Destination {
|
||||||
|
folder: folder.clone(),
|
||||||
|
key: None,
|
||||||
|
},
|
||||||
|
&cut,
|
||||||
|
true,
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
folder
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_restore_never_moves_books_something_holds() {
|
fn a_restore_never_moves_books_something_holds() {
|
||||||
use ledger_store::backup::Git;
|
|
||||||
let home = tmp("restore-held");
|
let home = tmp("restore-held");
|
||||||
let (root, _) = Root::setup(home.path(), None, None).unwrap();
|
let (root, _) = Root::setup(home.path(), None, None).unwrap();
|
||||||
let acme = id("acme");
|
let acme = id("acme");
|
||||||
let held = root.create_book(&acme, Currency::USD).unwrap();
|
let held = root.create_book(&acme, Currency::USD).unwrap();
|
||||||
let dir = root.book_dir(&acme);
|
let dir = root.book_dir(&acme);
|
||||||
let source = backed_up(home.path(), &dir, &held).expect("git is installed");
|
let source = backed_up(home.path(), &dir, &held);
|
||||||
let git = Git::find().unwrap();
|
let preview = root.restore_preview(&source, None, &acme).unwrap();
|
||||||
let preview = root.restore_preview(&git, &source, &acme).unwrap();
|
|
||||||
assert!(preview.exists);
|
assert!(preview.exists);
|
||||||
// Open (its writer lock held): refused, nothing moved.
|
// Open (its writer lock held): refused, nothing moved.
|
||||||
let e = root
|
let e = root
|
||||||
.restore(&git, &source, &acme, &preview.head, true)
|
.restore(&source, None, &acme, &preview.head, true)
|
||||||
.unwrap_err();
|
.unwrap_err();
|
||||||
assert!(e.to_string().contains("are open"), "{e}");
|
assert!(e.to_string().contains("are open"), "{e}");
|
||||||
assert!(dir.join(JOURNAL_FILE).is_file());
|
assert!(dir.join(JOURNAL_FILE).is_file());
|
||||||
@@ -1378,17 +1383,17 @@ fn a_restore_never_moves_books_something_holds() {
|
|||||||
);
|
);
|
||||||
// Not over books without --replace; nothing to replace that isn't.
|
// Not over books without --replace; nothing to replace that isn't.
|
||||||
let e = root
|
let e = root
|
||||||
.restore(&git, &source, &acme, &preview.head, false)
|
.restore(&source, None, &acme, &preview.head, false)
|
||||||
.unwrap_err();
|
.unwrap_err();
|
||||||
assert!(matches!(e, RootError::Exists(_)), "{e}");
|
assert!(matches!(e, RootError::Exists(_)), "{e}");
|
||||||
let e = root
|
let e = root
|
||||||
.restore(&git, &source, &id("nobody"), &preview.head, true)
|
.restore(&source, None, &id("nobody"), &preview.head, true)
|
||||||
.unwrap_err();
|
.unwrap_err();
|
||||||
assert!(e.to_string().contains("no books called"), "{e}");
|
assert!(e.to_string().contains("no books called"), "{e}");
|
||||||
// Let go: replaced, the old kept whole.
|
// Let go: replaced, the old kept whole.
|
||||||
drop(held);
|
drop(held);
|
||||||
let r = root
|
let r = root
|
||||||
.restore(&git, &source, &acme, &preview.head, true)
|
.restore(&source, None, &acme, &preview.head, true)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let kept = root.path().join("legacy").join(r.replaced.unwrap());
|
let kept = root.path().join("legacy").join(r.replaced.unwrap());
|
||||||
assert!(kept.join(JOURNAL_FILE).is_file());
|
assert!(kept.join(JOURNAL_FILE).is_file());
|
||||||
@@ -1831,17 +1836,16 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i
|
|||||||
// restore, over books that exist: they stay as they are.
|
// restore, over books that exist: they stay as they are.
|
||||||
let dir = root.book_dir(&id("adopted"));
|
let dir = root.book_dir(&id("adopted"));
|
||||||
let store = Store::open(&dir).unwrap();
|
let store = Store::open(&dir).unwrap();
|
||||||
let source = backed_up(home.path(), &dir, &store).expect("git is installed");
|
let source = backed_up(home.path(), &dir, &store);
|
||||||
drop(store);
|
drop(store);
|
||||||
let git = ledger_store::backup::Git::find().unwrap();
|
let preview = root.restore_preview(&source, None, &id("adopted")).unwrap();
|
||||||
let preview = root.restore_preview(&git, &source, &id("adopted")).unwrap();
|
|
||||||
let phases = ["start", "fetch", "copy", "file", "open", "verify", "place"];
|
let phases = ["start", "fetch", "copy", "file", "open", "verify", "place"];
|
||||||
for phase in phases {
|
for phase in phases {
|
||||||
let before = root_files(&root);
|
let before = root_files(&root);
|
||||||
let (stop, seen) = stopping_at(phase);
|
let (stop, seen) = stopping_at(phase);
|
||||||
let e = refused(root.restore_stoppable(
|
let e = refused(root.restore_stoppable(
|
||||||
&git,
|
|
||||||
&source,
|
&source,
|
||||||
|
None,
|
||||||
&id("adopted"),
|
&id("adopted"),
|
||||||
&preview.head,
|
&preview.head,
|
||||||
true,
|
true,
|
||||||
@@ -1858,7 +1862,7 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i
|
|||||||
// The preview too: stopped, nothing left of its clone.
|
// The preview too: stopped, nothing left of its clone.
|
||||||
let before = root_files(&root);
|
let before = root_files(&root);
|
||||||
let (stop, _) = stopping_at("fetch");
|
let (stop, _) = stopping_at("fetch");
|
||||||
let e = refused(root.restore_preview_stoppable(&git, &source, &id("adopted"), &stop));
|
let e = refused(root.restore_preview_stoppable(&source, None, &id("adopted"), &stop));
|
||||||
assert!(matches!(e, RootError::Stopped(_)), "{e:?}");
|
assert!(matches!(e, RootError::Stopped(_)), "{e:?}");
|
||||||
assert_eq!(root_files(&root), before);
|
assert_eq!(root_files(&root), before);
|
||||||
// Never stopped, a restore asks `place` last and goes through.
|
// Never stopped, a restore asks `place` last and goes through.
|
||||||
@@ -1868,7 +1872,7 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i
|
|||||||
std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string()))
|
std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string()))
|
||||||
});
|
});
|
||||||
let r = root
|
let r = root
|
||||||
.restore_stoppable(&git, &source, &id("adopted"), &preview.head, true, &stop)
|
.restore_stoppable(&source, None, &id("adopted"), &preview.head, true, &stop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(r.replaced.is_some());
|
assert!(r.replaced.is_some());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|||||||
Reference in new issue
Block a user