feat: the window and the command line set up, save and show backups; the system's folder dialog
Admin requests set up the backup folder (journaled as the books' own backup.folder setting, the owner the one who decided) and the passphrase, save a backup as one file, and say how the backups stand; the Backups window, Save a backup and Restore (a folder or a file, with the passphrase when it has one) use them, and the command line has backup-setup, backup-status and backup-save (the passphrase typed at a terminal, never on the command line). New dependency: rfd (MIT) in ledger-gui, with pollster, for the system's own folder and file dialogs (the portal on Linux, native on Windows and macOS). It adds no other crate to the tree (zbus is already there through the window toolkit); cargo deny passes and THIRD-PARTY-NOTICES.txt is regenerated. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
0720f3036d
commit
51a7607a82
11 files changed
+1214
-3
No files matched your search
@@ -147,6 +147,35 @@ pub enum Request {
|
||||
#[serde(default)]
|
||||
new_disk: bool,
|
||||
},
|
||||
/// 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).
|
||||
TokenCreate {
|
||||
/// The books it opens.
|
||||
@@ -709,6 +738,40 @@ pub struct BackedUpTarget {
|
||||
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>,
|
||||
}
|
||||
|
||||
/// The server's answer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", deny_unknown_fields)]
|
||||
@@ -739,6 +802,13 @@ pub enum Response {
|
||||
/// Each target.
|
||||
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).
|
||||
TokenCreated {
|
||||
/// The token.
|
||||
@@ -857,7 +927,11 @@ pub fn call_within(
|
||||
| Request::Sessions
|
||||
| Request::RemoteStatus
|
||||
| Request::RemotePending
|
||||
| Request::BackupStatus { .. }
|
||||
| Request::RemoteApprovals { .. } => None,
|
||||
Request::BackupSetup { .. } | Request::BackupSave { .. } => {
|
||||
Some("`wanderbooks books backup-status BOOK` says how the backups stand")
|
||||
}
|
||||
Request::RemoteStart { .. }
|
||||
| Request::RemoteStop
|
||||
| Request::RemoteAllow { .. }
|
||||
|
||||
@@ -922,6 +922,192 @@ impl Backups {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the window shows of a book's backups: the status, the folder the
|
||||
/// person chose (their own path, never one of the data root's), and whether
|
||||
/// the backups are protected by a passphrase.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Standing {
|
||||
/// How the folder stands.
|
||||
pub status: Status,
|
||||
/// The backup folder, if one is chosen.
|
||||
pub folder: Option<String>,
|
||||
/// Protected by a passphrase now.
|
||||
pub sealed: bool,
|
||||
}
|
||||
|
||||
impl Backups {
|
||||
/// What the window shows (read under the store's lock).
|
||||
pub async fn window_standing(&self) -> Standing {
|
||||
let store = self.store.clone();
|
||||
let (book, dir) = (self.book.clone(), self.dir.clone());
|
||||
let found = tokio::task::spawn_blocking(move || {
|
||||
store
|
||||
.with_store(|s| Standing {
|
||||
status: standing(s, &book, &dir),
|
||||
folder: s.ledger().settings().backup_folder().map(str::to_string),
|
||||
sealed: matches!(BackupKey::load(&dir), Ok(Some(_))),
|
||||
})
|
||||
.ok()
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
found.unwrap_or_else(|| Standing {
|
||||
status: standing_of(&[], &[], 0, chrono::Utc::now(), None),
|
||||
folder: None,
|
||||
sealed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Set up the backups (D-91, D-92), as the owner does it in the window:
|
||||
/// the folder (`folder`, journaled as the books' `backup.folder` setting,
|
||||
/// the owner the one who decided), and the passphrase (`passphrase`
|
||||
/// makes a new key, kept on this computer only: backups from the next on
|
||||
/// are sealed, in a set of their own beside any earlier one, which is
|
||||
/// untouched; `remove_passphrase` forgets the key: the next backup is
|
||||
/// plain). What was done, in words.
|
||||
pub async fn set_up(
|
||||
&self,
|
||||
folder: Option<String>,
|
||||
passphrase: Option<String>,
|
||||
remove_passphrase: bool,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let _one = self.running.lock().await;
|
||||
if self.is_shut() {
|
||||
return Err(SHUT.to_string());
|
||||
}
|
||||
let step = self.begin()?;
|
||||
let (store, dir) = (self.store.clone(), self.dir.clone());
|
||||
let done = tokio::task::spawn_blocking(move || -> Result<Vec<String>, String> {
|
||||
let _step = step;
|
||||
let mut lines = Vec::new();
|
||||
if let Some(folder) = folder.filter(|f| !f.trim().is_empty()) {
|
||||
let path = PathBuf::from(folder.trim());
|
||||
if !path.is_absolute() {
|
||||
return Err("the backup folder is named by its whole path".into());
|
||||
}
|
||||
if !path.is_dir() {
|
||||
return Err("that folder isn't there: choose a folder that exists".into());
|
||||
}
|
||||
if ledger_store::root::inside_a_root(&path) {
|
||||
return Err(format!(
|
||||
"that folder is inside {}: choose a folder somewhere else, on another disk if you can",
|
||||
ledger_store::root::THE_ROOT
|
||||
));
|
||||
}
|
||||
let change = ledger_core::settings::Change {
|
||||
key: "backup.folder".into(),
|
||||
value: Some(Value::String(path.display().to_string())),
|
||||
};
|
||||
let source = ledger_core::settings::Source {
|
||||
decided_by: "the owner, in the window".into(),
|
||||
decided_on: chrono::Utc::now().date_naive(),
|
||||
citation: None,
|
||||
note: Some("The backup folder.".into()),
|
||||
};
|
||||
let made = store
|
||||
.with_store_mut(|s| s.change_settings(&[change], &source))
|
||||
.map_err(|e| e.to_string())?
|
||||
.map_err(|e| e.to_string())?;
|
||||
lines.push(if made.is_empty() {
|
||||
"The backup folder is the one chosen already.".to_string()
|
||||
} else {
|
||||
"The backup folder is chosen: the books back themselves up there a little after each change, when they open and before they close.".to_string()
|
||||
});
|
||||
}
|
||||
if remove_passphrase && passphrase.is_some() {
|
||||
return Err("choose a passphrase or remove it, not both".into());
|
||||
}
|
||||
if let Some(p) = passphrase {
|
||||
let key = BackupKey::generate(&p).map_err(|e| e.to_string())?;
|
||||
key.store(&dir).map_err(|e| hide(&e.to_string(), &dir))?;
|
||||
lines.push("Backups are now protected by the passphrase: from the next backup on, every file in the backup folder is sealed. Backups made before stay as they were, unprotected, and are never deleted: delete their folder yourself if you want them gone. A forgotten passphrase cannot be recovered by anyone.".to_string());
|
||||
} else if remove_passphrase {
|
||||
BackupKey::forget(&dir).map_err(|e| hide(&e.to_string(), &dir))?;
|
||||
lines.push("The passphrase is taken off: from the next backup on, files are written without protection. Backups sealed before stay sealed with the passphrase they were made with.".to_string());
|
||||
}
|
||||
if lines.is_empty() {
|
||||
lines.push("Nothing was changed.".to_string());
|
||||
}
|
||||
Ok(lines)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| Err("the set-up stopped".into()));
|
||||
if let Ok(lines) = &done {
|
||||
self.record(json!({"kind": "setup", "lines": lines.len()}));
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
/// Save a backup as one file at `path` ("Save a backup..."): the same
|
||||
/// contents as the backup folder's, sealed when the backups are.
|
||||
pub async fn save_file(&self, path: &str) -> Result<Vec<String>, String> {
|
||||
let _one = self.running.lock().await;
|
||||
if self.is_shut() {
|
||||
return Err(SHUT.to_string());
|
||||
}
|
||||
if self.hurried() {
|
||||
return Err(self.stopped_words());
|
||||
}
|
||||
let mut file = PathBuf::from(path.trim());
|
||||
if !file.is_absolute() {
|
||||
return Err("the file is named by its whole path".into());
|
||||
}
|
||||
if file.extension().is_none_or(|e| e != backup::FILE_EXTENSION) {
|
||||
let mut name = file.file_name().unwrap_or_default().to_os_string();
|
||||
name.push(format!(".{}", backup::FILE_EXTENSION));
|
||||
file.set_file_name(name);
|
||||
}
|
||||
if file.parent().is_none_or(|p| !p.is_dir()) {
|
||||
return Err("the folder to save it in isn't there".into());
|
||||
}
|
||||
if ledger_store::root::inside_a_root(&file) {
|
||||
return Err(format!(
|
||||
"that is inside {}: save it somewhere else",
|
||||
ledger_store::root::THE_ROOT
|
||||
));
|
||||
}
|
||||
let step = self.begin()?;
|
||||
let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone());
|
||||
let ctx = self.ctx_for("asked");
|
||||
let sealed_to = file.clone();
|
||||
let saved = tokio::task::spawn_blocking(move || {
|
||||
let _step = step;
|
||||
let key = BackupKey::load(&dir).map_err(|e| e.to_string())?;
|
||||
let cut = store
|
||||
.with_store(|s| Cut::take(&book, &dir, s.head()))
|
||||
.map_err(|e| e)?
|
||||
.map_err(|e| e.to_string())?;
|
||||
backup::save_file(&sealed_to, &cut, key.as_ref(), &ctx)
|
||||
.map(|w| (w, key.is_some()))
|
||||
.map_err(|e| e.to_string())
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| Err("the backup stopped".into()));
|
||||
match saved {
|
||||
Ok((w, sealed)) => {
|
||||
self.record(json!({"kind": "saved", "ok": true, "sealed": sealed,
|
||||
"head": {"seq": w.head.0, "hash": w.head.1}}));
|
||||
Ok(vec![format!(
|
||||
"Saved a backup of the books through event {} as {}{}.",
|
||||
w.head.0,
|
||||
file.display(),
|
||||
if sealed {
|
||||
", protected by the passphrase"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
)])
|
||||
}
|
||||
Err(why) => {
|
||||
let why = hide(&why, &self.dir);
|
||||
self.record(json!({"kind": "saved", "ok": false, "error": why}));
|
||||
Err(why)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The old backup history's folder in a book's folder: left alone.
|
||||
const OLD_ARCHIVE_DIR: &str = "archive.git";
|
||||
|
||||
|
||||
@@ -1656,6 +1656,53 @@ impl Books {
|
||||
Err(why) => Response::Refused(self.hide(why)),
|
||||
}
|
||||
}
|
||||
Request::BackupSetup {
|
||||
id,
|
||||
folder,
|
||||
passphrase,
|
||||
remove_passphrase,
|
||||
} => match self.backups_of(&id) {
|
||||
Ok(backups) => {
|
||||
let rt = tokio::runtime::Handle::current();
|
||||
let pass = passphrase.as_ref().map(|p| p.0.clone());
|
||||
match rt.block_on(backups.set_up(folder, pass, remove_passphrase)) {
|
||||
Ok(lines) => Response::Said { lines },
|
||||
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,
|
||||
})
|
||||
}
|
||||
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 {
|
||||
id,
|
||||
source,
|
||||
@@ -2180,6 +2227,22 @@ impl Books {
|
||||
)
|
||||
}
|
||||
|
||||
/// The backups of the open book `id`, or the refusal to give a request
|
||||
/// that needs them.
|
||||
fn backups_of(&self, id: &str) -> Result<Arc<crate::backup::Backups>, Response> {
|
||||
let refused = |text: String| 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
|
||||
/// request that needs it open.
|
||||
fn not_open(&self, id: &BookId) -> String {
|
||||
|
||||
Reference in new issue
Block a user