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:
commit
e6d722372e
84 files changed
+14080
-7319
No files matched your search
@@ -57,7 +57,7 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
target: [fuzz_journal_line, fuzz_entry_validate, fuzz_op_sequence, fuzz_core_serde, fuzz_store_open, fuzz_store_replay, fuzz_settings_replay, fuzz_import_csv, fuzz_config_parse, fuzz_extract_pdf, fuzz_extract_xlsx, fuzz_http_mcp_request, fuzz_upload_put]
|
target: [fuzz_journal_line, fuzz_entry_validate, fuzz_op_sequence, fuzz_core_serde, fuzz_store_open, fuzz_backup_read, fuzz_store_replay, fuzz_settings_replay, fuzz_import_csv, fuzz_config_parse, fuzz_extract_pdf, fuzz_extract_xlsx, fuzz_http_mcp_request, fuzz_upload_put]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: jdx/mise-action@v2
|
- uses: jdx/mise-action@v2
|
||||||
|
|||||||
Generated
+40
-2
@@ -1732,6 +1732,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
|
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags 2.13.2",
|
"bitflags 2.13.2",
|
||||||
|
"block2 0.6.2",
|
||||||
|
"libc",
|
||||||
"objc2 0.6.5",
|
"objc2 0.6.5",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1831,7 +1833,7 @@ dependencies = [
|
|||||||
"objc2-foundation 0.3.2",
|
"objc2-foundation 0.3.2",
|
||||||
"parking_lot",
|
"parking_lot",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"pollster",
|
"pollster 1.0.1",
|
||||||
"profiling",
|
"profiling",
|
||||||
"raw-window-handle",
|
"raw-window-handle",
|
||||||
"ron",
|
"ron",
|
||||||
@@ -1987,7 +1989,7 @@ dependencies = [
|
|||||||
"kittest",
|
"kittest",
|
||||||
"log",
|
"log",
|
||||||
"open",
|
"open",
|
||||||
"pollster",
|
"pollster 1.0.1",
|
||||||
"serde",
|
"serde",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"toml 1.1.8+spec-1.1.0",
|
"toml 1.1.8+spec-1.1.0",
|
||||||
@@ -4105,6 +4107,7 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
"notify",
|
"notify",
|
||||||
"proptest",
|
"proptest",
|
||||||
|
"rfd",
|
||||||
"rust_decimal",
|
"rust_decimal",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -4118,6 +4121,7 @@ name = "ledger-host"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
|
"chrono",
|
||||||
"ledger-core",
|
"ledger-core",
|
||||||
"ledger-link",
|
"ledger-link",
|
||||||
"ledger-mcp",
|
"ledger-mcp",
|
||||||
@@ -4262,6 +4266,7 @@ name = "ledger-store"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
|
"chacha20poly1305",
|
||||||
"chrono",
|
"chrono",
|
||||||
"criterion",
|
"criterion",
|
||||||
"getrandom 0.2.17",
|
"getrandom 0.2.17",
|
||||||
@@ -4279,6 +4284,8 @@ dependencies = [
|
|||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
|
"zeroize",
|
||||||
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4855,6 +4862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
|
checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags 2.13.2",
|
"bitflags 2.13.2",
|
||||||
|
"block2 0.6.2",
|
||||||
"objc2 0.6.5",
|
"objc2 0.6.5",
|
||||||
"objc2-core-foundation",
|
"objc2-core-foundation",
|
||||||
"objc2-core-graphics",
|
"objc2-core-graphics",
|
||||||
@@ -5594,6 +5602,12 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pollster"
|
||||||
|
version = "0.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pollster"
|
name = "pollster"
|
||||||
version = "1.0.1"
|
version = "1.0.1"
|
||||||
@@ -6258,6 +6272,30 @@ dependencies = [
|
|||||||
"zune-jpeg",
|
"zune-jpeg",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rfd"
|
||||||
|
version = "0.17.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220"
|
||||||
|
dependencies = [
|
||||||
|
"block2 0.6.2",
|
||||||
|
"dispatch2",
|
||||||
|
"js-sys",
|
||||||
|
"libc",
|
||||||
|
"log",
|
||||||
|
"objc2 0.6.5",
|
||||||
|
"objc2-app-kit 0.3.2",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
"objc2-foundation 0.3.2",
|
||||||
|
"percent-encoding",
|
||||||
|
"pollster 0.4.0",
|
||||||
|
"raw-window-handle",
|
||||||
|
"wasm-bindgen",
|
||||||
|
"wasm-bindgen-futures",
|
||||||
|
"web-sys",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rgb"
|
name = "rgb"
|
||||||
version = "0.8.53"
|
version = "0.8.53"
|
||||||
|
|||||||
@@ -8020,6 +8020,7 @@ MIT License
|
|||||||
================================================================================
|
================================================================================
|
||||||
|
|
||||||
Used by:
|
Used by:
|
||||||
|
pollster 0.4.0
|
||||||
pollster 1.0.1
|
pollster 1.0.1
|
||||||
|
|
||||||
Copyright (c) 2020-2021 Joshua Barretto
|
Copyright (c) 2020-2021 Joshua Barretto
|
||||||
@@ -10049,6 +10050,36 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
|||||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
DEALINGS IN THE SOFTWARE.
|
DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
MIT License
|
||||||
|
================================================================================
|
||||||
|
|
||||||
|
Used by:
|
||||||
|
rfd 0.17.2
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2020 Bilal Elmoussaoui
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
|
||||||
|
|
||||||
================================================================================
|
================================================================================
|
||||||
MIT License
|
MIT License
|
||||||
================================================================================
|
================================================================================
|
||||||
@@ -10109,6 +10140,36 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|||||||
SOFTWARE.
|
SOFTWARE.
|
||||||
|
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
MIT License
|
||||||
|
================================================================================
|
||||||
|
|
||||||
|
Used by:
|
||||||
|
rfd 0.17.2
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2022 Bartłomiej Maryńczak
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
|
||||||
|
|
||||||
================================================================================
|
================================================================================
|
||||||
MIT License
|
MIT License
|
||||||
================================================================================
|
================================================================================
|
||||||
@@ -10429,6 +10490,7 @@ Used by:
|
|||||||
brotli-decompressor 5.0.3
|
brotli-decompressor 5.0.3
|
||||||
chrono 0.4.45
|
chrono 0.4.45
|
||||||
comemo-macros 0.5.1
|
comemo-macros 0.5.1
|
||||||
|
dispatch2 0.3.1
|
||||||
dispatch 0.2.0
|
dispatch 0.2.0
|
||||||
dpi 0.1.2
|
dpi 0.1.2
|
||||||
ecolor 0.36.2
|
ecolor 0.36.2
|
||||||
@@ -15973,6 +16035,7 @@ Their copyright notices are in their source repositories:
|
|||||||
block2 0.6.2 https://github.com/madsmtm/objc2
|
block2 0.6.2 https://github.com/madsmtm/objc2
|
||||||
comemo-macros 0.5.1 https://github.com/typst/comemo
|
comemo-macros 0.5.1 https://github.com/typst/comemo
|
||||||
dispatch 0.2.0 http://github.com/SSheldon/rust-dispatch
|
dispatch 0.2.0 http://github.com/SSheldon/rust-dispatch
|
||||||
|
dispatch2 0.3.1 https://github.com/madsmtm/objc2
|
||||||
ecolor 0.36.2 https://github.com/emilk/egui
|
ecolor 0.36.2 https://github.com/emilk/egui
|
||||||
eframe 0.36.2 https://github.com/emilk/egui/tree/main/crates/eframe
|
eframe 0.36.2 https://github.com/emilk/egui/tree/main/crates/eframe
|
||||||
egui 0.36.2 https://github.com/emilk/egui
|
egui 0.36.2 https://github.com/emilk/egui
|
||||||
|
|||||||
@@ -75,8 +75,6 @@ workspace = true
|
|||||||
# program: `just package-linux`. Paths are relative to the workspace root.
|
# program: `just package-linux`. Paths are relative to the workspace root.
|
||||||
[package.metadata.generate-rpm]
|
[package.metadata.generate-rpm]
|
||||||
name = "wanderbooks"
|
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"
|
summary = "Double-entry bookkeeping your agent keeps and you can read"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
url = "https://wanderbooks.ai"
|
url = "https://wanderbooks.ai"
|
||||||
|
|||||||
@@ -299,7 +299,41 @@ impl ledger_gui::owner::Owner for ViewerOwner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn back_up_now(&self, book: &str) -> Result<Vec<String>, String> {
|
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(
|
fn plan_restore(
|
||||||
@@ -307,10 +341,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 +364,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(),
|
||||||
|
|||||||
+299
-812
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,797 @@
|
|||||||
|
//! What a person is told when their backups are in trouble (WB-backup-13 to
|
||||||
|
//! WB-backup-16): the key file lost from a sealed destination, books behind
|
||||||
|
//! the folder's (a new set at their request), a newest backup that is
|
||||||
|
//! damaged while an older one is whole, and a folder a sync service keeps.
|
||||||
|
#![cfg(unix)]
|
||||||
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
use ledger_mcp::admin::{self, Request, Response};
|
||||||
|
use ledger_store::backup::{Ctx, find, verify_found};
|
||||||
|
use ledger_store::root::{BookId, Root};
|
||||||
|
use rmcp::ServiceExt;
|
||||||
|
use rmcp::model::{CallToolRequestParams, ClientConfig};
|
||||||
|
use rmcp::service::{RoleClient, RunningService};
|
||||||
|
use rmcp::transport::StreamableHttpClientTransport;
|
||||||
|
use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::io::{BufRead, BufReader};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Child, Command, Stdio};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
type Client = RunningService<RoleClient, ClientConfig>;
|
||||||
|
|
||||||
|
/// A home with a data root made by `wanderbooks setup`, and a place for
|
||||||
|
/// the backups beside it.
|
||||||
|
struct Home {
|
||||||
|
dir: tempfile::TempDir,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Home {
|
||||||
|
fn new(tag: &str) -> Self {
|
||||||
|
let dir = tempfile::Builder::new()
|
||||||
|
.prefix(&format!("wb-bk-{tag}-"))
|
||||||
|
.tempdir()
|
||||||
|
.unwrap();
|
||||||
|
let out = Command::new(env!("CARGO_BIN_EXE_wanderbooks"))
|
||||||
|
.args(["setup", "--home"])
|
||||||
|
.arg(dir.path())
|
||||||
|
.env_remove("XDG_DATA_HOME")
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(out.status.success(), "{out:?}");
|
||||||
|
Self { dir }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn root(&self) -> PathBuf {
|
||||||
|
ledger_store::root::default_root(self.dir.path())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn book_dir(&self, book: &str) -> PathBuf {
|
||||||
|
Root::open(&self.root())
|
||||||
|
.unwrap()
|
||||||
|
.book_dir(&BookId::parse(book).unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn admin(&self, request: Request) -> Response {
|
||||||
|
admin::call(&self.root().join("run/admin.sock"), request).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create(&self, id: &str) {
|
||||||
|
match self.admin(Request::Create {
|
||||||
|
id: id.into(),
|
||||||
|
currency: "USD".into(),
|
||||||
|
}) {
|
||||||
|
Response::Created { problem: None, .. } => {}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn token(&self, book: &str, scopes: &[&str]) -> String {
|
||||||
|
match self.admin(Request::TokenCreate {
|
||||||
|
book: book.into(),
|
||||||
|
name: format!("test-{}", scopes.join("-")),
|
||||||
|
scopes: scopes.iter().map(|s| s.to_string()).collect(),
|
||||||
|
replace: true,
|
||||||
|
}) {
|
||||||
|
Response::TokenCreated { text, .. } => text.0,
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A place outside the data root (a folder on "another disk").
|
||||||
|
fn outside(&self, name: &str) -> PathBuf {
|
||||||
|
let p = self.dir.path().join("elsewhere").join(name);
|
||||||
|
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||||
|
p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A running `wanderbooks server`, ended (kill) when dropped.
|
||||||
|
struct Server {
|
||||||
|
child: Child,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Server {
|
||||||
|
/// Start one, backing up after `quiet` of no writing (a drill first
|
||||||
|
/// looked for after the server's own wait: a minute, past any test).
|
||||||
|
fn start(home: &Home, quiet: Duration) -> Self {
|
||||||
|
Self::start_with(home, quiet, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Self::start`], a drill first looked for `drill_first` after books
|
||||||
|
/// are seen open.
|
||||||
|
fn start_with(home: &Home, quiet: Duration, drill_first: Option<Duration>) -> Self {
|
||||||
|
let mut command = Command::new(env!("CARGO_BIN_EXE_wanderbooks"));
|
||||||
|
command
|
||||||
|
.arg("server")
|
||||||
|
.arg("--root")
|
||||||
|
.arg(home.root())
|
||||||
|
.arg("--backup-quiet")
|
||||||
|
.arg(quiet.as_millis().to_string());
|
||||||
|
if let Some(d) = drill_first {
|
||||||
|
command.arg("--drill-first").arg(d.as_millis().to_string());
|
||||||
|
}
|
||||||
|
let mut child = command
|
||||||
|
.env_clear()
|
||||||
|
.env("PATH", "/usr/bin:/bin")
|
||||||
|
.env("HOME", home.dir.path())
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
let mut line = String::new();
|
||||||
|
BufReader::new(child.stdout.take().unwrap())
|
||||||
|
.read_line(&mut line)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(line, "ready\n", "the server didn't say ready");
|
||||||
|
Self { child }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close it as the host does (stdin ends) and wait for it to exit.
|
||||||
|
fn close(mut self) -> std::process::ExitStatus {
|
||||||
|
drop(self.child.stdin.take());
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(60);
|
||||||
|
loop {
|
||||||
|
if let Some(status) = self.child.try_wait().unwrap() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
assert!(Instant::now() < deadline, "the server didn't close");
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Server {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = self.child.kill();
|
||||||
|
let _ = self.child.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A session with one book, and what it takes to send the book a file as
|
||||||
|
/// an agent does (D-46: a file comes only by upload).
|
||||||
|
struct Agent {
|
||||||
|
client: Client,
|
||||||
|
http: reqwest::Client,
|
||||||
|
book: String,
|
||||||
|
token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::ops::Deref for Agent {
|
||||||
|
type Target = Client;
|
||||||
|
fn deref(&self) -> &Client {
|
||||||
|
&self.client
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Agent {
|
||||||
|
/// Upload `bytes` as `wanderbooks upload` does: books.begin_upload,
|
||||||
|
/// then the bytes PUT with this session's token. The upload_id.
|
||||||
|
async fn upload(&self, bytes: &[u8], file_name: &str, mime_type: &str) -> String {
|
||||||
|
let begun = call(
|
||||||
|
self,
|
||||||
|
"books.begin_upload",
|
||||||
|
json!({"sha256": ledger_store::journal::sha256_hex(bytes), "size": bytes.len(),
|
||||||
|
"mime_type": mime_type, "file_name": file_name, "purpose": "receipt"}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let id = begun["upload_id"].as_str().unwrap().to_string();
|
||||||
|
let r = self
|
||||||
|
.http
|
||||||
|
.put(format!("http://localhost/b/{}/u/{id}", self.book))
|
||||||
|
.bearer_auth(&self.token)
|
||||||
|
.body(bytes.to_vec())
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status().as_u16(), 200);
|
||||||
|
id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn connect(home: &Home, book: &str, token: String) -> Agent {
|
||||||
|
// The short path is good in this process only, while it lives: kept.
|
||||||
|
let short = ledger_store::root::SocketPath::new(&home.root().join("run"), "mcp.sock").unwrap();
|
||||||
|
let path = short.path().to_path_buf();
|
||||||
|
std::mem::forget(short);
|
||||||
|
let http = reqwest::Client::builder()
|
||||||
|
.unix_socket(path)
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
let config =
|
||||||
|
StreamableHttpClientTransportConfig::with_uri(format!("http://localhost/b/{book}/mcp"))
|
||||||
|
.auth_header(token.clone());
|
||||||
|
let client = ClientConfig::default()
|
||||||
|
.serve(StreamableHttpClientTransport::with_client(
|
||||||
|
http.clone(),
|
||||||
|
config,
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
Agent {
|
||||||
|
client,
|
||||||
|
http,
|
||||||
|
book: book.to_string(),
|
||||||
|
token,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Call a tool: Ok(structured result) or Err(the error text).
|
||||||
|
/// Call a tool the way an agent confirms (plan P4, D-50): a call with
|
||||||
|
/// `confirmed: true` and no `preview` is made first without `confirmed`,
|
||||||
|
/// then with the `preview` it returned. A refused preview is the answer.
|
||||||
|
async fn call(c: &Client, tool: &str, mut args: Value) -> Result<Value, String> {
|
||||||
|
if args.get("confirmed") == Some(&json!(true)) && args.get("preview").is_none() {
|
||||||
|
let mut first = args.clone();
|
||||||
|
first["confirmed"] = json!(false);
|
||||||
|
let seen = call_once(c, tool, first).await?;
|
||||||
|
if let Some(digest) = seen.get("preview").and_then(Value::as_str) {
|
||||||
|
args["preview"] = json!(digest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
call_once(c, tool, args).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call_once(c: &Client, tool: &str, args: Value) -> Result<Value, String> {
|
||||||
|
let mut args = args.as_object().cloned().unwrap_or_default();
|
||||||
|
// The key every write call carries (D-88).
|
||||||
|
static NEXT_KEY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||||
|
args.entry("request_key").or_insert_with(|| {
|
||||||
|
let n = NEXT_KEY.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
json!(format!("backups-key-{}-{n}", std::process::id()))
|
||||||
|
});
|
||||||
|
let r = tokio::time::timeout(
|
||||||
|
Duration::from_secs(60),
|
||||||
|
c.call_tool(CallToolRequestParams::new(tool.to_string()).with_arguments(args)),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "no answer".to_string())?
|
||||||
|
.map_err(|e| format!("protocol: {e}"))?;
|
||||||
|
let text = r
|
||||||
|
.content
|
||||||
|
.iter()
|
||||||
|
.find_map(|c| c.as_text().map(|t| t.text.clone()))
|
||||||
|
.unwrap_or_default();
|
||||||
|
if r.is_error == Some(true) {
|
||||||
|
Err(text)
|
||||||
|
} else {
|
||||||
|
Ok(r.structured_content
|
||||||
|
.unwrap_or_else(|| serde_json::from_str(&text).unwrap_or(Value::String(text))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn head(c: &Client) -> u64 {
|
||||||
|
call(c, "books.start", json!({})).await.unwrap()["head"]["seq"]
|
||||||
|
.as_u64()
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Name the backup folder in the book's settings.
|
||||||
|
async fn set_folder(c: &Client, folder: &Path) {
|
||||||
|
call(
|
||||||
|
c,
|
||||||
|
"books.set_setting",
|
||||||
|
json!({"changes": [{"key": "backup.folder", "value": folder.display().to_string()}],
|
||||||
|
"decided_by": "Test Owner", "note": "Backups."}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Draft, receipt and post one $n entry.
|
||||||
|
async fn post_one(c: &Agent, n: u64) {
|
||||||
|
for (code, name, ty) in [("1000", "Cash", "asset"), ("6000", "Supplies", "expense")] {
|
||||||
|
let _ = call(
|
||||||
|
c,
|
||||||
|
"books.add_account",
|
||||||
|
json!({"code": code, "name": name, "account_type": ty}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
let e = call(
|
||||||
|
c,
|
||||||
|
"books.draft_entry",
|
||||||
|
json!({"date": "2026-03-01", "description": format!("entry {n}")}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let id = e["entry_id"].as_u64().unwrap();
|
||||||
|
for (account, side) in [("6000", "debit"), ("1000", "credit")] {
|
||||||
|
call(
|
||||||
|
c,
|
||||||
|
"books.add_line",
|
||||||
|
json!({"entry_id": id, "account": account, "side": side, "amount": format!("{n}.00")}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
// Bytes of each entry's own: the same bytes stored already would be
|
||||||
|
// named for linking, not uploaded again.
|
||||||
|
let upload = c
|
||||||
|
.upload(
|
||||||
|
format!("receipt {n}").as_bytes(),
|
||||||
|
&format!("r{n}.txt"),
|
||||||
|
"text/plain",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
call(
|
||||||
|
c,
|
||||||
|
"books.attach_receipt",
|
||||||
|
json!({"entry_id": id, "upload_id": upload}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
call(
|
||||||
|
c,
|
||||||
|
"books.post_entry",
|
||||||
|
json!({"entry_id": id, "confirmed": true, "no_party_reason": "test"}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Long enough for the server's backup loop (which looks every 2 s) to
|
||||||
|
/// have seen books just made, before they name any target: what it does
|
||||||
|
/// on first seeing them (a backup, a drill) is then done.
|
||||||
|
async fn settle() {
|
||||||
|
tokio::time::sleep(Duration::from_millis(4500)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait until every target holds the books' head (or `within` passes).
|
||||||
|
async fn backed_up(c: &Client, within: Duration) -> Value {
|
||||||
|
let deadline = Instant::now() + within;
|
||||||
|
loop {
|
||||||
|
let s = call(c, "books.backup", json!({})).await.unwrap();
|
||||||
|
let head = s["head_seq"].as_u64().unwrap();
|
||||||
|
let targets = s["targets"].as_array().unwrap();
|
||||||
|
if !targets.is_empty()
|
||||||
|
&& targets
|
||||||
|
.iter()
|
||||||
|
.all(|t| t["through_seq"].as_u64() == Some(head))
|
||||||
|
{
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
assert!(Instant::now() < deadline, "not backed up in time: {s}");
|
||||||
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prove the backup at `source` (a destination folder, a set's folder, or a
|
||||||
|
/// file) whole; its head.
|
||||||
|
fn proven(home: &Home, source: &Path, tag: &str) -> (u64, String) {
|
||||||
|
let scratch = home.outside(&format!("scratch-{tag}"));
|
||||||
|
let found = find(source, None, &Ctx::new()).unwrap_or_else(|e| panic!("{tag}: {e}"));
|
||||||
|
verify_found(&found, &scratch, &Ctx::new())
|
||||||
|
.unwrap_or_else(|e| panic!("{tag}: {e}"))
|
||||||
|
.head
|
||||||
|
}
|
||||||
|
|
||||||
|
fn live_head(home: &Home, book: &str) -> (u64, String) {
|
||||||
|
let s = ledger_store::Snapshot::load(&home.book_dir(book)).unwrap();
|
||||||
|
(s.journal_seq(), s.head_hash().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
const ALL: [&str; 4] = ["read", "write", "post", "admin"];
|
||||||
|
|
||||||
|
/// Restore `source` as `id`: the preview, then (if it was one) the
|
||||||
|
/// restore confirmed against its head. Ok(what was restored) or Err(why).
|
||||||
|
fn restore(home: &Home, id: &str, source: &Path, replace: bool) -> Result<admin::Restored, String> {
|
||||||
|
restore_with(home, id, source, replace, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore_with(
|
||||||
|
home: &Home,
|
||||||
|
id: &str,
|
||||||
|
source: &Path,
|
||||||
|
replace: bool,
|
||||||
|
passphrase: Option<&str>,
|
||||||
|
) -> Result<admin::Restored, String> {
|
||||||
|
let request = |expect_head: Option<(u64, String)>| Request::Restore {
|
||||||
|
id: id.into(),
|
||||||
|
source: source.display().to_string(),
|
||||||
|
replace,
|
||||||
|
confirmed: expect_head.is_some(),
|
||||||
|
expect_head,
|
||||||
|
passphrase: passphrase.map(|p| admin::Passphrase(p.to_string())),
|
||||||
|
};
|
||||||
|
let preview = match home.admin(request(None)) {
|
||||||
|
Response::RestorePreview(p) => p,
|
||||||
|
Response::Refused(why) => return Err(why),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
};
|
||||||
|
match home.admin(request(Some(preview.head.clone()))) {
|
||||||
|
Response::Restored(r) => {
|
||||||
|
assert_eq!(r.head, preview.head);
|
||||||
|
assert_eq!(r.problem, None);
|
||||||
|
Ok(r)
|
||||||
|
}
|
||||||
|
Response::Refused(why) => Err(why),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn books_held(home: &Home) -> Vec<String> {
|
||||||
|
match home.admin(Request::List) {
|
||||||
|
Response::Books(b) => b.into_iter().map(|b| b.id).collect(),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the books say, for comparing two that should be the same.
|
||||||
|
async fn figures(c: &Client) -> Value {
|
||||||
|
json!({
|
||||||
|
"tb": call(c, "books.trial_balance", json!({})).await.unwrap(),
|
||||||
|
"receipts": call(c, "books.list_receipts", json!({})).await.unwrap(),
|
||||||
|
"settings": call(c, "books.settings", json!({})).await.unwrap()["settings"].clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A backup of acme (two entries, a receipt each) in the folder.
|
||||||
|
async fn backed_up_acme(home: &Home) -> (PathBuf, Value) {
|
||||||
|
settle().await;
|
||||||
|
let folder = home.outside("disk");
|
||||||
|
std::fs::create_dir_all(&folder).unwrap();
|
||||||
|
let c = connect(home, "acme", home.token("acme", &ALL)).await;
|
||||||
|
set_folder(&c, &folder).await;
|
||||||
|
post_one(&c, 4).await;
|
||||||
|
post_one(&c, 5).await;
|
||||||
|
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||||
|
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||||
|
(folder, figures(&c).await)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The files under `dir` whose path (below it) starts with `prefix`.
|
||||||
|
fn files_below(dir: &Path, prefix: &str) -> Vec<PathBuf> {
|
||||||
|
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||||
|
for e in std::fs::read_dir(dir).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
if p.is_dir() {
|
||||||
|
walk(&p, out);
|
||||||
|
} else {
|
||||||
|
out.push(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut all = Vec::new();
|
||||||
|
walk(dir, &mut all);
|
||||||
|
all.retain(|p| {
|
||||||
|
p.strip_prefix(dir)
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.replace('\\', "/")
|
||||||
|
.starts_with(prefix)
|
||||||
|
});
|
||||||
|
all.sort();
|
||||||
|
all
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_dir(from: &Path, to: &Path) {
|
||||||
|
std::fs::create_dir_all(to).unwrap();
|
||||||
|
for e in std::fs::read_dir(from).unwrap() {
|
||||||
|
let e = e.unwrap();
|
||||||
|
let target = to.join(e.file_name());
|
||||||
|
if e.path().is_dir() {
|
||||||
|
copy_dir(&e.path(), &target);
|
||||||
|
} else {
|
||||||
|
std::fs::copy(e.path(), target).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait until the folder's backup has been drilled.
|
||||||
|
async fn drilled(c: &Client) -> Value {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(60);
|
||||||
|
loop {
|
||||||
|
let s = call(c, "books.backup", json!({})).await.unwrap();
|
||||||
|
let targets = s["targets"].as_array().unwrap();
|
||||||
|
if !targets.is_empty() && targets.iter().all(|t| t["last_drill_at"].is_string()) {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
assert!(Instant::now() < deadline, "no drill: {s}");
|
||||||
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const PASS: &str = "correct horse battery staple";
|
||||||
|
|
||||||
|
fn said(r: Response) -> String {
|
||||||
|
match r {
|
||||||
|
Response::Said { lines } => lines.join(" "),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_lost_key_file_never_makes_backups_plain() {
|
||||||
|
let home = Home::new("lost-key");
|
||||||
|
let server = Server::start(&home, Duration::from_secs(3600));
|
||||||
|
home.create("acme");
|
||||||
|
let folder = home.outside("disk");
|
||||||
|
std::fs::create_dir_all(&folder).unwrap();
|
||||||
|
said(home.admin(Request::BackupSetup {
|
||||||
|
id: "acme".into(),
|
||||||
|
folder: Some(folder.display().to_string()),
|
||||||
|
passphrase: Some(admin::Passphrase(PASS.into())),
|
||||||
|
remove_passphrase: false,
|
||||||
|
}));
|
||||||
|
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||||
|
post_one(&c, 1).await;
|
||||||
|
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||||
|
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||||
|
assert_eq!(s["targets"][0]["sealed"], true);
|
||||||
|
// The key file is lost from this computer (a restored home folder, a
|
||||||
|
// cleaned `local/`).
|
||||||
|
let key = home.book_dir("acme").join("local").join("backup-key.json");
|
||||||
|
std::fs::remove_file(&key).unwrap();
|
||||||
|
let before: Vec<_> = files_below(&folder, "");
|
||||||
|
post_one(&c, 2).await;
|
||||||
|
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||||
|
let t = &s["targets"][0];
|
||||||
|
// Told in words, and nothing was written: no plain copy of the books.
|
||||||
|
let why = t["last_error"].as_str().unwrap_or_default();
|
||||||
|
assert!(why.contains("no longer has its key"), "{s}");
|
||||||
|
assert!(why.contains("remove the passphrase"), "{s}");
|
||||||
|
assert_eq!(t["error_kind"], "key_missing", "{s}");
|
||||||
|
assert_eq!(files_below(&folder, ""), before, "nothing was written");
|
||||||
|
assert!(!folder.join("wanderbooks-acme").exists());
|
||||||
|
// The words a person reads in the window.
|
||||||
|
let standing = match home.admin(Request::BackupStatus { id: "acme".into() }) {
|
||||||
|
Response::BackupStatus(st) => st,
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
};
|
||||||
|
let words = ledger_host::commands::backup_words(&standing).join(" | ");
|
||||||
|
assert!(words.contains("no longer has its key"), "{words}");
|
||||||
|
assert!(
|
||||||
|
words.contains("Enter the backup passphrase again"),
|
||||||
|
"{words}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Even with the backup record gone (set aside as damaged at the next
|
||||||
|
// open), the folder itself says its backups are sealed.
|
||||||
|
drop(c);
|
||||||
|
assert!(server.close().success());
|
||||||
|
std::fs::write(
|
||||||
|
home.book_dir("acme").join("ops").join("backup.jsonl"),
|
||||||
|
b"not a record\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let server = Server::start(&home, Duration::from_secs(3600));
|
||||||
|
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||||
|
let s = call(&c, "books.back_up_now", json!({"new_disk": true}))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(s["targets"][0]["error_kind"], "key_missing", "{s}");
|
||||||
|
assert!(!folder.join("wanderbooks-acme").exists());
|
||||||
|
|
||||||
|
// Plain is written only after an explicit "remove the passphrase".
|
||||||
|
said(home.admin(Request::BackupSetup {
|
||||||
|
id: "acme".into(),
|
||||||
|
folder: None,
|
||||||
|
passphrase: None,
|
||||||
|
remove_passphrase: true,
|
||||||
|
}));
|
||||||
|
let s = call(&c, "books.back_up_now", json!({"new_disk": true}))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||||
|
assert_eq!(s["targets"][0]["sealed"], false);
|
||||||
|
assert!(folder.join("wanderbooks-acme").join("manifests").is_dir());
|
||||||
|
drop(c);
|
||||||
|
assert!(server.close().success());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn books_restored_from_an_older_backup_are_ahead_and_a_new_set_begins_at_their_request() {
|
||||||
|
// Books A back up twice to a folder; books C are restored from a copy of
|
||||||
|
// the folder as it was after the first, and then pointed at the folder
|
||||||
|
// that holds more.
|
||||||
|
let a = Home::new("ahead-a");
|
||||||
|
let server_a = Server::start(&a, Duration::from_secs(3600));
|
||||||
|
a.create("acme");
|
||||||
|
settle().await;
|
||||||
|
let folder = a.outside("disk");
|
||||||
|
std::fs::create_dir_all(&folder).unwrap();
|
||||||
|
let ca = connect(&a, "acme", a.token("acme", &ALL)).await;
|
||||||
|
set_folder(&ca, &folder).await;
|
||||||
|
post_one(&ca, 1).await;
|
||||||
|
let s = call(&ca, "books.back_up_now", json!({})).await.unwrap();
|
||||||
|
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||||
|
let older = a.outside("older");
|
||||||
|
copy_dir(&folder, &older);
|
||||||
|
post_one(&ca, 2).await;
|
||||||
|
let s = call(&ca, "books.back_up_now", json!({})).await.unwrap();
|
||||||
|
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||||
|
let longer = live_head(&a, "acme");
|
||||||
|
drop(ca);
|
||||||
|
assert!(server_a.close().success());
|
||||||
|
|
||||||
|
let c_home = Home::new("ahead-c");
|
||||||
|
let server_c = Server::start(&c_home, Duration::from_secs(3600));
|
||||||
|
let restored = restore(&c_home, "acme", &older.join("wanderbooks-acme"), false).unwrap();
|
||||||
|
assert!(restored.head.0 < longer.0);
|
||||||
|
let cc = connect(&c_home, "acme", c_home.token("acme", &ALL)).await;
|
||||||
|
set_folder(&cc, &folder).await;
|
||||||
|
let before = files_below(&folder, "");
|
||||||
|
let bytes: Vec<Vec<u8>> = before.iter().map(|p| std::fs::read(p).unwrap()).collect();
|
||||||
|
let s = call(&cc, "books.back_up_now", json!({})).await.unwrap();
|
||||||
|
let t = &s["targets"][0];
|
||||||
|
// Told as ahead (not diverged), in words that say what to do.
|
||||||
|
assert_eq!(t["error_kind"], "ahead", "{s}");
|
||||||
|
let why = t["last_error"].as_str().unwrap();
|
||||||
|
assert!(why.contains("a longer history of these books"), "{why}");
|
||||||
|
assert!(why.contains("start a new backup set"), "{why}");
|
||||||
|
assert_eq!(files_below(&folder, ""), before, "nothing was written");
|
||||||
|
let standing = match c_home.admin(Request::BackupStatus { id: "acme".into() }) {
|
||||||
|
Response::BackupStatus(st) => st,
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
};
|
||||||
|
let words = ledger_host::commands::backup_words(&standing).join(" | ");
|
||||||
|
assert!(words.contains("start a new backup set"), "{words}");
|
||||||
|
|
||||||
|
// At the person's request: a new set beside the old, which is
|
||||||
|
// untouched; and the backups go on there.
|
||||||
|
match c_home.admin(Request::BackUpNewSet { id: "acme".into() }) {
|
||||||
|
Response::BackedUp { targets, .. } => {
|
||||||
|
assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}");
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
assert!(folder.join("wanderbooks-acme.2").join("manifests").is_dir());
|
||||||
|
for (p, b) in before.iter().zip(&bytes) {
|
||||||
|
assert_eq!(&std::fs::read(p).unwrap(), b, "{}", p.display());
|
||||||
|
}
|
||||||
|
post_one(&cc, 9).await;
|
||||||
|
let s = call(&cc, "books.back_up_now", json!({})).await.unwrap();
|
||||||
|
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||||
|
assert_eq!(s["targets"][0]["error_kind"], Value::Null, "{s}");
|
||||||
|
assert_eq!(
|
||||||
|
proven(&c_home, &folder.join("wanderbooks-acme.2"), "new").0,
|
||||||
|
live_head(&c_home, "acme").0
|
||||||
|
);
|
||||||
|
// The old set, still whole, still holds the longer history.
|
||||||
|
assert_eq!(
|
||||||
|
proven(&c_home, &folder.join("wanderbooks-acme"), "old"),
|
||||||
|
longer
|
||||||
|
);
|
||||||
|
drop(cc);
|
||||||
|
assert!(server_c.close().success());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_drill_that_finds_only_an_older_backup_is_a_failure_in_words_and_never_ok() {
|
||||||
|
let home = Home::new("older-only");
|
||||||
|
let server = Server::start(&home, Duration::from_secs(3600));
|
||||||
|
home.create("acme");
|
||||||
|
let (folder, _) = backed_up_acme(&home).await;
|
||||||
|
let c = connect(&home, "acme", home.token("acme", &ALL)).await;
|
||||||
|
post_one(&c, 6).await;
|
||||||
|
let s = call(&c, "books.back_up_now", json!({})).await.unwrap();
|
||||||
|
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||||
|
drop(c);
|
||||||
|
assert!(server.close().success());
|
||||||
|
// The newest backup's own segment is damaged after the fact; the one
|
||||||
|
// before it is whole.
|
||||||
|
let set = folder.join("wanderbooks-acme");
|
||||||
|
let newest = files_below(&set, "manifests/").pop().unwrap();
|
||||||
|
let text = std::fs::read_to_string(&newest).unwrap();
|
||||||
|
let m: Value = serde_json::from_str(text.lines().next().unwrap()).unwrap();
|
||||||
|
// Whatever the newest manifest itself adds: a journal, access or index
|
||||||
|
// segment (a manifest names only what is new).
|
||||||
|
let seg = ["journal", "access", "files"]
|
||||||
|
.iter()
|
||||||
|
.find_map(|k| m[*k]["segments"].as_array()?.last().cloned())
|
||||||
|
.expect("the newest manifest adds a segment");
|
||||||
|
let seg = set.join(seg["file"].as_str().unwrap());
|
||||||
|
let mut b = std::fs::read(&seg).unwrap();
|
||||||
|
let mid = b.len() / 2;
|
||||||
|
b[mid] ^= 1;
|
||||||
|
std::fs::write(&seg, b).unwrap();
|
||||||
|
let server = Server::start_with(
|
||||||
|
&home,
|
||||||
|
Duration::from_secs(3600),
|
||||||
|
Some(Duration::from_millis(300)),
|
||||||
|
);
|
||||||
|
let c = connect(&home, "acme", home.token("acme", &["read", "admin"])).await;
|
||||||
|
let s = drilled(&c).await;
|
||||||
|
let t = &s["targets"][0];
|
||||||
|
let why = t["drill_error"].as_str().unwrap_or_default();
|
||||||
|
assert!(why.contains("the newest backup"), "{s}");
|
||||||
|
assert!(why.contains("is damaged; an older one from"), "{s}");
|
||||||
|
assert_eq!(t["error_kind"], "newest_damaged", "{s}");
|
||||||
|
let standing = match home.admin(Request::BackupStatus { id: "acme".into() }) {
|
||||||
|
Response::BackupStatus(st) => st,
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
};
|
||||||
|
let words = ledger_host::commands::backup_words(&standing).join(" | ");
|
||||||
|
assert!(words.contains("failed"), "{words}");
|
||||||
|
assert!(words.contains("older books"), "{words}");
|
||||||
|
assert!(!words.contains("Proven restorable"), "{words}");
|
||||||
|
// A restore from the folder says so before anything else, with both
|
||||||
|
// dates and how many backups it passes over. (The books' own next
|
||||||
|
// backup would find the damage and write the piece again, so the
|
||||||
|
// damage is made again, after the books are closed.)
|
||||||
|
drop(c);
|
||||||
|
assert!(server.close().success());
|
||||||
|
let newest = files_below(&set, "manifests/").pop().unwrap();
|
||||||
|
let text = std::fs::read_to_string(&newest).unwrap();
|
||||||
|
let m: Value = serde_json::from_str(text.lines().next().unwrap()).unwrap();
|
||||||
|
let seg = ["journal", "access", "files"]
|
||||||
|
.iter()
|
||||||
|
.find_map(|k| m[*k]["segments"].as_array()?.last().cloned())
|
||||||
|
.expect("the newest manifest adds a segment");
|
||||||
|
let seg = set.join(seg["file"].as_str().unwrap());
|
||||||
|
let mut b = std::fs::read(&seg).unwrap();
|
||||||
|
let mid = b.len() / 2;
|
||||||
|
b[mid] ^= 1;
|
||||||
|
std::fs::write(&seg, b).unwrap();
|
||||||
|
let other = Home::new("older-only-new");
|
||||||
|
let server = Server::start(&other, Duration::from_secs(3600));
|
||||||
|
match other.admin(Request::Restore {
|
||||||
|
id: "acme".into(),
|
||||||
|
source: folder.display().to_string(),
|
||||||
|
replace: false,
|
||||||
|
confirmed: false,
|
||||||
|
expect_head: None,
|
||||||
|
passphrase: None,
|
||||||
|
}) {
|
||||||
|
Response::RestorePreview(p) => {
|
||||||
|
assert!(p.passed_over >= 1, "{p:?}");
|
||||||
|
assert!(p.written.is_some() && p.newest_written.is_some(), "{p:?}");
|
||||||
|
let words = ledger_host::commands::older_backup_words(&p);
|
||||||
|
assert!(words.starts_with("NOT THE NEWEST BACKUP"), "{words}");
|
||||||
|
assert!(words.contains("passes over "), "{words}");
|
||||||
|
assert!(words.contains(" newer backup"), "{words}");
|
||||||
|
assert!(words.contains("This backup is from"), "{words}");
|
||||||
|
assert!(
|
||||||
|
words.contains("the newest in the folder is from"),
|
||||||
|
"{words}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
assert!(server.close().success());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_folder_a_sync_service_keeps_is_said_in_plain_words_at_set_up() {
|
||||||
|
let home = Home::new("sync");
|
||||||
|
let server = Server::start(&home, Duration::from_secs(3600));
|
||||||
|
home.create("acme");
|
||||||
|
let dropbox = home.outside("Dropbox/Backups");
|
||||||
|
std::fs::create_dir_all(&dropbox).unwrap();
|
||||||
|
let words = said(home.admin(Request::BackupSetup {
|
||||||
|
id: "acme".into(),
|
||||||
|
folder: Some(dropbox.display().to_string()),
|
||||||
|
passphrase: None,
|
||||||
|
remove_passphrase: false,
|
||||||
|
}));
|
||||||
|
assert!(words.contains("kept in sync by Dropbox"), "{words}");
|
||||||
|
assert!(words.contains("one computer only"), "{words}");
|
||||||
|
assert!(words.contains("available offline"), "{words}");
|
||||||
|
assert!(words.contains("a folder of its own"), "{words}");
|
||||||
|
// A folder no service is known to keep still gets the general words.
|
||||||
|
let plain = home.outside("a-usb-stick");
|
||||||
|
std::fs::create_dir_all(&plain).unwrap();
|
||||||
|
let words = said(home.admin(Request::BackupSetup {
|
||||||
|
id: "acme".into(),
|
||||||
|
folder: Some(plain.display().to_string()),
|
||||||
|
passphrase: None,
|
||||||
|
remove_passphrase: false,
|
||||||
|
}));
|
||||||
|
assert!(
|
||||||
|
words.contains("If this folder is kept in sync by a service"),
|
||||||
|
"{words}"
|
||||||
|
);
|
||||||
|
assert!(words.contains("one computer only"), "{words}");
|
||||||
|
// And the window shows the same, under the status.
|
||||||
|
let standing = match home.admin(Request::BackupStatus { id: "acme".into() }) {
|
||||||
|
Response::BackupStatus(st) => st,
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
};
|
||||||
|
let lines = ledger_host::commands::backup_words(&standing).join(" | ");
|
||||||
|
assert!(lines.contains("one computer only"), "{lines}");
|
||||||
|
assert!(server.close().success());
|
||||||
|
}
|
||||||
@@ -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, &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,32 @@ 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!(
|
// (The test's own stall file went with the lift.)
|
||||||
!shim.join("resumed").exists(),
|
let changed = |before: &BTreeMap<String, (u64, String)>,
|
||||||
"a git went on after the close was answered"
|
now: &BTreeMap<String, (u64, String)>| {
|
||||||
);
|
moved(before, now)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|m| !m.contains("slow-backup"))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
};
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
moved(&at_close, &tree_of(&home.book_dir(A))),
|
changed(&at_close, &tree_of(&home.book_dir(A))),
|
||||||
Vec::<String>::new()
|
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
|
// 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 +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,
|
/// 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 +1292,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 +1302,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 +1699,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 +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:?}"),
|
Response::BackedUp { targets, .. } => assert!(targets[0].problem.is_none(), "{targets:?}"),
|
||||||
other => panic!("{other:?}"),
|
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
|
/// 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,
|
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 +1767,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 +1874,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 +1886,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 +2373,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 +2401,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 +2426,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 +2444,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 +2464,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 +2474,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 +2502,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()
|
||||||
@@ -2853,8 +2531,14 @@ fn a_close_stops_a_running_backup_call_and_says_so() {
|
|||||||
&& r.get("why") == Some(&json!("asked"))),
|
&& r.get("why") == Some(&json!("asked"))),
|
||||||
"{record:?}"
|
"{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!(
|
assert!(
|
||||||
!record
|
!record[stopped_at..]
|
||||||
.iter()
|
.iter()
|
||||||
.any(|r| r.get("why") == Some(&json!("asked"))
|
.any(|r| r.get("why") == Some(&json!("asked"))
|
||||||
&& r.get("kind") != Some(&json!("stopped"))),
|
&& r.get("kind") != Some(&json!("stopped"))),
|
||||||
@@ -3130,6 +2814,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 +2857,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 +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
|
/// 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 +3118,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 +3167,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 +3279,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 +3310,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() });
|
||||||
|
|||||||
@@ -887,7 +887,7 @@ impl Books {
|
|||||||
/// Every file under `dir`, by path relative to it, with the SHA-256 of its
|
/// 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:
|
/// contents, leaving out what a call writes by design whatever the call:
|
||||||
/// the access log (every call is recorded), the viewer's side channel
|
/// 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
|
/// and on their way in (`exports/`, `uploads/`), and SQLite's -wal and
|
||||||
/// -shm files (it moves pages between them on its own).
|
/// -shm files (it moves pages between them on its own).
|
||||||
pub fn book_files(dir: &Path) -> std::collections::BTreeMap<PathBuf, String> {
|
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()
|
.next()
|
||||||
.map(|c| c.as_os_str().to_string_lossy().into_owned())
|
.map(|c| c.as_os_str().to_string_lossy().into_owned())
|
||||||
.unwrap_or_default();
|
.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 == "access.jsonl"
|
||||||
|| name.ends_with("-wal")
|
|| name.ends_with("-wal")
|
||||||
|| name.ends_with("-shm")
|
|| name.ends_with("-shm")
|
||||||
|
|||||||
@@ -408,15 +408,21 @@ fn format_lines(dir: &Path) -> usize {
|
|||||||
.count()
|
.count()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// git, on the books' own backup repository: what it said.
|
/// The books' own local backup, proven whole and built in a scratch folder:
|
||||||
fn archive_git(dir: &Path, args: &[&str]) -> String {
|
/// the books as they were backed up.
|
||||||
let out = Command::new("git")
|
fn local_backup(dir: &Path) -> PathBuf {
|
||||||
.arg(format!("--git-dir={}", dir.join("archive.git").display()))
|
use ledger_store::backup::{Ctx, find, verify_found};
|
||||||
.args(args)
|
let scratch = dir.join("scratch-local-backup");
|
||||||
.output()
|
let _ = std::fs::remove_dir_all(&scratch);
|
||||||
.unwrap();
|
let found = find(
|
||||||
assert!(out.status.success(), "{out:?}");
|
&dir.join(ledger_store::backup::LOCAL_DIR),
|
||||||
String::from_utf8(out.stdout).unwrap()
|
None,
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.expect("a local backup is there");
|
||||||
|
verify_found(&found, &scratch, &Ctx::new())
|
||||||
|
.expect("it proves whole")
|
||||||
|
.tree
|
||||||
}
|
}
|
||||||
|
|
||||||
fn a_setting() -> Value {
|
fn a_setting() -> Value {
|
||||||
@@ -542,7 +548,7 @@ fn format_upgrade_waits_for_consent() {
|
|||||||
);
|
);
|
||||||
assert!(!shown.contains(wrong), "the passphrase was shown: {shown}");
|
assert!(!shown.contains(wrong), "the passphrase was shown: {shown}");
|
||||||
assert!(
|
assert!(
|
||||||
!dir.join("archive.git").exists(),
|
!dir.join(ledger_store::backup::LOCAL_DIR).exists(),
|
||||||
"no backup before consent"
|
"no backup before consent"
|
||||||
);
|
);
|
||||||
assert_eq!(format_lines(&dir), 0);
|
assert_eq!(format_lines(&dir), 0);
|
||||||
@@ -585,17 +591,14 @@ fn format_upgrade_waits_for_consent() {
|
|||||||
let after = journal(&dir);
|
let after = journal(&dir);
|
||||||
assert!(after.starts_with(&before));
|
assert!(after.starts_with(&before));
|
||||||
assert_eq!(format_lines(&dir), 1, "the format moved once");
|
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!(
|
assert_eq!(
|
||||||
archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.trim())]).as_bytes(),
|
std::fs::read(backup.join("journal.jsonl")).unwrap(),
|
||||||
before.as_slice(),
|
before.as_slice(),
|
||||||
"the backup holds the books as they were"
|
"the backup holds the books as they were"
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
archive_git(
|
std::fs::read_to_string(backup.join("keys").join("legacy.key")).unwrap(),
|
||||||
&dir,
|
|
||||||
&["show", &format!("{}:keys/legacy.key", backup.trim())]
|
|
||||||
),
|
|
||||||
"ab".repeat(32),
|
"ab".repeat(32),
|
||||||
"and their key"
|
"and their key"
|
||||||
);
|
);
|
||||||
@@ -801,19 +804,18 @@ fn books_p2_served_cut_over_whole() {
|
|||||||
2,
|
2,
|
||||||
"P2's declaration, then the upgrade's"
|
"P2's declaration, then the upgrade's"
|
||||||
);
|
);
|
||||||
let backup = archive_git(&dir, &["rev-parse", "HEAD"]);
|
let backup = local_backup(&dir);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.trim())]).as_bytes(),
|
std::fs::read(backup.join("journal.jsonl")).unwrap(),
|
||||||
waiting.as_slice(),
|
waiting.as_slice(),
|
||||||
"the backup holds the books as they were"
|
"the backup holds the books as they were"
|
||||||
);
|
);
|
||||||
for kept in ["keys/legacy.key", "vault/tin-1.bin", "vault/tin-3.bin"] {
|
for kept in ["keys/legacy.key", "vault/tin-1.bin", "vault/tin-3.bin"] {
|
||||||
let out = Command::new("git")
|
assert_eq!(
|
||||||
.arg(format!("--git-dir={}", dir.join("archive.git").display()))
|
std::fs::read(backup.join(kept)).unwrap(),
|
||||||
.args(["show", &format!("{}:{kept}", backup.trim())])
|
std::fs::read(dir.join(kept)).unwrap(),
|
||||||
.output()
|
"{kept}"
|
||||||
.unwrap();
|
);
|
||||||
assert_eq!(out.stdout, std::fs::read(dir.join(kept)).unwrap(), "{kept}");
|
|
||||||
}
|
}
|
||||||
assert_eq!(figures(&mut a), before, "the upgrade moves no figure");
|
assert_eq!(figures(&mut a), before, "the upgrade moves no figure");
|
||||||
|
|
||||||
|
|||||||
@@ -2655,6 +2655,20 @@ fn the_commands_given_run_as_the_agents_own_token() {
|
|||||||
a.end();
|
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]
|
#[test]
|
||||||
fn a_backup_is_restored_from_the_command_line() {
|
fn a_backup_is_restored_from_the_command_line() {
|
||||||
let home = Home::new("restore");
|
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}");
|
assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}");
|
||||||
let head = s["head_seq"].as_u64().unwrap();
|
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();
|
let backup = backup.to_str().unwrap();
|
||||||
// Previewed, and not done without a yes.
|
// Previewed, and not done without a yes.
|
||||||
let out = home.books(&["restore", backup, "--id", "copy"]);
|
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"),
|
String::from_utf8_lossy(&out.stderr).contains("already books called"),
|
||||||
"{out:?}"
|
"{out:?}"
|
||||||
);
|
);
|
||||||
// A repository named otherwise: restored as the books it holds, by
|
// A folder named otherwise: restored as the books it holds, by default
|
||||||
// default (here: over those, refused), said.
|
// (here: over those, refused), said.
|
||||||
let renamed = home.dir.path().join("disk").join("fernhill-backup.git");
|
let renamed = home.dir.path().join("fernhill-backup");
|
||||||
let out = Command::new("git")
|
copy_folder(&disk.join("wanderbooks-acme"), &renamed);
|
||||||
.args(["clone", "-q", "--bare"])
|
|
||||||
.arg(backup)
|
|
||||||
.arg(&renamed)
|
|
||||||
.output()
|
|
||||||
.unwrap();
|
|
||||||
assert!(out.status.success(), "{out:?}");
|
|
||||||
let out = home.books(&["restore", renamed.to_str().unwrap(), "--yes"]);
|
let out = home.books(&["restore", renamed.to_str().unwrap(), "--yes"]);
|
||||||
assert!(
|
assert!(
|
||||||
String::from_utf8_lossy(&out.stderr).contains("already books called \"acme\""),
|
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\""),
|
said.contains("It is a backup of the books \"acme\""),
|
||||||
"{out:?}"
|
"{out:?}"
|
||||||
);
|
);
|
||||||
assert!(said.contains("--id acme"), "{out:?}");
|
assert!(
|
||||||
// A repository whose name is no id: still restored as its books.
|
said.contains("They were backed up as \"acme\"; they come back as \"other\""),
|
||||||
let odd = home.dir.path().join("disk").join("Fernhill_Backup.git");
|
"{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();
|
std::fs::rename(&renamed, &odd).unwrap();
|
||||||
let out = home.books(&["restore", odd.to_str().unwrap(), "--yes"]);
|
let out = home.books(&["restore", odd.to_str().unwrap(), "--yes"]);
|
||||||
assert!(
|
assert!(
|
||||||
@@ -2738,7 +2749,7 @@ fn a_backup_is_restored_from_the_command_line() {
|
|||||||
String::from_utf8_lossy(&out.stdout).contains("Restored as \"copy\""),
|
String::from_utf8_lossy(&out.stdout).contains("Restored as \"copy\""),
|
||||||
"{out:?}"
|
"{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).
|
// given no id (the books it holds are replaced).
|
||||||
post_one(&mut a, 2).unwrap();
|
post_one(&mut a, 2).unwrap();
|
||||||
let out = home.books(&["restore", renamed.to_str().unwrap(), "--replace", "--yes"]);
|
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"),
|
String::from_utf8_lossy(&out.stdout).contains("Backed up to the backup folder"),
|
||||||
"{out:?}"
|
"{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.
|
// 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"]);
|
let out = home.books(&["back-up", "acme"]);
|
||||||
assert_eq!(out.status.code(), Some(1), "{out:?}");
|
assert_eq!(out.status.code(), Some(1), "{out:?}");
|
||||||
assert!(
|
assert!(
|
||||||
@@ -2925,7 +2936,7 @@ fn books_are_backed_up_now_from_the_command_line() {
|
|||||||
);
|
);
|
||||||
let out = home.books(&["back-up", "acme", "--new-disk"]);
|
let out = home.books(&["back-up", "acme", "--new-disk"]);
|
||||||
assert!(out.status.success(), "{out:?}");
|
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();
|
a.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
/// WB-pkg-4: a backup is plain files the program writes itself, so no
|
||||||
/// manager fetches it; nothing carries a git of its own.
|
/// package depends on another program for it and none carries one.
|
||||||
#[test]
|
#[test]
|
||||||
fn the_linux_packages_depend_on_git_and_none_carries_one() {
|
fn no_package_depends_on_another_program_for_backups() {
|
||||||
let packager = read("deploy/packaging/packager.toml");
|
let word = |text: &str| {
|
||||||
assert_eq!(
|
text.to_lowercase()
|
||||||
packager.matches("\"git\"").count(),
|
.split(|c: char| !c.is_ascii_alphanumeric())
|
||||||
2,
|
.any(|w| w == "git")
|
||||||
"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'"));
|
|
||||||
for file in [
|
for file in [
|
||||||
|
"deploy/packaging/packager.toml",
|
||||||
|
"deploy/packaging/aur/PKGBUILD",
|
||||||
|
"crates/ledger-cli/Cargo.toml",
|
||||||
"deploy/packaging/windows/wanderbooks.nsi",
|
"deploy/packaging/windows/wanderbooks.nsi",
|
||||||
"deploy/packaging/macos/build-macos.sh",
|
"deploy/packaging/macos/build-macos.sh",
|
||||||
] {
|
] {
|
||||||
let text = read(file).to_lowercase();
|
let text = read(file);
|
||||||
assert!(
|
// (Cargo.toml may name a git *dependency* of the build, never a
|
||||||
!text.contains("mingit") && !text.contains("git.exe"),
|
// package requirement.)
|
||||||
"{file} bundles a git"
|
let checked: String = text
|
||||||
);
|
.lines()
|
||||||
|
.filter(|l| !l.contains("git ="))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
assert!(!word(&checked), "{file} depends on, or bundles, a git");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -425,14 +425,14 @@ pub static KEYS: &[Key] = &[
|
|||||||
toml: ("backup", "git_remote"),
|
toml: ("backup", "git_remote"),
|
||||||
kind: Kind::Repository,
|
kind: Kind::Repository,
|
||||||
sensitivity: Sensitivity::Public,
|
sensitivity: Sensitivity::Public,
|
||||||
doc: "A private repository the books back themselves up to (plan D-30): its address as its host shows it for cloning, over ssh or https (such as https://host/owner/books), or a path on this computer. Unset: none.",
|
doc: "No longer used (D-91). Older books name a private repository here for the kind of backup that is no longer made: they open and work as ever, nothing is read from or sent to it, and the backup status says so. Choose backup.folder instead. Unset: none.",
|
||||||
},
|
},
|
||||||
Key {
|
Key {
|
||||||
name: "backup.folder",
|
name: "backup.folder",
|
||||||
toml: ("backup", "folder"),
|
toml: ("backup", "folder"),
|
||||||
kind: Kind::Folder,
|
kind: Kind::Folder,
|
||||||
sensitivity: Sensitivity::Public,
|
sensitivity: Sensitivity::Public,
|
||||||
doc: "A folder the books back themselves up to as well (D-30): an absolute path, an external disk or a synced folder; the backup is a repository in it named for the book. Unset: none.",
|
doc: "The folder the books back themselves up to (D-91): an absolute path, another disk or a folder a sync service keeps (Dropbox, iCloud, OneDrive, Google Drive); the backup is a folder in it named for the books, made of files that are only ever added. Unset: none.",
|
||||||
},
|
},
|
||||||
// P4b S4.2: invoicing, bills and the company's contact details.
|
// P4b S4.2: invoicing, bills and the company's contact details.
|
||||||
Key {
|
Key {
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ const CHECKED_FLOOR: usize = 300;
|
|||||||
/// Clauses passing only through the declared or external free-text
|
/// Clauses passing only through the declared or external free-text
|
||||||
/// branch. Edit this constant, on purpose, in the same commit that
|
/// branch. Edit this constant, on purpose, in the same commit that
|
||||||
/// changes the count.
|
/// changes the count.
|
||||||
const FREE_TEXT_COUNT: usize = 56;
|
const FREE_TEXT_COUNT: usize = 54;
|
||||||
|
|
||||||
fn strip_comment(line: &str) -> Option<String> {
|
fn strip_comment(line: &str) -> Option<String> {
|
||||||
let t = line.trim_start();
|
let t = line.trim_start();
|
||||||
|
|||||||
@@ -37,6 +37,10 @@ rust_decimal = "1"
|
|||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
zeroize = "1"
|
zeroize = "1"
|
||||||
|
# The system's own folder and file dialogs for "Back up to..." and "Save a
|
||||||
|
# backup...": the portal on Linux, the native ones on Windows and macOS. The
|
||||||
|
# window shows nothing but what the system's dialog gives back, a path.
|
||||||
|
rfd = { version = "0.17", default-features = false, features = ["xdg-portal"] }
|
||||||
# The dock: a terminal emulator over a PTY (ConPTY on Windows), P11b
|
# The dock: a terminal emulator over a PTY (ConPTY on Windows), P11b
|
||||||
alacritty_terminal = "0.26"
|
alacritty_terminal = "0.26"
|
||||||
|
|
||||||
|
|||||||
@@ -130,11 +130,46 @@ 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the books' backups stand, in words, for the Backups window.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct BackupState {
|
||||||
|
/// What to tell the person, a line each (when it last backed up, whether
|
||||||
|
/// it was proven restorable, a disk that isn't connected).
|
||||||
|
pub lines: Vec<String>,
|
||||||
|
/// The backup folder chosen, if one is.
|
||||||
|
pub folder: Option<String>,
|
||||||
|
/// Protected by a passphrase.
|
||||||
|
pub sealed: bool,
|
||||||
|
/// The folder holds a longer history of these books than they have
|
||||||
|
/// now (the books were restored from an older backup): a new backup set
|
||||||
|
/// can be started beside the old one.
|
||||||
|
pub ahead: bool,
|
||||||
|
}
|
||||||
|
|
||||||
/// A restore previewed: what it would do, and what it is of (INVARIANT 3).
|
/// 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/).
|
||||||
@@ -434,6 +469,31 @@ pub trait Owner: Send + Sync {
|
|||||||
fn new_books(&self, id: &str, currency: &str) -> Result<String, String>;
|
fn new_books(&self, id: &str, currency: &str) -> Result<String, String>;
|
||||||
/// Back the books `book` up now.
|
/// Back the books `book` up now.
|
||||||
fn back_up_now(&self, book: &str) -> Result<Vec<String>, String>;
|
fn back_up_now(&self, book: &str) -> Result<Vec<String>, String>;
|
||||||
|
/// Start a new backup set beside the old one in the backup folder and
|
||||||
|
/// back the books up to it (their history is the beginning of the old
|
||||||
|
/// set's): the old set is never touched.
|
||||||
|
fn start_new_backup_set(&self, _book: &str) -> Result<Vec<String>, String> {
|
||||||
|
Err("not here".into())
|
||||||
|
}
|
||||||
|
/// How the books `book`'s backups stand. Blocks.
|
||||||
|
fn backup_state(&self, _book: &str) -> Result<BackupState, String> {
|
||||||
|
Err("not here".into())
|
||||||
|
}
|
||||||
|
/// Set the books' backups up: the backup folder, and the passphrase
|
||||||
|
/// (set, or taken off). What was done, a line each. Blocks.
|
||||||
|
fn set_up_backups(
|
||||||
|
&self,
|
||||||
|
_book: &str,
|
||||||
|
_folder: Option<String>,
|
||||||
|
_passphrase: Option<Secret>,
|
||||||
|
_remove_passphrase: bool,
|
||||||
|
) -> Result<Vec<String>, String> {
|
||||||
|
Err("not here".into())
|
||||||
|
}
|
||||||
|
/// Save a backup of the books as one file at `file`. Blocks.
|
||||||
|
fn save_backup(&self, _book: &str, _file: &str) -> Result<Vec<String>, String> {
|
||||||
|
Err("not here".into())
|
||||||
|
}
|
||||||
/// Preview restoring the backup at `source` (as `id`, else its own
|
/// Preview restoring the backup at `source` (as `id`, else its own
|
||||||
/// books' id), replacing the books of that id or not.
|
/// books' id), replacing the books of that id or not.
|
||||||
fn plan_restore(
|
fn plan_restore(
|
||||||
@@ -441,6 +501,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>;
|
||||||
@@ -574,12 +635,64 @@ enum Dialog {
|
|||||||
None,
|
None,
|
||||||
/// "New books…": their id and currency.
|
/// "New books…": their id and currency.
|
||||||
NewBooks { id: String, currency: String },
|
NewBooks { id: String, currency: String },
|
||||||
|
/// "Backups…": the folder, the passphrase, and how they stand.
|
||||||
|
Backups(Box<BackupForm>),
|
||||||
/// "Restore…": the backup, then its preview.
|
/// "Restore…": the backup, then its preview.
|
||||||
Restore(Box<RestoreForm>),
|
Restore(Box<RestoreForm>),
|
||||||
/// The format upgrade: the go-ahead, with the owner passphrase.
|
/// The format upgrade: the go-ahead, with the owner passphrase.
|
||||||
Upgrade(Box<UpgradeForm>),
|
Upgrade(Box<UpgradeForm>),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The Backups window: how they stand, the folder to choose, the passphrase
|
||||||
|
/// to offer.
|
||||||
|
struct BackupForm {
|
||||||
|
/// What the server said of them, once it has.
|
||||||
|
state: Option<Result<BackupState, String>>,
|
||||||
|
/// The reading under way.
|
||||||
|
loading: Option<Receiver<Result<BackupState, String>>>,
|
||||||
|
/// The folder, as typed or chosen.
|
||||||
|
folder: String,
|
||||||
|
/// Whether a passphrase is being set (or changed).
|
||||||
|
protect: bool,
|
||||||
|
/// The passphrase, twice (wiped when the form is dropped).
|
||||||
|
pass: String,
|
||||||
|
again: String,
|
||||||
|
/// Why the last try was refused, or what it did.
|
||||||
|
problem: Option<String>,
|
||||||
|
said: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BackupForm {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
state: None,
|
||||||
|
loading: None,
|
||||||
|
folder: String::new(),
|
||||||
|
protect: false,
|
||||||
|
pass: String::new(),
|
||||||
|
again: String::new(),
|
||||||
|
problem: None,
|
||||||
|
said: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for BackupForm {
|
||||||
|
/// What was typed and not handed over is wiped from memory.
|
||||||
|
fn drop(&mut self) {
|
||||||
|
zeroize::Zeroize::zeroize(&mut self.pass);
|
||||||
|
zeroize::Zeroize::zeroize(&mut self.again);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The words a person is told when setting a passphrase: what it does, and
|
||||||
|
/// that it cannot be recovered (D-92).
|
||||||
|
/// What the first line of a restore that is not of the newest backup begins
|
||||||
|
/// with (ledger-host `older_backup_words`): the window shows it prominently.
|
||||||
|
pub const OLDER_BACKUP: &str = "NOT THE NEWEST BACKUP";
|
||||||
|
|
||||||
|
pub const PASSPHRASE_WARNING: &str = "Every file in the backup folder is sealed: only this passphrase opens it, and the files say nothing about your books but how many and how big. Your computer keeps the key so backups stay automatic. A forgotten passphrase cannot be recovered, by anyone, and backups made without it before this stay as they were. Write it down somewhere safe.";
|
||||||
|
|
||||||
/// The format upgrade's dialog (INVARIANT 5).
|
/// The format upgrade's dialog (INVARIANT 5).
|
||||||
struct UpgradeForm {
|
struct UpgradeForm {
|
||||||
/// What the books wait for.
|
/// What the books wait for.
|
||||||
@@ -632,6 +745,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 +755,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 {
|
||||||
@@ -907,7 +1030,7 @@ impl OwnerMenu {
|
|||||||
ui.set_min_width(240.0);
|
ui.set_min_width(240.0);
|
||||||
if ui
|
if ui
|
||||||
.button(format!("{} Back up now", icon::CLOUD_ARROW_UP))
|
.button(format!("{} Back up now", icon::CLOUD_ARROW_UP))
|
||||||
.on_hover_text("Back these books up now, to every backup their settings name")
|
.on_hover_text("Back these books up now, to the backup folder")
|
||||||
.clicked()
|
.clicked()
|
||||||
{
|
{
|
||||||
let (o, b) = (owner.clone(), book.clone());
|
let (o, b) = (owner.clone(), book.clone());
|
||||||
@@ -917,6 +1040,39 @@ impl OwnerMenu {
|
|||||||
Box::new(move || o.back_up_now(&b)),
|
Box::new(move || o.back_up_now(&b)),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
if ui
|
||||||
|
.button(format!("{} Backups…", icon::CLOUD_ARROW_UP))
|
||||||
|
.on_hover_text("Choose where these books back up to, protect the backups with a passphrase, and see how they stand")
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
self.dialog = Dialog::Backups(Box::new(BackupForm::new()));
|
||||||
|
}
|
||||||
|
if ui
|
||||||
|
.button(format!("{} Save a backup…", icon::CLOUD_ARROW_UP))
|
||||||
|
.on_hover_text("Save these books as one backup file to keep or carry")
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
let name = format!(
|
||||||
|
"{}-{}.wbbackup",
|
||||||
|
book,
|
||||||
|
chrono::Local::now().format("%Y-%m-%d")
|
||||||
|
);
|
||||||
|
if let Some(file) = rfd::FileDialog::new()
|
||||||
|
.set_title("Save a backup")
|
||||||
|
.set_file_name(name)
|
||||||
|
.add_filter("Wanderbooks backup", &[backup_extension()])
|
||||||
|
.save_file()
|
||||||
|
{
|
||||||
|
let (o, b) = (owner.clone(), book.clone());
|
||||||
|
let file = file.display().to_string();
|
||||||
|
start = Some((
|
||||||
|
"Save a backup".into(),
|
||||||
|
Effect::Reads,
|
||||||
|
Box::new(move || o.save_backup(&b, &file)),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
ui.close();
|
||||||
|
}
|
||||||
if ui
|
if ui
|
||||||
.button(format!("{} Restore…", icon::CLOCK_COUNTER_CLOCKWISE))
|
.button(format!("{} Restore…", icon::CLOCK_COUNTER_CLOCKWISE))
|
||||||
.on_hover_text("Bring back books from a backup, proven whole first")
|
.on_hover_text("Bring back books from a backup, proven whole first")
|
||||||
@@ -1093,6 +1249,18 @@ impl OwnerMenu {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
Dialog::Backups(form) => {
|
||||||
|
backups_dialog(
|
||||||
|
ctx,
|
||||||
|
self.scope.unwrap_or(egui::Id::NULL),
|
||||||
|
form,
|
||||||
|
owner,
|
||||||
|
book,
|
||||||
|
&jobs,
|
||||||
|
&mut close,
|
||||||
|
&mut run,
|
||||||
|
);
|
||||||
|
}
|
||||||
Dialog::Restore(form) => {
|
Dialog::Restore(form) => {
|
||||||
if let Some((rx, asked)) = &form.planning
|
if let Some((rx, asked)) = &form.planning
|
||||||
&& let Ok(planned) = rx.try_recv()
|
&& let Ok(planned) = rx.try_recv()
|
||||||
@@ -1114,7 +1282,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 +1290,46 @@ 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| {
|
||||||
|
if ui
|
||||||
|
.add_enabled(open, egui::Button::new("Choose a folder…"))
|
||||||
|
.clicked()
|
||||||
|
&& let Some(p) = rfd::FileDialog::new()
|
||||||
|
.set_title("Choose the backup folder")
|
||||||
|
.pick_folder()
|
||||||
|
{
|
||||||
|
form.source = p.display().to_string();
|
||||||
|
form.plan = None;
|
||||||
|
form.problem = None;
|
||||||
|
}
|
||||||
|
if ui
|
||||||
|
.add_enabled(open, egui::Button::new("Choose a file…"))
|
||||||
|
.clicked()
|
||||||
|
&& let Some(p) = rfd::FileDialog::new()
|
||||||
|
.set_title("Choose a backup file")
|
||||||
|
.add_filter("Wanderbooks backup", &[backup_extension()])
|
||||||
|
.pick_file()
|
||||||
|
{
|
||||||
|
form.source = p.display().to_string();
|
||||||
|
form.plan = None;
|
||||||
|
form.problem = None;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
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
|
||||||
@@ -1153,9 +1358,18 @@ impl OwnerMenu {
|
|||||||
if let Some(plan) = &form.plan {
|
if let Some(plan) = &form.plan {
|
||||||
ui.separator();
|
ui.separator();
|
||||||
for line in &plan.lines {
|
for line in &plan.lines {
|
||||||
|
// A restore that is not of the newest backup
|
||||||
|
// says so first and in the warning colour.
|
||||||
|
if line.starts_with(OLDER_BACKUP) {
|
||||||
|
ui.colored_label(
|
||||||
|
crate::theme::pal(ui.ctx()).warning,
|
||||||
|
egui::RichText::new(line).strong(),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
ui.label(line);
|
ui.label(line);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
let planning = form.planning.is_some();
|
let planning = form.planning.is_some();
|
||||||
match &form.plan {
|
match &form.plan {
|
||||||
@@ -1164,6 +1378,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 +1390,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();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -1220,6 +1436,184 @@ impl OwnerMenu {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The extension of a backup file, without the dot.
|
||||||
|
fn backup_extension() -> &'static str {
|
||||||
|
ledger_store::backup::FILE_EXTENSION
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Backups window: how the books' backups stand, the folder (chosen with
|
||||||
|
/// the system's folder dialog, or typed), the passphrase offer (off unless
|
||||||
|
/// asked for, with its warning), and a go.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn backups_dialog(
|
||||||
|
ctx: &egui::Context,
|
||||||
|
scope: egui::Id,
|
||||||
|
form: &mut BackupForm,
|
||||||
|
owner: &Arc<dyn Owner>,
|
||||||
|
book: &str,
|
||||||
|
jobs: &crate::jobs::Spawner,
|
||||||
|
close: &mut bool,
|
||||||
|
run: &mut Option<Start>,
|
||||||
|
) {
|
||||||
|
let p = crate::theme::pal(ctx);
|
||||||
|
// Read how they stand, once, and again after a change.
|
||||||
|
if form.state.is_none() && form.loading.is_none() {
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
let (o, b, c) = (owner.clone(), book.to_string(), ctx.clone());
|
||||||
|
let started = jobs.spawn("backup state", crate::jobs::Hold::Free, move |stop| {
|
||||||
|
if stop.requested() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let _ = tx.send(o.backup_state(&b));
|
||||||
|
c.request_repaint();
|
||||||
|
});
|
||||||
|
if started {
|
||||||
|
form.loading = Some(rx);
|
||||||
|
} else {
|
||||||
|
form.state = Some(Err("the system gave no thread for it".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(rx) = &form.loading
|
||||||
|
&& let Ok(state) = rx.try_recv()
|
||||||
|
{
|
||||||
|
form.loading = None;
|
||||||
|
if let Ok(s) = &state
|
||||||
|
&& form.folder.is_empty()
|
||||||
|
{
|
||||||
|
form.folder = s.folder.clone().unwrap_or_default();
|
||||||
|
}
|
||||||
|
form.state = Some(state);
|
||||||
|
}
|
||||||
|
egui::Modal::new(scope.with("owner-backups")).show(ctx, |ui| {
|
||||||
|
ui.set_max_width(540.0);
|
||||||
|
ui.heading("Backups");
|
||||||
|
ui.add_space(4.0);
|
||||||
|
match &form.state {
|
||||||
|
None => {
|
||||||
|
ui.label("Reading how the backups stand…");
|
||||||
|
}
|
||||||
|
Some(Err(why)) => {
|
||||||
|
ui.colored_label(p.warning, why);
|
||||||
|
}
|
||||||
|
Some(Ok(state)) => {
|
||||||
|
for line in &state.lines {
|
||||||
|
ui.label(line);
|
||||||
|
}
|
||||||
|
if state.ahead
|
||||||
|
&& ui
|
||||||
|
.button("Start a new backup set here")
|
||||||
|
.on_hover_text("The old set stays in the folder, untouched; these books back up to a new one beside it")
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
let (o, b) = (owner.clone(), book.to_string());
|
||||||
|
*run = Some((
|
||||||
|
"Backups".into(),
|
||||||
|
Effect::Changes("Starting a new backup set"),
|
||||||
|
Box::new(move || o.start_new_backup_set(&b)),
|
||||||
|
));
|
||||||
|
*close = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let sealed = matches!(&form.state, Some(Ok(s)) if s.sealed);
|
||||||
|
ui.separator();
|
||||||
|
ui.label("Back up to this folder: another disk, or one your cloud drive (Dropbox, iCloud, OneDrive, Google Drive) keeps in sync.");
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.add(
|
||||||
|
egui::TextEdit::singleline(&mut form.folder)
|
||||||
|
.desired_width(330.0)
|
||||||
|
.hint_text("choose a folder"),
|
||||||
|
);
|
||||||
|
if ui.button("Choose a folder…").clicked()
|
||||||
|
&& let Some(folder) = rfd::FileDialog::new()
|
||||||
|
.set_title("Choose the backup folder")
|
||||||
|
.pick_folder()
|
||||||
|
{
|
||||||
|
form.folder = folder.display().to_string();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.add_space(4.0);
|
||||||
|
if sealed {
|
||||||
|
ui.label("These backups are protected by a passphrase.");
|
||||||
|
}
|
||||||
|
ui.checkbox(
|
||||||
|
&mut form.protect,
|
||||||
|
if sealed {
|
||||||
|
"Change the passphrase"
|
||||||
|
} else {
|
||||||
|
"Protect the backups with a passphrase (optional)"
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if form.protect {
|
||||||
|
ui.label(PASSPHRASE_WARNING);
|
||||||
|
ui.add(
|
||||||
|
egui::TextEdit::singleline(&mut form.pass)
|
||||||
|
.password(true)
|
||||||
|
.hint_text("passphrase (at least 12 characters)")
|
||||||
|
.desired_width(f32::INFINITY),
|
||||||
|
);
|
||||||
|
ui.add(
|
||||||
|
egui::TextEdit::singleline(&mut form.again)
|
||||||
|
.password(true)
|
||||||
|
.hint_text("the same passphrase again")
|
||||||
|
.desired_width(f32::INFINITY),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(why) = &form.problem {
|
||||||
|
ui.colored_label(p.warning, why);
|
||||||
|
}
|
||||||
|
for line in &form.said {
|
||||||
|
ui.label(line);
|
||||||
|
}
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
let folder = form.folder.trim().to_string();
|
||||||
|
let known = matches!(&form.state, Some(Ok(s)) if s.folder.as_deref() == Some(folder.as_str()));
|
||||||
|
let pass_ready = !form.protect
|
||||||
|
|| (form.pass.chars().count() >= 12 && form.pass == form.again);
|
||||||
|
let wants = (!folder.is_empty() && !known) || form.protect;
|
||||||
|
if ui
|
||||||
|
.add_enabled(wants && pass_ready, egui::Button::new("Save these choices"))
|
||||||
|
.on_disabled_hover_text(
|
||||||
|
"Choose a folder, or set a passphrase of at least 12 characters, typed twice the same",
|
||||||
|
)
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
let (o, b) = (owner.clone(), book.to_string());
|
||||||
|
let pass = form
|
||||||
|
.protect
|
||||||
|
.then(|| Secret(std::mem::take(&mut form.pass)))
|
||||||
|
.filter(|s| !s.0.is_empty());
|
||||||
|
zeroize::Zeroize::zeroize(&mut form.again);
|
||||||
|
form.protect = false;
|
||||||
|
let folder = Some(folder).filter(|f| !f.is_empty() && !known);
|
||||||
|
*run = Some((
|
||||||
|
"Backups".into(),
|
||||||
|
Effect::Changes("Setting up the backups"),
|
||||||
|
Box::new(move || o.set_up_backups(&b, folder, pass, false)),
|
||||||
|
));
|
||||||
|
*close = true;
|
||||||
|
}
|
||||||
|
if sealed
|
||||||
|
&& ui
|
||||||
|
.button("Take the passphrase off")
|
||||||
|
.on_hover_text("Later backups are written without protection; earlier sealed ones stay sealed")
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
let (o, b) = (owner.clone(), book.to_string());
|
||||||
|
*run = Some((
|
||||||
|
"Backups".into(),
|
||||||
|
Effect::Changes("Setting up the backups"),
|
||||||
|
Box::new(move || o.set_up_backups(&b, None, None, true)),
|
||||||
|
));
|
||||||
|
*close = true;
|
||||||
|
}
|
||||||
|
if ui.button("Close").clicked() {
|
||||||
|
*close = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/// The format upgrade's dialog (INVARIANT 5): what it is, the owner
|
/// The format upgrade's dialog (INVARIANT 5): what it is, the owner
|
||||||
/// passphrase, and the go-ahead or not now.
|
/// passphrase, and the go-ahead or not now.
|
||||||
fn upgrade_dialog(
|
fn upgrade_dialog(
|
||||||
|
|||||||
@@ -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)),
|
||||||
@@ -66,6 +68,35 @@ impl Owner for Fake {
|
|||||||
));
|
));
|
||||||
Ok(vec![format!("Restored as \"{}\".", plan.id)])
|
Ok(vec![format!("Restored as \"{}\".", plan.id)])
|
||||||
}
|
}
|
||||||
|
fn backup_state(&self, book: &str) -> Result<ledger_gui::owner::BackupState, String> {
|
||||||
|
self.said(format!("state {book}"));
|
||||||
|
Ok(ledger_gui::owner::BackupState {
|
||||||
|
lines: vec![
|
||||||
|
"Not backed up: no backup folder is chosen yet.".into(),
|
||||||
|
"Not protected by a passphrase.".into(),
|
||||||
|
],
|
||||||
|
folder: None,
|
||||||
|
sealed: false,
|
||||||
|
ahead: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn set_up_backups(
|
||||||
|
&self,
|
||||||
|
book: &str,
|
||||||
|
folder: Option<String>,
|
||||||
|
passphrase: Option<ledger_gui::owner::Secret>,
|
||||||
|
remove: bool,
|
||||||
|
) -> Result<Vec<String>, String> {
|
||||||
|
self.said(format!(
|
||||||
|
"set up {book} {folder:?} {} {remove}",
|
||||||
|
if passphrase.is_some() {
|
||||||
|
"sealed"
|
||||||
|
} else {
|
||||||
|
"plain"
|
||||||
|
}
|
||||||
|
));
|
||||||
|
Ok(vec!["The backup folder is chosen.".into()])
|
||||||
|
}
|
||||||
fn connect(&self, agent: Agent, book: &str) -> Result<Vec<String>, String> {
|
fn connect(&self, agent: Agent, book: &str) -> Result<Vec<String>, String> {
|
||||||
self.said(format!("connect {agent:?} {book}"));
|
self.said(format!("connect {agent:?} {book}"));
|
||||||
Ok(vec!["Claude Code reaches the books.".into()])
|
Ok(vec!["Claude Code reaches the books.".into()])
|
||||||
@@ -220,7 +251,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 +261,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 +271,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 +338,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 +421,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();
|
||||||
@@ -398,3 +429,67 @@ fn screenshots() {
|
|||||||
shot(&mut h, "restore-plan");
|
shot(&mut h, "restore-plan");
|
||||||
h.get_by_label("Cancel").click();
|
h.get_by_label("Cancel").click();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The Backups window (D-91, D-92): how they stand in words, the folder, a
|
||||||
|
/// passphrase offered and off unless asked for, with its warning that a
|
||||||
|
/// forgotten one cannot be recovered; the owner is asked to set up only for
|
||||||
|
/// a folder, or a passphrase of 12 characters typed twice the same.
|
||||||
|
#[test]
|
||||||
|
fn the_backups_window_says_how_they_stand_and_offers_a_passphrase_plainly() {
|
||||||
|
let _alone = alone();
|
||||||
|
let f = fake();
|
||||||
|
let (_dir, _book, b) = books(true);
|
||||||
|
let mut h = harness(b);
|
||||||
|
let start = f.asked.lock().unwrap().len();
|
||||||
|
let page_fields = h
|
||||||
|
.query_all_by_role(egui::accesskit::Role::TextInput)
|
||||||
|
.count();
|
||||||
|
open_menu(&mut h);
|
||||||
|
h.get_by_label_contains("Backups…").click();
|
||||||
|
settle(&mut h, &f, start + 1);
|
||||||
|
assert_eq!(f.asked.lock().unwrap()[start], "state acme");
|
||||||
|
assert!(
|
||||||
|
h.query_by_label_contains("no backup folder is chosen yet")
|
||||||
|
.is_some()
|
||||||
|
);
|
||||||
|
// The passphrase is off, and its offer says what it means only when
|
||||||
|
// asked for.
|
||||||
|
assert!(h.query_by_label_contains("cannot be recovered").is_none());
|
||||||
|
h.get_by_label_contains("Protect the backups with a passphrase")
|
||||||
|
.click();
|
||||||
|
h.run_steps(3);
|
||||||
|
assert!(h.query_by_label_contains("cannot be recovered").is_some());
|
||||||
|
assert!(h.query_by_label_contains("git").is_none());
|
||||||
|
// Nothing is done without a folder or a good passphrase.
|
||||||
|
h.get_all_by_role(egui::accesskit::Role::TextInput)
|
||||||
|
.nth(page_fields)
|
||||||
|
.unwrap()
|
||||||
|
.focus();
|
||||||
|
h.run_steps(2);
|
||||||
|
h.get_all_by_role(egui::accesskit::Role::TextInput)
|
||||||
|
.nth(page_fields)
|
||||||
|
.unwrap()
|
||||||
|
.type_text("/media/disk");
|
||||||
|
h.run_steps(2);
|
||||||
|
for (n, text) in [
|
||||||
|
(0usize, "correct horse battery"),
|
||||||
|
(1, "correct horse battery"),
|
||||||
|
] {
|
||||||
|
h.get_all_by_role(egui::accesskit::Role::PasswordInput)
|
||||||
|
.nth(n)
|
||||||
|
.unwrap()
|
||||||
|
.focus();
|
||||||
|
h.run_steps(2);
|
||||||
|
h.get_all_by_role(egui::accesskit::Role::PasswordInput)
|
||||||
|
.nth(n)
|
||||||
|
.unwrap()
|
||||||
|
.type_text(text);
|
||||||
|
h.run_steps(2);
|
||||||
|
}
|
||||||
|
h.get_by_label("Save these choices").click();
|
||||||
|
settle(&mut h, &f, start + 2);
|
||||||
|
assert_eq!(
|
||||||
|
f.asked.lock().unwrap()[start + 1],
|
||||||
|
"set up acme Some(\"/media/disk\") sealed false"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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> {
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ tokio-util = { version = "0.7", features = ["rt"] }
|
|||||||
rpassword = "7"
|
rpassword = "7"
|
||||||
# Token texts and passphrases are wiped from memory when dropped.
|
# Token texts and passphrases are wiped from memory when dropped.
|
||||||
zeroize = "1"
|
zeroize = "1"
|
||||||
|
chrono = "0.4"
|
||||||
minisign-verify = "0.3.0"
|
minisign-verify = "0.3.0"
|
||||||
# The Claude desktop extension is a zip file (extension.rs).
|
# The Claude desktop extension is a zip file (extension.rs).
|
||||||
zip = { version = "9.0.1", default-features = false, features = ["deflate"] }
|
zip = { version = "9.0.1", default-features = false, features = ["deflate"] }
|
||||||
|
|||||||
@@ -749,7 +749,12 @@ fn books_usage(prog: &str) {
|
|||||||
" {prog} adopt DATA-DIR --id ID [--toml FILE] [--config-json FILE] [--vault DIR --vault-key FILE | --no-vault] [--skip-unknown] [--yes]"
|
" {prog} adopt DATA-DIR --id ID [--toml FILE] [--config-json FILE] [--vault DIR --vault-key FILE | --no-vault] [--skip-unknown] [--yes]"
|
||||||
);
|
);
|
||||||
eprintln!(" {prog} restore BACKUP [--id ID] [--replace] [--yes]");
|
eprintln!(" {prog} restore BACKUP [--id ID] [--replace] [--yes]");
|
||||||
eprintln!(" {prog} back-up ID [--new-disk]");
|
eprintln!(" {prog} back-up ID [--new-disk | --new-set]");
|
||||||
|
eprintln!(" {prog} backup-status ID");
|
||||||
|
eprintln!(
|
||||||
|
" {prog} backup-setup ID [--folder FOLDER] [--passphrase | --remove-passphrase]"
|
||||||
|
);
|
||||||
|
eprintln!(" {prog} backup-save ID FILE");
|
||||||
eprintln!(" {prog} upgrade ID");
|
eprintln!(" {prog} upgrade ID");
|
||||||
eprintln!(" {prog} extract BOOK ATTACHMENT");
|
eprintln!(" {prog} extract BOOK ATTACHMENT");
|
||||||
eprintln!(" {prog} open ID");
|
eprintln!(" {prog} open ID");
|
||||||
@@ -767,10 +772,10 @@ fn books_usage(prog: &str) {
|
|||||||
eprintln!(" create start new, empty books (base currency USD unless given)");
|
eprintln!(" create start new, empty books (base currency USD unless given)");
|
||||||
eprintln!(" adopt copy existing books in, verified; the original is left as it was");
|
eprintln!(" adopt copy existing books in, verified; the original is left as it was");
|
||||||
eprintln!(
|
eprintln!(
|
||||||
" back-up back the books up now to every backup their settings name (--new-disk: the backup folder's disk is new)"
|
" back-up back the books up now to every backup their settings name (--new-disk: the backup folder's disk is new; --new-set: the folder holds a longer history of these books, as after a restore from an older backup, so begin a new set beside it)"
|
||||||
);
|
);
|
||||||
eprintln!(
|
eprintln!(
|
||||||
" restore bring back a backup (a git repository's address, or BOOK.git in the backup folder), proven whole first: as new books, or replacing books (kept in legacy/)"
|
" restore bring back a backup (your backup folder, the folder of one set of books in it, or a backup file), proven whole first: as new books, or replacing books (kept in legacy/)"
|
||||||
);
|
);
|
||||||
eprintln!(
|
eprintln!(
|
||||||
" upgrade give the go-ahead, with the owner passphrase, for books an older wanderbooks wrote to move to this version's journal format (a verified backup with the vault and keys first)"
|
" upgrade give the go-ahead, with the owner passphrase, for books an older wanderbooks wrote to move to this version's journal format (a verified backup with the vault and keys first)"
|
||||||
@@ -779,7 +784,7 @@ fn books_usage(prog: &str) {
|
|||||||
" extract read one attachment's text (a PDF, XLSX or text file) and journal it, one at a time; books an older version filed are read this way after an upgrade"
|
" extract read one attachment's text (a PDF, XLSX or text file) and journal it, one at a time; books an older version filed are read this way after an upgrade"
|
||||||
);
|
);
|
||||||
eprintln!(
|
eprintln!(
|
||||||
" put-aside move the old copies of adopted books (their data folder, their vault and its key, and other paths given: settings file, git history) whole into the legacy folder, once the books hold everything they do, byte for byte; nothing is deleted"
|
" put-aside move the old copies of adopted books (their data folder, their vault and its key, and other paths given: settings file, old history) whole into the legacy folder, once the books hold everything they do, byte for byte; nothing is deleted"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -801,6 +806,10 @@ pub fn books(
|
|||||||
let mut yes = false;
|
let mut yes = false;
|
||||||
let mut replace = false;
|
let mut replace = false;
|
||||||
let mut new_disk = false;
|
let mut new_disk = false;
|
||||||
|
let mut new_set = false;
|
||||||
|
let mut folder: Option<String> = None;
|
||||||
|
let mut ask_passphrase = false;
|
||||||
|
let mut remove_passphrase = false;
|
||||||
let mut args = args.into_iter();
|
let mut args = args.into_iter();
|
||||||
while let Some(arg) = args.next() {
|
while let Some(arg) = args.next() {
|
||||||
if common.take(&arg, &mut args)? {
|
if common.take(&arg, &mut args)? {
|
||||||
@@ -808,6 +817,9 @@ pub fn books(
|
|||||||
}
|
}
|
||||||
let mut value = |what: &str| args.next().ok_or_else(|| format!("{arg} needs {what}"));
|
let mut value = |what: &str| args.next().ok_or_else(|| format!("{arg} needs {what}"));
|
||||||
match arg.as_str() {
|
match arg.as_str() {
|
||||||
|
"--folder" => folder = Some(value("a folder")?),
|
||||||
|
"--passphrase" => ask_passphrase = true,
|
||||||
|
"--remove-passphrase" => remove_passphrase = true,
|
||||||
"--currency" => currency = value("a currency code")?,
|
"--currency" => currency = value("a currency code")?,
|
||||||
"--id" => id = Some(value("an id")?),
|
"--id" => id = Some(value("an id")?),
|
||||||
"--toml" => toml = Some(PathBuf::from(value("a file")?)),
|
"--toml" => toml = Some(PathBuf::from(value("a file")?)),
|
||||||
@@ -818,6 +830,7 @@ pub fn books(
|
|||||||
"--skip-unknown" => skip_unknown = true,
|
"--skip-unknown" => skip_unknown = true,
|
||||||
"--replace" => replace = true,
|
"--replace" => replace = true,
|
||||||
"--new-disk" => new_disk = true,
|
"--new-disk" => new_disk = true,
|
||||||
|
"--new-set" => new_set = true,
|
||||||
"--yes" => yes = true,
|
"--yes" => yes = true,
|
||||||
"--help" | "-h" => {
|
"--help" | "-h" => {
|
||||||
books_usage(prog);
|
books_usage(prog);
|
||||||
@@ -916,8 +929,63 @@ pub fn books(
|
|||||||
id: (*book).to_string(),
|
id: (*book).to_string(),
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
["backup-status", book] => {
|
||||||
|
return match backup_status(&common, book) {
|
||||||
|
Ok(lines) => {
|
||||||
|
for line in lines {
|
||||||
|
println!("{line}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("error: {why}");
|
||||||
|
Err(exit(1))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
["backup-setup", book] => {
|
||||||
|
// A passphrase is typed by a person, at a terminal, twice and
|
||||||
|
// unechoed: never on the command line, where a shell keeps it.
|
||||||
|
let passphrase = if ask_passphrase {
|
||||||
|
match ask_backup_passphrase() {
|
||||||
|
Ok(p) => Some(p),
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("error: {why}");
|
||||||
|
return Err(exit(1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
return match backup_setup(&common, book, folder, passphrase, remove_passphrase) {
|
||||||
|
Ok(lines) => {
|
||||||
|
for line in lines {
|
||||||
|
println!("{line}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("error: {why}");
|
||||||
|
Err(exit(1))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
["backup-save", book, file] => {
|
||||||
|
return match backup_save(&common, book, file) {
|
||||||
|
Ok(lines) => {
|
||||||
|
for line in lines {
|
||||||
|
println!("{line}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("error: {why}");
|
||||||
|
Err(exit(1))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
["back-up", book] => {
|
["back-up", book] => {
|
||||||
return match back_up_now(&common, book, new_disk) {
|
return match back_up_now(&common, book, new_disk, new_set) {
|
||||||
Ok(lines) => {
|
Ok(lines) => {
|
||||||
for line in lines {
|
for line in lines {
|
||||||
println!("{line}");
|
println!("{line}");
|
||||||
@@ -1159,14 +1227,23 @@ fn database_line(b: &admin::BookStatus) -> Option<String> {
|
|||||||
|
|
||||||
/// Back the books `book` up now (the server does it): what came of it, a
|
/// Back the books `book` up now (the server does it): what came of it, a
|
||||||
/// line each; Err when it couldn't be done, or a target didn't take it.
|
/// line each; Err when it couldn't be done, or a target didn't take it.
|
||||||
pub fn back_up_now(common: &Common, book: &str, new_disk: bool) -> Result<Vec<String>, String> {
|
pub fn back_up_now(
|
||||||
match with_server(
|
common: &Common,
|
||||||
common,
|
book: &str,
|
||||||
|
new_disk: bool,
|
||||||
|
new_set: bool,
|
||||||
|
) -> Result<Vec<String>, String> {
|
||||||
|
let request = if new_set {
|
||||||
|
Request::BackUpNewSet {
|
||||||
|
id: book.to_string(),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
Request::BackUpNow {
|
Request::BackUpNow {
|
||||||
id: book.to_string(),
|
id: book.to_string(),
|
||||||
new_disk,
|
new_disk,
|
||||||
},
|
}
|
||||||
)? {
|
};
|
||||||
|
match with_server(common, request)? {
|
||||||
Response::BackedUp { head_seq, targets } => {
|
Response::BackedUp { head_seq, targets } => {
|
||||||
let lines = backed_up_lines(head_seq, &targets);
|
let lines = backed_up_lines(head_seq, &targets);
|
||||||
if targets.is_empty() || targets.iter().any(|t| t.problem.is_some()) {
|
if targets.is_empty() || targets.iter().any(|t| t.problem.is_some()) {
|
||||||
@@ -1180,6 +1257,198 @@ pub fn back_up_now(common: &Common, book: &str, new_disk: bool) -> Result<Vec<St
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ask at the terminal for the passphrase that protects the backups: twice,
|
||||||
|
/// unechoed, with the warning that a forgotten one cannot be recovered.
|
||||||
|
fn ask_backup_passphrase() -> Result<String, String> {
|
||||||
|
if !at_a_terminal() {
|
||||||
|
return Err(
|
||||||
|
"the backup passphrase is typed by a person, at a terminal (or set up in the window)"
|
||||||
|
.into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
println!(
|
||||||
|
"Backups protected by a passphrase are sealed: only this passphrase opens them. A forgotten passphrase cannot be recovered by anyone."
|
||||||
|
);
|
||||||
|
let first = rpassword::prompt_password("Backup passphrase: ").map_err(|e| e.to_string())?;
|
||||||
|
let again = rpassword::prompt_password("Again: ").map_err(|e| e.to_string())?;
|
||||||
|
if first != again {
|
||||||
|
return Err("the two passphrases differ: nothing was changed".into());
|
||||||
|
}
|
||||||
|
Ok(first)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the books' backups stand, as the server says it.
|
||||||
|
pub fn backup_standing(common: &Common, book: &str) -> Result<admin::BackupStanding, String> {
|
||||||
|
match with_server(
|
||||||
|
common,
|
||||||
|
Request::BackupStatus {
|
||||||
|
id: book.to_string(),
|
||||||
|
},
|
||||||
|
)? {
|
||||||
|
Response::BackupStatus(s) => Ok(s),
|
||||||
|
Response::Refused(why) => Err(why),
|
||||||
|
other => Err(format!("the books server answered oddly: {other:?}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the books' backups stand, in words, a line each.
|
||||||
|
pub fn backup_status(common: &Common, book: &str) -> Result<Vec<String>, String> {
|
||||||
|
backup_standing(common, book).map(|s| backup_words(&s))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A time the server recorded (UTC, RFC 3339) as a person reads it: their own
|
||||||
|
/// clock, day, month and year, hour and minute.
|
||||||
|
fn when(utc: &str) -> String {
|
||||||
|
chrono::DateTime::parse_from_rfc3339(utc).map_or_else(
|
||||||
|
|_| utc.to_string(),
|
||||||
|
|t| {
|
||||||
|
t.with_timezone(&chrono::Local)
|
||||||
|
.format("%B %-d, %Y at %H:%M")
|
||||||
|
.to_string()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a restore says before anything else when it is not of the newest
|
||||||
|
/// backup there is: both dates, and how many backups it passes over.
|
||||||
|
pub fn older_backup_words(p: &admin::RestorePreview) -> String {
|
||||||
|
let day = |at: &Option<String>| at.as_deref().map(when);
|
||||||
|
let (this, newest) = (day(&p.written), day(&p.newest_written));
|
||||||
|
let dates = match (this, newest) {
|
||||||
|
(Some(a), Some(b)) => format!(
|
||||||
|
" This backup is from {a}; the newest in the folder is from {b} and is not whole."
|
||||||
|
),
|
||||||
|
(Some(a), None) => format!(" This backup is from {a}."),
|
||||||
|
_ => String::new(),
|
||||||
|
};
|
||||||
|
format!(
|
||||||
|
"NOT THE NEWEST BACKUP: this restore passes over {} newer backup{} that did not prove whole, and brings back older books than the folder holds.{dates} Anything written after this backup is not in it.",
|
||||||
|
p.passed_over,
|
||||||
|
if p.passed_over == 1 { "" } else { "s" }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The words for a backup standing, as an ordinary person reads them.
|
||||||
|
pub fn backup_words(s: &admin::BackupStanding) -> Vec<String> {
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
match &s.folder {
|
||||||
|
None => lines.push("Not backed up: no backup folder is chosen yet.".to_string()),
|
||||||
|
Some(folder) => {
|
||||||
|
lines.push(format!("Backing up to {folder}."));
|
||||||
|
if s.disconnected {
|
||||||
|
lines.push("The disk with the backup is not connected: connect it, and the next backup goes there. If it is a new disk, say so when you back up now.".into());
|
||||||
|
} else if let Some(why) = &s.last_error {
|
||||||
|
lines.push(format!("The last backup didn't work: {why}"));
|
||||||
|
match s.error_kind.as_deref() {
|
||||||
|
Some("ahead") => lines.push("This usually means the books were restored from an older backup. To carry on with these books, start a new backup set: the old one stays in the folder, untouched.".into()),
|
||||||
|
Some("elsewhere") => lines.push("Nothing was written there. If these are the right books, choose another backup folder.".into()),
|
||||||
|
Some("key_missing") => lines.push("Enter the backup passphrase again in the backup settings to carry on, or remove the passphrase there to back up without one.".into()),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !s.damaged_files.is_empty() {
|
||||||
|
lines.push(format!(
|
||||||
|
"{} file(s) in the backup folder were found damaged and were written again; the damaged ones are left where they are (nothing in the folder is ever deleted), and you may delete them yourself: {}",
|
||||||
|
s.damaged_files.len(),
|
||||||
|
s.damaged_files.join(", ")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
match (&s.last_ok_at, s.through_seq) {
|
||||||
|
(Some(at), Some(seq)) => lines.push(format!(
|
||||||
|
"Last backed up {}, through event {seq} of {}.{}",
|
||||||
|
when(at),
|
||||||
|
s.head_seq,
|
||||||
|
if s.through_seq == Some(s.head_seq) {
|
||||||
|
" Up to date."
|
||||||
|
} else if s.stale {
|
||||||
|
" More than a day behind."
|
||||||
|
} else {
|
||||||
|
" Behind, and catching up."
|
||||||
|
}
|
||||||
|
)),
|
||||||
|
_ => lines.push("No backup has been made there yet.".into()),
|
||||||
|
}
|
||||||
|
match (&s.last_drill_at, &s.drill_error) {
|
||||||
|
(_, Some(why)) => {
|
||||||
|
lines.push(format!(
|
||||||
|
"The weekly check that the backup can be restored failed: {why}"
|
||||||
|
));
|
||||||
|
if s.error_kind.as_deref() == Some("newest_damaged")
|
||||||
|
|| why.contains("newest backup")
|
||||||
|
{
|
||||||
|
lines.push("Back up again now: a restore from this folder would give older books until a backup after the damage is made.".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(Some(at), None) => lines.push(format!("Proven restorable {at} (checked weekly).")),
|
||||||
|
(None, None) if s.through_seq.is_some() => {
|
||||||
|
lines.push("Not yet proven restorable: it is checked weekly.".into())
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
lines.push(if s.sealed {
|
||||||
|
"Protected by a passphrase. A forgotten passphrase cannot be recovered.".into()
|
||||||
|
} else {
|
||||||
|
"Not protected by a passphrase.".into()
|
||||||
|
});
|
||||||
|
if let Some(sync) = &s.sync {
|
||||||
|
lines.push(sync.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(note) = &s.note {
|
||||||
|
lines.push(note.clone());
|
||||||
|
}
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set up the books' backups: the folder, and the passphrase (D-92).
|
||||||
|
pub fn backup_setup(
|
||||||
|
common: &Common,
|
||||||
|
book: &str,
|
||||||
|
folder: Option<String>,
|
||||||
|
passphrase: Option<String>,
|
||||||
|
remove_passphrase: bool,
|
||||||
|
) -> Result<Vec<String>, String> {
|
||||||
|
let folder = folder.map(|f| {
|
||||||
|
std::path::absolute(&f)
|
||||||
|
.unwrap_or_else(|_| PathBuf::from(&f))
|
||||||
|
.display()
|
||||||
|
.to_string()
|
||||||
|
});
|
||||||
|
match with_server(
|
||||||
|
common,
|
||||||
|
Request::BackupSetup {
|
||||||
|
id: book.to_string(),
|
||||||
|
folder,
|
||||||
|
passphrase: passphrase.map(ledger_mcp::admin::Passphrase),
|
||||||
|
remove_passphrase,
|
||||||
|
},
|
||||||
|
)? {
|
||||||
|
Response::Said { lines } => Ok(lines),
|
||||||
|
Response::Refused(why) => Err(why),
|
||||||
|
other => Err(format!("the books server answered oddly: {other:?}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Save a backup of the books as one file.
|
||||||
|
pub fn backup_save(common: &Common, book: &str, file: &str) -> Result<Vec<String>, String> {
|
||||||
|
let file = std::path::absolute(file)
|
||||||
|
.unwrap_or_else(|_| PathBuf::from(file))
|
||||||
|
.display()
|
||||||
|
.to_string();
|
||||||
|
match with_server(
|
||||||
|
common,
|
||||||
|
Request::BackupSave {
|
||||||
|
id: book.to_string(),
|
||||||
|
path: file,
|
||||||
|
},
|
||||||
|
)? {
|
||||||
|
Response::Said { lines } => Ok(lines),
|
||||||
|
Response::Refused(why) => Err(why),
|
||||||
|
other => Err(format!("the books server answered oddly: {other:?}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// What a format upgrade the books `book` wait for means, a line each
|
/// What a format upgrade the books `book` wait for means, a line each
|
||||||
/// (plan 3.9, D-39): said before the owner is asked.
|
/// (plan 3.9, D-39): said before the owner is asked.
|
||||||
pub fn upgrade_explained(book: &str, waiting: &admin::FormatWaiting) -> Vec<String> {
|
pub fn upgrade_explained(book: &str, waiting: &admin::FormatWaiting) -> Vec<String> {
|
||||||
@@ -1617,7 +1886,7 @@ const CONNECT_WAIT: Duration = Duration::from_secs(60);
|
|||||||
pub fn backed_up_lines(head_seq: u64, targets: &[admin::BackedUpTarget]) -> Vec<String> {
|
pub fn backed_up_lines(head_seq: u64, targets: &[admin::BackedUpTarget]) -> Vec<String> {
|
||||||
if targets.is_empty() {
|
if targets.is_empty() {
|
||||||
return vec![
|
return vec![
|
||||||
"No backups are set up: ask your agent to set the private repository and the backup folder.".into(),
|
"No backups are set up: choose a backup folder, in the window or with `wanderbooks books backup-setup ID --folder FOLDER`.".into(),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
targets
|
targets
|
||||||
@@ -2493,14 +2762,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 +2796,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 +2811,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 +2854,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 +2881,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 +2906,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 +2955,17 @@ pub fn plan_restore(
|
|||||||
preview.blobs,
|
preview.blobs,
|
||||||
preview.vault_files
|
preview.vault_files
|
||||||
)];
|
)];
|
||||||
|
if preview.passed_over > 0 {
|
||||||
|
// First, before anything else: books older than the newest backup
|
||||||
|
// there is are not what a person expects to get.
|
||||||
|
lines.insert(0, older_backup_words(&preview));
|
||||||
|
}
|
||||||
|
if preview.sealed {
|
||||||
|
lines.push(
|
||||||
|
"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 +2976,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 +3003,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) => {
|
||||||
@@ -4108,16 +4410,165 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The words a person is told of each state of their backups: none set up,
|
||||||
|
/// a disk not connected, a failure, up to date and protected, behind, a
|
||||||
|
/// failed weekly check. No word of how it is made, and never git.
|
||||||
#[test]
|
#[test]
|
||||||
fn a_backup_is_restored_under_its_repository_name() {
|
fn the_backups_are_described_in_words_for_each_state() {
|
||||||
|
let base = admin::BackupStanding {
|
||||||
|
head_seq: 12,
|
||||||
|
folder: None,
|
||||||
|
sealed: false,
|
||||||
|
last_ok_at: None,
|
||||||
|
through_seq: None,
|
||||||
|
stale: false,
|
||||||
|
last_error: None,
|
||||||
|
last_drill_at: None,
|
||||||
|
drill_error: None,
|
||||||
|
disconnected: false,
|
||||||
|
note: None,
|
||||||
|
error_kind: None,
|
||||||
|
damaged_files: Vec::new(),
|
||||||
|
sync: None,
|
||||||
|
};
|
||||||
|
let say = |s: &admin::BackupStanding| backup_words(s).join(" | ");
|
||||||
|
assert_eq!(say(&base), "Not backed up: no backup folder is chosen yet.");
|
||||||
|
// The new states, each in words: books ahead of the folder, a key
|
||||||
|
// lost, a newest backup that is damaged, files found damaged, a
|
||||||
|
// synced folder.
|
||||||
|
let there = admin::BackupStanding {
|
||||||
|
folder: Some("/media/disk".into()),
|
||||||
|
last_ok_at: Some("2026-11-21T10:00:00Z".into()),
|
||||||
|
through_seq: Some(5),
|
||||||
|
..base.clone()
|
||||||
|
};
|
||||||
|
let ahead = admin::BackupStanding {
|
||||||
|
last_error: Some("the backup folder holds a longer history of these books".into()),
|
||||||
|
error_kind: Some("ahead".into()),
|
||||||
|
..there.clone()
|
||||||
|
};
|
||||||
|
let said = say(&ahead);
|
||||||
|
assert!(said.contains("restored from an older backup"), "{said}");
|
||||||
|
assert!(said.contains("start a new backup set"), "{said}");
|
||||||
|
let lost = admin::BackupStanding {
|
||||||
|
last_error: Some("no longer has its key".into()),
|
||||||
|
error_kind: Some("key_missing".into()),
|
||||||
|
sealed: true,
|
||||||
|
..there.clone()
|
||||||
|
};
|
||||||
|
assert!(say(&lost).contains("Enter the backup passphrase again"));
|
||||||
|
let drill = admin::BackupStanding {
|
||||||
|
drill_error: Some(
|
||||||
|
"the newest backup (number 3, from today) is damaged; an older one from last week is whole"
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
|
error_kind: Some("newest_damaged".into()),
|
||||||
|
..there.clone()
|
||||||
|
};
|
||||||
|
let said = say(&drill);
|
||||||
|
assert!(said.contains("weekly check"), "{said}");
|
||||||
|
assert!(said.contains("older books"), "{said}");
|
||||||
|
assert!(!said.contains("Proven restorable"), "{said}");
|
||||||
|
let damaged = admin::BackupStanding {
|
||||||
|
damaged_files: vec!["journal/000002-abc".into()],
|
||||||
|
sync: Some(ledger_mcp::backup::sync_words(Some("Dropbox"))),
|
||||||
|
..there.clone()
|
||||||
|
};
|
||||||
|
let said = say(&damaged);
|
||||||
|
assert!(
|
||||||
|
said.contains("found damaged and were written again"),
|
||||||
|
"{said}"
|
||||||
|
);
|
||||||
|
assert!(said.contains("journal/000002-abc"), "{said}");
|
||||||
|
assert!(said.contains("kept in sync by Dropbox"), "{said}");
|
||||||
|
let preview = admin::RestorePreview {
|
||||||
|
head: (3, "ab".into()),
|
||||||
|
blobs: 0,
|
||||||
|
vault_files: 0,
|
||||||
|
exists: false,
|
||||||
|
origin: None,
|
||||||
|
sealed: false,
|
||||||
|
passed_over: 2,
|
||||||
|
written: Some("2026-11-14T10:00:00Z".into()),
|
||||||
|
newest_written: Some("2026-11-21T10:00:00Z".into()),
|
||||||
|
};
|
||||||
|
let said = older_backup_words(&preview);
|
||||||
|
assert!(said.starts_with("NOT THE NEWEST BACKUP"), "{said}");
|
||||||
|
assert!(said.contains("passes over 2 newer backups"), "{said}");
|
||||||
|
assert!(said.contains("This backup is from"), "{said}");
|
||||||
|
assert!(said.contains("the newest in the folder is from"), "{said}");
|
||||||
|
let with_folder = admin::BackupStanding {
|
||||||
|
folder: Some("/media/disk/Backups".into()),
|
||||||
|
..base.clone()
|
||||||
|
};
|
||||||
|
let said = say(&with_folder);
|
||||||
|
assert!(
|
||||||
|
said.contains("Backing up to /media/disk/Backups."),
|
||||||
|
"{said}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
said.contains("No backup has been made there yet."),
|
||||||
|
"{said}"
|
||||||
|
);
|
||||||
|
assert!(said.contains("Not protected by a passphrase."), "{said}");
|
||||||
|
let away = admin::BackupStanding {
|
||||||
|
disconnected: true,
|
||||||
|
last_error: Some("the backup folder isn't there (is its disk connected?)".into()),
|
||||||
|
..with_folder.clone()
|
||||||
|
};
|
||||||
|
let said = say(&away);
|
||||||
|
assert!(
|
||||||
|
said.contains("The disk with the backup is not connected"),
|
||||||
|
"{said}"
|
||||||
|
);
|
||||||
|
let failing = admin::BackupStanding {
|
||||||
|
last_error: Some("another set of books is in the folder".into()),
|
||||||
|
..with_folder.clone()
|
||||||
|
};
|
||||||
|
assert!(say(&failing).contains("The last backup didn't work: another set of books"));
|
||||||
|
let fresh = admin::BackupStanding {
|
||||||
|
last_ok_at: Some("2026-11-21T10:00:00.000Z".into()),
|
||||||
|
through_seq: Some(12),
|
||||||
|
last_drill_at: Some("2026-11-21T10:05:00.000Z".into()),
|
||||||
|
sealed: true,
|
||||||
|
..with_folder.clone()
|
||||||
|
};
|
||||||
|
let said = say(&fresh);
|
||||||
|
assert!(
|
||||||
|
said.contains("through event 12 of 12. Up to date."),
|
||||||
|
"{said}"
|
||||||
|
);
|
||||||
|
assert!(said.contains("Proven restorable"), "{said}");
|
||||||
|
assert!(
|
||||||
|
said.contains("Protected by a passphrase. A forgotten passphrase cannot be recovered."),
|
||||||
|
"{said}"
|
||||||
|
);
|
||||||
|
let behind = admin::BackupStanding {
|
||||||
|
through_seq: Some(9),
|
||||||
|
stale: true,
|
||||||
|
drill_error: Some("a piece is damaged".into()),
|
||||||
|
..fresh.clone()
|
||||||
|
};
|
||||||
|
let said = say(&behind);
|
||||||
|
assert!(said.contains("More than a day behind."), "{said}");
|
||||||
|
assert!(
|
||||||
|
said.contains("The weekly check that the backup can be restored failed"),
|
||||||
|
"{said}"
|
||||||
|
);
|
||||||
|
for s in [&base, &with_folder, &away, &failing, &fresh, &behind] {
|
||||||
|
assert!(!say(s).to_lowercase().contains("git"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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),
|
||||||
] {
|
] {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
//! and DBUS_SESSION_BUS_ADDRESS only when they point at this
|
//! and DBUS_SESSION_BUS_ADDRESS only when they point at this
|
||||||
//! account's own private runtime folder, and SSH_AUTH_SOCK only when
|
//! account's own private runtime folder, and SSH_AUTH_SOCK only when
|
||||||
//! it names a socket this account owns (the owner's ssh agent, so the
|
//! it names a socket this account owns (the owner's ssh agent, so the
|
||||||
//! server's backups reach a private git repository, D-30). Nothing
|
//! server's backups reach a folder on the network, D-91). Nothing
|
||||||
//! else passes (a scope's own identifiers, such as INVOCATION_ID, are
|
//! else passes (a scope's own identifiers, such as INVOCATION_ID, are
|
||||||
//! systemd's). Two more: APPIMAGE and APPDIR, only when they are
|
//! systemd's). Two more: APPIMAGE and APPDIR, only when they are
|
||||||
//! this program's own (INVARIANT 6), so the host knows its own
|
//! this program's own (INVARIANT 6), so the host knows its own
|
||||||
@@ -441,9 +441,9 @@ fn scope_made(child: &mut std::process::Child, log: &std::fs::File, from: u64) -
|
|||||||
|
|
||||||
/// The host's environment on Windows (INVARIANT 1's counterpart): the
|
/// The host's environment on Windows (INVARIANT 1's counterpart): the
|
||||||
/// system's own variables, the account's profile, and a PATH fixed to the
|
/// system's own variables, the account's profile, and a PATH fixed to the
|
||||||
/// system folders and Git for Windows (the backups run `git`). Nothing
|
/// system folders. Nothing else of the opener's passes. (CHOICE, P11c: no
|
||||||
/// else of the opener's passes. (CHOICE, P11c: no authority states a
|
/// authority states a Windows list; this is the least a Windows program
|
||||||
/// Windows list; this is the least a Windows program and `git` need.)
|
/// needs.)
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
fn host_env(home: &Path) -> Vec<(String, std::ffi::OsString)> {
|
fn host_env(home: &Path) -> Vec<(String, std::ffi::OsString)> {
|
||||||
let var = |name: &str| std::env::var_os(name);
|
let var = |name: &str| std::env::var_os(name);
|
||||||
@@ -452,11 +452,7 @@ fn host_env(home: &Path) -> Vec<(String, std::ffi::OsString)> {
|
|||||||
.map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from);
|
.map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from);
|
||||||
let program_files: PathBuf =
|
let program_files: PathBuf =
|
||||||
var("ProgramFiles").map_or_else(|| PathBuf::from(r"C:\Program Files"), PathBuf::from);
|
var("ProgramFiles").map_or_else(|| PathBuf::from(r"C:\Program Files"), PathBuf::from);
|
||||||
let path = std::env::join_paths([
|
let path = std::env::join_paths([system_root.join("System32"), system_root.clone()])
|
||||||
system_root.join("System32"),
|
|
||||||
system_root.clone(),
|
|
||||||
program_files.join("Git").join("cmd"),
|
|
||||||
])
|
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let mut env: Vec<(String, std::ffi::OsString)> = vec![
|
let mut env: Vec<(String, std::ffi::OsString)> = vec![
|
||||||
("PATH".into(), path),
|
("PATH".into(), path),
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
# Backups
|
# Backups
|
||||||
|
|
||||||
- The books back themselves up: a little after each change, when they open, before they close. Each backup goes to the targets the settings name: backup.git_remote, a private repository the human owns, and backup.folder, a folder on another disk. Both is best. The backups aren't encrypted: the human's repository host and disk keep them private.
|
- The books back themselves up: a little after each change, when they open, before they close. The backup goes to the backup folder the settings name (backup.folder): a folder on another disk, or one that Dropbox, iCloud, OneDrive or Google Drive keeps in sync. It holds one folder for these books, made only of files that are added and never changed or deleted, so a sync service never sees one change under it.
|
||||||
- No targets set: books.start says so. Ask the human for the repository's address and the folder, then set them with books.set_setting (who decided, and when); choosing where backups go needs books:admin, as backing up does.
|
- No backup folder set: books.start says so. Ask the human which folder, then set it with books.set_setting (who decided, and when); choosing where backups go needs books:admin, as backing up does. The window has a folder chooser for the same.
|
||||||
- books.backup says how each target stands: when it last took the books, through which journal seq, why the last try failed, and whether its weekly restore check passed. A target that is stale, failing, or failed its check: tell the human what it says, in plain words (a disk not connected, a repository that refused).
|
- The human may protect the backups with a passphrase, set up in the window and off by default. Then every file in the folder is sealed and says no more than how many there are and how big. The passphrase is never in the books or in these tools, and a forgotten one can't be recovered: say so plainly if the human asks. books.backup says whether the backups are sealed.
|
||||||
- books.back_up_now backs up at once, for instance before the human changes computers. A backup never changes the books.
|
- books.backup says how the folder stands: when it last took the books, through which journal seq, why the last try failed, and whether its weekly restore check passed. A folder that is stale, failing, or failed its check: tell the human what it says, in plain words (a disk not connected, another set of books in the folder).
|
||||||
- A backup folder that took these books' backups but holds none now is a disk not connected: ask the human to connect it. Only if they say the disk is new, back up now with new_disk: true to begin the books' backup there again.
|
- books.back_up_now backs up at once, for instance before the human changes computers. A backup never changes the books. The window's Save a backup... makes the same backup as one file to keep or carry.
|
||||||
- Books restored as a copy of other books (under another name) don't back up to those books' repository (that would stop theirs): books.backup says so; ask the human for one of their own.
|
- A backup folder that took these books' backups but holds none now is a disk not connected (disconnected: true): ask the human to connect it. Only if they say the disk is new, back up now with new_disk: true to begin the books' backup there again.
|
||||||
- Restoring is the human's to do, outside these tools: a backup comes back as new books, or replacing these (the old books are kept, never deleted), and each is proven whole before it is restored.
|
- Books that still name a private repository in their settings (an older kind of backup) are told it is no longer used: ask the human for a backup folder instead. Nothing older is deleted.
|
||||||
|
- Restoring is the human's to do, outside these tools: a backup comes back as new books, or replacing these (the old books are kept, never deleted), from the backup folder or a backup file, and each is proven whole before it is restored.
|
||||||
@@ -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,
|
||||||
@@ -143,6 +147,43 @@ pub enum Request {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
new_disk: bool,
|
new_disk: bool,
|
||||||
},
|
},
|
||||||
|
/// Begin a new backup set beside the old one in the backup folder, and
|
||||||
|
/// back the books up to it (the books are behind the folder's: as
|
||||||
|
/// after a restore from an older backup): only at the person's
|
||||||
|
/// request; the old set is never touched.
|
||||||
|
BackUpNewSet {
|
||||||
|
/// The books.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// Set up a book's backups (D-91, D-92): the folder, and the
|
||||||
|
/// passphrase.
|
||||||
|
BackupSetup {
|
||||||
|
/// The books.
|
||||||
|
id: String,
|
||||||
|
/// The backup folder, by its whole path: set as the books'
|
||||||
|
/// `backup.folder`, the owner the one who decided.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
folder: Option<String>,
|
||||||
|
/// Protect the backups with this passphrase (never shown, never
|
||||||
|
/// kept: the key it makes is kept on this computer).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
passphrase: Option<Passphrase>,
|
||||||
|
/// Take the passphrase off.
|
||||||
|
#[serde(default)]
|
||||||
|
remove_passphrase: bool,
|
||||||
|
},
|
||||||
|
/// How a book's backups stand.
|
||||||
|
BackupStatus {
|
||||||
|
/// The books.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// Save a backup of a book as one file.
|
||||||
|
BackupSave {
|
||||||
|
/// The books.
|
||||||
|
id: String,
|
||||||
|
/// The file, by its whole path (.wbbackup is added if missing).
|
||||||
|
path: String,
|
||||||
|
},
|
||||||
/// Make a token for an agent (plan 3.3).
|
/// Make a token for an agent (plan 3.3).
|
||||||
TokenCreate {
|
TokenCreate {
|
||||||
/// The books it opens.
|
/// The books it opens.
|
||||||
@@ -509,7 +550,7 @@ pub enum CloseOutcome {
|
|||||||
/// sessions ended, and another process could open it.
|
/// sessions ended, and another process could open it.
|
||||||
Closed,
|
Closed,
|
||||||
/// It was open and is closed as `Closed` says, but its last backup
|
/// It was open and is closed as `Closed` says, but its last backup
|
||||||
/// wasn't whole (a target that couldn't be reached, git that failed, or
|
/// wasn't whole (a folder that couldn't be reached, a copy that failed, or
|
||||||
/// a backup stopped after its time): why, in words. The books on disk
|
/// a backup stopped after its time): why, in words. The books on disk
|
||||||
/// are whole; what they hold since the last good backup is not backed
|
/// are whole; what they hold since the last good backup is not backed
|
||||||
/// up.
|
/// up.
|
||||||
@@ -660,6 +701,19 @@ 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 or were damaged and were
|
||||||
|
/// passed over: not zero means this is not the newest backup there is.
|
||||||
|
#[serde(default)]
|
||||||
|
pub passed_over: u64,
|
||||||
|
/// When this backup was made (UTC), as its manifest says.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub written: Option<String>,
|
||||||
|
/// When the newest backup there is was made (UTC), if it can be read.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub newest_written: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a restore did.
|
/// What a restore did.
|
||||||
@@ -687,7 +741,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,
|
||||||
@@ -699,6 +753,51 @@ pub struct BackedUpTarget {
|
|||||||
pub problem: Option<String>,
|
pub problem: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How a book's backups stand, for the window and the command line.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct BackupStanding {
|
||||||
|
/// The books' head seq now.
|
||||||
|
pub head_seq: u64,
|
||||||
|
/// The backup folder chosen, if one is.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub folder: Option<String>,
|
||||||
|
/// Protected by a passphrase.
|
||||||
|
pub sealed: bool,
|
||||||
|
/// When it last took the books (UTC), if ever.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub last_ok_at: Option<String>,
|
||||||
|
/// The journal seq it holds, if any.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub through_seq: Option<u64>,
|
||||||
|
/// More than a day behind.
|
||||||
|
pub stale: bool,
|
||||||
|
/// Why its last backup failed, if it did.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub last_error: Option<String>,
|
||||||
|
/// When it was last proven restorable (UTC), if ever.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub last_drill_at: Option<String>,
|
||||||
|
/// Why that check failed, if it did.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub drill_error: Option<String>,
|
||||||
|
/// Its disk isn't connected.
|
||||||
|
pub disconnected: bool,
|
||||||
|
/// What to know or do: none set up, an older kind no longer used.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub note: Option<String>,
|
||||||
|
/// What kind of trouble the last backup or check had (`ahead`,
|
||||||
|
/// `elsewhere`, `key_missing`, `not_downloaded`, `newest_damaged`).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub error_kind: Option<String>,
|
||||||
|
/// Files in the backup folder found damaged and written again; each is
|
||||||
|
/// left where it is.
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub damaged_files: Vec<String>,
|
||||||
|
/// What to tell a person of a folder a sync service keeps (or may).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub sync: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
/// The server's answer.
|
/// The server's answer.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "snake_case", deny_unknown_fields)]
|
#[serde(rename_all = "snake_case", deny_unknown_fields)]
|
||||||
@@ -729,6 +828,13 @@ pub enum Response {
|
|||||||
/// Each target.
|
/// Each target.
|
||||||
targets: Vec<BackedUpTarget>,
|
targets: Vec<BackedUpTarget>,
|
||||||
},
|
},
|
||||||
|
/// What was done, in words (a backup set up or saved).
|
||||||
|
Said {
|
||||||
|
/// A line each.
|
||||||
|
lines: Vec<String>,
|
||||||
|
},
|
||||||
|
/// How a book's backups stand.
|
||||||
|
BackupStatus(BackupStanding),
|
||||||
/// A token made: its text, shown this once (INVARIANT 6).
|
/// A token made: its text, shown this once (INVARIANT 6).
|
||||||
TokenCreated {
|
TokenCreated {
|
||||||
/// The token.
|
/// The token.
|
||||||
@@ -847,7 +953,11 @@ pub fn call_within(
|
|||||||
| Request::Sessions
|
| Request::Sessions
|
||||||
| Request::RemoteStatus
|
| Request::RemoteStatus
|
||||||
| Request::RemotePending
|
| Request::RemotePending
|
||||||
|
| Request::BackupStatus { .. }
|
||||||
| Request::RemoteApprovals { .. } => None,
|
| Request::RemoteApprovals { .. } => None,
|
||||||
|
Request::BackupSetup { .. } | Request::BackupSave { .. } => {
|
||||||
|
Some("`wanderbooks books backup-status BOOK` says how the backups stand")
|
||||||
|
}
|
||||||
Request::RemoteStart { .. }
|
Request::RemoteStart { .. }
|
||||||
| Request::RemoteStop
|
| Request::RemoteStop
|
||||||
| Request::RemoteAllow { .. }
|
| Request::RemoteAllow { .. }
|
||||||
@@ -863,7 +973,7 @@ pub fn call_within(
|
|||||||
Request::Create { .. } | Request::Adopt { .. } | Request::Restore { .. } => {
|
Request::Create { .. } | Request::Adopt { .. } | Request::Restore { .. } => {
|
||||||
Some("`wanderbooks books list` shows the books there are")
|
Some("`wanderbooks books list` shows the books there are")
|
||||||
}
|
}
|
||||||
Request::BackUpNow { .. } => {
|
Request::BackUpNow { .. } | Request::BackUpNewSet { .. } => {
|
||||||
Some("`wanderbooks books back-up` again backs up whatever it didn't")
|
Some("`wanderbooks books back-up` again backs up whatever it didn't")
|
||||||
}
|
}
|
||||||
Request::TokenCreate { .. } | Request::TokenRevoke { .. } => {
|
Request::TokenCreate { .. } | Request::TokenRevoke { .. } => {
|
||||||
@@ -988,17 +1098,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 +1186,10 @@ 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,
|
||||||
|
written: None,
|
||||||
|
newest_written: None,
|
||||||
}),
|
}),
|
||||||
Response::Restored(Restored {
|
Response::Restored(Restored {
|
||||||
id: "acme".into(),
|
id: "acme".into(),
|
||||||
|
|||||||
+878
-442
File diff suppressed because it is too large.
Load diff
+199
-150
@@ -99,7 +99,7 @@
|
|||||||
//! and the book is let go (INVARIANT 13), its writer lock released, so
|
//! and the book is let go (INVARIANT 13), its writer lock released, so
|
||||||
//! another process could open it; and only then is a close answered.
|
//! another process could open it; and only then is a close answered.
|
||||||
//! It is answered `closed`, or `closed_backup_incomplete` with why when
|
//! It is answered `closed`, or `closed_backup_incomplete` with why when
|
||||||
//! its last backup wasn't whole (a target that failed, git that
|
//! its last backup wasn't whole (a folder that failed, a copy that
|
||||||
//! failed, a backup stopped after its time): never a plain `closed`
|
//! failed, a backup stopped after its time): never a plain `closed`
|
||||||
//! for a backup that wasn't made. After that answer no call on that
|
//! for a backup that wasn't made. After that answer no call on that
|
||||||
//! book runs until it is opened again. Every other book keeps serving,
|
//! book runs until it is opened again. Every other book keeps serving,
|
||||||
@@ -114,9 +114,8 @@
|
|||||||
//! long I/O or loop over a book's whole journal or files are exactly
|
//! long I/O or loop over a book's whole journal or files are exactly
|
||||||
//! these, and each is stoppable:
|
//! these, and each is stoppable:
|
||||||
//! - on the book: `books.back_up_now`, and a backup a timer asked for
|
//! - on the book: `books.back_up_now`, and a backup a timer asked for
|
||||||
//! (git is sent SIGTERM and killed only after TERM_GRACE: ledger_
|
//! (its copy stops at the next piece, ledger_store backup
|
||||||
//! store backup INVARIANT 5; between targets the flag is looked at
|
//! INVARIANT 8; between destinations the flag is looked at too); `books.verify` (once per journal line replayed and per
|
||||||
//! too); `books.verify` (once per journal line replayed and per
|
|
||||||
//! stored file hashed); `books.export_cpa_package` (before it
|
//! stored file hashed); `books.export_cpa_package` (before it
|
||||||
//! builds, and once per stored file it reads, unless it has
|
//! builds, and once per stored file it reads, unless it has
|
||||||
//! journaled a decision: below); a drill; and a
|
//! journaled a decision: below); a drill; and a
|
||||||
@@ -160,7 +159,7 @@
|
|||||||
//! their point of no return, and never waits behind one. A
|
//! their point of no return, and never waits behind one. A
|
||||||
//! PREVIEW (of a restore, of an adoption) changes nothing, and
|
//! PREVIEW (of a restore, of an adoption) changes nothing, and
|
||||||
//! holds no book's turn at all: a close never waits for one,
|
//! holds no book's turn at all: a close never waits for one,
|
||||||
//! however long its clone or its queue for `books.lock`; only the
|
//! however long its scratch build or its queue for `books.lock`; only the
|
||||||
//! server's close stops it. No close of any other book stops, fails,
|
//! server's close stops it. No close of any other book stops, fails,
|
||||||
//! refuses or delays an open, a close or a job of X, nor a job
|
//! refuses or delays an open, a close or a job of X, nor a job
|
||||||
//! queued for its turn at making books (`books.lock` in the root,
|
//! queued for its turn at making books (`books.lock` in the root,
|
||||||
@@ -171,7 +170,7 @@
|
|||||||
//! way waits for that book's turn, so for the close to end, and is
|
//! way waits for that book's turn, so for the close to end, and is
|
||||||
//! then asked as any other. Each is stopped, before its
|
//! then asked as any other. Each is stopped, before its
|
||||||
//! point of no return, at its next look (a phase, a stored file, a
|
//! point of no return, at its next look (a phase, a stored file, a
|
||||||
//! journal line, a git command): what it wrote is removed (a clone,
|
//! journal line, a piece of a copy): what it wrote is removed (a scratch,
|
||||||
//! a staging folder, and the lock file an adoption made in the
|
//! a staging folder, and the lock file an adoption made in the
|
||||||
//! source folder), and the root is byte for byte as it was. The
|
//! source folder), and the root is byte for byte as it was. The
|
||||||
//! point of no return of restore and adopt is the rename that puts
|
//! point of no return of restore and adopt is the rename that puts
|
||||||
@@ -227,16 +226,14 @@
|
|||||||
//! ANSWER_GRACE from the START of the close, inside (a): a
|
//! ANSWER_GRACE from the START of the close, inside (a): a
|
||||||
//! stalled client adds nothing);
|
//! stalled client adds nothing);
|
||||||
//! c. T_stop: the longest between two looks of what is stopped, one
|
//! c. T_stop: the longest between two looks of what is stopped, one
|
||||||
//! of: a git command's stop (SIGTERM and up to TERM_GRACE, 5 s;
|
//! of: one journal line, one stored file, one 64 KiB chunk, one
|
||||||
//! then a kill and GROUP_GONE_WAIT, 2 s, and its pipes, 10 s at
|
|
||||||
//! most), one journal line, one stored file, one 64 KiB chunk, one
|
|
||||||
//! phase of a job; and the removal of what a stopped job or drill
|
//! phase of a job; and the removal of what a stopped job or drill
|
||||||
//! wrote (its scratch clone or staging folder: a local deletion of
|
//! wrote (its scratch folder or staging folder: a local deletion of
|
||||||
//! the job's own output, as long as that is large, waiting on no
|
//! the job's own output, as long as that is large, waiting on no
|
||||||
//! one);
|
//! one);
|
||||||
//! d. BACKUP_AT_CLOSE for the last backup;
|
//! d. BACKUP_AT_CLOSE for the last backup;
|
||||||
//! e. T_stop again for what is left of that backup at its bound
|
//! e. T_stop again for what is left of that backup at its bound
|
||||||
//! (`Backups::shut`: git stopped, every step awaited);
|
//! (`Backups::shut`: copying stopped, every step awaited);
|
||||||
//! f. closing the logs and letting go of the store (instant).
|
//! f. closing the logs and letting go of the store (instant).
|
||||||
//! A drill (or a format upgrade) that took the backups' turn never
|
//! A drill (or a format upgrade) that took the backups' turn never
|
||||||
//! costs the last backup its time.
|
//! costs the last backup its time.
|
||||||
@@ -252,7 +249,7 @@
|
|||||||
//! book's sessions end with the book.
|
//! book's sessions end with the book.
|
||||||
//! 13. After a close of a book is answered, this process holds nothing
|
//! 13. After a close of a book is answered, this process holds nothing
|
||||||
//! that can write to that book's folder (journal, access log, ops
|
//! that can write to that book's folder (journal, access log, ops
|
||||||
//! logs, stored files, upload parts, the backup's git repository) or
|
//! logs, stored files, upload parts, the backup folder) or
|
||||||
//! read it on a caller's behalf, until the book is opened again; and
|
//! read it on a caller's behalf, until the book is opened again; and
|
||||||
//! a handle from before a close can never write after a reopen. Every
|
//! a handle from before a close can never write after a reopen. Every
|
||||||
//! path that touches a book is either counted by its gate (a request
|
//! path that touches a book is either counted by its gate (a request
|
||||||
@@ -261,11 +258,11 @@
|
|||||||
//! sweep takes the place too), or checks, under the same lock as its
|
//! sweep takes the place too), or checks, under the same lock as its
|
||||||
//! write, that the book is still open, and refuses if not: the
|
//! write, that the book is still open, and refuses if not: the
|
||||||
//! access log, the uploads, the exports and the backups (record,
|
//! access log, the uploads, the exports and the backups (record,
|
||||||
//! git, drill, upgrade) are each closed under the lock their own
|
//! copy, drill, upgrade) are each closed under the lock their own
|
||||||
//! writes go in under, by the close, once the gate is empty; the
|
//! writes go in under, by the close, once the gate is empty; the
|
||||||
//! store is let go under its lock. A close waits for the backup's
|
//! store is let go under its lock. A close waits for the backup's
|
||||||
//! work to END, not only for its future: a run past its bound is
|
//! work to END, not only for its future: a run past its bound is
|
||||||
//! stopped (git killed with all it started) and waited for, so the
|
//! stopped (its copy ended at the next piece) and waited for, so the
|
||||||
//! close is never answered while a backup runs. The timers (the
|
//! close is never answered while a backup runs. The timers (the
|
||||||
//! sweep, the look for a backup due, the look for a drill due) work
|
//! sweep, the look for a backup due, the look for a drill due) work
|
||||||
//! on handles that are closed with the book, and so can't act on a
|
//! on handles that are closed with the book, and so can't act on a
|
||||||
@@ -339,7 +336,7 @@
|
|||||||
//! answers closed; nothing is written to the book afterwards, and when
|
//! answers closed; nothing is written to the book afterwards, and when
|
||||||
//! it is opened again its access log continues one whole chain.
|
//! it is opened again its access log continues one whole chain.
|
||||||
//! 6. A book with a slow backup is closed: not answered while the backup
|
//! 6. A book with a slow backup is closed: not answered while the backup
|
||||||
//! runs; at its bound git is stopped and waited for, and the answer
|
//! runs; at its bound the copy is stopped and waited for, and the answer
|
||||||
//! says the last backup wasn't whole; nothing runs after.
|
//! says the last backup wasn't whole; nothing runs after.
|
||||||
//! 7. A restore replaces an open book while an upload is half received:
|
//! 7. A restore replaces an open book while an upload is half received:
|
||||||
//! the restore is not answered until the upload is, and no part file
|
//! the restore is not answered until the upload is, and no part file
|
||||||
@@ -353,23 +350,20 @@
|
|||||||
//! call running past it, are not cut; an upload that keeps coming,
|
//! call running past it, are not cut; an upload that keeps coming,
|
||||||
//! steadily, past the grace is cut.
|
//! steadily, past the grace is cut.
|
||||||
//! 10. A drill is slow (a large book): the book is closed, the drill is
|
//! 10. A drill is slow (a large book): the book is closed, the drill is
|
||||||
//! stopped at its next look and its clone removed, the last backup is
|
//! stopped at its next look and its scratch folder removed, the last backup is
|
||||||
//! made, and the close is answered within INVARIANT 10's bound. A
|
//! made, and the close is answered within INVARIANT 10's bound. A
|
||||||
//! format upgrade not yet journaled is stopped the same way, the books
|
//! format upgrade not yet journaled is stopped the same way, the books
|
||||||
//! unchanged.
|
//! unchanged.
|
||||||
//! 11. A backup's git is stopped inside a commit or a push: it is sent
|
//! 11. A backup's copy is stopped between pieces by a close: it writes no
|
||||||
//! SIGTERM and removes its own locks (nothing is left, nothing is
|
//! manifest, the folder proves whole at its previous one, nothing is
|
||||||
//! recorded), the book opened again backs up at once. A git that can't
|
//! left to clean up and nothing is recorded as done, and the book
|
||||||
//! end on SIGTERM and has to be killed after TERM_GRACE leaves locks
|
//! opened again backs up at once.
|
||||||
//! that this process removes from the book's own archive only, and
|
|
||||||
//! leaves in the owner's backup folder, recorded with their whole path
|
|
||||||
//! and said in the close's answer and in the backup's status, until the
|
|
||||||
//! owner removes them.
|
|
||||||
//! 12. The server is closed (standard input ends) with an upload stalled
|
//! 12. The server is closed (standard input ends) with an upload stalled
|
||||||
//! on one book and a call's body stalled on another: both are cut one
|
//! on one book and a call's body stalled on another: both are cut one
|
||||||
//! grace after the close began, the server exits 0 within its bound.
|
//! grace after the close began, the server exits 0 within its bound.
|
||||||
//! 13. A backup asked for (`books.back_up_now`) is running, git stalled,
|
//! 13. A backup asked for (`books.back_up_now`) is running, its copy
|
||||||
//! and the book is closed: the call is answered, git still stalled,
|
//! stalled, and the book is closed: the call is answered, the copy still
|
||||||
|
//! stalled,
|
||||||
//! that it was stopped because the books are closing; its record says
|
//! that it was stopped because the books are closing; its record says
|
||||||
//! `refused: stopped_by_close`; the close is answered `closed`.
|
//! `refused: stopped_by_close`; the close is answered `closed`.
|
||||||
//! 14. A restore of a large backup over `beta` is running (an admin job)
|
//! 14. A restore of a large backup over `beta` is running (an admin job)
|
||||||
@@ -1585,7 +1579,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),
|
||||||
@@ -1619,42 +1614,60 @@ impl Books {
|
|||||||
Err(why) => Response::Refused(self.hide(why)),
|
Err(why) => Response::Refused(self.hide(why)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Request::BackUpNow { id, new_disk } => {
|
Request::BackUpNewSet { id } => self.back_up_response(&id, false, true),
|
||||||
let id = match BookId::parse(&id) {
|
Request::BackUpNow { id, new_disk } => self.back_up_response(&id, new_disk, false),
|
||||||
Ok(id) => id,
|
Request::BackupSetup {
|
||||||
Err(e) => return refused(e),
|
id,
|
||||||
};
|
folder,
|
||||||
let backups = match self.held().get(id.as_str()) {
|
passphrase,
|
||||||
Some(Book::Open { backups, .. }) => backups.clone(),
|
remove_passphrase,
|
||||||
Some(Book::Failed(why)) => {
|
} => match self.backups_of(&id) {
|
||||||
return Response::Refused(format!("those books didn't open: {why}"));
|
Ok(backups) => {
|
||||||
}
|
|
||||||
Some(Book::Closed) => return Response::Refused(self.not_open(&id)),
|
|
||||||
None => {
|
|
||||||
return Response::Refused(format!(
|
|
||||||
"there are no books called {:?}",
|
|
||||||
id.as_str()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let rt = tokio::runtime::Handle::current();
|
let rt = tokio::runtime::Handle::current();
|
||||||
match rt.block_on(backups.run_with("asked", new_disk)) {
|
let pass = passphrase
|
||||||
Ok(status) => Response::BackedUp {
|
.as_ref()
|
||||||
head_seq: status.head_seq,
|
.map(|p| zeroize::Zeroizing::new(p.0.clone()));
|
||||||
targets: status
|
match rt.block_on(backups.set_up(folder, pass, remove_passphrase)) {
|
||||||
.targets
|
Ok(lines) => Response::Said { lines },
|
||||||
.into_iter()
|
|
||||||
.map(|t| admin::BackedUpTarget {
|
|
||||||
target: t.target,
|
|
||||||
at: t.at,
|
|
||||||
through_seq: t.through_seq,
|
|
||||||
problem: t.last_error,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
},
|
|
||||||
Err(why) => Response::Refused(self.hide(why)),
|
Err(why) => Response::Refused(self.hide(why)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Err(r) => *r,
|
||||||
|
},
|
||||||
|
Request::BackupStatus { id } => match self.backups_of(&id) {
|
||||||
|
Ok(backups) => {
|
||||||
|
let rt = tokio::runtime::Handle::current();
|
||||||
|
let s = rt.block_on(backups.window_standing());
|
||||||
|
let t = s.status.targets.first();
|
||||||
|
Response::BackupStatus(admin::BackupStanding {
|
||||||
|
head_seq: s.status.head_seq,
|
||||||
|
folder: s.folder,
|
||||||
|
sealed: s.sealed,
|
||||||
|
last_ok_at: t.and_then(|t| t.last_ok_at.clone()),
|
||||||
|
through_seq: t.and_then(|t| t.through_seq),
|
||||||
|
stale: t.is_some_and(|t| t.stale),
|
||||||
|
last_error: t.and_then(|t| t.last_error.clone()),
|
||||||
|
last_drill_at: t.and_then(|t| t.last_drill_at.clone()),
|
||||||
|
drill_error: t.and_then(|t| t.drill_error.clone()),
|
||||||
|
disconnected: t.is_some_and(|t| t.disconnected),
|
||||||
|
note: s.status.note,
|
||||||
|
error_kind: t.and_then(|t| t.error_kind.clone()),
|
||||||
|
damaged_files: t.map(|t| t.damaged_files.clone()).unwrap_or_default(),
|
||||||
|
sync: s.sync,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(r) => *r,
|
||||||
|
},
|
||||||
|
Request::BackupSave { id, path } => match self.backups_of(&id) {
|
||||||
|
Ok(backups) => {
|
||||||
|
let rt = tokio::runtime::Handle::current();
|
||||||
|
match rt.block_on(backups.save_file(&path)) {
|
||||||
|
Ok(lines) => Response::Said { lines },
|
||||||
|
Err(why) => Response::Refused(self.hide(why)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(r) => *r,
|
||||||
|
},
|
||||||
Request::Adopt {
|
Request::Adopt {
|
||||||
id,
|
id,
|
||||||
source,
|
source,
|
||||||
@@ -2023,7 +2036,7 @@ impl Books {
|
|||||||
/// the access log; the client may retry it: INVARIANT 10);
|
/// the access log; the client may retry it: INVARIANT 10);
|
||||||
/// 3. its MCP sessions end;
|
/// 3. its MCP sessions end;
|
||||||
/// 4. the last backup, for `backup_at_close` at most; the backups are
|
/// 4. the last backup, for `backup_at_close` at most; the backups are
|
||||||
/// then shut, which stops a run still going (git killed) and waits
|
/// then shut, which stops a run still going (its copy stopped) and waits
|
||||||
/// for it to end, so the answer never comes while it runs;
|
/// for it to end, so the answer never comes while it runs;
|
||||||
/// 5. the access log, uploads and exports close, each under the lock
|
/// 5. the access log, uploads and exports close, each under the lock
|
||||||
/// its own writes go in under, so a late writer is refused;
|
/// its own writes go in under, so a late writer is refused;
|
||||||
@@ -2092,19 +2105,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))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2187,6 +2192,58 @@ impl Books {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The backups of the open book `id`, or the refusal to give a request
|
||||||
|
/// that needs them.
|
||||||
|
/// Back the books `id` up now (`new_disk`: their disk is new; `new_set`:
|
||||||
|
/// begin a new set beside the old one), what came of it.
|
||||||
|
fn back_up_response(&self, id: &str, new_disk: bool, new_set: bool) -> Response {
|
||||||
|
let id = match BookId::parse(id) {
|
||||||
|
Ok(id) => id,
|
||||||
|
Err(e) => return Response::Refused(e.to_string()),
|
||||||
|
};
|
||||||
|
let backups = match self.held().get(id.as_str()) {
|
||||||
|
Some(Book::Open { backups, .. }) => backups.clone(),
|
||||||
|
Some(Book::Failed(why)) => {
|
||||||
|
return Response::Refused(format!("those books didn't open: {why}"));
|
||||||
|
}
|
||||||
|
Some(Book::Closed) => return Response::Refused(self.not_open(&id)),
|
||||||
|
None => {
|
||||||
|
return Response::Refused(format!("there are no books called {:?}", id.as_str()));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let rt = tokio::runtime::Handle::current();
|
||||||
|
match rt.block_on(backups.run_with_set("asked", new_disk, new_set)) {
|
||||||
|
Ok(status) => Response::BackedUp {
|
||||||
|
head_seq: status.head_seq,
|
||||||
|
targets: status
|
||||||
|
.targets
|
||||||
|
.into_iter()
|
||||||
|
.map(|t| admin::BackedUpTarget {
|
||||||
|
target: t.target,
|
||||||
|
at: t.at,
|
||||||
|
through_seq: t.through_seq,
|
||||||
|
problem: t.last_error,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
},
|
||||||
|
Err(why) => Response::Refused(self.hide(why)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn backups_of(&self, id: &str) -> Result<Arc<crate::backup::Backups>, Box<Response>> {
|
||||||
|
let refused = |text: String| Box::new(Response::Refused(self.hide(text)));
|
||||||
|
let id = BookId::parse(id).map_err(|e| refused(e.to_string()))?;
|
||||||
|
match self.held().get(id.as_str()) {
|
||||||
|
Some(Book::Open { backups, .. }) => Ok(backups.clone()),
|
||||||
|
Some(Book::Failed(why)) => Err(refused(format!("those books didn't open: {why}"))),
|
||||||
|
Some(Book::Closed) => Err(refused(self.not_open(&id))),
|
||||||
|
None => Err(refused(format!(
|
||||||
|
"there are no books called {:?}",
|
||||||
|
id.as_str()
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// What is said of a book that exists but isn't open, to an admin
|
/// What is said of a book that exists but isn't open, to an admin
|
||||||
/// request that needs it open.
|
/// request that needs it open.
|
||||||
fn not_open(&self, id: &BookId) -> String {
|
fn not_open(&self, id: &BookId) -> String {
|
||||||
@@ -2203,8 +2260,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 +2275,25 @@ 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,
|
||||||
|
written: p.written,
|
||||||
|
newest_written: p.newest_written,
|
||||||
}),
|
}),
|
||||||
Err(e) => said(e.to_string()),
|
Err(e) => said(e.to_string()),
|
||||||
};
|
};
|
||||||
@@ -2291,7 +2348,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 +4376,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 +4562,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 +4572,20 @@ 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,
|
||||||
|
error_kind: None,
|
||||||
|
damaged_files: Vec::new(),
|
||||||
};
|
};
|
||||||
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 +5245,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, &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 +5306,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 +5344,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 +5376,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 +5386,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 +5409,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("wanderbooks-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 +5447,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 +5470,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) => {
|
||||||
|
|||||||
@@ -216,7 +216,7 @@ pub struct SharedStore {
|
|||||||
/// A close of these books has begun (`hurry`): a call that can run
|
/// A close of these books has begun (`hurry`): a call that can run
|
||||||
/// long (a verification, a backup asked for, a package of every stored
|
/// long (a verification, a backup asked for, a package of every stored
|
||||||
/// file) stops at its next look, answering that it was stopped. Shared
|
/// file) stops at its next look, answering that it was stopped. Shared
|
||||||
/// with the books' backups (backup.rs), whose git it stops.
|
/// with the books' backups (backup.rs), whose copy it stops.
|
||||||
hurry: Arc<std::sync::atomic::AtomicBool>,
|
hurry: Arc<std::sync::atomic::AtomicBool>,
|
||||||
/// Requests running (from before their blocking task to its end).
|
/// Requests running (from before their blocking task to its end).
|
||||||
running: std::sync::atomic::AtomicUsize,
|
running: std::sync::atomic::AtomicUsize,
|
||||||
@@ -392,7 +392,7 @@ impl SharedStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The stop flag itself, for what looks at it from another thread or
|
/// The stop flag itself, for what looks at it from another thread or
|
||||||
/// hands it to git (ledger_store `cancel`, `Git::with_cancel`).
|
/// hands it to the backup (ledger_store `cancel`, `Ctx::with_stop`).
|
||||||
pub fn hurry_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
|
pub fn hurry_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
|
||||||
self.hurry.clone()
|
self.hurry.clone()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -25,11 +25,17 @@ pub struct BackUpNowParams {
|
|||||||
/// should hold one is otherwise a disk not connected.
|
/// should hold one is otherwise a disk not connected.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub new_disk: bool,
|
pub new_disk: bool,
|
||||||
|
/// The backup folder holds a longer history of these books than they
|
||||||
|
/// have now (a restore from an older backup): begin a new backup set
|
||||||
|
/// beside the old one, which is never touched. Only when the human
|
||||||
|
/// says so.
|
||||||
|
#[serde(default)]
|
||||||
|
pub new_set: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, JsonSchema)]
|
#[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,
|
||||||
@@ -39,15 +45,27 @@ pub struct TargetOut {
|
|||||||
pub through_seq: Option<u64>,
|
pub through_seq: Option<u64>,
|
||||||
/// More than a day without the books' latest: tell the human.
|
/// More than a day without the books' latest: tell the human.
|
||||||
pub stale: bool,
|
pub stale: bool,
|
||||||
|
/// What kind of trouble the last backup or check had: `ahead` (the
|
||||||
|
/// folder holds a longer history of these books: offer new_set),
|
||||||
|
/// `elsewhere` (other or diverged books), `key_missing` (the backups
|
||||||
|
/// are sealed and this computer lost the key: ask the human for the
|
||||||
|
/// passphrase), `not_downloaded` (files a sync service has not put here
|
||||||
|
/// yet), `newest_damaged` (a restore would give older books).
|
||||||
|
pub error_kind: Option<String>,
|
||||||
|
/// Files in the backup folder found damaged and written again (each is
|
||||||
|
/// left where it is): tell the human.
|
||||||
|
pub damaged_files: Vec<String>,
|
||||||
/// Why its last backup failed, if it did.
|
/// 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)]
|
||||||
@@ -74,10 +92,13 @@ impl From<crate::backup::Status> for BackupOut {
|
|||||||
last_ok_at: t.last_ok_at,
|
last_ok_at: t.last_ok_at,
|
||||||
through_seq: t.through_seq,
|
through_seq: t.through_seq,
|
||||||
stale: t.stale,
|
stale: t.stale,
|
||||||
|
error_kind: t.error_kind,
|
||||||
|
damaged_files: t.damaged_files,
|
||||||
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 +110,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 +120,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. new_set: true only when the human says so after a backup failed because the folder holds a longer history of these books (error_kind ahead): a new set begins beside the old one. Needs books:admin.",
|
||||||
annotations(
|
annotations(
|
||||||
read_only_hint = false,
|
read_only_hint = false,
|
||||||
destructive_hint = false,
|
destructive_hint = false,
|
||||||
@@ -113,7 +134,11 @@ impl BooksServer {
|
|||||||
) -> Result<Json<BackupOut>, String> {
|
) -> Result<Json<BackupOut>, String> {
|
||||||
// Stopped by a close (backup.rs INVARIANT 11): said so, and on
|
// Stopped by a close (backup.rs INVARIANT 11): said so, and on
|
||||||
// record as stopped, not as an answer it gave.
|
// record as stopped, not as an answer it gave.
|
||||||
match self.backups.run_with("asked", params.0.new_disk).await {
|
match self
|
||||||
|
.backups
|
||||||
|
.run_with_set("asked", params.0.new_disk, params.0.new_set)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(status) => Ok(Json(status.into())),
|
Ok(status) => Ok(Json(status.into())),
|
||||||
Err(why) if why.starts_with(crate::server::STOPPED_BY_CLOSE_WORDS) => {
|
Err(why) if why.starts_with(crate::server::STOPPED_BY_CLOSE_WORDS) => {
|
||||||
crate::server::stopped_by_close();
|
crate::server::stopped_by_close();
|
||||||
|
|||||||
@@ -1038,11 +1038,11 @@ impl BooksServer {
|
|||||||
// failing.
|
// failing.
|
||||||
{
|
{
|
||||||
let st = self.backups.standing(store);
|
let st = self.backups.standing(store);
|
||||||
if st.note.is_some() {
|
if st.targets.is_empty() {
|
||||||
next_steps.push(step(
|
next_steps.push(step(
|
||||||
"books.backup",
|
"books.backup",
|
||||||
None,
|
None,
|
||||||
"No backups are set up: ask the human for a private repository and a folder on another disk, then set backup.git_remote and backup.folder (books.set_setting).",
|
"No backups are set up: ask the human which folder to back up to (a folder on another disk, or one a sync service keeps), then set backup.folder (books.set_setting).",
|
||||||
));
|
));
|
||||||
} else if st.needs_attention() {
|
} else if st.needs_attention() {
|
||||||
next_steps.push(step(
|
next_steps.push(step(
|
||||||
|
|||||||
@@ -1124,7 +1124,7 @@ impl BooksServer {
|
|||||||
/// ```text
|
/// ```text
|
||||||
/// GOAL: everything the CPA needs for the return in one zip, the K-1s'
|
/// GOAL: everything the CPA needs for the return in one zip, the K-1s'
|
||||||
/// and 1099s' TINs included, without a full TIN ever landing in
|
/// and 1099s' TINs included, without a full TIN ever landing in
|
||||||
/// the books (a git repository) or the conversation.
|
/// the books or the conversation.
|
||||||
/// SOURCE: docs/mcp-interface.md; BS-partner-2; DECISION (owner,
|
/// SOURCE: docs/mcp-interface.md; BS-partner-2; DECISION (owner,
|
||||||
/// 2026-10-15): "it needs to be in the damn CPA package."
|
/// 2026-10-15): "it needs to be in the damn CPA package."
|
||||||
/// INVARIANTS:
|
/// INVARIANTS:
|
||||||
|
|||||||
@@ -1294,7 +1294,7 @@ pub fn find_with(
|
|||||||
count(ids.len(), "stored file is", "stored files are")
|
count(ids.len(), "stored file is", "stored files are")
|
||||||
),
|
),
|
||||||
detail: format!(
|
detail: format!(
|
||||||
"Attachment {}: the bytes on disk don't match their recorded hash. Restore them from a backup (the books dir's git history).",
|
"Attachment {}: the bytes on disk don't match their recorded hash. Restore them from a backup.",
|
||||||
ids.join(", ")
|
ids.join(", ")
|
||||||
),
|
),
|
||||||
target: Target::Documents,
|
target: Target::Documents,
|
||||||
|
|||||||
@@ -25,6 +25,14 @@ hex = "0.4"
|
|||||||
getrandom = { version = "0.2", features = ["std"] }
|
getrandom = { version = "0.2", features = ["std"] }
|
||||||
subtle = "2"
|
subtle = "2"
|
||||||
argon2 = "0.6"
|
argon2 = "0.6"
|
||||||
|
# A backup protected by a passphrase is sealed as the TIN vault is
|
||||||
|
# (XChaCha20-Poly1305, already in the tree); its key is kept off the
|
||||||
|
# page when this program is done with it (D-92).
|
||||||
|
chacha20poly1305 = "0.11"
|
||||||
|
zeroize = "1"
|
||||||
|
# "Save a backup..." is one file: a zip of the backup's folder form (the
|
||||||
|
# crate the viewer and the packages already use, deflate only).
|
||||||
|
zip = { version = "9.0.1", default-features = false, features = ["deflate"] }
|
||||||
|
|
||||||
[target.'cfg(unix)'.dependencies]
|
[target.'cfg(unix)'.dependencies]
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,260 @@
|
|||||||
|
//! A cut of the books: what a backup is made from, taken in one look
|
||||||
|
//! under the store's lock, and read from the book's folder after it.
|
||||||
|
//!
|
||||||
|
//! The journal is append-only and a stored file never changes once it is
|
||||||
|
//! there, so what the lock has to fix is small: how long the journal is
|
||||||
|
//! (and that its last line is the head), how much of the access log is
|
||||||
|
//! whole lines, and the vault and the keys, which can change. Everything
|
||||||
|
//! else is read afterwards, outside the lock, and cannot move: the bytes
|
||||||
|
//! of the journal before the cut's length are the same bytes a moment
|
||||||
|
//! later.
|
||||||
|
|
||||||
|
use super::form::{IndexLine, is_plain_name, is_sha};
|
||||||
|
use super::{BackupError, Ctx};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::io::{Read, Seek, SeekFrom};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// A cut of one book. Take it with the store's lock held ([`Cut::take`]).
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Cut {
|
||||||
|
book: String,
|
||||||
|
dir: PathBuf,
|
||||||
|
head: (u64, String),
|
||||||
|
pub(crate) journal_len: u64,
|
||||||
|
pub(crate) access_len: u64,
|
||||||
|
pub(crate) vault: Vec<(String, Vec<u8>)>,
|
||||||
|
pub(crate) keys: Vec<(String, Vec<u8>)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bytes of the last line of `path`, which is `len` long and ends in a
|
||||||
|
/// newline, read from the end.
|
||||||
|
fn last_line(path: &Path, len: u64) -> std::io::Result<Vec<u8>> {
|
||||||
|
let mut f = std::fs::File::open(path)?;
|
||||||
|
let mut tail: Vec<u8> = Vec::new();
|
||||||
|
let mut at = len;
|
||||||
|
// Without the final newline; looking back for the one before it.
|
||||||
|
loop {
|
||||||
|
let step = at.min(64 * 1024);
|
||||||
|
at -= step;
|
||||||
|
f.seek(SeekFrom::Start(at))?;
|
||||||
|
let mut chunk = vec![0u8; step as usize];
|
||||||
|
f.read_exact(&mut chunk)?;
|
||||||
|
chunk.extend_from_slice(&tail);
|
||||||
|
tail = chunk;
|
||||||
|
if tail.last() != Some(&b'\n') {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
"the journal does not end in a whole line",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let body = &tail[..tail.len() - 1];
|
||||||
|
if let Some(i) = body.iter().rposition(|b| *b == b'\n') {
|
||||||
|
return Ok(body[i + 1..].to_vec());
|
||||||
|
}
|
||||||
|
if at == 0 {
|
||||||
|
return Ok(body.to_vec());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much of `path`, `len` long, is whole lines.
|
||||||
|
fn whole_lines(path: &Path, len: u64) -> std::io::Result<u64> {
|
||||||
|
let mut f = std::fs::File::open(path)?;
|
||||||
|
let mut at = len;
|
||||||
|
while at > 0 {
|
||||||
|
let step = at.min(64 * 1024);
|
||||||
|
at -= step;
|
||||||
|
f.seek(SeekFrom::Start(at))?;
|
||||||
|
let mut chunk = vec![0u8; step as usize];
|
||||||
|
f.read_exact(&mut chunk)?;
|
||||||
|
if let Some(i) = chunk.iter().rposition(|b| *b == b'\n') {
|
||||||
|
return Ok(at + i as u64 + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the exactly-once writes of the vault (ledger-vault `stage`,
|
||||||
|
/// `settle`) leave in its folder while a call is between its first step
|
||||||
|
/// and its last: a new record staged under `NAME.staged-TAG`, an old one
|
||||||
|
/// set aside under `NAME.purging-TAG`.
|
||||||
|
enum Scratch<'a> {
|
||||||
|
/// A record staged for a call that has not committed: not the books'
|
||||||
|
/// yet, and nothing the journal at the cut names.
|
||||||
|
Staged,
|
||||||
|
/// A record set aside for a purge that has not committed: still the
|
||||||
|
/// books' record as the journal at the cut stands, under the name it
|
||||||
|
/// has when it is not set aside (`own`).
|
||||||
|
Purging { own: &'a str },
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scratch_of(name: &str) -> Option<Scratch<'_>> {
|
||||||
|
if name.contains(".staged-") {
|
||||||
|
return Some(Scratch::Staged);
|
||||||
|
}
|
||||||
|
name.split_once(".purging-")
|
||||||
|
.map(|(stem, _)| Scratch::Purging { own: stem })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The plain files of a flat folder of a book, by name, with their bytes.
|
||||||
|
/// With `vault`, the vault's scratch files are met as they are meant (see
|
||||||
|
/// [`Scratch`]): never backed up as records of their own, so a backup cut
|
||||||
|
/// while a write of the vault is under way holds the vault as the journal
|
||||||
|
/// at the cut says it is.
|
||||||
|
fn flat_files(dir: &Path, vault: bool) -> Result<Vec<(String, Vec<u8>)>, BackupError> {
|
||||||
|
let entries = match std::fs::read_dir(dir) {
|
||||||
|
Ok(e) => e,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
};
|
||||||
|
let mut named: Vec<(String, PathBuf)> = Vec::new();
|
||||||
|
for entry in entries {
|
||||||
|
let entry = entry?;
|
||||||
|
let name = entry.file_name().to_string_lossy().into_owned();
|
||||||
|
let meta = std::fs::symlink_metadata(entry.path())?;
|
||||||
|
if !meta.is_file() || !is_plain_name(&name) {
|
||||||
|
return Err(BackupError::Damaged(format!(
|
||||||
|
"a folder of the books holds something no book keeps ({name:?})"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
named.push((name, entry.path()));
|
||||||
|
}
|
||||||
|
let held: std::collections::BTreeSet<String> = named.iter().map(|(n, _)| n.clone()).collect();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (name, path) in named {
|
||||||
|
let name = match vault.then(|| scratch_of(&name)).flatten() {
|
||||||
|
None => name,
|
||||||
|
Some(Scratch::Staged) => continue,
|
||||||
|
Some(Scratch::Purging { own }) => {
|
||||||
|
let own = format!("{own}.bin");
|
||||||
|
if held.contains(&own) {
|
||||||
|
// The record was written anew: that one is the books'.
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
own
|
||||||
|
}
|
||||||
|
};
|
||||||
|
out.push((name, std::fs::read(path)?));
|
||||||
|
}
|
||||||
|
out.sort();
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Cut {
|
||||||
|
/// Take a cut of the book `book` kept in `dir`, whose journal's head
|
||||||
|
/// is `head`. The caller holds the store's lock, so the journal is
|
||||||
|
/// whole lines and the vault matches it.
|
||||||
|
pub fn take(book: &str, dir: &Path, head: (u64, String)) -> Result<Cut, BackupError> {
|
||||||
|
let journal = dir.join(crate::JOURNAL_FILE);
|
||||||
|
let journal_len = match std::fs::metadata(&journal) {
|
||||||
|
Ok(m) => m.len(),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
};
|
||||||
|
if head.0 == 0 {
|
||||||
|
if journal_len != 0 {
|
||||||
|
return Err(BackupError::Damaged(
|
||||||
|
"the journal has lines the books don't count".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let line = last_line(&journal, journal_len)?;
|
||||||
|
if hex::encode(Sha256::digest(&line)) != head.1 {
|
||||||
|
return Err(BackupError::Damaged(
|
||||||
|
"the journal's last line isn't the books' head".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let access = dir.join(crate::access::ACCESS_FILE);
|
||||||
|
let access_len = match std::fs::metadata(&access) {
|
||||||
|
Ok(m) => whole_lines(&access, m.len())?,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
};
|
||||||
|
Ok(Cut {
|
||||||
|
book: book.to_string(),
|
||||||
|
dir: dir.to_path_buf(),
|
||||||
|
head,
|
||||||
|
journal_len,
|
||||||
|
access_len,
|
||||||
|
vault: flat_files(&dir.join(crate::root::VAULT_DIR), true)?,
|
||||||
|
keys: flat_files(&dir.join(crate::root::KEYS_DIR), false)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The book's folder the cut was taken from.
|
||||||
|
pub(crate) fn dir(&self) -> &Path {
|
||||||
|
&self.dir
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The books' id.
|
||||||
|
pub fn book(&self) -> &str {
|
||||||
|
&self.book
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The journal's head at the cut: seq and hash.
|
||||||
|
pub fn head(&self) -> &(u64, String) {
|
||||||
|
&self.head
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn journal_path(&self) -> PathBuf {
|
||||||
|
self.dir.join(crate::JOURNAL_FILE)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn access_path(&self) -> PathBuf {
|
||||||
|
self.dir.join(crate::access::ACCESS_FILE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stored files, by hash, with their lengths: those named as this
|
||||||
|
/// program names them (`blobs/ab/cd/<sha256>`), nothing else.
|
||||||
|
pub(crate) fn stored_files(&self, ctx: &Ctx) -> Result<Vec<IndexLine>, BackupError> {
|
||||||
|
let root = self.dir.join(crate::store::BLOBS_DIR);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let level = |p: &Path| -> std::io::Result<Vec<std::fs::DirEntry>> {
|
||||||
|
match std::fs::read_dir(p) {
|
||||||
|
Ok(e) => e.collect(),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for a in level(&root)? {
|
||||||
|
ctx.check("listing the stored files")?;
|
||||||
|
let an = a.file_name().to_string_lossy().into_owned();
|
||||||
|
if an.len() != 2 || !a.path().is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for b in level(&a.path())? {
|
||||||
|
let bn = b.file_name().to_string_lossy().into_owned();
|
||||||
|
if bn.len() != 2 || !b.path().is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for f in level(&b.path())? {
|
||||||
|
let name = f.file_name().to_string_lossy().into_owned();
|
||||||
|
let meta = std::fs::symlink_metadata(f.path())?;
|
||||||
|
if meta.is_file()
|
||||||
|
&& is_sha(&name)
|
||||||
|
&& name.starts_with(&an)
|
||||||
|
&& name[2..].starts_with(&bn)
|
||||||
|
{
|
||||||
|
out.push(IndexLine {
|
||||||
|
sha256: name,
|
||||||
|
bytes: meta.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.sort_by(|x, y| x.sha256.cmp(&y.sha256));
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a stored file is in the book.
|
||||||
|
pub(crate) fn blob_path(&self, sha: &str) -> PathBuf {
|
||||||
|
self.dir
|
||||||
|
.join(crate::store::BLOBS_DIR)
|
||||||
|
.join(&sha[0..2])
|
||||||
|
.join(&sha[2..4])
|
||||||
|
.join(sha)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,419 @@
|
|||||||
|
//! The records of a backup: pieces, series of pieces, and the manifest
|
||||||
|
//! that names them, and the names a piece is kept under.
|
||||||
|
//!
|
||||||
|
//! A *series* is what grows: the journal, the access log and the index of
|
||||||
|
//! stored files are each a run of immutable segments whose bytes, read one
|
||||||
|
//! after another, are the whole. A backup that has new lines adds a
|
||||||
|
//! segment; nothing already written is touched.
|
||||||
|
|
||||||
|
use super::BackupError;
|
||||||
|
use super::seal::Keys;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
/// What a manifest says it is.
|
||||||
|
pub(crate) const FORMAT: &str = "wanderbooks-backup";
|
||||||
|
/// The form's version. A reader refuses one it does not know.
|
||||||
|
pub(crate) const VERSION: u32 = 1;
|
||||||
|
/// The folder name of a plain set begins with this.
|
||||||
|
pub(crate) const SET_PREFIX: &str = "wanderbooks-";
|
||||||
|
/// The folder of manifests in a set.
|
||||||
|
pub(crate) const MANIFESTS: &str = "manifests";
|
||||||
|
/// The folder of proof marks in a set: one tiny file per manifest whose
|
||||||
|
/// proof (write.rs) came out whole, so a manifest whose proof was cut short
|
||||||
|
/// is proven by the next backup, even one with nothing new to write.
|
||||||
|
pub(crate) const PROOFS: &str = "proofs";
|
||||||
|
/// The words a person can open.
|
||||||
|
pub(crate) const READ_ME: &str = "READ-ME.txt";
|
||||||
|
/// The sealed form's header: how to derive the key.
|
||||||
|
pub(crate) const HEADER: &str = "header.json";
|
||||||
|
/// Where a sealed set keeps every piece, under names that say nothing.
|
||||||
|
pub(crate) const PIECES: &str = "pieces";
|
||||||
|
/// A manifest names the one before it and only what is new, until a chain
|
||||||
|
/// of this many is made; then one names everything again. A reader walks
|
||||||
|
/// at most this many manifests (each proven by the hash its successor
|
||||||
|
/// holds) to know one manifest's whole.
|
||||||
|
pub(crate) const DELTA_CHAIN: u32 = 64;
|
||||||
|
|
||||||
|
/// The kinds of piece.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) enum Kind {
|
||||||
|
/// A segment of the journal.
|
||||||
|
Journal,
|
||||||
|
/// A segment of the access log.
|
||||||
|
Access,
|
||||||
|
/// A segment of the index of stored files.
|
||||||
|
Index,
|
||||||
|
/// A stored file.
|
||||||
|
File,
|
||||||
|
/// A vault record.
|
||||||
|
Vault,
|
||||||
|
/// A key file.
|
||||||
|
Key,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Kind {
|
||||||
|
pub(crate) fn dir(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Kind::Journal => "journal",
|
||||||
|
Kind::Access => "access",
|
||||||
|
Kind::Index => "files-index",
|
||||||
|
Kind::File => "files",
|
||||||
|
Kind::Vault => "vault",
|
||||||
|
Kind::Key => "keys",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One piece: a file of the set, by where it is, how long it is as it is
|
||||||
|
/// kept, and what is in it.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct Piece {
|
||||||
|
/// Its path in the set.
|
||||||
|
pub file: String,
|
||||||
|
/// Its length as kept (sealed pieces are longer than their contents).
|
||||||
|
pub stored: u64,
|
||||||
|
/// Its contents' length.
|
||||||
|
pub bytes: u64,
|
||||||
|
/// Its contents' SHA-256, hex.
|
||||||
|
pub sha256: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A run of segments, and what they make together.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct Series {
|
||||||
|
/// Bytes in all the segments.
|
||||||
|
pub bytes: u64,
|
||||||
|
/// SHA-256 of all of them, one after another, hex.
|
||||||
|
pub sha256: String,
|
||||||
|
/// The segments, in order. In a manifest that names the one before it
|
||||||
|
/// ([`Manifest::base`]), only those after the first `keep`.
|
||||||
|
pub segments: Vec<Piece>,
|
||||||
|
/// How many of its base's first segments this series begins with (a
|
||||||
|
/// manifest that names its base only). Always 0 once read whole.
|
||||||
|
#[serde(default, skip_serializing_if = "is_zero_usize")]
|
||||||
|
pub keep: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_zero_usize(n: &usize) -> bool {
|
||||||
|
*n == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_zero_u32(n: &u32) -> bool {
|
||||||
|
*n == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The manifest a delta manifest is built on: its number and what its
|
||||||
|
/// body hashes to, so a changed or swapped base is known.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct BaseRef {
|
||||||
|
/// Its number.
|
||||||
|
pub number: u64,
|
||||||
|
/// SHA-256 of its body (the text before its check line), hex.
|
||||||
|
pub sha256: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A file named by its place in a flat folder of a book (the vault, the
|
||||||
|
/// keys).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct Named {
|
||||||
|
/// Its name in the book's folder.
|
||||||
|
pub name: String,
|
||||||
|
/// Where it is kept.
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub piece: Piece,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The journal's head.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct Head {
|
||||||
|
/// Its last line's seq.
|
||||||
|
pub seq: u64,
|
||||||
|
/// Its last line's hash.
|
||||||
|
pub hash: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What makes a backup whole: written last, and never again.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct Manifest {
|
||||||
|
/// [`FORMAT`].
|
||||||
|
pub format: String,
|
||||||
|
/// [`VERSION`].
|
||||||
|
pub version: u32,
|
||||||
|
/// The books' id, as they were backed up.
|
||||||
|
pub book: String,
|
||||||
|
/// Its number in the set: also its name.
|
||||||
|
pub number: u64,
|
||||||
|
/// When it was written (UTC).
|
||||||
|
pub written: String,
|
||||||
|
/// The journal's head it reaches.
|
||||||
|
pub head: Head,
|
||||||
|
/// The journal.
|
||||||
|
pub journal: Series,
|
||||||
|
/// The access log.
|
||||||
|
pub access: Series,
|
||||||
|
/// The index of stored files: one `{"sha256","bytes"}` per line.
|
||||||
|
pub files: Series,
|
||||||
|
/// How many stored files the index names, and their bytes.
|
||||||
|
pub file_count: u64,
|
||||||
|
/// Bytes of the stored files.
|
||||||
|
pub file_bytes: u64,
|
||||||
|
/// The vault's records.
|
||||||
|
pub vault: Vec<Named>,
|
||||||
|
/// The keys.
|
||||||
|
pub keys: Vec<Named>,
|
||||||
|
/// The manifest this one is built on, when it names only what is new
|
||||||
|
/// in its series (the vault and keys are always named whole).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub base: Option<BaseRef>,
|
||||||
|
/// How many manifests are chained below this one (0 for one that names
|
||||||
|
/// everything).
|
||||||
|
#[serde(default, skip_serializing_if = "is_zero_u32")]
|
||||||
|
pub depth: u32,
|
||||||
|
/// What its body hashes to: set when it is read or written, never
|
||||||
|
/// part of it.
|
||||||
|
#[serde(skip)]
|
||||||
|
pub sha: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A line of the index of stored files.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct IndexLine {
|
||||||
|
/// The file's SHA-256, hex.
|
||||||
|
pub sha256: String,
|
||||||
|
/// Its length.
|
||||||
|
pub bytes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SHA-256, hex.
|
||||||
|
pub(crate) fn sha_hex(bytes: &[u8]) -> String {
|
||||||
|
hex::encode(Sha256::digest(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `s` is a SHA-256 in hex as this program writes it.
|
||||||
|
pub(crate) fn is_sha(s: &str) -> bool {
|
||||||
|
s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A name in a book's flat folders: nothing that could leave the folder.
|
||||||
|
pub(crate) fn is_plain_name(s: &str) -> bool {
|
||||||
|
!s.is_empty()
|
||||||
|
&& s.len() <= 200
|
||||||
|
&& s != "."
|
||||||
|
&& s != ".."
|
||||||
|
&& s.bytes()
|
||||||
|
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The manifest's file name in a set, as its number.
|
||||||
|
pub(crate) fn manifest_path(number: u64, sealed: bool) -> String {
|
||||||
|
if sealed {
|
||||||
|
format!("{MANIFESTS}/{number:06}")
|
||||||
|
} else {
|
||||||
|
format!("{MANIFESTS}/{number:06}.json")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The mark that manifest `number` was proven whole.
|
||||||
|
pub(crate) fn proof_path(number: u64) -> String {
|
||||||
|
format!("{PROOFS}/{number:06}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The number a manifest file name carries, if it is one.
|
||||||
|
pub(crate) fn manifest_number(name: &str, sealed: bool) -> Option<u64> {
|
||||||
|
let digits = if sealed {
|
||||||
|
name
|
||||||
|
} else {
|
||||||
|
name.strip_suffix(".json")?
|
||||||
|
};
|
||||||
|
if digits.len() < 6 || !digits.bytes().all(|b| b.is_ascii_digit()) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let n: u64 = digits.parse().ok()?;
|
||||||
|
// Exactly the name this program writes (no conflict copy of one, no
|
||||||
|
// other spelling of the same number).
|
||||||
|
(manifest_path(n, sealed) == format!("{MANIFESTS}/{name}")).then_some(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a piece of `kind` whose contents hash to `sha` is kept, as the
|
||||||
|
/// `ordinal`th of its series. Sealed sets keep every piece under a name
|
||||||
|
/// made from the key and the hash (it says nothing of what the piece is),
|
||||||
|
/// in a folder of its first two digits, so no folder grows past what a
|
||||||
|
/// small disk's file system allows.
|
||||||
|
pub(crate) fn piece_path(keys: Option<&Keys>, kind: Kind, ordinal: usize, sha: &str) -> String {
|
||||||
|
match keys {
|
||||||
|
Some(k) => {
|
||||||
|
let name = k.piece_name(kind.dir(), sha);
|
||||||
|
format!("{PIECES}/{}/{name}", &name[..2])
|
||||||
|
}
|
||||||
|
None => match kind {
|
||||||
|
Kind::Journal | Kind::Access | Kind::Index => {
|
||||||
|
format!("{}/{:06}-{}", kind.dir(), ordinal + 1, &sha[..16])
|
||||||
|
}
|
||||||
|
Kind::File => format!("{}/{}/{sha}", kind.dir(), &sha[..2]),
|
||||||
|
Kind::Vault | Kind::Key => format!("{}/{sha}", kind.dir()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The path of generation `g` of the piece kept at `base`: generation 0
|
||||||
|
/// is `base` itself. A piece found damaged is written again under the next
|
||||||
|
/// generation, beside the damaged file, which is never touched.
|
||||||
|
pub(crate) fn generation_path(base: &str, g: u32) -> String {
|
||||||
|
if g == 0 {
|
||||||
|
base.to_string()
|
||||||
|
} else {
|
||||||
|
format!("{base}.g{g}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The path without its generation suffix, and the generation.
|
||||||
|
pub(crate) fn split_generation(path: &str) -> (&str, u32) {
|
||||||
|
if let Some((stem, g)) = path.rsplit_once(".g")
|
||||||
|
&& !g.is_empty()
|
||||||
|
&& g.bytes().all(|b| b.is_ascii_digit())
|
||||||
|
&& let Ok(n) = g.parse::<u32>()
|
||||||
|
&& n > 0
|
||||||
|
{
|
||||||
|
return (stem, n);
|
||||||
|
}
|
||||||
|
(path, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The folder a set of `book` is kept in, in a destination, when it is not
|
||||||
|
/// sealed: a fixed prefix and the id, so the name is legal on every
|
||||||
|
/// system whatever the id is (`con` and `nul` are not names on Windows,
|
||||||
|
/// `wanderbooks-con` is). A later set of the same books, begun beside the
|
||||||
|
/// first, ends `.2`, `.3`: no id holds a dot, so none is another book's.
|
||||||
|
pub(crate) fn plain_set_name(book: &str, number: u32) -> String {
|
||||||
|
if number <= 1 {
|
||||||
|
format!("{SET_PREFIX}{book}")
|
||||||
|
} else {
|
||||||
|
format!("{SET_PREFIX}{book}.{number}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The book and set number a plain set's folder name says, if it is one.
|
||||||
|
pub(crate) fn parse_plain_set_name(name: &str) -> Option<(&str, u32)> {
|
||||||
|
let rest = name.strip_prefix(SET_PREFIX)?;
|
||||||
|
let (book, number) = match rest.rsplit_once('.') {
|
||||||
|
Some((book, n)) => (book, n.parse::<u32>().ok().filter(|n| *n >= 2)?),
|
||||||
|
None => (rest, 1),
|
||||||
|
};
|
||||||
|
(!book.is_empty()).then_some((book, number))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A manifest as written: its JSON, a newline, and a line that is the
|
||||||
|
/// SHA-256 of that JSON, so a short or changed one is known for what it is.
|
||||||
|
pub(crate) fn encode_manifest(m: &Manifest) -> Vec<u8> {
|
||||||
|
let body = serde_json::to_string(m).expect("a manifest serializes");
|
||||||
|
let check = sha_hex(body.as_bytes());
|
||||||
|
format!("{body}\nwanderbooks-manifest-sha256 {check}\n").into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A manifest read back, or why it is not one.
|
||||||
|
pub(crate) fn decode_manifest(bytes: &[u8]) -> Result<Manifest, BackupError> {
|
||||||
|
let bad = || BackupError::Damaged("a manifest of the backup is cut short or changed".into());
|
||||||
|
let text = std::str::from_utf8(bytes).map_err(|_| bad())?;
|
||||||
|
let text = text.strip_suffix('\n').ok_or_else(bad)?;
|
||||||
|
let (body, check) = text.rsplit_once('\n').ok_or_else(bad)?;
|
||||||
|
let check = check
|
||||||
|
.strip_prefix("wanderbooks-manifest-sha256 ")
|
||||||
|
.ok_or_else(bad)?;
|
||||||
|
if check != sha_hex(body.as_bytes()) {
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let mut m: Manifest = serde_json::from_str(body).map_err(|_| bad())?;
|
||||||
|
m.sha = check.to_string();
|
||||||
|
if m.format != FORMAT {
|
||||||
|
return Err(BackupError::Damaged(
|
||||||
|
"that isn't a wanderbooks backup".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if m.version != VERSION {
|
||||||
|
return Err(BackupError::Damaged(
|
||||||
|
"that backup was made by a newer wanderbooks: update to read it".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Manifest {
|
||||||
|
/// What this manifest holds, apart from its number and time: two with
|
||||||
|
/// the same content need not both be written.
|
||||||
|
pub(crate) fn same_content(&self, other: &Manifest) -> bool {
|
||||||
|
let mut a = self.clone();
|
||||||
|
let mut b = other.clone();
|
||||||
|
for m in [&mut a, &mut b] {
|
||||||
|
m.number = 0;
|
||||||
|
m.written.clear();
|
||||||
|
m.base = None;
|
||||||
|
m.depth = 0;
|
||||||
|
m.sha.clear();
|
||||||
|
}
|
||||||
|
a == b
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every name in it is one this program would have written: nothing
|
||||||
|
/// that could lead out of the set or into another's.
|
||||||
|
pub(crate) fn check_names(&self, sealed: bool) -> Result<(), BackupError> {
|
||||||
|
let bad = |why: &str| BackupError::Damaged(format!("a manifest of the backup {why}"));
|
||||||
|
if !is_sha(&self.head.hash) && self.head.seq > 0 {
|
||||||
|
return Err(bad("has a head that is not a hash"));
|
||||||
|
}
|
||||||
|
for series in [&self.journal, &self.access, &self.files] {
|
||||||
|
if !is_sha(&series.sha256) && series.bytes > 0 {
|
||||||
|
return Err(bad("has a series that is not a hash"));
|
||||||
|
}
|
||||||
|
let total = series
|
||||||
|
.segments
|
||||||
|
.iter()
|
||||||
|
.fold(0u64, |a, s| a.saturating_add(s.bytes));
|
||||||
|
if total != series.bytes {
|
||||||
|
return Err(bad("has segments that don't add up"));
|
||||||
|
}
|
||||||
|
for p in &series.segments {
|
||||||
|
self.check_piece(p, sealed)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for n in self.vault.iter().chain(&self.keys) {
|
||||||
|
if !is_plain_name(&n.name) {
|
||||||
|
return Err(bad("names a file no book keeps"));
|
||||||
|
}
|
||||||
|
self.check_piece(&n.piece, sealed)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_piece(&self, p: &Piece, sealed: bool) -> Result<(), BackupError> {
|
||||||
|
let bad = |why: &str| BackupError::Damaged(format!("a manifest of the backup {why}"));
|
||||||
|
if !is_sha(&p.sha256) {
|
||||||
|
return Err(bad("has a piece that is not a hash"));
|
||||||
|
}
|
||||||
|
let ok_path = p.file.split('/').all(|part| {
|
||||||
|
!part.is_empty()
|
||||||
|
&& part != "."
|
||||||
|
&& part != ".."
|
||||||
|
&& part
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
|
||||||
|
});
|
||||||
|
let starts = [
|
||||||
|
"journal/",
|
||||||
|
"access/",
|
||||||
|
"files-index/",
|
||||||
|
"files/",
|
||||||
|
"vault/",
|
||||||
|
"keys/",
|
||||||
|
];
|
||||||
|
let right_place = if sealed {
|
||||||
|
p.file.starts_with(&format!("{PIECES}/"))
|
||||||
|
} else {
|
||||||
|
starts.iter().any(|s| p.file.starts_with(s))
|
||||||
|
};
|
||||||
|
if !ok_path || !right_place {
|
||||||
|
return Err(bad("names a piece outside the backup"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,489 @@
|
|||||||
|
//! Where a backup's files live, behind one seam: a folder on a disk
|
||||||
|
//! ([`DirSet`]), or the one-file form ([`crate::backup::single`]).
|
||||||
|
//!
|
||||||
|
//! 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
|
||||||
|
//! there. Nothing deletes, nothing replaces (INVARIANT 1 of the module).
|
||||||
|
//!
|
||||||
|
//! How a file is put (the whole of the argument for two writers):
|
||||||
|
//!
|
||||||
|
//! * It is written under a name no reader looks at (`.wb-tmp-…`, in the
|
||||||
|
//! folder it is for), synced, and then given its real name by a
|
||||||
|
//! *hard link*, which every disk and every network share this program
|
||||||
|
//! meets either does atomically and exclusively (the name is made, or
|
||||||
|
//! it exists already: Unix, NTFS, SMB, NFS) or refuses outright (FAT and
|
||||||
|
//! exFAT disks, some sync folders). A rename is not used for a manifest
|
||||||
|
//! because on Windows a rename replaces what is at the new name, and on
|
||||||
|
//! some network shares it does so without telling.
|
||||||
|
//! * Only an error that means "this disk makes no links" ([`link_unsupported`],
|
||||||
|
//! named per platform) sends a put down the no-link path. Any other
|
||||||
|
//! error is an error: it is never taken to mean that a rename, which
|
||||||
|
//! replaces what is at the new name on POSIX and on Windows, will do.
|
||||||
|
//! * Where links are refused, the finished scratch file is moved into
|
||||||
|
//! place by a move that *refuses to replace*: `renameat2` with
|
||||||
|
//! `RENAME_NOREPLACE` on Linux, `renamex_np` with `RENAME_EXCL` on macOS,
|
||||||
|
//! `MoveFileExW` without `MOVEFILE_REPLACE_EXISTING` on Windows
|
||||||
|
//! ([`rename_new`]). Where even that is not offered (a file system that
|
||||||
|
//! cannot say no), the last resort is exclusive create (`create_new`)
|
||||||
|
//! under the real name and a copy of the bytes in: nothing is replaced,
|
||||||
|
//! but a crash in the middle leaves a short file under the real name,
|
||||||
|
//! which the next proof finds (it re-hashes) and repairs by writing the
|
||||||
|
//! piece again under a new generation (write.rs); a short manifest is
|
||||||
|
//! accepted by no reader (it carries its own check), and its number is
|
||||||
|
//! spent.
|
||||||
|
//! * A file that is there already is never touched: a piece is taken as
|
||||||
|
//! the piece (the proof after the backup re-hashes it, and a piece found
|
||||||
|
//! damaged is written again beside it); a manifest number taken is
|
||||||
|
//! reported to the writer, which looks again and tries the next.
|
||||||
|
//!
|
||||||
|
//! The scratch names are the one thing this code removes from a
|
||||||
|
//! destination, and only the file it made itself a moment before; one left
|
||||||
|
//! by a process that died stays (a person may delete `.wb-tmp-*` by hand).
|
||||||
|
|
||||||
|
use super::{BackupError, Ctx};
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// What kind of file is being put: how an existing file at the name is met.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) enum PutKind {
|
||||||
|
/// Named by what is in it: if it is there, it is the one.
|
||||||
|
Piece,
|
||||||
|
/// One for the whole set, written once (the read-me, the header): if
|
||||||
|
/// it is there, it stays.
|
||||||
|
Once,
|
||||||
|
/// A manifest: the name is a number, taken exclusively. The decision
|
||||||
|
/// point of a backup.
|
||||||
|
Manifest,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a put came out.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) enum Put {
|
||||||
|
/// This call made the file.
|
||||||
|
Created,
|
||||||
|
/// It was there already: untouched.
|
||||||
|
Existed,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fill a file: the callback writes its bytes.
|
||||||
|
pub(crate) type Fill<'a> = &'a mut dyn FnMut(&mut dyn Write) -> std::io::Result<()>;
|
||||||
|
|
||||||
|
/// Where a set's files live.
|
||||||
|
pub(crate) trait SetIo: Send + Sync {
|
||||||
|
/// The names directly in `dir` (a path in the set, `/` between parts),
|
||||||
|
/// none if it is not there.
|
||||||
|
fn list(&self, dir: &str) -> std::io::Result<Vec<String>>;
|
||||||
|
/// How long the file at `rel` is, None if it is not there.
|
||||||
|
fn len(&self, rel: &str) -> std::io::Result<Option<u64>>;
|
||||||
|
/// Read the file at `rel` through `f`.
|
||||||
|
fn read_with(
|
||||||
|
&self,
|
||||||
|
rel: &str,
|
||||||
|
f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>,
|
||||||
|
) -> std::io::Result<()>;
|
||||||
|
/// Put a file at `rel` that is not there ([`PutKind`]).
|
||||||
|
fn put(&self, rel: &str, kind: PutKind, fill: Fill<'_>) -> std::io::Result<Put>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A backup error carried through an `io::Error` (a callback that has to
|
||||||
|
/// stop the file it is writing).
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Carried(BackupError);
|
||||||
|
|
||||||
|
impl std::fmt::Display for Carried {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
self.0.fmt(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for Carried {}
|
||||||
|
|
||||||
|
/// `e` as an `io::Error` a callback can return.
|
||||||
|
pub(crate) fn carry(e: BackupError) -> std::io::Error {
|
||||||
|
std::io::Error::other(Carried(e))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A backup error back out of an `io::Error` (one that was carried, or the
|
||||||
|
/// disk's own).
|
||||||
|
pub(crate) fn uncarry(e: std::io::Error) -> BackupError {
|
||||||
|
match e.get_ref().and_then(|i| i.downcast_ref::<Carried>()) {
|
||||||
|
Some(c) => c.0.clone(),
|
||||||
|
None => BackupError::Io(e.kind()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A set that is a folder on a disk.
|
||||||
|
pub(crate) struct DirSet {
|
||||||
|
root: PathBuf,
|
||||||
|
ctx: Ctx,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DirSet {
|
||||||
|
/// The set in the folder `root` (which need not exist yet).
|
||||||
|
pub(crate) fn new(root: PathBuf, ctx: Ctx) -> Self {
|
||||||
|
Self { root, ctx }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path(&self, rel: &str) -> PathBuf {
|
||||||
|
let mut p = self.root.clone();
|
||||||
|
for part in rel.split('/').filter(|s| !s.is_empty()) {
|
||||||
|
p.push(part);
|
||||||
|
}
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the sync service's stand-in for the file at `rel` is there
|
||||||
|
/// (`.name.icloud` beside where the file should be).
|
||||||
|
fn stand_in_for(&self, rel: &str) -> bool {
|
||||||
|
let path = self.path(rel);
|
||||||
|
match (path.parent(), path.file_name().and_then(|n| n.to_str())) {
|
||||||
|
(Some(dir), Some(name)) => dir.join(format!(".{name}.icloud")).exists(),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The finished file at `tmp` given its real name `path` on a disk
|
||||||
|
/// that makes no links: by a move that refuses to replace, else by
|
||||||
|
/// exclusive create and copy. The scratch file is gone after.
|
||||||
|
fn place_without_links(&self, tmp: &Path, path: &Path) -> std::io::Result<Put> {
|
||||||
|
let moved = if self.ctx.refuses_noreplace() {
|
||||||
|
Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
|
||||||
|
} else {
|
||||||
|
rename_new(tmp, path)
|
||||||
|
};
|
||||||
|
match moved {
|
||||||
|
Ok(()) => Ok(Put::Created),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||||
|
let _ = std::fs::remove_file(tmp);
|
||||||
|
Ok(Put::Existed)
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::Unsupported => {
|
||||||
|
// The last resort: made exclusively under the real name,
|
||||||
|
// and the finished scratch file copied into it.
|
||||||
|
let mut file = match std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(path)
|
||||||
|
{
|
||||||
|
Ok(f) => f,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||||
|
let _ = std::fs::remove_file(tmp);
|
||||||
|
return Ok(Put::Existed);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let _ = std::fs::remove_file(tmp);
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let copied = (|| -> std::io::Result<()> {
|
||||||
|
let mut from = std::fs::File::open(tmp)?;
|
||||||
|
{
|
||||||
|
let mut w = std::io::BufWriter::with_capacity(1 << 16, &mut file);
|
||||||
|
std::io::copy(&mut from, &mut w)?;
|
||||||
|
w.flush()?;
|
||||||
|
}
|
||||||
|
file.sync_all()
|
||||||
|
})();
|
||||||
|
let _ = std::fs::remove_file(tmp);
|
||||||
|
copied?;
|
||||||
|
Ok(Put::Created)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let _ = std::fs::remove_file(tmp);
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A name for a scratch file: unique to this process and moment.
|
||||||
|
fn scratch_name() -> String {
|
||||||
|
let mut r = [0u8; 6];
|
||||||
|
let _ = getrandom::getrandom(&mut r);
|
||||||
|
format!(
|
||||||
|
".wb-tmp-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
r.iter().map(|b| format!("{b:02x}")).collect::<String>()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether Windows file attributes say the file is a placeholder of an
|
||||||
|
/// online-only service (OneDrive, Dropbox Smart Sync, iCloud for Windows):
|
||||||
|
/// `FILE_ATTRIBUTE_OFFLINE` (0x1000), `FILE_ATTRIBUTE_RECALL_ON_OPEN`
|
||||||
|
/// (0x40000) or `FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS` (0x400000). Reading
|
||||||
|
/// one makes Windows fetch it, which may take long or fail with no
|
||||||
|
/// network, so it is reported as not downloaded, not read.
|
||||||
|
#[allow(dead_code)] // used where Windows attributes are read; tested everywhere
|
||||||
|
pub(crate) fn placeholder_attributes(attrs: u32) -> bool {
|
||||||
|
attrs & (0x1000 | 0x40000 | 0x400000) != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether macOS file flags say the file is dataless (an iCloud or file
|
||||||
|
/// provider stand-in whose contents are not on this disk): `SF_DATALESS`.
|
||||||
|
#[allow(dead_code)] // used where macOS flags are read; tested everywhere
|
||||||
|
pub(crate) fn dataless_flags(flags: u32) -> bool {
|
||||||
|
flags & 0x4000_0000 != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the name is the stand-in a sync service leaves for a file it
|
||||||
|
/// has not downloaded (iCloud before macOS 14: `.name.icloud`).
|
||||||
|
pub(crate) fn is_stand_in_name(name: &str) -> bool {
|
||||||
|
name.len() > ".x.icloud".len() - 1 && name.starts_with('.') && name.ends_with(".icloud")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the file's metadata says it is online only. Where nothing can
|
||||||
|
/// tell (Linux, whatever the sync client), false: such a file reads as
|
||||||
|
/// what it is, and a short or missing one is found by the proof.
|
||||||
|
fn online_only(meta: &std::fs::Metadata) -> bool {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::fs::MetadataExt;
|
||||||
|
placeholder_attributes(meta.file_attributes())
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
use std::os::macos::fs::MetadataExt;
|
||||||
|
dataless_flags(meta.st_flags())
|
||||||
|
}
|
||||||
|
#[cfg(not(any(windows, target_os = "macos")))]
|
||||||
|
{
|
||||||
|
let _ = meta;
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Make a folder's entries durable (Unix; NTFS journals its own).
|
||||||
|
pub(crate) fn sync_dir(path: &Path) {
|
||||||
|
#[cfg(unix)]
|
||||||
|
if let Ok(dir) = std::fs::File::open(path) {
|
||||||
|
let _ = dir.sync_all();
|
||||||
|
}
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
let _ = path;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a failed hard link means the disk does not make links (FAT,
|
||||||
|
/// exFAT, some network shares and sync folders), as against the name
|
||||||
|
/// being taken or the disk refusing for another reason. The errors that
|
||||||
|
/// mean it, by platform:
|
||||||
|
///
|
||||||
|
/// * Unix: `EPERM` (what Linux's vfat and exFAT answer), `ENOSYS`,
|
||||||
|
/// `EOPNOTSUPP` and `ENOTSUP` (network and FUSE file systems), and the
|
||||||
|
/// portable kind `Unsupported`.
|
||||||
|
/// * Windows: `ERROR_INVALID_FUNCTION` (1, FAT and exFAT), `ERROR_NOT_SUPPORTED`
|
||||||
|
/// (50), `ERROR_INVALID_PARAMETER` (87) and `ERROR_CALL_NOT_IMPLEMENTED`
|
||||||
|
/// (120).
|
||||||
|
pub(crate) fn link_unsupported(e: &std::io::Error) -> bool {
|
||||||
|
if e.kind() == std::io::ErrorKind::Unsupported {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let Some(n) = e.raw_os_error() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
n == libc::EPERM || n == libc::ENOSYS || n == libc::EOPNOTSUPP || n == libc::ENOTSUP
|
||||||
|
}
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
matches!(n, 1 | 50 | 87 | 120)
|
||||||
|
}
|
||||||
|
#[cfg(not(any(unix, windows)))]
|
||||||
|
{
|
||||||
|
let _ = n;
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Move `from` to `to`, which must not be there: never over something
|
||||||
|
/// already at `to` (that is `AlreadyExists`). `Unsupported` when the file
|
||||||
|
/// system cannot refuse to replace, which the caller meets by exclusive
|
||||||
|
/// create and copy.
|
||||||
|
fn rename_new(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
{
|
||||||
|
use std::os::unix::ffi::OsStrExt;
|
||||||
|
let f = std::ffi::CString::new(from.as_os_str().as_bytes())?;
|
||||||
|
let t = std::ffi::CString::new(to.as_os_str().as_bytes())?;
|
||||||
|
// SAFETY: two NUL-terminated paths that live past the call.
|
||||||
|
let rc = unsafe {
|
||||||
|
libc::renameat2(
|
||||||
|
libc::AT_FDCWD,
|
||||||
|
f.as_ptr(),
|
||||||
|
libc::AT_FDCWD,
|
||||||
|
t.as_ptr(),
|
||||||
|
libc::RENAME_NOREPLACE,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if rc == 0 {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let e = std::io::Error::last_os_error();
|
||||||
|
match e.raw_os_error() {
|
||||||
|
Some(n) if n == libc::EINVAL || n == libc::ENOSYS || n == libc::ENOTSUP => {
|
||||||
|
Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
|
||||||
|
}
|
||||||
|
_ => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
use std::os::unix::ffi::OsStrExt;
|
||||||
|
let f = std::ffi::CString::new(from.as_os_str().as_bytes())?;
|
||||||
|
let t = std::ffi::CString::new(to.as_os_str().as_bytes())?;
|
||||||
|
// SAFETY: two NUL-terminated paths that live past the call.
|
||||||
|
let rc = unsafe { libc::renamex_np(f.as_ptr(), t.as_ptr(), libc::RENAME_EXCL) };
|
||||||
|
if rc == 0 {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let e = std::io::Error::last_os_error();
|
||||||
|
match e.raw_os_error() {
|
||||||
|
Some(n) if n == libc::ENOTSUP || n == libc::EINVAL || n == libc::ENOSYS => {
|
||||||
|
Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
|
||||||
|
}
|
||||||
|
_ => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
// MoveFileExW without MOVEFILE_REPLACE_EXISTING refuses an
|
||||||
|
// existing target itself.
|
||||||
|
crate::winsec::rename_new(from, to)
|
||||||
|
}
|
||||||
|
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
|
||||||
|
{
|
||||||
|
let _ = (from, to);
|
||||||
|
Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SetIo for DirSet {
|
||||||
|
fn list(&self, dir: &str) -> std::io::Result<Vec<String>> {
|
||||||
|
match std::fs::read_dir(self.path(dir)) {
|
||||||
|
Ok(entries) => {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for e in entries {
|
||||||
|
if let Some(n) = e?.file_name().to_str() {
|
||||||
|
// A stand-in of a file not downloaded: it is
|
||||||
|
// there, though not as the file itself.
|
||||||
|
if is_stand_in_name(n) {
|
||||||
|
return Err(carry(BackupError::NotDownloaded));
|
||||||
|
}
|
||||||
|
out.push(n.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.sort();
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn len(&self, rel: &str) -> std::io::Result<Option<u64>> {
|
||||||
|
self.ctx.traced("len", rel);
|
||||||
|
match std::fs::symlink_metadata(self.path(rel)) {
|
||||||
|
// A link is not a file of a backup: it could lead anywhere.
|
||||||
|
Ok(m) if m.is_file() && online_only(&m) => Err(carry(BackupError::NotDownloaded)),
|
||||||
|
Ok(m) if m.is_file() => Ok(Some(m.len())),
|
||||||
|
Ok(_) => Ok(None),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
if self.stand_in_for(rel) {
|
||||||
|
Err(carry(BackupError::NotDownloaded))
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_with(
|
||||||
|
&self,
|
||||||
|
rel: &str,
|
||||||
|
f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
self.ctx.traced("read", rel);
|
||||||
|
let path = self.path(rel);
|
||||||
|
let meta = match std::fs::symlink_metadata(&path) {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound && self.stand_in_for(rel) => {
|
||||||
|
return Err(carry(BackupError::NotDownloaded));
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
};
|
||||||
|
if online_only(&meta) {
|
||||||
|
return Err(carry(BackupError::NotDownloaded));
|
||||||
|
}
|
||||||
|
if !meta.is_file() {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
"not a plain file",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut file = std::fs::File::open(path)?;
|
||||||
|
f(&mut file)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put(&self, rel: &str, kind: PutKind, fill: Fill<'_>) -> std::io::Result<Put> {
|
||||||
|
let path = self.path(rel);
|
||||||
|
let parent = path.parent().unwrap_or(&self.root).to_path_buf();
|
||||||
|
std::fs::create_dir_all(&parent)?;
|
||||||
|
if kind != PutKind::Manifest && std::fs::symlink_metadata(&path).is_ok() {
|
||||||
|
return Ok(Put::Existed);
|
||||||
|
}
|
||||||
|
let tmp = parent.join(scratch_name());
|
||||||
|
self.ctx.point("create", rel).map_err(carry)?;
|
||||||
|
let written = (|| -> std::io::Result<()> {
|
||||||
|
let mut file = std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(&tmp)?;
|
||||||
|
{
|
||||||
|
let mut w = std::io::BufWriter::with_capacity(1 << 16, &mut file);
|
||||||
|
fill(&mut w)?;
|
||||||
|
w.flush()?;
|
||||||
|
}
|
||||||
|
if self.ctx.syncs() {
|
||||||
|
file.sync_all()
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
if let Err(e) = written {
|
||||||
|
// Something of ours that failed on its own: its scratch file
|
||||||
|
// goes (a death, which `point` reports, leaves it).
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
self.ctx.point("written", rel).map_err(carry)?;
|
||||||
|
let linked = if self.ctx.refuses_links() {
|
||||||
|
// A test's disk that makes no links.
|
||||||
|
Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
|
||||||
|
} else {
|
||||||
|
std::fs::hard_link(&tmp, &path)
|
||||||
|
};
|
||||||
|
let put = match linked {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
Put::Created
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
Put::Existed
|
||||||
|
}
|
||||||
|
Err(e) if link_unsupported(&e) => self.place_without_links(&tmp, &path)?,
|
||||||
|
// Any other error is an error: never a reason to replace.
|
||||||
|
Err(e) => {
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if self.ctx.syncs() {
|
||||||
|
sync_dir(&parent);
|
||||||
|
}
|
||||||
|
self.ctx.point("published", rel).map_err(carry)?;
|
||||||
|
Ok(put)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,410 @@
|
|||||||
|
//! Backups in plain folders (plan/p15-app-and-relay.md section 9, D-91,
|
||||||
|
//! D-92): a backup is a folder the person picks, holding one folder per
|
||||||
|
//! set of books, made only of files that are written once.
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! GOAL: a book's every write survives the loss of this computer, a
|
||||||
|
//! backup is proven whole before it is trusted or restored, and the
|
||||||
|
//! person needs nothing installed and nothing explained to have one.
|
||||||
|
//! SOURCE: plan/p15-app-and-relay.md section 9 (the form, D-91: git leaves
|
||||||
|
//! backups entirely; D-92: a passphrase, off by default), plan 3.7
|
||||||
|
//! (what a backup holds, when it runs, the proof after it, the
|
||||||
|
//! weekly drill), 3.9 and D-39 (a proven local backup with the
|
||||||
|
//! keys before a format upgrade), WB-backup-1.
|
||||||
|
//! INVARIANTS:
|
||||||
|
//! 1. Nothing in a destination is ever deleted or rewritten. Every file
|
||||||
|
//! is put once (io.rs): a piece under a name made from what is in it,
|
||||||
|
//! a manifest under its number, taken exclusively. The one thing this
|
||||||
|
//! code removes from a destination is the scratch file it made itself
|
||||||
|
//! a moment before. So a destination only grows, a syncing service
|
||||||
|
//! never sees a file change under it, and an earlier state of the
|
||||||
|
//! books is always still there.
|
||||||
|
//! 2. A backup is whole when its manifest is in place, and not before.
|
||||||
|
//! The manifest is written last, after every piece it names is there;
|
||||||
|
//! a run that dies leaves pieces no manifest names, which are
|
||||||
|
//! harmless, and at most a short manifest, which no reader accepts
|
||||||
|
//! (it carries its own check) and whose number is spent.
|
||||||
|
//! 3. A manifest names every piece it needs, by where it is, how long it
|
||||||
|
//! is and what is in it (SHA-256), either itself or by naming the
|
||||||
|
//! manifest before it (by number and by what its body hashes to) and
|
||||||
|
//! only what is new, a chain of at most `DELTA_CHAIN` links; a reader
|
||||||
|
//! proves the chain link by link. A reader tries the manifests newest
|
||||||
|
//! first and takes the first whose pieces are all there at the length
|
||||||
|
//! it names and that proves (`verify_found`), reading no more: the
|
||||||
|
//! journal's chain replays to the head the manifest records, the books
|
||||||
|
//! open, every stored file re-hashes, every vault record the books name
|
||||||
|
//! and the key that opens them are there. A piece is accepted under
|
||||||
|
//! any generation of it whose contents hash right.
|
||||||
|
//! 4. A backup is written only onto a destination whose newest whole
|
||||||
|
//! manifest is a point on the live journal (same line, same hash,
|
||||||
|
//! same place in the file). Otherwise it is said, and nothing is
|
||||||
|
//! written: the live journal is the beginning of a longer one
|
||||||
|
//! (`Ahead`: the books are behind the folder, and a new set may be
|
||||||
|
//! begun beside the old at the person's request), or the books are
|
||||||
|
//! others or have diverged (`Elsewhere`).
|
||||||
|
//! 5. Two programs, or two computers, writing one destination cannot
|
||||||
|
//! corrupt it: pieces are named by what is in them, so two writers of
|
||||||
|
//! one piece write the same bytes; the only decision is which of them
|
||||||
|
//! takes the next manifest number, and the disk decides it
|
||||||
|
//! (exclusive create). The loser looks again and goes on from what the
|
||||||
|
//! winner wrote, or finds there is nothing left to write.
|
||||||
|
//! 6. A manifest that is lost, or replaced by a sync service's conflict
|
||||||
|
//! copy, makes unreadable only the manifests chained on it (at most
|
||||||
|
//! the rest of its chain of 64); every earlier one, and every later
|
||||||
|
//! one that names everything, stands.
|
||||||
|
//! 7. With a passphrase every piece, every manifest, is sealed
|
||||||
|
//! (seal.rs); names say no more than counts and sizes; the key is
|
||||||
|
//! derived by a memory-hard function; this computer keeps it in the
|
||||||
|
//! book's `local/` folder, owner-only, never in a backup. A wrong
|
||||||
|
//! passphrase opens nothing, and is told from damage.
|
||||||
|
//! 8. A step that has to end when the books are let go looks for the
|
||||||
|
//! stop between pieces, and once per chunk of a file read; a stopped
|
||||||
|
//! backup leaves a destination that proves whole at its previous
|
||||||
|
//! manifest.
|
||||||
|
//! 9. Nothing here names a path of the data root: errors speak of "the
|
||||||
|
//! backup folder".
|
||||||
|
//! 10. A backup is proven before it is recorded good (write.rs
|
||||||
|
//! `prove_and_repair`, read.rs `prove_written`): the manifest just put
|
||||||
|
//! is read back, every journal and access segment re-hashed, the chain
|
||||||
|
//! replayed to its head, the vault and keys present, and the stored
|
||||||
|
//! files this backup added and one sixteenth of the rest re-hashed (a
|
||||||
|
//! share that comes round within 16 backups); what is found damaged is
|
||||||
|
//! written again under a new generation beside it and proven again.
|
||||||
|
//! A manifest whose proof was cut short is marked unproven (no mark in
|
||||||
|
//! `proofs/`) and proven by the next backup.
|
||||||
|
//! 11. A drill passes only on the newest manifest, and only if it reaches
|
||||||
|
//! the last head recorded good (`drill`).
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
|
mod cut;
|
||||||
|
mod form;
|
||||||
|
mod io;
|
||||||
|
mod read;
|
||||||
|
mod seal;
|
||||||
|
mod single;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
mod write;
|
||||||
|
|
||||||
|
pub use cut::Cut;
|
||||||
|
pub use read::list;
|
||||||
|
pub use read::{Candidate, Found, Verified, drill, find, prove_local, verify_found};
|
||||||
|
pub use seal::{BackupKey, key_derivations};
|
||||||
|
pub use single::{FILE_EXTENSION, save_file};
|
||||||
|
pub use write::{
|
||||||
|
Destination, Options, Written, holds_only_sealed, set_name_for, write_destination,
|
||||||
|
write_destination_with, write_local,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// What a backup holds, of a book's folder.
|
||||||
|
pub const BACKED_UP: [&str; 5] = [
|
||||||
|
crate::JOURNAL_FILE,
|
||||||
|
"blobs",
|
||||||
|
crate::root::VAULT_DIR,
|
||||||
|
crate::root::KEYS_DIR,
|
||||||
|
crate::access::ACCESS_FILE,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// A book's own local backup, in its folder: the same form as a
|
||||||
|
/// destination, written under the store's lock before a format upgrade.
|
||||||
|
pub const LOCAL_DIR: &str = "local-backup";
|
||||||
|
|
||||||
|
/// Why a backup couldn't be made, proven or restored. Never names a path
|
||||||
|
/// of the data root (INVARIANT 9).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum BackupError {
|
||||||
|
/// A folder that isn't there (an external disk not connected).
|
||||||
|
#[error("the backup folder isn't there (is its disk connected?)")]
|
||||||
|
NoFolder,
|
||||||
|
/// A folder that took these books' backups but holds none now (a disk
|
||||||
|
/// not mounted on its mount point, or a new disk).
|
||||||
|
#[error(
|
||||||
|
"the backup folder holds no backup of these books: connect the disk that does; if it is a new disk, back up now saying so (new_disk)"
|
||||||
|
)]
|
||||||
|
NoBackupThere,
|
||||||
|
/// The destination holds other books, or another history of these.
|
||||||
|
#[error(
|
||||||
|
"the backup folder holds a backup of other books, or of a different history of these books (they have diverged): nothing was written there"
|
||||||
|
)]
|
||||||
|
Elsewhere,
|
||||||
|
/// The destination holds a longer history of these same books.
|
||||||
|
#[error(
|
||||||
|
"the backup folder holds a longer history of these books (through event {0}) than this computer has (event {1}), as after restoring from an older backup: nothing was written there. If these books are the ones to carry on with, start a new backup set beside the old one: the old one is never touched"
|
||||||
|
)]
|
||||||
|
Ahead(u64, u64),
|
||||||
|
/// Another program kept taking the next place in the destination.
|
||||||
|
#[error("another program kept writing to the backup folder: try again in a moment")]
|
||||||
|
Busy,
|
||||||
|
/// A backup that isn't whole.
|
||||||
|
#[error("that backup can't be trusted: {0}")]
|
||||||
|
Damaged(String),
|
||||||
|
/// The backup is protected by a passphrase and none was given.
|
||||||
|
#[error("that backup is protected by a passphrase: it needs the passphrase it was made with")]
|
||||||
|
NeedsPassphrase,
|
||||||
|
/// The backups were sealed with a passphrase and this computer has
|
||||||
|
/// lost its key.
|
||||||
|
#[error(
|
||||||
|
"these backups are protected by a passphrase, but this computer no longer has its key: nothing was written. Enter the passphrase in the backup settings to carry on, or choose remove the passphrase there to back up without one"
|
||||||
|
)]
|
||||||
|
KeyMissing,
|
||||||
|
/// A file of the backup folder is online only: its sync service has
|
||||||
|
/// not put it on this computer.
|
||||||
|
#[error(
|
||||||
|
"some files in the backup folder are online only and not downloaded to this computer yet: open the folder in your sync app, keep it available offline, wait until it has finished, and try again"
|
||||||
|
)]
|
||||||
|
NotDownloaded,
|
||||||
|
/// The newest backup does not prove whole; an older one does.
|
||||||
|
#[error("{}", newest_damaged_words(*.number, .older_from.as_deref(), .newest_from.as_deref()))]
|
||||||
|
NewestDamaged {
|
||||||
|
/// The newest manifest's number.
|
||||||
|
number: u64,
|
||||||
|
/// When the newest was made, if it can be read.
|
||||||
|
newest_from: Option<String>,
|
||||||
|
/// When the newest one that proves whole was made (None: none does).
|
||||||
|
older_from: Option<String>,
|
||||||
|
},
|
||||||
|
/// The passphrase given opens nothing.
|
||||||
|
#[error("that isn't the passphrase this backup was made with")]
|
||||||
|
WrongPassphrase,
|
||||||
|
/// A passphrase of a length not taken.
|
||||||
|
#[error(
|
||||||
|
"a backup passphrase is {} to {} characters long",
|
||||||
|
crate::passphrase::MIN_CHARS,
|
||||||
|
crate::passphrase::MAX_CHARS
|
||||||
|
)]
|
||||||
|
PassphraseLength,
|
||||||
|
/// More than one set of books is there, and which was not said.
|
||||||
|
#[error(
|
||||||
|
"that folder holds backups of more than one set of books ({0}): choose the folder of one"
|
||||||
|
)]
|
||||||
|
Several(String),
|
||||||
|
/// Nothing there is a backup.
|
||||||
|
#[error("there is no backup there")]
|
||||||
|
NotABackup,
|
||||||
|
/// Stopped because the books are closing.
|
||||||
|
#[error("{0} was stopped: the books are closing")]
|
||||||
|
Cancelled(String),
|
||||||
|
/// A test's death at a write point; never made otherwise.
|
||||||
|
#[doc(hidden)]
|
||||||
|
#[error("the program died here")]
|
||||||
|
Died,
|
||||||
|
/// The disk refused.
|
||||||
|
#[error("the backup couldn't be made: {0}")]
|
||||||
|
Io(std::io::ErrorKind),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<std::io::Error> for BackupError {
|
||||||
|
fn from(e: std::io::Error) -> Self {
|
||||||
|
io::uncarry(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<crate::StoreError> for BackupError {
|
||||||
|
fn from(e: crate::StoreError) -> Self {
|
||||||
|
match e {
|
||||||
|
crate::StoreError::Cancelled => BackupError::Cancelled("verifying".into()),
|
||||||
|
e => BackupError::Damaged(e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn newest_damaged_words(number: u64, older: Option<&str>, newest: Option<&str>) -> String {
|
||||||
|
let which = match newest {
|
||||||
|
Some(d) => format!("the newest backup (number {number}, from {d})"),
|
||||||
|
None => format!("the newest backup (number {number})"),
|
||||||
|
};
|
||||||
|
match older {
|
||||||
|
Some(d) => format!(
|
||||||
|
"{which} is damaged; an older one from {d} is whole, and a restore would give that one, not the newest"
|
||||||
|
),
|
||||||
|
None => format!("{which} is damaged, and no older one proves whole either"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Told the name of each phase of a long step as it begins (the server's
|
||||||
|
/// test knob waits in them).
|
||||||
|
pub type PhaseWatch = Arc<dyn Fn(&str) + Send + Sync>;
|
||||||
|
|
||||||
|
/// A test's way to die at a write point: told the kind of point and the
|
||||||
|
/// file it is for, answers true to die there.
|
||||||
|
pub type Faults = Arc<dyn Fn(&str, &str) -> bool + Send + Sync>;
|
||||||
|
|
||||||
|
/// What a step is run under: the stop it looks for (INVARIANT 8) and, in
|
||||||
|
/// tests, where it dies.
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
pub struct Ctx {
|
||||||
|
stop: Option<Arc<AtomicBool>>,
|
||||||
|
faults: Option<Faults>,
|
||||||
|
phase: Option<PhaseWatch>,
|
||||||
|
/// Tests: a disk that makes no hard links, and one whose move cannot
|
||||||
|
/// refuse to replace.
|
||||||
|
no_links: bool,
|
||||||
|
no_noreplace: bool,
|
||||||
|
/// Tests: nothing is synced to disk (a destination of thousands of
|
||||||
|
/// backups is made quickly; a real one never is).
|
||||||
|
no_sync: bool,
|
||||||
|
/// Tests: the proof after a backup is left out (for the tests that make
|
||||||
|
/// many backups only to see what is written, which prove what they
|
||||||
|
/// made themselves).
|
||||||
|
no_proof: bool,
|
||||||
|
/// Tests: told each read and length look at a file of the set.
|
||||||
|
trace: Option<Trace>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A test's look at which files of a set are read or measured.
|
||||||
|
pub type Trace = Arc<dyn Fn(&str, &str) + Send + Sync>;
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Ctx {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("Ctx")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ctx {
|
||||||
|
/// No stop, no faults.
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stopped when `flag` is set.
|
||||||
|
pub fn with_stop(mut self, flag: Arc<AtomicBool>) -> Self {
|
||||||
|
self.stop = Some(flag);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dies where `faults` says (tests).
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn with_faults(mut self, faults: Faults) -> Self {
|
||||||
|
self.faults = Some(faults);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A disk that makes no hard links (tests: the commonest other disk,
|
||||||
|
/// FAT or exFAT on a stick).
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn with_no_hard_links(mut self) -> Self {
|
||||||
|
self.no_links = true;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A disk that makes no links and whose move cannot refuse to replace
|
||||||
|
/// (tests: the last resort of `io.rs`).
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn with_no_exclusive_move(mut self) -> Self {
|
||||||
|
self.no_links = true;
|
||||||
|
self.no_noreplace = true;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Told, in tests, each `read` and `len` of a file of a set.
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn with_trace(mut self, trace: Trace) -> Self {
|
||||||
|
self.trace = Some(trace);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn traced(&self, kind: &str, rel: &str) {
|
||||||
|
if let Some(t) = &self.trace {
|
||||||
|
t(kind, rel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nothing is synced to disk (tests that make thousands of backups).
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn with_no_sync(mut self) -> Self {
|
||||||
|
self.no_sync = true;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The proof after a backup is left out (tests that make many backups
|
||||||
|
/// only to see what is written; the proof has tests of its own).
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn with_proof_skipped(mut self) -> Self {
|
||||||
|
self.no_proof = true;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn skips_proof(&self) -> bool {
|
||||||
|
self.no_proof
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn syncs(&self) -> bool {
|
||||||
|
!self.no_sync
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn refuses_links(&self) -> bool {
|
||||||
|
self.no_links
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn refuses_noreplace(&self) -> bool {
|
||||||
|
self.no_noreplace
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Told each phase of a long step as it begins.
|
||||||
|
pub fn with_phase_watch(mut self, watch: PhaseWatch) -> Self {
|
||||||
|
self.phase = Some(watch);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A phase of a step begins.
|
||||||
|
pub(crate) fn phase(&self, name: &str) {
|
||||||
|
if let Some(w) = &self.phase {
|
||||||
|
w(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stop flag, if there is one.
|
||||||
|
pub fn stop_flag(&self) -> Option<Arc<AtomicBool>> {
|
||||||
|
self.stop.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ok, or [`BackupError::Cancelled`] when a stop was asked for.
|
||||||
|
pub fn check(&self, what: &str) -> Result<(), BackupError> {
|
||||||
|
if self.stop.as_ref().is_some_and(|f| f.load(Ordering::SeqCst)) {
|
||||||
|
Err(BackupError::Cancelled(what.to_string()))
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A write point: where a test's fault may die.
|
||||||
|
pub(crate) fn point(&self, kind: &str, rel: &str) -> Result<(), BackupError> {
|
||||||
|
match &self.faults {
|
||||||
|
Some(f) if f(kind, rel) => Err(BackupError::Died),
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a person sees of a backup's standing in one line of the record:
|
||||||
|
/// serialisable pieces for the server.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Reached {
|
||||||
|
/// The journal seq the backup reaches.
|
||||||
|
pub seq: u64,
|
||||||
|
/// Its hash.
|
||||||
|
pub hash: String,
|
||||||
|
/// The number of the manifest that made it whole.
|
||||||
|
pub number: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The words in a set's READ-ME, for a person who opens the folder.
|
||||||
|
pub(crate) const READ_ME_TEXT: &str = "\
|
||||||
|
This folder is a backup of a set of books kept with Wanderbooks.
|
||||||
|
|
||||||
|
Nothing in it needs to be opened or changed by hand, and nothing in it is
|
||||||
|
ever deleted or rewritten by Wanderbooks: a backup only adds files. If your
|
||||||
|
disk is short of room you may delete the whole folder, but not parts of it.
|
||||||
|
|
||||||
|
To get the books back, open Wanderbooks and choose Restore, then point it at
|
||||||
|
this folder (or at the folder above it). It checks everything before it
|
||||||
|
puts anything in place.
|
||||||
|
|
||||||
|
If these backups are protected by a passphrase, the files here are sealed:
|
||||||
|
only Wanderbooks with that passphrase can read them, and nobody can recover
|
||||||
|
a forgotten passphrase.
|
||||||
|
";
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,504 @@
|
|||||||
|
//! A backup protected by a passphrase (D-92): the key, the header that
|
||||||
|
//! lets another computer derive it, the sealed form of a piece, and the
|
||||||
|
//! key kept privately on this computer.
|
||||||
|
//!
|
||||||
|
//! The passphrase is run through Argon2id (the same function and the same
|
||||||
|
//! cost as the owner passphrase, `passphrase.rs`: 64 MiB, 3 passes, 1 lane,
|
||||||
|
//! RFC 9106) with a random salt of its own. The 32 bytes it gives (the
|
||||||
|
//! *master*) are what this computer keeps, never the passphrase. Two keys
|
||||||
|
//! come from the master, each by SHA-256 of a label and the master: the
|
||||||
|
//! one pieces are sealed with, and the one their names are made with.
|
||||||
|
//!
|
||||||
|
//! A piece is sealed in chunks of 1 MiB with XChaCha20-Poly1305 (as the TIN
|
||||||
|
//! vault is): a random 16-byte prefix per piece and an 8-byte chunk
|
||||||
|
//! counter make each chunk's 24-byte nonce; each chunk's associated data
|
||||||
|
//! is the piece's identity (what is in it) and whether it is the last, so
|
||||||
|
//! a piece cut short, reordered, or put under another's name is not
|
||||||
|
//! opened.
|
||||||
|
|
||||||
|
use super::BackupError;
|
||||||
|
use super::form::sha_hex;
|
||||||
|
use argon2::{Algorithm, Argon2, Params, Version};
|
||||||
|
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||||
|
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::path::Path;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
/// The sealed piece's first bytes.
|
||||||
|
const MAGIC: &[u8; 4] = b"WBS1";
|
||||||
|
/// Plaintext bytes in a chunk.
|
||||||
|
const CHUNK: usize = 1 << 20;
|
||||||
|
/// What a chunk's seal adds.
|
||||||
|
const TAG: usize = 16;
|
||||||
|
/// The salt's length.
|
||||||
|
const SALT_LEN: usize = 16;
|
||||||
|
/// The words the header's check seals: opening them tells a right
|
||||||
|
/// passphrase from a wrong one.
|
||||||
|
const CHECK_TEXT: &[u8] = b"wanderbooks backup key check";
|
||||||
|
/// The local key file's folder in a book's folder, and its name.
|
||||||
|
pub(crate) const LOCAL_DIR: &str = "local";
|
||||||
|
/// The key file's name.
|
||||||
|
pub(crate) const KEY_FILE: &str = "backup-key.json";
|
||||||
|
|
||||||
|
/// How the passphrase is stretched. Recorded in the header so another
|
||||||
|
/// computer derives the same key.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct Kdf {
|
||||||
|
pub alg: String,
|
||||||
|
pub m: u32,
|
||||||
|
pub t: u32,
|
||||||
|
pub p: u32,
|
||||||
|
/// Hex.
|
||||||
|
pub salt: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key a passphrase makes, with how it was made. Kept on this
|
||||||
|
/// computer in the book's `local/` folder; never in a backup, never in the
|
||||||
|
/// journal, never in a log (its `Debug` says nothing of the key).
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct BackupKey {
|
||||||
|
kdf: Kdf,
|
||||||
|
master: Zeroizing<[u8; 32]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for BackupKey {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("BackupKey(..)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many times this program's own setting a header may ask for, of
|
||||||
|
/// memory, passes and lanes: a header is read from a folder anyone may
|
||||||
|
/// have written, and what it asks for is spent before the passphrase is
|
||||||
|
/// known right.
|
||||||
|
const KDF_CAP_FACTOR: u32 = 4;
|
||||||
|
|
||||||
|
/// Whether `kdf` asks nothing weaker than this program's own cost, and
|
||||||
|
/// nothing more than [`KDF_CAP_FACTOR`] times it (a header changed by
|
||||||
|
/// hand, or written to make a computer spend its memory).
|
||||||
|
fn kdf_in_bounds(kdf: &Kdf) -> bool {
|
||||||
|
use crate::passphrase::{M_COST, P_COST, T_COST};
|
||||||
|
kdf.alg == "argon2id"
|
||||||
|
&& (M_COST..=M_COST.saturating_mul(KDF_CAP_FACTOR)).contains(&kdf.m)
|
||||||
|
&& (T_COST..=T_COST.saturating_mul(KDF_CAP_FACTOR)).contains(&kdf.t)
|
||||||
|
&& (P_COST..=P_COST.saturating_mul(KDF_CAP_FACTOR)).contains(&kdf.p)
|
||||||
|
&& hex::decode(&kdf.salt).is_ok_and(|s| (SALT_LEN..=64).contains(&s.len()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the header's sealed check is bound to: the settings the key was
|
||||||
|
/// made with, so that the check opens only under the settings it was
|
||||||
|
/// sealed with. (A change a disk or a person makes by accident breaks the
|
||||||
|
/// header's own check line and reads as damage; one made on purpose, with
|
||||||
|
/// that line made right again, can only make the key come out different,
|
||||||
|
/// which opens nothing: no passphrase is guessed faster by it.)
|
||||||
|
fn header_aad(kdf: &Kdf) -> Vec<u8> {
|
||||||
|
format!(
|
||||||
|
"wb1|header|{}|{}|{}|{}|{}",
|
||||||
|
kdf.alg, kdf.m, kdf.t, kdf.p, kdf.salt
|
||||||
|
)
|
||||||
|
.into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many keys this program has derived from a passphrase (tests: a
|
||||||
|
/// folder of sealed sets costs one derivation per distinct setting).
|
||||||
|
static DERIVATIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||||
|
|
||||||
|
/// How many keys have been derived by this process.
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn key_derivations() -> usize {
|
||||||
|
DERIVATIONS.load(std::sync::atomic::Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stretch(passphrase: &str, kdf: &Kdf) -> Result<Zeroizing<[u8; 32]>, BackupError> {
|
||||||
|
if !kdf_in_bounds(kdf) {
|
||||||
|
return Err(BackupError::Damaged(
|
||||||
|
"its header asks for a key this program won't derive".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
DERIVATIONS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
let salt = hex::decode(&kdf.salt).expect("checked");
|
||||||
|
let params = Params::new(kdf.m, kdf.t, kdf.p, Some(32))
|
||||||
|
.map_err(|_| BackupError::Damaged("its header's key settings are not valid".into()))?;
|
||||||
|
let mut out = Zeroizing::new([0u8; 32]);
|
||||||
|
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
|
||||||
|
.hash_password_into(passphrase.as_bytes(), &salt, &mut *out)
|
||||||
|
.map_err(|_| BackupError::Damaged("the key could not be derived".into()))?;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BackupKey {
|
||||||
|
/// A new key from `passphrase` with a salt of its own.
|
||||||
|
pub fn generate(passphrase: &str) -> Result<Self, BackupError> {
|
||||||
|
crate::passphrase::check_length(passphrase).map_err(|_| BackupError::PassphraseLength)?;
|
||||||
|
let mut salt = [0u8; SALT_LEN];
|
||||||
|
getrandom::getrandom(&mut salt)
|
||||||
|
.map_err(|e| BackupError::Io(std::io::Error::from(e).kind()))?;
|
||||||
|
let kdf = Kdf {
|
||||||
|
alg: "argon2id".into(),
|
||||||
|
m: crate::passphrase::M_COST,
|
||||||
|
t: crate::passphrase::T_COST,
|
||||||
|
p: crate::passphrase::P_COST,
|
||||||
|
salt: hex::encode(salt),
|
||||||
|
};
|
||||||
|
let master = stretch(passphrase, &kdf)?;
|
||||||
|
Ok(Self { kdf, master })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn label(&self, label: &str) -> Zeroizing<[u8; 32]> {
|
||||||
|
let mut h = Sha256::new();
|
||||||
|
h.update(b"wanderbooks backup v1 ");
|
||||||
|
h.update(label.as_bytes());
|
||||||
|
h.update(*self.master);
|
||||||
|
Zeroizing::new(h.finalize().into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sealing and naming keys.
|
||||||
|
pub(crate) fn keys(&self) -> Keys {
|
||||||
|
Keys {
|
||||||
|
enc: self.label("encryption"),
|
||||||
|
names: self.label("names"),
|
||||||
|
kdf: self.kdf.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same key as another: the same passphrase and salt.
|
||||||
|
pub fn same_as(&self, other: &BackupKey) -> bool {
|
||||||
|
use subtle::ConstantTimeEq;
|
||||||
|
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).
|
||||||
|
pub fn store(&self, book_dir: &Path) -> Result<(), BackupError> {
|
||||||
|
let dir = crate::root::private_book_folder(book_dir, LOCAL_DIR)
|
||||||
|
.map_err(|e| BackupError::Damaged(e.to_string()))?;
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct OnDisk<'a> {
|
||||||
|
version: u32,
|
||||||
|
kdf: &'a Kdf,
|
||||||
|
master: String,
|
||||||
|
}
|
||||||
|
let text = Zeroizing::new(
|
||||||
|
serde_json::to_string_pretty(&OnDisk {
|
||||||
|
version: 1,
|
||||||
|
kdf: &self.kdf,
|
||||||
|
master: hex::encode(*self.master),
|
||||||
|
})
|
||||||
|
.expect("a key serializes"),
|
||||||
|
);
|
||||||
|
let tmp = dir.join(format!(".{KEY_FILE}.new"));
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
crate::root::write_new_private_file(&tmp, text.as_bytes())?;
|
||||||
|
std::fs::rename(&tmp, dir.join(KEY_FILE))?;
|
||||||
|
super::io::sync_dir(&dir);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key kept for the book in `book_dir`, if one is.
|
||||||
|
pub fn load(book_dir: &Path) -> Result<Option<Self>, BackupError> {
|
||||||
|
let path = book_dir.join(LOCAL_DIR).join(KEY_FILE);
|
||||||
|
let text = match std::fs::read_to_string(&path) {
|
||||||
|
Ok(t) => Zeroizing::new(t),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
};
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct OnDisk {
|
||||||
|
version: u32,
|
||||||
|
kdf: Kdf,
|
||||||
|
master: String,
|
||||||
|
}
|
||||||
|
let bad = || BackupError::Damaged("the backup passphrase's key can't be read".into());
|
||||||
|
let on: OnDisk = serde_json::from_str(&text).map_err(|_| bad())?;
|
||||||
|
if on.version != 1 || !kdf_in_bounds(&on.kdf) {
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let master_hex = Zeroizing::new(on.master);
|
||||||
|
let raw = Zeroizing::new(hex::decode(master_hex.as_str()).map_err(|_| bad())?);
|
||||||
|
let master: [u8; 32] = raw.as_slice().try_into().map_err(|_| bad())?;
|
||||||
|
Ok(Some(Self {
|
||||||
|
kdf: on.kdf,
|
||||||
|
master: Zeroizing::new(master),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forget it (the passphrase is taken off): the next backup is plain.
|
||||||
|
/// The file is removed from this computer only.
|
||||||
|
pub fn forget(book_dir: &Path) -> Result<(), BackupError> {
|
||||||
|
match std::fs::remove_file(book_dir.join(LOCAL_DIR).join(KEY_FILE)) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||||
|
Err(e) => Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BackupKey {
|
||||||
|
/// The key `passphrase` makes under `header`'s settings, derived once
|
||||||
|
/// for each distinct setting in `cache`: a folder of many sealed sets
|
||||||
|
/// made with one passphrase costs one derivation, not one per set.
|
||||||
|
pub(crate) fn from_header_cached(
|
||||||
|
passphrase: &str,
|
||||||
|
header: &Header,
|
||||||
|
cache: &mut Vec<(Kdf, Result<BackupKey, BackupError>)>,
|
||||||
|
) -> Result<Self, BackupError> {
|
||||||
|
if let Some((_, got)) = cache.iter().find(|(k, _)| *k == header.kdf) {
|
||||||
|
return match got {
|
||||||
|
Ok(key) => {
|
||||||
|
key.keys().check(header)?;
|
||||||
|
Ok(key.clone())
|
||||||
|
}
|
||||||
|
Err(e) => Err(e.clone()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let derived = stretch(passphrase, &header.kdf).map(|master| Self {
|
||||||
|
kdf: header.kdf.clone(),
|
||||||
|
master,
|
||||||
|
});
|
||||||
|
cache.push((header.kdf.clone(), derived.clone()));
|
||||||
|
let key = derived?;
|
||||||
|
key.keys().check(header)?;
|
||||||
|
Ok(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The two keys a set uses.
|
||||||
|
pub(crate) struct Keys {
|
||||||
|
enc: Zeroizing<[u8; 32]>,
|
||||||
|
names: Zeroizing<[u8; 32]>,
|
||||||
|
kdf: Kdf,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A sealed set's header: what another computer needs to derive the key,
|
||||||
|
/// and a sealed check that tells a wrong passphrase from damage.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct Header {
|
||||||
|
pub format: String,
|
||||||
|
pub version: u32,
|
||||||
|
pub cipher: String,
|
||||||
|
pub kdf: Kdf,
|
||||||
|
/// Hex of the check text, sealed.
|
||||||
|
pub check: String,
|
||||||
|
/// SHA-256 of the sealed check, hex: it differs from the check only if
|
||||||
|
/// the header was damaged.
|
||||||
|
pub check_sha256: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
const HEADER_FORMAT: &str = "wanderbooks-backup-header";
|
||||||
|
|
||||||
|
impl Header {
|
||||||
|
/// The header's file: JSON, a newline, and its own check line.
|
||||||
|
pub(crate) fn encode(&self) -> Vec<u8> {
|
||||||
|
let body = serde_json::to_string(self).expect("a header serializes");
|
||||||
|
format!(
|
||||||
|
"{body}\nwanderbooks-header-sha256 {}\n",
|
||||||
|
sha_hex(body.as_bytes())
|
||||||
|
)
|
||||||
|
.into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A header read back, or why it is not one.
|
||||||
|
pub(crate) fn decode(bytes: &[u8]) -> Result<Self, BackupError> {
|
||||||
|
let bad =
|
||||||
|
|| BackupError::Damaged("the sealed backup's header is cut short or changed".into());
|
||||||
|
let text = std::str::from_utf8(bytes).map_err(|_| bad())?;
|
||||||
|
let text = text.strip_suffix('\n').ok_or_else(bad)?;
|
||||||
|
let (body, check) = text.rsplit_once('\n').ok_or_else(bad)?;
|
||||||
|
if check.strip_prefix("wanderbooks-header-sha256 ") != Some(&sha_hex(body.as_bytes())) {
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let h: Header = serde_json::from_str(body).map_err(|_| bad())?;
|
||||||
|
if h.format != HEADER_FORMAT || h.version != 1 || h.cipher != "xchacha20poly1305-stream" {
|
||||||
|
return Err(BackupError::Damaged(
|
||||||
|
"the sealed backup's header is of a kind this program doesn't know".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Keys {
|
||||||
|
/// The header for a set sealed with these keys.
|
||||||
|
pub(crate) fn header(&self) -> Header {
|
||||||
|
let mut sealed = Vec::new();
|
||||||
|
self.seal_stream(&mut &CHECK_TEXT[..], &mut sealed, &header_aad(&self.kdf))
|
||||||
|
.expect("sealing into memory");
|
||||||
|
Header {
|
||||||
|
format: HEADER_FORMAT.into(),
|
||||||
|
version: 1,
|
||||||
|
cipher: "xchacha20poly1305-stream".into(),
|
||||||
|
kdf: self.kdf.clone(),
|
||||||
|
check_sha256: sha_hex(&sealed),
|
||||||
|
check: hex::encode(sealed),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether these keys open `header`'s check.
|
||||||
|
pub(crate) fn check(&self, header: &Header) -> Result<(), BackupError> {
|
||||||
|
let sealed = hex::decode(&header.check)
|
||||||
|
.ok()
|
||||||
|
.filter(|s| sha_hex(s) == header.check_sha256)
|
||||||
|
.ok_or_else(|| BackupError::Damaged("the sealed backup's header was changed".into()))?;
|
||||||
|
let mut plain = Vec::new();
|
||||||
|
match self.open_stream(&mut &sealed[..], &header_aad(&header.kdf), &mut |b| {
|
||||||
|
plain.extend_from_slice(b);
|
||||||
|
Ok(())
|
||||||
|
}) {
|
||||||
|
Ok(()) if plain == CHECK_TEXT => Ok(()),
|
||||||
|
_ => Err(BackupError::WrongPassphrase),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The name a piece is kept under: made from the key, the piece's
|
||||||
|
/// kind and its hash.
|
||||||
|
pub(crate) fn piece_name(&self, kind: &str, sha: &str) -> String {
|
||||||
|
let mut h = Sha256::new();
|
||||||
|
h.update(*self.names);
|
||||||
|
h.update(kind.as_bytes());
|
||||||
|
h.update([0]);
|
||||||
|
h.update(sha.as_bytes());
|
||||||
|
hex::encode(h.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cipher(&self) -> XChaCha20Poly1305 {
|
||||||
|
XChaCha20Poly1305::new_from_slice(&self.enc[..]).expect("a 32-byte key")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The length a piece of `plain` bytes is kept at.
|
||||||
|
pub(crate) fn sealed_len(plain: u64) -> u64 {
|
||||||
|
let chunks = plain.div_ceil(CHUNK as u64).max(1);
|
||||||
|
(MAGIC.len() + 16) as u64 + plain + chunks * TAG as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seal all of `plain` into `out`, bound to `aad` (the piece's
|
||||||
|
/// identity).
|
||||||
|
pub(crate) fn seal_stream(
|
||||||
|
&self,
|
||||||
|
plain: &mut dyn Read,
|
||||||
|
out: &mut dyn Write,
|
||||||
|
aad: &[u8],
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
let cipher = self.cipher();
|
||||||
|
let mut prefix = [0u8; 16];
|
||||||
|
getrandom::getrandom(&mut prefix).map_err(std::io::Error::from)?;
|
||||||
|
out.write_all(MAGIC)?;
|
||||||
|
out.write_all(&prefix)?;
|
||||||
|
let mut cur = read_full(plain, CHUNK)?;
|
||||||
|
let mut counter = 0u64;
|
||||||
|
loop {
|
||||||
|
let next = read_full(plain, CHUNK)?;
|
||||||
|
let last = next.is_empty();
|
||||||
|
let mut nonce = [0u8; 24];
|
||||||
|
nonce[..16].copy_from_slice(&prefix);
|
||||||
|
nonce[16..].copy_from_slice(&counter.to_be_bytes());
|
||||||
|
let mut a = aad.to_vec();
|
||||||
|
a.push(u8::from(last));
|
||||||
|
let ct = cipher
|
||||||
|
.encrypt(&XNonce::from(nonce), Payload { msg: &cur, aad: &a })
|
||||||
|
.map_err(|_| std::io::Error::other("sealing failed"))?;
|
||||||
|
out.write_all(&ct)?;
|
||||||
|
if last {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
cur = next;
|
||||||
|
counter += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open a sealed piece, handing its contents to `sink` chunk by chunk.
|
||||||
|
/// A wrong key, a changed byte, a piece cut short, or one bound to
|
||||||
|
/// another identity is an error before the contents are complete; the
|
||||||
|
/// caller discards what the sink had.
|
||||||
|
pub(crate) fn open_stream(
|
||||||
|
&self,
|
||||||
|
stored: &mut dyn Read,
|
||||||
|
aad: &[u8],
|
||||||
|
sink: &mut dyn FnMut(&[u8]) -> std::io::Result<()>,
|
||||||
|
) -> Result<(), BackupError> {
|
||||||
|
let bad =
|
||||||
|
|| BackupError::Damaged("a piece of the sealed backup is damaged or cut short".into());
|
||||||
|
let cipher = self.cipher();
|
||||||
|
let mut head = [0u8; 4 + 16];
|
||||||
|
stored.read_exact(&mut head).map_err(|_| bad())?;
|
||||||
|
if &head[..4] != MAGIC {
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let prefix: [u8; 16] = head[4..].try_into().expect("16 bytes");
|
||||||
|
let mut cur = read_full(stored, CHUNK + TAG).map_err(super::io::uncarry)?;
|
||||||
|
if cur.is_empty() {
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let mut counter = 0u64;
|
||||||
|
loop {
|
||||||
|
let next = read_full(stored, CHUNK + TAG).map_err(super::io::uncarry)?;
|
||||||
|
let last = next.is_empty();
|
||||||
|
let mut nonce = [0u8; 24];
|
||||||
|
nonce[..16].copy_from_slice(&prefix);
|
||||||
|
nonce[16..].copy_from_slice(&counter.to_be_bytes());
|
||||||
|
let mut a = aad.to_vec();
|
||||||
|
a.push(u8::from(last));
|
||||||
|
let plain = cipher
|
||||||
|
.decrypt(&XNonce::from(nonce), Payload { msg: &cur, aad: &a })
|
||||||
|
.map_err(|_| bad())?;
|
||||||
|
sink(&plain).map_err(super::io::uncarry)?;
|
||||||
|
if last {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
cur = next;
|
||||||
|
counter += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A small file sealed whole.
|
||||||
|
pub(crate) fn seal_bytes(&self, plain: &[u8], aad: &[u8]) -> Vec<u8> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
self.seal_stream(&mut &plain[..], &mut out, aad)
|
||||||
|
.expect("sealing into memory");
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A small file opened whole.
|
||||||
|
pub(crate) fn open_bytes(&self, stored: &[u8], aad: &[u8]) -> Result<Vec<u8>, BackupError> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
self.open_stream(&mut &stored[..], aad, &mut |b| {
|
||||||
|
out.extend_from_slice(b);
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Up to `n` bytes from `r`: fewer only at its end.
|
||||||
|
fn read_full(r: &mut dyn Read, n: usize) -> std::io::Result<Vec<u8>> {
|
||||||
|
let mut buf = vec![0u8; n];
|
||||||
|
let mut got = 0;
|
||||||
|
while got < n {
|
||||||
|
match r.read(&mut buf[got..]) {
|
||||||
|
Ok(0) => break,
|
||||||
|
Ok(k) => got += k,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buf.truncate(got);
|
||||||
|
Ok(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A piece's identity: what it is bound to when sealed.
|
||||||
|
pub(crate) fn piece_aad(kind: &str, sha: &str) -> Vec<u8> {
|
||||||
|
format!("wb1|{kind}|{sha}").into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A manifest's identity.
|
||||||
|
pub(crate) fn manifest_aad(number: u64) -> Vec<u8> {
|
||||||
|
format!("wb1|manifest|{number}").into_bytes()
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
//! The backup as one file ("Save a backup..."): a zip of the folder form
|
||||||
|
//! of one set, holding one manifest and only the pieces it names. A zip is
|
||||||
|
//! a file any computer can carry and a person can open to see what is
|
||||||
|
//! inside. Sealed when the backups are: the pieces in it are the sealed
|
||||||
|
//! pieces, so the file says no more than a sealed folder does.
|
||||||
|
//!
|
||||||
|
//! The extension is `.wbbackup`.
|
||||||
|
|
||||||
|
use super::cut::Cut;
|
||||||
|
use super::io::{Fill, Put, PutKind, SetIo};
|
||||||
|
use super::read::{Found, Set, verify_found};
|
||||||
|
use super::write::{Written, proof_scratch, write_into_set};
|
||||||
|
use super::{BackupError, Ctx};
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::io::Read;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
/// The file's extension, without the dot.
|
||||||
|
pub const FILE_EXTENSION: &str = "wbbackup";
|
||||||
|
|
||||||
|
/// A set read from a zip.
|
||||||
|
struct ZipRead {
|
||||||
|
archive: Mutex<zip::ZipArchive<std::fs::File>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||||
|
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SetIo for ZipRead {
|
||||||
|
fn list(&self, dir: &str) -> std::io::Result<Vec<String>> {
|
||||||
|
let prefix = format!("{}/", dir.trim_end_matches('/'));
|
||||||
|
let archive = lock(&self.archive);
|
||||||
|
let mut out: Vec<String> = archive
|
||||||
|
.file_names()
|
||||||
|
.filter_map(|n| n.ok())
|
||||||
|
.filter_map(|n| n.strip_prefix(prefix.as_str()).map(str::to_string))
|
||||||
|
.filter(|rest| !rest.is_empty() && !rest.contains('/'))
|
||||||
|
.collect();
|
||||||
|
out.sort();
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn len(&self, rel: &str) -> std::io::Result<Option<u64>> {
|
||||||
|
let mut archive = lock(&self.archive);
|
||||||
|
match archive.by_name(rel) {
|
||||||
|
Ok(f) if f.is_file() => Ok(Some(f.size())),
|
||||||
|
Ok(_) | Err(zip::result::ZipError::FileNotFound) => Ok(None),
|
||||||
|
Err(e) => Err(std::io::Error::other(e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_with(
|
||||||
|
&self,
|
||||||
|
rel: &str,
|
||||||
|
f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
let mut archive = lock(&self.archive);
|
||||||
|
let mut file = archive
|
||||||
|
.by_name(rel)
|
||||||
|
.map_err(|_| std::io::Error::from(std::io::ErrorKind::NotFound))?;
|
||||||
|
f(&mut file)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put(&self, _rel: &str, _kind: PutKind, _fill: Fill<'_>) -> std::io::Result<Put> {
|
||||||
|
Err(std::io::Error::other("a backup file is read only"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A zip being written. The writer is shared with [`save_file`], which
|
||||||
|
/// finishes it.
|
||||||
|
struct ZipWrite {
|
||||||
|
writer: Arc<Mutex<Option<zip::ZipWriter<std::fs::File>>>>,
|
||||||
|
names: Mutex<BTreeSet<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SetIo for ZipWrite {
|
||||||
|
fn list(&self, _dir: &str) -> std::io::Result<Vec<String>> {
|
||||||
|
Ok(Vec::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn len(&self, _rel: &str) -> std::io::Result<Option<u64>> {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_with(
|
||||||
|
&self,
|
||||||
|
_rel: &str,
|
||||||
|
_f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
Err(std::io::Error::from(std::io::ErrorKind::NotFound))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put(&self, rel: &str, _kind: PutKind, fill: Fill<'_>) -> std::io::Result<Put> {
|
||||||
|
if !lock(&self.names).insert(rel.to_string()) {
|
||||||
|
return Ok(Put::Existed);
|
||||||
|
}
|
||||||
|
// Text compresses; stored files and sealed pieces do not.
|
||||||
|
let text = ["journal/", "access/", "files-index/", "manifests/"]
|
||||||
|
.iter()
|
||||||
|
.any(|p| rel.starts_with(p))
|
||||||
|
|| rel == super::form::READ_ME;
|
||||||
|
let method = if text {
|
||||||
|
zip::CompressionMethod::Deflated
|
||||||
|
} else {
|
||||||
|
zip::CompressionMethod::Stored
|
||||||
|
};
|
||||||
|
let options = zip::write::SimpleFileOptions::default()
|
||||||
|
.compression_method(method)
|
||||||
|
.large_file(true);
|
||||||
|
let mut guard = lock(&self.writer);
|
||||||
|
let writer = guard
|
||||||
|
.as_mut()
|
||||||
|
.ok_or_else(|| std::io::Error::other("the backup file is finished"))?;
|
||||||
|
writer
|
||||||
|
.start_file(rel, options)
|
||||||
|
.map_err(std::io::Error::other)?;
|
||||||
|
fill(writer)?;
|
||||||
|
Ok(Put::Created)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open a backup file for reading.
|
||||||
|
pub(crate) fn open(path: &Path, _ctx: &Ctx) -> Result<Box<dyn SetIo>, BackupError> {
|
||||||
|
let file = std::fs::File::open(path)?;
|
||||||
|
let archive = zip::ZipArchive::new(file).map_err(|_| BackupError::NotABackup)?;
|
||||||
|
Ok(Box::new(ZipRead {
|
||||||
|
archive: Mutex::new(archive),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write the cut as one file at `path` (which must not be there): the same
|
||||||
|
/// contents as a backup folder, sealed when `key` is given. Written aside
|
||||||
|
/// and moved into place only when whole, so a file by that name is a
|
||||||
|
/// whole backup.
|
||||||
|
pub fn save_file(
|
||||||
|
path: &Path,
|
||||||
|
cut: &Cut,
|
||||||
|
key: Option<&super::BackupKey>,
|
||||||
|
ctx: &Ctx,
|
||||||
|
) -> Result<Written, BackupError> {
|
||||||
|
if std::fs::symlink_metadata(path).is_ok() {
|
||||||
|
return Err(BackupError::Damaged(
|
||||||
|
"a file by that name is there already: choose another name".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let name = path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
.ok_or(BackupError::NotABackup)?;
|
||||||
|
let aside = path.with_file_name(format!(".{name}.partial"));
|
||||||
|
let _ = std::fs::remove_file(&aside);
|
||||||
|
let file = std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(&aside)?;
|
||||||
|
let shared = Arc::new(Mutex::new(Some(zip::ZipWriter::new(file))));
|
||||||
|
let set = Set {
|
||||||
|
io: Box::new(ZipWrite {
|
||||||
|
writer: shared.clone(),
|
||||||
|
names: Mutex::new(BTreeSet::new()),
|
||||||
|
}),
|
||||||
|
keys: key.map(|k| k.keys()),
|
||||||
|
ctx: ctx.clone(),
|
||||||
|
};
|
||||||
|
let result = write_into_set(&set, cut, ctx, false).and_then(|written| {
|
||||||
|
// The zip's directory, then the file's.
|
||||||
|
let writer = lock(&shared)
|
||||||
|
.take()
|
||||||
|
.ok_or_else(|| BackupError::Damaged("the backup file was finished twice".into()))?;
|
||||||
|
let file = writer
|
||||||
|
.finish()
|
||||||
|
.map_err(|e| BackupError::Io(std::io::Error::other(e).kind()))?;
|
||||||
|
file.sync_all()?;
|
||||||
|
// Read back as a restore would read it, and proven whole (every
|
||||||
|
// piece re-hashed, the chain replayed, the books opened), before it
|
||||||
|
// is given its name: a file by that name is a backup that proved.
|
||||||
|
let reader = Set {
|
||||||
|
io: open(&aside, ctx)?,
|
||||||
|
keys: key.map(|k| k.keys()),
|
||||||
|
ctx: ctx.clone(),
|
||||||
|
};
|
||||||
|
let found = Found::of(reader, key.cloned(), cut.book());
|
||||||
|
let scratch = proof_scratch(cut)?;
|
||||||
|
let proven = verify_found(&found, &scratch, ctx);
|
||||||
|
let _ = std::fs::remove_dir_all(&scratch);
|
||||||
|
proven?;
|
||||||
|
Ok(written)
|
||||||
|
});
|
||||||
|
match result {
|
||||||
|
Ok(written) => {
|
||||||
|
// Moved into place only if the name is still free.
|
||||||
|
let placed = std::fs::hard_link(&aside, path).or_else(|e| {
|
||||||
|
if e.kind() == std::io::ErrorKind::AlreadyExists
|
||||||
|
|| std::fs::symlink_metadata(path).is_ok()
|
||||||
|
{
|
||||||
|
Err(std::io::Error::from(std::io::ErrorKind::AlreadyExists))
|
||||||
|
} else {
|
||||||
|
std::fs::rename(&aside, path)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let _ = std::fs::remove_file(&aside);
|
||||||
|
placed?;
|
||||||
|
Ok(written)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let _ = std::fs::remove_file(&aside);
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
//! Tests of the parts of a backup that need what the crate keeps to itself:
|
||||||
|
//! how a failed link is told from a disk that makes none, what a sync
|
||||||
|
//! service's stand-ins look like, the share of stored files each backup
|
||||||
|
//! re-reads, and a destination with thousands of backups.
|
||||||
|
|
||||||
|
use super::Ctx;
|
||||||
|
use super::cut::Cut;
|
||||||
|
use super::form::*;
|
||||||
|
use super::io::{dataless_flags, is_stand_in_name, link_unsupported, placeholder_attributes};
|
||||||
|
use super::read::{Set, in_rotation};
|
||||||
|
use super::write::{kept_form, write_into_set};
|
||||||
|
use std::io::Write;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_an_error_that_means_no_links_is_taken_to_mean_it() {
|
||||||
|
use std::io::{Error, ErrorKind};
|
||||||
|
assert!(link_unsupported(&Error::from(ErrorKind::Unsupported)));
|
||||||
|
// The name being taken, a missing folder, a refused permission and a
|
||||||
|
// full disk are what they say: never a reason to try a rename, which
|
||||||
|
// replaces.
|
||||||
|
for kind in [
|
||||||
|
ErrorKind::AlreadyExists,
|
||||||
|
ErrorKind::NotFound,
|
||||||
|
ErrorKind::PermissionDenied,
|
||||||
|
ErrorKind::StorageFull,
|
||||||
|
ErrorKind::Other,
|
||||||
|
] {
|
||||||
|
assert!(!link_unsupported(&Error::from(kind)), "{kind:?}");
|
||||||
|
}
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
for n in [libc::EPERM, libc::ENOSYS, libc::EOPNOTSUPP, libc::ENOTSUP] {
|
||||||
|
assert!(link_unsupported(&Error::from_raw_os_error(n)), "errno {n}");
|
||||||
|
}
|
||||||
|
for n in [
|
||||||
|
libc::EACCES,
|
||||||
|
libc::ENOENT,
|
||||||
|
libc::EEXIST,
|
||||||
|
libc::ENOSPC,
|
||||||
|
libc::EIO,
|
||||||
|
] {
|
||||||
|
assert!(!link_unsupported(&Error::from_raw_os_error(n)), "errno {n}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn what_a_sync_service_leaves_for_a_file_it_has_not_downloaded_is_known() {
|
||||||
|
// iCloud, before macOS 14: `.name.icloud` in the folder.
|
||||||
|
assert!(is_stand_in_name(".000002.json.icloud"));
|
||||||
|
assert!(is_stand_in_name(".a.icloud"));
|
||||||
|
assert!(!is_stand_in_name("000002.json"));
|
||||||
|
assert!(!is_stand_in_name(".wb-tmp-1-abc"));
|
||||||
|
assert!(!is_stand_in_name(".icloud"));
|
||||||
|
// Windows: offline (0x1000), recall on open (0x40000), recall on data
|
||||||
|
// access (0x400000); a plain file (archive, 0x20) and a read-only one
|
||||||
|
// (0x1) are not.
|
||||||
|
for attrs in [0x1000, 0x40000, 0x400000, 0x20 | 0x400000] {
|
||||||
|
assert!(placeholder_attributes(attrs), "{attrs:#x}");
|
||||||
|
}
|
||||||
|
for attrs in [0x20, 0x1, 0x80, 0x100] {
|
||||||
|
assert!(!placeholder_attributes(attrs), "{attrs:#x}");
|
||||||
|
}
|
||||||
|
// macOS: SF_DATALESS.
|
||||||
|
assert!(dataless_flags(0x4000_0000));
|
||||||
|
assert!(!dataless_flags(0x0004_0000));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_piece_belongs_to_one_share_and_every_share_is_read_within_sixteen_backups() {
|
||||||
|
use super::read::ROTATION;
|
||||||
|
let mut x = 0x2545_f491_4f6c_dd1du64;
|
||||||
|
for _ in 0..2000 {
|
||||||
|
// A pseudo-random hash.
|
||||||
|
let mut sha = String::new();
|
||||||
|
while sha.len() < 64 {
|
||||||
|
x ^= x << 13;
|
||||||
|
x ^= x >> 7;
|
||||||
|
x ^= x << 17;
|
||||||
|
sha.push_str(&format!("{x:016x}"));
|
||||||
|
}
|
||||||
|
sha.truncate(64);
|
||||||
|
for start in [1u64, 2, 17, 255, 3000] {
|
||||||
|
let reads = (start..start + ROTATION)
|
||||||
|
.filter(|n| in_rotation(&sha, *n))
|
||||||
|
.count();
|
||||||
|
assert_eq!(reads, 1, "{sha} from backup {start}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn generations_and_set_names_round_trip() {
|
||||||
|
assert_eq!(generation_path("files/ab/xyz", 0), "files/ab/xyz");
|
||||||
|
assert_eq!(generation_path("files/ab/xyz", 2), "files/ab/xyz.g2");
|
||||||
|
assert_eq!(split_generation("files/ab/xyz.g2"), ("files/ab/xyz", 2));
|
||||||
|
assert_eq!(split_generation("files/ab/xyz"), ("files/ab/xyz", 0));
|
||||||
|
assert_eq!(
|
||||||
|
split_generation("journal/000001-abcd.g"),
|
||||||
|
("journal/000001-abcd.g", 0)
|
||||||
|
);
|
||||||
|
assert_eq!(plain_set_name("con", 1), "wanderbooks-con");
|
||||||
|
assert_eq!(plain_set_name("acme", 3), "wanderbooks-acme.3");
|
||||||
|
assert_eq!(parse_plain_set_name("wanderbooks-acme"), Some(("acme", 1)));
|
||||||
|
assert_eq!(
|
||||||
|
parse_plain_set_name("wanderbooks-acme.3"),
|
||||||
|
Some(("acme", 3))
|
||||||
|
);
|
||||||
|
// No book id holds a dot, so a later set is never another book's.
|
||||||
|
assert_eq!(parse_plain_set_name("wanderbooks-acme.1"), None);
|
||||||
|
assert_eq!(parse_plain_set_name("acme"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `Set` over a fresh folder, nothing synced.
|
||||||
|
fn fresh_set(root: &std::path::Path) -> (Set, std::path::PathBuf) {
|
||||||
|
let at = root.join("disk/wanderbooks-acme");
|
||||||
|
(Set::dir(at.clone(), None, &Ctx::new().with_no_sync()), at)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a person's backups look like after a while, made by the real
|
||||||
|
/// writer: every manifest names every segment once read, but is kept as
|
||||||
|
/// the one before it and what is new, and a chain is cut at 64.
|
||||||
|
#[test]
|
||||||
|
fn the_writers_manifests_chain_to_a_bounded_depth_and_are_proven_link_by_link() {
|
||||||
|
const N: u64 = 150;
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let book = dir.path().join("book");
|
||||||
|
std::fs::create_dir(&book).unwrap();
|
||||||
|
let ctx = Ctx::new().with_no_sync();
|
||||||
|
let (set, at) = fresh_set(dir.path());
|
||||||
|
// A journal of made-up lines: the writer never reads one, it hashes the
|
||||||
|
// bytes and takes the head from the caller. Each backup adds a line.
|
||||||
|
let mut journal = std::fs::File::create(book.join(crate::JOURNAL_FILE)).unwrap();
|
||||||
|
for i in 1..=N {
|
||||||
|
let line = format!("{{\"seq\":{i},\"pad\":\"{}\"}}", "x".repeat(60));
|
||||||
|
writeln!(journal, "{line}").unwrap();
|
||||||
|
journal.flush().unwrap();
|
||||||
|
let cut = Cut::take("acme", &book, (i, sha_hex(line.as_bytes()))).unwrap();
|
||||||
|
let w = write_into_set(&set, &cut, &ctx, false).unwrap();
|
||||||
|
assert!(w.new && w.number == i);
|
||||||
|
}
|
||||||
|
let mut depths = Vec::new();
|
||||||
|
for n in 1..=N {
|
||||||
|
let m = set.manifest(n).unwrap();
|
||||||
|
depths.push(m.depth);
|
||||||
|
assert_eq!(m.journal.segments.len() as u64, n, "manifest {n}");
|
||||||
|
let raw = std::fs::read_to_string(at.join(manifest_path(n, false))).unwrap();
|
||||||
|
let stored: Manifest = serde_json::from_str(raw.lines().next().unwrap()).unwrap();
|
||||||
|
assert_eq!(stored.depth == 0, stored.base.is_none());
|
||||||
|
// A stored manifest that chains names only what is new.
|
||||||
|
if stored.base.is_some() {
|
||||||
|
assert_eq!(stored.journal.segments.len(), 1, "manifest {n}");
|
||||||
|
assert_eq!(stored.journal.keep as u64, n - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Chains of 64: a manifest that names everything at 1, 65, 129.
|
||||||
|
assert_eq!(depths[0], 0);
|
||||||
|
assert_eq!(depths[63], 63);
|
||||||
|
assert_eq!(depths[64], 0);
|
||||||
|
assert_eq!(depths[128], 0);
|
||||||
|
assert!(depths.iter().all(|d| *d < DELTA_CHAIN));
|
||||||
|
|
||||||
|
// Each link is proven by the hash its successor holds: a manifest in
|
||||||
|
// the chain that was changed makes the ones built on it unreadable, and
|
||||||
|
// the reader takes the newest that still reads, saying how many it
|
||||||
|
// passed.
|
||||||
|
let k = N - 5;
|
||||||
|
let bad = at.join(manifest_path(k, false));
|
||||||
|
let mut bytes = std::fs::read(&bad).unwrap();
|
||||||
|
let i = bytes.len() / 3;
|
||||||
|
bytes[i] = if bytes[i] == b'0' { b'1' } else { b'0' };
|
||||||
|
std::fs::write(&bad, bytes).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
set.manifest(N),
|
||||||
|
Err(super::BackupError::Damaged(_))
|
||||||
|
));
|
||||||
|
let (m, passed) = set.newest_whole().unwrap().unwrap();
|
||||||
|
assert_eq!((m.number, passed as u64), (k - 1, N - k + 1));
|
||||||
|
assert_eq!(m.journal.segments.len() as u64, k - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A destination of thousands of backups, made cheaply: the real forms
|
||||||
|
/// (`kept_form`, `encode_manifest`) written straight into a folder with a
|
||||||
|
/// one-byte file for each segment, no books and no syncing, then read as
|
||||||
|
/// a restore reads it. The time and size are printed (the numbers the
|
||||||
|
/// docs quote) and bounded.
|
||||||
|
#[test]
|
||||||
|
fn a_destination_of_thousands_of_backups_stays_small_and_quick_to_read() {
|
||||||
|
const N: u64 = 3000;
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (set, at) = fresh_set(dir.path());
|
||||||
|
std::fs::create_dir_all(at.join("journal")).unwrap();
|
||||||
|
std::fs::create_dir_all(at.join(MANIFESTS)).unwrap();
|
||||||
|
let made = Instant::now();
|
||||||
|
let mut full = Manifest {
|
||||||
|
format: FORMAT.into(),
|
||||||
|
version: VERSION,
|
||||||
|
book: "acme".into(),
|
||||||
|
number: 0,
|
||||||
|
written: "2026-11-21T00:00:00Z".into(),
|
||||||
|
head: Head {
|
||||||
|
seq: 0,
|
||||||
|
hash: String::new(),
|
||||||
|
},
|
||||||
|
journal: Series::default(),
|
||||||
|
access: Series::default(),
|
||||||
|
files: Series::default(),
|
||||||
|
file_count: 0,
|
||||||
|
file_bytes: 0,
|
||||||
|
vault: Vec::new(),
|
||||||
|
keys: Vec::new(),
|
||||||
|
base: None,
|
||||||
|
depth: 0,
|
||||||
|
sha: String::new(),
|
||||||
|
};
|
||||||
|
let mut prev: Option<Manifest> = None;
|
||||||
|
for i in 1..=N {
|
||||||
|
let name = format!("journal/{i:06}-{i:016x}");
|
||||||
|
std::fs::write(at.join(&name), b"x").unwrap();
|
||||||
|
full.journal.segments.push(Piece {
|
||||||
|
file: name,
|
||||||
|
stored: 1,
|
||||||
|
bytes: 1,
|
||||||
|
sha256: format!("{i:064x}"),
|
||||||
|
});
|
||||||
|
full.journal.bytes = i;
|
||||||
|
full.journal.sha256 = format!("{i:064x}");
|
||||||
|
full.number = i;
|
||||||
|
full.head = Head {
|
||||||
|
seq: i,
|
||||||
|
hash: format!("{i:064x}"),
|
||||||
|
};
|
||||||
|
let kept = kept_form(&full, prev.as_ref());
|
||||||
|
let bytes = encode_manifest(&kept);
|
||||||
|
std::fs::write(at.join(manifest_path(i, false)), &bytes).unwrap();
|
||||||
|
let mut view = full.clone();
|
||||||
|
view.depth = kept.depth;
|
||||||
|
view.sha = decode_manifest(&bytes).unwrap().sha;
|
||||||
|
prev = Some(view);
|
||||||
|
}
|
||||||
|
let made = made.elapsed();
|
||||||
|
|
||||||
|
let sizes: Vec<u64> = (1..=N)
|
||||||
|
.map(|n| {
|
||||||
|
std::fs::metadata(at.join(manifest_path(n, false)))
|
||||||
|
.unwrap()
|
||||||
|
.len()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let total: u64 = sizes.iter().sum();
|
||||||
|
let largest = *sizes.iter().max().unwrap();
|
||||||
|
let newest = *sizes.last().unwrap();
|
||||||
|
// What it would have been if every manifest named everything: a
|
||||||
|
// journal segment is ~170 bytes of a manifest.
|
||||||
|
let everything: u64 = (1..=N).map(|n| 170 * n).sum();
|
||||||
|
|
||||||
|
// Read as a restore reads it: the newest found, and whole.
|
||||||
|
let began = Instant::now();
|
||||||
|
let (m, passed) = set.newest_whole().unwrap().unwrap();
|
||||||
|
let found_in = began.elapsed();
|
||||||
|
assert_eq!((m.number, passed), (N, 0));
|
||||||
|
assert_eq!(m.journal.segments.len() as u64, N);
|
||||||
|
let began = Instant::now();
|
||||||
|
let numbers = set.numbers().unwrap().len();
|
||||||
|
let listed_in = began.elapsed();
|
||||||
|
assert_eq!(numbers as u64, N);
|
||||||
|
println!(
|
||||||
|
"{N} backups: manifests {total} bytes in all (named in full each time: ~{everything}), largest {largest}, newest {newest}; made in {made:?}; newest found and whole in {found_in:?}; listed in {listed_in:?}"
|
||||||
|
);
|
||||||
|
assert!(newest < 6 * 1024, "the newest manifest is {newest} bytes");
|
||||||
|
assert!(total < everything / 20, "{total} of ~{everything}");
|
||||||
|
assert!(found_in.as_secs() < 10, "{found_in:?}");
|
||||||
|
// Any manifest in it reads whole (a sample: each read walks a chain).
|
||||||
|
for n in (1..=N).step_by(131).chain([N - 1]) {
|
||||||
|
let m = set.manifest(n).unwrap();
|
||||||
|
assert_eq!(m.journal.segments.len() as u64, n);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -25,12 +25,10 @@ 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;
|
||||||
|
|||||||
@@ -16,8 +16,9 @@
|
|||||||
//! every process that could still hold it: a child forked by another
|
//! every process that could still hold it: a child forked by another
|
||||||
//! thread of this process holds a copy of every open descriptor (this
|
//! thread of this process holds a copy of every open descriptor (this
|
||||||
//! lock's too) from its fork until its exec, and a `flock` lasts as
|
//! lock's too) from its fork until its exec, and a `flock` lasts as
|
||||||
//! long as any copy does. Every child this crate starts is started by
|
//! long as any copy does. Every child a process that holds a store starts
|
||||||
//! [`spawn`], and dropping a [`WriterLock`] returns only once every
|
//! is started by [`spawn`] (the store itself starts none since backups
|
||||||
|
//! became plain files, D-91; the seam stays for any that does), and dropping a [`WriterLock`] returns only once every
|
||||||
//! [`spawn`] begun before it has ended (its child has exec'd and the
|
//! [`spawn`] begun before it has ended (its child has exec'd and the
|
||||||
//! copies are closed), and then the lock is taken afresh and let go
|
//! copies are closed), and then the lock is taken afresh and let go
|
||||||
//! (it is free, or another writer has it, or 500 ms passed: the system
|
//! (it is free, or another writer has it, or 500 ms passed: the system
|
||||||
|
|||||||
@@ -196,7 +196,7 @@ impl JobStop {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The flag: what git and the store's loops are handed to look at.
|
/// The flag: what a backup's copy and the store's loops are handed to look at.
|
||||||
pub fn flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
|
pub fn flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
|
||||||
self.flag.clone()
|
self.flag.clone()
|
||||||
}
|
}
|
||||||
@@ -229,7 +229,7 @@ impl JobStop {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A stop that reached the store's own loops or git, said as a job's.
|
/// A stop that reached the store's own loops or a backup's copy, said as a job's.
|
||||||
fn said(&self, e: RootError, undone: &str) -> RootError {
|
fn said(&self, e: RootError, undone: &str) -> RootError {
|
||||||
match e {
|
match e {
|
||||||
RootError::Store(_, StoreError::Cancelled) => RootError::Stopped(format!(
|
RootError::Store(_, StoreError::Cancelled) => RootError::Stopped(format!(
|
||||||
@@ -1146,6 +1146,15 @@ 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 or were damaged and were
|
||||||
|
/// passed over: not zero means this is not the newest backup there is.
|
||||||
|
pub passed_over: u64,
|
||||||
|
/// When this backup was made (UTC).
|
||||||
|
pub written: Option<String>,
|
||||||
|
/// When the newest backup there is was made (UTC), if it can be read.
|
||||||
|
pub newest_written: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What [`Root::restore`] did.
|
/// What [`Root::restore`] did.
|
||||||
@@ -1166,21 +1175,21 @@ 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,
|
||||||
) -> 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 +1203,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, &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 +1225,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 +1245,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)?;
|
||||||
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 +1261,10 @@ 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,
|
||||||
|
written: Some(v.written.clone()),
|
||||||
|
newest_written: v.newest_written.clone(),
|
||||||
})
|
})
|
||||||
})()
|
})()
|
||||||
.map_err(|e| self.hide(e))
|
.map_err(|e| self.hide(e))
|
||||||
@@ -1264,13 +1279,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 +1302,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 +1322,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 +1359,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)?;
|
||||||
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 +1399,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(
|
||||||
|
|||||||
@@ -0,0 +1,980 @@
|
|||||||
|
//! Backups in plain folders (WB-backup-1 to WB-backup-9): what a backup
|
||||||
|
//! is, that it only grows, that a restore of any whole manifest is a
|
||||||
|
//! prefix of the books, that two writers do not corrupt one destination,
|
||||||
|
//! that a program that dies at any write leaves a destination that proves
|
||||||
|
//! whole at its previous manifest, that a flipped or cut piece is never
|
||||||
|
//! restored, and that a wrong passphrase never yields books.
|
||||||
|
|
||||||
|
use ledger_core::{AccountType, Currency, Money, Side};
|
||||||
|
use ledger_store::Store;
|
||||||
|
use ledger_store::backup::{
|
||||||
|
BackupError, BackupKey, Ctx, Cut, Destination, find, save_file, verify_found, write_destination,
|
||||||
|
};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
fn usd(s: &str) -> Money {
|
||||||
|
Money::new(s.parse().unwrap(), Currency::USD)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A book with a few entries and a stored file.
|
||||||
|
fn book(dir: &Path) -> Store {
|
||||||
|
let mut s = Store::create(dir, Currency::USD).unwrap();
|
||||||
|
let cash = s
|
||||||
|
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||||
|
.unwrap();
|
||||||
|
let cap = s
|
||||||
|
.add_account("3000", "Capital", AccountType::Equity, None, false)
|
||||||
|
.unwrap();
|
||||||
|
let e = s
|
||||||
|
.create_entry(
|
||||||
|
chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(),
|
||||||
|
"Start",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap();
|
||||||
|
s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap();
|
||||||
|
s.post_entry(e).unwrap();
|
||||||
|
s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None)
|
||||||
|
.unwrap();
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One more write to the books: an account and a stored file.
|
||||||
|
fn more(s: &mut Store, n: usize) {
|
||||||
|
s.add_account(
|
||||||
|
&format!("{}", 6000 + n),
|
||||||
|
&format!("Expense {n}"),
|
||||||
|
AccountType::Expense,
|
||||||
|
None,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
s.attach_receipt(
|
||||||
|
None,
|
||||||
|
&format!("f{n}.txt"),
|
||||||
|
"text/plain",
|
||||||
|
format!("receipt number {n}").as_bytes(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cut(dir: &Path, s: &Store) -> Cut {
|
||||||
|
Cut::take("acme", dir, s.head()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plain(folder: &Path) -> Destination {
|
||||||
|
Destination {
|
||||||
|
folder: folder.to_path_buf(),
|
||||||
|
key: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every file under `root`, by relative path, with its bytes.
|
||||||
|
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||||
|
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||||
|
for e in std::fs::read_dir(dir).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
if p.is_dir() {
|
||||||
|
walk(base, &p, out);
|
||||||
|
} else {
|
||||||
|
let rel = p
|
||||||
|
.strip_prefix(base)
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.replace('\\', "/");
|
||||||
|
out.insert(rel, std::fs::read(&p).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
if root.is_dir() {
|
||||||
|
walk(root, root, &mut out);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prove the backup at `source` and give the books it holds, built in a
|
||||||
|
/// scratch folder next to `root`.
|
||||||
|
fn prove(
|
||||||
|
source: &Path,
|
||||||
|
pass: Option<&str>,
|
||||||
|
root: &Path,
|
||||||
|
name: &str,
|
||||||
|
) -> Result<ledger_store::backup::Verified, BackupError> {
|
||||||
|
let found = find(source, pass, &Ctx::new())?;
|
||||||
|
verify_found(&found, &root.join(name), &Ctx::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_backup_is_the_book_and_proves_whole() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(w.new);
|
||||||
|
assert_eq!(w.number, 1);
|
||||||
|
assert_eq!(w.head, s.head());
|
||||||
|
|
||||||
|
// The form on disk: a folder for the books, a read-me, one manifest,
|
||||||
|
// the journal as a segment, the stored file under its hash.
|
||||||
|
let t = tree(&disk);
|
||||||
|
let names: Vec<&String> = t.keys().collect();
|
||||||
|
assert!(
|
||||||
|
names.iter().any(|n| *n == "wanderbooks-acme/READ-ME.txt"),
|
||||||
|
"{names:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
names
|
||||||
|
.iter()
|
||||||
|
.any(|n| *n == "wanderbooks-acme/manifests/000001.json")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
names
|
||||||
|
.iter()
|
||||||
|
.any(|n| n.starts_with("wanderbooks-acme/journal/000001-"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
names
|
||||||
|
.iter()
|
||||||
|
.any(|n| n.starts_with("wanderbooks-acme/files/"))
|
||||||
|
);
|
||||||
|
assert!(!names.iter().any(|n| n.contains(".git")));
|
||||||
|
|
||||||
|
// Nothing new: no manifest.
|
||||||
|
let again = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(!again.new);
|
||||||
|
assert_eq!(again.number, 1);
|
||||||
|
assert_eq!(tree(&disk), t);
|
||||||
|
|
||||||
|
// Proven, and the books it holds are the book.
|
||||||
|
let v = prove(&disk, None, dir.path(), "v1").unwrap();
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
assert_eq!(v.blobs, 1);
|
||||||
|
assert_eq!(v.book.as_deref(), Some("acme"));
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(v.tree.join("journal.jsonl")).unwrap(),
|
||||||
|
std::fs::read(b.join("journal.jsonl")).unwrap()
|
||||||
|
);
|
||||||
|
|
||||||
|
// More writes: a new manifest and new pieces; the old ones untouched.
|
||||||
|
more(&mut s, 1);
|
||||||
|
let w2 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(w2.number, 2);
|
||||||
|
let t2 = tree(&disk);
|
||||||
|
for (name, bytes) in &t {
|
||||||
|
assert_eq!(t2.get(name), Some(bytes), "{name} must not change");
|
||||||
|
}
|
||||||
|
assert!(t2.len() > t.len());
|
||||||
|
let v2 = prove(&disk, None, dir.path(), "v2").unwrap();
|
||||||
|
assert_eq!(v2.head, s.head());
|
||||||
|
assert_eq!(v2.blobs, 2);
|
||||||
|
// No scratch file of ours is left behind.
|
||||||
|
assert!(!t2.keys().any(|n| n.contains(".wb-tmp-")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_destination_of_other_books_or_another_history_is_never_written() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (b1, b2) = (dir.path().join("one"), dir.path().join("two"));
|
||||||
|
let (mut s1, s2) = (book(&b1), book(&b2));
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap();
|
||||||
|
let before = tree(&disk);
|
||||||
|
// The same id, another history (a different journal from the start).
|
||||||
|
assert_eq!(
|
||||||
|
write_destination(&plain(&disk), &cut(&b2, &s2), true, &Ctx::new()).unwrap_err(),
|
||||||
|
BackupError::Elsewhere
|
||||||
|
);
|
||||||
|
assert_eq!(tree(&disk), before);
|
||||||
|
// Books behind the destination: said, nothing written.
|
||||||
|
more(&mut s1, 1);
|
||||||
|
write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap();
|
||||||
|
let ahead = tree(&disk);
|
||||||
|
let b1_old = dir.path().join("one-old");
|
||||||
|
let _old = book(&b1_old);
|
||||||
|
let err =
|
||||||
|
write_destination(&plain(&disk), &cut(&b1_old, &_old), true, &Ctx::new()).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
matches!(err, BackupError::Ahead(..) | BackupError::Elsewhere),
|
||||||
|
"{err:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(tree(&disk), ahead);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_disk_that_is_gone_is_never_made_again_where_it_should_be() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let missing = dir.path().join("nodisk");
|
||||||
|
assert_eq!(
|
||||||
|
write_destination(&plain(&missing), &cut(&b, &s), true, &Ctx::new()).unwrap_err(),
|
||||||
|
BackupError::NoFolder
|
||||||
|
);
|
||||||
|
// A mount point with nothing on it: the folder is there, the books'
|
||||||
|
// backup is not, and the caller says it never made one here.
|
||||||
|
let mount = dir.path().join("mount");
|
||||||
|
std::fs::create_dir(&mount).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
write_destination(&plain(&mount), &cut(&b, &s), false, &Ctx::new()).unwrap_err(),
|
||||||
|
BackupError::NoBackupThere
|
||||||
|
);
|
||||||
|
assert!(tree(&mount).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stopped_backup_leaves_what_proved_whole_before() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
more(&mut s, 1);
|
||||||
|
let stop = Arc::new(std::sync::atomic::AtomicBool::new(true));
|
||||||
|
let err = write_destination(
|
||||||
|
&plain(&disk),
|
||||||
|
&cut(&b, &s),
|
||||||
|
true,
|
||||||
|
&Ctx::new().with_stop(stop),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(err, BackupError::Cancelled(_)), "{err:?}");
|
||||||
|
let v = prove(&disk, None, dir.path(), "v").unwrap();
|
||||||
|
assert_eq!(v.number, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- the passphrase --------------------------------------------------
|
||||||
|
|
||||||
|
const PASS: &str = "correct horse battery staple";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_sealed_backup_gives_away_counts_and_sizes_only() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let key = BackupKey::generate(PASS).unwrap();
|
||||||
|
let dest = Destination {
|
||||||
|
folder: disk.clone(),
|
||||||
|
key: Some(key),
|
||||||
|
};
|
||||||
|
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
for (name, bytes) in tree(&disk) {
|
||||||
|
for word in [
|
||||||
|
"acme", "journal", "access", "vault", "keys", "blobs", "files", "receipt", "Cash",
|
||||||
|
] {
|
||||||
|
// The read-me is plain words and says nothing of the books;
|
||||||
|
// nothing else carries a word of them, in its name or in it.
|
||||||
|
if !name.ends_with("READ-ME.txt") {
|
||||||
|
assert!(!name.contains(word), "{name} names {word}");
|
||||||
|
assert!(
|
||||||
|
!String::from_utf8_lossy(&bytes).contains(word)
|
||||||
|
|| name.ends_with("header.json"),
|
||||||
|
"{name} holds {word}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(!bytes.windows(8).any(|w| w == b"PDF-1.4 "), "{name}");
|
||||||
|
}
|
||||||
|
// Opened with the passphrase: the same books.
|
||||||
|
let v = prove(&disk, Some(PASS), dir.path(), "v").unwrap();
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
assert!(v.key.is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wrong_passphrase_never_yields_books_and_is_told_from_damage() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let dest = Destination {
|
||||||
|
folder: disk.clone(),
|
||||||
|
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||||
|
};
|
||||||
|
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
find(&disk, None, &Ctx::new()),
|
||||||
|
Err(BackupError::NeedsPassphrase)
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
find(&disk, Some("not the right words at all"), &Ctx::new()),
|
||||||
|
Err(BackupError::WrongPassphrase)
|
||||||
|
));
|
||||||
|
// A damaged header is damage, not a wrong passphrase.
|
||||||
|
let set = std::fs::read_dir(&disk)
|
||||||
|
.unwrap()
|
||||||
|
.flatten()
|
||||||
|
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
|
||||||
|
.unwrap()
|
||||||
|
.path();
|
||||||
|
let header = set.join("header.json");
|
||||||
|
let mut bytes = std::fs::read(&header).unwrap();
|
||||||
|
bytes[40] ^= 1;
|
||||||
|
std::fs::write(&header, &bytes).unwrap();
|
||||||
|
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
|
||||||
|
assert!(
|
||||||
|
matches!(err, BackupError::Damaged(_) | BackupError::NotABackup),
|
||||||
|
"{err:?}"
|
||||||
|
);
|
||||||
|
assert!(!dir.path().join("v").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_changed_passphrase_is_a_new_set_beside_the_old_which_is_untouched() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let first = Destination {
|
||||||
|
folder: disk.clone(),
|
||||||
|
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||||
|
};
|
||||||
|
write_destination(&first, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let before = tree(&disk);
|
||||||
|
more(&mut s, 1);
|
||||||
|
// Another passphrase: found no set of its own, so (the caller says it
|
||||||
|
// may) a new one is made; the first is not touched.
|
||||||
|
let second = Destination {
|
||||||
|
folder: disk.clone(),
|
||||||
|
key: Some(BackupKey::generate("an entirely different phrase").unwrap()),
|
||||||
|
};
|
||||||
|
write_destination(&second, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let after = tree(&disk);
|
||||||
|
for (name, bytes) in &before {
|
||||||
|
assert_eq!(after.get(name), Some(bytes), "{name}");
|
||||||
|
}
|
||||||
|
let sets: Vec<_> = std::fs::read_dir(&disk).unwrap().flatten().collect();
|
||||||
|
assert_eq!(sets.len(), 2);
|
||||||
|
// The old passphrase still opens the old set only when it is alone;
|
||||||
|
// with two sets, a passphrase opens the one that is its own.
|
||||||
|
let v = prove(&disk, Some("an entirely different phrase"), dir.path(), "v").unwrap();
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_key_is_kept_privately_and_only_there() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let key = BackupKey::generate(PASS).unwrap();
|
||||||
|
key.store(&b).unwrap();
|
||||||
|
let loaded = BackupKey::load(&b).unwrap().expect("kept");
|
||||||
|
assert!(key.same_as(&loaded));
|
||||||
|
let file = b.join("local").join("backup-key.json");
|
||||||
|
let text = std::fs::read_to_string(&file).unwrap();
|
||||||
|
assert!(!text.contains(PASS));
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
|
||||||
|
assert_eq!(mode, 0o600);
|
||||||
|
let dir_mode = std::fs::metadata(file.parent().unwrap())
|
||||||
|
.unwrap()
|
||||||
|
.permissions()
|
||||||
|
.mode()
|
||||||
|
& 0o777;
|
||||||
|
assert_eq!(dir_mode, 0o700);
|
||||||
|
}
|
||||||
|
// Never in a backup: not the journal, not the folder of the backup.
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let raw = text
|
||||||
|
.lines()
|
||||||
|
.find(|l| l.contains("master"))
|
||||||
|
.unwrap()
|
||||||
|
.to_string();
|
||||||
|
let master = raw.split('"').nth(3).unwrap().to_string();
|
||||||
|
for (name, bytes) in tree(&disk) {
|
||||||
|
assert!(!String::from_utf8_lossy(&bytes).contains(&master), "{name}");
|
||||||
|
}
|
||||||
|
BackupKey::forget(&b).unwrap();
|
||||||
|
assert!(BackupKey::load(&b).unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- the single file -------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_single_file_holds_the_same_backup_plain_or_sealed() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
for (pass, name) in [(None, "plain.wbbackup"), (Some(PASS), "sealed.wbbackup")] {
|
||||||
|
let key = pass.map(|p| BackupKey::generate(p).unwrap());
|
||||||
|
let file = dir.path().join(name);
|
||||||
|
let w = save_file(&file, &cut(&b, &s), key.as_ref(), &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(w.head, s.head());
|
||||||
|
let v = prove(&file, pass, dir.path(), &format!("v-{name}")).unwrap();
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
assert_eq!(v.blobs, 1);
|
||||||
|
// A file by that name is not written over.
|
||||||
|
assert!(save_file(&file, &cut(&b, &s), key.as_ref(), &Ctx::new()).is_err());
|
||||||
|
}
|
||||||
|
assert!(matches!(
|
||||||
|
find(&dir.path().join("sealed.wbbackup"), None, &Ctx::new()),
|
||||||
|
Err(BackupError::NeedsPassphrase)
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
find(
|
||||||
|
&dir.path().join("sealed.wbbackup"),
|
||||||
|
Some("a wrong passphrase here"),
|
||||||
|
&Ctx::new()
|
||||||
|
),
|
||||||
|
Err(BackupError::WrongPassphrase)
|
||||||
|
));
|
||||||
|
// Not a backup at all.
|
||||||
|
let junk = dir.path().join("junk.wbbackup");
|
||||||
|
std::fs::write(&junk, b"not a zip").unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
find(&junk, None, &Ctx::new()),
|
||||||
|
Err(BackupError::NotABackup)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- damage ------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Every piece a manifest names, as paths under the set.
|
||||||
|
fn pieces(set: &Path) -> Vec<PathBuf> {
|
||||||
|
tree(set)
|
||||||
|
.keys()
|
||||||
|
.filter(|n| {
|
||||||
|
!n.starts_with("manifests/")
|
||||||
|
&& !n.starts_with("proofs/")
|
||||||
|
&& !n.ends_with("READ-ME.txt")
|
||||||
|
&& !n.ends_with("header.json")
|
||||||
|
})
|
||||||
|
.map(|n| set.join(n))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_flipped_or_cut_piece_is_found_and_never_restored() {
|
||||||
|
for sealed in [false, true] {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let key = sealed.then(|| BackupKey::generate(PASS).unwrap());
|
||||||
|
let dest = Destination {
|
||||||
|
folder: disk.clone(),
|
||||||
|
key,
|
||||||
|
};
|
||||||
|
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let pass = sealed.then_some(PASS);
|
||||||
|
// Found once (a sealed backup's key takes a moment to derive).
|
||||||
|
let found = find(&disk, pass, &Ctx::new()).unwrap();
|
||||||
|
let prove = |_: &Path, _: Option<&str>, root: &Path, name: &str| {
|
||||||
|
verify_found(&found, &root.join(name), &Ctx::new())
|
||||||
|
};
|
||||||
|
let set = std::fs::read_dir(&disk)
|
||||||
|
.unwrap()
|
||||||
|
.flatten()
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.path();
|
||||||
|
for piece in pieces(&set) {
|
||||||
|
let original = std::fs::read(&piece).unwrap();
|
||||||
|
for damage in 0..3 {
|
||||||
|
let mut bytes = original.clone();
|
||||||
|
match damage {
|
||||||
|
0 => {
|
||||||
|
let at = bytes.len() / 2;
|
||||||
|
bytes[at] ^= 0x01;
|
||||||
|
}
|
||||||
|
1 => bytes.truncate(bytes.len().saturating_sub(1)),
|
||||||
|
_ => bytes.clear(),
|
||||||
|
}
|
||||||
|
std::fs::write(&piece, &bytes).unwrap();
|
||||||
|
let scratch = format!("v-{damage}");
|
||||||
|
let got = prove(&disk, pass, dir.path(), &scratch);
|
||||||
|
assert!(
|
||||||
|
got.is_err(),
|
||||||
|
"{} damage {damage} of {piece:?} was restored",
|
||||||
|
if sealed { "sealed" } else { "plain" }
|
||||||
|
);
|
||||||
|
assert!(!dir.path().join(&scratch).exists(), "scratch left");
|
||||||
|
}
|
||||||
|
std::fs::write(&piece, &original).unwrap();
|
||||||
|
}
|
||||||
|
// Whole again once put back.
|
||||||
|
prove(&disk, pass, dir.path(), "ok").unwrap();
|
||||||
|
// A manifest cut short or changed is no manifest.
|
||||||
|
let manifest = tree(&set)
|
||||||
|
.keys()
|
||||||
|
.find(|n| n.starts_with("manifests/"))
|
||||||
|
.cloned()
|
||||||
|
.unwrap();
|
||||||
|
let mpath = set.join(&manifest);
|
||||||
|
let original = std::fs::read(&mpath).unwrap();
|
||||||
|
std::fs::write(&mpath, &original[..original.len() / 2]).unwrap();
|
||||||
|
assert!(prove(&disk, pass, dir.path(), "cut").is_err());
|
||||||
|
std::fs::write(&mpath, &original).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_damaged_newest_backup_falls_back_to_the_one_before_and_says_so() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let first_head = s.head();
|
||||||
|
more(&mut s, 1);
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
// Flip a byte in the second journal segment.
|
||||||
|
let seg = tree(&disk.join("wanderbooks-acme"))
|
||||||
|
.keys()
|
||||||
|
.filter(|n| n.starts_with("journal/"))
|
||||||
|
.max()
|
||||||
|
.cloned()
|
||||||
|
.unwrap();
|
||||||
|
let path = disk.join("wanderbooks-acme").join(&seg);
|
||||||
|
let mut bytes = std::fs::read(&path).unwrap();
|
||||||
|
bytes[3] ^= 1;
|
||||||
|
std::fs::write(&path, bytes).unwrap();
|
||||||
|
let v = prove(&disk, None, dir.path(), "v").unwrap();
|
||||||
|
assert_eq!(v.number, 1);
|
||||||
|
assert_eq!(v.passed_over, 1);
|
||||||
|
assert_eq!(v.head, first_head);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- death at every write point --------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let base_disk = dir.path().join("base");
|
||||||
|
std::fs::create_dir(&base_disk).unwrap();
|
||||||
|
write_destination(
|
||||||
|
&plain(&base_disk),
|
||||||
|
&cut(&b, &s),
|
||||||
|
true,
|
||||||
|
&Ctx::new().with_proof_skipped(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let first_head = s.head();
|
||||||
|
more(&mut s, 1);
|
||||||
|
let c = cut(&b, &s);
|
||||||
|
|
||||||
|
// How many write points a whole second backup has.
|
||||||
|
let counted = Arc::new(AtomicUsize::new(0));
|
||||||
|
let probe = {
|
||||||
|
let disk = dir.path().join("probe");
|
||||||
|
copy_tree(&base_disk, &disk);
|
||||||
|
let n = counted.clone();
|
||||||
|
let ctx = Ctx::new()
|
||||||
|
.with_proof_skipped()
|
||||||
|
.with_faults(Arc::new(move |_, _| {
|
||||||
|
n.fetch_add(1, Ordering::SeqCst);
|
||||||
|
false
|
||||||
|
}));
|
||||||
|
write_destination(&plain(&disk), &c, true, &ctx).unwrap();
|
||||||
|
counted.load(Ordering::SeqCst)
|
||||||
|
};
|
||||||
|
assert!(probe >= 6, "a second backup has several writes: {probe}");
|
||||||
|
|
||||||
|
for die_at in 0..probe {
|
||||||
|
let disk = dir.path().join(format!("died-{die_at}"));
|
||||||
|
copy_tree(&base_disk, &disk);
|
||||||
|
let n = Arc::new(AtomicUsize::new(0));
|
||||||
|
let ctx = {
|
||||||
|
let n = n.clone();
|
||||||
|
Ctx::new()
|
||||||
|
.with_proof_skipped()
|
||||||
|
.with_faults(Arc::new(move |_, _| {
|
||||||
|
n.fetch_add(1, Ordering::SeqCst) == die_at
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
let err = write_destination(&plain(&disk), &c, true, &ctx).unwrap_err();
|
||||||
|
assert_eq!(err, BackupError::Died, "point {die_at}");
|
||||||
|
// What is left proves whole at the previous manifest, never a
|
||||||
|
// half-written one (before the manifest was in place), or at the
|
||||||
|
// new one (after).
|
||||||
|
let v = prove(&disk, None, dir.path(), &format!("r-{die_at}")).unwrap();
|
||||||
|
assert!(
|
||||||
|
v.head == first_head || v.head == s.head(),
|
||||||
|
"point {die_at}: head {:?}",
|
||||||
|
v.head
|
||||||
|
);
|
||||||
|
// A restore from what is left is a prefix of the books.
|
||||||
|
let restored = std::fs::read(v.tree.join("journal.jsonl")).unwrap();
|
||||||
|
let live = std::fs::read(b.join("journal.jsonl")).unwrap();
|
||||||
|
assert!(live.starts_with(&restored), "point {die_at}");
|
||||||
|
// And the next run goes on from it (proven again at some points:
|
||||||
|
// each proof replays the books).
|
||||||
|
let w =
|
||||||
|
write_destination(&plain(&disk), &c, true, &Ctx::new().with_proof_skipped()).unwrap();
|
||||||
|
assert_eq!(w.head, s.head());
|
||||||
|
if die_at % 6 == 0 {
|
||||||
|
let again = prove(&disk, None, dir.path(), &format!("again-{die_at}")).unwrap();
|
||||||
|
assert_eq!(again.head, s.head());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_tree(from: &Path, to: &Path) {
|
||||||
|
for (rel, bytes) in tree(from) {
|
||||||
|
let p = to.join(rel);
|
||||||
|
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(p, bytes).unwrap();
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(to).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- two writers -------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_programs_writing_one_destination_do_not_corrupt_it() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
for round in 0..3 {
|
||||||
|
more(&mut s, round);
|
||||||
|
let c = cut(&b, &s);
|
||||||
|
let results: Vec<_> = std::thread::scope(|scope| {
|
||||||
|
let handles: Vec<_> = (0..3)
|
||||||
|
.map(|_| {
|
||||||
|
let (c, disk) = (c.clone(), disk.clone());
|
||||||
|
scope.spawn(move || write_destination(&plain(&disk), &c, true, &Ctx::new()))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||||
|
});
|
||||||
|
for r in &results {
|
||||||
|
let w = r
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_or_else(|e| panic!("round {round}: {e:?}"));
|
||||||
|
assert_eq!(w.head, s.head());
|
||||||
|
}
|
||||||
|
// However they interleaved: whole, at these books, and every
|
||||||
|
// manifest there stands alone.
|
||||||
|
let v = prove(&disk, None, dir.path(), &format!("v{round}")).unwrap();
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
let set = disk.join("wanderbooks-acme");
|
||||||
|
for n in std::fs::read_dir(set.join("manifests")).unwrap().flatten() {
|
||||||
|
assert!(n.file_name().to_string_lossy().ends_with(".json"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_loser_of_a_manifest_number_goes_on_from_the_winner() {
|
||||||
|
// Another program takes the next number between this one's look and its
|
||||||
|
// write: this one looks again and finds nothing left to write.
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let c = cut(&b, &s);
|
||||||
|
let rival_disk = disk.clone();
|
||||||
|
let rival_cut = c.clone();
|
||||||
|
let done = Arc::new(AtomicUsize::new(0));
|
||||||
|
let ctx = {
|
||||||
|
let done = done.clone();
|
||||||
|
Ctx::new().with_faults(Arc::new(move |kind, rel| {
|
||||||
|
// Just before this writer's manifest, the rival writes its own.
|
||||||
|
if kind == "create"
|
||||||
|
&& rel.starts_with("manifests/")
|
||||||
|
&& done.fetch_add(1, Ordering::SeqCst) == 0
|
||||||
|
{
|
||||||
|
write_destination(&plain(&rival_disk), &rival_cut, true, &Ctx::new()).unwrap();
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
let w = write_destination(&plain(&disk), &c, true, &ctx).unwrap();
|
||||||
|
assert_eq!(w.head, s.head());
|
||||||
|
assert!(!w.new, "the winner's manifest already says it");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_dir(disk.join("wanderbooks-acme/manifests"))
|
||||||
|
.unwrap()
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
prove(&disk, None, dir.path(), "v").unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- what the store reads of a backup -----------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_text_read_from_a_stored_file_is_a_stored_file_too() {
|
||||||
|
// The store's own verification reads the text an extraction recorded as
|
||||||
|
// a stored file; a backup that left it out would not prove whole, so it
|
||||||
|
// is carried and proven with the rest.
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let (attachment, _, _) = s
|
||||||
|
.attach_receipt(
|
||||||
|
None,
|
||||||
|
"words.txt",
|
||||||
|
"text/plain",
|
||||||
|
b"a receipt with words",
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
s.extract_attachment(attachment).unwrap();
|
||||||
|
let text_sha = s
|
||||||
|
.extraction(attachment)
|
||||||
|
.unwrap()
|
||||||
|
.and_then(|x| x.text_sha256)
|
||||||
|
.expect("the text is a stored file");
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let v = prove(&disk, None, dir.path(), "v").unwrap();
|
||||||
|
assert!(
|
||||||
|
v.tree
|
||||||
|
.join("blobs")
|
||||||
|
.join(&text_sha[0..2])
|
||||||
|
.join(&text_sha[2..4])
|
||||||
|
.join(&text_sha)
|
||||||
|
.is_file()
|
||||||
|
);
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- what the removed tests of the old form protected ------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_purged_vault_leaves_the_next_backup_and_not_the_earlier_ones() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
std::fs::create_dir_all(b.join("vault")).unwrap();
|
||||||
|
std::fs::write(b.join("vault").join("tin-1.bin"), b"sealed record").unwrap();
|
||||||
|
std::fs::create_dir_all(b.join("keys")).unwrap();
|
||||||
|
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
// The vault is purged to nothing: the next backup holds none, the
|
||||||
|
// earlier one still does (nothing in a destination is deleted).
|
||||||
|
std::fs::remove_file(b.join("vault").join("tin-1.bin")).unwrap();
|
||||||
|
std::fs::remove_dir(b.join("vault")).unwrap();
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(w.new && w.number == 2, "{w:?}");
|
||||||
|
let now = prove(&disk, None, dir.path(), "now").unwrap();
|
||||||
|
assert!(!now.tree.join("vault").exists());
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(now.tree.join("keys").join("legacy.key")).unwrap(),
|
||||||
|
"ab".repeat(32)
|
||||||
|
);
|
||||||
|
let then = dir.path().join("then");
|
||||||
|
copy_tree(&disk, &then);
|
||||||
|
std::fs::remove_file(then.join("wanderbooks-acme/manifests/000002.json")).unwrap();
|
||||||
|
let old = prove(&then, None, dir.path(), "old").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(old.tree.join("vault").join("tin-1.bin")).unwrap(),
|
||||||
|
b"sealed record"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_scratch_file_left_by_a_dead_program_never_stops_the_next_backup() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
// What a program that died leaves: a scratch file, a short manifest at
|
||||||
|
// the next number (its number is spent), a piece cut short.
|
||||||
|
let set = disk.join("wanderbooks-acme");
|
||||||
|
std::fs::write(set.join("manifests").join(".wb-tmp-9-abcdef"), b"half").unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
set.join("manifests").join("000002.json"),
|
||||||
|
b"{\"format\":\"wan",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
more(&mut s, 1);
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(w.new && w.number == 3, "{w:?}");
|
||||||
|
let v = prove(&disk, None, dir.path(), "v").unwrap();
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stored_file_that_does_not_match_its_name_is_refused_and_nothing_is_written() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let sha = ledger_store::journal::sha256_hex(b"%PDF-1.4 r");
|
||||||
|
let blob = b.join("blobs").join(&sha[0..2]).join(&sha[2..4]).join(&sha);
|
||||||
|
std::fs::write(&blob, b"changed under its name").unwrap();
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let err = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err();
|
||||||
|
assert!(matches!(err, BackupError::Damaged(_)), "{err:?}");
|
||||||
|
// No manifest: nothing there is a backup.
|
||||||
|
assert!(
|
||||||
|
!tree(&disk)
|
||||||
|
.keys()
|
||||||
|
.any(|n| n.contains("manifests/") && n.ends_with(".json"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_drill_proves_this_books_history_only() {
|
||||||
|
use ledger_store::backup::drill;
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (b1, b2) = (dir.path().join("one"), dir.path().join("two"));
|
||||||
|
let (mut s1, s2) = (book(&b1), book(&b2));
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap();
|
||||||
|
let head = s1.head();
|
||||||
|
// The books move on: the backup is the beginning of their journal.
|
||||||
|
more(&mut s1, 1);
|
||||||
|
let got = drill(
|
||||||
|
&plain(&disk),
|
||||||
|
"acme",
|
||||||
|
&b1.join("journal.jsonl"),
|
||||||
|
&dir.path().join("d1"),
|
||||||
|
None,
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(got, head);
|
||||||
|
assert!(!dir.path().join("d1").exists(), "the scratch is removed");
|
||||||
|
// Another book's history under the same name: not this book's.
|
||||||
|
let err = drill(
|
||||||
|
&plain(&disk),
|
||||||
|
"acme",
|
||||||
|
&b2.join("journal.jsonl"),
|
||||||
|
&dir.path().join("d2"),
|
||||||
|
None,
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(
|
||||||
|
matches!(err, BackupError::Damaged(_)),
|
||||||
|
"{err:?} {:?}",
|
||||||
|
s2.head()
|
||||||
|
);
|
||||||
|
assert!(!dir.path().join("d2").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_local_backup_proves_to_hold_the_book_as_it_is_keys_and_all() {
|
||||||
|
use ledger_store::backup::{prove_local, write_local};
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
std::fs::create_dir_all(b.join("keys")).unwrap();
|
||||||
|
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
|
||||||
|
let scratch = dir.path().join("check");
|
||||||
|
let c = cut(&b, &s);
|
||||||
|
write_local(&b, &c, &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).unwrap(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert!(!scratch.exists(), "the scratch folder is removed");
|
||||||
|
// A changed key, a changed vault record, an extra one, books that moved
|
||||||
|
// on, each refused.
|
||||||
|
std::fs::write(b.join("keys").join("legacy.key"), "cd".repeat(32)).unwrap();
|
||||||
|
assert!(prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).is_err());
|
||||||
|
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
|
||||||
|
std::fs::create_dir_all(b.join("vault")).unwrap();
|
||||||
|
std::fs::write(b.join("vault").join("tin-2.bin"), b"extra").unwrap();
|
||||||
|
assert!(prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).is_err());
|
||||||
|
std::fs::remove_file(b.join("vault").join("tin-2.bin")).unwrap();
|
||||||
|
more(&mut s, 1);
|
||||||
|
assert!(prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).is_err());
|
||||||
|
// Written again, it proves the books as they are now.
|
||||||
|
write_local(&b, &cut(&b, &s), &Ctx::new()).unwrap();
|
||||||
|
prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).unwrap();
|
||||||
|
assert!(!scratch.exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_link_in_a_backup_is_never_followed() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
// The journal's piece replaced by a link to a file elsewhere with the
|
||||||
|
// same bytes: it is no piece of the backup.
|
||||||
|
let set = disk.join("wanderbooks-acme");
|
||||||
|
let piece = std::fs::read_dir(set.join("journal"))
|
||||||
|
.unwrap()
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.path();
|
||||||
|
let elsewhere = dir.path().join("elsewhere");
|
||||||
|
std::fs::copy(&piece, &elsewhere).unwrap();
|
||||||
|
std::fs::remove_file(&piece).unwrap();
|
||||||
|
std::os::unix::fs::symlink(&elsewhere, &piece).unwrap();
|
||||||
|
assert!(prove(&disk, None, dir.path(), "v").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_drill_stops_inside_the_phase_it_is_told_to_stop_in() {
|
||||||
|
use ledger_store::backup::drill;
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
// The phases a drill goes through; a stop asked as each begins ends the
|
||||||
|
// drill there (the observer sees no later phase), scratch removed.
|
||||||
|
let phases = ["fetch", "replay", "verify", "blobs", "vault", "prefix"];
|
||||||
|
for stop_at in phases {
|
||||||
|
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||||
|
let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
|
||||||
|
let ctx = {
|
||||||
|
let (stop, seen) = (stop.clone(), seen.clone());
|
||||||
|
Ctx::new()
|
||||||
|
.with_stop(stop.clone())
|
||||||
|
.with_phase_watch(Arc::new(move |p: &str| {
|
||||||
|
seen.lock().unwrap().push(p.to_string());
|
||||||
|
if p == stop_at {
|
||||||
|
stop.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
let scratch = dir.path().join(format!("d-{stop_at}"));
|
||||||
|
let got = drill(
|
||||||
|
&plain(&disk),
|
||||||
|
"acme",
|
||||||
|
&b.join("journal.jsonl"),
|
||||||
|
&scratch,
|
||||||
|
None,
|
||||||
|
&ctx,
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(got, Err(BackupError::Cancelled(_))),
|
||||||
|
"{stop_at}: {got:?}"
|
||||||
|
);
|
||||||
|
let seen = seen.lock().unwrap().clone();
|
||||||
|
assert_eq!(seen.last().map(String::as_str), Some(stop_at), "{seen:?}");
|
||||||
|
assert!(!scratch.exists(), "{stop_at}: scratch left");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,473 @@
|
|||||||
|
//! Backups onto the disks people really have (WB-backup-18 to WB-backup-22):
|
||||||
|
//! a disk that makes no hard links (FAT or exFAT on a stick), sealed pieces
|
||||||
|
//! in folders a small disk can hold, a header that asks for more than it
|
||||||
|
//! should, and a folder a sync service has not finished putting on this
|
||||||
|
//! computer.
|
||||||
|
|
||||||
|
use ledger_core::{AccountType, Currency, Money, Side};
|
||||||
|
use ledger_store::Store;
|
||||||
|
use ledger_store::backup::{
|
||||||
|
BackupError, BackupKey, Ctx, Cut, Destination, Options, find, key_derivations, verify_found,
|
||||||
|
write_destination, write_destination_with,
|
||||||
|
};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
fn usd(s: &str) -> Money {
|
||||||
|
Money::new(s.parse().unwrap(), Currency::USD)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn book(dir: &Path) -> Store {
|
||||||
|
let mut s = Store::create(dir, Currency::USD).unwrap();
|
||||||
|
let cash = s
|
||||||
|
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||||
|
.unwrap();
|
||||||
|
let cap = s
|
||||||
|
.add_account("3000", "Capital", AccountType::Equity, None, false)
|
||||||
|
.unwrap();
|
||||||
|
let e = s
|
||||||
|
.create_entry(
|
||||||
|
chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(),
|
||||||
|
"Start",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap();
|
||||||
|
s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap();
|
||||||
|
s.post_entry(e).unwrap();
|
||||||
|
s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None)
|
||||||
|
.unwrap();
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
fn more(s: &mut Store, n: usize) {
|
||||||
|
s.add_account(
|
||||||
|
&format!("{}", 6000 + n),
|
||||||
|
&format!("Expense {n}"),
|
||||||
|
AccountType::Expense,
|
||||||
|
None,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
s.attach_receipt(
|
||||||
|
None,
|
||||||
|
&format!("f{n}.txt"),
|
||||||
|
"text/plain",
|
||||||
|
format!("receipt number {n}").as_bytes(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cut(dir: &Path, s: &Store) -> Cut {
|
||||||
|
Cut::take("acme", dir, s.head()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plain(folder: &Path) -> Destination {
|
||||||
|
Destination {
|
||||||
|
folder: folder.to_path_buf(),
|
||||||
|
key: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||||
|
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||||
|
for e in std::fs::read_dir(dir).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
if p.is_dir() {
|
||||||
|
walk(base, &p, out);
|
||||||
|
} else {
|
||||||
|
let rel = p
|
||||||
|
.strip_prefix(base)
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.replace('\\', "/");
|
||||||
|
out.insert(rel, std::fs::read(&p).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
if root.is_dir() {
|
||||||
|
walk(root, root, &mut out);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prove(
|
||||||
|
source: &Path,
|
||||||
|
pass: Option<&str>,
|
||||||
|
root: &Path,
|
||||||
|
name: &str,
|
||||||
|
) -> ledger_store::backup::Verified {
|
||||||
|
let found = find(source, pass, &Ctx::new()).unwrap();
|
||||||
|
verify_found(&found, &root.join(name), &Ctx::new()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- a disk that makes no hard links ---------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_disk_that_makes_no_links_takes_whole_backups_and_only_grows() {
|
||||||
|
for ctx in [
|
||||||
|
Ctx::new().with_no_hard_links(),
|
||||||
|
// And one whose move cannot refuse to replace either: exclusive
|
||||||
|
// create and copy.
|
||||||
|
Ctx::new().with_no_exclusive_move(),
|
||||||
|
] {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let mut before = BTreeMap::new();
|
||||||
|
for n in 0..3 {
|
||||||
|
more(&mut s, n);
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap();
|
||||||
|
assert!(w.new && w.repaired.is_empty(), "{w:?}");
|
||||||
|
let now = tree(&disk);
|
||||||
|
for (name, bytes) in &before {
|
||||||
|
assert_eq!(now.get(name), Some(bytes), "{name} must not change");
|
||||||
|
}
|
||||||
|
assert!(!now.keys().any(|n| n.contains(".wb-tmp-")), "scratch left");
|
||||||
|
before = now;
|
||||||
|
}
|
||||||
|
let v = prove(&disk, None, dir.path(), "v");
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
assert_eq!(v.passed_over, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_writers_racing_on_a_disk_that_makes_no_links_do_not_corrupt_it() {
|
||||||
|
for exclusive_move_missing in [false, true] {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
for round in 0..3 {
|
||||||
|
more(&mut s, round);
|
||||||
|
let c = cut(&b, &s);
|
||||||
|
let results: Vec<_> = std::thread::scope(|scope| {
|
||||||
|
let handles: Vec<_> = (0..3)
|
||||||
|
.map(|_| {
|
||||||
|
let (c, disk) = (c.clone(), disk.clone());
|
||||||
|
scope.spawn(move || {
|
||||||
|
let ctx = if exclusive_move_missing {
|
||||||
|
Ctx::new().with_no_exclusive_move()
|
||||||
|
} else {
|
||||||
|
Ctx::new().with_no_hard_links()
|
||||||
|
};
|
||||||
|
write_destination(&plain(&disk), &c, true, &ctx)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||||
|
});
|
||||||
|
for r in &results {
|
||||||
|
let w = r
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_or_else(|e| panic!("round {round}: {e:?}"));
|
||||||
|
assert_eq!(w.head, s.head());
|
||||||
|
}
|
||||||
|
let v = prove(&disk, None, dir.path(), &format!("v{round}"));
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
assert_eq!(v.passed_over, 0, "round {round}");
|
||||||
|
assert!(
|
||||||
|
!tree(&disk).keys().any(|n| n.contains(".wb-tmp-")),
|
||||||
|
"scratch left"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_taken_number_or_name_is_never_replaced_on_a_disk_that_makes_no_links() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let ctx = Ctx::new().with_no_hard_links();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap();
|
||||||
|
let set = disk.join("wanderbooks-acme");
|
||||||
|
// A rival's manifest 2 is already in place when this one comes to put
|
||||||
|
// its own as number 2.
|
||||||
|
more(&mut s, 1);
|
||||||
|
let rival = disk.join("rival");
|
||||||
|
std::fs::create_dir(&rival).unwrap();
|
||||||
|
let c = cut(&b, &s);
|
||||||
|
let taken = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||||
|
let hook = {
|
||||||
|
let (set, taken) = (set.clone(), taken.clone());
|
||||||
|
Ctx::new()
|
||||||
|
.with_no_hard_links()
|
||||||
|
.with_faults(std::sync::Arc::new(move |kind, rel| {
|
||||||
|
if kind == "create"
|
||||||
|
&& rel.starts_with("manifests/")
|
||||||
|
&& taken.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0
|
||||||
|
{
|
||||||
|
std::fs::write(set.join("manifests/000002.json"), b"a rival's, whole").unwrap();
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
let _ = write_destination(&plain(&disk), &c, true, &hook);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(set.join("manifests/000002.json")).unwrap(),
|
||||||
|
b"a rival's, whole",
|
||||||
|
"the manifest that was there is never replaced"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- sealed pieces in folders a small disk can hold --------------------------
|
||||||
|
|
||||||
|
const PASS: &str = "correct horse battery staple";
|
||||||
|
|
||||||
|
/// The count of derived keys is the process's: the tests that read it, and
|
||||||
|
/// every test that derives one, take turns.
|
||||||
|
static KEYS: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||||
|
|
||||||
|
fn one_at_a_time() -> std::sync::MutexGuard<'static, ()> {
|
||||||
|
KEYS.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sealed_pieces_are_spread_over_folders_as_the_plain_form_does() {
|
||||||
|
let _turn = one_at_a_time();
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
for n in 0..30 {
|
||||||
|
more(&mut s, n);
|
||||||
|
}
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let dest = Destination {
|
||||||
|
folder: disk.clone(),
|
||||||
|
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||||
|
};
|
||||||
|
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let set = std::fs::read_dir(&disk)
|
||||||
|
.unwrap()
|
||||||
|
.flatten()
|
||||||
|
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
|
||||||
|
.unwrap()
|
||||||
|
.path();
|
||||||
|
let mut in_folders = 0usize;
|
||||||
|
for entry in std::fs::read_dir(set.join("pieces")).unwrap().flatten() {
|
||||||
|
let name = entry.file_name().to_string_lossy().into_owned();
|
||||||
|
assert!(
|
||||||
|
entry.path().is_dir(),
|
||||||
|
"{name}: a piece sits in a flat folder"
|
||||||
|
);
|
||||||
|
assert_eq!(name.len(), 2, "{name}");
|
||||||
|
for piece in std::fs::read_dir(entry.path()).unwrap().flatten() {
|
||||||
|
assert!(
|
||||||
|
piece.file_name().to_string_lossy().starts_with(&name),
|
||||||
|
"a piece is in the folder of its name's first two digits"
|
||||||
|
);
|
||||||
|
in_folders += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(in_folders > 30, "{in_folders}");
|
||||||
|
let v = prove(&disk, Some(PASS), dir.path(), "v");
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- a header that is read from a folder anyone may have written -------------
|
||||||
|
|
||||||
|
/// The sealed set's folder in `disk`.
|
||||||
|
fn sealed_set(disk: &Path) -> PathBuf {
|
||||||
|
std::fs::read_dir(disk)
|
||||||
|
.unwrap()
|
||||||
|
.flatten()
|
||||||
|
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
|
||||||
|
.unwrap()
|
||||||
|
.path()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rewrite the header's key settings and make its own check line right
|
||||||
|
/// again (what a person who meant to would do).
|
||||||
|
fn set_header(header: &Path, edit: impl Fn(&mut serde_json::Value)) {
|
||||||
|
let text = std::fs::read_to_string(header).unwrap();
|
||||||
|
let body = text.lines().next().unwrap();
|
||||||
|
let mut v: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||||
|
edit(&mut v);
|
||||||
|
let body = serde_json::to_string(&v).unwrap();
|
||||||
|
let check = hex::encode(Sha256::digest(body.as_bytes()));
|
||||||
|
std::fs::write(
|
||||||
|
header,
|
||||||
|
format!("{body}\nwanderbooks-header-sha256 {check}\n"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_header_cannot_ask_for_more_than_a_few_times_what_this_program_spends() {
|
||||||
|
let _turn = one_at_a_time();
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let dest = Destination {
|
||||||
|
folder: disk.clone(),
|
||||||
|
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||||
|
};
|
||||||
|
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let header = sealed_set(&disk).join("header.json");
|
||||||
|
let original = std::fs::read(&header).unwrap();
|
||||||
|
for (what, value) in [
|
||||||
|
("m", serde_json::json!(4_000_000u32)),
|
||||||
|
("m", serde_json::json!(64 * 1024 * 5)),
|
||||||
|
("t", serde_json::json!(13)),
|
||||||
|
("p", serde_json::json!(5)),
|
||||||
|
] {
|
||||||
|
set_header(&header, |v| v["kdf"][what] = value.clone());
|
||||||
|
let derived = key_derivations();
|
||||||
|
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
|
||||||
|
// Refused as damage before any key is derived: no memory spent.
|
||||||
|
assert!(
|
||||||
|
matches!(err, BackupError::Damaged(_) | BackupError::NotABackup),
|
||||||
|
"{what}: {err:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(key_derivations(), derived, "{what}: a key was derived");
|
||||||
|
}
|
||||||
|
std::fs::write(&header, &original).unwrap();
|
||||||
|
let v = prove(&disk, Some(PASS), dir.path(), "v");
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_header_that_was_changed_reads_as_damage_and_not_as_a_wrong_passphrase() {
|
||||||
|
let _turn = one_at_a_time();
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let dest = Destination {
|
||||||
|
folder: disk.clone(),
|
||||||
|
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||||
|
};
|
||||||
|
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let header = sealed_set(&disk).join("header.json");
|
||||||
|
// A setting changed in the file as a bad sector or a bad sync would:
|
||||||
|
// the header's own check line no longer matches.
|
||||||
|
let text = std::fs::read_to_string(&header).unwrap();
|
||||||
|
let changed = text.replacen("\"t\":3", "\"t\":4", 1);
|
||||||
|
assert_ne!(text, changed, "the header names its passes");
|
||||||
|
std::fs::write(&header, changed).unwrap();
|
||||||
|
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
|
||||||
|
assert!(
|
||||||
|
matches!(err, BackupError::Damaged(_) | BackupError::NotABackup),
|
||||||
|
"{err:?}"
|
||||||
|
);
|
||||||
|
// Changed on purpose and made consistent again: the key comes out
|
||||||
|
// different and opens nothing (the safe way to fail), and no
|
||||||
|
// passphrase is guessed any faster.
|
||||||
|
std::fs::write(&header, &text).unwrap();
|
||||||
|
set_header(&header, |v| v["kdf"]["t"] = serde_json::json!(4));
|
||||||
|
assert!(matches!(
|
||||||
|
find(&disk, Some(PASS), &Ctx::new()),
|
||||||
|
Err(BackupError::WrongPassphrase)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_folder_of_sealed_sets_costs_one_key_derivation_per_setting_not_one_per_set() {
|
||||||
|
let _turn = one_at_a_time();
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let dest = Destination {
|
||||||
|
folder: disk.clone(),
|
||||||
|
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||||
|
};
|
||||||
|
let c = cut(&b, &s);
|
||||||
|
write_destination(&dest, &c, true, &Ctx::new()).unwrap();
|
||||||
|
for _ in 0..2 {
|
||||||
|
write_destination_with(
|
||||||
|
&dest,
|
||||||
|
&c,
|
||||||
|
Options {
|
||||||
|
may_create: true,
|
||||||
|
new_set: true,
|
||||||
|
},
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let sets = std::fs::read_dir(&disk)
|
||||||
|
.unwrap()
|
||||||
|
.flatten()
|
||||||
|
.filter(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
|
||||||
|
.count();
|
||||||
|
assert_eq!(sets, 3);
|
||||||
|
let derived = key_derivations();
|
||||||
|
// Three sets of one book: it asks which, after one derivation.
|
||||||
|
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
|
||||||
|
assert!(matches!(err, BackupError::Several(_)), "{err:?}");
|
||||||
|
assert_eq!(key_derivations() - derived, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- files a sync service has not downloaded ---------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_file_that_is_not_downloaded_yet_reads_as_such_and_never_as_damage_or_absence() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let set = disk.join("wanderbooks-acme");
|
||||||
|
let before = tree(&disk);
|
||||||
|
|
||||||
|
// A piece of the newest backup that iCloud has left as a stand-in
|
||||||
|
// (`.name.icloud`) in its place.
|
||||||
|
let manifest = std::fs::read_to_string(set.join("manifests/000001.json")).unwrap();
|
||||||
|
let m: serde_json::Value = serde_json::from_str(manifest.lines().next().unwrap()).unwrap();
|
||||||
|
let seg = set.join(m["journal"]["segments"][0]["file"].as_str().unwrap());
|
||||||
|
let stand_in = seg.with_file_name(format!(
|
||||||
|
".{}.icloud",
|
||||||
|
seg.file_name().unwrap().to_string_lossy()
|
||||||
|
));
|
||||||
|
let held = std::fs::read(&seg).unwrap();
|
||||||
|
std::fs::rename(&seg, &stand_in).unwrap();
|
||||||
|
let found = find(&disk, None, &Ctx::new());
|
||||||
|
// Nothing says "damaged", nothing says "not a backup": it is waiting.
|
||||||
|
assert_eq!(found.err(), Some(BackupError::NotDownloaded));
|
||||||
|
more(&mut s, 1);
|
||||||
|
assert_eq!(
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err(),
|
||||||
|
BackupError::NotDownloaded
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
BackupError::NotDownloaded
|
||||||
|
.to_string()
|
||||||
|
.contains("not downloaded to this computer yet")
|
||||||
|
);
|
||||||
|
// Downloaded: all as it was.
|
||||||
|
std::fs::rename(&stand_in, &seg).unwrap();
|
||||||
|
assert_eq!(std::fs::read(&seg).unwrap(), held);
|
||||||
|
assert_eq!(tree(&disk), before);
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
|
||||||
|
// The newest manifest as a stand-in: the folder is listed with it, and
|
||||||
|
// the writer will not make a manifest under its number.
|
||||||
|
let newest = set.join("manifests/000002.json");
|
||||||
|
let stand = set.join("manifests/.000002.json.icloud");
|
||||||
|
std::fs::rename(&newest, &stand).unwrap();
|
||||||
|
more(&mut s, 2);
|
||||||
|
assert_eq!(
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err(),
|
||||||
|
BackupError::NotDownloaded
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
find(&disk, None, &Ctx::new()).err(),
|
||||||
|
Some(BackupError::NotDownloaded)
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
//! Backups as properties (WB-backup-1 to WB-backup-7): random books and
|
||||||
|
//! random sequences of backups, interleavings of two writers, damage to any
|
||||||
|
//! piece, and passphrases that are not the right one. Each case builds a
|
||||||
|
//! book, which is the cost; the cases are few and the oracles are the laws.
|
||||||
|
|
||||||
|
use ledger_core::{AccountType, Currency};
|
||||||
|
use ledger_store::Store;
|
||||||
|
use ledger_store::backup::{
|
||||||
|
BackupError, BackupKey, Ctx, Cut, Destination, find, verify_found, write_destination,
|
||||||
|
};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
/// One thing that happens to the books between backups.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
enum Op {
|
||||||
|
/// A new account.
|
||||||
|
Account,
|
||||||
|
/// A stored file of these bytes (the same bytes twice are one file).
|
||||||
|
File(Vec<u8>),
|
||||||
|
/// A backup.
|
||||||
|
Backup,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ops() -> impl Strategy<Value = Vec<Op>> {
|
||||||
|
prop::collection::vec(
|
||||||
|
prop_oneof![
|
||||||
|
2 => Just(Op::Account),
|
||||||
|
2 => prop::collection::vec(any::<u8>(), 1..40).prop_map(Op::File),
|
||||||
|
3 => Just(Op::Backup),
|
||||||
|
],
|
||||||
|
2..9,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A context for tests of logic, not of durability: nothing is synced.
|
||||||
|
fn fast() -> Ctx {
|
||||||
|
// The proof after a backup has tests of its own (backup_repair.rs); the
|
||||||
|
// properties here prove what they make by restoring it.
|
||||||
|
Ctx::new().with_no_sync().with_proof_skipped()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plain(folder: &Path) -> Destination {
|
||||||
|
Destination {
|
||||||
|
folder: folder.to_path_buf(),
|
||||||
|
key: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||||
|
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||||
|
for e in std::fs::read_dir(dir).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
if p.is_dir() {
|
||||||
|
walk(base, &p, out);
|
||||||
|
} else {
|
||||||
|
let rel = p
|
||||||
|
.strip_prefix(base)
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.replace('\\', "/");
|
||||||
|
out.insert(rel, std::fs::read(&p).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
if root.is_dir() {
|
||||||
|
walk(root, root, &mut out);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_tree(from: &Path, to: &Path) {
|
||||||
|
std::fs::create_dir_all(to).unwrap();
|
||||||
|
for (rel, bytes) in tree(from) {
|
||||||
|
let p = to.join(rel);
|
||||||
|
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(p, bytes).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A book with one account, and a way to apply [`Op`]s to it.
|
||||||
|
struct Books {
|
||||||
|
store: Store,
|
||||||
|
dir: std::path::PathBuf,
|
||||||
|
n: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Books {
|
||||||
|
fn new(dir: &Path) -> Self {
|
||||||
|
let mut store = Store::create(dir, Currency::USD).unwrap();
|
||||||
|
store
|
||||||
|
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||||
|
.unwrap();
|
||||||
|
Self {
|
||||||
|
store,
|
||||||
|
dir: dir.to_path_buf(),
|
||||||
|
n: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(&mut self, op: &Op) {
|
||||||
|
match op {
|
||||||
|
Op::Account => {
|
||||||
|
self.n += 1;
|
||||||
|
self.store
|
||||||
|
.add_account(
|
||||||
|
&format!("{}", 6000 + self.n),
|
||||||
|
&format!("Expense {}", self.n),
|
||||||
|
AccountType::Expense,
|
||||||
|
None,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
Op::File(bytes) => {
|
||||||
|
self.store
|
||||||
|
.attach_receipt(None, "f.bin", "application/octet-stream", bytes, None)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
Op::Backup => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cut(&self) -> Cut {
|
||||||
|
Cut::take("acme", &self.dir, self.store.head()).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prove(
|
||||||
|
folder: &Path,
|
||||||
|
pass: Option<&str>,
|
||||||
|
scratch: &Path,
|
||||||
|
) -> Result<ledger_store::backup::Verified, BackupError> {
|
||||||
|
let found = find(folder, pass, &Ctx::new())?;
|
||||||
|
verify_found(&found, scratch, &Ctx::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config() -> ProptestConfig {
|
||||||
|
ProptestConfig {
|
||||||
|
cases: 5,
|
||||||
|
max_shrink_iters: 4,
|
||||||
|
failure_persistence: None,
|
||||||
|
..ProptestConfig::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(config())]
|
||||||
|
|
||||||
|
/// WB-backup-1: whatever the books do and whenever they are backed up,
|
||||||
|
/// every file the destination held is still there, byte for byte.
|
||||||
|
#[test]
|
||||||
|
fn a_destination_only_grows(ops in ops()) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let mut books = Books::new(&dir.path().join("book"));
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let mut before = tree(&disk);
|
||||||
|
for op in &ops {
|
||||||
|
books.apply(op);
|
||||||
|
if matches!(op, Op::Backup) {
|
||||||
|
write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
|
||||||
|
let after = tree(&disk);
|
||||||
|
for (name, bytes) in &before {
|
||||||
|
prop_assert_eq!(after.get(name), Some(bytes), "{} changed or went", name);
|
||||||
|
}
|
||||||
|
prop_assert!(!after.keys().any(|n| n.contains(".wb-tmp-")));
|
||||||
|
before = after;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-backup-3: the destination as of any of its manifests restores to
|
||||||
|
/// books whose journal is byte-identical to the beginning of the
|
||||||
|
/// books' journal now, and whose head is the one that manifest names.
|
||||||
|
#[test]
|
||||||
|
fn any_whole_manifest_restores_a_prefix_of_the_books(ops in ops()) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let mut books = Books::new(&dir.path().join("book"));
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let mut heads = Vec::new();
|
||||||
|
for op in &ops {
|
||||||
|
books.apply(op);
|
||||||
|
if matches!(op, Op::Backup) {
|
||||||
|
let w = write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
|
||||||
|
if w.new {
|
||||||
|
heads.push((w.number, w.head));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// (A last backup, so there is at least one.)
|
||||||
|
let w = write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
|
||||||
|
if w.new {
|
||||||
|
heads.push((w.number, w.head));
|
||||||
|
}
|
||||||
|
let live = std::fs::read(dir.path().join("book").join("journal.jsonl")).unwrap();
|
||||||
|
for (number, head) in &heads {
|
||||||
|
// The destination as it was when that manifest was the newest.
|
||||||
|
let then = dir.path().join(format!("then-{number}"));
|
||||||
|
copy_tree(&disk, &then);
|
||||||
|
for (name, _) in tree(&then) {
|
||||||
|
if let Some(n) = name
|
||||||
|
.strip_prefix("wanderbooks-acme/manifests/")
|
||||||
|
.and_then(|r| r.strip_suffix(".json"))
|
||||||
|
.and_then(|r| r.parse::<u64>().ok())
|
||||||
|
&& n > *number
|
||||||
|
{
|
||||||
|
std::fs::remove_file(then.join(&name)).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let v = prove(&then, None, &dir.path().join(format!("v-{number}"))).unwrap();
|
||||||
|
prop_assert_eq!(&v.head, head);
|
||||||
|
let restored = std::fs::read(v.tree.join("journal.jsonl")).unwrap();
|
||||||
|
prop_assert!(live.starts_with(&restored));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-backup-5: a writer that finds another writer's backup appear at
|
||||||
|
/// any of its write points (the other with books a little behind or a
|
||||||
|
/// little ahead) leaves a destination that proves whole, at the head
|
||||||
|
/// of one of them, restoring to a prefix of the longer books.
|
||||||
|
#[test]
|
||||||
|
fn random_interleavings_of_two_writers_leave_a_whole_backup(
|
||||||
|
files in prop::collection::vec(prop::collection::vec(any::<u8>(), 1..20), 1..3),
|
||||||
|
rival_after in 0usize..3,
|
||||||
|
at in 0usize..14,
|
||||||
|
) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let mut books = Books::new(&dir.path().join("book"));
|
||||||
|
for f in &files {
|
||||||
|
books.apply(&Op::File(f.clone()));
|
||||||
|
}
|
||||||
|
let first = books.cut();
|
||||||
|
for _ in 0..rival_after {
|
||||||
|
books.apply(&Op::Account);
|
||||||
|
}
|
||||||
|
let second = books.cut();
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
// The writer of `first` is met, at its `at`th write point, by a
|
||||||
|
// complete write of `second`.
|
||||||
|
let count = Arc::new(AtomicUsize::new(0));
|
||||||
|
let rival = {
|
||||||
|
let (disk, second, count) = (disk.clone(), second.clone(), count.clone());
|
||||||
|
fast().with_faults(Arc::new(move |_, _| {
|
||||||
|
if count.fetch_add(1, Ordering::SeqCst) == at {
|
||||||
|
write_destination(
|
||||||
|
&plain(&disk),
|
||||||
|
&second,
|
||||||
|
true,
|
||||||
|
&fast(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
let mine = write_destination(&plain(&disk), &first, true, &rival);
|
||||||
|
match mine {
|
||||||
|
Ok(_) | Err(BackupError::Ahead(..)) | Err(BackupError::Elsewhere) => {}
|
||||||
|
Err(e) => prop_assert!(false, "{e:?}"),
|
||||||
|
}
|
||||||
|
let v = prove(&disk, None, &dir.path().join("v")).unwrap();
|
||||||
|
prop_assert!(v.head == *first.head() || v.head == *second.head());
|
||||||
|
let live = std::fs::read(dir.path().join("book").join("journal.jsonl")).unwrap();
|
||||||
|
prop_assert!(live.starts_with(&std::fs::read(v.tree.join("journal.jsonl")).unwrap()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-backup-6: a piece with one byte flipped, or cut anywhere, is
|
||||||
|
/// found: the backup that names it is not restored.
|
||||||
|
#[test]
|
||||||
|
fn any_flipped_or_cut_piece_is_found_never_restored(
|
||||||
|
ops in ops(),
|
||||||
|
pick in any::<prop::sample::Index>(),
|
||||||
|
at in any::<prop::sample::Index>(),
|
||||||
|
cut in any::<bool>(),
|
||||||
|
) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let mut books = Books::new(&dir.path().join("book"));
|
||||||
|
books.apply(&Op::File(vec![1, 2, 3, 4]));
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
for op in &ops {
|
||||||
|
books.apply(op);
|
||||||
|
}
|
||||||
|
write_destination(
|
||||||
|
&plain(&disk),
|
||||||
|
&books.cut(),
|
||||||
|
true,
|
||||||
|
&fast(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let set = disk.join("wanderbooks-acme");
|
||||||
|
let pieces: Vec<String> = tree(&set)
|
||||||
|
.into_keys()
|
||||||
|
.filter(|n| {
|
||||||
|
!n.starts_with("manifests/") && !n.starts_with("proofs/") && n != "READ-ME.txt"
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let name = &pieces[pick.index(pieces.len())];
|
||||||
|
let path = set.join(name);
|
||||||
|
let mut bytes = std::fs::read(&path).unwrap();
|
||||||
|
prop_assume!(!bytes.is_empty());
|
||||||
|
let i = at.index(bytes.len());
|
||||||
|
if cut {
|
||||||
|
bytes.truncate(i);
|
||||||
|
} else {
|
||||||
|
bytes[i] ^= 0x01;
|
||||||
|
}
|
||||||
|
std::fs::write(&path, &bytes).unwrap();
|
||||||
|
let scratch = dir.path().join("v");
|
||||||
|
prop_assert!(prove(&disk, None, &scratch).is_err(), "{name} damaged was restored");
|
||||||
|
prop_assert!(!scratch.exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WB-backup-7: no passphrase but the right one gives books.
|
||||||
|
#[test]
|
||||||
|
fn a_wrong_passphrase_never_yields_books(wrong in "[a-zA-Z0-9 ]{1,30}") {
|
||||||
|
prop_assume!(wrong != "the right words, exactly");
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let books = Books::new(&dir.path().join("book"));
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let dest = Destination {
|
||||||
|
folder: disk.clone(),
|
||||||
|
key: Some(BackupKey::generate("the right words, exactly").unwrap()),
|
||||||
|
};
|
||||||
|
write_destination(&dest, &books.cut(), true, &fast()).unwrap();
|
||||||
|
let scratch = dir.path().join("v");
|
||||||
|
let got = prove(&disk, Some(&wrong), &scratch);
|
||||||
|
prop_assert!(matches!(got, Err(BackupError::WrongPassphrase)), "{got:?}");
|
||||||
|
prop_assert!(!scratch.exists());
|
||||||
|
let none = prove(&disk, None, &scratch);
|
||||||
|
prop_assert!(matches!(none, Err(BackupError::NeedsPassphrase)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,790 @@
|
|||||||
|
//! A backup that restores old or wrong books while reporting good is the
|
||||||
|
//! worst defect this product can have (WB-backup-12 to WB-backup-17): a
|
||||||
|
//! damaged piece must not be reused by later backups, the drill must not
|
||||||
|
//! prove an older backup and say ok, a damaged piece must be found by the
|
||||||
|
//! proof after the backup and written again beside the damaged file, books
|
||||||
|
//! that are behind a destination must be told from books that have
|
||||||
|
//! diverged, and a restore must say when it is not of the newest backup.
|
||||||
|
|
||||||
|
use ledger_core::{AccountType, Currency, Money, Role, Side, TinFacts, TinType};
|
||||||
|
use ledger_store::Store;
|
||||||
|
use ledger_store::backup::{
|
||||||
|
BackupError, Ctx, Cut, Destination, Options, drill, find, verify_found, write_destination,
|
||||||
|
write_destination_with,
|
||||||
|
};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
fn usd(s: &str) -> Money {
|
||||||
|
Money::new(s.parse().unwrap(), Currency::USD)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn book(dir: &Path) -> Store {
|
||||||
|
let mut s = Store::create(dir, Currency::USD).unwrap();
|
||||||
|
let cash = s
|
||||||
|
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||||
|
.unwrap();
|
||||||
|
let cap = s
|
||||||
|
.add_account("3000", "Capital", AccountType::Equity, None, false)
|
||||||
|
.unwrap();
|
||||||
|
let e = s
|
||||||
|
.create_entry(
|
||||||
|
chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(),
|
||||||
|
"Start",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap();
|
||||||
|
s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap();
|
||||||
|
s.post_entry(e).unwrap();
|
||||||
|
s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None)
|
||||||
|
.unwrap();
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
fn more(s: &mut Store, n: usize) {
|
||||||
|
s.add_account(
|
||||||
|
&format!("{}", 6000 + n),
|
||||||
|
&format!("Expense {n}"),
|
||||||
|
AccountType::Expense,
|
||||||
|
None,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
s.attach_receipt(
|
||||||
|
None,
|
||||||
|
&format!("f{n}.txt"),
|
||||||
|
"text/plain",
|
||||||
|
format!("receipt number {n}").as_bytes(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cut(dir: &Path, s: &Store) -> Cut {
|
||||||
|
Cut::take("acme", dir, s.head()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plain(folder: &Path) -> Destination {
|
||||||
|
Destination {
|
||||||
|
folder: folder.to_path_buf(),
|
||||||
|
key: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_of(disk: &Path) -> PathBuf {
|
||||||
|
disk.join("wanderbooks-acme")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||||
|
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||||
|
for e in std::fs::read_dir(dir).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
if p.is_dir() {
|
||||||
|
walk(base, &p, out);
|
||||||
|
} else {
|
||||||
|
let rel = p
|
||||||
|
.strip_prefix(base)
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.replace('\\', "/");
|
||||||
|
out.insert(rel, std::fs::read(&p).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
if root.is_dir() {
|
||||||
|
walk(root, root, &mut out);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_tree(from: &Path, to: &Path) {
|
||||||
|
std::fs::create_dir_all(to).unwrap();
|
||||||
|
for e in std::fs::read_dir(from).unwrap() {
|
||||||
|
let e = e.unwrap();
|
||||||
|
let (src, dst) = (e.path(), to.join(e.file_name()));
|
||||||
|
if src.is_dir() {
|
||||||
|
copy_tree(&src, &dst);
|
||||||
|
} else {
|
||||||
|
std::fs::copy(&src, &dst).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Flip one byte in the middle of a file, as a bad sector or a bad sync
|
||||||
|
/// would; the file keeps its length.
|
||||||
|
fn flip(path: &Path) {
|
||||||
|
let mut bytes = std::fs::read(path).unwrap();
|
||||||
|
let at = bytes.len() / 2;
|
||||||
|
bytes[at] ^= 0x55;
|
||||||
|
std::fs::write(path, bytes).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The manifest `n` of the set, as JSON.
|
||||||
|
fn manifest(set: &Path, n: u64) -> serde_json::Value {
|
||||||
|
let text = std::fs::read_to_string(set.join(format!("manifests/{n:06}.json"))).unwrap();
|
||||||
|
serde_json::from_str(text.lines().next().unwrap()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The newest journal segment a manifest names (the one its backup added).
|
||||||
|
fn newest_journal_segment(set: &Path, n: u64) -> String {
|
||||||
|
manifest(set, n)["journal"]["segments"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.last()
|
||||||
|
.unwrap()["file"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sha(bytes: &[u8]) -> String {
|
||||||
|
hex::encode(Sha256::digest(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_damaged_segment_is_found_by_the_next_backup_and_the_drill_does_not_hide_it() {
|
||||||
|
// The reviewer's sequence: a byte flips in the segment backup 2 wrote;
|
||||||
|
// backups go on; a drill runs; a restore is made. Before: every later
|
||||||
|
// backup reused the damaged segment and was recorded good, the drill
|
||||||
|
// proved backup 1 and said ok, and a restore returned books from long
|
||||||
|
// ago.
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let first_head = s.head();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
more(&mut s, 1);
|
||||||
|
let w2 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(w2.number, 2);
|
||||||
|
assert!(w2.repaired.is_empty());
|
||||||
|
let seg = newest_journal_segment(&set_of(&disk), 2);
|
||||||
|
let damaged = set_of(&disk).join(&seg);
|
||||||
|
flip(&damaged);
|
||||||
|
let flipped = std::fs::read(&damaged).unwrap();
|
||||||
|
|
||||||
|
// The very next backup finds it (its proof re-hashes every journal
|
||||||
|
// segment its manifest names) and writes the piece again beside it.
|
||||||
|
more(&mut s, 2);
|
||||||
|
let w3 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(w3.new);
|
||||||
|
assert_eq!(w3.repaired, vec![seg.clone()], "{w3:?}");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(&damaged).unwrap(),
|
||||||
|
flipped,
|
||||||
|
"the damaged file is left exactly where it is"
|
||||||
|
);
|
||||||
|
let again = set_of(&disk).join(format!("{seg}.g1"));
|
||||||
|
assert!(
|
||||||
|
again.is_file(),
|
||||||
|
"the piece is written again as generation 1"
|
||||||
|
);
|
||||||
|
assert_eq!(sha(&std::fs::read(&again).unwrap()), {
|
||||||
|
let m = manifest(&set_of(&disk), 2);
|
||||||
|
m["journal"]["segments"].as_array().unwrap().last().unwrap()["sha256"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
});
|
||||||
|
|
||||||
|
// Many more backups: none reuses the damaged file, none finds more.
|
||||||
|
for n in 3..8 {
|
||||||
|
more(&mut s, n);
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(w.new && w.repaired.is_empty(), "{n}: {w:?}");
|
||||||
|
}
|
||||||
|
let last = s.head();
|
||||||
|
// The drill proves the newest backup, which reaches the live head.
|
||||||
|
let got = drill(
|
||||||
|
&plain(&disk),
|
||||||
|
"acme",
|
||||||
|
&b.join("journal.jsonl"),
|
||||||
|
&dir.path().join("drill"),
|
||||||
|
Some(&last),
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(got, last);
|
||||||
|
// A restore gives the newest books, not backup 1's.
|
||||||
|
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||||
|
let v = verify_found(&found, &dir.path().join("restore"), &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(v.head, last);
|
||||||
|
assert_ne!(v.head, first_head);
|
||||||
|
assert_eq!(v.passed_over, 0);
|
||||||
|
// Manifests 1, 2, 3, the repair's (4) and the five after it.
|
||||||
|
assert_eq!(v.number, 9);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_drill_never_passes_on_an_older_backup() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
more(&mut s, 1);
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let second_head = s.head();
|
||||||
|
more(&mut s, 2);
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let newest_head = s.head();
|
||||||
|
// The newest backup's own segment is damaged after it was made, and no
|
||||||
|
// backup comes after it to find that.
|
||||||
|
flip(&set_of(&disk).join(newest_journal_segment(&set_of(&disk), 3)));
|
||||||
|
|
||||||
|
// The drill is a failure that says so, with the date of the older one.
|
||||||
|
let err = drill(
|
||||||
|
&plain(&disk),
|
||||||
|
"acme",
|
||||||
|
&b.join("journal.jsonl"),
|
||||||
|
&dir.path().join("drill"),
|
||||||
|
Some(&newest_head),
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
let words = err.to_string();
|
||||||
|
match &err {
|
||||||
|
BackupError::NewestDamaged {
|
||||||
|
number,
|
||||||
|
older_from,
|
||||||
|
newest_from,
|
||||||
|
} => {
|
||||||
|
assert_eq!(*number, 3);
|
||||||
|
assert!(older_from.is_some() && newest_from.is_some(), "{err:?}");
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
assert!(words.contains("the newest backup (number 3"), "{words}");
|
||||||
|
assert!(words.contains("is damaged; an older one from "), "{words}");
|
||||||
|
assert!(!dir.path().join("drill").exists());
|
||||||
|
|
||||||
|
// A restore passes over it, and the preview can say so: both dates and
|
||||||
|
// how many it passes over.
|
||||||
|
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||||
|
let v = verify_found(&found, &dir.path().join("restore"), &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(v.number, 2);
|
||||||
|
assert_eq!(v.head, second_head);
|
||||||
|
assert_eq!(v.passed_over, 1);
|
||||||
|
assert!(v.newest_written.is_some() && !v.written.is_empty());
|
||||||
|
|
||||||
|
// Everything damaged: no older one proves whole either, and it says so.
|
||||||
|
for n in [1u64, 2] {
|
||||||
|
flip(&set_of(&disk).join(newest_journal_segment(&set_of(&disk), n)));
|
||||||
|
}
|
||||||
|
let err = drill(
|
||||||
|
&plain(&disk),
|
||||||
|
"acme",
|
||||||
|
&b.join("journal.jsonl"),
|
||||||
|
&dir.path().join("drill2"),
|
||||||
|
None,
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("no older one proves whole either"),
|
||||||
|
"{err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_drill_needs_the_newest_backup_to_reach_the_last_one_recorded_good() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let have = s.head();
|
||||||
|
more(&mut s, 1);
|
||||||
|
let recorded = s.head();
|
||||||
|
// A backup was recorded good through `recorded`, but the folder's
|
||||||
|
// newest stops at `have` (a manifest lost to a sync conflict, say).
|
||||||
|
let err = drill(
|
||||||
|
&plain(&disk),
|
||||||
|
"acme",
|
||||||
|
&b.join("journal.jsonl"),
|
||||||
|
&dir.path().join("d"),
|
||||||
|
Some(&recorded),
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(
|
||||||
|
err.to_string()
|
||||||
|
.contains("a backup that was made is not there"),
|
||||||
|
"{err}"
|
||||||
|
);
|
||||||
|
// The same head with another hash is no better.
|
||||||
|
let other = (have.0, "0".repeat(64));
|
||||||
|
assert!(
|
||||||
|
drill(
|
||||||
|
&plain(&disk),
|
||||||
|
"acme",
|
||||||
|
&b.join("journal.jsonl"),
|
||||||
|
&dir.path().join("d"),
|
||||||
|
Some(&other),
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
// And it passes when it reaches what was recorded.
|
||||||
|
assert_eq!(
|
||||||
|
drill(
|
||||||
|
&plain(&disk),
|
||||||
|
"acme",
|
||||||
|
&b.join("journal.jsonl"),
|
||||||
|
&dir.path().join("d"),
|
||||||
|
Some(&have),
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
have
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_damaged_stored_file_is_found_by_the_rotation_and_the_next_backup_repairs_it() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
// Stored files, until one is in the share backup number 2 re-reads
|
||||||
|
// (the share a file belongs to is its hash's first four digits modulo
|
||||||
|
// 16: every stored file is re-read within 16 backups).
|
||||||
|
let mut chosen: Option<(String, Vec<u8>)> = None;
|
||||||
|
for n in 0..400 {
|
||||||
|
let bytes = format!("a stored file, number {n}").into_bytes();
|
||||||
|
s.attach_receipt(None, &format!("s{n}.txt"), "text/plain", &bytes, None)
|
||||||
|
.unwrap();
|
||||||
|
let h = sha(&bytes);
|
||||||
|
if chosen.is_none() && u64::from_str_radix(&h[..4], 16).unwrap() % 16 == 2 {
|
||||||
|
chosen = Some((h, bytes));
|
||||||
|
}
|
||||||
|
if chosen.is_some() && n > 5 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (h, bytes) = chosen.expect("some file is in the share");
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let rel = format!("files/{}/{h}", &h[..2]);
|
||||||
|
let piece = set_of(&disk).join(&rel);
|
||||||
|
flip(&piece);
|
||||||
|
let flipped = std::fs::read(&piece).unwrap();
|
||||||
|
more(&mut s, 1);
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(w.number, 2);
|
||||||
|
assert_eq!(w.repaired, vec![rel.clone()], "{w:?}");
|
||||||
|
assert_eq!(std::fs::read(&piece).unwrap(), flipped, "left where it is");
|
||||||
|
let again = set_of(&disk).join(format!("{rel}.g1"));
|
||||||
|
assert_eq!(std::fs::read(&again).unwrap(), bytes);
|
||||||
|
// Every manifest of the set restores with the file whole (the reader
|
||||||
|
// takes the generation that hashes right).
|
||||||
|
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||||
|
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(v.passed_over, 0);
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
let restored = v.tree.join("blobs").join(&h[..2]).join(&h[2..4]).join(&h);
|
||||||
|
assert_eq!(std::fs::read(restored).unwrap(), bytes);
|
||||||
|
// And the next backup carries on without finding it again.
|
||||||
|
more(&mut s, 2);
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(w.new && w.repaired.is_empty(), "{w:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_piece_damaged_as_it_is_written_is_repaired_in_the_same_backup() {
|
||||||
|
// A piece that is there under its name but is not what its name says
|
||||||
|
// (a copy that died half way on a disk that takes no links, a bad
|
||||||
|
// sector) is taken as the piece by a put; the proof finds it.
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let set = set_of(&disk);
|
||||||
|
let flipped_once = Arc::new(Mutex::new(false));
|
||||||
|
let ctx = {
|
||||||
|
let (set, done) = (set.clone(), flipped_once.clone());
|
||||||
|
Ctx::new().with_faults(Arc::new(move |kind, rel| {
|
||||||
|
if kind == "published" && rel.starts_with("files/") {
|
||||||
|
let mut d = done.lock().unwrap();
|
||||||
|
if !*d {
|
||||||
|
flip(&set.join(rel));
|
||||||
|
*d = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap();
|
||||||
|
assert!(w.new);
|
||||||
|
assert_eq!(w.repaired.len(), 1, "{w:?}");
|
||||||
|
assert!(set.join(format!("{}.g1", w.repaired[0])).is_file());
|
||||||
|
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||||
|
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_damaged_vault_record_and_an_index_segment_are_written_again_too() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let vault_bytes = b"a sealed vault record".to_vec();
|
||||||
|
std::fs::create_dir_all(b.join("vault")).unwrap();
|
||||||
|
std::fs::write(b.join("vault").join("tin-1.bin"), &vault_bytes).unwrap();
|
||||||
|
std::fs::create_dir_all(b.join("keys")).unwrap();
|
||||||
|
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let set = set_of(&disk);
|
||||||
|
flip(&set.join(format!("vault/{}", sha(&vault_bytes))));
|
||||||
|
let index = manifest(&set, 1)["files"]["segments"][0]["file"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.to_string();
|
||||||
|
flip(&set.join(&index));
|
||||||
|
more(&mut s, 1);
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(w.new, "{w:?}");
|
||||||
|
assert_eq!(w.repaired.len(), 2, "{w:?}");
|
||||||
|
// The newest manifest names the new generations; the restore proves.
|
||||||
|
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||||
|
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(v.head, s.head());
|
||||||
|
assert_eq!(v.passed_over, 0);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(v.tree.join("vault").join("tin-1.bin")).unwrap(),
|
||||||
|
vault_bytes
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn books_behind_the_destination_are_ahead_and_other_books_are_diverged() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (b, old, other) = (
|
||||||
|
dir.path().join("book"),
|
||||||
|
dir.path().join("old"),
|
||||||
|
dir.path().join("other"),
|
||||||
|
);
|
||||||
|
let mut s = book(&b);
|
||||||
|
// The books as they were: a copy of the folder at this point.
|
||||||
|
copy_tree(&b, &old);
|
||||||
|
more(&mut s, 1);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let before = tree(&disk);
|
||||||
|
|
||||||
|
// Restored from an older backup: the live journal is the beginning of
|
||||||
|
// the destination's. That is ahead, and the words say what to do.
|
||||||
|
let old_store = Store::open(&old).unwrap();
|
||||||
|
let err = write_destination(
|
||||||
|
&plain(&disk),
|
||||||
|
&Cut::take("acme", &old, old_store.head()).unwrap(),
|
||||||
|
true,
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(err, BackupError::Ahead(..)), "{err:?}");
|
||||||
|
let words = err.to_string();
|
||||||
|
assert!(words.contains("a longer history of these books"), "{words}");
|
||||||
|
assert!(words.contains("start a new backup set"), "{words}");
|
||||||
|
assert_eq!(tree(&disk), before, "nothing was written");
|
||||||
|
|
||||||
|
// Another history under the same id is diverged, said as such (not
|
||||||
|
// ahead, whichever is longer).
|
||||||
|
let other_store = book(&other);
|
||||||
|
let err = write_destination(
|
||||||
|
&plain(&disk),
|
||||||
|
&Cut::take("acme", &other, other_store.head()).unwrap(),
|
||||||
|
true,
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(err, BackupError::Elsewhere);
|
||||||
|
assert!(err.to_string().contains("diverged"), "{err}");
|
||||||
|
let mut longer = other_store;
|
||||||
|
for n in 0..4 {
|
||||||
|
more(&mut longer, n);
|
||||||
|
}
|
||||||
|
let err = write_destination(
|
||||||
|
&plain(&disk),
|
||||||
|
&Cut::take("acme", &other, longer.head()).unwrap(),
|
||||||
|
true,
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(err, BackupError::Elsewhere);
|
||||||
|
assert_eq!(tree(&disk), before);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_new_set_begins_beside_the_old_at_the_persons_request_and_the_old_is_never_touched() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (b, old) = (dir.path().join("book"), dir.path().join("old"));
|
||||||
|
let mut s = book(&b);
|
||||||
|
copy_tree(&b, &old);
|
||||||
|
more(&mut s, 1);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
let before = tree(&disk);
|
||||||
|
let mut old_store = Store::open(&old).unwrap();
|
||||||
|
let old_cut = Cut::take("acme", &old, old_store.head()).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
write_destination(&plain(&disk), &old_cut, true, &Ctx::new()),
|
||||||
|
Err(BackupError::Ahead(..))
|
||||||
|
));
|
||||||
|
|
||||||
|
// At the person's request: a new set, `.2`, beside it.
|
||||||
|
let w = write_destination_with(
|
||||||
|
&plain(&disk),
|
||||||
|
&old_cut,
|
||||||
|
Options {
|
||||||
|
may_create: true,
|
||||||
|
new_set: true,
|
||||||
|
},
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!((w.number, w.new), (1, true));
|
||||||
|
assert!(
|
||||||
|
disk.join("wanderbooks-acme.2/manifests/000001.json")
|
||||||
|
.is_file()
|
||||||
|
);
|
||||||
|
let after = tree(&disk);
|
||||||
|
for (name, bytes) in &before {
|
||||||
|
assert_eq!(
|
||||||
|
after.get(name),
|
||||||
|
Some(bytes),
|
||||||
|
"{name}: the old set is untouched"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The next ordinary backup goes to the new set, which grows; the old
|
||||||
|
// one stays as it was.
|
||||||
|
more(&mut old_store, 9);
|
||||||
|
let w = write_destination(
|
||||||
|
&plain(&disk),
|
||||||
|
&Cut::take("acme", &old, old_store.head()).unwrap(),
|
||||||
|
true,
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(w.number, 2);
|
||||||
|
assert!(
|
||||||
|
disk.join("wanderbooks-acme.2/manifests/000002.json")
|
||||||
|
.is_file()
|
||||||
|
);
|
||||||
|
let after = tree(&disk);
|
||||||
|
for (name, bytes) in &before {
|
||||||
|
assert_eq!(after.get(name), Some(bytes), "{name}");
|
||||||
|
}
|
||||||
|
// A drill takes the newest set too.
|
||||||
|
assert_eq!(
|
||||||
|
drill(
|
||||||
|
&plain(&disk),
|
||||||
|
"acme",
|
||||||
|
&old.join("journal.jsonl"),
|
||||||
|
&dir.path().join("d"),
|
||||||
|
Some(&old_store.head()),
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
old_store.head()
|
||||||
|
);
|
||||||
|
// The folder now holds two sets of the same books: a restore from it
|
||||||
|
// asks which (the sets are listed with their dates), never guesses.
|
||||||
|
assert!(matches!(
|
||||||
|
find(&disk, None, &Ctx::new()),
|
||||||
|
Err(BackupError::Several(_))
|
||||||
|
));
|
||||||
|
let listed = ledger_store::backup::list(&disk);
|
||||||
|
assert_eq!(listed.len(), 2);
|
||||||
|
assert!(
|
||||||
|
listed
|
||||||
|
.iter()
|
||||||
|
.all(|c| c.through_seq.is_some() && c.written.is_some())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_set_folder_is_a_legal_name_whatever_the_books_are_called() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
for id in ["con", "nul", "aux", "prn", "com1", "lpt9"] {
|
||||||
|
let b = dir.path().join(format!("book-{id}"));
|
||||||
|
let s = book(&b);
|
||||||
|
write_destination(
|
||||||
|
&plain(&disk),
|
||||||
|
&Cut::take(id, &b, s.head()).unwrap(),
|
||||||
|
true,
|
||||||
|
&Ctx::new(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
disk.join(format!("wanderbooks-{id}/manifests/000001.json"))
|
||||||
|
.is_file(),
|
||||||
|
"{id}"
|
||||||
|
);
|
||||||
|
assert!(!disk.join(id).exists(), "{id}: no reserved name is made");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_newest_backup_is_tried_in_the_good_case() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
for n in 0..6 {
|
||||||
|
more(&mut s, n);
|
||||||
|
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
}
|
||||||
|
// Each backup added one segment, and each manifest names only its own.
|
||||||
|
let segments: usize = (1..=6)
|
||||||
|
.map(|n| {
|
||||||
|
manifest(&set_of(&disk), n)["journal"]["segments"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.len()
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
assert_eq!(segments, 6);
|
||||||
|
let probes = Arc::new(Mutex::new(0usize));
|
||||||
|
let ctx = {
|
||||||
|
let probes = probes.clone();
|
||||||
|
Ctx::new().with_trace(Arc::new(move |kind, rel| {
|
||||||
|
if kind == "len" && rel.starts_with("journal/") {
|
||||||
|
*probes.lock().unwrap() += 1;
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
let found = find(&disk, None, &ctx).unwrap();
|
||||||
|
let v = verify_found(&found, &dir.path().join("v"), &ctx).unwrap();
|
||||||
|
assert_eq!(v.number, 6);
|
||||||
|
// One look at each journal segment of the newest manifest to find the
|
||||||
|
// set's book, one to prove it: never the segments of the five older
|
||||||
|
// manifests, which reading every manifest first would have measured
|
||||||
|
// too (1 + 2 + ... + 6 more).
|
||||||
|
assert_eq!(*probes.lock().unwrap(), 2 * segments);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_backup_cut_while_the_vault_is_being_written_restores_a_vault_that_matches_the_journal() {
|
||||||
|
// ledger-vault stages a record as `NAME.staged-TAG` and sets the old one
|
||||||
|
// aside as `NAME.purging-TAG` while a call is between its first step and
|
||||||
|
// its last. A backup taken then must hold the vault as the journal says
|
||||||
|
// it is: the staged record is not the books' yet, and the set-aside one
|
||||||
|
// still is.
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let mut s = book(&b);
|
||||||
|
let record = b"sealed tin record, party one".to_vec();
|
||||||
|
let party = s.add_party("Mo", &[Role::Member]).unwrap();
|
||||||
|
s.set_party_tin(
|
||||||
|
party,
|
||||||
|
Some(TinFacts {
|
||||||
|
tin_type: TinType::Ssn,
|
||||||
|
last4: "4915".into(),
|
||||||
|
vault_record: Some(sha(&record)),
|
||||||
|
purged: None,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::create_dir_all(b.join("vault")).unwrap();
|
||||||
|
std::fs::create_dir_all(b.join("keys")).unwrap();
|
||||||
|
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
|
||||||
|
// The purge of party 1's record is staged: set aside, not yet journaled.
|
||||||
|
let tag = "0123456789abcdef";
|
||||||
|
std::fs::write(
|
||||||
|
b.join("vault").join(format!("tin-1.purging-{tag}")),
|
||||||
|
&record,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
// And a new record for party 2 is staged, not the books'.
|
||||||
|
std::fs::write(
|
||||||
|
b.join("vault").join(format!("tin-2.staged-{tag}")),
|
||||||
|
b"staged, not committed",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(w.new && w.repaired.is_empty(), "{w:?}");
|
||||||
|
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||||
|
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
|
||||||
|
let held: Vec<String> = std::fs::read_dir(v.tree.join("vault"))
|
||||||
|
.unwrap()
|
||||||
|
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(held, vec!["tin-1.bin".to_string()], "{held:?}");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(v.tree.join("vault").join("tin-1.bin")).unwrap(),
|
||||||
|
record
|
||||||
|
);
|
||||||
|
// No scratch name of the vault is anywhere in the destination.
|
||||||
|
assert!(
|
||||||
|
!tree(&disk)
|
||||||
|
.keys()
|
||||||
|
.any(|n| n.contains(".staged-") || n.contains(".purging-"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_proof_cut_short_by_a_close_ends_cleanly_and_is_made_again_by_the_next_backup() {
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let b = dir.path().join("book");
|
||||||
|
let s = book(&b);
|
||||||
|
let disk = dir.path().join("disk");
|
||||||
|
std::fs::create_dir(&disk).unwrap();
|
||||||
|
// The books close while the backup's proof is under way (here: as it
|
||||||
|
// replays the chain).
|
||||||
|
let stop = Arc::new(AtomicBool::new(false));
|
||||||
|
let ctx = {
|
||||||
|
let stop = stop.clone();
|
||||||
|
Ctx::new()
|
||||||
|
.with_stop(stop.clone())
|
||||||
|
.with_phase_watch(Arc::new(move |p: &str| {
|
||||||
|
if p == "replay" {
|
||||||
|
stop.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
let err = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap_err();
|
||||||
|
assert!(matches!(err, BackupError::Cancelled(_)), "{err:?}");
|
||||||
|
// Nothing of the proof is left behind in the books' folder, and the
|
||||||
|
// manifest that was written is there but is not marked proven.
|
||||||
|
let left: Vec<_> = std::fs::read_dir(b.join("ops"))
|
||||||
|
.map(|d| {
|
||||||
|
d.flatten()
|
||||||
|
.filter(|e| e.file_name().to_string_lossy().starts_with("proof-"))
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
assert!(left.is_empty(), "scratch books left: {left:?}");
|
||||||
|
let set = set_of(&disk);
|
||||||
|
assert!(set.join("manifests/000001.json").is_file());
|
||||||
|
assert!(!set.join("proofs/000001").exists());
|
||||||
|
// The next backup has nothing new to write, and still proves it: it
|
||||||
|
// never says good of a backup that was not proven.
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert_eq!(w.number, 1);
|
||||||
|
assert!(!w.new, "{w:?}");
|
||||||
|
assert!(set.join("proofs/000001").is_file());
|
||||||
|
// Once proven, a backup with nothing new is only looked at.
|
||||||
|
let before = tree(&disk);
|
||||||
|
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||||
|
assert!(!w.new);
|
||||||
|
assert_eq!(tree(&disk), before);
|
||||||
|
}
|
||||||
@@ -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!(
|
||||||
|
|||||||
+6
-12
@@ -104,17 +104,11 @@ and `IPAddressDeny=any` with `IPAddressAllow=localhost`, and no seccomp or
|
|||||||
Landlock lines (D-32, D-51).
|
Landlock lines (D-32, D-51).
|
||||||
|
|
||||||
The loopback-only rule is deliberate: the server reaches nothing out. A
|
The loopback-only rule is deliberate: the server reaches nothing out. A
|
||||||
book whose backup target is a **remote** git repository needs that host
|
backup is a folder of plain files (docs/backups.md): a folder on this
|
||||||
allowed, or its backups fail:
|
machine's disks needs nothing, and nothing else is installed for it. (A
|
||||||
|
folder on a network share the machine mounts is a disk to the server, and
|
||||||
```ini
|
the mount, not the server, reaches the network.) The tunnel and Caddy run as
|
||||||
# /etc/systemd/system/wanderbooks-server.service.d/backup.conf
|
their own services and reach 127.0.0.1:7411, which the rule allows.
|
||||||
[Service]
|
|
||||||
IPAddressAllow=203.0.113.10
|
|
||||||
```
|
|
||||||
|
|
||||||
A backup to a folder on this machine needs nothing. The tunnel and Caddy
|
|
||||||
run as their own services and reach 127.0.0.1:7411, which the rule allows.
|
|
||||||
|
|
||||||
## 5. A token for each client
|
## 5. A token for each client
|
||||||
|
|
||||||
@@ -221,7 +215,7 @@ a last backup and closes (3.9), so `TimeoutStopSec=600` is generous rather
|
|||||||
than needed.
|
than needed.
|
||||||
|
|
||||||
Backups still run on their own, from the books' settings, as on the
|
Backups still run on their own, from the books' settings, as on the
|
||||||
desktop (3.7, D-30, D-31); this machine runs git itself.
|
desktop (3.7, D-91): plain files in a folder, written by the server.
|
||||||
|
|
||||||
## 9. Prove the boundary (what CI runs)
|
## 9. Prove the boundary (what CI runs)
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ pkgdesc="Double-entry bookkeeping your agent keeps and you can read"
|
|||||||
arch=('x86_64')
|
arch=('x86_64')
|
||||||
url="https://wanderbooks.ai"
|
url="https://wanderbooks.ai"
|
||||||
license=('MIT' 'Apache-2.0')
|
license=('MIT' 'Apache-2.0')
|
||||||
depends=('gcc-libs' 'glibc' 'git')
|
depends=('gcc-libs' 'glibc')
|
||||||
provides=('wanderbooks')
|
provides=('wanderbooks')
|
||||||
conflicts=('wanderbooks')
|
conflicts=('wanderbooks')
|
||||||
options=('!lto' '!strip')
|
options=('!lto' '!strip')
|
||||||
|
|||||||
@@ -5,13 +5,13 @@
|
|||||||
The app is signed with the hardened runtime (codesign --options
|
The app is signed with the hardened runtime (codesign --options
|
||||||
runtime), which Apple's notarization requires. It is NOT sandboxed
|
runtime), which Apple's notarization requires. It is NOT sandboxed
|
||||||
(the App Sandbox would forbid what the product is: it starts a copy of
|
(the App Sandbox would forbid what the product is: it starts a copy of
|
||||||
itself as the books server, runs the system's git for backups, and
|
itself as the books server, and
|
||||||
reads and writes the person's data folder and the folders they pick
|
reads and writes the person's data folder and the folders they pick
|
||||||
for backups). Outside the sandbox, none of that needs an entitlement:
|
for backups). Outside the sandbox, none of that needs an entitlement:
|
||||||
|
|
||||||
* starting itself as a child process and git as another: none;
|
* starting itself as a child process: none;
|
||||||
* outgoing network connections (the relay, the update look, a git
|
* outgoing network connections (the relay, the update look): none
|
||||||
remote): none (com.apple.security.network.client is a SANDBOX
|
(com.apple.security.network.client is a SANDBOX
|
||||||
entitlement);
|
entitlement);
|
||||||
* reading and writing its data folder, Application Support/wanderbooks:
|
* reading and writing its data folder, Application Support/wanderbooks:
|
||||||
none (the Documents folder is a privacy prompt, answered by
|
none (the Documents folder is a privacy prompt, answered by
|
||||||
|
|||||||
@@ -24,9 +24,8 @@ section = "utils"
|
|||||||
# A deb marks itself package-managed: `wanderbooks update` refuses on it
|
# A deb marks itself package-managed: `wanderbooks update` refuses on it
|
||||||
# and says to use apt (plan 3.9).
|
# and says to use apt (plan 3.9).
|
||||||
desktop-template = "deploy/packaging/wanderbooks.desktop"
|
desktop-template = "deploy/packaging/wanderbooks.desktop"
|
||||||
# git: the backups run the system's git (WB-pkg-4); the package manager
|
# Backups need nothing installed (WB-pkg-4): they are plain files.
|
||||||
# fetches it, so a Linux person never sees the missing-git words.
|
depends = ["libc6", "libgcc-s1"]
|
||||||
depends = ["libc6", "libgcc-s1", "git"]
|
|
||||||
|
|
||||||
[deb.files]
|
[deb.files]
|
||||||
"deploy/packaging/install-method-deb" = "usr/share/wanderbooks/install-method"
|
"deploy/packaging/install-method-deb" = "usr/share/wanderbooks/install-method"
|
||||||
@@ -42,7 +41,7 @@ depends = ["libc6", "libgcc-s1", "git"]
|
|||||||
"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE"
|
"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE"
|
||||||
|
|
||||||
[pacman]
|
[pacman]
|
||||||
depends = ["gcc-libs", "glibc", "git"]
|
depends = ["gcc-libs", "glibc"]
|
||||||
|
|
||||||
[pacman.files]
|
[pacman.files]
|
||||||
"deploy/packaging/install-method-aur" = "usr/share/wanderbooks/install-method"
|
"deploy/packaging/install-method-aur" = "usr/share/wanderbooks/install-method"
|
||||||
|
|||||||
@@ -50,9 +50,8 @@ ProtectHome=yes
|
|||||||
PrivateTmp=yes
|
PrivateTmp=yes
|
||||||
PrivateDevices=yes
|
PrivateDevices=yes
|
||||||
# No network but loopback: the tunnel reaches 127.0.0.1:7411, and the
|
# No network but loopback: the tunnel reaches 127.0.0.1:7411, and the
|
||||||
# server reaches nothing out. A book whose backup target is a remote git
|
# server reaches nothing out. Backups go to a folder on this machine's
|
||||||
# repository needs that host allowed here (`IPAddressAllow=` its address)
|
# disks (see README.md), so they need no network.
|
||||||
# or its backups fail; see README.md.
|
|
||||||
IPAddressDeny=any
|
IPAddressDeny=any
|
||||||
IPAddressAllow=localhost
|
IPAddressAllow=localhost
|
||||||
|
|
||||||
|
|||||||
@@ -487,9 +487,8 @@ already running with other flags keeps them; on a self-host machine
|
|||||||
`serve` is the unit's only holder.
|
`serve` is the unit's only holder.
|
||||||
|
|
||||||
The unit sets `IPAddressDeny=any` and `IPAddressAllow=localhost`: the
|
The unit sets `IPAddressDeny=any` and `IPAddressAllow=localhost`: the
|
||||||
server reaches nothing out. A book whose backup target is a remote git
|
server reaches nothing out. Backups go to a folder on the machine's own
|
||||||
repository therefore needs that host allowed in a drop-in (D-31 backups
|
disks and need no network (D-91). The recipe, the head check for the move and the
|
||||||
still run on the server). The recipe, the head check for the move and the
|
|
||||||
two-account CI job are in `deploy/README.md`, `deploy/wanderbooks-server.service`
|
two-account CI job are in `deploy/README.md`, `deploy/wanderbooks-server.service`
|
||||||
and `.github/workflows/two-user.yml`; the checks are
|
and `.github/workflows/two-user.yml`; the checks are
|
||||||
`crates/ledger-cli/tests/two_user.rs`.
|
`crates/ledger-cli/tests/two_user.rs`.
|
||||||
|
|||||||
+164
@@ -0,0 +1,164 @@
|
|||||||
|
# Backups
|
||||||
|
|
||||||
|
A backup of your books is an ordinary folder of ordinary files. Nothing needs
|
||||||
|
to be installed to make one or to read one back, and you never need to know how
|
||||||
|
it works. This page says where it is, what is in it, and how to get your books
|
||||||
|
back, on this computer, on a new one, or from a backup an older version made.
|
||||||
|
|
||||||
|
## Where it is
|
||||||
|
|
||||||
|
You choose the folder once (in the window: **Back up to...**): another disk, a
|
||||||
|
USB drive, a folder on your network, or a folder your cloud drive keeps in sync
|
||||||
|
(Dropbox, iCloud Drive, OneDrive, Google Drive). Your books then back
|
||||||
|
themselves up a little after each change, when they open and before they
|
||||||
|
close; **Back up now** does it at once. Every backup is read back and checked
|
||||||
|
before it is counted as good. A backup that is more than a day behind is
|
||||||
|
flagged, and once a week your books prove they can be restored from it: the
|
||||||
|
newest backup, in full. If the newest backup is damaged, that check fails and
|
||||||
|
says so, even when an older backup is still whole.
|
||||||
|
|
||||||
|
**If the folder is kept in sync by Dropbox, iCloud Drive, OneDrive, Google
|
||||||
|
Drive or the like:** use that folder from one computer only (two computers
|
||||||
|
backing up into one synced folder can overwrite each other's work; a second
|
||||||
|
computer needs a folder of its own), and keep it available offline, not online
|
||||||
|
only. A file that is online only and not yet on this computer reads as "not
|
||||||
|
downloaded yet", never as damage: the backup waits, and nothing is written
|
||||||
|
over it. The set-up and the Backups window say this too.
|
||||||
|
|
||||||
|
## What is in it
|
||||||
|
|
||||||
|
One folder for your books, inside the folder you chose:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Backups/ the folder you chose
|
||||||
|
wanderbooks-acme/ your books (wanderbooks- and the name you gave them)
|
||||||
|
READ-ME.txt a few words about the folder
|
||||||
|
manifests/
|
||||||
|
000001.json one per backup that changed something
|
||||||
|
000002.json
|
||||||
|
proofs/000001 a mark that a backup was read back and proven
|
||||||
|
journal/000001-..., 000002-... the journal, in pieces
|
||||||
|
access/000001-... who reached the books, in pieces
|
||||||
|
files-index/000001-... which receipts and files there are
|
||||||
|
files/ab/abcdef... each receipt or file, once
|
||||||
|
vault/... keys/... your tax-ID vault and its key
|
||||||
|
```
|
||||||
|
|
||||||
|
Files are only ever **added**. Nothing in the folder is changed or deleted by
|
||||||
|
Wanderbooks, so a sync service never sees a file change under it, and an earlier
|
||||||
|
state of your books is always still there. A backup counts as complete only
|
||||||
|
when its small manifest file is in place, written last; an interrupted backup
|
||||||
|
leaves a few unused files and the last complete backup is still whole. A
|
||||||
|
manifest lists the one before it and what is new, and one in sixty-four lists
|
||||||
|
everything again, so a folder of thousands of backups stays small (3,000 backups
|
||||||
|
took 12 MB of manifests, the newest 0.8 KB). Two computers backing up to one
|
||||||
|
folder cannot damage it either: whichever writes the next manifest first wins,
|
||||||
|
and the other goes on from there (but see above: one computer per synced
|
||||||
|
folder).
|
||||||
|
|
||||||
|
**What "backed up" means.** After each backup Wanderbooks reads the new manifest
|
||||||
|
back from the folder and checks it: every piece of the journal and the access
|
||||||
|
log is read again and its checksum checked, the journal's chain is replayed to
|
||||||
|
its end, your books are opened from it, the vault and its key are there, and the
|
||||||
|
receipts and files that backup added are read again together with a sixteenth
|
||||||
|
of the others, so **every receipt and file is read again within sixteen
|
||||||
|
backups** (the weekly check reads all of them). Only then is the backup counted
|
||||||
|
as good. If a file in the folder turns out to be damaged (a bad sector, a bad
|
||||||
|
sync), the next backup writes that file again beside it under a new name ending
|
||||||
|
`.g1`, uses the good one from then on, and the Backups window lists the damaged
|
||||||
|
file as found and written again. The damaged file stays where it is, because
|
||||||
|
Wanderbooks never deletes anything in the folder: you may delete it yourself.
|
||||||
|
|
||||||
|
**If your books are behind the folder.** If you restored your books from an
|
||||||
|
older backup (or a backup file) and then point them at the folder that holds a
|
||||||
|
longer history of them, Wanderbooks says so and writes nothing: *the backup
|
||||||
|
folder holds a longer history of these books than this computer has*. To carry
|
||||||
|
on with the books you have, choose **Start a new backup set here** in the
|
||||||
|
Backups window (or `wanderbooks books back-up ID --new-set`): a new set
|
||||||
|
(`wanderbooks-acme.2`) begins beside the old one, which stays in the folder,
|
||||||
|
untouched, and later backups go to the new one. If instead the folder holds
|
||||||
|
other books, or a history that has diverged from yours, Wanderbooks says so and
|
||||||
|
writes nothing.
|
||||||
|
|
||||||
|
**If the passphrase key is lost.** Your computer keeps the passphrase's key
|
||||||
|
privately. If that file is lost while the folder's backups are sealed,
|
||||||
|
Wanderbooks stops, writes nothing, and asks for the passphrase again in the
|
||||||
|
backup settings: it never quietly writes an unprotected copy of your books into
|
||||||
|
a folder you protected. Backups are written without protection only after you
|
||||||
|
choose **Take the passphrase off**.
|
||||||
|
|
||||||
|
If your disk is short of room, you may delete the whole folder of your books
|
||||||
|
(never parts of it) once you have another backup.
|
||||||
|
|
||||||
|
## A passphrase (optional)
|
||||||
|
|
||||||
|
When you set up backups you may protect them with a passphrase. It is off unless
|
||||||
|
you turn it on. With one, every file in the folder is sealed (XChaCha20-Poly1305;
|
||||||
|
the key comes from your passphrase through Argon2id) and the file names say
|
||||||
|
nothing about your books, only how many files there are and how big. Your
|
||||||
|
computer keeps the key privately, so backups stay automatic. **A forgotten
|
||||||
|
passphrase cannot be recovered**, by anyone: write it down somewhere safe.
|
||||||
|
On another computer, restoring asks for the passphrase.
|
||||||
|
|
||||||
|
Changing the passphrase starts a new set of sealed backups beside the old
|
||||||
|
ones, which stay as they are and stay sealed with the passphrase they were made
|
||||||
|
with. Turning it off makes later backups plain. If you want old backups gone
|
||||||
|
after a change, delete their folder yourself.
|
||||||
|
|
||||||
|
## One file instead of a folder
|
||||||
|
|
||||||
|
**Save a backup...** writes the same backup as a single file ending in
|
||||||
|
.wbbackup (a zip). Keep it, email it to yourself, or carry it on a USB stick. It
|
||||||
|
is sealed if your backups are. A file by the same name is never overwritten.
|
||||||
|
|
||||||
|
## Getting your books back
|
||||||
|
|
||||||
|
**Restore...** takes the backup folder you chose (or the folder of one set of
|
||||||
|
books inside it), or a .wbbackup file. It checks everything first and shows you
|
||||||
|
what it found: how far the books go, how many files. If the newest backup in the
|
||||||
|
folder is damaged and this restore would use an older one, the first thing it
|
||||||
|
says, in bold, is **NOT THE NEWEST BACKUP**, with how many newer backups it passes
|
||||||
|
over, when this backup was made, when the newest was, and that anything written
|
||||||
|
after this backup is not in it. Only then does it put your books back, as new
|
||||||
|
books, or in place of books with the same name (those are kept whole in a
|
||||||
|
`legacy` folder, never deleted).
|
||||||
|
|
||||||
|
On a **new computer**: install Wanderbooks, open it, choose **Restore...**, point it
|
||||||
|
at the backup folder (connect the disk or let your cloud drive finish syncing
|
||||||
|
first) or at the .wbbackup file, and give the passphrase if it asks. Then choose
|
||||||
|
a backup folder again to keep backing up.
|
||||||
|
|
||||||
|
If the disk your backups were on is not connected, Wanderbooks says so and does
|
||||||
|
not start over on another disk by itself: connect the disk, or, if it is a new
|
||||||
|
disk, say so when you back up and it begins there again.
|
||||||
|
|
||||||
|
## A backup made with an older version
|
||||||
|
|
||||||
|
Older versions kept backups differently, in a way that needed another program
|
||||||
|
called git. Wanderbooks no longer writes those or reads them, and does not touch
|
||||||
|
them: they stay exactly where they are. If you still have one and want your books
|
||||||
|
from it, you can get them back with git yourself:
|
||||||
|
|
||||||
|
1. In a terminal, make a plain folder from the old backup (it is the folder named
|
||||||
|
after your books, ending in .git, inside the folder you backed up to):
|
||||||
|
|
||||||
|
```text
|
||||||
|
git clone /path/to/backups/acme.git acme-old
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Adopt that folder as books (with your vault and its key, which the backup
|
||||||
|
also kept), and check what it says:
|
||||||
|
|
||||||
|
```text
|
||||||
|
wanderbooks books adopt acme-old --id acme --vault acme-old/vault --vault-key acme-old/keys/legacy.key
|
||||||
|
```
|
||||||
|
|
||||||
|
It copies the books in, proves them whole, and leaves the original as it was.
|
||||||
|
(If your books had a tax-ID vault you did not use, leave out the two vault
|
||||||
|
options and add `--no-vault`.)
|
||||||
|
|
||||||
|
3. Choose a backup folder for the books you got back, so new backups are made in
|
||||||
|
the new form beside the old one.
|
||||||
|
|
||||||
|
Your books still list the private repository they used to back up to; it is no
|
||||||
|
longer used, and you may clear that setting.
|
||||||
+7
-6
@@ -23,8 +23,8 @@ close the window: that quits Wanderbooks fully and closes your books.
|
|||||||
|
|
||||||
Where things are: the program is in `%LOCALAPPDATA%\Programs\Wanderbooks`; your
|
Where things are: the program is in `%LOCALAPPDATA%\Programs\Wanderbooks`; your
|
||||||
books, keys and backups are in `%LOCALAPPDATA%\wanderbooks`.
|
books, keys and backups are in `%LOCALAPPDATA%\wanderbooks`.
|
||||||
Backups need Git for Windows (https://git-scm.com/download/win, or `winget
|
Backups need nothing installed: choose a backup folder in Wanderbooks
|
||||||
install --id Git.Git -e`); without it Wanderbooks works and says so.
|
(another disk, or a folder your cloud drive keeps in sync).
|
||||||
|
|
||||||
## macOS
|
## macOS
|
||||||
|
|
||||||
@@ -38,8 +38,9 @@ install --id Git.Git -e`); without it Wanderbooks works and says so.
|
|||||||
remove it, drag it to the Trash. Neither touches your books.
|
remove it, drag it to the Trash. Neither touches your books.
|
||||||
|
|
||||||
Your books, keys and backups are in `~/Library/Application Support/wanderbooks`.
|
Your books, keys and backups are in `~/Library/Application Support/wanderbooks`.
|
||||||
Backups need git: run `xcode-select --install` in Terminal (or `brew install
|
Backups need nothing installed: choose a backup folder in Wanderbooks
|
||||||
git`).
|
(another disk, or a folder iCloud, Dropbox, OneDrive or Google Drive keeps in
|
||||||
|
sync).
|
||||||
|
|
||||||
## Linux
|
## Linux
|
||||||
|
|
||||||
@@ -48,8 +49,8 @@ Ubuntu), the `.rpm` (Fedora), the Arch package, or the AppImage (one file: mark
|
|||||||
it executable, keep it where you put it, and run it). Open **Wanderbooks** from
|
it executable, keep it where you put it, and run it). Open **Wanderbooks** from
|
||||||
the menu. To update, install the newer package, or replace the AppImage. Your
|
the menu. To update, install the newer package, or replace the AppImage. Your
|
||||||
books are in `~/.local/share/wanderbooks` and are never touched by a package.
|
books are in `~/.local/share/wanderbooks` and are never touched by a package.
|
||||||
Backups need git (`sudo apt install git`, `sudo dnf install git`,
|
Backups need nothing installed: choose a backup folder in Wanderbooks
|
||||||
`sudo pacman -S git`).
|
(another disk, or a folder your sync program keeps).
|
||||||
|
|
||||||
## After it is installed
|
## After it is installed
|
||||||
|
|
||||||
|
|||||||
+71
-78
@@ -378,27 +378,21 @@ didn't open, with why). Protocol version 1: the requests are new, the
|
|||||||
(a drill, or a format upgrade not yet journaled, is stopped when the
|
(a drill, or a format upgrade not yet journaled, is stopped when the
|
||||||
close begins, at its next look, so it never takes the last backup's
|
close begins, at its next look, so it never takes the last backup's
|
||||||
turn; its scratch clone is removed and the books are unchanged):
|
turn; its scratch clone is removed and the books are unchanged):
|
||||||
a backup still running after that is stopped (git is sent SIGTERM, which
|
a backup still running after that is stopped (its copy of files
|
||||||
makes it remove its own lock files, and killed with all it started only
|
stops at the next piece, or the next 64 KiB of one) and waited for to
|
||||||
if it hasn't ended after 5 seconds) and waited for to end. The program
|
end. The program never rewrites or deletes anything in a backup folder
|
||||||
never writes to or deletes from a backup folder (it is the owner's, and
|
(it is the owner's, and may be shared with other computers or a sync
|
||||||
may be shared with other computers or a sync program): a lock git left
|
program): a backup stopped part way leaves pieces no manifest names and
|
||||||
there when it had to be killed is left in place, recorded in
|
the folder proves whole at its previous manifest, so there is nothing to
|
||||||
`ops/backup.jsonl` as `lock_left` with its whole path, and the target's
|
clean up and nothing to remove by hand.
|
||||||
backup is marked failed with words naming the file and saying to remove
|
|
||||||
it only when nothing else is using the backup folder (`books.backup`
|
|
||||||
and the close's answer say the same; the next backup that finds the
|
|
||||||
lock gone goes on). In the book's own archive (`archive.git`, private to
|
|
||||||
the program; running git by hand inside it is unsupported) it removes
|
|
||||||
only the locks its own stopped git made, and, at open and when a backup
|
|
||||||
begins, locks older than ten minutes, each recorded `lock_removed`;
|
|
||||||
**What a close stops, and what it waits for.** At its start a close
|
**What a close stops, and what it waits for.** At its start a close
|
||||||
stops the calls and jobs that can do long I/O or loop over a book's
|
stops the calls and jobs that can do long I/O or loop over a book's
|
||||||
whole journal or files, each at its next look: `books.back_up_now` and
|
whole journal or files, each at its next look: `books.back_up_now` and
|
||||||
a backup a timer asked for (git is stopped; the call answers that it was
|
a backup a timer asked for (its copy is stopped; the call answers that it
|
||||||
stopped because the books are closing, its access record says
|
was stopped because the books are closing, its access record says
|
||||||
`refused: stopped_by_close`, and nothing it was doing is recorded as done;
|
`refused: stopped_by_close`, and nothing it was doing is recorded as done;
|
||||||
a commit it had made stands), `books.verify` (once per journal line and
|
what it had written stands, and the folder still proves whole at its
|
||||||
|
previous manifest), `books.verify` (once per journal line and
|
||||||
per stored file; a heal of a drifted database is begun only if no stop
|
per stored file; a heal of a drifted database is begun only if no stop
|
||||||
was asked before it, then finishes), `books.export_cpa_package` (once per
|
was asked before it, then finishes), `books.export_cpa_package` (once per
|
||||||
stored file, unless it has journaled a decision, below), a drill, and a
|
stored file, unless it has journaled a decision, below), a drill, and a
|
||||||
@@ -1365,75 +1359,74 @@ through the policy.
|
|||||||
|
|
||||||
## Tools — backups
|
## Tools — backups
|
||||||
|
|
||||||
Books back themselves up (plan 3.7, D-30,
|
Books back themselves up (plan 3.7, D-91, D-92): to the folder the settings
|
||||||
D-31): each keeps `archive.git`, a bare repository whose commits are its
|
name, `backup.folder` (a folder on another disk, or one a sync service
|
||||||
journal, stored files, vault, keys and access log as they were (one
|
keeps), as plain files written once (docs/backups.md): a folder for the
|
||||||
commit per backup, made under the store's lock, its message
|
books holding a read-me, a `manifests/` folder, and the pieces the manifests
|
||||||
`seq N head H` and, below, `book <id>`), pushed fast-forward only to the targets the settings
|
name, the journal and the access log as numbered segments, an index of the
|
||||||
name: `backup.git_remote` (the owner's private repository) and
|
stored files and the files themselves under their hash, the vault and keys
|
||||||
`backup.folder` (a repository `<book>.git` in a folder on another disk).
|
by content hash. The manifest is written last and makes a backup complete;
|
||||||
Not encrypted: the destinations keep it private. Backups run a little
|
nothing in the folder is ever rewritten or deleted. Taking a backup holds
|
||||||
after the books are last written (`--backup-quiet`, 30 s), when they
|
the store's lock only to cut the books (the journal's length and head, the
|
||||||
open, before they close, and on request; a failed one is retried after
|
vault, the keys); the files are written after it. With a passphrase (D-92,
|
||||||
15 minutes. Each target is drilled weekly: cloned, its chain replayed,
|
set up in the window; off by default) every file is sealed with
|
||||||
every stored file re-hashed, every TIN record the books name there with
|
XChaCha20-Poly1305, the key derived with Argon2id (64 MiB, 3 passes, 1
|
||||||
its key, its head the one its commit records, its journal a byte prefix
|
lane), names say no more than counts and sizes, and the key is kept on this
|
||||||
of the live one (a failed drill is tried again at the server's next
|
computer only. Backups run a little after the books are last written
|
||||||
hourly look, once 15 minutes have passed). A backup's tree is checked
|
(`--backup-quiet`, 30 s), when they open, before they close, and on request;
|
||||||
before any of it is written out: plain files under the backed-up paths
|
a failed one is retried after 15 minutes. The folder's backup is drilled
|
||||||
only, never a link or a submodule. git runs with no hooks (in a
|
weekly: its books built and proven whole, every stored file re-hashed, every
|
||||||
repository on this computer it pushes to as well), no ignore or
|
TIN record the books name there with its key, its head the one its manifest
|
||||||
attributes rules of anyone's (a `.gitattributes` in a book's folder
|
records, its journal a byte prefix of the live one (a failed drill is tried
|
||||||
refuses the backup) and no command-running transports; a repository on
|
again at the server's next hourly look, once 15 minutes have passed). A
|
||||||
this computer is used only if plain (a bare repository at that very
|
backup is written only onto a folder whose newest whole manifest is a point
|
||||||
path, no settings of its own but where a copy came from, nothing sending
|
on the live journal; one holding other books, another history, or more than
|
||||||
git elsewhere, no link where it or its parts are), and a backup folder that took backups and is gone is
|
these books have is said, and nothing is written. A backup folder that took
|
||||||
reported as a disk not connected, never made again (restored books count
|
backups and is gone is reported as a disk not connected, never made again
|
||||||
the backups of the books they were). Books restored beside the books they
|
(restored books count the backups of the books they were). Books restored
|
||||||
were (under another id) don't push to those books' repository, which
|
under another id back up to a folder of their own in the same place. A
|
||||||
would stop theirs: `books.backup` says it is paused for them until
|
damaged backup record is set aside and begun again; it never keeps the books
|
||||||
another is named. A damaged backup record is set aside and begun again;
|
shut. A folder whose write failed is left out of the backups after writes
|
||||||
it never keeps the books shut. One book's drill holds the others'
|
for 15 minutes, then tried again. Every cut, write and drill is a record in
|
||||||
backups until it ends (a backup at close waits at most a minute for
|
the book's `ops/backup.jsonl` (a chain log; a backup never moves the books'
|
||||||
it). A target
|
head), the folder's records keyed by the folder and the passphrase. Setting
|
||||||
whose push failed is left out of the backups after writes for 15
|
`backup.*` (books.set_setting) needs books:admin, as backing up does: a
|
||||||
minutes, then tried again, written to or not; the other targets don't
|
backup is the whole book, its vault and key included. Books that still name
|
||||||
wait for it. Every
|
a private repository (`backup.git_remote`, an older kind of backup) work as
|
||||||
commit, push and drill is a record in the book's `ops/backup.jsonl` (a
|
ever; `books.backup`'s `note` says it is no longer used, and an older backup
|
||||||
chain log; a backup never moves the books' head), each target's records
|
history in the book's folder is left alone and said once.
|
||||||
keyed by the target itself. Setting `backup.*` (books.set_setting) needs
|
|
||||||
books:admin, as
|
|
||||||
backing up does: a backup is the whole book, its vault and key included.
|
|
||||||
|
|
||||||
- `books.backup {}` (books:read) → `{ head_seq, targets: [{ target:
|
- `books.backup {}` (books:read) → `{ head_seq, targets: [{ target:
|
||||||
"repository" | "folder", at, last_ok_at, through_seq, stale,
|
"folder", at, last_ok_at, through_seq, stale, last_error,
|
||||||
last_error, last_drill_at, drill_error, paused }], note }`. `paused`:
|
last_drill_at, drill_error, sealed, disconnected }], note }`.
|
||||||
not backed up there, these books being restored as a copy of others
|
`sealed`: protected by a passphrase. `disconnected`: its disk isn't
|
||||||
(its `last_error` says so). `stale`: the target
|
there. `stale`: the target
|
||||||
lacks the head, and the first try to back up what it lacks (since its
|
lacks the head, and the first try to back up what it lacks (since its
|
||||||
last good backup, or ever) is more than a day old. `last_error`: its
|
last good backup, or ever) is more than a day old. `last_error`: its
|
||||||
last push's, or a later failed commit's. `note`
|
last write's, or a later failed cut's. `note`
|
||||||
says what to set when no target is. `books.start` adds a next step when
|
says what to set when no folder is, and what older settings or history are
|
||||||
none is set up, or one is stale, failing, paused or failed its drill.
|
no longer used. `books.start` adds a next step when none is set up, or the
|
||||||
|
folder is stale, failing or failed its drill.
|
||||||
- `books.back_up_now { new_disk? }` (books:admin) → the same, after
|
- `books.back_up_now { new_disk? }` (books:admin) → the same, after
|
||||||
backing up to every target now. `new_disk`: the backup folder's disk is
|
backing up to the folder now. `new_disk`: the backup folder's disk is
|
||||||
new, so a folder that took these books' backups and holds none now is
|
new, so a folder that took these books' backups and holds none now is
|
||||||
begun again (otherwise it is a disk not connected). The one tool whose
|
begun again (otherwise it is a disk not connected). The one tool whose
|
||||||
`openWorldHint` is true. A target paused for books restored as a copy
|
`openWorldHint` is true.
|
||||||
of others shows `paused` (and is no failure to retry).
|
|
||||||
|
|
||||||
Restoring is the owner's, from a terminal: `wanderbooks books restore
|
Restoring is the owner's, in the window (Restore...) or from a terminal:
|
||||||
BACKUP [--id ID] [--replace] [--yes]` (the admin socket's `restore`,
|
`wanderbooks books restore BACKUP [--id ID] [--replace] [--yes]` (the admin
|
||||||
previewed then confirmed against the previewed head; without `--id`, the
|
socket's `restore`, previewed then confirmed against the previewed head;
|
||||||
books keep the id of the books the backup holds, which the preview names,
|
without `--id`, the books keep the id of the books the backup holds, which the
|
||||||
else the repository's name; under another id they are a copy, and don't
|
preview names). BACKUP is the backup folder, the folder of one set of books in
|
||||||
push to those books' repository). The backup is
|
it, or a backup file (`.wbbackup`); a sealed one asks for its passphrase
|
||||||
cloned into the root, proven whole as a drill proves it (but for the
|
(unechoed at a terminal, never on the command line). The backup is built in
|
||||||
live-journal check: there may be no live books), and built as an
|
the root, proven whole as a drill proves it (but for the live-journal check:
|
||||||
adoption builds; it arrives as new books, or replaces books (`--replace`,
|
there may be no live books), and built as an adoption builds; it arrives as
|
||||||
which are let go and moved whole into `legacy/<id>-<time>/`). The
|
new books, or replaces books (`--replace`, which are let go and moved whole
|
||||||
restored books keep the backup's history, so their next backups carry
|
into `legacy/<id>-<time>/`). If the newest backup in the folder is damaged,
|
||||||
on from it.
|
the newest whole one is the one previewed, and the preview says so. A sealed
|
||||||
|
backup's restored books keep backing up sealed, to the same folder, from this
|
||||||
|
computer.
|
||||||
|
|
||||||
## Tools — payouts
|
## Tools — payouts
|
||||||
|
|
||||||
|
|||||||
+2
-26
@@ -280,7 +280,7 @@ entry, icon, licences).
|
|||||||
| Books | `%LOCALAPPDATA%\wanderbooks` | `~/Library/Application Support/wanderbooks` | `~/.local/share/wanderbooks` (unchanged) |
|
| Books | `%LOCALAPPDATA%\wanderbooks` | `~/Library/Application Support/wanderbooks` | `~/.local/share/wanderbooks` (unchanged) |
|
||||||
| Removal leaves the books | the uninstaller names no data folder | dragging to Trash runs nothing | no package script runs |
|
| Removal leaves the books | the uninstaller names no data folder | dragging to Trash runs nothing | no package script runs |
|
||||||
| No console window | built for the GUI subsystem; attaches to a terminal for commands | n/a | n/a |
|
| No console window | built for the GUI subsystem; attaches to a terminal for commands | n/a | n/a |
|
||||||
| Without git | says how to get Git for Windows | says `xcode-select --install`; the system's stub is not taken for git | says the package manager's command |
|
| Backups | plain files; nothing to install | plain files; nothing to install | plain files; nothing to install |
|
||||||
|
|
||||||
**Why NSIS written by hand, not cargo-packager's.** The installer's rules
|
**Why NSIS written by hand, not cargo-packager's.** The installer's rules
|
||||||
(per user, one program, an uninstaller that can never reach the books) are
|
(per user, one program, an uninstaller that can never reach the books) are
|
||||||
@@ -320,30 +320,6 @@ icon);
|
|||||||
`wanderbooks.cmd`/PATH setup so a terminal waits for a command on Windows (a
|
`wanderbooks.cmd`/PATH setup so a terminal waits for a command on Windows (a
|
||||||
GUI-subsystem program returns the prompt at once); a macOS refusal for a program
|
GUI-subsystem program returns the prompt at once); a macOS refusal for a program
|
||||||
run from a mounted disk image (a path under `/Volumes` may be a real install on
|
run from a mounted disk image (a path under `/Volumes` may be a real install on
|
||||||
another disk); bundling git on Windows and macOS (the owner's decision, below); the signed `manifest.json` of the earlier self-update
|
another disk); the signed `manifest.json` of the earlier self-update
|
||||||
(needs the release key, Q-4).
|
(needs the release key, Q-4).
|
||||||
|
|
||||||
### Bundling git (an owner decision, not made here)
|
|
||||||
|
|
||||||
Backups run the system's git. **Linux:** the packages now depend on git, so the
|
|
||||||
package manager fetches it (nothing is bundled). **Windows and macOS:** the app
|
|
||||||
detects a missing git and says how to get it (WB-pkg-4); nothing is bundled.
|
|
||||||
|
|
||||||
What bundling would mean. Git is GPL-2.0-only free software. Shipping an
|
|
||||||
unmodified git as a separate file that our program starts as its own process
|
|
||||||
(never linked) is what the GPL calls aggregation: our MIT OR Apache-2.0 code is
|
|
||||||
unaffected, and AGENTS.md's clean-room rule (never copy GnuCash's code) is not
|
|
||||||
touched, since nothing of git is copied into ours; `deny.toml` governs Rust
|
|
||||||
crates only and does not see it. It still requires, for each release that
|
|
||||||
carries git: git's GPL text and copyright notices beside it (Git for Windows'
|
|
||||||
MinGit adds the notices of the components it carries: OpenSSL/curl, the MSYS2
|
|
||||||
runtime); the corresponding source of exactly that git, or a written offer for it
|
|
||||||
valid three years (GPLv2 section 3), most simply the git version's source
|
|
||||||
archive attached to the same release; no term of ours that forbids the
|
|
||||||
recipient what the GPL permits; and a note of any change if git were modified.
|
|
||||||
`THIRD-PARTY-NOTICES.txt` (cargo-about) covers Rust crates only, so it would
|
|
||||||
need an addition. On Windows the candidate is MinGit from Git for Windows
|
|
||||||
(about 40 MB, unpacked beside the program; `Git::find` would look there first);
|
|
||||||
on macOS Apple's command line tools' git is Apple's and cannot be bundled, so
|
|
||||||
it would be a build of our own (Homebrew's, or from source), universal, signed
|
|
||||||
inside the app, with the same obligations.
|
|
||||||
@@ -280,3 +280,16 @@ product's own sign-in has been tried against it yet.
|
|||||||
| A tool call's lines commit together with a closing line or not at all; a call that never closed, or failed, builds nothing in any replay; a failed call is on the record | A database transaction; QBO and Xero make a write all or nothing and say so on failure | partial | WB-format-8, WB-format-10; `ledger-store` `tests/calls.rs` (`a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it`, `a_replay_of_any_prefix_inside_a_call_is_the_replay_of_the_prefix_before_it`, `a_failed_call_is_on_the_record_and_builds_nothing`); partial until the Lean law is in bookspec and a `done` needs a golden |
|
| A tool call's lines commit together with a closing line or not at all; a call that never closed, or failed, builds nothing in any replay; a failed call is on the record | A database transaction; QBO and Xero make a write all or nothing and say so on failure | partial | WB-format-8, WB-format-10; `ledger-store` `tests/calls.rs` (`a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it`, `a_replay_of_any_prefix_inside_a_call_is_the_replay_of_the_prefix_before_it`, `a_failed_call_is_on_the_record_and_builds_nothing`); partial until the Lean law is in bookspec and a `done` needs a golden |
|
||||||
| Every write carries a request key; a repeat returns the first answer and writes nothing, across a restart; the same key for another request is refused | An idempotency key (a payments API's `Idempotency-Key`); QBO's `requestid` | partial | WB-format-9; `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`); `books.import_bank_csv` is one transaction (`the_import_is_one_transaction`) |
|
| Every write carries a request key; a repeat returns the first answer and writes nothing, across a restart; the same key for another request is refused | An idempotency key (a payments API's `Idempotency-Key`); QBO's `requestid` | partial | WB-format-9; `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`); `books.import_bank_csv` is one transaction (`the_import_is_one_transaction`) |
|
||||||
| Books that haven't declared the feature take no write and still read; every set of books has a unique id | No counterpart; the owner's rule (D-89) | partial | WB-format-11, WB-format-12; `ledger-store` `tests/calls.rs` (`books_that_have_not_declared_the_feature_take_no_call_and_still_read`, `new_books_are_born_with_an_id_and_no_two_share_one`); `ledger-cli` `tests/format_upgrade.rs` (`books_p2_served_cut_over_whole`) |
|
| Books that haven't declared the feature take no write and still read; every set of books has a unique id | No counterpart; the owner's rule (D-89) | partial | WB-format-11, WB-format-12; `ledger-store` `tests/calls.rs` (`books_that_have_not_declared_the_feature_take_no_call_and_still_read`, `new_books_are_born_with_an_id_and_no_two_share_one`); `ledger-cli` `tests/format_upgrade.rs` (`books_p2_served_cut_over_whole`) |
|
||||||
|
|
||||||
|
## P15 section 9: backups without git (2026-11-21, D-91, D-92)
|
||||||
|
|
||||||
|
Two new rows below; none above changed status, so the floor stands. A backup is a
|
||||||
|
folder of plain files written once, optionally sealed with a passphrase
|
||||||
|
(WB-backup-1 to WB-backup-11, `docs/backups.md`); the old backup made with git
|
||||||
|
is gone. Both rows are `partial`: nothing of the window's folder chooser and
|
||||||
|
passphrase set-up has run on Windows or macOS, and the window part has no golden.
|
||||||
|
|
||||||
|
| Area | Counterpart (a cross-check, not the spec) | Status | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| A backup is a folder the person picks, made of files written once, complete when its manifest is in place; a restore previews first and restores only the head it previewed; a restore of any whole manifest is a prefix of the books; a destination only grows | QBO's "back up company" is one file on the vendor's servers; Xero's export is a copy; GnuCash keeps one file and a dated backup beside it | partial | WB-backup-1 to WB-backup-6, WB-backup-9, WB-backup-10; `ledger-store` `tests/backup.rs` (`a_backup_is_the_book_and_proves_whole`, `a_program_that_dies_at_any_write_leaves_what_proved_whole_before`, `two_programs_writing_one_destination_do_not_corrupt_it`), `tests/backup_props.rs` (`any_whole_manifest_restores_a_prefix_of_the_books`, `a_destination_only_grows`); `ledger-cli` `tests/backups.rs` |
|
||||||
|
| The backups can be protected with a passphrase, off by default, and a backup can be saved as one file | GnuCash and QBO export files are not sealed; a sealed archive with a passphrase is the usual cross-check | partial | WB-backup-7, WB-backup-8; `ledger-store` `tests/backup.rs` (`a_wrong_passphrase_never_yields_books_and_is_told_from_damage`, `a_single_file_holds_the_same_backup_plain_or_sealed`), `tests/backup_props.rs` (`a_wrong_passphrase_never_yields_books`) |
|
||||||
+14
-13
@@ -28,19 +28,20 @@ easily backupable, journable":
|
|||||||
journals a `journal.tail_repaired` line; `books.digest` reports it.
|
journals a `journal.tail_repaired` line; `books.digest` reports it.
|
||||||
Damage before the last newline is corruption and refuses to open: that
|
Damage before the last newline is corruption and refuses to open: that
|
||||||
is for a human, never repaired automatically. The server does better
|
is for a human, never repaired automatically. The server does better
|
||||||
(plan 3.7): it commits the journal, the blobs, the vault, its key and
|
(plan 3.7, D-91): it backs the journal, the stored files, the vault, its
|
||||||
the access log to each book's own git repository (the blobs staged
|
key and the access log up to a folder the owner chooses, as plain files
|
||||||
ahead, the commit under the store's lock) and pushes it to the
|
that are written once and never changed or deleted (docs/backups.md, and
|
||||||
owner's private repository and backup folder, versioned and
|
docs/mcp-interface.md, "Tools — backups"): the journal and the access log
|
||||||
deduplicated, with full history (docs/mcp-interface.md, "Tools —
|
as numbered segments, each stored file once under its hash, and a
|
||||||
backups"). The program stops its git gently (SIGTERM first, so git
|
manifest, written last, that says which pieces make a backup whole. The
|
||||||
removes its own lock files, and a kill only after 5 seconds), and never
|
books' lock is held only to take a cut of the journal's length and the
|
||||||
writes to or deletes from a backup folder, which is the owner's (shared,
|
vault; the files are written after it. With a passphrase (D-92) every file
|
||||||
perhaps, with another computer or a sync program): a lock git left
|
is sealed. Nothing is installed for it, and nothing in the backup folder
|
||||||
there after a kill is reported with its path, never removed. The book's
|
is ever deleted or rewritten by the program, which is the owner's (shared,
|
||||||
own archive (`archive.git`) is private to the program; there it removes
|
perhaps, with another computer or a sync program). The book's own
|
||||||
only the locks its own stopped git made, and locks older than ten
|
folder keeps a local backup of the same form (`local-backup/`) made
|
||||||
minutes found when the books open or a backup begins.
|
before a format upgrade. The old history older versions kept in the book's
|
||||||
|
folder is left where it is, unread and unwritten.
|
||||||
- **Journable.** It literally is a journal: `{seq, ts, type, payload, prev}`.
|
- **Journable.** It literally is a journal: `{seq, ts, type, payload, prev}`.
|
||||||
Greppable, diffable, replayable. The audit trail isn't a feature bolted
|
Greppable, diffable, replayable. The audit trail isn't a feature bolted
|
||||||
on — it's the storage format.
|
on — it's the storage format.
|
||||||
|
|||||||
@@ -0,0 +1,401 @@
|
|||||||
|
# Claims: backups
|
||||||
|
|
||||||
|
Wanderbooks' own product rules for backups: plain folders, written once,
|
||||||
|
optionally sealed with a passphrase (plan P15 section 9, D-91 and D-92,
|
||||||
|
`plan/p15-app-and-relay.md`). No authority outside this product states them.
|
||||||
|
They are `WB-backup-<n>`. They replace the rules for backups made with git
|
||||||
|
(D-30, D-31), which are gone.
|
||||||
|
|
||||||
|
Rules: none from bookspec's list; these are product rules only. What a backup
|
||||||
|
holds (the journal, the stored files, the vault, the keys, the access log;
|
||||||
|
never the database, which a restore rebuilds) and when it runs are unchanged
|
||||||
|
(plan 3.7).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Product rules
|
||||||
|
|
||||||
|
**WB-backup-1 A backup is plain files, each written once, so a destination
|
||||||
|
only grows.** A destination is a folder the person picks. It holds one folder
|
||||||
|
per set of books, named with a fixed prefix and the books' id so that it is a
|
||||||
|
legal folder name on every system whatever the id is, with a read-me in plain
|
||||||
|
words, a folder of manifests, and the pieces the manifests name: the journal
|
||||||
|
and the access log as numbered segments, an index of the stored files, the
|
||||||
|
stored files themselves under their hash, and the vault and the keys under
|
||||||
|
their content hash. Every file is put once: written under a scratch name in
|
||||||
|
its own folder, synced, and given its name by a hard link, which is made
|
||||||
|
exactly once or refused (WB-backup-18 says what is done on a disk that makes
|
||||||
|
none). Nothing in a destination is
|
||||||
|
ever deleted or rewritten by the program: the only file it removes there is the
|
||||||
|
scratch file it made a moment before. So a service that syncs the folder never
|
||||||
|
sees a file change under it, and an earlier state of the books is always still
|
||||||
|
there (the journal is the history: an earlier state is a shorter prefix, and
|
||||||
|
each manifest marks one).
|
||||||
|
*Enforced:* `ledger_store::backup::write::write_destination`,
|
||||||
|
`ledger_store::backup::write::Destination`, `crates/ledger-store/src/backup/io.rs`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup.rs`
|
||||||
|
(`a_backup_is_the_book_and_proves_whole`,
|
||||||
|
`a_program_that_dies_at_any_write_leaves_what_proved_whole_before`),
|
||||||
|
`tests/backup_props.rs` (`a_destination_only_grows`).
|
||||||
|
|
||||||
|
**WB-backup-2 A backup is whole when its manifest is in place, and a manifest
|
||||||
|
names only pieces that exist and hash right.** The manifest is written last
|
||||||
|
and atomically. It names the books' id, the head and sequence number it
|
||||||
|
reaches, every segment, and the vault and key files, each by where it is, how
|
||||||
|
long it is and what is in it (SHA-256). A manifest names the manifest before
|
||||||
|
it and only the segments added since, until a chain of 64 is made, when one
|
||||||
|
names everything again (WB-backup-17); read, every manifest names everything,
|
||||||
|
and one that is lost, or replaced by a sync service's conflict copy, makes
|
||||||
|
unreadable only those chained on it, never an earlier one. A reader looks at
|
||||||
|
the manifests newest first and takes the first whose pieces are all there at the
|
||||||
|
length it names and that proves whole (it reads no more than that), and the
|
||||||
|
proof re-hashes every piece: the journal's chain replays to the head the manifest
|
||||||
|
records before the books are opened, the books open, every stored file re-hashes,
|
||||||
|
every TIN record the books name and the key that opens them are there. A
|
||||||
|
manifest that is cut short or changed is no manifest. A run that dies leaves
|
||||||
|
pieces no manifest names, which are harmless.
|
||||||
|
*Enforced:* `ledger_store::backup::read::find`, `ledger_store::backup::read::verify_found`,
|
||||||
|
`ledger_store::backup::read::Set`, `ledger_store::backup::read::prove_books`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup.rs`
|
||||||
|
(`a_flipped_or_cut_piece_is_found_and_never_restored`,
|
||||||
|
`the_text_read_from_a_stored_file_is_a_stored_file_too`), `tests/backup_repair.rs`
|
||||||
|
(`only_the_newest_backup_is_tried_in_the_good_case`).
|
||||||
|
|
||||||
|
**WB-backup-3 A restore of any whole manifest yields books whose journal is
|
||||||
|
byte-identical to a prefix of the source's.** A restore previews first and
|
||||||
|
restores only the head it previewed, as new books or replacing books (which are
|
||||||
|
moved whole into the legacy folder, never deleted). When the newest manifest is
|
||||||
|
damaged the newest whole one is used, and the preview says so before anything
|
||||||
|
else (WB-backup-15). The backup's journal is a byte prefix of the live one (a
|
||||||
|
drill checks it).
|
||||||
|
*Enforced:* `ledger_store::backup::read::verify_found`, `ledger_store::root::Root::restore`,
|
||||||
|
`ledger_store::root::Root::restore_preview`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup_props.rs`
|
||||||
|
(`any_whole_manifest_restores_a_prefix_of_the_books`),
|
||||||
|
`tests/backup.rs` (`a_damaged_newest_backup_falls_back_to_the_one_before_and_says_so`);
|
||||||
|
`ledger-cli` `tests/backups_restore.rs` (`a_restore_is_of_the_backup_previewed_only`,
|
||||||
|
`restore_never_overwrites_and_replacing_keeps_the_old_books`).
|
||||||
|
|
||||||
|
**WB-backup-4 A destination of other books, another history of these, or more
|
||||||
|
than these books have is never written, and the two are told apart.** Before
|
||||||
|
writing, the destination's newest whole manifest must be a point on the live
|
||||||
|
journal: the bytes of the journal it names are the first bytes of the live one.
|
||||||
|
When the destination's journal is the longer, the live journal is checked to be
|
||||||
|
the beginning of it: if it is, the books are behind the folder (as after a
|
||||||
|
restore from an older backup or a backup file) and that is said, in words that
|
||||||
|
say what to do; if it is not, the books are other books or have diverged, and
|
||||||
|
that is said. Either way nothing is written. A person who wants to carry on
|
||||||
|
with the books they have can start a new set of backups beside the old one, in
|
||||||
|
the same folder, at their explicit request; the old set is never touched, and
|
||||||
|
later backups go to the new one. A folder that took these books' backups and
|
||||||
|
holds none now is a disk not connected, never made again where the disk should
|
||||||
|
be unless the person says it is a new disk.
|
||||||
|
*Enforced:* `ledger_store::backup::write::write_destination_with`,
|
||||||
|
`ledger_store::backup::write::Options`, `ledger_store::backup::BackupError`,
|
||||||
|
`ledger_mcp::backup::Backups`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup.rs`
|
||||||
|
(`a_destination_of_other_books_or_another_history_is_never_written`,
|
||||||
|
`a_disk_that_is_gone_is_never_made_again_where_it_should_be`),
|
||||||
|
`tests/backup_repair.rs` (`books_behind_the_destination_are_ahead_and_other_books_are_diverged`,
|
||||||
|
`a_new_set_begins_beside_the_old_at_the_persons_request_and_the_old_is_never_touched`);
|
||||||
|
`ledger-cli` `tests/backups.rs` (`a_backup_of_another_history_is_never_written_over`),
|
||||||
|
`tests/backups_restore.rs` (`restored_books_never_make_their_backup_folder_again`),
|
||||||
|
`tests/backups_trouble.rs`
|
||||||
|
(`books_restored_from_an_older_backup_are_ahead_and_a_new_set_begins_at_their_request`).
|
||||||
|
|
||||||
|
**WB-backup-5 Two programs, or two computers, writing one destination cannot
|
||||||
|
corrupt it, and a program that dies at any write leaves what proved whole
|
||||||
|
before.** Pieces are named by what is in them, so two writers of one piece write
|
||||||
|
the same bytes; the only decision is which writer takes the next manifest
|
||||||
|
number, and the disk decides it (exclusive create). The loser looks again and
|
||||||
|
goes on from what the winner wrote, or finds nothing left to write. A program
|
||||||
|
that dies at any write point (a scratch file, a piece, the manifest) leaves a
|
||||||
|
destination whose newest whole manifest is the one before, or the new one, and
|
||||||
|
a restore from it is a prefix of the books. No lock a sync service ignores is
|
||||||
|
relied on.
|
||||||
|
*Enforced:* `ledger_store::backup::write::write_destination`,
|
||||||
|
`crates/ledger-store/src/backup/write.rs`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup.rs`
|
||||||
|
(`two_programs_writing_one_destination_do_not_corrupt_it`,
|
||||||
|
`a_loser_of_a_manifest_number_goes_on_from_the_winner`,
|
||||||
|
`a_program_that_dies_at_any_write_leaves_what_proved_whole_before`),
|
||||||
|
`tests/backup_props.rs` (`random_interleavings_of_two_writers_leave_a_whole_backup`).
|
||||||
|
|
||||||
|
**WB-backup-6 A flipped or cut piece is found and never restored.** Every piece
|
||||||
|
is checked against what its manifest says, in length and in hash, and a sealed
|
||||||
|
piece against its seal; a piece that fails ends the proof of that manifest, and
|
||||||
|
nothing is put in the books' place from it. A piece is accepted under any
|
||||||
|
generation of it (WB-backup-13) if its contents hash right.
|
||||||
|
*Enforced:* `ledger_store::backup::read::verify_found`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup_props.rs`
|
||||||
|
(`any_flipped_or_cut_piece_is_found_never_restored`), `tests/backup.rs`
|
||||||
|
(`a_flipped_or_cut_piece_is_found_and_never_restored`); `ledger-cli`
|
||||||
|
`tests/backups_restore.rs` (`restore_refuses_a_damaged_backup_and_writes_nothing`),
|
||||||
|
`tests/backups.rs` (`restore_drill_failure_is_flagged`).
|
||||||
|
|
||||||
|
**WB-backup-7 A passphrase seals every piece, and a wrong passphrase never
|
||||||
|
yields books.** The passphrase is offered at set-up and is off by default
|
||||||
|
(D-92). With one, every piece and every manifest is sealed with
|
||||||
|
XChaCha20-Poly1305 in chunks of 1 MiB, each bound to what is in it and to
|
||||||
|
whether it is the last. The key is derived from the passphrase with Argon2id at
|
||||||
|
the owner passphrase's own cost (64 MiB, 3 passes, 1 lane) and a salt of its
|
||||||
|
own, which the set's header records, so another computer derives the same key.
|
||||||
|
File names are made from the key and say no more than counts and sizes. The
|
||||||
|
header carries a sealed check bound to the key settings, so a wrong passphrase
|
||||||
|
is told from a damaged header; a setting the header asks for beyond four times
|
||||||
|
this program's own (memory, passes, lanes) is refused as damage before any key is
|
||||||
|
derived, a header that was changed by accident breaks its own check line and
|
||||||
|
reads as damage, and one changed on purpose can only make the key come out
|
||||||
|
different, which opens nothing. A folder of sealed sets costs one key derivation
|
||||||
|
for each distinct setting, not one for each set. Pieces are kept in folders of
|
||||||
|
the first two digits of their names, so no folder outgrows a small disk's file
|
||||||
|
system. The derived key is kept on this computer only, in the book's own
|
||||||
|
folder, readable by the person's account alone; never in a backup, never in the
|
||||||
|
journal, never in a record or an error. Changing the passphrase starts a new set
|
||||||
|
beside the old one and removing it makes the next backup plain: pieces already
|
||||||
|
written are never rewritten, so the old ones stay as they were, sealed with the
|
||||||
|
passphrase they were made with. A forgotten passphrase cannot be recovered, and
|
||||||
|
the set-up says so.
|
||||||
|
*Enforced:* `ledger_store::backup::seal::BackupKey`,
|
||||||
|
`crates/ledger-store/src/backup/seal.rs`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup.rs`
|
||||||
|
(`a_sealed_backup_gives_away_counts_and_sizes_only`,
|
||||||
|
`a_wrong_passphrase_never_yields_books_and_is_told_from_damage`,
|
||||||
|
`a_changed_passphrase_is_a_new_set_beside_the_old_which_is_untouched`,
|
||||||
|
`the_key_is_kept_privately_and_only_there`), `tests/backup_props.rs`
|
||||||
|
(`a_wrong_passphrase_never_yields_books`), `tests/backup_disk.rs`
|
||||||
|
(`a_header_cannot_ask_for_more_than_a_few_times_what_this_program_spends`,
|
||||||
|
`a_header_that_was_changed_reads_as_damage_and_not_as_a_wrong_passphrase`,
|
||||||
|
`a_folder_of_sealed_sets_costs_one_key_derivation_per_setting_not_one_per_set`,
|
||||||
|
`sealed_pieces_are_spread_over_folders_as_the_plain_form_does`).
|
||||||
|
|
||||||
|
**WB-backup-8 "Save a backup..." is the same backup as one file.** The file is a
|
||||||
|
zip of the set's folder form holding one manifest and only the pieces it names,
|
||||||
|
sealed when the backups are, with the extension .wbbackup. A file by the name
|
||||||
|
asked for is never written over, and is moved into place only when it has been
|
||||||
|
read back as a restore reads it and proven whole. Restore reads a destination
|
||||||
|
folder, a set's own folder, or this file.
|
||||||
|
*Enforced:* `ledger_store::backup::single::save_file`, `ledger_store::backup::single::FILE_EXTENSION`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup.rs`
|
||||||
|
(`a_single_file_holds_the_same_backup_plain_or_sealed`).
|
||||||
|
|
||||||
|
**WB-backup-9 A stopped backup leaves a destination that proves whole at its
|
||||||
|
previous manifest, and a close is bounded.** A backup a close stops (the
|
||||||
|
books' close, or a call or timer's backup when a close begins) looks for the
|
||||||
|
stop between pieces and once per chunk of a file read, including in the proof
|
||||||
|
after the backup, so it ends promptly; the server records `stopped` and no
|
||||||
|
result of the run's own, and the close's own last backup is stopped only at its
|
||||||
|
bound. A manifest written before the stop is not marked proven: the next
|
||||||
|
backup proves it, even one with nothing new to write (WB-backup-12). The proof's
|
||||||
|
scratch books are removed whatever ends it.
|
||||||
|
*Enforced:* `ledger_store::backup::Ctx`, `ledger_mcp::backup::Backups`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup.rs`
|
||||||
|
(`a_stopped_backup_leaves_what_proved_whole_before`), `tests/backup_repair.rs`
|
||||||
|
(`a_proof_cut_short_by_a_close_ends_cleanly_and_is_made_again_by_the_next_backup`);
|
||||||
|
`ledger-cli` `tests/book_open_close.rs`
|
||||||
|
(`a_close_is_not_answered_while_its_backup_still_runs`,
|
||||||
|
`a_close_stops_a_running_backup_call_and_says_so`).
|
||||||
|
|
||||||
|
**WB-backup-10 Older forms are left alone and said.** Books that still carry
|
||||||
|
the old setting naming a private repository open and work; the backup status
|
||||||
|
says in plain words that it is no longer used and to choose a folder. An older
|
||||||
|
backup history in a book's own folder, and an older backup folder made with git
|
||||||
|
beside a destination, are neither read, written, moved nor deleted; the new form
|
||||||
|
goes beside them, and the status says once, until a backup has been made in the
|
||||||
|
new form, that the older one is no longer written. A person who has an older
|
||||||
|
backup clones it themselves and adopts the plain folder (docs/backups.md).
|
||||||
|
*Enforced:* `ledger_mcp::backup::Backups`.
|
||||||
|
*Checked:* `ledger-cli` `tests/backups.rs`
|
||||||
|
(`old_settings_and_an_old_backup_history_are_left_alone_and_said`,
|
||||||
|
`a_clone_of_an_old_git_backup_is_adopted_as_a_plain_folder`: it builds a clone's
|
||||||
|
working tree itself, so it runs, and says nothing is skipped, with no git on the
|
||||||
|
machine).
|
||||||
|
|
||||||
|
**WB-backup-11 A format upgrade needs a proven local backup, made under the
|
||||||
|
store's lock.** The local backup is the same form in the book's own folder
|
||||||
|
(`local-backup`), written and proven to hold the books exactly as they are
|
||||||
|
(journal, vault and keys byte for byte, every stored file re-hashed) before
|
||||||
|
the journal's format moves, all under the store's lock.
|
||||||
|
*Enforced:* `ledger_store::backup::write::write_local`, `ledger_store::backup::read::prove_local`,
|
||||||
|
`ledger_mcp::backup::Backups`.
|
||||||
|
*Checked:* `ledger-mcp` `local.rs` (`format_upgrade_waits_for_consent`,
|
||||||
|
`no_upgrade_unless_the_backup_is_proven`, `no_upgrade_without_a_backup`).
|
||||||
|
|
||||||
|
**WB-backup-12 "Recorded good" means the backup was read back and proven, and
|
||||||
|
this is exactly what that proves.** After a manifest is put and before the
|
||||||
|
backup is recorded good, the manifest is read back from the destination as a
|
||||||
|
restore would read it, and proven: every journal and access segment it names is
|
||||||
|
re-hashed and the hash chain replays to the head it records, the books built
|
||||||
|
from them open, the vault and the keys and their presence are checked (every TIN
|
||||||
|
record the books name, and the key that opens them), the index of stored files
|
||||||
|
is read, every stored file the books name is in it, and of the stored files
|
||||||
|
itself those this backup added and one sixteenth of the others are re-hashed.
|
||||||
|
The sixteenth is the files whose hash begins with a digit group equal to the
|
||||||
|
manifest number modulo 16, so any 16 manifest numbers in a row between them re-read
|
||||||
|
every stored file once: **every stored file is re-read within 16 backups** (the
|
||||||
|
weekly drill re-reads all of them), and the cost of a backup's proof is the
|
||||||
|
journal and access log, which the books need anyway, plus a sixteenth of the
|
||||||
|
stored files. A backup that is not proven is not recorded good. The proof is
|
||||||
|
marked, per manifest, by a tiny file written once, so a manifest whose proof
|
||||||
|
was cut short is proven by the next backup. What "recorded good" does not prove:
|
||||||
|
that a stored file that is not in the share of the 16 is still whole today (the
|
||||||
|
rotation and the drill will say, and a damaged one is written again, WB-backup-13);
|
||||||
|
that the destination is still whole after the backup (the next backup and the
|
||||||
|
weekly drill say). A backup file saved on request is proven whole in full before
|
||||||
|
it is named.
|
||||||
|
*Enforced:* `ledger_store::backup::read::prove_written`,
|
||||||
|
`ledger_store::backup::read::in_rotation`, `ledger_store::backup::read::ROTATION`,
|
||||||
|
`ledger_store::backup::write::prove_and_repair`, `ledger_store::backup::form::proof_path`,
|
||||||
|
`ledger_store::backup::single::save_file`, `ledger_mcp::backup::Backups`.
|
||||||
|
*Checked:* `ledger-store` `src/backup/tests.rs`
|
||||||
|
(`a_piece_belongs_to_one_share_and_every_share_is_read_within_sixteen_backups`),
|
||||||
|
`tests/backup_repair.rs`
|
||||||
|
(`one_damaged_segment_is_found_by_the_next_backup_and_the_drill_does_not_hide_it`,
|
||||||
|
`a_damaged_stored_file_is_found_by_the_rotation_and_the_next_backup_repairs_it`,
|
||||||
|
`a_proof_cut_short_by_a_close_ends_cleanly_and_is_made_again_by_the_next_backup`).
|
||||||
|
|
||||||
|
**WB-backup-13 A damaged piece is written again beside the damaged file, and a
|
||||||
|
damaged destination can be repaired.** A piece already in the destination under
|
||||||
|
its name is taken as the piece when it is put (its name is its hash), so a
|
||||||
|
damaged one would be taken again by every later backup; the proof after a
|
||||||
|
backup finds it, and the backup writes the piece again from the books under the
|
||||||
|
next generation of its name (a name ending .g1, then .g2), a new manifest names
|
||||||
|
the good one, and the proof is made again. Nothing is rewritten or deleted: the
|
||||||
|
damaged file is left where it is, and is listed in the status and in the window
|
||||||
|
as written again, for the person to delete if they wish. A stored file is found
|
||||||
|
by its hash and generation, a segment, vault record or key by the manifest that
|
||||||
|
names it, and an index segment that cannot be read is begun again from the
|
||||||
|
stored files the books have. A damaged piece that can't be written again from the
|
||||||
|
books (the books' own file is the damaged one) is an error said in words, and
|
||||||
|
the backup is not recorded good.
|
||||||
|
*Enforced:* `ledger_store::backup::write::fresh_path`,
|
||||||
|
`ledger_store::backup::write::prove_and_repair`, `ledger_store::backup::form::generation_path`,
|
||||||
|
`ledger_store::backup::read::Set`, `ledger_mcp::backup::TargetStatus`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup_repair.rs`
|
||||||
|
(`one_damaged_segment_is_found_by_the_next_backup_and_the_drill_does_not_hide_it`,
|
||||||
|
`a_damaged_stored_file_is_found_by_the_rotation_and_the_next_backup_repairs_it`,
|
||||||
|
`a_piece_damaged_as_it_is_written_is_repaired_in_the_same_backup`,
|
||||||
|
`a_damaged_vault_record_and_an_index_segment_are_written_again_too`), `src/backup/tests.rs`
|
||||||
|
(`generations_and_set_names_round_trip`).
|
||||||
|
|
||||||
|
**WB-backup-14 A drill passes only on the newest manifest.** The weekly drill
|
||||||
|
builds the newest backup's books and proves them whole, re-hashing every stored
|
||||||
|
file, and passes only if that manifest proves whole and reaches the head of the
|
||||||
|
last backup recorded good, and its journal is the beginning of the live one.
|
||||||
|
An older manifest that proves whole while the newest does not is a failure,
|
||||||
|
never ok: the status and the window say "the newest backup (number N, from
|
||||||
|
DATE) is damaged; an older one from DATE is whole", and a restore from the
|
||||||
|
folder would give that older one. A newest manifest that stops short of the last
|
||||||
|
backup recorded good is a failure too: a backup that was made is not there.
|
||||||
|
*Enforced:* `ledger_store::backup::read::drill`, `ledger_store::backup::BackupError`,
|
||||||
|
`ledger_mcp::backup::Backups`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup_repair.rs`
|
||||||
|
(`a_drill_never_passes_on_an_older_backup`,
|
||||||
|
`a_drill_needs_the_newest_backup_to_reach_the_last_one_recorded_good`);
|
||||||
|
`ledger-cli` `tests/backups_trouble.rs`
|
||||||
|
(`a_drill_that_finds_only_an_older_backup_is_a_failure_in_words_and_never_ok`).
|
||||||
|
|
||||||
|
**WB-backup-15 A restore that is not of the newest backup says so before the
|
||||||
|
person confirms.** When the newest backup in the folder does not prove whole and
|
||||||
|
a restore would use an older one, the preview says so first, before anything
|
||||||
|
else, in the warning colour in the window: this is not the newest backup, how
|
||||||
|
many newer backups it passes over, when this one was made and when the newest
|
||||||
|
was, and that anything written after is not in it.
|
||||||
|
*Enforced:* `ledger_host::commands::older_backup_words`,
|
||||||
|
`ledger_store::root::RestorePreview`, `ledger_store::backup::read::Verified`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup_repair.rs` (`a_drill_never_passes_on_an_older_backup`);
|
||||||
|
`ledger-cli` `tests/backups_trouble.rs`
|
||||||
|
(`a_drill_that_finds_only_an_older_backup_is_a_failure_in_words_and_never_ok`).
|
||||||
|
|
||||||
|
**WB-backup-16 A key lost from a sealed destination never makes backups
|
||||||
|
plain.** That a destination is sealed is kept where it survives losing the key
|
||||||
|
file: in the backup record (what was last chosen about the passphrase, and the
|
||||||
|
key's fingerprint, which opens nothing) and, where the record has nothing, in
|
||||||
|
the folder itself (it holds sealed sets and none that is plain). A sealed
|
||||||
|
destination with no key available stops backing up, writes nothing, and says in
|
||||||
|
words to enter the passphrase or remove it; plain backups are written only after
|
||||||
|
the person removes the passphrase, which the record keeps.
|
||||||
|
*Enforced:* `ledger_mcp::backup::Backups`, `ledger_store::backup::write::holds_only_sealed`,
|
||||||
|
`ledger_store::backup::BackupError`.
|
||||||
|
*Checked:* `ledger-cli` `tests/backups_trouble.rs`
|
||||||
|
(`a_lost_key_file_never_makes_backups_plain`).
|
||||||
|
|
||||||
|
**WB-backup-17 A manifest names the one before it, and its growth is bounded
|
||||||
|
without trusting an unproven chain.** No series is ever written again as one
|
||||||
|
(a series of many small segments is acceptable). A manifest names its base by
|
||||||
|
number and by what its body hashes to, and the segments added since; a chain is
|
||||||
|
at most 64 long, then one names everything. A reader proves a chain link by link:
|
||||||
|
each base must hash to what its successor names and be one link shorter, so a
|
||||||
|
changed, swapped, missing or looping base makes the manifest unreadable and the
|
||||||
|
reader takes the newest that reads; no manifest is believed on a chain it has not
|
||||||
|
read. For a destination of 3000 backups the manifests were 12.1 MB in all
|
||||||
|
(naming everything each time would be about 765 MB), the largest 413 KB (one in
|
||||||
|
64 names everything) and the newest 0.8 KB, and the newest was found and read
|
||||||
|
whole in 32 ms (an unoptimised build; the proof's own time is the journal's).
|
||||||
|
*Enforced:* `ledger_store::backup::write::kept_form`, `ledger_store::backup::form::DELTA_CHAIN`,
|
||||||
|
`ledger_store::backup::form::BaseRef`, `ledger_store::backup::read::Set`.
|
||||||
|
*Checked:* `ledger-store` `src/backup/tests.rs`
|
||||||
|
(`the_writers_manifests_chain_to_a_bounded_depth_and_are_proven_link_by_link`,
|
||||||
|
`a_destination_of_thousands_of_backups_stays_small_and_quick_to_read`).
|
||||||
|
|
||||||
|
**WB-backup-18 A disk that makes no hard links takes backups too, and a failed
|
||||||
|
link is never a reason to replace.** Only an error that means the disk makes no
|
||||||
|
links (on Unix EPERM, ENOSYS, EOPNOTSUPP, ENOTSUP; on Windows
|
||||||
|
ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER,
|
||||||
|
ERROR_CALL_NOT_IMPLEMENTED) sends a put down the path for such a disk; any other
|
||||||
|
error is an error. There the finished scratch file is moved into place by a move
|
||||||
|
that refuses to replace (renameat2 with RENAME_NOREPLACE on Linux, renamex_np
|
||||||
|
with RENAME_EXCL on macOS, MoveFileExW without the replace flag on Windows); on a
|
||||||
|
file system that cannot say no, the last resort is exclusive create under the
|
||||||
|
real name and a copy, which leaves a short file under the name if the program
|
||||||
|
dies in the middle: the next proof finds it and the piece is written again
|
||||||
|
(WB-backup-13); a short manifest is accepted by no reader.
|
||||||
|
*Enforced:* `crates/ledger-store/src/backup/io.rs`,
|
||||||
|
`ledger_store::backup::Ctx`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup_disk.rs`
|
||||||
|
(`a_disk_that_makes_no_links_takes_whole_backups_and_only_grows`,
|
||||||
|
`two_writers_racing_on_a_disk_that_makes_no_links_do_not_corrupt_it`,
|
||||||
|
`a_taken_number_or_name_is_never_replaced_on_a_disk_that_makes_no_links`),
|
||||||
|
`src/backup/tests.rs` (`only_an_error_that_means_no_links_is_taken_to_mean_it`).
|
||||||
|
|
||||||
|
**WB-backup-19 A folder a sync service keeps is said in plain words, and a file
|
||||||
|
it has not downloaded is never read as damage or absence.** When the backup
|
||||||
|
folder is inside a known sync service's folder (told by the names in its path:
|
||||||
|
Dropbox, OneDrive, iCloud Drive, Google Drive, Nextcloud, pCloud, Box), and
|
||||||
|
otherwise in general words, the set-up and the window say: use this folder from
|
||||||
|
one computer only, keep it available offline, a second computer needs a folder
|
||||||
|
of its own. A file that is not on this computer yet reads as "not downloaded
|
||||||
|
yet", the backup waits, and nothing is written over it: on macOS before 14 by
|
||||||
|
the stand-in name (.name.icloud), on macOS by the dataless file flag, on Windows
|
||||||
|
by the offline and recall file attributes (read there it would make Windows fetch
|
||||||
|
it, which may take long or fail, so it is not read). Where nothing can tell
|
||||||
|
(Linux, whatever client), a file reads as the file it is, and a missing or short
|
||||||
|
one is found by the proof.
|
||||||
|
*Enforced:* `ledger_mcp::backup::sync_service`, `ledger_mcp::backup::sync_words`,
|
||||||
|
`ledger_store::backup::BackupError`, `crates/ledger-store/src/backup/io.rs`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup_disk.rs`
|
||||||
|
(`a_file_that_is_not_downloaded_yet_reads_as_such_and_never_as_damage_or_absence`),
|
||||||
|
`src/backup/tests.rs`
|
||||||
|
(`what_a_sync_service_leaves_for_a_file_it_has_not_downloaded_is_known`);
|
||||||
|
`ledger-cli` `tests/backups_trouble.rs`
|
||||||
|
(`a_folder_a_sync_service_keeps_is_said_in_plain_words_at_set_up`).
|
||||||
|
|
||||||
|
**WB-backup-20 The vault's scratch files are never backed up as records.** A
|
||||||
|
vault write that is between its steps leaves a record staged under a name ending
|
||||||
|
.staged- and a tag, or an old one set aside under .purging- and a tag. A backup
|
||||||
|
cut then holds the vault as the journal says it is: a staged record is not the
|
||||||
|
books' yet and is left out; a record set aside for a purge that has not
|
||||||
|
committed is still the books' and is backed up under the name it has when it is
|
||||||
|
not set aside.
|
||||||
|
*Enforced:* `crates/ledger-store/src/backup/cut.rs`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup_repair.rs`
|
||||||
|
(`a_backup_cut_while_the_vault_is_being_written_restores_a_vault_that_matches_the_journal`).
|
||||||
|
|
||||||
|
**WB-backup-21 A set's folder is a legal name on every system.** The folder is
|
||||||
|
named with a fixed prefix and the books' id (con, nul, aux, prn, com1 to com9 and
|
||||||
|
lpt1 to lpt9 are not names on Windows, but the prefixed names are), and a later
|
||||||
|
set of the same books ends in a dot and a number, which no id holds.
|
||||||
|
*Enforced:* `ledger_store::backup::form::plain_set_name`,
|
||||||
|
`ledger_store::backup::write::set_name_for`.
|
||||||
|
*Checked:* `ledger-store` `tests/backup_repair.rs`
|
||||||
|
(`a_set_folder_is_a_legal_name_whatever_the_books_are_called`).
|
||||||
@@ -185,8 +185,8 @@ consent; `tests/p2_compat.rs`). Only the owner's go-ahead moves them, with the
|
|||||||
owner passphrase (the server checks it, Argon2id): in the app, which asks at
|
owner passphrase (the server checks it, Argon2id): in the app, which asks at
|
||||||
every open until it is given, or with `wanderbooks books upgrade ID` at a
|
every open until it is given, or with `wanderbooks books upgrade ID` at a
|
||||||
terminal, whose commands that open the books also ask; never an agent, and no
|
terminal, whose commands that open the books also ask; never an agent, and no
|
||||||
tool. Before the upgrade the server commits the books to their own backup
|
tool. Before the upgrade the server writes the books to a local backup in their own
|
||||||
repository and proves the copy holds them exactly as they are (journal, stored
|
folder (WB-backup-11) and proves it holds them exactly as they are (journal, stored
|
||||||
files, vault and keys, byte for byte), all under the books' lock; a backup
|
files, vault and keys, byte for byte), all under the books' lock; a backup
|
||||||
that can't be made or proven upgrades nothing. The upgrade is then one
|
that can't be made or proven upgrades nothing. The upgrade is then one
|
||||||
`journal.format_set` declaring the whole format, so a book's format moves
|
`journal.format_set` declaring the whole format, so a book's format moves
|
||||||
@@ -195,8 +195,8 @@ copy is new books of this version and moves to its format as it is made (the
|
|||||||
original keeps its own). The upgrade never weakens the gate: books declaring a
|
original keeps its own). The upgrade never weakens the gate: books declaring a
|
||||||
feature this version doesn't know are newer, as above.
|
feature this version doesn't know are newer, as above.
|
||||||
|
|
||||||
*Enforced:* `ledger_store::format` (`current`, `JournalFormat::upgrade`), `Store::create`, `Store::upgrade_format`, `Root::adopt`, `ledger_store::backup::prove_archive`, ledger-mcp `Backups::upgrade_format` and `local.rs` (the passphrase), ledger-host `host.rs` (the lease intent, handed to the server) and `commands.rs` (`books upgrade`, asking at open), ledger-gui `owner.rs` (the notice and the dialog).
|
*Enforced:* `ledger_store::format` (`current`, `JournalFormat::upgrade`), `Store::create`, `Store::upgrade_format`, `Root::adopt`, `ledger_store::backup::read::prove_local`, ledger-mcp `Backups::upgrade_format` and `local.rs` (the passphrase), ledger-host `host.rs` (the lease intent, handed to the server) and `commands.rs` (`books upgrade`, asking at open), ledger-gui `owner.rs` (the notice and the dialog).
|
||||||
*Checked:* `ledger-store` `tests/format_upgrade.rs` (new books in this version's format, a change waiting for the upgrade, every old-books fixture upgrading to its figures, a newer feature still refused), the unit tests in `format.rs` and `backup.rs` (`the_archive_proves_to_hold_the_book_as_it_is_keys_and_all`), `tests/root.rs` (adoption); `ledger-mcp` `local.rs` (`format_upgrade_waits_for_consent`, `no_upgrade_without_a_backup`, `no_upgrade_unless_the_backup_just_made_is_proven`); `ledger-host` `lease.rs` (`a_consent_never_shows_its_passphrase`); `ledger-cli` `tests/format_upgrade.rs` (from end to end); `ledger-gui` `tests/format_upgrade.rs`.
|
*Checked:* `ledger-store` `tests/format_upgrade.rs` (new books in this version's format, a change waiting for the upgrade, every old-books fixture upgrading to its figures, a newer feature still refused), the unit tests in `format.rs`, `tests/root.rs` (adoption); `ledger-mcp` `local.rs` (`format_upgrade_waits_for_consent`, `no_upgrade_without_a_backup`, `no_upgrade_unless_the_backup_is_proven`); `ledger-host` `lease.rs` (`a_consent_never_shows_its_passphrase`); `ledger-cli` `tests/format_upgrade.rs` (from end to end); `ledger-gui` `tests/format_upgrade.rs`.
|
||||||
|
|
||||||
**WB-format-4 Each projection schema in a file of its own.** (The lead's
|
**WB-format-4 Each projection schema in a file of its own.** (The lead's
|
||||||
decision, 2026-10-21, for 3.9's "before consent, the way back is always
|
decision, 2026-10-21, for 3.9's "before consent, the way back is always
|
||||||
|
|||||||
@@ -88,21 +88,14 @@ earlier staged update still works; no release key exists yet, so today none does
|
|||||||
`update.rs` (`a_macos_app_is_never_updated_in_place`); `ledger-gui`
|
`update.rs` (`a_macos_app_is_never_updated_in_place`); `ledger-gui`
|
||||||
`tests/update_notice.rs` (`a_newer_version_is_told_with_where_to_get_it`).
|
`tests/update_notice.rs` (`a_newer_version_is_told_with_where_to_get_it`).
|
||||||
|
|
||||||
**WB-pkg-4 Without git, backups are off and the person is told how to get
|
**WB-pkg-4 Backups need nothing installed.** A backup is a folder of plain files
|
||||||
it.** Backups run the system's git; the program carries none. With no git found, a
|
the program writes itself (WB-backup-1), so no package depends on another program
|
||||||
backup says so in plain words for the system it runs on (Git for Windows or winget; Apple's
|
for it, none carries one, and no backup asks the person to install anything. This
|
||||||
command line tools or Homebrew; the package manager) and the books work as
|
replaces the rule that backups ran the system's git and said how to get it (D-91).
|
||||||
ever; the next backup looks again, so installing git needs no restart. On a Mac
|
*Enforced:* `deploy/packaging/packager.toml`, `deploy/packaging/aur/PKGBUILD` and
|
||||||
without the developer tools, the stub at the system's git path is not taken for a
|
`crates/ledger-cli/Cargo.toml` name no such dependency.
|
||||||
git. Whether to ship a git with the app is the owner's decision, since git is
|
*Checked:* `ledger-cli` `tests/packaging.rs`
|
||||||
GPL-2.0-only free software and shipping it carries a source offer and notices.
|
(`no_package_depends_on_another_program_for_backups`).
|
||||||
*Enforced:* `ledger_store::backup::how_to_get_git`,
|
|
||||||
`ledger_store::backup::Git::find`.
|
|
||||||
*Checked:* `ledger-store` unit tests in `backup.rs`
|
|
||||||
(`a_missing_git_says_how_to_get_it`,
|
|
||||||
`the_mac_stub_is_not_a_git_until_the_developer_tools_are_there`);
|
|
||||||
`ledger-cli` `tests/packaging.rs`
|
|
||||||
(`the_linux_packages_depend_on_git_and_none_carries_one`).
|
|
||||||
|
|
||||||
**WB-pkg-5 The Connect page can write a one-click Claude desktop extension
|
**WB-pkg-5 The Connect page can write a one-click Claude desktop extension
|
||||||
for a company.** The "Claude desktop app" row has one button. It makes the
|
for a company.** The "Claude desktop app" row has one button. It makes the
|
||||||
|
|||||||
+82
-42
@@ -561,25 +561,19 @@ suites (`exports.rs`, `read_only.rs`, `show.rs`, `kept.rs`, `live.rs` and
|
|||||||
the rest), `ledger-package/tests/package.rs`, `ledger-store` `saving.rs`
|
the rest), `ledger-package/tests/package.rs`, `ledger-store` `saving.rs`
|
||||||
and `ops.rs`.
|
and `ops.rs`.
|
||||||
|
|
||||||
**Slice 7, backups and restore.** `ledger_store::backup`, `Root::restore`,
|
**Slice 7, backups and restore.** (Rewritten for the plain-folder form,
|
||||||
`ledger-mcp` `backup.rs` and `tools/backup.rs`, the loop in `local.rs`:
|
D-91: see "Backups in plain folders" below; the git form's tests are gone and
|
||||||
`ledger-cli/tests/backups.rs` (17: both targets after a write, the quiet
|
the table there says what holds each promise now.) `ledger_store::backup`,
|
||||||
before a backup, close and catching up at the next open, admin only and
|
`Root::restore`, `ledger-mcp` `backup.rs` and `tools/backup.rs`, the loop in
|
||||||
the head unmoved, a target that moved on, a failing target waiting while
|
`local.rs`: `ledger-cli/tests/backups.rs` (18: the folder after a write, the
|
||||||
the others carry on, a damaged record, restore beside and on a clean
|
quiet before a backup, close and catching up at the next open, admin only and
|
||||||
install, of the previewed backup only, with its vault and key, refusing
|
the head unmoved, another history never written over, restore beside and on a
|
||||||
damage, never overwriting, a failed replace, a restored copy leaving its
|
clean install, of the previewed backup only, with its vault and key, refusing
|
||||||
original's repository alone, a backup folder never made again, drills on
|
damage, never overwriting, a failed replace, a backup folder never made again,
|
||||||
open and a failed drill flagged), `open_while_held.rs` (`books restore`
|
drills on open and a failed drill flagged, old settings and an old history left
|
||||||
and its default id), `backup.rs`'s unit tests (20, among them links and
|
alone and said, a clone of an old backup adopted), `open_while_held.rs`
|
||||||
strangers refused before checkout, target and archive hooks never run, the
|
(`books restore` and its default id), `tests/root.rs` (never moving books
|
||||||
owner's hostile git configuration never spoiling a backup, repositories
|
something holds).
|
||||||
with settings of their own or something beside them refused, fake gits
|
|
||||||
for the time limit and the process group), `tests/root.rs` (never moving
|
|
||||||
books something holds). Five review rounds (about 25, 15, 10, 7 and 3
|
|
||||||
findings, all fixed) and a sixth that only attacked the repository guard
|
|
||||||
(one low finding, fixed). The backup suite passed every run three at a
|
|
||||||
time.
|
|
||||||
|
|
||||||
**Slice 8, the viewer's menu, setup, no confinement (D-32).**
|
**Slice 8, the viewer's menu, setup, no confinement (D-32).**
|
||||||
`ledger-gui/tests/owner_menu.rs` (each item through a fake owner, the
|
`ledger-gui/tests/owner_menu.rs` (each item through a fake owner, the
|
||||||
@@ -1557,23 +1551,20 @@ version's journal format (BS-format-1). Mutation testing waits for P12
|
|||||||
books' file named for its schema. Checked by breaking it (the legacy
|
books' file named for its schema. Checked by breaking it (the legacy
|
||||||
file always taken, the schema check dropped): three tests fail. The
|
file always taken, the schema check dropped): three tests fail. The
|
||||||
store's other tests use `db_file()`, this version's file.
|
store's other tests use `db_file()`, this version's file.
|
||||||
- `ledger-store` `backup.rs`: `the_archive_proves_to_hold_the_book_as_it_is_keys_and_all`
|
- `ledger-store` `tests/backup.rs`: `the_local_backup_proves_to_hold_the_book_as_it_is_keys_and_all`
|
||||||
(a changed or extra key, a changed vault record, books that moved on, a
|
(a changed or extra key, a changed vault record, books that moved on:
|
||||||
journal changed under the recorded head: each refused; the scratch
|
each refused; the scratch folder always removed).
|
||||||
folder always removed).
|
|
||||||
- `ledger-mcp` `local.rs`: `format_upgrade_waits_for_consent` (listed as
|
- `ledger-mcp` `local.rs`: `format_upgrade_waits_for_consent` (listed as
|
||||||
waiting; no passphrase set, a wrong one or none refused before anything
|
waiting; no passphrase set, a wrong one or none refused before anything
|
||||||
is done, no backup, no line, still served; with it, the backup is the
|
is done, no backup, no line, still served; with it, the backup is the
|
||||||
archive's latest commit, holding the journal as it was and the key; one
|
local backup's latest, holding the journal as it was and the key; one
|
||||||
line, the whole format; on the backup record; again, nothing; new books
|
line, the whole format; on the backup record; again, nothing; new books
|
||||||
wait for nothing, and asking for their upgrade makes not even a backup
|
wait for nothing, and asking for their upgrade makes not even a local
|
||||||
repository), `no_upgrade_without_a_backup` (a backup refused: nothing
|
backup), `no_upgrade_without_a_backup` (a backup refused: nothing
|
||||||
upgraded, still waiting, recorded) and
|
upgraded, still waiting, recorded) and
|
||||||
`no_upgrade_unless_the_backup_just_made_is_proven` (an archive whose
|
`no_upgrade_unless_the_backup_is_proven` (a local backup with a piece
|
||||||
head names another branch takes the commit where no clone finds it:
|
damaged proves nothing whole: nothing upgraded, recorded; put right, the
|
||||||
what is proven isn't what was made, nothing upgraded, both recorded;
|
backup, which already holds the books, is proven and the upgrade made). Each checked by breaking the code it guards (the
|
||||||
put right, the latest commit, which already holds the books, is proven
|
|
||||||
and the upgrade made). Each checked by breaking the code it guards (the
|
|
||||||
proof skipped, the made-is-proven check dropped, the early return for
|
proof skipped, the made-is-proven check dropped, the early return for
|
||||||
books that wait for nothing removed): the test fails, then passes once
|
books that wait for nothing removed): the test fails, then passes once
|
||||||
restored.
|
restored.
|
||||||
@@ -1610,8 +1601,7 @@ version's journal format (BS-format-1). Mutation testing waits for P12
|
|||||||
**For P12:** `ledger-store` `format.rs` (`current`, `upgrade_to`, `adds`,
|
**For P12:** `ledger-store` `format.rs` (`current`, `upgrade_to`, `adds`,
|
||||||
`require_format`, `require_feature`), `store.rs` (`create_in_format`,
|
`require_format`, `require_feature`), `store.rs` (`create_in_format`,
|
||||||
`ensure_format`, `ensure_feature`, `upgrade_format`), `root.rs`
|
`ensure_format`, `ensure_feature`, `upgrade_format`), `root.rs`
|
||||||
(adoption's upgrade and its verify), `backup.rs` (`prove_archive`,
|
(adoption's upgrade and its verify), `backup/read.rs` (`prove_local`); `ledger-mcp` `backup.rs` (`upgrade_format`,
|
||||||
`held_files`); `ledger-mcp` `backup.rs` (`upgrade_format`,
|
|
||||||
`UpgradeFailed::parts`), `local.rs` (`upgrade_format`, the List's
|
`UpgradeFailed::parts`), `local.rs` (`upgrade_format`, the List's
|
||||||
`format_upgrade`, `waiting`), `server.rs` (`with_store_mut`),
|
`format_upgrade`, `waiting`), `server.rs` (`with_store_mut`),
|
||||||
`tools/kept.rs` (the first next step, `format_upgrade`), `admin.rs`;
|
`tools/kept.rs` (the first next step, `format_upgrade`), `admin.rs`;
|
||||||
@@ -2321,7 +2311,7 @@ data root of its own, reached as an agent reaches it.
|
|||||||
each start, as a new server process read the same books, and lets a
|
each start, as a new server process read the same books, and lets a
|
||||||
test write books into the root before the first), the async rmcp
|
test write books into the root before the first), the async rmcp
|
||||||
`connect` and `call`, and `book_files` (the books' files but what every
|
`connect` and `call`, and `book_files` (the books' files but what every
|
||||||
call writes by design: the access log, `ops/`, `archive.git/`,
|
call writes by design: the access log, `ops/`, `local-backup/`,
|
||||||
`exports/`, `uploads/`, SQLite's -wal and -shm). Settings a test gives
|
`exports/`, `uploads/`, SQLite's -wal and -shm). Settings a test gives
|
||||||
as a settings file's text are set as an agent sets them: the changes
|
as a settings file's text are set as an agent sets them: the changes
|
||||||
`ledger_config::codec::import` reads from it, by `books.set_setting`.
|
`ledger_config::codec::import` reads from it, by `books.set_setting`.
|
||||||
@@ -4328,13 +4318,13 @@ one book never refuses or holds up a call on another.
|
|||||||
| `book_open_close::the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time` | one upload stalled on one book and one MCP body stalled on another, the server's stdin closed: exit code 0 within the bound, both cut after the grace, no part file, nothing journaled, two `cut_by_close` records, every log whole |
|
| `book_open_close::the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time` | one upload stalled on one book and one MCP body stalled on another, the server's stdin closed: exit code 0 within the bound, both cut after the grace, no part file, nothing journaled, two `cut_by_close` records, every log whole |
|
||||||
| `book_open_close::a_backup_and_a_sweep_that_took_their_handles_before_a_close_do_nothing_after_it`, `…a_drill_and_a_sweep…` | `--timer-hold` holds a timer between taking a book's handles and acting; the book is closed meanwhile, stray files planted, the timers go on: the closed book's tree doesn't move; opened again the sweep works (fail with the handles' closed state, the gate's check and the backups' shut flag removed) |
|
| `book_open_close::a_backup_and_a_sweep_that_took_their_handles_before_a_close_do_nothing_after_it`, `…a_drill_and_a_sweep…` | `--timer-hold` holds a timer between taking a book's handles and acting; the book is closed meanwhile, stray files planted, the timers go on: the closed book's tree doesn't move; opened again the sweep works (fail with the handles' closed state, the gate's check and the backups' shut flag removed) |
|
||||||
| `book_open_close::a_close_stops_a_slow_drill_instead_of_waiting_for_it` | `--slow-steps` makes each phase of a drill wait a minute: the close answers plain `closed` (the last backup was made), within the stated sum, with the drill's scratch clone removed (fails without `hurry`: `closed_backup_incomplete`) |
|
| `book_open_close::a_close_stops_a_slow_drill_instead_of_waiting_for_it` | `--slow-steps` makes each phase of a drill wait a minute: the close answers plain `closed` (the last backup was made), within the stated sum, with the drill's scratch clone removed (fails without `hurry`: `closed_backup_incomplete`) |
|
||||||
| `book_open_close::a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds` | REAL git (a wrapper that points git's hooks at a `reference-transaction` hook that waits) stopped inside `init`, a commit and a push to a folder by a close: git is sent SIGTERM and removes its own locks, so none is left in the archive or the folder and the backup's record holds no `lock_removed` or `lock_left` (nothing for the server to clean up), the reopened book backs up with no step by hand, `git fsck --strict` passes on both |
|
| `book_open_close::a_close_is_not_answered_while_its_backup_still_runs` | a backup held at each phase (`--slow-steps` and the book's `ops/slow-backup` file) when a close begins: the close is answered at its bound, saying the backup wasn't whole; the destination still proves whole at its previous manifest and nothing in it or in the book moves after the answer, with the stall lifted |
|
||||||
| `local::tests::a_close_stops_a_format_upgrade_before_it_is_journaled` | an upgrade held in its backup's proof: the close stops it, it says nothing was upgraded, the journal is byte for byte as before |
|
| `local::tests::a_close_stops_a_format_upgrade_before_it_is_journaled` | an upgrade held in its backup's proof: the close stops it, it says nothing was upgraded, the journal is byte for byte as before |
|
||||||
| `local::tests::a_body_read_to_its_end_is_never_cut_and_one_not_yet_is` | the line of the cut: a body read to its end is never cut (the cut firing, the body asked again), one not read to its end is cut even with bytes on the way |
|
| `local::tests::a_body_read_to_its_end_is_never_cut_and_one_not_yet_is` | the line of the cut: a body read to its end is never cut (the cut firing, the body asked again), one not read to its end is cut even with bytes on the way |
|
||||||
| `ledger-store` `backup::tests::a_git_stopped_by_sigterm_mid_commit_…`, `…_stopped_mid_add_…`, `a_push_stopped_by_sigterm_…`, `a_git_that_ignores_sigterm_…`, `a_git_that_cannot_end_on_sigterm_…`, `a_lock_left_in_a_folder_target_…`, `a_push_stopped_during_the_pack_transfer_…`, `the_archives_age_rule_at_open`, `removal_after_a_stop_goes_through_the_handle_…`, `git_locks::tests` (3) | REAL git stopped inside a commit (HEAD and ref locks), an add (the index lock) and a push to a folder (the target's ref lock): on SIGTERM it removes its own locks and nothing is noted (the grace is long, so a git that needed the kill would show); a git whose group is frozen (SIGSTOP, so SIGTERM stays pending) is killed only after the grace, and the archive's locks it left (not there when the command began) are removed, noted; the folder target's lock is NEVER removed, reported with its whole path (`LockLeft`, `lock_left` with `path`), a lock that was there before the push is untouched and not named, a later push fails by git's words and removes nothing, the next one passes once the test removes the file; a fake git that traps SIGTERM is sent it first (marker) and killed after the grace with all it started; a 48 MiB pack held in the receiving end's `pre-receive` hook (the target's `incoming-` quarantine present) stopped by SIGTERM and by the kill, `git fsck --strict` on both repositories at once; the archive's locks at open: older than ten minutes removed and noted, younger left and said, non-lock names, folders and links untouched; a swapped `refs` folder or archive path after the handle was opened touches nothing outside; the handle module: exact lock names only, regular files only, no link followed |
|
| `ledger-store` `tests/backup.rs` `a_program_that_dies_at_any_write_leaves_what_proved_whole_before`, `a_stopped_backup_leaves_what_proved_whole_before` | a death at each of a backup's write points, and a stop asked before it: what is left proves whole at the previous manifest or the new one, and the next run goes on (replaces the tests of a git stopped by SIGTERM or killed, and of the locks it left) |
|
||||||
| `ledger-store` `backup::tests::a_drill_stops_inside_the_phase_it_is_told_to_stop_in` | for each phase (clone, replay, verify, blobs, prefix) a stop set as the phase begins ends the drill inside it (the observer sees no later phase), scratch removed; each case fails when the loop's looks inside that phase are removed |
|
| `ledger-store` `tests/backup.rs` `a_drill_stops_inside_the_phase_it_is_told_to_stop_in` | for each phase (fetch, replay, verify, blobs, vault, prefix) a stop set as the phase begins ends the drill inside it (the observer sees no later phase), scratch removed |
|
||||||
| `book_open_close::a_running_call_is_never_cut_when_the_grace_runs_out` | an ordinary call (`books.attach_receipt`, held inside its read of its file, a named pipe) past the grace (body whole) is not cut: it finishes when fed, is answered and recorded `ok`, and then the close is answered (a backup asked for is no longer this call: it is stoppable) |
|
| `book_open_close::a_running_call_is_never_cut_when_the_grace_runs_out` | an ordinary call (`books.attach_receipt`, held inside its read of its file, a named pipe) past the grace (body whole) is not cut: it finishes when fed, is answered and recorded `ok`, and then the close is answered (a backup asked for is no longer this call: it is stoppable) |
|
||||||
| `book_open_close::a_close_stops_a_running_backup_call_and_says_so` | `books.back_up_now` held in a stalled `git` (never lifted until the call answers): the close stops it, the call is answered that it was stopped because the books are closing, its access record is `refused: stopped_by_close` with no head, the backup record holds `stopped` and no result of its own for the run, git and all it started are gone, the close's last backup is made and the close answers `closed` |
|
| `book_open_close::a_close_stops_a_running_backup_call_and_says_so` | `books.back_up_now` held at a phase of its copy (never lifted until the call answers): the close stops it, the call is answered that it was stopped because the books are closing, its access record is `refused: stopped_by_close` with no head, the backup record says `stopped` and no result of the run's own; the close's own last backup is made as always |
|
||||||
| `book_open_close::a_close_stops_a_running_verification_and_a_running_package_and_says_so` | `books.verify` and `books.export_cpa_package` held as they begin by `--timer-hold` (`call:...`), which the close releases: each is stopped at its first look, answers it was stopped, is recorded `refused: stopped_by_close`, the journal is unchanged |
|
| `book_open_close::a_close_stops_a_running_verification_and_a_running_package_and_says_so` | `books.verify` and `books.export_cpa_package` held as they begin by `--timer-hold` (`call:...`), which the close releases: each is stopped at its first look, answers it was stopped, is recorded `refused: stopped_by_close`, the journal is unchanged |
|
||||||
| `book_open_close::a_close_stops_the_restore_and_the_open_of_its_own_book_leaving_the_root_as_it_was` | a restore over a book and the open of a book, each held inside a phase (`restore:copy`, `open:start`): its scratch or staging folder is there while held; a close of THAT book stops it, it answers it was stopped, the root's `books/` and `legacy/` are byte for byte as before; asked again it goes through |
|
| `book_open_close::a_close_stops_the_restore_and_the_open_of_its_own_book_leaving_the_root_as_it_was` | a restore over a book and the open of a book, each held inside a phase (`restore:copy`, `open:start`): its scratch or staging folder is there while held; a close of THAT book stops it, it answers it was stopped, the root's `books/` and `legacy/` are byte for byte as before; asked again it goes through |
|
||||||
| `book_open_close::the_servers_close_stops_every_running_admin_job_leaving_the_root_as_it_was` | restore (a new book, and over `acme`), adopt, create and open, each held inside a phase, the server closed with nothing lifting the hold: each answers it was stopped, the root as it was, exit 0; asked again on a new server the first goes through |
|
| `book_open_close::the_servers_close_stops_every_running_admin_job_leaving_the_root_as_it_was` | restore (a new book, and over `acme`), adopt, create and open, each held inside a phase, the server closed with nothing lifting the hold: each answers it was stopped, the root as it was, exit 0; asked again on a new server the first goes through |
|
||||||
@@ -4343,10 +4333,9 @@ one book never refuses or holds up a call on another.
|
|||||||
| `ledger-store` `tests/root.rs::a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_it_was` | create, adopt, restore (over existing books) and the restore preview stopped at each phase they ask: `Stopped`, the root (`books/`, `legacy/`) byte for byte as before; never stopped, `place` is the last phase asked (nothing after the point of no return) |
|
| `ledger-store` `tests/root.rs::a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_it_was` | create, adopt, restore (over existing books) and the restore preview stopped at each phase they ask: `Stopped`, the root (`books/`, `legacy/`) byte for byte as before; never stopped, `place` is the last phase asked (nothing after the point of no return) |
|
||||||
| `ledger-store` `tests/root.rs::an_adoption_that_does_not_finish_leaves_no_lock_file_in_the_source` | a source with no lock file: the adoption stopped at each of its seven phases, refused after taking the lock (a stale preview head), and panicking in the middle leaves the source folder name for name, byte for byte and mode for mode as it was; a lock file swapped in by someone else during the adoption is not removed; a source that had its lock keeps it (stopped or adopted, `source_lock_created` false); a success of a source with none leaves the one it made and says so. Mutation: no removal fails it |
|
| `ledger-store` `tests/root.rs::an_adoption_that_does_not_finish_leaves_no_lock_file_in_the_source` | a source with no lock file: the adoption stopped at each of its seven phases, refused after taking the lock (a stale preview head), and panicking in the middle leaves the source folder name for name, byte for byte and mode for mode as it was; a lock file swapped in by someone else during the adoption is not removed; a source that had its lock keeps it (stopped or adopted, `source_lock_created` false); a success of a source with none leaves the one it made and says so. Mutation: no removal fails it |
|
||||||
| `ledger-store` `tests/root.rs::a_job_waiting_for_its_turn_stops_when_asked_and_otherwise_waits_for_it` | the turn at making books held (as another process would): a create that isn't asked to stop waits, and stops within seconds once asked (`Stopped`, nothing made); not asked, it goes through when the turn is let go. Mutation: a blocking wait for the turn fails it |
|
| `ledger-store` `tests/root.rs::a_job_waiting_for_its_turn_stops_when_asked_and_otherwise_waits_for_it` | the turn at making books held (as another process would): a create that isn't asked to stop waits, and stops within seconds once asked (`Stopped`, nothing made); not asked, it goes through when the turn is let go. Mutation: a blocking wait for the turn fails it |
|
||||||
| `book_open_close::a_lock_a_kill_leaves_in_the_backup_folder_is_reported_and_never_removed_by_the_server` | REAL git in a push to a folder with its group frozen, so only the kill after the grace ends it: the lock it leaves is still there after the close, recorded `lock_left` with its whole path, no `lock_removed` for the folder, the close's answer and `books.backup` name the file and say when it may be removed, a lock that was there before is neither touched nor named, a later backup fails by git's words and removes nothing, and once the file is removed the backup goes on, `git fsck --strict` on both |
|
|
||||||
| `book_open_close::a_call_whose_answer_was_never_read_is_on_record_as_having_run` | a journaled draft whose client goes without reading: after the close the access log has its record, outcome `ok`, with the head it wrote (INVARIANT 14: a retry isn't made safe by anything; the record says it ran) |
|
| `book_open_close::a_call_whose_answer_was_never_read_is_on_record_as_having_run` | a journaled draft whose client goes without reading: after the close the access log has its record, outcome `ok`, with the head it wrote (INVARIANT 14: a retry isn't made safe by anything; the record says it ran) |
|
||||||
| `book_open_close::a_close_is_not_answered_while_its_backup_still_runs` | a book with a folder target and a stand-in `git` on the server's PATH that waits: the close isn't answered before its backup bound (1.2 s), then answers `closed_backup_incomplete`, git and all it started are gone, and lifting the stall makes nothing resume; the reopened book's backup record is a whole chain and it backs up (fails when `shut` is removed: git still runs after the answer) |
|
| `book_open_close::a_close_is_not_answered_while_its_backup_still_runs` | a book with a backup folder whose backup waits at each phase: the close isn't answered before its backup bound (1.2 s), then answers `closed_backup_incomplete`; the folder still proves whole at the backup before, and lifting the stall makes nothing resume; the reopened book's backup record is a whole chain and it backs up (fails when `shut` is removed: the copy still runs after the answer) |
|
||||||
| `book_open_close::a_close_whose_backup_fails_says_so_and_leaves_nothing_running` | a target whose disk isn't there: `closed_backup_incomplete` naming the failure, quickly, no git run afterwards; the same book with its disk back is answered plainly `closed` |
|
| `book_open_close::a_close_whose_backup_fails_says_so_and_leaves_nothing_running` | a target whose disk isn't there: `closed_backup_incomplete` naming the failure, quickly, nothing run afterwards; the same book with its disk back is answered plainly `closed` |
|
||||||
| `book_open_close::an_upload_in_flight_finishes_before_the_close_is_answered` | an upload half received when the close begins: the close isn't answered until it is complete (200), its bytes are kept, its record is written, no `.part` is left, nothing moves afterwards |
|
| `book_open_close::an_upload_in_flight_finishes_before_the_close_is_answered` | an upload half received when the close begins: the close isn't answered until it is complete (200), its bytes are kept, its record is written, no `.part` is left, nothing moves afterwards |
|
||||||
| `book_open_close::a_restore_over_an_open_book_waits_for_what_is_inside_it` | a replacing restore over a book with an upload half received isn't answered for five seconds (a restore that doesn't wait takes about one); the upload then completes, the replaced book's log in `legacy/` holds it, is whole, no `.part` is left in `legacy/`, and it stands still (fails when the restore lets the store go without the drain) |
|
| `book_open_close::a_restore_over_an_open_book_waits_for_what_is_inside_it` | a replacing restore over a book with an upload half received isn't answered for five seconds (a restore that doesn't wait takes about one); the upload then completes, the replaced book's log in `legacy/` holds it, is whole, no `.part` is left in `legacy/`, and it stands still (fails when the restore lets the store go without the drain) |
|
||||||
| `book_open_close::downloads_during_a_close_complete_or_are_refused` | four clients download a 300 KB file in a loop while the book closes: each answer is a whole 200 or a refusal, the number of 200s is the number of download records, and nothing moves after the answer |
|
| `book_open_close::downloads_during_a_close_complete_or_are_refused` | four clients download a 300 KB file in a loop while the book closes: each answer is a whole 200 or a refusal, the number of 200s is the number of download records, and nothing moves after the answer |
|
||||||
@@ -4901,7 +4890,7 @@ count.
|
|||||||
- [P3 format upgrade] `format.rs` (`current`, `upgrade_to`, `adds`,
|
- [P3 format upgrade] `format.rs` (`current`, `upgrade_to`, `adds`,
|
||||||
`require_format`, `require_feature`), `store.rs` (`create_in_format`,
|
`require_format`, `require_feature`), `store.rs` (`create_in_format`,
|
||||||
`ensure_format`, `ensure_feature`, `upgrade_format`), `root.rs` (adoption's
|
`ensure_format`, `ensure_feature`, `upgrade_format`), `root.rs` (adoption's
|
||||||
upgrade and its verify), `backup.rs` (`prove_archive`, `held_files`).
|
upgrade and its verify), `backup/read.rs` (`prove_local`).
|
||||||
- [P3 asset basis] `asset_basis_from_journal` (newer vs corrupt); the
|
- [P3 asset basis] `asset_basis_from_journal` (newer vs corrupt); the
|
||||||
projection loader's two key sets.
|
projection loader's two key sets.
|
||||||
- [P3 projects] `project_set_of` (newer vs corrupt); `Store::add_project`'s
|
- [P3 projects] `project_set_of` (newer vs corrupt); `Store::add_project`'s
|
||||||
@@ -5213,3 +5202,54 @@ count.
|
|||||||
`rule_for_refusal`'s new arms; `check_amount`'s `positive` flag; `derive`'s
|
`rule_for_refusal`'s new arms; `check_amount`'s `positive` flag; `derive`'s
|
||||||
`refusal_justified` arms, `Model::post`'s close, `signed`'s date window and
|
`refusal_justified` arms, `Model::post`'s close, `signed`'s date window and
|
||||||
`closings` flag, the accounting-equation check; the spec test's pin search.
|
`closings` flag, the accounting-equation check; the spec test's pin search.
|
||||||
|
|
||||||
|
|
||||||
|
## Backups in plain folders (P15 section 9, D-91, D-92)
|
||||||
|
|
||||||
|
The form is files written once (docs/backups.md), so what is tested is what
|
||||||
|
the files promise, in four layers.
|
||||||
|
|
||||||
|
- `ledger-store` `tests/backup.rs` (22 tests, about 35 s): the form on disk
|
||||||
|
and that a second backup only adds files; other or newer history never
|
||||||
|
written; a disk that is gone never made again; two writers; a loser of a
|
||||||
|
manifest number; a death at every write point of a second backup (the
|
||||||
|
program is made to die at each write point in turn: what is left restores,
|
||||||
|
and the next run goes on); a stop; a flipped, cut or emptied piece, sealed or
|
||||||
|
not; a damaged newest backup falling back to the one before and saying so; the
|
||||||
|
passphrase (counts and sizes only, a wrong one never yields books and is
|
||||||
|
told from damage, a changed one a new set beside the old, the key private);
|
||||||
|
the single file; the removed tests' promises (a purged vault, a scratch file
|
||||||
|
left behind, a stored file that doesn't match its name, a drill of this book's
|
||||||
|
history only, the local backup proof, a link never followed, a drill stopping
|
||||||
|
inside its phase).
|
||||||
|
- `ledger-store` `tests/backup_props.rs` (5 properties, 5 cases each, about
|
||||||
|
30 s): a destination only grows; the destination as of any manifest restores
|
||||||
|
to a prefix of the books; random interleavings of two writers; any flipped or
|
||||||
|
cut piece is found; no wrong passphrase yields books.
|
||||||
|
- `ledger-cli` `tests/backups.rs` and `tests/book_open_close.rs`: the server and
|
||||||
|
the admin socket on a real root of its own.
|
||||||
|
- `ledger-mcp` `backup.rs`, `local.rs` (the format upgrade's proven local
|
||||||
|
backup), `ledger-store` `tests/root.rs` (restore's phases).
|
||||||
|
|
||||||
|
What each removed test of the git form is now (git, its locks and its output
|
||||||
|
are gone; a promise is either held by a new test or named as gone):
|
||||||
|
|
||||||
|
| Removed | Now |
|
||||||
|
|---|---|
|
||||||
|
| `a_missing_git_says_how_to_get_it`, `the_mac_stub_is_not_a_git_until_the_developer_tools_are_there` | gone: nothing is installed for backups; `no_package_depends_on_another_program_for_backups` |
|
||||||
|
| `a_backup_is_the_book_and_proves_whole` | `a_backup_is_the_book_and_proves_whole` |
|
||||||
|
| `a_folder_targets_hooks_never_run`, `the_archives_own_hooks_never_run`, `the_owners_git_configuration_never_spoils_a_backup`, `no_attributes_rule_changes_a_byte`, `no_ignore_rule_leaves_a_file_out`, `a_file_git_wont_take_fails_the_backup`, `what_git_said_keeps_whole_lines_and_drops_its_progress`, `what_git_said_cut_short_ends_at_its_last_whole_line`, `local_addresses_are_told_from_networked_ones`, `a_repository_with_settings_of_its_own_is_never_pushed_to_or_read` | gone: no program runs, no rule or setting of anyone's can change a file, and there are no addresses; bytes are held by `any_whole_manifest_restores_a_prefix_of_the_books` |
|
||||||
|
| `a_target_that_moved_on_is_never_overwritten` | `a_destination_of_other_books_or_another_history_is_never_written` |
|
||||||
|
| `a_missing_folder_or_a_strange_address_is_said_plainly`, `a_backup_folder_gone_from_a_connected_disk_is_never_made_again` | `a_disk_that_is_gone_is_never_made_again_where_it_should_be` |
|
||||||
|
| `a_purged_vault_leaves_the_next_backup` | `a_purged_vault_leaves_the_next_backup_and_not_the_earlier_ones` |
|
||||||
|
| `a_lock_left_behind_never_stops_the_next_backup`, `the_archives_age_rule_at_open`, `removal_after_a_stop_goes_through_the_handle_opened_before_the_command`, `a_lock_left_in_a_folder_target_by_a_kill_is_never_removed_but_reported`, the `git_locks.rs` tests | gone: the form has no lock to leave; `a_scratch_file_left_by_a_dead_program_never_stops_the_next_backup` |
|
||||||
|
| `a_backup_with_a_changed_stored_file_or_a_busy_scratch_is_refused` | `a_stored_file_that_does_not_match_its_name_is_refused_and_nothing_is_written` |
|
||||||
|
| `a_drill_proves_this_books_history_only` | `a_drill_proves_this_books_history_only` |
|
||||||
|
| `the_archive_proves_to_hold_the_book_as_it_is_keys_and_all` | `the_local_backup_proves_to_hold_the_book_as_it_is_keys_and_all` |
|
||||||
|
| `a_backup_holding_a_link_or_a_stranger_is_refused_before_checkout` | `a_link_in_a_backup_is_never_followed`; the names in a manifest are checked on read |
|
||||||
|
| the five tests of a git stopped by SIGTERM, killed after the grace, left quiet or cancelled, and `a_push_stopped_during_the_pack_transfer_leaves_both_repositories_whole` | gone: no process is stopped; `a_program_that_dies_at_any_write_leaves_what_proved_whole_before`, `a_stopped_backup_leaves_what_proved_whole_before` |
|
||||||
|
| `a_drill_stops_inside_the_phase_it_is_told_to_stop_in` | `a_drill_stops_inside_the_phase_it_is_told_to_stop_in` |
|
||||||
|
| the `drain.rs` tests (a pipe another process holds) | gone: nothing is piped |
|
||||||
|
| `book_open_close` `a_close_that_stops_git_in_a_commit_or_a_push_...`, `a_lock_a_kill_leaves_in_the_backup_folder_is_reported_and_never_removed_by_the_server` | `a_close_is_not_answered_while_its_backup_still_runs`; the lock one is gone with locks |
|
||||||
|
| `ledger-cli` `backups.rs` `books_restored_beside_their_original_leave_its_repository_alone` | `restore_beside_existing_books_and_on_a_clean_install` (a copy backs up to a folder of its own) |
|
||||||
|
| `a_failing_target_waits_while_the_others_carry_on` | `a_failing_destination_is_not_tried_again_after_each_write` (one destination) |
|
||||||
Generated
+684
-12
File diff suppressed because it is too large.
Load diff
@@ -14,6 +14,7 @@ serde_json = "1"
|
|||||||
serde = "1"
|
serde = "1"
|
||||||
rust_decimal = "1"
|
rust_decimal = "1"
|
||||||
chrono = "0.4"
|
chrono = "0.4"
|
||||||
|
tempfile = "3"
|
||||||
|
|
||||||
[dependencies.ledger-core]
|
[dependencies.ledger-core]
|
||||||
path = "../crates/ledger-core"
|
path = "../crates/ledger-core"
|
||||||
@@ -61,6 +62,13 @@ test = false
|
|||||||
doc = false
|
doc = false
|
||||||
bench = false
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "fuzz_backup_read"
|
||||||
|
path = "fuzz_targets/fuzz_backup_read.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "fuzz_store_open"
|
name = "fuzz_store_open"
|
||||||
path = "fuzz_targets/fuzz_store_open.rs"
|
path = "fuzz_targets/fuzz_store_open.rs"
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
// Fuzz target: a backup folder is read from a disk someone else may have
|
||||||
|
// written (a sync service's, another computer's, a damaged one), so every
|
||||||
|
// file of it is untrusted input: the manifest, the header, a piece. Finding
|
||||||
|
// and proving a backup must return books or an error, never panic or hang,
|
||||||
|
// and it must never accept what is not whole.
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
fn put(root: &Path, rel: &str, bytes: &[u8]) {
|
||||||
|
let p = root.join(rel);
|
||||||
|
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(p, bytes).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
// The input is split in three: a manifest, a header and a piece.
|
||||||
|
let third = data.len() / 3;
|
||||||
|
let (manifest, rest) = data.split_at(third);
|
||||||
|
let (header, piece) = rest.split_at(third.min(rest.len()));
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let set = dir.path().join("acme");
|
||||||
|
put(&set, "manifests/000001.json", manifest);
|
||||||
|
put(&set, "manifests/000001", manifest);
|
||||||
|
put(&set, "header.json", header);
|
||||||
|
put(&set, "journal/000001-0000000000000000", piece);
|
||||||
|
put(&set, "pieces/00", piece);
|
||||||
|
let ctx = ledger_store::backup::Ctx::new();
|
||||||
|
for pass in [None, Some("a passphrase of enough length")] {
|
||||||
|
if let Ok(found) = ledger_store::backup::find(dir.path(), pass, &ctx) {
|
||||||
|
let scratch = dir.path().join("scratch");
|
||||||
|
// Whatever a manifest claims, what is made of this input must
|
||||||
|
// fail: nothing in it is a whole backup.
|
||||||
|
let proven = ledger_store::backup::verify_found(&found, &scratch, &ctx);
|
||||||
|
assert!(proven.is_err(), "random bytes proved whole");
|
||||||
|
let _ = std::fs::remove_dir_all(&scratch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"format":"wanderbooks-backup"}
|
||||||
+22
-5
@@ -1,5 +1,24 @@
|
|||||||
# STATUS — 2026-11-10: the evaluation batch: no money arithmetic outside the kernel in any crate, exact Decimal sums, four gates the build did not have
|
# STATUS — 2026-11-10: the evaluation batch: no money arithmetic outside the kernel in any crate, exact Decimal sums, four gates the build did not have
|
||||||
|
|
||||||
|
## 2026-11-21: backups without git (plan/p15-app-and-relay.md section 9, D-91, D-92)
|
||||||
|
|
||||||
|
Written on Linux; **nothing of the window's part, and nothing on Windows or
|
||||||
|
macOS, has run**. A backup is now a folder of plain files written once
|
||||||
|
(`docs/backups.md`, claims `WB-backup-1` to `WB-backup-11` in
|
||||||
|
`docs/spec/claims/backup.md`); git, its processes, locks and output handling
|
||||||
|
are gone from the program, from the packages and from every word a person or an
|
||||||
|
assistant reads. What is there: the form and its writer, reader, proof, drill and
|
||||||
|
restore (`crates/ledger-store/src/backup/`); the passphrase (Argon2id at the owner
|
||||||
|
passphrase's cost, XChaCha20-Poly1305 in chunks; the key in the book's `local/`
|
||||||
|
folder); "Save a backup" as one `.wbbackup` file (a zip); the server's backups on
|
||||||
|
the new form (`crates/ledger-mcp/src/backup.rs`); the proven local backup before
|
||||||
|
a format upgrade (`local-backup/` in the book's folder); old settings and an old
|
||||||
|
history left alone and said. Property tests, death-at-every-write tests and the
|
||||||
|
removed git tests' table are in `docs/testing.md`. **Owner's, open:** the
|
||||||
|
window's folder chooser, passphrase set-up and status words (see the report of
|
||||||
|
the unit); a first run on Windows and macOS; segment consolidation is only a
|
||||||
|
size rule (200 segments), never tried at scale.
|
||||||
|
|
||||||
## 2026-11-21: P15 unit C1, the installed app (branch `t3/p15-c1-desktop-packages`)
|
## 2026-11-21: P15 unit C1, the installed app (branch `t3/p15-c1-desktop-packages`)
|
||||||
|
|
||||||
Written on Linux; **nothing of it has run on Windows or macOS**, and no
|
Written on Linux; **nothing of it has run on Windows or macOS**, and no
|
||||||
@@ -15,8 +34,8 @@ claims `WB-pkg-1` to `WB-pkg-8` in `docs/spec/claims/packaging.md`):
|
|||||||
entitlements file with the reasons, a Documents-folder purpose string);
|
entitlements file with the reasons, a Documents-folder purpose string);
|
||||||
signing and notarization run only with the owner's Apple secrets.
|
signing and notarization run only with the owner's Apple secrets.
|
||||||
- **Linux**: the tools are unchanged; the desktop entries carry the icon and
|
- **Linux**: the tools are unchanged; the desktop entries carry the icon and
|
||||||
the window's app id, every package carries the licences, and the packages
|
the window's app id, every package carries the licences (the packages no longer
|
||||||
depend on git.
|
depend on git: backups are plain files, D-91).
|
||||||
- **The Claude desktop extension**: the Connect page's last row writes a
|
- **The Claude desktop extension**: the Connect page's last row writes a
|
||||||
`.mcpb` (Anthropic's MCP Bundle, manifest 0.3) per company.
|
`.mcpb` (Anthropic's MCP Bundle, manifest 0.3) per company.
|
||||||
- **Update**: the window says when a newer version exists and where to get it
|
- **Update**: the window says when a newer version exists and where to get it
|
||||||
@@ -24,9 +43,7 @@ claims `WB-pkg-1` to `WB-pkg-8` in `docs/spec/claims/packaging.md`):
|
|||||||
is the newer package installed over the old.
|
is the newer package installed over the old.
|
||||||
- **Release**: a draft only, tests on each system, SHA-256 sums, licences;
|
- **Release**: a draft only, tests on each system, SHA-256 sums, licences;
|
||||||
the apt/dnf publish moved to a by-hand workflow.
|
the apt/dnf publish moved to a by-hand workflow.
|
||||||
- **Owner's, open**: signing identities and their secrets; whether to bundle
|
- **Owner's, open**: signing identities and their secrets; the first run of the release workflow on GitHub and the first install on a
|
||||||
git on Windows and macOS (a GPL-2.0 consequence, `docs/packaging.md`);
|
|
||||||
the first run of the release workflow on GitHub and the first install on a
|
|
||||||
clean Windows and macOS machine.
|
clean Windows and macOS machine.
|
||||||
|
|
||||||
## 2026-11-10: the evaluation batch (plan/2026-11-09_TRIAGE.md)
|
## 2026-11-10: the evaluation batch (plan/2026-11-09_TRIAGE.md)
|
||||||
|
|||||||
@@ -624,3 +624,71 @@ The form (the lead's design; the unit may refine it and must say where):
|
|||||||
touched. A person restoring from one clones it with git themselves and
|
touched. A person restoring from one clones it with git themselves and
|
||||||
uses the existing adopt of a plain folder; the docs say how. A books'
|
uses the existing adopt of a plain folder; the docs say how. A books'
|
||||||
old `backup.git_remote` setting is reported as no longer used.
|
old `backup.git_remote` setting is reported as no longer used.
|
||||||
|
|
||||||
|
**Built (2026-11-21): where the build refined this section.** The code is
|
||||||
|
`crates/ledger-store/src/backup/` and `crates/ledger-mcp/src/backup.rs`; the
|
||||||
|
rules are `docs/spec/claims/backup.md`; the words for a person are
|
||||||
|
`docs/backups.md`.
|
||||||
|
|
||||||
|
- The store's lock is held only to take a *cut* (the journal's length and head,
|
||||||
|
the vault, the keys): the files are read after it, which is safe because the
|
||||||
|
journal is append-only and a stored file never changes. Section 9 said "under
|
||||||
|
the store's lock exactly where the commit was taken"; the commit is gone and
|
||||||
|
so is the local copy it wrote, so no slow disk is ever under the lock. The
|
||||||
|
local copy exists only for the format upgrade (`local-backup/`).
|
||||||
|
- A destination is tested for being "a point on the live journal" by the
|
||||||
|
byte-identity of the journal prefix its newest manifest names (a SHA-256 of
|
||||||
|
those bytes), which says more than the head at a sequence number.
|
||||||
|
- Series of segments are consolidated into one segment when they reach 200, so
|
||||||
|
a manifest stays small however long the books have been backed up; the old
|
||||||
|
segments stay (nothing is deleted).
|
||||||
|
- A passphrase is not a journal setting: the key is the book's local file, and a
|
||||||
|
sealed destination is a set of its own beside any plain one, so no journal
|
||||||
|
feature and no format upgrade is needed.
|
||||||
|
- Sealed sets are folders named by a random id, so a sealed destination's names
|
||||||
|
say nothing of the books; restore finds the one a passphrase opens.
|
||||||
|
|
||||||
|
**Second pass (2026-11-22): what a review of the built unit found, and what the
|
||||||
|
fix round changed.** A backup that restores old or wrong books while reporting
|
||||||
|
good is the worst defect this product can have, and the first build could.
|
||||||
|
Changes to what this section says:
|
||||||
|
|
||||||
|
- *A proof after every backup* (promised above, and now made). The manifest just
|
||||||
|
put is read back from the destination and proven before the backup is recorded
|
||||||
|
good: every journal and access segment re-hashed, the chain replayed to the
|
||||||
|
recorded head, the books opened, the vault and keys present, the index read, and
|
||||||
|
of the stored files those the backup added plus one sixteenth of the rest (every
|
||||||
|
stored file is re-read within 16 backups; the weekly drill re-reads all). The
|
||||||
|
proof is marked in the destination, a tiny file per proven manifest (`proofs/`),
|
||||||
|
so one cut short is proven by the next backup even when it has nothing new.
|
||||||
|
- *A piece already there is not trusted.* A damaged piece found by the proof is
|
||||||
|
written again under a generation suffix (`.g1`) beside it, a new manifest names
|
||||||
|
it, and the reader takes any generation whose contents hash right: "nothing is
|
||||||
|
rewritten or deleted" holds, the damaged file stays and is listed in the status.
|
||||||
|
- *The drill passes only on the newest manifest*, which must reach the last head
|
||||||
|
recorded good; proving an older one is a failure in words, never ok. A restore
|
||||||
|
that would use anything but the newest says so first, with both dates and how
|
||||||
|
many backups it passes over.
|
||||||
|
- *No consolidation.* "Series of segments are consolidated into one at 200" above
|
||||||
|
is withdrawn: it wrote the whole journal, access log and index again every 200
|
||||||
|
backups into what may be a quota-limited synced folder. A manifest instead names
|
||||||
|
the one before it (by number and body hash) and what is new, a chain of at most
|
||||||
|
64 and then one that names everything; a reader proves the chain link by link and
|
||||||
|
never trusts an unproven one. 3,000 backups: 12 MB of manifests (765 MB if each
|
||||||
|
named everything), the newest 0.8 KB, found and read in 32 ms.
|
||||||
|
- *Ahead is told from diverged.* The live journal is checked to be the beginning
|
||||||
|
of a longer destination before it is called ahead; ahead offers, at the person's
|
||||||
|
request, a new set beside the old (`.2`), which is never touched.
|
||||||
|
- *A set's folder is `wanderbooks-` and the id* (legal on every system whatever
|
||||||
|
the id), sealed pieces are in folders of two digits, a failed link is never
|
||||||
|
taken to mean "make no links" unless the error says so (and then the move
|
||||||
|
refuses to replace), header settings are capped at four times ours and bound
|
||||||
|
into the sealed check, and the vault's scratch files are never backed up as
|
||||||
|
records.
|
||||||
|
- *A lost key never makes backups plain*, and a folder a sync service keeps (or
|
||||||
|
may) is explained at set-up; a file not downloaded yet reads as such.
|
||||||
|
|
||||||
|
Where the lead's design said "each manifest stands alone", it now stands alone
|
||||||
|
only as far as its chain: a lost manifest makes unreadable the manifests chained
|
||||||
|
on it (at most the rest of 64), never an earlier one.
|
||||||
|
|
||||||
+2
-2
@@ -211,7 +211,7 @@ footer { padding: 72px 0 48px; color: var(--faint); font-size: 14px; display: fl
|
|||||||
<p class="sub">QuickBooks rents you access to your own financial history, raises the rent every year, and makes leaving painful. You still do the bookkeeping yourself, in forms. wanderbooks turns that around.</p>
|
<p class="sub">QuickBooks rents you access to your own financial history, raises the rent every year, and makes leaving painful. You still do the bookkeeping yourself, in forms. wanderbooks turns that around.</p>
|
||||||
<table class="vs">
|
<table class="vs">
|
||||||
<tr><th></th><th>wanderbooks</th><th>QuickBooks Online</th></tr>
|
<tr><th></th><th>wanderbooks</th><th>QuickBooks Online</th></tr>
|
||||||
<tr><td>Where your books live</td><td>A folder on your computer, under git. Plain, documented files.</td><td>Intuit's servers. You get access while you pay.</td></tr>
|
<tr><td>Where your books live</td><td>A folder on your computer. Plain, documented files.</td><td>Intuit's servers. You get access while you pay.</td></tr>
|
||||||
<tr><td>What it costs</td><td>Nothing. Free and open source, forever. It runs on the Claude or ChatGPT plan you already have.</td><td>A monthly subscription per company, and the price keeps rising.</td></tr>
|
<tr><td>What it costs</td><td>Nothing. Free and open source, forever. It runs on the Claude or ChatGPT plan you already have.</td><td>A monthly subscription per company, and the price keeps rising.</td></tr>
|
||||||
<tr><td>Who does the bookkeeping</td><td>An AI bookkeeper: receipts, entries, categories, fixes, closes.</td><td>You do, in screens and forms. Or you pay someone.</td></tr>
|
<tr><td>Who does the bookkeeping</td><td>An AI bookkeeper: receipts, entries, categories, fixes, closes.</td><td>You do, in screens and forms. Or you pay someone.</td></tr>
|
||||||
<tr><td>Receipts</td><td>Required over a threshold you set, enforced on every entry, shown right beside it.</td><td>Optional attachments.</td></tr>
|
<tr><td>Receipts</td><td>Required over a threshold you set, enforced on every entry, shown right beside it.</td><td>Optional attachments.</td></tr>
|
||||||
@@ -304,7 +304,7 @@ footer { padding: 72px 0 48px; color: var(--faint); font-size: 14px; display: fl
|
|||||||
<details><summary>Wait, what's an MCP server?</summary><p>MCP is the standard way AI tools like Claude Code and Codex plug into other software. wanderbooks is an accounting engine that speaks it: your AI calls its tools to draft entries, attach receipts, and run reports, and the engine enforces the accounting rules. The one-line installer sets it up; you never have to touch it.</p></details>
|
<details><summary>Wait, what's an MCP server?</summary><p>MCP is the standard way AI tools like Claude Code and Codex plug into other software. wanderbooks is an accounting engine that speaks it: your AI calls its tools to draft entries, attach receipts, and run reports, and the engine enforces the accounting rules. The one-line installer sets it up; you never have to touch it.</p></details>
|
||||||
<details><summary>Do I need to be technical?</summary><p>You need to paste one command into a terminal, once. After that you talk to your bookkeeper in plain English, in Claude Code or Codex, and look at your books in the viewer whenever you like.</p></details>
|
<details><summary>Do I need to be technical?</summary><p>You need to paste one command into a terminal, once. After that you talk to your bookkeeper in plain English, in Claude Code or Codex, and look at your books in the viewer whenever you like.</p></details>
|
||||||
<details><summary>How does it find my receipts?</summary><p>Give your AI access to your email (in Claude, an email connector like Gmail's or the Claude browser extension with your mail open) and ask. It searches for the vendor and amount, files one clean PDF per receipt, and attaches it to the entry. It asks before downloading anything, and it never types passwords or account numbers.</p></details>
|
<details><summary>How does it find my receipts?</summary><p>Give your AI access to your email (in Claude, an email connector like Gmail's or the Claude browser extension with your mail open) and ask. It searches for the vendor and amount, files one clean PDF per receipt, and attaches it to the entry. It asks before downloading anything, and it never types passwords or account numbers.</p></details>
|
||||||
<details><summary>Where's my data, and what does the AI see?</summary><p>Your books are files in a private folder on your computer: a journal and your receipts. They back themselves up to a private git repository and a folder you choose. Nothing is uploaded to wanderbooks; there is no wanderbooks server. What your bookkeeper reads to help you goes to your AI provider (Anthropic or OpenAI), like any other conversation with it.</p></details>
|
<details><summary>Where's my data, and what does the AI see?</summary><p>Your books are files in a private folder on your computer: a journal and your receipts. They back themselves up to a folder you choose (another disk, or one your cloud drive keeps in sync), and you can protect that backup with a passphrase. Nothing is uploaded to wanderbooks; there is no wanderbooks server. What your bookkeeper reads to help you goes to your AI provider (Anthropic or OpenAI), like any other conversation with it.</p></details>
|
||||||
<details><summary>What if the AI gets something wrong?</summary><p>Every posting is previewed before it happens. If something slips through, it's corrected the way accountants do it, with a reversing entry, so the mistake and the fix are both on the record. The engine itself refuses anything that doesn't balance, anything without a required receipt, and anything in a closed period.</p></details>
|
<details><summary>What if the AI gets something wrong?</summary><p>Every posting is previewed before it happens. If something slips through, it's corrected the way accountants do it, with a reversing entry, so the mistake and the fix are both on the record. The engine itself refuses anything that doesn't balance, anything without a required receipt, and anything in a closed period.</p></details>
|
||||||
<details><summary>Is this real accounting, or a spreadsheet with an AI on top?</summary><p>Real double-entry accounting, with the rules enforced in code: exact decimal money, balanced entries, immutable posting, closes, depreciation, accrual or cash basis. Its statements are tested against hand-computed numbers, golden files, and property tests.</p></details>
|
<details><summary>Is this real accounting, or a spreadsheet with an AI on top?</summary><p>Real double-entry accounting, with the rules enforced in code: exact decimal money, balanced entries, immutable posting, closes, depreciation, accrual or cash basis. Its statements are tested against hand-computed numbers, golden files, and property tests.</p></details>
|
||||||
<details><summary>Can I bring my history from QuickBooks or a spreadsheet?</summary><p>Yes. Export your chart of accounts, journal, and reports, and ask your bookkeeper to move you over. It rebuilds the history and compares every statement against the old system, to the cent, before calling it done. Keep the old system read-only until you've closed a month in wanderbooks.</p></details>
|
<details><summary>Can I bring my history from QuickBooks or a spreadsheet?</summary><p>Yes. Export your chart of accounts, journal, and reports, and ask your bookkeeper to move you over. It rebuilds the history and compares every statement against the old system, to the cent, before calling it done. Keep the old system read-only until you've closed a month in wanderbooks.</p></details>
|
||||||
|
|||||||
Reference in new issue
Block a user