//! BACKUP WITHOUT AN ACCOUNT, the phone's half in the core (owner, 25 Nov 2026; `assets/design/shared/BACKUP.md`,//! the shells' contract `BACKUP-CONTRACT.md`).//!//! The core makes the sealed file from this phone's own database, opens and checks one whole, counts what a restore//! would change, swaps the database with what was there kept aside (Undo restore), and says every word. The phone//! keeps the code in its key store, moves the made file to iCloud Drive or `files/backup/` (Google's Auto Backup) or a//! picked folder, and hands a found file back. Signed in, every method refuses `backup_signed_in`: sync is the//! authority.//!//! ```text//! backup.screen {platform, store: {held, cloud?, old?}} → {row?, page?, signedIn?}//! backup.turn {on} → {on}//! backup.code {held?} | {typed} | {mint: true} → {code, made?} | refusal (the shell keeps `code`)//! backup.codePage {code} → the recovery code's page//! backup.codeSaved {} → {codeSaved: true}//! backup.due {byHand?} → {due}//! backup.make {code, withFiles?, device} → {path, name, bytes, fitsGoogle, madeAt}//! backup.placed {place, bytes, madeAt} | {trouble, why?} → {row}//! backup.look {path, code?, typed?} → {ask} | {refused}//! backup.restore {path, code?, typed?} → {said, key?, code?} (look first, always)//! backup.undo {} → {said}//! ```use std::collections::BTreeMap;use std::io::Writeas _;use std::path::{Path, PathBuf};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engineas _;use cotton_client::connection::{ConnectionFile, ConnectionMode, StoredConnection};use cotton_client::seal::DataKeyStoreas _;use cotton_core::backup::file::{self, Manifest, Part, Refusal, Source, Unlock};use cotton_core::backup::plan::{self, Last, Platform, Restored, State, Store, Trouble};use cotton_core::backup::BackupKey;use cotton_core::seal::DataKey;use serde_json::{json, Value};usecrate::methods::MethodError;usecrate::shell::client::ClientController;usecrate::CottonHandle;pubconst METHODS: &[&str] = &["backup.screen","backup.turn","backup.code","backup.codePage","backup.codeSaved","backup.due","backup.make","backup.placed","backup.look","backup.restore","backup.reset","backup.undo",];/// The state file, beside `connection.json`: counts and times only.const STATE: &str = "backup.json";/// Where a made file waits for the phone to move it.const OUT: &str = "backup-out";/// Where a file being restored is opened whole and checked.const STAGED: &str = "backup-staged";/// Where what was on the phone before a restore waits for Undo restore.const ASIDE: &str = "backup-aside";/// One turn at a time over the state and the aside folders: a restore, an Undo, a prune and a reset never interleave/// (ABSENCE 3, item 8).static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());fn bad(why: implInto<String>) -> MethodError {MethodError::new("bad_request", why.into())}fn io(why: impl std::fmt::Display) -> MethodError {MethodError::new("io", why.to_string())}pubfn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {let client = handle.client();let kit = kit_of(&client);let app = handle.app_name().to_string();letSome(kit) = kit.filter(|kit| plan::counted(kit).is_some()) else {returnErr(MethodError::new("backup_not_here", plan_say("refused.no_backup_here", &[("app", &app)]))); };let signed_in = client.signed_in();if signed_in && method != "backup.screen" {returnErr(MethodError::new("backup_signed_in", plan_say("refused.signed_in", &[("app", &app)]))); }let bk = Backup { client: &client, kit: &kit, app: &app };match method {"backup.screen" => bk.screen(request, signed_in),"backup.turn" => bk.turn(request),"backup.code" => bk.code(request),"backup.codePage" => {let code = request["code"].as_str().ok_or_else(|| bad("code is missing"))?;let key = BackupKey::from_code(code).map_err(|_| bad("not a code"))?;Ok(plan::code_page(&app, &key.code())) }"backup.codeSaved" => { bk.change(|state| state.code_saved = true)?;Ok(json!({"codeSaved": true})) }"backup.due" => bk.due(request),"backup.make" => bk.make(request),"backup.placed" => bk.placed(request),"backup.look" => bk.look(request),"backup.restore" => bk.restore(request),"backup.undo" => bk.undo(),"backup.reset" => bk.reset(), other => Err(MethodError::new("unknown_method", other.to_string())), }}fn plan_say(line: &str, fills: &[(&str, &str)]) -> String { cotton_core::rules::shell_lines::resolve("backup", line, &[], fills).unwrap_or_default()}fn kit_of(client: &ClientController) -> Option<String> { cotton_core::kit::AppKit::at(client.layout().root()).ok().flatten().map(|kit| kit.id)}/// The name on another app's icon, by its kit.fn name_of(kit: &str) -> String {match kit {"notes" => "Words","days" => "Days","story" => "Story","keys" => "Secrets","sites" => "Sites","messages" => "Comms", other => other, } .to_string()}structBackup<'a> { client: &'a ClientController, kit: &'a str, app: &'a str,}implBackup<'_> {fn dir(&self, name: &str) -> PathBuf {self.client.layout().client_dir().join(name) }fn state(&self) -> State {self.state_read().unwrap_or_default() }/// The state as the file holds it: none yet is the default; a file that does not read is an error, never "no/// restore" (ABSENCE 1: what decides a prune or a write over it).fn state_read(&self) -> Result<State, MethodError> {match std::fs::read(self.dir(STATE)) {Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(State::default()),Err(e) => Err(io(e)),Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| io(format!("the backup state does not read ({e})"))), } }fn change(&self, edit: implFnOnce(&mutState)) -> Result<State, MethodError> {letmut state = self.state_read()?; edit(&mut state);let bytes = serde_json::to_vec_pretty(&state).map_err(io)?;// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep. cotton_client::whole_file::replace(&self.dir(STATE), &bytes).map_err(io)?;Ok(state) }fn zone(&self) -> String {self.client.time_zone().unwrap_or("UTC").to_string() }/// A moment said for a glance: the clock today, the day otherwise.fn when(&self, iso: &str) -> String {let zone = self.zone();let today = cotton_core::kit::local_clock(&self.client.now_iso(), &zone, "%Y-%m-%d");match cotton_core::kit::local_clock(iso, &zone, "%Y-%m-%d") {Some(day) ifSome(&day) == today.as_ref() => cotton_core::kit::local_clock(iso, &zone, "%-H:%M").unwrap_or_else(|| iso.to_string()),Some(_) => cotton_core::kit::local_clock(iso, &zone, "%-d %b").unwrap_or_else(|| iso.to_string()),None => iso.to_string(), } }fn database(&self) -> Result<String, MethodError> {ConnectionFile::at(self.client.layout().connection_json()) .read() .and_then(|held| held.workspace_id) .filter(|id| !id.is_empty()) .ok_or_else(|| MethodError::new("no_database", "this phone has not started a database yet")) }fn screen(&self, request: &Value, signed_in: bool) -> Result<Value, MethodError> {let platform = Platform::parse(request["platform"].as_str().unwrap_or_default()).ok_or_else(|| bad("platform is ios or android"))?;let store: Store = serde_json::from_value(request.get("store").cloned().unwrap_or(json!({}))).map_err(|why| bad(why.to_string()))?;ifself.state_read().is_err() {returnOk(json!({ "broken": { "line": plan_say("trouble.state_broken", &[("app", self.app)]), "act": { "label": plan_say("acts.state_again", &[]), "method": "backup.reset" } } })); }self.prune_aside();let state = self.state();let when = state.last.as_ref().map(|last| self.when(&last.at));if signed_in {let place = plan_say(&format!("places.{}", if platform == Platform::Ios { "ios" } else { "android" }), &[]);let line = state.last.as_ref().map(|_| plan_say("signed_in.line", &[("app", self.app), ("place", &place)]));returnOk(json!({"signedIn": line})); }Ok(json!({"row": plan::row(self.kit, false, platform, &state, when.as_deref()),"page": plan::page(self.app, platform, &state, store, when.as_deref()), })) }fn turn(&self, request: &Value) -> Result<Value, MethodError> {let on = request["on"].as_bool().ok_or_else(|| bad("on is true or false"))?;let state = self.change(|state| { state.on = on;if !on { state.trouble = None; } })?;Ok(json!({"on": state.on})) }/// The code the shell keeps: the one it holds read back, a typed one taken, or a new one minted.fn code(&self, request: &Value) -> Result<Value, MethodError> {ifletSome(typed) = request["typed"].as_str() {let key = BackupKey::from_code(typed).map_err(|_| MethodError::new("code_typed", plan_say("refused.code_typed", &[])))?;returnOk(json!({"code": key.code(), "made": false})); }ifletSome(held) = request["held"].as_str() {ifletOk(key) = BackupKey::from_code(held) {returnOk(json!({"code": key.code(), "made": false})); } }if request["mint"] == json!(true) {returnOk(json!({"code": BackupKey::mint().code(), "made": true})); }Err(bad("give held, typed, or mint: true")) }fn due(&self, request: &Value) -> Result<Value, MethodError> {let state = self.state();let database = self.database()?;let replica = self.client.layout().replica(&database);let changed = [replica.clone(), replica.with_extension("db-wal")].iter().filter_map(|path| modified_s(path)).max();let last = state.last.as_ref().and_then(|last| chrono::DateTime::parse_from_rfc3339(&last.at).ok()).map(|at| at.timestamp());let now = chrono::Utc::now().timestamp();Ok(json!({"due": plan::due(&state, false, changed, last, now, request["byHand"] == json!(true))})) }fn make(&self, request: &Value) -> Result<Value, MethodError> {let key = BackupKey::from_code(request["code"].as_str().ok_or_else(|| bad("code is missing"))?).map_err(|_| bad("not a code"))?;let with_files = request["withFiles"] == json!(true);let device = request["device"].as_str().unwrap_or("unknown").to_string();let database = self.database()?;let layout = self.client.layout().clone();let out = self.dir(OUT);// not a copy: the backup file being made.let _ = std::fs::remove_dir_all(&out); std::fs::create_dir_all(&out).map_err(io)?;let snapshot = out.join("data.sqlite"); cotton_store::snapshot::copy_file(&layout.replica(&database), &snapshot).map_err(io)?;letmut counts = count(&snapshot, self.kit)?;letmut parts: Vec<(String, PathBuf)> = vec![("data.sqlite".into(), snapshot.clone())];ifletSome(dk) = self.client.data_keys().data_key(&database).map_err(io)? {let key_file = out.join("key");// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep. std::fs::write(&key_file, URL_SAFE_NO_PAD.encode(dk.expose())).map_err(io)?; parts.push(("key".into(), key_file)); }ifletOk(root) = std::fs::read(layout.media_paths_root()) {let file = out.join("media-paths-root");// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep. std::fs::write(&file, root).map_err(io)?; parts.push(("media-paths-root".into(), file)); }if with_files {let media = layout.client_media_dir();letmut files = Vec::new(); walk(&media, &media, &mut files); counts.insert("files".into(), files.len() as u64); parts.extend(files.into_iter().map(|(rel, path)| (format!("files/{rel}"), path))); }let made_at = self.client.now_iso();let manifest = Manifest { app: self.kit.to_string(), made_at: made_at.clone(), made_by: env!("CARGO_PKG_VERSION").to_string(), device, parts: vec![], counts, };let name = plan::file_name(self.app);let path = out.join(&name);letmut opened = Vec::new();for (name, path) in &parts {let file = std::fs::File::open(path).map_err(io)?;let bytes = file.metadata().map_err(io)?.len(); opened.push((name.clone(), bytes, file)); }letmut sources: Vec<Source<'_>> = opened.iter_mut().map(|(name, bytes, file)| Source { name: name.clone(), bytes: *bytes, read: file }).collect();let fresh = out.join(format!(".{name}.new"));// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep.letmut writer = std::io::BufWriter::new(std::fs::File::create(&fresh).map_err(io)?);let made = file::make(&mut writer, &key, &manifest, &mut sources).map_err(|refusal| io(format!("{refusal:?}")))?; writer.flush().map_err(io)?; drop(writer);// not a copy: the backup file, written whole, and its parts. std::fs::rename(&fresh, &path).map_err(io)?;for (_, part) in parts.iter().filter(|(name, _)| !name.starts_with("files/")) {// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep.let _ = std::fs::remove_file(part); }Ok(json!({"path": path.display().to_string(),"name": name,"bytes": made.bytes,"fitsGoogle": plan::fits_google(made.bytes),"madeAt": made_at, })) }fn placed(&self, request: &Value) -> Result<Value, MethodError> {let state = ifletSome(trouble) = request["trouble"].as_str() {let trouble = match trouble {"icloud_off" => Trouble::IcloudOff,"full" => Trouble::Full,"too_big" => Trouble::TooBig,"folder_gone" => Trouble::FolderGone, _ => Trouble::Failed { why: request["why"].as_str().unwrap_or(trouble).to_string() }, };self.change(|state| state.trouble = Some(trouble))? } else {let place = request["place"].as_str().ok_or_else(|| bad("place or trouble"))?.to_string();let bytes = request["bytes"].as_u64().ok_or_else(|| bad("bytes is missing"))?;let at = request["madeAt"].as_str().ok_or_else(|| bad("madeAt is missing"))?.to_string();let folder = request["folder"].as_str().map(str::to_string);self.change(|state| { state.last = Some(Last { at, bytes, place }); state.trouble = None;if folder.is_some() { state.folder = folder; } })? };// not a copy: the backup file's making folder.let _ = std::fs::remove_dir_all(self.dir(OUT));let when = state.last.as_ref().map(|last| self.when(&last.at));let platform = if request["platform"] == json!("android") { Platform::Android } else { Platform::Ios };Ok(json!({"row": plan::row(self.kit, false, platform, &state, when.as_deref())})) }/// Open the file whole into the staging folder and check it; the answer is what a restore would change, or why/// it cannot be restored. Nothing on the phone changes.fn look(&self, request: &Value) -> Result<Value, MethodError> {matchself.stage(request) {Ok(staged) => {let database = self.database().ok();let here = match &database {Some(database) ifself.client.layout().replica(database).exists() => {let snapshot = self.dir(STAGED).join("here.sqlite");// not a copy: a snapshot of the copy, made only to count it.let _ = std::fs::remove_file(&snapshot); cotton_store::snapshot::copy_file(&self.client.layout().replica(database), &snapshot).map_err(io)?;let here = count(&snapshot, self.kit)?;// not a copy: the same snapshot.let _ = std::fs::remove_file(&snapshot); here } _ => BTreeMap::new(), };let when = self.when(&staged.manifest.made_at);let device = staged.manifest.device.clone();Ok(json!({"ask": plan::restore_ask(self.app, self.kit, &here, &staged.manifest.counts, &when, &device)})) }Err(Staging::Refused(refusal)) => Ok(json!({"refused": self.refused(&refusal)})),Err(Staging::Failed(error)) => Err(error), } }fn refused(&self, refusal: &Refusal) -> Value { plan::refusal_said(refusal, self.app, &plan::file_name(self.app), &name_of) }fn stage(&self, request: &Value) -> Result<Staged, Staging> {let path = PathBuf::from(request["path"].as_str().ok_or_else(|| Staging::Failed(bad("path is missing")))?);let held = request["code"].as_str().and_then(|code| BackupKey::from_code(code).ok());let typed = request["typed"].as_str();let unlock = match (&held, typed) { (Some(held), Some(typed)) => Unlock::Both(held, typed), (Some(held), None) => Unlock::Key(held), (None, Some(typed)) => Unlock::Code(typed), (None, None) => {// No key at all: the file's header still says whether it is a backup of this app.letmut input = std::fs::File::open(&path).map_err(|why| Staging::Refused(Refusal::Io(why.to_string())))?;let (outer, _) = file::read_outer(&mut input).map_err(Staging::Refused)?;if outer.app != self.kit {returnErr(Staging::Refused(Refusal::OtherApp(outer.app))); }returnErr(Staging::Refused(Refusal::OtherKey)); } };let staged = self.dir(STAGED);// not a copy: a backup's parts being staged.let _ = std::fs::remove_dir_all(&staged); std::fs::create_dir_all(staged.join("parts")).map_err(|why| Staging::Failed(io(why)))?;letmut input = std::io::BufReader::new(std::fs::File::open(&path).map_err(|why| Staging::Refused(Refusal::Io(why.to_string())))?);letmut current: Option<(String, std::fs::File)> = None;let parts_dir = staged.join("parts");let opened = file::open(&mut input, self.kit, unlock, &mut |part: &Part, bytes: &[u8]| {if current.as_ref().map(|(name, _)| name.as_str()) != Some(part.name.as_str()) {let target = parts_dir.join(&part.name);ifletSome(parent) = target.parent() { std::fs::create_dir_all(parent)?; }// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep. current = Some((part.name.clone(), std::fs::File::create(target)?)); } current.as_mut().expect("just opened").1.write_all(bytes) }); drop(current);let opened = match opened {Ok(opened) => opened,Err(refusal) => {// not a copy: a backup's parts being staged.let _ = std::fs::remove_dir_all(&staged);returnErr(Staging::Refused(refusal)); } };// Parts the manifest names but that were empty were never written: make them, so every part stands.for part in &opened.manifest.parts {let target = parts_dir.join(&part.name);if !target.exists() {ifletSome(parent) = target.parent() {let _ = std::fs::create_dir_all(parent); }// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep. std::fs::write(&target, b"").map_err(|why| Staging::Failed(io(why)))?; } }let data = parts_dir.join("data.sqlite");let checked = check_database(&data, self.kit, &opened.manifest.counts);ifletErr(why) = checked {// not a copy: a backup's parts being staged.let _ = std::fs::remove_dir_all(&staged); tracing_like(&why);returnErr(Staging::Refused(Refusal::Damaged)); }let staged_at = json!({"path": path.display().to_string(), "key": opened.outer.key, "madeAt": opened.manifest.made_at});// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep.let _ = std::fs::write(staged.join("staged.json"), staged_at.to_string());Ok(Staged { manifest: opened.manifest, key: opened.key, parts: parts_dir }) }fn restore(&self, request: &Value) -> Result<Value, MethodError> {let _turn = TURN.lock().unwrap_or_else(|p| p.into_inner());// A state that does not read refuses before anything is let go (ABSENCE 3, item 5).self.state_read()?;let staged = matchself.stage(request) {Ok(staged) => staged,Err(Staging::Refused(refusal)) => returnOk(json!({"refused": self.refused(&refusal)})),Err(Staging::Failed(error)) => returnErr(error), };let restored_db = workspace_of(&staged.parts.join("data.sqlite")).ok_or_else(|| io("the backup names no database"))?;let client = self.client;let layout = client.layout().clone();let connection = ConnectionFile::at(layout.connection_json());let held = connection.read();let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string();let aside = self.dir(ASIDE).join(&stamp); {let _swap = client.swapping(); client.detach(); std::fs::create_dir_all(&aside).map_err(io)?;// Named before anything moves into it: a restore that stops part way leaves an aside the state names, for// Undo restore, never one a prune would take (ABSENCE 1).let now = client.now_iso();self.change(|state| {ifletSome(before) = state.restored.take() { state.earlier.push(before); } state.restored = Some(Restored { at: now.clone(), at_s: chrono::Utc::now().timestamp(), aside: stamp.clone(), day_at: Some(state.days) }); })?;// What was on the phone goes aside whole: its connection first, then its folder, for Undo restore.if layout.connection_json().exists() {// not a copy: the connection file, copied aside with a restore and back with its Undo. std::fs::copy(layout.connection_json(), aside.join("connection.json")).map_err(io)?; }ifletSome(current) = held.as_ref().and_then(|held| held.workspace_id.clone()).filter(|id| !id.is_empty()) {// Which database it is, written before it moves: an Undo never puts back what it cannot name.// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep. std::fs::write(aside.join("database.id"), ¤t).map_err(io)?;let folder = layout.client_dir().join(¤t);if folder.exists() {// The copy moves whole, through the one place a copy moves (QUEUE BAD OP 4). cotton_client::copy_keep::relocate_folder(&folder, &aside.join("database")).map_err(io)?; } }// A folder of the restored database's name that is not the one just set aside (a stale one) goes too.let target = layout.client_dir().join(&restored_db);if target.exists() { cotton_client::copy_keep::relocate_folder(&target, &aside.join("stale")).map_err(io)?; } std::fs::create_dir_all(&target).map_err(io)?; cotton_client::copy_keep::place_new(&staged.parts.join("data.sqlite"), &target.join("replica.db")).map_err(io)?;let files = staged.parts.join("files");if files.exists() {let media = layout.client_media_dir();letmut found = Vec::new(); walk(&files, &files, &mut found);for (rel, path) in found {let to = media.join(&rel);if !to.exists() {ifletSome(parent) = to.parent() { std::fs::create_dir_all(parent).map_err(io)?; }// not a copy: a media file. std::fs::rename(&path, &to).or_else(|_| std::fs::copy(&path, &to).map(|_| ())).map_err(io)?; } } }ifletOk(root) = std::fs::read(staged.parts.join("media-paths-root")) {// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep. cotton_client::whole_file::replace(&layout.media_paths_root(), &root).map_err(io)?; } connection .write(StoredConnection { device_scope: None, takes_placements: false, mode: ConnectionMode::Local, base_url: String::new(), workspace_id: Some(restored_db.clone()), owner_id: crate::phone::adopt::local_owner(&target.join("replica.db")), connected_at: None, }) .map_err(|error| io(error.to_string()))?; client.let_go_if_stale(); }let key = std::fs::read_to_string(staged.parts.join("key")).ok().and_then(|text| {let bytes: [u8; 32] = URL_SAFE_NO_PAD.decode(text.trim()).ok()?.try_into().ok()?;let dk = DataKey::from_bytes(bytes); client.data_keys().hold(&restored_db, &dk);Some(URL_SAFE_NO_PAD.encode(dk.expose())) });// not a copy: the staged parts, the database already placed.let _ = std::fs::remove_dir_all(self.dir(STAGED));let when = self.when(&staged.manifest.made_at);Ok(json!({"said": plan::restored_said(self.kit, &staged.manifest.counts, &when),"databaseId": restored_db,// The copy's own data key, for the shell to keep as a first sign-in's (`seal.heldKey`)."key": key,// The code that opened it, for the shell's key store: its next backups need no code."code": staged.key.code(), })) }fn undo(&self) -> Result<Value, MethodError> {let _turn = TURN.lock().unwrap_or_else(|p| p.into_inner());let state = self.state_read()?;let restored = state.restored.clone().ok_or_else(|| MethodError::new("nothing_to_undo", "no restore to undo"))?;let aside = self.dir(ASIDE).join(&restored.aside);let client = self.client;let layout = client.layout().clone();let connection = ConnectionFile::at(layout.connection_json());// Only an aside that names its database and still holds it (or one an earlier Undo already put back) is undone:// an Undo never moves the live database aside for nothing (ABSENCE 3, item 4). Asked again after it stopped// part way, it finishes (item 6).let before = std::fs::read_to_string(aside.join("database.id")).ok().map(|id| id.trim().to_string()).filter(|id| !id.is_empty());letSome(before) = before else { returnErr(MethodError::new("nothing_to_undo", plan_say("refused.nothing_to_undo", &[]))) };let put_back = layout.client_dir().join(&before).exists() && aside.join("undone").read_dir().is_ok_and(|mut d| d.next().is_some());if !aside.join("database").exists() && !put_back {returnErr(MethodError::new("nothing_to_undo", plan_say("refused.nothing_to_undo", &[]))); } {let _swap = client.swapping(); client.detach();let undone = aside.join("undone"); std::fs::create_dir_all(&undone).map_err(io)?;ifletSome(now) = connection.read().and_then(|held| held.workspace_id).filter(|id| !id.is_empty()) {let folder = layout.client_dir().join(&now);// The restored copy goes aside, unless it is the earlier one already put back.if folder.exists() && aside.join("database").exists() && !undone.join(&now).exists() { cotton_client::copy_keep::relocate_folder(&folder, &undone.join(&now)).map_err(io)?; } }if aside.join("database").exists() && !layout.client_dir().join(&before).exists() { cotton_client::copy_keep::relocate_folder(&aside.join("database"), &layout.client_dir().join(&before)).map_err(io)?; }if aside.join("connection.json").exists() {// not a copy: the connection file, copied aside with a restore and back with its Undo. std::fs::copy(aside.join("connection.json"), layout.connection_json()).map_err(io)?; } else {// not a copy: the connection file.let _ = std::fs::remove_file(layout.connection_json()); } client.let_go_if_stale(); }self.change(|state| state.restored = None)?;Ok(json!({"said": plan_say("restore.undone", &[])})) }/// One folder Undo restore kept, gone (QUEUE BAD OP 4): each copy in it (the one on the phone before the restore, a/// stale one, one undone) leaves through the one function, kept whole aside if it holds anything unsent; the rest/// of the folder goes only once every copy has left. Answers whether it went.fn prune_one(&self, dir: &std::path::Path) -> bool {let layout = self.client.layout().clone();let named = std::fs::read_to_string(dir.join("database.id")).map(|id| id.trim().to_string()).unwrap_or_default();letmut copies: Vec<(String, std::path::PathBuf)> = vec![(named.clone(), dir.join("database")), (named, dir.join("stale"))];for entry in std::fs::read_dir(dir.join("undone")).into_iter().flatten().flatten() { copies.push((entry.file_name().to_string_lossy().into_owned(), entry.path())); }// QUEUE BAD OP 7: kept, each is filed under the database restored (the live one), where recovery, Storage and// account delete read; never under an earlier database's id or "unknown", which nothing reads.let live = cotton_client::connection::ConnectionFile::at(layout.connection_json()).read().and_then(|mine| mine.workspace_id).filter(|id| !id.is_empty());for (database, folder) in copies {let database = if database.is_empty() { live.clone().unwrap_or_else(|| "unknown".to_string()) } else { database };let into = live.clone().unwrap_or_else(|| database.clone());ifletErr(error) = cotton_client::copy_keep::retire_folder(&layout, &database, &folder, cotton_client::copy_keep::Ending::keep_into("a restore's Undo window ended", &into, &[])) { eprintln!("[backup] a copy Undo restore kept stays where it is: {error}");returnfalse; } }// not a copy: what is left of the folder once every copy in it left through copy_keep above. std::fs::remove_dir_all(dir).is_ok() || !dir.exists() }/// What Undo restore keeps goes after 30 days: only an aside the state names, once its 30 days have passed. A/// state file that does not read prunes nothing, and a folder the state does not name is never pruned (ABSENCE 1)./// In one turn with restore and Undo; the days are counted on the later of the clock and the latest it has shown;/// an aside holding a change the server never took is kept; a named aside holding nothing is cleared from the/// state, its folder left (ABSENCE 3).fn prune_aside(&self) {let _turn = TURN.lock().unwrap_or_else(|p| p.into_inner());letOk(state) = self.state_read() else { return };// One day counted per calendar day the phone is used, never the clock's jump (ABSENCE 4, item G).let today = chrono::Utc::now().format("%Y-%m-%d").to_string();// Only a day later than the latest counted counts: a clock set back and forth counts nothing twice (ABSENCE 6).let later = state.day.as_deref().is_none_or(|d| today.as_str() > d);let days = if later { state.days + 1 } else { state.days };let now = chrono::Utc::now().timestamp();let old = |restored: &Restored| restored.day_at.is_some_and(|at| days.saturating_sub(at) >= plan::ASIDE_DAYS) && now - restored.at_s > plan::ASIDE_FOR;let empty = |restored: &Restored| {let aside = self.dir(ASIDE).join(&restored.aside); !aside.join("database").exists() && !aside.join("undone").exists() && !aside.join("stale").exists() };let unsent = |restored: &Restored| {let aside = self.dir(ASIDE).join(&restored.aside);letmut copies = vec![aside.join("database").join("replica.db"), aside.join("stale").join("replica.db")];for entry in std::fs::read_dir(aside.join("undone")).into_iter().flatten().flatten() { copies.push(entry.path().join("replica.db")); } copies.iter().filter(|p| p.exists()).any(|p| holds_unsent(p)) };let gone: Vec<Restored> = state.restored.iter().chain(state.earlier.iter()).filter(|r| old(r) && !unsent(r) && !state.listed.contains(&r.aside)).filter(|r| self.prune_one(&self.dir(ASIDE).join(&r.aside))).cloned().collect();let cleared = |r: &Restored| gone.contains(r) || empty(r);let _ = self.change(|state| { state.earlier.retain(|r| !cleared(r));if state.restored.as_ref().is_some_and(|r| cleared(r)) { state.restored = None; }for r in state.earlier.iter_mut().chain(state.restored.iter_mut()) { r.day_at.get_or_insert(days); } state.days = days;if later { state.day = Some(today.clone()); } }); }/// `backup.reset`: Start backup settings again, after the state stopped reading. The broken file is kept beside/// it; every aside folder on disk stays and is listed in the new state, never pruned.fn reset(&self) -> Result<Value, MethodError> {let _turn = TURN.lock().unwrap_or_else(|p| p.into_inner());let file = self.dir(STATE);if file.exists() {let kept = file.with_extension(format!("json.broken-{}", chrono::Utc::now().format("%Y%m%dT%H%M%SZ")));// not a copy: the backup state file that stopped reading, kept beside it. std::fs::rename(&file, kept).map_err(io)?; }let now = chrono::Utc::now();let _ = now;letmut state = State::default();// Listed, never pruned: no readable state named them (ABSENCE 4, item F).for entry in std::fs::read_dir(self.dir(ASIDE)).into_iter().flatten().flatten() { state.listed.push(entry.file_name().to_string_lossy().to_string()); } state.listed.sort();let bytes = serde_json::to_vec_pretty(&state).map_err(io)?;// not a copy: the backup's own files (its state, keys, staging and parts); a restore puts its copy in place only through copy_keep. cotton_client::whole_file::replace(&file, &bytes).map_err(io)?;Ok(json!({ "reset": true, "kept": state.listed.len(), "listed": state.listed })) }}structStaged { manifest: Manifest, key: BackupKey, parts: PathBuf,}enumStaging {Refused(Refusal),Failed(MethodError),}/// A damaged database inside a file that opened is said as damaged; the reason goes to the log only.fn tracing_like(why: &str) { eprintln!("backup: the restored database did not check: {why}");}fn modified_s(path: &Path) -> Option<i64> {let modified = std::fs::metadata(path).ok()?.modified().ok()?;Some(modified.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs() as i64)}/// Every file under `dir`, with its path relative to `root` (`/` between folders).fn walk(root: &Path, dir: &Path, out: &mutVec<(String, PathBuf)>) {letOk(entries) = std::fs::read_dir(dir) else { return };letmut entries: Vec<_> = entries.flatten().collect(); entries.sort_by_key(|entry| entry.file_name());for entry in entries {let path = entry.path();if path.is_dir() { walk(root, &path, out); } elseifletOk(rel) = path.strip_prefix(root) {let rel = rel.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/");if !rel.starts_with('.') { out.push((rel, path)); } } }}/// How many of each counted thing a database file holds, by the kit's nouns: live ones only (not binned).fn count(path: &Path, kit: &str) -> Result<BTreeMap<String, u64>, MethodError> {let db = rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).map_err(io)?;letmut counts = BTreeMap::new();for counted in plan::counted(kit).unwrap_or_default() {let (table, noun) = (counted.table, counted.noun);let columns: Vec<String> = match db.prepare(&format!("PRAGMA table_info(\"{table}\")")) {Ok(mut statement) => statement.query_map([], |row| row.get::<_, String>(1)).map_err(io)?.flatten().collect(),Err(_) => vec![], };if columns.is_empty() { counts.insert(noun.to_string(), 0);continue; }letmut only: Vec<String> = ["deleted_at", "trashed_at"].into_iter().filter(|c| columns.iter().any(|have| have == c)).map(|c| format!("{c} IS NULL")).collect();if !counted.only.is_empty() { only.push(counted.only.to_string()); }let filter = if only.is_empty() { String::new() } else { format!(" WHERE {}", only.join(" AND ")) };let n: i64 = db.query_row(&format!("SELECT COUNT(*) FROM \"{table}\"{filter}"), [], |row| row.get(0)).map_err(io)?; counts.insert(noun.to_string(), n.max(0) as u64); }Ok(counts)}/// A restored database is whole: SQLite's own check says ok, and it holds what its manifest counted.fn check_database(path: &Path, kit: &str, counted: &BTreeMap<String, u64>) -> Result<(), String> {let db = rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).map_err(|e| e.to_string())?;let verdict: String = db.query_row("PRAGMA integrity_check", [], |row| row.get(0)).map_err(|e| e.to_string())?;if verdict != "ok" {returnErr(verdict); } drop(db);let found = count(path, kit).map_err(|e| e.message.clone())?;for (noun, n) in counted.iter().filter(|(noun, _)| *noun != "files") {if found.get(noun) != Some(n) {returnErr(format!("{noun}: the manifest says {n}, the database {:?}", found.get(noun))); } } workspace_of(path).map(|_| ()).ok_or_else(|| "no database id".to_string())}/// The database id a copy names itself by.fn workspace_of(path: &Path) -> Option<String> {let db = rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).ok()?; db.query_row("SELECT workspace_id FROM _meta", [], |row| row.get::<_, String>(0)).ok().filter(|id| !id.is_empty())}#[cfg(test)]#[path = "backup_tests.rs"]mod tests;/// Whether a copy set aside holds anything the server never acknowledged, failing shut (ABSENCE 4, item H): any row/// waiting in the outbox, parked for a push, held back or set aside counts, read or not; a copy that does not answer/// counts too.fn holds_unsent(path: &std::path::Path) -> bool {letOk(db) = rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX) else { returntrue };let has = |table: &str| db.query_row("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?1", [table], |r| r.get::<_, i64>(0)).map(|n| n > 0);let any = |sql: &str| db.query_row(sql, [], |r| r.get::<_, i64>(0)).map(|n| n > 0);let checks: [(&str, &str); 4] = [ ("_outbox", "SELECT COUNT(*) FROM _outbox"), ("_parked", "SELECT COUNT(*) FROM _parked WHERE direction = 'push'"), ("_writes", "SELECT COUNT(*) FROM _writes WHERE held <> 0"), ("_tombstones", "SELECT COUNT(*) FROM _tombstones WHERE held <> 0"), ];for (table, sql) in checks {match has(table) {Ok(false) => {}Ok(true) => {if any(sql).unwrap_or(true) {returntrue; } }Err(_) => returntrue, } }false}