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

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

No files matched your search

-2
View File
@@ -75,8 +75,6 @@ workspace = true
# program: `just package-linux`. Paths are relative to the workspace root.
[package.metadata.generate-rpm]
name = "wanderbooks"
# Backups run the system's git (WB-pkg-4): dnf fetches it.
requires = { git = "*" }
summary = "Double-entry bookkeeping your agent keeps and you can read"
license = "MIT OR Apache-2.0"
url = "https://wanderbooks.ai"
+47 -2
View File
@@ -299,7 +299,41 @@ impl ledger_gui::owner::Owner for ViewerOwner {
}
fn back_up_now(&self, book: &str) -> Result<Vec<String>, String> {
ledger_host::commands::back_up_now(&self.common, book, false)
ledger_host::commands::back_up_now(&self.common, book, false, false)
}
fn start_new_backup_set(&self, book: &str) -> Result<Vec<String>, String> {
ledger_host::commands::back_up_now(&self.common, book, false, true)
}
fn backup_state(&self, book: &str) -> Result<ledger_gui::owner::BackupState, String> {
let s = ledger_host::commands::backup_standing(&self.common, book)?;
Ok(ledger_gui::owner::BackupState {
lines: ledger_host::commands::backup_words(&s),
folder: s.folder.clone(),
sealed: s.sealed,
ahead: s.error_kind.as_deref() == Some("ahead"),
})
}
fn set_up_backups(
&self,
book: &str,
folder: Option<String>,
passphrase: Option<ledger_gui::owner::Secret>,
remove_passphrase: bool,
) -> Result<Vec<String>, String> {
ledger_host::commands::backup_setup(
&self.common,
book,
folder,
passphrase.map(|p| p.0.clone()),
remove_passphrase,
)
}
fn save_backup(&self, book: &str, file: &str) -> Result<Vec<String>, String> {
ledger_host::commands::backup_save(&self.common, book, file)
}
fn plan_restore(
@@ -307,10 +341,17 @@ impl ledger_gui::owner::Owner for ViewerOwner {
source: &str,
id: Option<String>,
replace: bool,
passphrase: Option<ledger_gui::owner::Secret>,
) -> 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 {
source: p.source,
passphrase: p
.passphrase
.as_ref()
.map(|p| ledger_gui::owner::Secret(p.0.clone())),
id: p.id,
replace: p.replace,
head: p.head,
@@ -323,6 +364,10 @@ impl ledger_gui::owner::Owner for ViewerOwner {
&self.common,
&ledger_host::commands::RestorePlan {
source: plan.source.clone(),
passphrase: plan
.passphrase
.as_ref()
.map(|p| ledger_mcp::admin::Passphrase(p.0.clone())),
id: plan.id.clone(),
replace: plan.replace,
head: plan.head.clone(),
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+797
View File
@@ -0,0 +1,797 @@
//! What a person is told when their backups are in trouble (WB-backup-13 to
//! WB-backup-16): the key file lost from a sealed destination, books behind
//! the folder's (a new set at their request), a newest backup that is
//! damaged while an older one is whole, and a folder a sync service keeps.
#![cfg(unix)]
#![allow(dead_code)]
use ledger_mcp::admin::{self, Request, Response};
use ledger_store::backup::{Ctx, find, verify_found};
use ledger_store::root::{BookId, Root};
use rmcp::ServiceExt;
use rmcp::model::{CallToolRequestParams, ClientConfig};
use rmcp::service::{RoleClient, RunningService};
use rmcp::transport::StreamableHttpClientTransport;
use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
use serde_json::{Value, json};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
type Client = RunningService<RoleClient, ClientConfig>;
/// A home with a data root made by `wanderbooks setup`, and a place for
/// the backups beside it.
struct Home {
dir: tempfile::TempDir,
}
impl Home {
fn new(tag: &str) -> Self {
let dir = tempfile::Builder::new()
.prefix(&format!("wb-bk-{tag}-"))
.tempdir()
.unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_wanderbooks"))
.args(["setup", "--home"])
.arg(dir.path())
.env_remove("XDG_DATA_HOME")
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
Self { dir }
}
fn root(&self) -> PathBuf {
ledger_store::root::default_root(self.dir.path())
}
fn book_dir(&self, book: &str) -> PathBuf {
Root::open(&self.root())
.unwrap()
.book_dir(&BookId::parse(book).unwrap())
}
fn admin(&self, request: Request) -> Response {
admin::call(&self.root().join("run/admin.sock"), request).unwrap()
}
fn create(&self, id: &str) {
match self.admin(Request::Create {
id: id.into(),
currency: "USD".into(),
}) {
Response::Created { problem: None, .. } => {}
other => panic!("{other:?}"),
}
}
fn token(&self, book: &str, scopes: &[&str]) -> String {
match self.admin(Request::TokenCreate {
book: book.into(),
name: format!("test-{}", scopes.join("-")),
scopes: scopes.iter().map(|s| s.to_string()).collect(),
replace: true,
}) {
Response::TokenCreated { text, .. } => text.0,
other => panic!("{other:?}"),
}
}
/// A place outside the data root (a folder on "another disk").
fn outside(&self, name: &str) -> PathBuf {
let p = self.dir.path().join("elsewhere").join(name);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
p
}
}
/// A running `wanderbooks server`, ended (kill) when dropped.
struct Server {
child: Child,
}
impl Server {
/// Start one, backing up after `quiet` of no writing (a drill first
/// looked for after the server's own wait: a minute, past any test).
fn start(home: &Home, quiet: Duration) -> Self {
Self::start_with(home, quiet, None)
}
/// [`Self::start`], a drill first looked for `drill_first` after books
/// are seen open.
fn start_with(home: &Home, quiet: Duration, drill_first: Option<Duration>) -> Self {
let mut command = Command::new(env!("CARGO_BIN_EXE_wanderbooks"));
command
.arg("server")
.arg("--root")
.arg(home.root())
.arg("--backup-quiet")
.arg(quiet.as_millis().to_string());
if let Some(d) = drill_first {
command.arg("--drill-first").arg(d.as_millis().to_string());
}
let mut child = command
.env_clear()
.env("PATH", "/usr/bin:/bin")
.env("HOME", home.dir.path())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut line = String::new();
BufReader::new(child.stdout.take().unwrap())
.read_line(&mut line)
.unwrap();
assert_eq!(line, "ready\n", "the server didn't say ready");
Self { child }
}
/// Close it as the host does (stdin ends) and wait for it to exit.
fn close(mut self) -> std::process::ExitStatus {
drop(self.child.stdin.take());
let deadline = Instant::now() + Duration::from_secs(60);
loop {
if let Some(status) = self.child.try_wait().unwrap() {
return status;
}
assert!(Instant::now() < deadline, "the server didn't close");
std::thread::sleep(Duration::from_millis(20));
}
}
}
impl Drop for Server {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// A session with one book, and what it takes to send the book a file as
/// an agent does (D-46: a file comes only by upload).
struct Agent {
client: Client,
http: reqwest::Client,
book: String,
token: String,
}
impl std::ops::Deref for Agent {
type Target = Client;
fn deref(&self) -> &Client {
&self.client
}
}
impl Agent {
/// Upload `bytes` as `wanderbooks upload` does: books.begin_upload,
/// then the bytes PUT with this session's token. The upload_id.
async fn upload(&self, bytes: &[u8], file_name: &str, mime_type: &str) -> String {
let begun = call(
self,
"books.begin_upload",
json!({"sha256": ledger_store::journal::sha256_hex(bytes), "size": bytes.len(),
"mime_type": mime_type, "file_name": file_name, "purpose": "receipt"}),
)
.await
.unwrap();
let id = begun["upload_id"].as_str().unwrap().to_string();
let r = self
.http
.put(format!("http://localhost/b/{}/u/{id}", self.book))
.bearer_auth(&self.token)
.body(bytes.to_vec())
.send()
.await
.unwrap();
assert_eq!(r.status().as_u16(), 200);
id
}
}
async fn connect(home: &Home, book: &str, token: String) -> Agent {
// The short path is good in this process only, while it lives: kept.
let short = ledger_store::root::SocketPath::new(&home.root().join("run"), "mcp.sock").unwrap();
let path = short.path().to_path_buf();
std::mem::forget(short);
let http = reqwest::Client::builder()
.unix_socket(path)
.build()
.unwrap();
let config =
StreamableHttpClientTransportConfig::with_uri(format!("http://localhost/b/{book}/mcp"))
.auth_header(token.clone());
let client = ClientConfig::default()
.serve(StreamableHttpClientTransport::with_client(
http.clone(),
config,
))
.await
.unwrap();
Agent {
client,
http,
book: book.to_string(),
token,
}
}
/// Call a tool: Ok(structured result) or Err(the error text).
/// Call a tool the way an agent confirms (plan P4, D-50): a call with
/// `confirmed: true` and no `preview` is made first without `confirmed`,
/// then with the `preview` it returned. A refused preview is the answer.
async fn call(c: &Client, tool: &str, mut args: Value) -> Result<Value, String> {
if args.get("confirmed") == Some(&json!(true)) && args.get("preview").is_none() {
let mut first = args.clone();
first["confirmed"] = json!(false);
let seen = call_once(c, tool, first).await?;
if let Some(digest) = seen.get("preview").and_then(Value::as_str) {
args["preview"] = json!(digest);
}
}
call_once(c, tool, args).await
}
async fn call_once(c: &Client, tool: &str, args: Value) -> Result<Value, String> {
let mut args = args.as_object().cloned().unwrap_or_default();
// The key every write call carries (D-88).
static NEXT_KEY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
args.entry("request_key").or_insert_with(|| {
let n = NEXT_KEY.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
json!(format!("backups-key-{}-{n}", std::process::id()))
});
let r = tokio::time::timeout(
Duration::from_secs(60),
c.call_tool(CallToolRequestParams::new(tool.to_string()).with_arguments(args)),
)
.await
.map_err(|_| "no answer".to_string())?
.map_err(|e| format!("protocol: {e}"))?;
let text = r
.content
.iter()
.find_map(|c| c.as_text().map(|t| t.text.clone()))
.unwrap_or_default();
if r.is_error == Some(true) {
Err(text)
} else {
Ok(r.structured_content
.unwrap_or_else(|| serde_json::from_str(&text).unwrap_or(Value::String(text))))
}
}
async fn head(c: &Client) -> u64 {
call(c, "books.start", json!({})).await.unwrap()["head"]["seq"]
.as_u64()
.unwrap()
}
/// Name the backup folder in the book's settings.
async fn set_folder(c: &Client, folder: &Path) {
call(
c,
"books.set_setting",
json!({"changes": [{"key": "backup.folder", "value": folder.display().to_string()}],
"decided_by": "Test Owner", "note": "Backups."}),
)
.await
.unwrap();
}
/// Draft, receipt and post one $n entry.
async fn post_one(c: &Agent, n: u64) {
for (code, name, ty) in [("1000", "Cash", "asset"), ("6000", "Supplies", "expense")] {
let _ = call(
c,
"books.add_account",
json!({"code": code, "name": name, "account_type": ty}),
)
.await;
}
let e = call(
c,
"books.draft_entry",
json!({"date": "2026-03-01", "description": format!("entry {n}")}),
)
.await
.unwrap();
let id = e["entry_id"].as_u64().unwrap();
for (account, side) in [("6000", "debit"), ("1000", "credit")] {
call(
c,
"books.add_line",
json!({"entry_id": id, "account": account, "side": side, "amount": format!("{n}.00")}),
)
.await
.unwrap();
}
// Bytes of each entry's own: the same bytes stored already would be
// named for linking, not uploaded again.
let upload = c
.upload(
format!("receipt {n}").as_bytes(),
&format!("r{n}.txt"),
"text/plain",
)
.await;
call(
c,
"books.attach_receipt",
json!({"entry_id": id, "upload_id": upload}),
)
.await
.unwrap();
call(
c,
"books.post_entry",
json!({"entry_id": id, "confirmed": true, "no_party_reason": "test"}),
)
.await
.unwrap();
}
/// Long enough for the server's backup loop (which looks every 2 s) to
/// have seen books just made, before they name any target: what it does
/// on first seeing them (a backup, a drill) is then done.
async fn settle() {
tokio::time::sleep(Duration::from_millis(4500)).await;
}
/// Wait until every target holds the books' head (or `within` passes).
async fn backed_up(c: &Client, within: Duration) -> Value {
let deadline = Instant::now() + within;
loop {
let s = call(c, "books.backup", json!({})).await.unwrap();
let head = s["head_seq"].as_u64().unwrap();
let targets = s["targets"].as_array().unwrap();
if !targets.is_empty()
&& targets
.iter()
.all(|t| t["through_seq"].as_u64() == Some(head))
{
return s;
}
assert!(Instant::now() < deadline, "not backed up in time: {s}");
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
/// Prove the backup at `source` (a destination folder, a set's folder, or a
/// file) whole; its head.
fn proven(home: &Home, source: &Path, tag: &str) -> (u64, String) {
let scratch = home.outside(&format!("scratch-{tag}"));
let found = find(source, None, &Ctx::new()).unwrap_or_else(|e| panic!("{tag}: {e}"));
verify_found(&found, &scratch, &Ctx::new())
.unwrap_or_else(|e| panic!("{tag}: {e}"))
.head
}
fn live_head(home: &Home, book: &str) -> (u64, String) {
let s = ledger_store::Snapshot::load(&home.book_dir(book)).unwrap();
(s.journal_seq(), s.head_hash().to_string())
}
const ALL: [&str; 4] = ["read", "write", "post", "admin"];
/// Restore `source` as `id`: the preview, then (if it was one) the
/// restore confirmed against its head. Ok(what was restored) or Err(why).
fn restore(home: &Home, id: &str, source: &Path, replace: bool) -> Result<admin::Restored, String> {
restore_with(home, id, source, replace, None)
}
fn restore_with(
home: &Home,
id: &str,
source: &Path,
replace: bool,
passphrase: Option<&str>,
) -> Result<admin::Restored, String> {
let request = |expect_head: Option<(u64, String)>| Request::Restore {
id: id.into(),
source: source.display().to_string(),
replace,
confirmed: expect_head.is_some(),
expect_head,
passphrase: passphrase.map(|p| admin::Passphrase(p.to_string())),
};
let preview = match home.admin(request(None)) {
Response::RestorePreview(p) => p,
Response::Refused(why) => return Err(why),
other => panic!("{other:?}"),
};
match home.admin(request(Some(preview.head.clone()))) {
Response::Restored(r) => {
assert_eq!(r.head, preview.head);
assert_eq!(r.problem, None);
Ok(r)
}
Response::Refused(why) => Err(why),
other => panic!("{other:?}"),
}
}
fn books_held(home: &Home) -> Vec<String> {
match home.admin(Request::List) {
Response::Books(b) => b.into_iter().map(|b| b.id).collect(),
other => panic!("{other:?}"),
}
}
/// What the books say, for comparing two that should be the same.
async fn figures(c: &Client) -> Value {
json!({
"tb": call(c, "books.trial_balance", json!({})).await.unwrap(),
"receipts": call(c, "books.list_receipts", json!({})).await.unwrap(),
"settings": call(c, "books.settings", json!({})).await.unwrap()["settings"].clone(),
})
}
/// A backup of acme (two entries, a receipt each) in the folder.
async fn backed_up_acme(home: &Home) -> (PathBuf, Value) {
settle().await;
let folder = home.outside("disk");
std::fs::create_dir_all(&folder).unwrap();
let c = connect(home, "acme", home.token("acme", &ALL)).await;
set_folder(&c, &folder).await;
post_one(&c, 4).await;
post_one(&c, 5).await;
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
(folder, figures(&c).await)
}
/// The files under `dir` whose path (below it) starts with `prefix`.
fn files_below(dir: &Path, prefix: &str) -> Vec<PathBuf> {
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
for e in std::fs::read_dir(dir).unwrap() {
let p = e.unwrap().path();
if p.is_dir() {
walk(&p, out);
} else {
out.push(p);
}
}
}
let mut all = Vec::new();
walk(dir, &mut all);
all.retain(|p| {
p.strip_prefix(dir)
.unwrap()
.to_string_lossy()
.replace('\\', "/")
.starts_with(prefix)
});
all.sort();
all
}
fn copy_dir(from: &Path, to: &Path) {
std::fs::create_dir_all(to).unwrap();
for e in std::fs::read_dir(from).unwrap() {
let e = e.unwrap();
let target = to.join(e.file_name());
if e.path().is_dir() {
copy_dir(&e.path(), &target);
} else {
std::fs::copy(e.path(), target).unwrap();
}
}
}
/// Wait until the folder's backup has been drilled.
async fn drilled(c: &Client) -> Value {
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let s = call(c, "books.backup", json!({})).await.unwrap();
let targets = s["targets"].as_array().unwrap();
if !targets.is_empty() && targets.iter().all(|t| t["last_drill_at"].is_string()) {
return s;
}
assert!(Instant::now() < deadline, "no drill: {s}");
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
const PASS: &str = "correct horse battery staple";
fn said(r: Response) -> String {
match r {
Response::Said { lines } => lines.join(" "),
other => panic!("{other:?}"),
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_lost_key_file_never_makes_backups_plain() {
let home = Home::new("lost-key");
let server = Server::start(&home, Duration::from_secs(3600));
home.create("acme");
let folder = home.outside("disk");
std::fs::create_dir_all(&folder).unwrap();
said(home.admin(Request::BackupSetup {
id: "acme".into(),
folder: Some(folder.display().to_string()),
passphrase: Some(admin::Passphrase(PASS.into())),
remove_passphrase: false,
}));
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
post_one(&c, 1).await;
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
assert_eq!(s["targets"][0]["sealed"], true);
// The key file is lost from this computer (a restored home folder, a
// cleaned `local/`).
let key = home.book_dir("acme").join("local").join("backup-key.json");
std::fs::remove_file(&key).unwrap();
let before: Vec<_> = files_below(&folder, "");
post_one(&c, 2).await;
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
let t = &s["targets"][0];
// Told in words, and nothing was written: no plain copy of the books.
let why = t["last_error"].as_str().unwrap_or_default();
assert!(why.contains("no longer has its key"), "{s}");
assert!(why.contains("remove the passphrase"), "{s}");
assert_eq!(t["error_kind"], "key_missing", "{s}");
assert_eq!(files_below(&folder, ""), before, "nothing was written");
assert!(!folder.join("wanderbooks-acme").exists());
// The words a person reads in the window.
let standing = match home.admin(Request::BackupStatus { id: "acme".into() }) {
Response::BackupStatus(st) => st,
other => panic!("{other:?}"),
};
let words = ledger_host::commands::backup_words(&standing).join(" | ");
assert!(words.contains("no longer has its key"), "{words}");
assert!(
words.contains("Enter the backup passphrase again"),
"{words}"
);
// Even with the backup record gone (set aside as damaged at the next
// open), the folder itself says its backups are sealed.
drop(c);
assert!(server.close().success());
std::fs::write(
home.book_dir("acme").join("ops").join("backup.jsonl"),
b"not a record\n",
)
.unwrap();
let server = Server::start(&home, Duration::from_secs(3600));
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
let s = call(&c, "books.back_up_now", json!({"new_disk": true}))
.await
.unwrap();
assert_eq!(s["targets"][0]["error_kind"], "key_missing", "{s}");
assert!(!folder.join("wanderbooks-acme").exists());
// Plain is written only after an explicit "remove the passphrase".
said(home.admin(Request::BackupSetup {
id: "acme".into(),
folder: None,
passphrase: None,
remove_passphrase: true,
}));
let s = call(&c, "books.back_up_now", json!({"new_disk": true}))
.await
.unwrap();
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
assert_eq!(s["targets"][0]["sealed"], false);
assert!(folder.join("wanderbooks-acme").join("manifests").is_dir());
drop(c);
assert!(server.close().success());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn books_restored_from_an_older_backup_are_ahead_and_a_new_set_begins_at_their_request() {
// Books A back up twice to a folder; books C are restored from a copy of
// the folder as it was after the first, and then pointed at the folder
// that holds more.
let a = Home::new("ahead-a");
let server_a = Server::start(&a, Duration::from_secs(3600));
a.create("acme");
settle().await;
let folder = a.outside("disk");
std::fs::create_dir_all(&folder).unwrap();
let ca = connect(&a, "acme", a.token("acme", &ALL)).await;
set_folder(&ca, &folder).await;
post_one(&ca, 1).await;
let s = call(&ca, "books.back_up_now", json!({})).await.unwrap();
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
let older = a.outside("older");
copy_dir(&folder, &older);
post_one(&ca, 2).await;
let s = call(&ca, "books.back_up_now", json!({})).await.unwrap();
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
let longer = live_head(&a, "acme");
drop(ca);
assert!(server_a.close().success());
let c_home = Home::new("ahead-c");
let server_c = Server::start(&c_home, Duration::from_secs(3600));
let restored = restore(&c_home, "acme", &older.join("wanderbooks-acme"), false).unwrap();
assert!(restored.head.0 < longer.0);
let cc = connect(&c_home, "acme", c_home.token("acme", &ALL)).await;
set_folder(&cc, &folder).await;
let before = files_below(&folder, "");
let bytes: Vec<Vec<u8>> = before.iter().map(|p| std::fs::read(p).unwrap()).collect();
let s = call(&cc, "books.back_up_now", json!({})).await.unwrap();
let t = &s["targets"][0];
// Told as ahead (not diverged), in words that say what to do.
assert_eq!(t["error_kind"], "ahead", "{s}");
let why = t["last_error"].as_str().unwrap();
assert!(why.contains("a longer history of these books"), "{why}");
assert!(why.contains("start a new backup set"), "{why}");
assert_eq!(files_below(&folder, ""), before, "nothing was written");
let standing = match c_home.admin(Request::BackupStatus { id: "acme".into() }) {
Response::BackupStatus(st) => st,
other => panic!("{other:?}"),
};
let words = ledger_host::commands::backup_words(&standing).join(" | ");
assert!(words.contains("start a new backup set"), "{words}");
// At the person's request: a new set beside the old, which is
// untouched; and the backups go on there.
match c_home.admin(Request::BackUpNewSet { id: "acme".into() }) {
Response::BackedUp { targets, .. } => {
assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}");
}
other => panic!("{other:?}"),
}
assert!(folder.join("wanderbooks-acme.2").join("manifests").is_dir());
for (p, b) in before.iter().zip(&bytes) {
assert_eq!(&std::fs::read(p).unwrap(), b, "{}", p.display());
}
post_one(&cc, 9).await;
let s = call(&cc, "books.back_up_now", json!({})).await.unwrap();
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
assert_eq!(s["targets"][0]["error_kind"], Value::Null, "{s}");
assert_eq!(
proven(&c_home, &folder.join("wanderbooks-acme.2"), "new").0,
live_head(&c_home, "acme").0
);
// The old set, still whole, still holds the longer history.
assert_eq!(
proven(&c_home, &folder.join("wanderbooks-acme"), "old"),
longer
);
drop(cc);
assert!(server_c.close().success());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_drill_that_finds_only_an_older_backup_is_a_failure_in_words_and_never_ok() {
let home = Home::new("older-only");
let server = Server::start(&home, Duration::from_secs(3600));
home.create("acme");
let (folder, _) = backed_up_acme(&home).await;
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
post_one(&c, 6).await;
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
drop(c);
assert!(server.close().success());
// The newest backup's own segment is damaged after the fact; the one
// before it is whole.
let set = folder.join("wanderbooks-acme");
let newest = files_below(&set, "manifests/").pop().unwrap();
let text = std::fs::read_to_string(&newest).unwrap();
let m: Value = serde_json::from_str(text.lines().next().unwrap()).unwrap();
// Whatever the newest manifest itself adds: a journal, access or index
// segment (a manifest names only what is new).
let seg = ["journal", "access", "files"]
.iter()
.find_map(|k| m[*k]["segments"].as_array()?.last().cloned())
.expect("the newest manifest adds a segment");
let seg = set.join(seg["file"].as_str().unwrap());
let mut b = std::fs::read(&seg).unwrap();
let mid = b.len() / 2;
b[mid] ^= 1;
std::fs::write(&seg, b).unwrap();
let server = Server::start_with(
&home,
Duration::from_secs(3600),
Some(Duration::from_millis(300)),
);
let c = connect(&home, "acme", home.token("acme", &["read", "admin"])).await;
let s = drilled(&c).await;
let t = &s["targets"][0];
let why = t["drill_error"].as_str().unwrap_or_default();
assert!(why.contains("the newest backup"), "{s}");
assert!(why.contains("is damaged; an older one from"), "{s}");
assert_eq!(t["error_kind"], "newest_damaged", "{s}");
let standing = match home.admin(Request::BackupStatus { id: "acme".into() }) {
Response::BackupStatus(st) => st,
other => panic!("{other:?}"),
};
let words = ledger_host::commands::backup_words(&standing).join(" | ");
assert!(words.contains("failed"), "{words}");
assert!(words.contains("older books"), "{words}");
assert!(!words.contains("Proven restorable"), "{words}");
// A restore from the folder says so before anything else, with both
// dates and how many backups it passes over. (The books' own next
// backup would find the damage and write the piece again, so the
// damage is made again, after the books are closed.)
drop(c);
assert!(server.close().success());
let newest = files_below(&set, "manifests/").pop().unwrap();
let text = std::fs::read_to_string(&newest).unwrap();
let m: Value = serde_json::from_str(text.lines().next().unwrap()).unwrap();
let seg = ["journal", "access", "files"]
.iter()
.find_map(|k| m[*k]["segments"].as_array()?.last().cloned())
.expect("the newest manifest adds a segment");
let seg = set.join(seg["file"].as_str().unwrap());
let mut b = std::fs::read(&seg).unwrap();
let mid = b.len() / 2;
b[mid] ^= 1;
std::fs::write(&seg, b).unwrap();
let other = Home::new("older-only-new");
let server = Server::start(&other, Duration::from_secs(3600));
match other.admin(Request::Restore {
id: "acme".into(),
source: folder.display().to_string(),
replace: false,
confirmed: false,
expect_head: None,
passphrase: None,
}) {
Response::RestorePreview(p) => {
assert!(p.passed_over >= 1, "{p:?}");
assert!(p.written.is_some() && p.newest_written.is_some(), "{p:?}");
let words = ledger_host::commands::older_backup_words(&p);
assert!(words.starts_with("NOT THE NEWEST BACKUP"), "{words}");
assert!(words.contains("passes over "), "{words}");
assert!(words.contains(" newer backup"), "{words}");
assert!(words.contains("This backup is from"), "{words}");
assert!(
words.contains("the newest in the folder is from"),
"{words}"
);
}
other => panic!("{other:?}"),
}
assert!(server.close().success());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_folder_a_sync_service_keeps_is_said_in_plain_words_at_set_up() {
let home = Home::new("sync");
let server = Server::start(&home, Duration::from_secs(3600));
home.create("acme");
let dropbox = home.outside("Dropbox/Backups");
std::fs::create_dir_all(&dropbox).unwrap();
let words = said(home.admin(Request::BackupSetup {
id: "acme".into(),
folder: Some(dropbox.display().to_string()),
passphrase: None,
remove_passphrase: false,
}));
assert!(words.contains("kept in sync by Dropbox"), "{words}");
assert!(words.contains("one computer only"), "{words}");
assert!(words.contains("available offline"), "{words}");
assert!(words.contains("a folder of its own"), "{words}");
// A folder no service is known to keep still gets the general words.
let plain = home.outside("a-usb-stick");
std::fs::create_dir_all(&plain).unwrap();
let words = said(home.admin(Request::BackupSetup {
id: "acme".into(),
folder: Some(plain.display().to_string()),
passphrase: None,
remove_passphrase: false,
}));
assert!(
words.contains("If this folder is kept in sync by a service"),
"{words}"
);
assert!(words.contains("one computer only"), "{words}");
// And the window shows the same, under the status.
let standing = match home.admin(Request::BackupStatus { id: "acme".into() }) {
Response::BackupStatus(st) => st,
other => panic!("{other:?}"),
};
let lines = ledger_host::commands::backup_words(&standing).join(" | ");
assert!(lines.contains("one computer only"), "{lines}");
assert!(server.close().success());
}
+111 -601
View File
@@ -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
/// is closed and opened again, over and over. Afterwards both journals are
/// 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
// 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.
// 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(
&home,
&[("WANDERBOOKS_GIT_TIMINGS", timings.as_path())],
&[],
&[
"--timers",
"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 took = began.elapsed();
eprintln!("cycle {cycle}: the close took {took:?}");
if closed != CloseOutcome::Closed || took > Duration::from_secs(10) {
say_git_timings(&timings);
}
assert_eq!(
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());
}
/// A stand-in `git` for the server's PATH: it runs the real one, unless
/// the test has said otherwise with a file beside it: `stall` (it waits,
/// recording itself in `stalled`, until the file is gone, then in
/// `resumed`), which is how a backup is made slow.
#[cfg(unix)]
fn shim_git(home: &Home) -> PathBuf {
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
/// The test knob that holds a backup at each phase, as a slow disk would:
/// while this file is in the book's `ops/` (and the server was given
/// `--slow-steps`), a backup waits until the stop it runs under is asked
/// for. Each wait is a line of [`reached`].
fn stall_file(home: &Home, id: &str) -> PathBuf {
home.book_dir(id).join("ops").join("slow-backup")
}
/// Whether process `pid` is still there.
#[cfg(unix)]
fn alive(pid: u32) -> bool {
// `ps` on Linux and macOS alike (there is no /proc on macOS, where a
// test of "is it gone" would pass whatever the server had done): its
// state is empty for a process that isn't there, and starts with Z for
// 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')
/// How many times a backup of `id` has reached a phase and waited.
fn reached(home: &Home, id: &str) -> usize {
std::fs::read_to_string(home.book_dir(id).join("ops").join("slow-backup-reached"))
.unwrap_or_default()
.lines()
.count()
}
/// The server, with the stand-in git first on its PATH.
#[cfg(unix)]
fn server_with_shim(home: &Home, shim: &std::path::Path, args: &[&str]) -> Server {
let path = std::env::join_paths([
shim,
std::path::Path::new("/usr/bin"),
std::path::Path::new("/bin"),
])
.unwrap();
let path: PathBuf = path.into();
Server::start_full(home, &[("PATH", path.as_path())], args)
/// The folder a backup of `id` to `disk` lives in, proven whole: its head.
fn proven_head(home: &Home, disk: &std::path::Path, tag: &str) -> (u64, String) {
use ledger_store::backup::{Ctx, find, verify_found};
let scratch = home.dir.path().join(format!("scratch-{tag}"));
let found = find(disk, None, &Ctx::new()).unwrap_or_else(|e| panic!("{tag}: {e}"));
verify_found(&found, &scratch, &Ctx::new())
.unwrap_or_else(|e| panic!("{tag}: {e}"))
.head
}
/// A book with a backup target whose backup is slow: the close is not
/// answered while the backup's work runs. Its bound lapses, git is
/// stopped (with all it started), the close waits for that to be done,
/// and says the backup wasn't whole. Nothing of the backup runs after the
/// answer, though the stall is lifted: a git left running would go on.
#[cfg(unix)]
/// A book with a backup folder whose backup is slow: the close is not
/// answered while the backup's work runs. Its bound lapses, the copy is
/// stopped at its next piece, the close waits for that to be done, and
/// says the backup wasn't whole. The folder still proves whole at the
/// backup before, and nothing of the backup runs after the answer, though
/// the stall is lifted: a copy left running would go on.
#[test]
fn a_close_is_not_answered_while_its_backup_still_runs() {
let home = Home::new("close-slow-backup");
let shim = shim_git(&home);
let server = server_with_shim(
let server = Server::start_with(
&home,
&shim,
&[
"--close-backup",
"1200",
@@ -1255,6 +1182,8 @@ fn a_close_is_not_answered_while_its_backup_still_runs() {
"3600000",
"--timers",
"20",
"--slow-steps",
"600000",
],
);
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);
w.initialize("owner");
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");
w.end();
// From here every git waits.
std::fs::write(shim.join("stall"), b"").unwrap();
// From here every backup waits.
std::fs::write(stall_file(&home, A), b"").unwrap();
let started = std::time::Instant::now();
let outcome = close_book(&home, A);
let took = started.elapsed();
@@ -1282,36 +1220,32 @@ fn a_close_is_not_answered_while_its_backup_still_runs() {
}
other => panic!("a stopped backup was answered as {other:?}"),
}
// Answered: the git that was stalled is gone, with what it started.
let stalled: Vec<u32> = std::fs::read_to_string(shim.join("stalled"))
.unwrap_or_default()
.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"
);
}
assert!(reached(&home, A) > 0, "the backup never reached a phase");
// The folder proves whole at the backup before.
assert_eq!(proven_head(&home, &disk, "after"), kept);
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.
std::fs::remove_file(shim.join("stall")).unwrap();
std::fs::remove_file(stall_file(&home, A)).unwrap();
stands_still(
&home,
A,
Duration::from_millis(500),
"after the close was answered",
);
assert!(
!shim.join("resumed").exists(),
"a git went on after the close was answered"
);
// (The test's own stall file went with the lift.)
let changed = |before: &BTreeMap<String, (u64, String)>,
now: &BTreeMap<String, (u64, String)>| {
moved(before, now)
.into_iter()
.filter(|m| !m.contains("slow-backup"))
.collect::<Vec<_>>()
};
assert_eq!(
moved(&at_close, &tree_of(&home.book_dir(A))),
changed(&at_close, &tree_of(&home.book_dir(A))),
Vec::<String>::new()
);
assert_eq!(changed(&in_folder, &tree_of(&disk)), Vec::<String>::new());
// Opened again, the book's backup record is a whole chain, and it
// backs up (nothing of the old backups is in its way).
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
@@ -1331,23 +1265,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,
/// quickly, and says so: never a plain "closed" for a backup that wasn't
/// made; and nothing runs after.
#[cfg(unix)]
#[test]
fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() {
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
// first look is at the server's start, before any book is made here. A
// timer's backup that a close hurried could have its git miss the
// 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"],
);
// first look is at the server's start, before any book is made here.
let server = Server::start_with(&home, &["--backup-quiet", "3600000", "--timers", "3600000"]);
home.create(A, "USD");
let unplugged = home.dir.path().join("elsewhere").join("unplugged");
std::fs::create_dir_all(unplugged.parent().unwrap()).unwrap();
@@ -1369,10 +1292,6 @@ fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() {
}
assert_eq!(listed(&home, A), (false, true, None));
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(
&home,
A,
@@ -1383,14 +1302,6 @@ fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() {
moved(&at_close, &tree_of(&home.book_dir(A))),
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.
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
std::fs::create_dir(&unplugged).unwrap();
@@ -1788,7 +1699,7 @@ fn a_running_call_is_never_cut_when_the_grace_runs_out() {
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)]
fn backed_up_to_folder(home: &Home, w: &mut Wire, id: &str) -> PathBuf {
let disk = home.dir.path().join("disk");
@@ -1802,7 +1713,7 @@ fn backed_up_to_folder(home: &Home, w: &mut Wire, id: &str) -> PathBuf {
Response::BackedUp { targets, .. } => assert!(targets[0].problem.is_none(), "{targets:?}"),
other => panic!("{other:?}"),
}
disk.join(format!("{id}.git"))
disk.join(format!("wanderbooks-{id}"))
}
/// A restore over an open book lets go of it as a close does: what is
@@ -1840,6 +1751,7 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() {
replace: true,
confirmed: false,
expect_head: None,
passphrase: None,
}) {
Response::RestorePreview(p) => p,
other => panic!("{other:?}"),
@@ -1855,6 +1767,7 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() {
replace: true,
confirmed: true,
expect_head: Some(preview.head),
passphrase: None,
},
)
.unwrap()
@@ -1961,6 +1874,7 @@ fn a_restore_over_an_open_book_is_not_held_by_a_stalled_upload() {
replace: true,
confirmed: false,
expect_head: None,
passphrase: None,
}) {
Response::RestorePreview(p) => p,
other => panic!("{other:?}"),
@@ -1972,6 +1886,7 @@ fn a_restore_over_an_open_book_is_not_held_by_a_stalled_upload() {
replace: true,
confirmed: true,
expect_head: Some(preview.head),
passphrase: None,
}) {
Response::Restored(r) => r,
other => panic!("{other:?}"),
@@ -2458,7 +2373,7 @@ fn a_close_stops_a_slow_drill_instead_of_waiting_for_it() {
"the last backup waited behind the drill"
);
// 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).
let bound = Duration::from_millis(2 * grace + last_backup) + Duration::from_millis(13_500);
assert!(took < bound, "{took:?} past the stated bound {bound:?}");
@@ -2486,229 +2401,6 @@ fn a_close_stops_a_slow_drill_instead_of_waiting_for_it() {
.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
/// not yet read: the connection it went out on.
#[cfg(unix)]
@@ -2734,24 +2426,6 @@ fn call_unanswered(home: &Home, w: &Wire, id: u64, tool: &str, args: Value) -> r
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
/// 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
@@ -2770,21 +2444,19 @@ fn backup_record_of(home: &Home, id: &str) -> Vec<serde_json::Map<String, Value>
.records
}
/// A backup call that is running (git stalled) when a close begins is
/// STOPPED by it, not waited for: the call is answered, while git is still
/// stalled, that it was stopped because the books are closing; its access
/// record says `refused: stopped_by_close`; the backup records `stopped`
/// and no result of the run's own (nothing it was doing is recorded as
/// done); git and all it started are gone; and the close's own last
/// backup is made as always (local.rs INVARIANT 10).
#[cfg(unix)]
/// 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 the copy is
/// still stalled, that it was stopped because the books are closing; its
/// access record says `refused: stopped_by_close`; the backup records
/// `stopped` and no result of the run's own (nothing it was doing is
/// recorded as done); the folder still proves whole at the backup before;
/// and the close's own last backup is made as always (local.rs INVARIANT
/// 10).
#[test]
fn a_close_stops_a_running_backup_call_and_says_so() {
let home = Home::new("close-stops-backup-call");
let shim = shim_git(&home);
let server = server_with_shim(
let server = Server::start_with(
&home,
&shim,
&[
"--close-backup",
"20000",
@@ -2792,6 +2464,8 @@ fn a_close_stops_a_running_backup_call_and_says_so() {
"3600000",
"--timers",
"20",
"--slow-steps",
"600000",
],
);
home.create(A, "USD");
@@ -2800,18 +2474,27 @@ fn a_close_stops_a_running_backup_call_and_says_so() {
let mut w = Wire::new(&home, A);
w.initialize("owner");
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");
std::fs::write(shim.join("stall"), b"").unwrap();
let mut call = call_unanswered(&home, &w, 4, "books.back_up_now", json!({}));
wait_for("the call reached git", Duration::from_secs(60), || {
shim.join("stalled").exists()
std::fs::write(stall_file(&home, A), b"").unwrap();
let mut call = call_unanswered(&home, &w, 5, "books.back_up_now", json!({}));
wait_for("the call reached a phase", Duration::from_secs(60), || {
reached(&home, A) > 0
});
let started = std::time::Instant::now();
let closing = std::thread::spawn({
let admin = home.run().join("admin.sock");
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();
assert_eq!(status, 200, "{said}");
assert!(
@@ -2819,22 +2502,17 @@ fn a_close_stops_a_running_backup_call_and_says_so() {
&& said.contains("nothing it was doing is recorded as done"),
"{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.
std::fs::remove_file(shim.join("stall")).unwrap();
std::fs::remove_file(stall_file(&home, A)).unwrap();
match closing.join().unwrap() {
Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed),
other => panic!("{other:?}"),
}
assert!(started.elapsed() < NEVER_LONGER);
let stalled: Vec<u32> = std::fs::read_to_string(shim.join("stalled"))
.unwrap_or_default()
.lines()
.filter_map(|l| l.trim().parse().ok())
.collect();
for pid in &stalled {
assert!(!alive(*pid), "git {pid} still runs");
}
// The close's own backup made the last head whole; before it the stopped
// one had left the folder at `kept`, which it was proven to be above.
assert!(proven_head(&home, &disk, "after").0 >= kept.0);
let records = access_of(&home, A);
let mine = records
.iter()
@@ -2853,8 +2531,14 @@ fn a_close_stops_a_running_backup_call_and_says_so() {
&& r.get("why") == Some(&json!("asked"))),
"{record:?}"
);
// The run before the stall made its record; the stopped one made none
// of its own after its `stopped`.
let stopped_at = record
.iter()
.position(|r| r.get("kind") == Some(&json!("stopped")))
.unwrap();
assert!(
!record
!record[stopped_at..]
.iter()
.any(|r| r.get("why") == Some(&json!("asked"))
&& r.get("kind") != Some(&json!("stopped"))),
@@ -3130,6 +2814,7 @@ impl Jobs {
replace: false,
confirmed: false,
expect_head: None,
passphrase: None,
}) {
Response::RestorePreview(p) => p.head,
other => panic!("{other:?}"),
@@ -3172,6 +2857,7 @@ impl Jobs {
replace,
confirmed: true,
expect_head: Some(self.restore_head.clone()),
passphrase: None,
}
}
}
@@ -3424,7 +3110,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
/// 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
/// 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
/// `acme` is still not answered. All three jobs finish correctly, none
/// stopped, none told of any error.
@@ -3432,23 +3118,17 @@ fn finished<T>(what: &str, thread: std::thread::JoinHandle<T>) -> T {
#[test]
fn closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_jobs() {
let home = Home::new("close-spares-other-jobs");
let shim = shim_git(&home);
let mut args = JOB_ARGS.to_vec();
args.extend(["--close-backup", "120000"]);
let server = server_with_shim(&home, &shim, &args);
args.extend(["--close-backup", "120000", "--slow-steps", "600000"]);
let server = Server::start_with(&home, &args);
let jobs = Jobs::new(&home);
home.create(B, "USD");
let run = home.run();
let stalled = || {
std::fs::read_to_string(shim.join("stalled"))
.unwrap_or_default()
.lines()
.count()
};
let stalled = || reached(&home, A);
// One close and reopening of `acme`, while the jobs are held.
let cycle = |why: &str| {
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() });
wait_for(
&format!("{why}: the close of {A} is in its backup"),
@@ -3487,7 +3167,7 @@ fn closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_j
"{why}"
);
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!(
finished(&format!("{why}: the close of {A}"), closing),
Response::CloseBook {
@@ -3599,177 +3279,6 @@ fn job_server_again(home: &Home) -> Server {
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.
#[cfg(unix)]
fn finishes_within<T>(thread: &std::thread::JoinHandle<T>, within: Duration) -> bool {
@@ -3801,6 +3310,7 @@ fn a_close_is_answered_while_a_restore_preview_of_its_book_is_still_running() {
replace: false,
confirmed: false,
expect_head: None,
passphrase: None,
};
let previewing = job_held_in(&home, "restore:fetch", &preview, "restore:fetch");
let closing = admin_in_thread(&home, Request::CloseBook { id: A.to_string() });
+2 -2
View File
@@ -887,7 +887,7 @@ impl Books {
/// Every file under `dir`, by path relative to it, with the SHA-256 of its
/// contents, leaving out what a call writes by design whatever the call:
/// the access log (every call is recorded), the viewer's side channel
/// (`ops/`), the books' own backup (`archive.git/`), the files handed over
/// (`ops/`), the books' own local backup (`local-backup/`), the files handed over
/// and on their way in (`exports/`, `uploads/`), and SQLite's -wal and
/// -shm files (it moves pages between them on its own).
pub fn book_files(dir: &Path) -> std::collections::BTreeMap<PathBuf, String> {
@@ -904,7 +904,7 @@ pub fn book_files(dir: &Path) -> std::collections::BTreeMap<PathBuf, String> {
.next()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.unwrap_or_default();
if ["ops", "archive.git", "exports", "uploads"].contains(&first.as_str())
if ["ops", "local-backup", "local", "exports", "uploads"].contains(&first.as_str())
|| name == "access.jsonl"
|| name.ends_with("-wal")
|| name.ends_with("-shm")
+26 -24
View File
@@ -408,15 +408,21 @@ fn format_lines(dir: &Path) -> usize {
.count()
}
/// git, on the books' own backup repository: what it said.
fn archive_git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.arg(format!("--git-dir={}", dir.join("archive.git").display()))
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
String::from_utf8(out.stdout).unwrap()
/// The books' own local backup, proven whole and built in a scratch folder:
/// the books as they were backed up.
fn local_backup(dir: &Path) -> PathBuf {
use ledger_store::backup::{Ctx, find, verify_found};
let scratch = dir.join("scratch-local-backup");
let _ = std::fs::remove_dir_all(&scratch);
let found = find(
&dir.join(ledger_store::backup::LOCAL_DIR),
None,
&Ctx::new(),
)
.expect("a local backup is there");
verify_found(&found, &scratch, &Ctx::new())
.expect("it proves whole")
.tree
}
fn a_setting() -> Value {
@@ -542,7 +548,7 @@ fn format_upgrade_waits_for_consent() {
);
assert!(!shown.contains(wrong), "the passphrase was shown: {shown}");
assert!(
!dir.join("archive.git").exists(),
!dir.join(ledger_store::backup::LOCAL_DIR).exists(),
"no backup before consent"
);
assert_eq!(format_lines(&dir), 0);
@@ -585,17 +591,14 @@ fn format_upgrade_waits_for_consent() {
let after = journal(&dir);
assert!(after.starts_with(&before));
assert_eq!(format_lines(&dir), 1, "the format moved once");
let backup = archive_git(&dir, &["rev-parse", "HEAD"]);
let backup = local_backup(&dir);
assert_eq!(
archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.trim())]).as_bytes(),
std::fs::read(backup.join("journal.jsonl")).unwrap(),
before.as_slice(),
"the backup holds the books as they were"
);
assert_eq!(
archive_git(
&dir,
&["show", &format!("{}:keys/legacy.key", backup.trim())]
),
std::fs::read_to_string(backup.join("keys").join("legacy.key")).unwrap(),
"ab".repeat(32),
"and their key"
);
@@ -801,19 +804,18 @@ fn books_p2_served_cut_over_whole() {
2,
"P2's declaration, then the upgrade's"
);
let backup = archive_git(&dir, &["rev-parse", "HEAD"]);
let backup = local_backup(&dir);
assert_eq!(
archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.trim())]).as_bytes(),
std::fs::read(backup.join("journal.jsonl")).unwrap(),
waiting.as_slice(),
"the backup holds the books as they were"
);
for kept in ["keys/legacy.key", "vault/tin-1.bin", "vault/tin-3.bin"] {
let out = Command::new("git")
.arg(format!("--git-dir={}", dir.join("archive.git").display()))
.args(["show", &format!("{}:{kept}", backup.trim())])
.output()
.unwrap();
assert_eq!(out.stdout, std::fs::read(dir.join(kept)).unwrap(), "{kept}");
assert_eq!(
std::fs::read(backup.join(kept)).unwrap(),
std::fs::read(dir.join(kept)).unwrap(),
"{kept}"
);
}
assert_eq!(figures(&mut a), before, "the upgrade moves no figure");
+29 -18
View File
@@ -2655,6 +2655,20 @@ fn the_commands_given_run_as_the_agents_own_token() {
a.end();
}
/// A copy of a folder and everything in it.
fn copy_folder(from: &std::path::Path, to: &std::path::Path) {
std::fs::create_dir_all(to).unwrap();
for e in std::fs::read_dir(from).unwrap() {
let e = e.unwrap();
let target = to.join(e.file_name());
if e.path().is_dir() {
copy_folder(&e.path(), &target);
} else {
std::fs::copy(e.path(), target).unwrap();
}
}
}
#[test]
fn a_backup_is_restored_from_the_command_line() {
let home = Home::new("restore");
@@ -2683,7 +2697,7 @@ fn a_backup_is_restored_from_the_command_line() {
);
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
let head = s["head_seq"].as_u64().unwrap();
let backup = disk.join("acme.git");
let backup = disk.join("wanderbooks-acme");
let backup = backup.to_str().unwrap();
// Previewed, and not done without a yes.
let out = home.books(&["restore", backup, "--id", "copy"]);
@@ -2700,16 +2714,10 @@ fn a_backup_is_restored_from_the_command_line() {
String::from_utf8_lossy(&out.stderr).contains("already books called"),
"{out:?}"
);
// A repository named otherwise: restored as the books it holds, by
// default (here: over those, refused), said.
let renamed = home.dir.path().join("disk").join("fernhill-backup.git");
let out = Command::new("git")
.args(["clone", "-q", "--bare"])
.arg(backup)
.arg(&renamed)
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
// A folder named otherwise: restored as the books it holds, by default
// (here: over those, refused), said.
let renamed = home.dir.path().join("fernhill-backup");
copy_folder(&disk.join("wanderbooks-acme"), &renamed);
let out = home.books(&["restore", renamed.to_str().unwrap(), "--yes"]);
assert!(
String::from_utf8_lossy(&out.stderr).contains("already books called \"acme\""),
@@ -2721,9 +2729,12 @@ fn a_backup_is_restored_from_the_command_line() {
said.contains("It is a backup of the books \"acme\""),
"{out:?}"
);
assert!(said.contains("--id acme"), "{out:?}");
// A repository whose name is no id: still restored as its books.
let odd = home.dir.path().join("disk").join("Fernhill_Backup.git");
assert!(
said.contains("They were backed up as \"acme\"; they come back as \"other\""),
"{out:?}"
);
// A folder whose name is no id: still restored as its books.
let odd = home.dir.path().join("Fernhill_Backup");
std::fs::rename(&renamed, &odd).unwrap();
let out = home.books(&["restore", odd.to_str().unwrap(), "--yes"]);
assert!(
@@ -2738,7 +2749,7 @@ fn a_backup_is_restored_from_the_command_line() {
String::from_utf8_lossy(&out.stdout).contains("Restored as \"copy\""),
"{out:?}"
);
// Replacing them, the old kept: from the repository named otherwise,
// Replacing them, the old kept: from the folder named otherwise,
// given no id (the books it holds are replaced).
post_one(&mut a, 2).unwrap();
let out = home.books(&["restore", renamed.to_str().unwrap(), "--replace", "--yes"]);
@@ -2914,9 +2925,9 @@ fn books_are_backed_up_now_from_the_command_line() {
String::from_utf8_lossy(&out.stdout).contains("Backed up to the backup folder"),
"{out:?}"
);
assert!(disk.join("acme.git").join("HEAD").is_file());
assert!(disk.join("wanderbooks-acme").join("manifests").is_dir());
// A folder gone since: said, and --new-disk begins it again.
std::fs::rename(disk.join("acme.git"), home.dir.path().join("away.git")).unwrap();
std::fs::rename(disk.join("wanderbooks-acme"), home.dir.path().join("away")).unwrap();
let out = home.books(&["back-up", "acme"]);
assert_eq!(out.status.code(), Some(1), "{out:?}");
assert!(
@@ -2925,7 +2936,7 @@ fn books_are_backed_up_now_from_the_command_line() {
);
let out = home.books(&["back-up", "acme", "--new-disk"]);
assert!(out.status.success(), "{out:?}");
assert!(disk.join("acme.git").join("HEAD").is_file());
assert!(disk.join("wanderbooks-acme").join("manifests").is_dir());
a.end();
}
+20 -16
View File
@@ -684,26 +684,30 @@ fn only_a_person_runs_the_workflow_that_publishes_the_repositories() {
);
}
/// WB-pkg-4: on Linux git is a dependency of every package, so the package
/// manager fetches it; nothing carries a git of its own.
/// WB-pkg-4: a backup is plain files the program writes itself, so no
/// package depends on another program for it and none carries one.
#[test]
fn the_linux_packages_depend_on_git_and_none_carries_one() {
let packager = read("deploy/packaging/packager.toml");
assert_eq!(
packager.matches("\"git\"").count(),
2,
"the deb and the pacman package depend on git"
);
assert!(read("crates/ledger-cli/Cargo.toml").contains("requires = { git = \"*\" }"));
assert!(read("deploy/packaging/aur/PKGBUILD").contains("'git'"));
fn no_package_depends_on_another_program_for_backups() {
let word = |text: &str| {
text.to_lowercase()
.split(|c: char| !c.is_ascii_alphanumeric())
.any(|w| w == "git")
};
for file in [
"deploy/packaging/packager.toml",
"deploy/packaging/aur/PKGBUILD",
"crates/ledger-cli/Cargo.toml",
"deploy/packaging/windows/wanderbooks.nsi",
"deploy/packaging/macos/build-macos.sh",
] {
let text = read(file).to_lowercase();
assert!(
!text.contains("mingit") && !text.contains("git.exe"),
"{file} bundles a git"
);
let text = read(file);
// (Cargo.toml may name a git *dependency* of the build, never a
// package requirement.)
let checked: String = text
.lines()
.filter(|l| !l.contains("git ="))
.collect::<Vec<_>>()
.join("\n");
assert!(!word(&checked), "{file} depends on, or bundles, a git");
}
}