1574 lines · 78.9 KB · RustRaw
//! **The one place a phone's copy leaves its place** (QUEUE BAD OP 4 and 5, coordinator, 27 Nov 2026).//!//! Three rounds of review found paths that threw away a change the person made: a rebuild, a sign-in, a waiting copy,//! a carried file not yet landed. Each was a path that read the copy to decide, and missed what did not read. So the//! shape changed: this module is the ONLY code in the core that deletes, replaces or moves a local copy's file or//! folder ([`retire`], [`retire_folder`], [`relocate`]); a lint test (`copy_keep_tests::nothing_else_removes_a_copy`)//! fails on any other.//!//! It decides by ONE question asked of the raw files, never of what reads://! - of a copy ([`unsent_in`]): any row in a place the store lists as one a change waits in//! (`cotton_store::local_places`: the queue, the push parks, receipts held in any way, uploads not done), any//! carried file beside it (`*.set-aside.json`, QUEUE BAD OP 3), readable or not, any build's format. A SQLite file//! holding tables but none of those places cannot be asked;//! - of a folder ([`unsent_in_folder`]): every file in it is a copy (asked as above, `.before-update` too), a file the//! module names as derivable ([`DERIVABLE_FILES`], each with why), or something that holds what this phone alone//! has (`kept-rows.json`, `sites.local.c1`, anything not named): it counts.//!//! If anything counts, or the question cannot be answered (a file does not open, a read fails), nothing is deleted://! - a copy ([`retire`]) moves with its own files only (journal, shared memory, carried file) into its own kept folder//! under `kept-copies/<database>/`, by hard links made first and the originals removed after, the copy's file last,//! so a stop part way leaves every byte in one place or the other. The folder it stood in is never moved: it may//! hold the live copy, and what else it holds stays the database's;//! - a folder ([`retire_folder`]) moves whole in one rename.//!//! A state line beside each (why, when, from which build, which database it belongs to now) is written first, marked//! as moving, and settled once the move is done; a move a stop interrupted is settled at the next look//! ([`settle_moves`]). Nothing is extracted at that moment, so nothing can be missed.//!//! A kept copy is filed under the database it BELONGS to now: an adopted local database under the signed-in one//! ([`Ending::keep_into`]), so everything that reads kept copies by the live database sees it, and account delete//! removes it with the rest.//!//! Recovery is separate and unhurried ([`recover`]: at launch, after an update and on each pass): each kept copy of the//! database is opened and each change it holds that the server has not acknowledged is tried, one by one. One that//! reads in this build is sent under a fresh author at its ORIGINAL time (`cotton_store::mint::clock::send_recovered`)//! and marked done in the kept folder's state; one that does not read, or that the copy refuses, stays, counted in//! You > Sync as kept ([`kept_changes`]) with Let go ([`let_go`]), and the others go on. A kept copy is deleted only once//! every change in it is done or let go.//!//! Exactly three endings remove a copy outright ([`Ending`]): the account deleted, the person's own Remove of a local//! database, and Let go. Each can be built only from a [`PersonsAct`], which only the three act handlers make (a lint//! test holds that). A kept copy never blocks sign-in, Connect or a remake; nothing is capped by deleting; its size is//! said in You > Storage ([`kept_bytes`]).use std::collections::{BTreeMap, BTreeSet};use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};use crate::layout::Layout;/// The person's own act: the only thing a destroying [`Ending`] can be built from. Made only in the three act/// handlers (account delete, the person's own Remove of a local database, Let go); the lint test/// `copy_keep_tests::only_the_three_acts_make_a_persons_act` fails on any other maker.#[derive(Debug)]pub struct PersonsAct { _made: (),}impl PersonsAct { /// The person asked for it, on a screen that asked first. Call it only in one of the three act handlers. #[must_use] pub fn of_the_person() -> PersonsAct { PersonsAct { _made: () } }}/// How a copy leaves its place.#[derive(Debug, Clone, Copy)]pub enum Ending<'a> { /// Every path but the three below: the copy goes only when it holds nothing unsent; otherwise it is kept whole. /// `why` is written beside a kept copy. `whole`: keep it even when nothing is unsent (its rows were not checked /// against the server, a remake whose send did not finish); such a copy stays until the person lets it go. /// `acknowledged`: changes the server took or answered for good, sent from this very copy before it goes. /// `belongs_to`: the database it is filed under when kept, when that is not its own (an adopted local database /// belongs to the signed-in one). /// `held_back`: changes the server never took that no copy of this app can send (a table its kit does not carry): /// kept and listed, never sent by recovery. /// `before_restore`: the server was put back to this time (RESTORE 2): the copy stood before it, so what it holds /// is listed for the person and never sent by recovery (the damage the restore undid may be among it). Keep { why: &'a str, whole: bool, acknowledged: &'a [String], belongs_to: Option<&'a str>, held_back: &'a [String], before_restore: Option<&'a str> }, /// The account is deleted: everything of it goes. AccountDelete(&'a PersonsAct), /// The person removed this local database themselves, asked first on the screen. OwnRemove(&'a PersonsAct), /// The person let go of what a kept copy held. LetGo(&'a PersonsAct),}impl<'a> Ending<'a> { /// The ordinary ending: kept when it holds anything unsent. #[must_use] pub fn keep(why: &'a str) -> Ending<'a> { Ending::Keep { why, whole: false, acknowledged: &[], belongs_to: None, held_back: &[], before_restore: None } } /// Kept when it holds anything unsent beyond `acknowledged`: the changes the server just took or answered for /// good, sent from this very copy before it goes (a remake's send). #[must_use] pub fn keep_beyond(why: &'a str, acknowledged: &'a [String]) -> Ending<'a> { Ending::Keep { why, whole: false, acknowledged, belongs_to: None, held_back: &[], before_restore: None } } /// [`Ending::keep_beyond`], with changes no copy of this app can send kept and listed, never sent by recovery. #[must_use] pub fn keep_beyond_holding(why: &'a str, acknowledged: &'a [String], held_back: &'a [String]) -> Ending<'a> { Ending::Keep { why, whole: false, acknowledged, belongs_to: None, held_back, before_restore: None } } /// Kept when it holds anything beyond `acknowledged`, filed under `belongs_to` (an adopt: the local database's /// rows now belong to the signed-in database, and only what the adopt did not carry counts). #[must_use] pub fn keep_into(why: &'a str, belongs_to: &'a str, acknowledged: &'a [String]) -> Ending<'a> { Ending::Keep { why, whole: false, acknowledged, belongs_to: Some(belongs_to), held_back: &[], before_restore: None } } /// A copy the server's restore left behind (RESTORE 2): kept when it holds anything unsent, marked as from before /// the server was put back to `restored_to` (its time, or empty when the server did not say), so recovery lists /// what it holds and never sends it. #[must_use] pub fn keep_restored(why: &'a str, restored_to: &'a str) -> Ending<'a> { Ending::Keep { why, whole: false, acknowledged: &[], belongs_to: None, held_back: &[], before_restore: Some(restored_to) } }}/// What [`retire`] did.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Retired { /// There was nothing there. Absent, /// It held nothing unsent (or an ending removed it): gone. Gone, /// It was moved whole into this kept folder. Kept(PathBuf),}/// What the one question found.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Unsent { /// Nothing the server has not acknowledged. Nothing, /// This many things the server has not acknowledged, or this phone alone holds (readable or not). Holds(usize), /// The question could not be answered: the copy is kept. Unknown(String),}impl Unsent { fn and(self, other: Unsent) -> Unsent { match (self, other) { (Unsent::Unknown(a), _) => Unsent::Unknown(a), (_, Unsent::Unknown(b)) => Unsent::Unknown(b), (Unsent::Holds(a), Unsent::Holds(b)) => Unsent::Holds(a + b), (Unsent::Holds(a), Unsent::Nothing) | (Unsent::Nothing, Unsent::Holds(a)) => Unsent::Holds(a), (Unsent::Nothing, Unsent::Nothing) => Unsent::Nothing, } }}/// The state line beside a kept copy.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct KeptState { /// The database it belongs to now (and is filed under). pub database: String, pub why: String, pub at: String, pub build: String, /// Where the copy stood. pub from: String, /// Kept whatever it held: its rows were not checked against the server. #[serde(default)] pub whole: bool, /// The database it was, when that is not `database` (an adopted local database). Its changes name that /// database's ids, so recovery lists them and never sends them by itself. #[serde(default)] pub adopted_from: Option<String>, /// Written before the move and cleared once it is done: a kept folder still moving is settled at the next look. #[serde(default)] pub moving: bool, /// Changes sent from it under new stamps (and files returned beside the live copy). #[serde(default)] pub done: BTreeSet<String>, /// Changes the person let go. #[serde(default)] pub let_go: BTreeSet<String>, /// Changes the server never took that no copy of this app can send: listed, never sent by recovery. #[serde(default)] pub held_back: BTreeSet<String>, /// The copy stood before the server was put back to this time (RESTORE 2; empty when the server did not say when): /// what it holds is listed for the person and never sent by recovery, since the damage the restore undid may be /// among it. #[serde(default)] pub before_restore: Option<String>,}/// One kept copy.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Kept { pub dir: PathBuf, pub state: KeptState,}/// Something a kept copy holds that has not been sent or let go.#[derive(Debug, Clone, PartialEq, Eq)]pub struct KeptChange { pub op_id: String, pub table: String, pub row_id: String, pub bytes: Vec<u8>, /// Where it waits in the kept copy: `queued`, `parked`, `held`, `media` (a place of the store's list), `carried`, /// `file` (a file this phone alone held), `unopened` (a copy that does not open). pub place: &'static str, pub kept: PathBuf,}const STATE: &str = "kept.json";const COPY: &str = "copy";const CARRIED_SUFFIX: &str = ".set-aside.json";const KEPT_ROWS: &str = "kept-rows.json";/// The rows the server refused, made a copy's own file at a restore ([`fence_kept_rows`]): they leave with the copy,/// and no pass posts them (a pass reads `kept-rows.json` alone).const ROWS_SUFFIX: &str = ".kept-rows.json";const SITES_LOCAL: &str = "sites.local.c1";/// The files a database's folder may hold that are derived again or are this device's own note, by name or by the/// end of their name, each with why. Anything in a folder that is not a copy, a copy's own file, or on this list/// counts as something this phone alone holds.pub const DERIVABLE_FILES: &[(&str, &str)] = &[ ("adopt.log", "an adopt's own log, read only to resume that adopt"), ("discarded-unsent.json", "the record of changes the server refused for good, filed for Feedback; their rows are in kept-rows.json"), ("kept-here.json", "the count of kept changes waiting to be seen"), ("last_pull_at", "when a pass last reached the server"), ("core-built", "the newest core that opened the copy to write, made again at its next open"), ("signed-in.json", "which account and person the copy was signed in by, read again at sign-in"), ("file-check.json", "the last check of the copy's file, made again"), ("first-sync.json", "a fresh copy's first sync's measured times, a measure only"), ("first-sync.json.partial", "the same, part written"), ("sites.stores.json", "the website stores' random keys, read only to remove those stores"), ("sites.unread-said.json", "which Sites files that did not open were already said once"), (".owner", "which database a Sites file belongs to"), ("-shm", "a copy's shared-memory index, made again when it opens"), (".not-moved", "why an update did not move this copy, written again"), (".kit", "the kit the copy was pulled for, read again from the server"), (".download", "a snapshot not finished downloading, fetched again"), (".download.size", "the size a download expects"), (".DS_Store", "the Mac's own note"),];/// The build this core is, written beside a kept copy.fn build() -> String { format!("{} (schema {})", env!("CARGO_PKG_VERSION"), cotton_store::migrate::SCHEMA_VERSION)}fn now_iso() -> String { chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}/// Where the copies of `database` kept aside live.pub fn kept_dir(layout: &Layout, database: &str) -> PathBuf { layout.root().join("kept-copies").join(database)}/// The suffixes of a copy's own files beside it: its journal, its shared memory, a carried file, its marks.const SIDECARS: &[&str] = &["-wal", "-shm", "-journal", CARRIED_SUFFIX, ROWS_SUFFIX, crate::bootstrap::not_moved::NOT_MOVED_SUFFIX, crate::transport::object::COPY_KIT_SUFFIX];fn with_suffix(path: &Path, suffix: &str) -> PathBuf { let mut name = path.as_os_str().to_os_string(); name.push(suffix); PathBuf::from(name)}// ── a test's seam: a stop part way, as a phone killed there would ─────────────/// Where a test stops a move, as a kill would: the next launch finds what that left. Never set outside a test.#[doc(hidden)]#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Stop { /// The move itself fails (another volume, no space): nothing moves. FailMove, /// The state line is written, nothing moved. BeforeMove, /// Moved (linked, or the folder renamed), the state still says moving; in recovery, sent and its kept folder not /// yet gone. BeforeSettle, /// A copy's files linked into the kept folder and the first of the originals removed, the rest not yet. AfterFirstRemoval, /// A kept folder does not read (QUEUE BAD OP 7): the question cannot be answered, so nothing is removed. FailRead,}thread_local! { static STOP: std::cell::Cell<Option<Stop>> = const { std::cell::Cell::new(None) };}/// A test's kill on this thread (`None` clears it).#[doc(hidden)]pub fn stop_for_tests(at: Option<Stop>) { STOP.with(|stop| stop.set(at));}fn stop_at(at: Stop) -> bool { STOP.with(|stop| stop.get() == Some(at))}// ── THE ONE QUESTION ──────────────────────────────────────────────────────────/// THE ONE QUESTION, of a copy: the raw file at `path` and its own files beside it, never what reads. Any failure to/// answer is [`Unsent::Unknown`].pub fn unsent_in(path: &Path) -> Unsent { unsent_beyond(path, &[])}/// [`unsent_in`], leaving out the changes in `acknowledged` (by op id).pub fn unsent_beyond(path: &Path, acknowledged: &[String]) -> Unsent { unsent_leaving(path, acknowledged, Leaving::Own)}/// Where a copy is asked from: its own database's place, or leaving INTO ANOTHER database (an adopt, a give way; a/// copy kept under the database it was adopted into), where its founding is not the person's work and never counts/// ([`crate::founding::FOUNDING_TABLES`], KEPT FOUR).#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Leaving { Own, IntoAnother,}impl Leaving { fn of(database: &str, belongs_to: Option<&str>) -> Self { if belongs_to.is_some_and(|live| live != database) { Self::IntoAnother } else { Self::Own } } fn of_kept(state: &KeptState) -> Self { if state.adopted_from.is_some() { Self::IntoAnother } else { Self::Own } } /// Whether a change of `tbl` counts here: never a founding row leaving into another database. fn counts(self, tbl: Option<&str>) -> bool { !(self == Self::IntoAnother && tbl.is_some_and(crate::founding::is_founding)) }}/// KEPT FOUR 3 (B, C): a local vault key the copies hold, leaving `local` for `into`: its wrap is secured in its own/// file first ([`crate::vault_keep::secure`]; one that cannot be written keeps the copies), and the copies stay, one/// count per wrap, until the key was let go of on the server's evidence ([`crate::vault_keep::held_open`]).fn vault_depends(layout: &Layout, local: &str, copies: &[PathBuf], into: &str) -> Unsent { if let Err(error) = crate::vault_keep::secure(layout, local, copies, Some(into)) { return Unsent::Unknown(format!("the vault key it holds could not be kept in its own file ({error})")); } match crate::vault_keep::held_open(layout, copies) { Ok(0) => Unsent::Nothing, Ok(n) => Unsent::Holds(n), Err(error) => Unsent::Unknown(format!("the vault key it holds could not be checked ({error})")), }}/// The copies a folder holds (each SQLite copy in it, a `.before-update` one too).fn copies_in_folder(folder: &Path) -> Vec<PathBuf> { std::fs::read_dir(folder).into_iter().flatten().flatten().map(|entry| entry.path()).filter(|path| path.is_file() && file_is(path) == FileIs::Copy).collect()}/// The copies a kept folder holds.pub fn copies_kept(kept: &Kept) -> Result<Vec<PathBuf>, String> { Ok(files_in(&kept.dir)?.into_iter().filter(|file| file_is(file) == FileIs::Copy).collect())}/// The live copy of the database a kept folder is filed under (`<root>/kept-copies/<database>/<stamp>`).fn live_of(kept: &Kept) -> PathBuf { let root = kept.dir.parent().and_then(Path::parent).and_then(Path::parent).map(Path::to_path_buf).unwrap_or_default(); Layout::new(root).replica(&kept.state.database)}/// THE ONE GUARD every removal of a kept folder asks (KEPT FOUR 2, 3): a folder adopted from a local database whose/// vault key was not let go of on the server's evidence never goes, whatever else it holds; nor one that cannot be/// asked. Its wraps are secured in the key's own file first. A folder of a database's own (not adopted) holds that/// database's own vault, held by its live copy.fn vault_lets_go(kept: &Kept) -> Result<bool, String> { let Some(local) = kept.state.adopted_from.as_deref() else { return Ok(true) }; let copies = copies_kept(kept)?; let layout = layout_of(kept); crate::vault_keep::secure(&layout, local, &copies, Some(&kept.state.database))?; crate::vault_keep::copies_may_go(&layout, &copies)}/// The layout a kept folder belongs to (`<root>/kept-copies/<database>/<stamp>`).fn layout_of(kept: &Kept) -> Layout { Layout::new(kept.dir.parent().and_then(Path::parent).and_then(Path::parent).map(Path::to_path_buf).unwrap_or_default())}fn unsent_leaving(path: &Path, acknowledged: &[String], leaving: Leaving) -> Unsent { let carried = match carried_beside(path, leaving) { Ok(n) => n, Err(error) => return Unsent::Unknown(error), }; if !path.exists() { // A journal without its file is something a stopped move left: not answerable. if ["-wal", "-journal"].iter().any(|suffix| with_suffix(path, suffix).metadata().is_ok_and(|meta| meta.len() > 0)) { return Unsent::Unknown("a journal stands without its copy".into()); } return if carried > 0 { Unsent::Holds(carried) } else { Unsent::Nothing }; } match count_unsent(path, acknowledged, leaving) { Ok(n) if n + carried > 0 => Unsent::Holds(n + carried), Ok(_) => Unsent::Nothing, Err(error) => Unsent::Unknown(error), }}fn carried_beside(path: &Path, leaving: Leaving) -> Result<usize, String> { // The rows a restore made the copy's own (RESTORE 2): one that does not read still counts. let rows = with_suffix(path, ROWS_SUFFIX); let rows = if rows.exists() { kept_rows_in(&rows) } else { 0 }; let carried = with_suffix(path, CARRIED_SUFFIX); if !carried.exists() { return Ok(rows); } if leaving == Leaving::IntoAnother { if let Ok(found) = crate::transport::object::carried_file_read(&carried) { return Ok(rows + found.iter().filter(|change| leaving.counts(Some(&change.table))).count()); } } let bytes = std::fs::read(&carried).map_err(|error| format!("a carried file could not be read ({error})"))?; // A carried file that does not parse still holds what it held: counted as one. Ok(rows + serde_json::from_slice::<Vec<serde_json::Value>>(&bytes).map(|changes| changes.len()).unwrap_or(1))}fn tables_of(file: &rusqlite::Connection) -> Result<BTreeSet<String>, String> { file.prepare("SELECT name FROM sqlite_master WHERE type = 'table'") .and_then(|mut statement| statement.query_map([], |row| row.get::<_, String>(0))?.collect::<Result<BTreeSet<_>, _>>()) .map_err(|error| format!("the copy does not read ({error})"))}fn open_read_only(path: &Path) -> Result<rusqlite::Connection, String> { rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX).map_err(|error| format!("the copy does not open ({error})"))}/// A SQLite file holding tables, none of them a place a change waits in, cannot be asked: it is not a copy this build/// knows. One with no tables of a person's at all holds nothing.fn answerable(tables: &BTreeSet<String>) -> Result<(), String> { let places = cotton_store::local_places::unsent_places().any(|(table, _, _)| tables.contains(table)); let persons = tables.iter().filter(|table| !table.starts_with('_') && !table.starts_with("sqlite_")).count(); if !places && persons > 0 { return Err(format!("it holds {persons} table(s) and none of the places a change waits in")); } Ok(())}fn count_unsent(path: &Path, acknowledged: &[String], leaving: Leaving) -> Result<usize, String> { let file = open_read_only(path)?; let tables = tables_of(&file)?; answerable(&tables)?; // Each change counted once by its op id (a held write is often queued too); one with no op id always counts. let mut ids: BTreeSet<String> = BTreeSet::new(); let mut nameless = 0usize; for (table, kind, sql) in cotton_store::local_places::unsent_places() { if !tables.contains(table) { continue; } let mut statement = file.prepare(sql).map_err(|error| format!("{table} does not read ({error})"))?; let rows = statement .query_map([], |row| Ok((row.get::<_, Option<String>>(0)?, row.get::<_, Option<String>>(1)?))) .map_err(|error| format!("{table} does not read ({error})"))?; for row in rows { let (id, tbl) = row.map_err(|error| format!("{table} does not read ({error})"))?; if !travels(kind, tbl.as_deref()) || !leaving.counts(tbl.as_deref()) { continue; } match id { Some(id) if !id.is_empty() => { ids.insert(id); } _ => nameless += 1, } } } Ok(ids.iter().filter(|id| !acknowledged.contains(id)).count() + nameless)}/// Whether a row of a place of `kind` naming table `tbl` waits for the server. Everything queued, parked or uploading/// does; a held receipt does unless its table never travels (a device's own observations, `cotton_store`'s fixed list/// of device-local and server-only tables): the server never acknowledges those, by design, and they are this phone's/// alone. A row naming no table fails shut: it waits.fn travels(kind: &str, tbl: Option<&str>) -> bool { match (kind, tbl) { ("held", Some(tbl)) => cotton_store::schema::table_specs::is_handed_over(tbl), _ => true, }}/// What a file in a database's folder is.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum FileIs { /// A copy: asked by [`unsent_in`]. Copy, /// A copy's own file (journal, carried file, marks), asked with its copy, or alone when its copy is gone. CopysOwn, /// On [`DERIVABLE_FILES`]. Derivable, /// Rows the server refused, kept on this phone (`kept-rows.json`). KeptRows, /// Anything else: this phone alone holds it. Other,}fn is_sqlite(path: &Path) -> bool { use std::io::Read as _; let mut head = [0u8; 16]; std::fs::File::open(path).and_then(|mut file| file.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0"}fn file_is(path: &Path) -> FileIs { let name = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); if name == KEPT_ROWS || name.ends_with(ROWS_SUFFIX) { return FileIs::KeptRows; } if DERIVABLE_FILES.iter().any(|(derivable, _)| name == *derivable || (derivable.starts_with(['.', '-']) && name.ends_with(derivable))) { return FileIs::Derivable; } if ["-wal", "-journal", CARRIED_SUFFIX].iter().any(|suffix| name.ends_with(suffix)) { return FileIs::CopysOwn; } if is_sqlite(path) || name.ends_with(".db") || name.ends_with(".sqlite") || name.ends_with(crate::bootstrap::previous::SUFFIX) || name.ends_with(crate::bootstrap::unclaimed::SUFFIX) { return FileIs::Copy; } FileIs::Other}/// The copy a copy's own file belongs to.fn copy_of_own(path: &Path) -> PathBuf { let text = path.to_string_lossy(); for suffix in ["-wal", "-journal", CARRIED_SUFFIX] { if let Some(base) = text.strip_suffix(suffix) { return PathBuf::from(base); } } path.to_path_buf()}fn kept_rows_in(path: &Path) -> usize { std::fs::read(path).ok().map_or(1, |bytes| serde_json::from_slice::<Vec<serde_json::Value>>(&bytes).map(|rows| rows.len()).unwrap_or(1))}/// THE ONE QUESTION, of a whole folder: every copy in it asked (a `.before-update` copy too), every other file either/// on [`DERIVABLE_FILES`] or counted (rows the server refused kept here, the sites kept on this phone only, anything/// not named, a folder inside it).pub fn unsent_in_folder(folder: &Path, acknowledged: &[String]) -> Unsent { unsent_in_folder_leaving(folder, acknowledged, Leaving::Own)}fn unsent_in_folder_leaving(folder: &Path, acknowledged: &[String], leaving: Leaving) -> Unsent { let entries = match std::fs::read_dir(folder) { Ok(entries) => entries, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Unsent::Nothing, Err(error) => return Unsent::Unknown(format!("the folder does not read ({error})")), }; let mut found = Unsent::Nothing; for entry in entries { let Ok(entry) = entry else { return Unsent::Unknown("the folder does not read".into()) }; let path = entry.path(); if path.is_dir() { found = found.and(Unsent::Holds(1)); continue; } found = found.and(match file_is(&path) { FileIs::Copy => unsent_leaving(&path, acknowledged, leaving), // Asked with its copy; alone, it is asked as a copy that is gone (a journal alone cannot be asked). FileIs::CopysOwn if copy_of_own(&path).exists() => Unsent::Nothing, FileIs::CopysOwn => unsent_leaving(©_of_own(&path), acknowledged, leaving), FileIs::Derivable => Unsent::Nothing, FileIs::KeptRows => match kept_rows_in(&path) { 0 => Unsent::Nothing, n => Unsent::Holds(n), }, FileIs::Other => match path.metadata() { Ok(meta) if meta.len() == 0 => Unsent::Nothing, _ => Unsent::Holds(1), }, }); } found}// ── removing, keeping ─────────────────────────────────────────────────────────/// Remove `path` and its own files (an ending that removes, or a copy that holds nothing unsent).fn remove_copy_files(path: &Path) -> Result<(), String> { for suffix in std::iter::once("").chain(SIDECARS.iter().copied()) { match std::fs::remove_file(with_suffix(path, suffix)) { Ok(()) => {} Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(format!("{} could not be removed ({error})", with_suffix(path, suffix).display())), } } Ok(())}fn remove_folder(folder: &Path) -> Result<(), String> { match std::fs::remove_dir_all(folder) { Ok(()) => Ok(()), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(error) => Err(format!("{} could not be removed ({error})", folder.display())), }}/// The start of a kept folder's name while it is being removed (QUEUE BAD OP 6, M3).const GONE: &str = ".gone-";fn is_gone(path: &Path) -> bool { path.file_name().is_some_and(|name| name.to_string_lossy().starts_with(GONE))}/// A kept folder removed: first renamed to a tombstone name in one step, then deleted. A stop part way through the/// delete leaves a tombstone, which nothing reads as a kept copy and the next look finishes removing; never a kept/// folder whose state went first and is then read as one made up.fn remove_kept(dir: &Path) -> Result<(), String> { if std::fs::symlink_metadata(dir).is_err() { return Ok(()); } let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else { return Err("a kept folder has a parent".into()) }; let name = name.to_string_lossy(); let tomb = (0..).map(|n| parent.join(format!("{GONE}{name}.{n}"))).find(|tomb| std::fs::symlink_metadata(tomb).is_err()).unwrap_or_default(); std::fs::rename(dir, &tomb).map_err(|error| format!("{} could not be removed ({error})", dir.display()))?; remove_folder(&tomb)}/// A new kept folder for `database`, its state written first, marked moving.#[allow(clippy::too_many_arguments)]fn new_kept(layout: &Layout, database: &str, adopted_from: Option<&str>, why: &str, whole: bool, from: &Path, acknowledged: &[String], held_back: &[String], before_restore: Option<&str>) -> Result<PathBuf, String> { let base = kept_dir(layout, database); std::fs::create_dir_all(&base).map_err(|error| format!("the kept folder could not be made ({error})"))?; let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%S%3fZ").to_string(); let mut dir = base.join(&stamp); let mut n = 1; while dir.exists() { dir = base.join(format!("{stamp}-{n}")); n += 1; } std::fs::create_dir_all(&dir).map_err(|error| format!("the kept folder could not be made ({error})"))?; let state = KeptState { database: database.to_string(), why: why.to_string(), at: now_iso(), build: build(), from: from.display().to_string(), whole, adopted_from: adopted_from.map(str::to_string), moving: true, done: acknowledged.iter().cloned().collect(), held_back: held_back.iter().cloned().collect(), before_restore: before_restore.map(str::to_string), ..Default::default() }; write_state(&dir, &state)?; Ok(dir)}fn write_state(dir: &Path, state: &KeptState) -> Result<(), String> { let bytes = serde_json::to_vec_pretty(state).map_err(|error| error.to_string())?; crate::whole_file::replace(&dir.join(STATE), &bytes).map_err(|error| format!("a kept copy's state could not be written ({error})"))}fn read_state(dir: &Path) -> Option<KeptState> { std::fs::read(dir.join(STATE)).ok().and_then(|bytes| serde_json::from_slice::<KeptState>(&bytes).ok())}fn said(why: &str, unsent: &Unsent, detail: &str) -> String { match unsent { Unsent::Holds(n) => format!("{why}; it holds {n} thing(s) the server has not acknowledged ({detail})"), Unsent::Unknown(reason) => format!("{why}; it could not be asked what it holds ({reason})"), Unsent::Nothing => format!("{why}; its rows were not checked against the server"), }}/// What the person reads when an app on an older core would remake or adopt the phone's shared copy.pub const OLDER_CORE: &str = "Another Cotton app on this phone is newer than this one. Update this app, then try again.";/// This core's commit time (seconds), set once by the app's core at open; 0 when unstamped (tests, a build outside a/// checkout), which never refuses.static CORE_BUILT: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0);pub fn set_core_built(seconds: i64) { CORE_BUILT.store(seconds, std::sync::atomic::Ordering::Relaxed);}#[must_use]pub fn core_built() -> i64 { CORE_BUILT.load(std::sync::atomic::Ordering::Relaxed)}/// The file beside a copy that names the newest core that opened it to write.fn core_stamp(path: &Path) -> PathBuf { path.with_file_name("core-built")}/// This core opened the copy at `path` to write: the stamp beside it says the newest core that has.pub fn stamp_core(path: &Path) { let mine = core_built(); if mine <= 0 { return; } let stamp = core_stamp(path); let held = std::fs::read_to_string(&stamp).ok().and_then(|t| t.trim().parse::<i64>().ok()).unwrap_or(0); if mine > held { let _ = std::fs::write(&stamp, mine.to_string()); }}/// The newer core that opened this copy to write, when one did: this core is older than the copy.fn newer_core(path: &Path) -> Option<i64> { let mine = core_built(); if mine <= 0 { return None; } let held = std::fs::read_to_string(core_stamp(path)).ok().and_then(|t| t.trim().parse::<i64>().ok())?; (held > mine).then_some(held)}/// THE ONE FUNCTION a copy leaves its place by. `path` is the copy's file (`…/replica.db`, `…/replica.db.before-update`)./// With [`Ending::Keep`], a copy holding anything unsent (or that cannot be asked) moves with its own files into a kept/// folder; one holding nothing goes. The folder it stood in is never moved and what else it holds stays: it is the/// database's, and may hold the live copy. The three other endings remove the copy.pub fn retire(layout: &Layout, database: &str, path: &Path, ending: Ending<'_>) -> Result<Retired, String> { let present = std::iter::once("").chain(SIDECARS.iter().copied()).any(|suffix| with_suffix(path, suffix).exists()); if !present { return Ok(Retired::Absent); } // RULE (owner, 28 Nov 2026): one copy is shared by every app on the phone, and an app on an older core never // remakes or adopts it out of its place: what the newer core keeps there (a group's log, before it travelled) would // go. The person's own acts (deleting the account, removing a database, letting a kept copy go) still go. if matches!(ending, Ending::Keep { .. }) { if let Some(newer) = newer_core(path) { return Err(format!("{OLDER_CORE} (this core {}, the copy's {newer})", core_built())); } } let Ending::Keep { why, whole, acknowledged, belongs_to, held_back, before_restore } = ending else { remove_copy_files(path)?; return Ok(Retired::Gone); }; settle_moves(layout, Some(belongs_to.unwrap_or(database))); let leaving = Leaving::of(database, belongs_to); let mut unsent = unsent_leaving(path, acknowledged, leaving); if leaving == Leaving::IntoAnother { unsent = unsent.and(vault_depends(layout, database, &[path.to_path_buf()], belongs_to.unwrap_or(database))); } if unsent == Unsent::Nothing && !whole { remove_copy_files(path)?; return Ok(Retired::Gone); } let said = said(why, &unsent, &detail(path, leaving)); let into = belongs_to.unwrap_or(database); let dir = new_kept(layout, into, belongs_to.filter(|live| *live != database).map(|_| database), &said, whole, path, acknowledged, held_back, before_restore)?; if stop_at(Stop::BeforeMove) { return Err("stopped before the move (a test's kill)".into()); } match move_copy_files(path, &dir.join(COPY)) { Ok(()) => {} // Nothing of the copy left its place: the half-made kept folder goes, the copy stays where it is. Err((error, false)) => { let _ = remove_kept(&dir); return Err(format!("the copy could not be kept ({error}); it stays where it is")); } // Something of it left its place (QUEUE BAD OP 6): the kept folder holds the only copy of that, so it stays, // still moving, and the next look finishes the move. Err((error, true)) => return Err(format!("the copy was kept part way ({error}); the next look finishes it")), } if stop_at(Stop::BeforeSettle) { return Err("stopped before the kept state was settled (a test's kill)".into()); } settle(&dir); eprintln!("[copy-keep] the copy of {database} is kept at {}: {said}", dir.display()); Ok(Retired::Kept(dir))}/// A RESTORE (RESTORE 2): the rows the server refused, kept beside the copy at `path` (`kept-rows.json`, which every/// pass posts again), are made the copy's own file, so they leave with it through [`retire`] and are listed, never/// posted by the copy made again. Nothing beside: nothing done. One already made the copy's own (a restore stopped/// part way) with new rows beside it again: an error, and nothing moves.pub fn fence_kept_rows(path: &Path) -> Result<(), String> { let beside = path.with_file_name(KEPT_ROWS); if std::fs::symlink_metadata(&beside).is_err() { return Ok(()); } let own = with_suffix(path, ROWS_SUFFIX); if std::fs::symlink_metadata(&own).is_ok() { return Err("rows refused by the server stand beside the copy and as its own; nothing is moved".into()); } std::fs::rename(&beside, &own).map_err(|error| format!("the rows kept beside the copy could not be made its own ({error})"))}/// A copy's own files moved into `to` (a new folder): every one linked there first, then the originals removed, the/// copy's file LAST. A stop before the removals leaves the copy whole in its place (the links are undone at the next/// look); a stop part way through them leaves every byte in the kept folder, the journal never split from its copy/// there. A link that cannot be made (another volume) moves nothing./// Fails with whether any original had left its place.fn move_copy_files(path: &Path, to: &Path) -> Result<(), (String, bool)> { if stop_at(Stop::FailMove) { return Err(("the move failed (a test's other volume)".into(), false)); } std::fs::create_dir_all(to).map_err(|error| (error.to_string(), false))?; let name = path.file_name().ok_or(("a copy has a name".to_string(), false))?.to_os_string(); let mut moved = Vec::new(); for suffix in std::iter::once("").chain(SIDECARS.iter().copied()) { let source = with_suffix(path, suffix); if !source.exists() { continue; } let target = with_suffix(&to.join(&name), suffix); std::fs::hard_link(&source, &target).map_err(|error| (format!("{} could not be linked into the kept folder ({error})", source.display()), false))?; moved.push(source); } // The copy's file FIRST (QUEUE BAD OP 6, LOW): a stop after it leaves its journal behind without it, which is // never opened as a copy (asked, it cannot be answered; the next look finishes the move), never a copy standing // without the journal that holds its newest changes. moved.sort_by_key(|source| source.as_path() != path); for (n, source) in moved.into_iter().enumerate() { if n == 1 && stop_at(Stop::AfterFirstRemoval) { return Err(("stopped after the first file left its place (a test's kill)".into(), true)); } std::fs::remove_file(&source).map_err(|error| (format!("{} could not leave its place ({error})", source.display()), n > 0))?; } Ok(())}/// [`retire`] for a copy known only by its path (`<root>/client/…/<database>/<file>`): its database is its folder's/// name, its layout the folder above `client`.pub fn retire_at(path: &Path, ending: Ending<'_>) -> Result<Retired, String> { let folder = path.parent().ok_or("a copy has a folder")?; let database = folder.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); let root = folder .ancestors() .find(|dir| dir.file_name().is_some_and(|name| name == "client")) .and_then(Path::parent) .or_else(|| folder.parent().and_then(Path::parent)) .ok_or("a copy's folder has no root")?; retire(&Layout::new(root), &database, path, ending)}/// Where a copy's unsent changes wait and of which tables, counted, for the log and the kept state (no values).fn detail(path: &Path, leaving: Leaving) -> String { let mut by: BTreeMap<(String, String), usize> = BTreeMap::new(); for change in changes_of(path, Path::new(""), leaving).unwrap_or_default() { *by.entry((change.place.to_string(), change.table)).or_default() += 1; } by.iter().map(|((place, table), n)| format!("{place} {table} {n}")).collect::<Vec<_>>().join(", ")}/// The media folder of `database` goes with the newest copy of it kept aside (one kept from its folder), when there is/// one: an upload not done is part of what that copy holds (QUEUE BAD OP 6, H1; an erase keeps a copy and was about to/// remove every media folder). Answers whether they went with one; a move that fails is an error and they stay.pub fn keep_media_with_kept(layout: &Layout, database: &str, media: &Path) -> Result<bool, String> { let folder = layout.replica(database).parent().map(Path::to_path_buf).unwrap_or_default(); let Some(kept) = kept(layout, None).into_iter().filter(|kept| Path::new(&kept.state.from).starts_with(&folder)).max_by(|a, b| a.dir.file_name().cmp(&b.dir.file_name())) else { return Ok(false); }; if std::fs::symlink_metadata(media).is_err() { return Ok(true); } let to = (0..).map(|n| if n == 0 { kept.dir.join("media") } else { kept.dir.join(format!("media.{n}")) }).find(|to| std::fs::symlink_metadata(to).is_err()).unwrap_or_default(); relocate_folder(media, &to).map(|()| true).map_err(|error| format!("the media of {database} could not go with its kept copy ({error})"))}/// A database's folder AND its media folder leave their place together (QUEUE BAD OP 6, H1): the folder by/// [`retire_folder`]; kept, its media go with it into the kept folder (an upload not done is part of what it holds);/// gone, its media go too. A folder that did not leave (the move failed) keeps its media where they are, and a media/// move that fails is an error, so the caller tries again: that try finds the kept folder the first one made.pub fn retire_database(layout: &Layout, database: &str, folder: &Path, media: &Path, ending: Ending<'_>) -> Result<Retired, String> { let retired = retire_folder(layout, database, folder, ending)?; let kept = match &retired { Retired::Kept(kept) => Some(kept.clone()), Retired::Absent => kept(layout, None).into_iter().find(|kept| Path::new(&kept.state.from) == folder).map(|kept| kept.dir), Retired::Gone => None, }; match (kept, &retired) { (Some(kept), _) if std::fs::symlink_metadata(media).is_ok() => { relocate_folder(media, &kept.join("media")).map_err(|error| format!("the media of {database} could not go with its kept copy ({error})"))?; } (Some(_), _) => {} // Gone: its copy held nothing unsent (an upload not done counts), so its media go with it. (None, Retired::Gone) => cotton_store::database_bin::remove_folder(media).map_err(|error| error.to_string())?, // QUEUE BAD OP 7: its folder is not there and no kept copy came from it (set aside, moved elsewhere): its media // are not this function's to remove, and stay. (None, _) => {} } Ok(retired)}/// A database's whole folder leaves its place (the database deleted or out of scope, adopted, a restored backup's/// prune): with [`Ending::Keep`], the one question of the whole folder ([`unsent_in_folder`]); anything counts, or it/// cannot be asked: the folder moves whole into a kept folder in one rename. Nothing counts: the folder goes. The/// three other endings remove it.pub fn retire_folder(layout: &Layout, database: &str, folder: &Path, ending: Ending<'_>) -> Result<Retired, String> { if !folder.exists() { return Ok(Retired::Absent); } // The shared copy's rule, for a whole folder (an adopt): never moved out by an older core ([`retire`]). if matches!(ending, Ending::Keep { .. }) { if let Some(newer) = newer_core(&folder.join("replica.db")) { return Err(format!("{OLDER_CORE} (this core {}, the copy's {newer})", core_built())); } } let Ending::Keep { why, whole, acknowledged, belongs_to, held_back, before_restore } = ending else { remove_folder(folder)?; return Ok(Retired::Gone); }; let into = belongs_to.unwrap_or(database); settle_moves(layout, Some(into)); let leaving = Leaving::of(database, belongs_to); let mut unsent = unsent_in_folder_leaving(folder, acknowledged, leaving); if leaving == Leaving::IntoAnother { unsent = unsent.and(vault_depends(layout, database, &copies_in_folder(folder), into)); } if unsent == Unsent::Nothing && !whole { remove_folder(folder)?; return Ok(Retired::Gone); } let said = said(why, &unsent, &folder_detail(folder, leaving)); let dir = new_kept(layout, into, belongs_to.filter(|live| *live != database).map(|_| database), &said, whole, folder, acknowledged, held_back, before_restore)?; if stop_at(Stop::BeforeMove) { return Err("stopped before the move (a test's kill)".into()); } let failed = stop_at(Stop::FailMove); // The one rename: the folder whole, every file in it with it. let renamed = if failed { Err(std::io::Error::other("a test's other volume")) } else { std::fs::rename(folder, dir.join(COPY)) }; if let Err(error) = renamed { let _ = remove_kept(&dir); return Err(format!("the folder could not be kept ({error}); it stays where it is")); } if stop_at(Stop::BeforeSettle) { return Err("stopped before the kept state was settled (a test's kill)".into()); } settle(&dir); eprintln!("[copy-keep] the folder of {database} is kept at {}: {said}", dir.display()); Ok(Retired::Kept(dir))}/// What a folder holds that counts, by file, for the log and the kept state (names of files and tables, no values).fn folder_detail(folder: &Path, leaving: Leaving) -> String { let mut parts = Vec::new(); for entry in std::fs::read_dir(folder).into_iter().flatten().flatten() { let path = entry.path(); let name = entry.file_name().to_string_lossy().into_owned(); match file_is(&path) { FileIs::Copy => { let detail = detail(&path, leaving); if !detail.is_empty() { parts.push(format!("{name}: {detail}")); } } FileIs::KeptRows | FileIs::Other => parts.push(name), FileIs::CopysOwn | FileIs::Derivable => {} } } parts.join("; ")}/// A kept folder's move done: its state no longer says moving.fn settle(dir: &Path) { if let Some(mut state) = read_state(dir) { if state.moving { state.moving = false; if let Err(error) = write_state(dir, &state) { eprintln!("[copy-keep] {}: {error}", dir.display()); } } }}#[cfg(unix)]fn same_file(a: &Path, b: &Path) -> bool { use std::os::unix::fs::MetadataExt as _; match (std::fs::symlink_metadata(a), std::fs::symlink_metadata(b)) { (Ok(a), Ok(b)) => a.dev() == b.dev() && a.ino() == b.ino(), _ => false, }}#[cfg(not(unix))]fn same_file(_: &Path, _: &Path) -> bool { false}/// MOVES A STOP INTERRUPTED, settled (each look at the kept copies of `database`, every database when `None`):/// - nothing moved yet (the state written, no copy beside it): the empty kept folder goes;/// - a copy's files all still linked where they stood (stopped before the removals): the links go, the copy stays/// where it is, whole;/// - anything left its place: the move is finished (what still stands there of it, by the very same file, goes) and/// the state settled.pub fn settle_moves(layout: &Layout, database: Option<&str>) { for (dir, state) in kept_folders(layout, database) { let Some(state) = state else { continue }; if !state.moving { continue; } let copy = dir.join(COPY); if !copy.exists() { let _ = remove_kept(&dir); continue; } let from = PathBuf::from(&state.from); if from.is_dir() { // A folder's rename is one step: the folder there now is another one. settle(&dir); continue; } let folder = from.parent().map(Path::to_path_buf).unwrap_or_default(); let linked: Vec<(PathBuf, PathBuf)> = std::fs::read_dir(©) .into_iter() .flatten() .flatten() .map(|entry| (entry.path(), folder.join(entry.file_name()))) .collect(); let all_there = !linked.is_empty() && linked.iter().all(|(kept, origin)| same_file(kept, origin)); if all_there { let _ = remove_kept(&dir); continue; } let mut finished = true; let (copy_file, own): (Vec<_>, Vec<_>) = linked.iter().filter(|(kept, origin)| same_file(kept, origin)).partition(|(_, origin)| *origin == from); // The copy's file first, as the move does. for (_, origin) in copy_file.into_iter().chain(own) { if std::fs::remove_file(origin).is_err() { finished = false; } } if finished { settle(&dir); } }}/// A copy moved whole from `from` to `to` (set to wait for its data key, set aside for another person, taken back):/// its journal folded in first where it opens, its own files moved with it, the file LAST, so a move stopped part way/// leaves the copy where it was. Refused when something stands at `to`.pub fn relocate(from: &Path, to: &Path) -> Result<(), String> { if to.exists() { return Err(format!("a copy already stands at {}", to.display())); } if from.exists() { let _ = rusqlite::Connection::open(from).and_then(|file| file.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))); } // QUEUE BAD OP 7: nothing of the copy is moved over a file already standing there (a journal of another copy). for suffix in SIDECARS { if with_suffix(from, suffix).exists() && std::fs::symlink_metadata(with_suffix(to, suffix)).is_ok() { return Err(format!("a {suffix} file already stands at {}; the copy is not moved over it", to.display())); } } std::fs::create_dir_all(to.parent().ok_or("a copy has a folder")?).map_err(|error| error.to_string())?; // The copy's file first, as a retire moves it: a stop after it leaves its journal behind without it, which is never // opened as a copy and is asked as one that cannot be answered. for suffix in std::iter::once("").chain(SIDECARS.iter().copied()) { let source = with_suffix(from, suffix); if source.exists() { std::fs::rename(&source, with_suffix(to, suffix)).map_err(|error| format!("{} could not be moved ({error})", source.display()))?; } } Ok(())}/// A copy just made beside its place (`.making`) moved into it: refused when a copy stands there, so a new copy never/// replaces one; that one must leave through [`retire`] first.pub fn place_new(made: &Path, to: &Path) -> Result<(), String> { if to.exists() { return Err(format!("a copy already stands at {}; the new one is not put over it", to.display())); } std::fs::rename(made, to).map_err(|error| format!("{} ({error})", to.display()))}/// A whole folder moved in one rename (a copy set aside with everything beside it, a folder taken back).pub fn relocate_folder(from: &Path, to: &Path) -> Result<(), String> { if to.exists() { return Err(format!("something already stands at {}", to.display())); } std::fs::create_dir_all(to.parent().ok_or("a folder has a parent")?).map_err(|error| error.to_string())?; std::fs::rename(from, to).map_err(|error| format!("{} could not be moved ({error})", from.display()))}// ── what is kept ──────────────────────────────────────────────────────────────fn kept_folders(layout: &Layout, database: Option<&str>) -> Vec<(PathBuf, Option<KeptState>)> { let root = layout.root().join("kept-copies"); let databases: Vec<PathBuf> = match database { Some(database) => vec![root.join(database)], None => std::fs::read_dir(&root).into_iter().flatten().flatten().map(|entry| entry.path()).collect(), }; // A tombstone (a removal a stop interrupted) is no kept copy: its removal is finished, and it is never read. let finish = |path: &PathBuf| { if is_gone(path) { let _ = remove_folder(path); return false; } true }; let mut found = Vec::new(); for base in databases.into_iter().filter(finish) { let mut dirs: Vec<PathBuf> = std::fs::read_dir(&base).into_iter().flatten().flatten().map(|entry| entry.path()).filter(finish).filter(|dir| dir.is_dir()).collect(); dirs.sort(); found.extend(dirs.into_iter().map(|dir| { let state = read_state(&dir); (dir, state) })); } found}/// Every kept copy of `database` (every database when `None`), moves a stop interrupted settled first.pub fn kept(layout: &Layout, database: Option<&str>) -> Vec<Kept> { settle_moves(layout, database); kept_folders(layout, database) .into_iter() .map(|(dir, state)| { let state = state.unwrap_or_else(|| KeptState { database: dir.parent().and_then(Path::file_name).map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(), why: "its state line did not read".into(), whole: true, ..Default::default() }); Kept { dir, state } }) .collect()}/// Every file in a kept folder, below its `copy` folder./// Every file a kept folder holds. A folder or an entry that does not read is an error (QUEUE BAD OP 7): the/// question cannot be answered, and nothing is removed on an answer that is not whole.fn files_in(dir: &Path) -> Result<Vec<PathBuf>, String> { if stop_at(Stop::FailRead) { return Err("the kept folder does not read (a test's failure)".into()); } let unread = |path: &Path, error: std::io::Error| format!("{} does not read ({error})", path.display()); let mut files = Vec::new(); let mut walk = vec![dir.join(COPY)]; while let Some(folder) = walk.pop() { for entry in std::fs::read_dir(&folder).map_err(|error| unread(&folder, error))? { let entry = entry.map_err(|error| unread(&folder, error))?; let path = entry.path(); if entry.file_type().map_err(|error| unread(&path, error))?.is_dir() { walk.push(path); } else { files.push(path); } } } files.sort(); Ok(files)}/// The unsent changes the copy at `path` holds, by the store's list of local places, read on a read-only connection/// (never a writer's, which could move its journal into the file or change its shape).pub fn changes_in(path: &Path) -> Result<Vec<KeptChange>, String> { changes_of(path, path.parent().unwrap_or(path), Leaving::Own)}/// Every change a copy file (and its carried file) holds that the server has not acknowledged, raw: op id, table,/// row, bytes. A row with no bytes is still listed (it can only be let go). Unreadable as a whole: `Err`.fn changes_of(path: &Path, kept: &Path, leaving: Leaving) -> Result<Vec<KeptChange>, String> { let mut changes = Vec::new(); let mut seen = BTreeSet::new(); if path.exists() { let file = open_read_only(path)?; let tables = tables_of(&file)?; answerable(&tables)?; for (table, kind, sql) in cotton_store::local_places::unsent_places() { if !tables.contains(table) { continue; } let mut statement = file.prepare(sql).map_err(|error| format!("{table} does not read ({error})"))?; let rows = statement .query_map([], |row| { let bytes = match row.get_ref(3)? { rusqlite::types::ValueRef::Blob(bytes) => bytes.to_vec(), rusqlite::types::ValueRef::Text(text) => text.to_vec(), _ => Vec::new(), }; Ok((row.get::<_, Option<String>>(0)?.unwrap_or_default(), row.get::<_, Option<String>>(1)?.unwrap_or_default(), row.get::<_, Option<String>>(2)?.unwrap_or_default(), bytes)) }) .map_err(|error| format!("{table} does not read ({error})"))?; for row in rows { let (op_id, tbl, row_id, bytes) = row.map_err(|error| error.to_string())?; let named = Some(&tbl).filter(|tbl| !tbl.is_empty()).map(String::as_str); if !travels(kind, named) || !leaving.counts(named) { continue; } // A row with no op id is still something unsent: named by where it is. let op_id = if op_id.is_empty() { format!("{table}:{tbl}:{row_id}") } else { op_id }; if !seen.insert(op_id.clone()) { continue; } changes.push(KeptChange { op_id, table: tbl, row_id, bytes, place: kind, kept: kept.to_path_buf() }); } } } let carried = with_suffix(path, CARRIED_SUFFIX); if carried.exists() { // A carried file that does not read or parse whole (QUEUE BAD OP 7: any entry missing a field too) is one // thing, kept whole and untouched; only the person lets it go. let found = match crate::transport::object::carried_file_read(&carried) { Ok(found) => found, Err(_) => { changes.push(KeptChange { op_id: format!("file:{}", carried.display()), table: String::new(), row_id: String::new(), bytes: Vec::new(), place: "file", kept: kept.to_path_buf() }); Vec::new() } }; for change in found.into_iter().filter(|change| leaving.counts(Some(&change.table))) { if seen.insert(change.op_id.clone()) { changes.push(KeptChange { op_id: change.op_id, table: change.table, row_id: change.row_id, bytes: change.bytes, place: "carried", kept: kept.to_path_buf() }); } } } Ok(changes)}fn file_change(path: &Path, kept: &Path) -> KeptChange { let name = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); KeptChange { op_id: format!("file:{name}"), table: String::new(), row_id: name, bytes: Vec::new(), place: "file", kept: kept.to_path_buf() }}/// Everything one kept folder holds: each copy's changes, each file this phone alone held, a copy that does not open/// as one thing of its own (`kept:<folder>`, so it is said and can be let go)./// What a kept folder holds, for a list: one that does not read is listed whole, as a copy that does not open.fn holdings(kept: &Kept) -> Vec<KeptChange> { holdings_read(kept).unwrap_or_else(|error| { eprintln!("[copy-keep] a kept folder of {} does not read: {error}", kept.state.database); vec![unopened(kept)] })}fn unopened(kept: &Kept) -> KeptChange { let name = kept.dir.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); KeptChange { op_id: format!("kept:{name}"), table: String::new(), row_id: String::new(), bytes: Vec::new(), place: "unopened", kept: kept.dir.clone() }}/// What a kept folder holds, or why it cannot be said: every removal asks this, and removes nothing on an error.fn holdings_read(kept: &Kept) -> Result<Vec<KeptChange>, String> { let name = kept.dir.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); let mut all = Vec::new(); // Kept under the database it was adopted into: its founding is not the person's work (KEPT FOUR). A phone an // earlier build left showing it heals here: nothing is listed, and recovery removes a folder holding nothing else. let leaving = Leaving::of_kept(&kept.state); for file in files_in(&kept.dir)? { match file_is(&file) { FileIs::Copy => match changes_of(&file, &kept.dir, leaving) { Ok(changes) => all.extend(changes), Err(error) => { eprintln!("[copy-keep] a kept copy of {} does not open: {error}", kept.state.database); all.push(KeptChange { op_id: format!("kept:{name}"), table: String::new(), row_id: String::new(), bytes: Vec::new(), place: "unopened", kept: kept.dir.clone() }); } }, // A carried file whose copy is gone, read alone. FileIs::CopysOwn if file.to_string_lossy().ends_with(CARRIED_SUFFIX) && !copy_of_own(&file).exists() => match changes_of(©_of_own(&file), &kept.dir, leaving) { Ok(changes) => all.extend(changes), Err(_) => all.push(KeptChange { op_id: format!("kept:{name}"), table: String::new(), row_id: String::new(), bytes: Vec::new(), place: "unopened", kept: kept.dir.clone() }), }, FileIs::CopysOwn if !copy_of_own(&file).exists() => { all.push(KeptChange { op_id: format!("kept:{name}"), table: String::new(), row_id: String::new(), bytes: Vec::new(), place: "unopened", kept: kept.dir.clone() }); } FileIs::KeptRows if kept_rows_in(&file) > 0 => all.push(file_change(&file, &kept.dir)), FileIs::Other if file.file_name().is_some_and(|name| name != STATE) => { if file.metadata().map_err(|error| format!("{} does not read ({error})", file.display()))?.len() > 0 { all.push(file_change(&file, &kept.dir)); } } _ => {} } } let mut seen = BTreeSet::new(); all.retain(|change| seen.insert(change.op_id.clone())); all.retain(|change| !kept.state.done.contains(&change.op_id) && !kept.state.let_go.contains(&change.op_id)); if leaving == Leaving::IntoAnother { let sealed_tables: BTreeSet<&str> = crate::vault_keep::SEALED.iter().map(|(table, _, _)| *table).collect(); // KEPT FOUR 3 B, LOW: while the local key waits in its own file, what is sealed under it, and every row that // links to one of those, waits with it quietly (the carry takes them at an unlock): never shown as kept. let local = kept.state.adopted_from.as_deref().unwrap_or_default(); if crate::vault_keep::key_file(&layout_of(kept), local)?.is_some() { let held: BTreeSet<String> = all.iter().filter(|change| sealed_tables.contains(change.table.as_str())).map(|change| change.row_id.clone()).collect(); let mut waiting: BTreeSet<(String, String)> = BTreeSet::new(); if !held.is_empty() { let candidates: Vec<(String, String)> = all.iter().map(|change| (change.table.clone(), change.row_id.clone())).collect(); for copy in copies_kept(kept)?.iter().filter(|copy| !copy.to_string_lossy().ends_with(".before-update")) { waiting.extend(crate::vault_keep::rows_naming(copy, &held, &candidates)?); } } all.retain(|change| !sealed_tables.contains(change.table.as_str()) && !waiting.contains(&(change.table.clone(), change.row_id.clone()))); } // KEPT FOUR 2: a row sealed under the local vault key that this phone sealed again into the live copy (the // re-seal, `cotton-ffi`'s `vault_carry`) is carried: its change no longer waits. if all.iter().any(|change| sealed_tables.contains(change.table.as_str())) { let live = live_of(kept); let mut again = BTreeSet::new(); for copy in copies_kept(kept)? { for row in crate::vault_keep::sealed_rows(©)? { if crate::vault_keep::sealed_again(&row, &live)? { again.insert((row.table.to_string(), row.id)); } } } all.retain(|change| !again.contains(&(change.table.clone(), change.row_id.clone()))); } } Ok(all)}/// What a kept folder holds, read again only when its files changed (each status query asks; most of the time/// nothing changed): by the folder, its state's and its copy's times.fn holdings_cached(kept: &Kept) -> Vec<KeptChange> { use std::sync::{Mutex, OnceLock}; type Seen = BTreeMap<PathBuf, (Vec<Option<std::time::SystemTime>>, Vec<KeptChange>)>; static CACHE: OnceLock<Mutex<Seen>> = OnceLock::new(); let mtime = |path: &Path| std::fs::metadata(path).and_then(|meta| meta.modified()).ok(); let mut stamp = vec![mtime(&kept.dir), mtime(&kept.dir.join(STATE)), mtime(&kept.dir.join(COPY))]; stamp.extend(files_in(&kept.dir).unwrap_or_default().iter().map(|file| mtime(file))); let cache = CACHE.get_or_init(|| Mutex::new(BTreeMap::new())); if let Some((seen, holdings)) = cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(&kept.dir) { if *seen == stamp && stamp.iter().all(Option::is_some) { return holdings.clone(); } } let found = holdings(kept); cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(kept.dir.clone(), (stamp, found.clone())); found}/// What the kept copies of `database` still hold: not sent, not let go.pub fn kept_changes(layout: &Layout, database: &str) -> Vec<KeptChange> { kept(layout, Some(database)).iter().flat_map(holdings_cached).collect()}/// What one recovery did.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Recovery { pub sent: usize, pub still_kept: usize, pub kept_copies_gone: usize,}/// RECOVERY (at launch, after an update, each pass): every change the kept copies of `database` hold that reads in/// this build is sent from the copy `db` (the live one) under a fresh author at its original time, one by one; each/// sent one is marked done beside its kept copy; one the copy refuses stays kept and the rest go on. Rows the server/// refused that a kept folder holds go back beside the live copy. A kept copy with nothing left (and not kept whole)/// goes. A carried file beside the live copy (QUEUE BAD OP 3) is read the same way, and goes once nothing in it is/// left.pub fn recover(layout: &Layout, database: &str, db: &cotton_store::Driver, live: &Path, wall_ms: i64, ids: &mut dyn cotton_store::outbox::IdSource) -> Result<Recovery, String> { recover_by(layout, database, db, live, wall_ms, None, ids)}type Send<'s> = dyn FnMut(&[(String, Vec<u8>)], &str, &mut dyn cotton_store::outbox::IdSource) -> Result<Vec<String>, String> + 's;/// Sends `changes` one by one: a change the copy refuses (it does not read here, its table is gone) is skipped and/// stays kept; answers the op ids sent.fn send_each(send: &mut Send<'_>, changes: &[&KeptChange], at: &str, ids: &mut dyn cotton_store::outbox::IdSource) -> Vec<String> { let handed: Vec<(String, Vec<u8>)> = changes.iter().map(|change| (change.op_id.clone(), change.bytes.clone())).collect(); if handed.is_empty() { return Vec::new(); } // All at once first (one transaction); a refusal of the whole sends them one at a time. match send(&handed, at, ids) { Ok(sent) => sent, Err(whole) => { eprintln!("[copy-keep] recovery sends one at a time: {whole}"); let mut sent = Vec::new(); for one in &handed { match send(std::slice::from_ref(one), at, ids) { Ok(done) => sent.extend(done), Err(error) => eprintln!("[copy-keep] kept change {} stays kept: {error}", one.0), } } sent } }}/// [`recover`] by the mint clock given (a test's judged clock), or the copy's own judge when `None`.pub fn recover_by(layout: &Layout, database: &str, db: &cotton_store::Driver, live: &Path, wall_ms: i64, clock: Option<&cotton_store::mint::Clock>, ids: &mut dyn cotton_store::outbox::IdSource) -> Result<Recovery, String> { let mut send = |handed: &[(String, Vec<u8>)], at: &str, ids: &mut dyn cotton_store::outbox::IdSource| -> Result<Vec<String>, String> { match clock { Some(clock) => cotton_store::mint::clock::send_recovered_with(db, clock, handed, ids, at), None => cotton_store::mint::clock::send_recovered(db, wall_ms, handed, ids, at), } .map(|sent| sent.sent) .map_err(|error| error.to_string()) }; let mut recovery = Recovery::default(); let at = chrono::DateTime::from_timestamp_millis(wall_ms).map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)).unwrap_or_else(now_iso); for mut kept in kept(layout, Some(database)) { // A kept folder that does not read is left as it is: nothing in it is sent, and it is never removed. let changes = match holdings_read(&kept) { Ok(changes) => changes, Err(error) => { eprintln!("[copy-keep] a kept folder of {database} does not read, so it stays as it is: {error}"); recovery.still_kept += 1; continue; } }; let mut done: Vec<String> = Vec::new(); // A copy from before the server's restore (RESTORE 2) is listed only: nothing in it is sent or posted again. let lists_only = kept.state.before_restore.is_some(); if kept.state.adopted_from.is_none() { // Sendable: rows of a place with bytes. An upload is done once the live copy holds its media synced. let sendable: Vec<&KeptChange> = changes.iter().filter(|change| !lists_only && matches!(change.place, "queued" | "parked" | "held" | "carried") && !change.bytes.is_empty() && !kept.state.held_back.contains(&change.op_id)).collect(); done.extend(send_each(&mut send, &sendable, &at, ids)); for change in changes.iter().filter(|change| change.place == "media") { let synced = db .get("SELECT 1 FROM _media WHERE key = ? AND state = 'synced'", &[rusqlite::types::Value::Text(change.row_id.clone())]) .ok() .flatten() .is_some(); if synced { done.push(change.op_id.clone()); } } // Rows the server refused, kept beside the copy that went: back beside the live copy, where a pass posts them. for change in changes.iter().filter(|change| !lists_only && change.op_id == format!("file:{KEPT_ROWS}")) { if return_kept_rows(layout, database, &kept.dir).is_ok() { done.push(change.op_id.clone()); } } } if !done.is_empty() { kept.state.done.extend(done.iter().cloned()); write_state(&kept.dir, &kept.state)?; recovery.sent += done.iter().filter(|id| !id.starts_with("file:") && !id.starts_with("media:")).count(); } let left = changes.iter().filter(|change| !kept.state.done.contains(&change.op_id)).count(); recovery.still_kept += left; // KEPT FOUR 2: nothing left to send, and still never removed while a row of the live copy depends on the vault // key it holds (or that cannot be asked): the next unlock seals those rows again, then it goes. if left == 0 && !kept.state.whole && !vault_lets_go(&kept).unwrap_or(false) { continue; } if left == 0 && !kept.state.whole { if stop_at(Stop::BeforeSettle) { return Err("stopped before the kept folder went (a test's kill)".into()); } remove_kept(&kept.dir)?; recovery.kept_copies_gone += 1; } } // A carried file beside the live copy, from QUEUE BAD OP 3. let carried = with_suffix(live, CARRIED_SUFFIX); if carried.exists() { // QUEUE BAD OP 7: a carried file that does not read or parse whole is left untouched, never removed or // written again without what it could not say. let changes = match crate::transport::object::carried_file_read(&carried) { Ok(changes) => changes, Err(error) => { eprintln!("[copy-keep] the carried file beside {database}'s copy stays as it is: {error}"); recovery.still_kept += 1; return Ok(recovery); } }; let listed: Vec<KeptChange> = changes .iter() .map(|change| KeptChange { op_id: change.op_id.clone(), table: change.table.clone(), row_id: change.row_id.clone(), bytes: change.bytes.clone(), place: "carried", kept: carried.clone() }) .collect(); let sent = send_each(&mut send, &listed.iter().collect::<Vec<_>>(), &at, ids); let left: Vec<_> = changes.into_iter().filter(|change| !sent.contains(&change.op_id)).collect(); recovery.sent += sent.len(); recovery.still_kept += left.len(); if left.is_empty() { remove_copy_file_only(&carried)?; } else if !sent.is_empty() { crate::transport::object::carry_set_aside_to(&carried, &left)?; } } Ok(recovery)}/// The rows a kept folder's `kept-rows.json` holds, added beside the live copy where it has none of the same row.fn return_kept_rows(layout: &Layout, database: &str, dir: &Path) -> Result<(), String> { let file = files_in(dir)?.into_iter().find(|file| file.file_name().is_some_and(|name| name == KEPT_ROWS)).ok_or("no kept rows")?; let rows: Vec<crate::unsent::KeptRow> = serde_json::from_slice(&std::fs::read(&file).map_err(|error| error.to_string())?).map_err(|error| error.to_string())?; let live = crate::unsent::kept_rows(layout, database); for row in rows { // KEPT FOUR 3 B: a founding row is never a kept row (its wrap is the local key's own file's). if crate::founding::is_founding(&row.table) { continue; } if !live.iter().any(|here| here.table == row.table && here.row_id == row.row_id) { crate::unsent::keep_row(layout, database, row)?; } } Ok(())}fn remove_copy_file_only(file: &Path) -> Result<(), String> { match std::fs::remove_file(file) { Ok(()) => Ok(()), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(error) => Err(error.to_string()), }}/// Why a kept folder is not let go (KEPT FOUR 2): a log line, never shown; the screen says its own words.pub const VAULT_HELD: &str = "vault_key_held: it holds the vault key rows of this account still open with; they are sealed again at the next unlock, then it can go";/// The person let go of something a kept copy holds (`kept:<folder>` lets go of a kept copy that does not open). Its/// kept copy goes once nothing in it is left. Answers whether anything was let go.pub fn let_go(layout: &Layout, database: &str, op_id: &str, _act: &PersonsAct) -> Result<bool, String> { for mut kept in kept(layout, Some(database)) { let whole_copy = op_id.strip_prefix("kept:").is_some_and(|name| kept.dir.file_name().is_some_and(|dir| dir.to_string_lossy() == name)); // A folder that does not read cannot say what it holds: an error, and nothing in it is removed. let holds = whole_copy || holdings_read(&kept)?.iter().any(|change| change.op_id == op_id); if !holds { continue; } if whole_copy { // KEPT FOUR 2: even a copy that does not open is never removed while the vault key it holds may still open // rows of the live copy: an answer that cannot be had refuses. if !vault_lets_go(&kept)? { return Err(VAULT_HELD.to_string()); } remove_kept(&kept.dir)?; return Ok(true); } kept.state.let_go.insert(op_id.to_string()); write_state(&kept.dir, &kept.state)?; if holdings_read(&kept).is_ok_and(|left| left.is_empty()) && !kept.state.whole && vault_lets_go(&kept).unwrap_or(false) { remove_kept(&kept.dir)?; } return Ok(true); } Ok(false)}/// The person let go of a whole kept copy (You > Storage), whatever it holds.pub fn let_go_copy(layout: &Layout, database: &str, dir: &Path, _act: &PersonsAct) -> Result<bool, String> { let Some(ours) = kept(layout, Some(database)).into_iter().find(|kept| kept.dir == dir) else { return Ok(false) }; // KEPT FOUR 2: whatever it holds, but never the only vault key rows of the live copy still open with. if !vault_lets_go(&ours)? { return Err(VAULT_HELD.to_string()); } remove_kept(dir)?; Ok(true)}/// Everything kept aside that belongs to `database` goes: the account is deleted. Every kept copy filed under it (an/// adopted local database's with them), and any filed elsewhere whose state says it belongs to it.pub fn forget_account(layout: &Layout, database: &str, _act: &PersonsAct) -> Result<(), String> { remove_kept(&kept_dir(layout, database))?; for (dir, state) in kept_folders(layout, None) { if state.is_some_and(|state| state.database == database || state.adopted_from.as_deref() == Some(database)) { remove_kept(&dir)?; } } Ok(())}/// A folder of the deleted account's (its copy's folder, a copy of it set aside, its media) gone for good: one of the/// three endings ([`Ending::AccountDelete`]). A pass under way as the phone let go may still write a file into it, so a/// removal that meets one is tried again a few times before it is said.pub fn remove_for_account(folder: &Path, _act: &PersonsAct) -> Result<(), String> { for _ in 0..10 { match std::fs::remove_dir_all(folder) { Ok(()) => return Ok(()), Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), Err(_) => std::thread::sleep(std::time::Duration::from_millis(100)), } } remove_folder(folder)}/// The bytes the kept copies of `database` take on disk (every database when `None`).pub fn kept_bytes(layout: &Layout, database: Option<&str>) -> u64 { fn size(path: &Path) -> u64 { match std::fs::symlink_metadata(path) { Ok(meta) if meta.is_dir() => std::fs::read_dir(path).into_iter().flatten().flatten().map(|entry| size(&entry.path())).sum(), Ok(meta) => meta.len(), Err(_) => 0, } } kept(layout, database).iter().map(|kept| size(&kept.dir)).sum()}#[cfg(test)]#[path = "copy_keep_tests.rs"]mod tests;