Cotton code
554 lines · 24.2 KB · RustRaw
//! Leaving a server: forget the address and the file, keep the identity.//!//! The port of `apps/cotton/src/lib/leaveServer.ts`. The split is the whole of//! it, and it is not obvious in either direction://!//! **Forgotten** — `client/connection.json` (the address AND the cached//! workspace), the replica with its `-wal` and `-shm`, and every download//! leftover beside it. A replica left behind after a leave is somebody's data//! sitting on a phone that is no longer allowed to read it, and the next join//! would find a file for a workspace it has nothing to do with.//!//! **Kept** — the device KEY (`deviceSecret`, in the Keychain, which this crate//! never touches) and the op-author id (`client/device.json`). Both are this//! device's identity rather than its address://!//! * minting a new key on every leave would mean a person who left and rejoined//!   the same server has to approve the same phone twice, and the server's//!   device list grows a dead row each time;//! * minting a new AUTHOR id would make the file's history read as a fleet of//!   phones, and the fold would stop recognising this device's own writes.//!//! `join.leave` after a REVOKED refusal is the case that makes the second one//! matter: the phone was just removed, the person will pair it again in a//! minute, and it should come back as the same device.//!//! ## And the other verb, [`erase_device`]//!//! A leave is *"stop talking to that server"*. **An erase is *"there is no//! Cotton on this phone any more"*** — the verb behind the second button on a//! revoked device's screen, and the one a remote revocation with `erase: true`//! takes without asking. It is [`leave_server`] plus every folder this device//! kept the person's own material in, plus the identity a leave is careful to//! keep, because a phone that is erasing itself is not coming back as the same//! device.//!//! **It is NOT an overload of `leave_server`**, and that is deliberate: one//! function with a `destroy: bool` is one function a caller passes the wrong//! literal to, and the wrong literal here is somebody's photographs.use std::path::Path;use crate::connection::ConnectionFile;use crate::layout::Layout;/// What a leave actually removed, for the log and for a test.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub struct Left {    pub forgot_server: bool,    pub deleted_replica: bool,    /// The `-wal`, the `-shm`, the `.download` and the `.download.size`.    pub deleted_leftovers: usize,    /// How many OTHER held databases' replicas went with it.    pub deleted_databases: usize,}/// Forget the server this device joined.////// Best effort per file and NEVER an error outward: a leave that refused half/// way would leave a phone with an address it cannot use and no way to type a/// new one. What it could not delete is reported in the count, not thrown.pub fn leave_server(    layout: &Layout,    connection: &ConnectionFile,    workspace_id: Option<&str>,) -> Left {    leave_server_ending(layout, connection, workspace_id, crate::copy_keep::Ending::keep("this device left the server"))}/// [`leave_server`], each copy leaving by `ending` (QUEUE BAD OP 4): kept aside when it holds anything unsent, or, in an/// erase, removed.fn leave_server_ending(    layout: &Layout,    connection: &ConnectionFile,    workspace_id: Option<&str>,    ending: crate::copy_keep::Ending<'_>,) -> Left {    let mut left = Left::default();    if connection.path().exists() {        left.forgot_server = true;    }    // EVERY HELD DATABASE GOES WITH THE SERVER, read before the record that    // names them is forgotten — and the notes that spoke for them, so a    // rejoin never sends a section for a file that is no longer here.    let places: Vec<String> = connection        .read_record()        .map(|record| record.places.into_iter().map(|place| place.id).collect())        .unwrap_or_default();    crate::connection::held::HeldNotes::beside(connection.path()).forget_all();    connection.forget();    for place in &places {        if Some(place.as_str()) == workspace_id {            continue;        }        if delete_replica_files(layout, place, ending).0 {            left.deleted_databases += 1;        }    }    let Some(workspace_id) = workspace_id else {        // No workspace named means no replica was ever opened. The address is        // forgotten and there is nothing else to do.        return left;    };    let (deleted, leftovers) = delete_replica_files(layout, workspace_id, ending);    left.deleted_replica = deleted;    left.deleted_leftovers = leftovers;    left}/// What a leave does with changes this copy holds that the serving Mac has/// not taken. Two words, not a `bool`: the wrong literal here is somebody's/// unsent writes, deleted with the file.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Unsent {    /// Refuse the leave and say what is held (the default a screen sends).    Refuse,    /// The person chose to drop them: leave anyway.    Discard,}/// Why a leave did not happen.#[derive(Debug, Clone, PartialEq, Eq)]pub enum LeaveError {    /// The copy holds what the serving Mac has not taken; the words say what.    Unsent(String),    /// The leave could not be carried out.    Failed(String),}impl std::fmt::Display for LeaveError {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        match self {            Self::Unsent(reason) | Self::Failed(reason) => f.write_str(reason),        }    }}/// What leaving `database` would lose — `None` when its copy holds nothing/// the serving Mac lacks, or there is no copy. The same three debts a/// re-hydrate refuses on ([`crate::bootstrap::owes_hand_over`]): queued/// writes, parked pushes, a hand-over owed to a Mac that took over. A copy/// that cannot be read is an error, never "nothing to lose".pub fn what_leaving_loses(layout: &Layout, database: &str) -> Result<Option<String>, String> {    let replica = layout.replica(database);    if !replica.exists() {        return Ok(None);    }    cotton_store::driver::Driver::open(&replica)        .and_then(|db| crate::bootstrap::owes_hand_over(&db))        .map_err(|error| format!("this device's copy could not be checked before leaving ({error})"))}/// Leave a shared database on this device, without touching Personal or/// other held copies. The caller closes its open replica before this call.////// With [`Unsent::Refuse`] a copy that still holds what the serving Mac has/// not taken is refused and nothing is forgotten: the file IS those writes,/// and deleting it is the only place they would be lost.pub fn leave_database(    layout: &Layout,    connection: &ConnectionFile,    database: &str,    unsent: Unsent,) -> Result<bool, LeaveError> {    let held = connection.read_record().is_some_and(|record| record.places.iter().any(|place| place.id == database));    if !held {        return Ok(false);    }    if unsent == Unsent::Refuse {        if let Some(reason) = what_leaving_loses(layout, database).map_err(LeaveError::Failed)? {            return Err(LeaveError::Unsent(reason));        }    }    let Some(_entry) = connection.forget_database(database).map_err(|error| LeaveError::Failed(error.to_string()))? else {        return Ok(false);    };    delete_replica_files(layout, database, crate::copy_keep::Ending::keep("this device left it"));    if let Err(error) = crate::connection::held::HeldNotes::beside(connection.path()).forget(database) {        eprintln!("[cotton-sync] the left database's held note was not dropped: {error}");    }    Ok(true)}/// A DEVICE SCOPED TO ONE DATABASE HOLDS ONE (owner's 70th amendment, 20 Oct/// 2026): every held copy `admits` refuses goes from this device with its/// bytes — the entry (named left, so no listing offers it back), its folder,/// its media, its thumbnails and its held note. Unscoped but kept, twelve such/// copies sat on the 304 phone, counted in its state and never synced.////// The device's own database is never a place and is never touched. A copy/// that holds what the serving Mac has not taken — queued writes, parked/// pushes, a hand-over owed — is KEPT and said: those writes exist nowhere/// else. Idempotent: a second call finds nothing to remove. Answers the/// databases removed.pub fn remove_out_of_scope(layout: &Layout, connection: &ConnectionFile, admits: impl Fn(&str) -> bool) -> Vec<String> {    let Some(record) = connection.read_record() else {        return Vec::new();    };    let mut removed = Vec::new();    for place in record.places.iter().filter(|place| !admits(&place.id)) {        let database = place.id.as_str();        if record.mine.workspace_id.as_deref() == Some(database) {            continue;        }        match what_leaving_loses(layout, database) {            Ok(None) => {}            Ok(Some(reason)) => {                eprintln!("[cotton-sync] {database} is outside this app's scope but kept: {reason}");                continue;            }            Err(error) => {                eprintln!("[cotton-sync] {database} is outside this app's scope but kept: {error}");                continue;            }        }        // Its thumbnails are read off the copy before the copy goes: the        // cache is shared and flat, and only the copy says which are its.        let thumbs = thumb_files(layout, database);        match connection.forget_database(database) {            Ok(Some(_)) => {}            Ok(None) => continue,            Err(error) => {                eprintln!("[cotton-sync] {database} is outside this app's scope and was not forgotten: {error}");                continue;            }        }        if let Err(error) = super::bin::purge_copy(layout, database) {            // Named left already: `sweep_left` takes the file at the next pass.            eprintln!("[cotton-sync] {database}'s copy did not all go: {error}");            delete_replica_files(layout, database, crate::copy_keep::Ending::keep("this device left it"));        }        for thumb in thumbs {            // not a copy: a thumbnail.            let _ = std::fs::remove_file(thumb);        }        if let Err(error) = crate::connection::held::HeldNotes::beside(connection.path()).forget(database) {            eprintln!("[cotton-sync] {database}'s held note was not dropped: {error}");        }        removed.push(database.to_string());    }    removed}/// Delete the copies of databases this device LEFT that are still on disk./// Answers how many went.////// [`leave_database`] marks the database left on the connection record/// first and deletes its file second, so a device killed between the two/// holds a file nothing addresses: a stray that refuses the next join. The/// leave already passed its check (or the person chose to discard), so the/// file holds nothing the serving Mac lacks and goes here, at the next pass,/// never attached. A database admitted again since (an invitation lifts the/// mark) is not named left and is not touched.pub fn sweep_left(layout: &Layout, connection: &ConnectionFile) -> usize {    let Some(record) = connection.read_record() else {        return 0;    };    let mut swept = 0;    for database in &record.left_databases {        let addressed = record.mine.workspace_id.as_deref() == Some(database.as_str())            || record.places.iter().any(|place| &place.id == database);        if addressed || !layout.replica(database).exists() {            continue;        }        let (deleted, _) = delete_replica_files(layout, database, crate::copy_keep::Ending::keep("this device left it"));        if deleted {            swept += 1;        }    }    swept}/// PURGE the copy of a database this device was removed from, once its 30/// days in the Bin are up ([`super::bin::purge_removed`]): the entry (the/// database named left, so no joined place offers it back), its folder, its/// media and its thumbnails, its held note, and — when nothing else is held/// at that Mac — the refusal note kept for it. `false` when the record holds/// no such removed database or its days are not up, and then nothing is/// deleted.////// The entry is forgotten only after its file and media are gone, so a/// failed purge is retried.pub fn delete_removed_copy(    layout: &Layout,    connection: &ConnectionFile,    database: &str,    now: chrono::DateTime<chrono::Utc>,) -> Result<bool, String> {    purge_removed_copy(layout, connection, database, || {        super::bin::purge_removed(layout, connection, database, now)    })}/// [`delete_removed_copy`] whatever its days in the Bin — what a new/// admission at the same Mac does first, so the database comes back as a/// fresh copy (architect's ruling, 16 Oct 2026).pub fn purge_removed_copy_now(    layout: &Layout,    connection: &ConnectionFile,    database: &str,) -> Result<bool, String> {    purge_removed_copy(layout, connection, database, || {        super::bin::purge_removed_now(layout, connection, database)    })}fn purge_removed_copy(    layout: &Layout,    connection: &ConnectionFile,    database: &str,    purge: impl FnOnce() -> Result<bool, String>,) -> Result<bool, String> {    let entry = connection        .read_record()        .and_then(|record| record.places.into_iter().find(|place| place.id == database));    // Its thumbnails are read off the copy before the copy goes: the cache    // is shared and flat, and only the copy says which files are its.    let thumbs = thumb_files(layout, database);    if !purge()? {        return Ok(false);    }    for thumb in thumbs {        // not a copy: a thumbnail.        let _ = std::fs::remove_file(thumb);    }    let notes = crate::connection::held::HeldNotes::beside(&layout.connection_json());    if let Err(error) = notes.forget(database) {        eprintln!("[cotton-sync] the held note was not dropped: {error}");    }    if let Some(origin) = entry.as_ref().and_then(|entry| entry.origin.as_deref()) {        let still_there = connection.read_record().is_some_and(|record| {            record                .places                .iter()                .any(|place| place.origin.as_deref() == Some(origin))        });        if !still_there {            // not a copy: the refusal note.            let _ = std::fs::remove_file(crate::connection::joined::refusal_note_path(                &layout.connection_json(),                origin,            ));        }    }    Ok(true)}/// The thumbnail files a copy recorded in the shared thumbnail cache — only/// those inside it, so a row naming anywhere else is never followed.fn thumb_files(layout: &Layout, database: &str) -> Vec<std::path::PathBuf> {    let replica = layout.replica(database);    if !replica.exists() {        return Vec::new();    }    let cache = layout.thumbs_cache_dir();    cotton_store::driver::Driver::open(&replica)        .and_then(|db| {            db.all(                "SELECT local_path FROM _media WHERE tier = 'thumb' AND local_path IS NOT NULL",                &[],            )        })        .map(|rows| {            rows.iter()                .filter_map(|row| row.text("local_path").map(std::path::PathBuf::from))                .filter(|path| path.starts_with(&cache) && !path.components().any(|part| part == std::path::Component::ParentDir))                .collect()        })        .unwrap_or_default()}/// Delete one database's replica, its `-wal`/`-shm` and the download pair:/// whether the replica itself went, and how many leftovers did.////// QUEUE BAD OP 4: the copy and the copy an update saved before it (`.before-update`) leave through the one function,/// `crate::copy_keep::retire`: with `Ending::Keep` a copy holding anything unsent is kept whole aside. Only the/// download's leftovers are removed here.pub(crate) fn delete_replica_files(layout: &Layout, workspace_id: &str, ending: crate::copy_keep::Ending<'_>) -> (bool, usize) {    let replica = layout.replica(workspace_id);    let deleted = match crate::copy_keep::retire(layout, workspace_id, &replica, ending) {        Ok(crate::copy_keep::Retired::Gone | crate::copy_keep::Retired::Kept(_)) => true,        Ok(crate::copy_keep::Retired::Absent) => false,        Err(error) => {            eprintln!("[cotton-sync] {workspace_id}'s copy stays where it is: {error}");            false        }    };    let mut before = replica.as_os_str().to_os_string();    before.push(crate::bootstrap::previous::SUFFIX);    if let Err(error) = crate::copy_keep::retire(layout, workspace_id, Path::new(&before), ending) {        eprintln!("[cotton-sync] {workspace_id}'s copy from before an update stays where it is: {error}");    }    let mut leftovers = 0;    for suffix in [        crate::bootstrap::file::DOWNLOAD_SUFFIX,        crate::bootstrap::file::EXPECTED_SUFFIX,        crate::bootstrap::not_moved::NOT_MOVED_SUFFIX,        crate::bootstrap::unclaimed::SUFFIX,    ] {        if remove_beside(&replica, suffix) {            leftovers += 1;        }    }    (deleted, leftovers)}fn remove_beside(replica: &Path, suffix: &str) -> bool {    let mut name = replica.as_os_str().to_string_lossy().to_string();    name.push_str(suffix);    // not a copy: a download's leftovers and the marks beside a copy.    std::fs::remove_file(name).is_ok()}/// What an erase removed. Every field is a COUNT or a fact, never a path: the/// log says what went, and a caller that wanted the paths would be a second/// opinion about the layout.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub struct Erased {    /// Everything a plain leave takes.    pub left: Left,    /// How many places' replicas went — the other databases this device    /// synced, each beside Mine.    pub deleted_places: usize,    /// How many of the folders below were there to remove.    pub deleted_folders: usize,    /// `client/device.json` — the op-author id a leave keeps on purpose.    pub deleted_author_id: bool,    /// A REHEARSAL build's device seed. The packaged app keeps its seed in the    /// Keychain and there is no file; this is the scratch-data-directory one.    pub deleted_rehearsal_key: bool,}/// The Keychain items only the APP can forget, named so a caller cannot miss/// one.////// **This crate never touches the Keychain and never will** — the device seed/// and the vault key reach Rust as `OpenConfig` values Swift read, and the/// items themselves belong to the process that has an entitlement for them. So/// the erase answers their names rather than pretending they are gone:/// `DeviceKey.forget` and `VaultKeyring.forget` are the two calls, and/// `BootModel.resetKey` already makes both.pub const KEYCHAIN_ITEMS: [&str; 2] = ["deviceKey", "vaultKey"];/// Take Cotton off this device: the server, the file, the bytes and the/// identity.////// **One call, and idempotent.** Running it twice is running it on a device/// that is already empty, which is the state it is trying to reach — so every/// removal is best effort and a thing that was not there is not an error./// Nothing is reported outward but the counts.////// What goes, and why each one:////// * everything [`leave_server`] takes — the connection file, the replica, its///   `-wal`/`-shm`, the download leftovers. **The OUTBOX goes with the///   replica**: `_outbox` is a table inside that file, so a queued write that///   never reached the server dies with the database it was queued against,///   which is the only honest place for it;/// * every PLACE's replica and its leftovers, read off the record BEFORE the///   leave forgets it. Left behind, each would be a stray, and a stray refuses///   every later join — an erased device that could never join again;/// * `client/media/` — the content-addressed store. These are the person's///   photographs and documents, and they are the reason this verb exists;/// * `client/snapshots/` — a source's copy-before-read scratch, which on a Mac///   is a whole copy of somebody's Messages database;/// * `cache/thumbs/` and `cache/exports/` — renditions and the whole-database///   JSON document "Export everything" writes. Disposable, and both are the///   person's material rendered legible;/// * `client/device.json`, the op-author id, and a rehearsal build's///   `identity/device.key`. A leave keeps these so a rejoin is the same device///   to the file; an erase is the opposite intent, and leaving an author id///   behind on a phone that has been wiped would let a reinstall author rows as///   a device the server has already forgotten.////// The two Keychain items are [`KEYCHAIN_ITEMS`] and are the app's to forget.pub fn erase_device(    layout: &Layout,    connection: &ConnectionFile,    workspace_id: Option<&str>,) -> Erased {    let places: Vec<String> = connection        .read_record()        .map(|record| record.places.into_iter().map(|place| place.id).collect())        .unwrap_or_default();    // QUEUE BAD OP 5 (item 5): an erase is not the person's own Remove of a local database. Each copy leaves through    // the one function like any other: one holding anything unsent is kept aside, and kept copies stay (account delete,    // the person's Remove and Let go are the only endings that remove one).    let left = leave_server_ending(layout, connection, workspace_id, crate::copy_keep::Ending::keep("this device was erased"));    // The leave already took every other held database's file; what is left    // for this loop is their folders, and any file the leave could not take.    let mut erased = Erased {        deleted_places: left.deleted_databases,        left,        ..Erased::default()    };    for place in &places {        if delete_replica_files(layout, place, crate::copy_keep::Ending::keep("this device was erased")).0 {            erased.deleted_places += 1;        }        if let Some(folder) = layout.replica(place).parent() {            // not a copy: an empty folder only: remove_dir refuses one that holds anything.            let _ = std::fs::remove_dir(folder);        }    }    // QUEUE BAD OP 6 (H1): the media of a database whose copy was kept aside go with that kept copy (an upload not    // done is part of what it holds); one whose move fails stays where it is, and so does the media folder.    let mut media_kept = false;    for entry in std::fs::read_dir(layout.client_media_dir()).into_iter().flatten().flatten() {        let database = entry.file_name().to_string_lossy().into_owned();        match crate::copy_keep::keep_media_with_kept(layout, &database, &entry.path()) {            Ok(true) => {}            // QUEUE BAD OP 7: no kept copy, but a copy of it still stands on this phone (one that did not leave, or one            // set aside whose media did not go with it): its media are part of what that copy holds, and stay.            Ok(false) if layout.replica(&database).exists() || layout.client_dir().join("aside").join(&database).exists() => media_kept = true,            Ok(false) => {}            Err(error) => {                eprintln!("[cotton-sync] {error}; they stay where they are");                media_kept = true;            }        }    }    let media = if media_kept { None } else { Some(layout.client_media_dir()) };    for folder in media.into_iter().chain([        layout.snapshots_dir(),        layout.thumbs_cache_dir(),        layout.exports_dir(),    ]) {        // not a copy: media no kept copy holds, snapshots, thumbnails and exports, in an erase.        if std::fs::remove_dir_all(&folder).is_ok() {            erased.deleted_folders += 1;        }    }    // The workspace folder itself, once its replica is gone: `leave_server`    // removes the file and the sidecars, and an empty `client/<ws>/` left    // behind is a directory named after a database this device no longer has.    if let Some(workspace_id) = workspace_id {        if let Some(folder) = layout.replica(workspace_id).parent() {            // not a copy: an empty folder only: remove_dir refuses one that holds anything.            let _ = std::fs::remove_dir(folder);        }    }    // not a copy: the device's identity, in an erase.    erased.deleted_author_id = std::fs::remove_file(crate::replica::device_file_path(layout)).is_ok();    // not a copy: the rehearsal device key.    erased.deleted_rehearsal_key = std::fs::remove_file(layout.rehearsal_device_key()).is_ok();    erased}#[cfg(test)]#[path = "leave_tests.rs"]mod tests;