//! ONE COPY, ONE OBJECT (coordinator, 14 Nov 2026). //! //! Books Dev on one simulator: B signed out, A signed in with another number, //! and A's Want to read showed B's books. B's copy had been kept as the local //! database at sign-out, and A's sign-in restored it whole into A's object. //! //! A copy that has ever been signed in belongs to its object: //! //! - **Signing out sets the copy aside** (`personal.standLocal {signedOut: //! true}`): its folder, its media and what the phone keeps of it move under //! `client/aside//`, where no attach, scan or read reaches, and the //! phone stands on a fresh local database of its own. It is kept, not //! removed: its unsent writes wait in it for its own person (the owner, //! 12 Nov 2026: a copy holding a row that did not go up is never deleted), //! and signing in again is as fast as a launch. //! - **Another person's sign-in never adopts, merges or sends it**: a copy //! still standing for another object is set aside the same way and the new //! object's copy is made fresh. The one exception is the owner's own //! restore-from-phone (10 Nov 2026): the SAME person — the same number, as //! each object's `GET /v1/me` says it — signing in to a new object (their //! old one gone) still brings the copy whole. //! - **Signing in again takes it back** (`personal.connect` naming that //! database): folder, media and keeps return, the copy opens as the //! object's, and its unsent writes go up by the loop. //! - A database this phone started and never signed in is adopted at its //! first sign-in, as it always was. //! //! The number is never kept: a copy is marked with a digest of it, salted by //! this device's id, written beside the copy (`signed-in.json`). use std::path::{Path, PathBuf}; use cotton_client::connection::{ConnectionFile, StoredConnection}; use cotton_client::layout::Layout; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use crate::methods::MethodError; /// Beside a copy: the object it was signed in to, and whose it is. const MARK: &str = "signed-in.json"; /// Where copies set aside are kept, under the client folder. const ASIDE: &str = "aside"; /// What a copy set aside keeps of its connection. const CONNECTION: &str = "connection.json"; /// Its media, set aside with it. const MEDIA: &str = "media"; /// What the phone keeps of a database's files, by key (`/…`): /// these files' maps follow the copy; their settings stay the phone's. /// Each is moved under its module's own write lock, so a keep written /// meanwhile (a download landing) is never lost. type Lock = fn() -> std::sync::MutexGuard<'static, ()>; const KEEPS: &[(&str, Lock)] = &[ (crate::phone::books::FILE, crate::phone::books::write_lock), (crate::phone::songs::FILE, crate::phone::songs::write_lock), (crate::phone::films::FILE, crate::phone::films::write_lock), ]; /// Whose a copy is: the object it was signed in to, and the person (a /// digest of their number) when this build saw it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Belongs { pub database: String, pub person: Option, } /// The digest a copy is marked with for the number `phone`, salted by this /// device's id: equal for the same number on this phone, and no number in it. pub fn person_of(phone: &str, device: &str) -> String { let digits: String = phone.chars().filter(char::is_ascii_digit).collect(); let mut hash = Sha256::new(); hash.update(b"cotton-copy-person\0"); hash.update(device.as_bytes()); hash.update(b"\0"); hash.update(digits.as_bytes()); hex::encode(hash.finalize()) } /// The person an object's `GET /v1/me` answer names, as a copy is marked. pub fn person_in(me: &Value, device: &str) -> Option { me["person"]["phone"].as_str().filter(|phone| !phone.trim().is_empty()).map(|phone| person_of(phone, device)) } fn mark_path(replica: &Path) -> Option { replica.parent().map(|folder| folder.join(MARK)) } /// Mark the copy at `replica` as signed in to `database`, by `person`. pub fn mark(replica: &Path, database: &str, person: Option<&str>) -> Result<(), MethodError> { let Some(path) = mark_path(replica) else { return Ok(()) }; let said = json!({"database": database, "person": person}); // not a copy: the sign-in mark, a keep or the connection kept with a copy set aside. std::fs::write(&path, said.to_string()).map_err(|error| MethodError::new("io", format!("this phone could not mark its copy ({error})"))) } /// The copy at `replica` is the phone's own again, signed in to nothing: its mark goes (a backup that never /// finished, given back on sign-out; `personal_object::stand_signed_out`). pub fn unmark(replica: &Path) -> Result<(), MethodError> { let Some(path) = mark_path(replica) else { return Ok(()) }; // not a copy: the mark beside it. match std::fs::remove_file(&path) { Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(MethodError::new("io", format!("this phone could not unmark its copy ({error})"))), _ => Ok(()), } } fn marked(replica: &Path) -> Option { let said: Value = serde_json::from_slice(&std::fs::read(mark_path(replica)?).ok()?).ok()?; Some(Belongs { database: said["database"].as_str()?.to_string(), person: said["person"].as_str().map(str::to_string) }) } /// Whether the copy at `replica` is marked as a copy of the person's object /// on Cotton's server (`personal.connect` marks every copy it makes). pub fn is_objects_copy(replica: &Path) -> bool { marked(replica).is_some() } /// Whose the database `held` names is, or `None` for one this phone started /// and never signed in: a copy of an object (connected, marked, or holding /// definitions an object wrote, as a copy from before this build does). pub fn belongs(layout: &Layout, held: &StoredConnection) -> Result, MethodError> { let Some(id) = held.workspace_id.as_deref().filter(|id| !id.is_empty()) else { return Ok(None) }; let replica = layout.replica(id); if let Some(mark) = marked(&replica) { return Ok(Some(mark)); } if held.mode.has_server() || (replica.exists() && crate::phone::adopt::former_copy(&replica)?) { return Ok(Some(Belongs { database: id.to_string(), person: None })); } Ok(None) } fn aside_dir(layout: &Layout) -> PathBuf { layout.client_dir().join(ASIDE) } /// Where a copy of `database` set aside is. pub fn aside_of(layout: &Layout, database: &str) -> PathBuf { aside_dir(layout).join(database) } fn io(what: &str) -> impl Fn(std::io::Error) -> MethodError + '_ { move |error| MethodError::new("io", format!("{what} ({error})")) } /// Move `from` to `to` when `from` exists; `to` must not. fn shift(from: &Path, to: &Path) -> Result<(), MethodError> { if !from.exists() { return Ok(()); } // A copy's folder moves only through the one place a copy moves (QUEUE BAD OP 4): one rename, whole. cotton_client::copy_keep::relocate_folder(from, to).map_err(|error| MethodError::new("io", format!("a copy could not be moved ({error})"))) } /// Every file under `from` moved to the same place under `to` where `to` /// has none (media files are named by their bytes, so one already there is /// the same file), and `from` gone. fn merge_into(from: &Path, to: &Path) -> Result<(), MethodError> { if !from.exists() { return Ok(()); } for entry in std::fs::read_dir(from).map_err(io("a folder could not be read"))?.flatten() { let (source, target) = (entry.path(), to.join(entry.file_name())); if source.is_dir() { std::fs::create_dir_all(&target).map_err(io("a folder could not be made"))?; merge_into(&source, &target)?; } else if !target.exists() { // not a copy: a media file, named by its bytes. std::fs::rename(&source, &target).map_err(io("a file could not be moved"))?; } } // not a copy: a media folder, every file in it merged above. std::fs::remove_dir_all(from).map_err(io("a folder could not be removed")) } fn read_json(path: &Path) -> Result>, MethodError> { match std::fs::read(path) { Ok(bytes) => serde_json::from_slice::(&bytes) .map_err(|error| MethodError::new("unreadable", format!("{} is not valid JSON ({error})", path.display()))) .map(|value| value.as_object().cloned()), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(error) => Err(MethodError::new("unreadable", format!("{} ({error})", path.display()))), } } fn write_json(path: &Path, value: &serde_json::Map) -> Result<(), MethodError> { let partial = path.with_extension(format!("json.{}.partial", std::process::id())); // not a copy: the sign-in mark, a keep or the connection kept with a copy set aside. std::fs::write(&partial, serde_json::to_vec_pretty(value).expect("JSON serialises")).map_err(io("a keep could not be written"))?; // not a copy: a keep file written whole. std::fs::rename(&partial, path).map_err(io("a keep could not be written")) } /// Each map of a keep file split: what is keyed under `database` goes from /// `from` into `to`, merged with what `to` holds; settings stay where they are. fn move_keeps(from: &Path, to: &Path, database: &str) -> Result<(), MethodError> { let Some(mut source) = read_json(from)? else { return Ok(()) }; let prefix = format!("{database}/"); let mut target = read_json(to)?.unwrap_or_default(); let mut moved = false; for (field, value) in source.iter_mut() { let Some(map) = value.as_object_mut() else { continue }; let keys: Vec = map.keys().filter(|key| key.starts_with(&prefix)).cloned().collect(); if keys.is_empty() { continue; } let into = target.entry(field.clone()).or_insert_with(|| json!({})); if !into.is_object() { *into = json!({}); } for key in keys { if let Some(entry) = map.remove(&key) { into.as_object_mut().expect("an object").insert(key, entry); } } moved = true; } if moved { write_json(&ready(to)?, &target)?; write_json(from, &source)?; } Ok(()) } fn ready(path: &Path) -> Result { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(io("a folder could not be made"))?; } Ok(path.to_path_buf()) } /// Set the database `held` names aside: its folder (copy, journal, marks), /// its media and what the phone keeps of its files move under /// `aside//` with its connection, and `connection.json` goes. The /// caller has let go of it (detached, no transport). Answers the database. pub fn set_aside(layout: &Layout, held: &StoredConnection) -> Result, MethodError> { let Some(database) = held.workspace_id.clone().filter(|id| !id.is_empty()) else { return Ok(None) }; let folder = layout.replica(&database).parent().map(Path::to_path_buf).unwrap_or_else(|| layout.client_dir().join(&database)); let mut into = aside_of(layout, &database); if into.exists() { // An earlier copy of the same database set aside and never taken // back: both are kept, the earlier under its own name. let earlier = aside_dir(layout).join(format!("{database}.{}", chrono::Utc::now().timestamp_millis())); shift(&into, &earlier)?; into = aside_of(layout, &database); } shift(&folder, &into)?; std::fs::create_dir_all(&into).map_err(io("a folder could not be made"))?; shift(&layout.client_media_dir().join(&database), &into.join(MEDIA))?; for (keep, lock) in KEEPS { let _guard = lock(); move_keeps(&layout.client_dir().join(keep), &into.join(keep), &database)?; } // not a copy: the sign-in mark, a keep or the connection kept with a copy set aside. std::fs::write(into.join(CONNECTION), serde_json::to_vec_pretty(held).expect("a connection serialises")).map_err(io("a connection could not be kept"))?; // not a copy: the connection file. match std::fs::remove_file(layout.connection_json()) { Ok(()) => {} Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(MethodError::new("io", format!("this phone's connection could not be removed ({error})"))), } Ok(Some(database)) } /// Take the copy set aside as `name` back where copies are opened: its /// folder, media and keeps return. Answers the connection it was set aside /// with, or `None` when none is set aside (or a copy of it already stands). pub fn take_back(layout: &Layout, name: &str) -> Result, MethodError> { let from = aside_of(layout, name); if !from.join("replica.db").exists() { return Ok(None); } let held: Option = std::fs::read(from.join(CONNECTION)).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()); // The database it is a copy of, as its connection says (an earlier copy // set aside beside a later one is kept under `.`). let database = held.as_ref().and_then(|held| held.workspace_id.clone()).unwrap_or_else(|| name.to_string()); let database = database.as_str(); let folder = layout.replica(database).parent().map(Path::to_path_buf).unwrap_or_else(|| layout.client_dir().join(database)); // An empty folder where the copy was (a pass let go of as the copy moved // makes its folder again before it finds no file) holds nothing: it goes. // A folder holding anything is a copy of its own, never written over. // not a copy: an empty folder only: remove_dir refuses one that holds anything. if folder.exists() && std::fs::remove_dir(&folder).is_err() { return Ok(None); } let media = layout.client_media_dir().join(database); if !media.exists() { shift(&from.join(MEDIA), &media)?; } else { // A media folder made again meanwhile (a fetch landing as the copy // moved): the files set aside join it. Left behind, they went into the // copy's own folder below as `/media/`, where nothing reads // or removes them. merge_into(&from.join(MEDIA), &media)?; } for (keep, lock) in KEEPS { let _guard = lock(); move_keeps(&from.join(keep), &layout.client_dir().join(keep), database)?; // not a copy: a keep file moved above. let _ = std::fs::remove_file(from.join(keep)); } // not a copy: the connection it was set aside with. let _ = std::fs::remove_file(from.join(CONNECTION)); shift(&from, &folder)?; Ok(held) } /// The copy set aside that a sign-in to `database` takes back: the copy of /// that database, or else one marked as going into it (a database whose /// adopt into it began, or a restore of the same person's former copy). pub fn aside_for(layout: &Layout, database: &str) -> Option { if is_aside(layout, database) { return Some(database.to_string()); } let mut marked_for: Vec = std::fs::read_dir(aside_dir(layout)) .ok()? .flatten() .filter_map(|entry| entry.file_name().to_str().map(str::to_string)) .filter(|name| marked(&aside_of(layout, name).join("replica.db")).is_some_and(|mark| mark.database == database)) .collect(); marked_for.sort(); marked_for.into_iter().next() } /// Whether a copy of `database` is set aside on this phone. pub fn is_aside(layout: &Layout, database: &str) -> bool { aside_of(layout, database).join("replica.db").exists() } /// The connection this phone holds now. pub fn held(layout: &Layout) -> Option { ConnectionFile::at(layout.connection_json()).read() } #[cfg(test)] mod tests { use super::*; #[test] fn the_same_number_is_the_same_person_on_this_phone_and_no_number_is_kept() { let one = person_of("+91 90000 00001", "device-a"); assert_eq!(one, person_of("+919000000001", "device-a")); assert_ne!(one, person_of("+919000000002", "device-a")); assert_ne!(one, person_of("+919000000001", "device-b")); assert!(!one.contains("9000000001")); } /// RULE (21 Nov 2026): a copy taken back while its database's media folder was made again meanwhile brings its files into that folder; none is left inside the copy's own folder, where nothing reads or removes it. #[test] fn a_copy_taken_back_beside_a_media_folder_made_again_leaves_no_file_behind() { let dir = tempfile::tempdir().expect("a container"); let layout = Layout::new(dir.path()); let database = "11111111-1111-4111-8111-111111111111"; let aside = aside_of(&layout, database); std::fs::create_dir_all(aside.join(MEDIA).join("aa")).expect("aside media"); std::fs::write(aside.join("replica.db"), b"copy").expect("the copy"); std::fs::write(aside.join(MEDIA).join("aa/kept.jpg"), b"kept").expect("a file set aside"); std::fs::write(aside.join(MEDIA).join("aa/both.jpg"), b"same").expect("a file in both"); let media = layout.client_media_dir().join(database); std::fs::create_dir_all(media.join("aa")).expect("the media folder made again"); std::fs::write(media.join("aa/both.jpg"), b"same").expect("landed meanwhile"); take_back(&layout, database).expect("taken back"); assert_eq!(std::fs::read(media.join("aa/kept.jpg")).expect("the file set aside is in the media folder"), b"kept"); assert_eq!(std::fs::read(media.join("aa/both.jpg")).expect("the file in both"), b"same"); let folder = layout.replica(database).parent().expect("a folder").to_path_buf(); assert!(folder.join("replica.db").exists(), "the copy is back"); assert!(!folder.join(MEDIA).exists(), "no media left inside the copy's folder"); } } /// Everything this phone holds of `database`, gone for good: its folder (the /// copy, its journal and marks), its media, what the keeps say of its files, /// and every copy of it set aside. The person deleted the account /// (`phone::account_delete`); the caller has let go of it. Answers whether /// anything was there. pub fn forget(layout: &Layout, database: &str, act: &cotton_client::copy_keep::PersonsAct) -> Result { if database.is_empty() || database.contains('/') || database.contains("..") { return Ok(false); } let mut held = false; // A pass that was under way as the phone let go may still write a file into the folder: a removal that meets // one is tried again, a few times, before it is said. let mut gone = |path: PathBuf| -> Result<(), MethodError> { if !path.exists() { return Ok(()); } held = true; // The website stores its Sites list named go with it (`sites.stores.gone`). crate::phone::sites::folder_forgotten(layout, &path); // The account is deleted: one of the three endings that remove a copy (QUEUE BAD OP 4). cotton_client::copy_keep::remove_for_account(&path, act).map_err(|error| MethodError::new("io", format!("a folder could not be removed ({error})"))) }; cotton_client::copy_keep::forget_account(layout, database, act).map_err(|error| MethodError::new("io", format!("the kept copies could not be removed ({error})")))?; if let Some(folder) = layout.replica(database).parent() { gone(folder.to_path_buf())?; } gone(layout.client_media_dir().join(database))?; let named: Vec = std::fs::read_dir(aside_dir(layout)) .into_iter() .flatten() .flatten() .filter(|entry| entry.file_name().to_str().is_some_and(|name| name == database || name.starts_with(&format!("{database}.")))) .map(|entry| entry.path()) .collect(); for path in named { gone(path)?; } let prefix = format!("{database}/"); for (keep, lock) in KEEPS { let _guard = lock(); let path = layout.client_dir().join(keep); let Some(mut source) = read_json(&path)? else { continue }; let mut changed = false; for value in source.values_mut() { let Some(map) = value.as_object_mut() else { continue }; let before = map.len(); map.retain(|key, _| !key.starts_with(&prefix)); changed |= map.len() != before; } if changed { held = true; write_json(&path, &source)?; } } // The notes beside the copies that name it: Home's sync line (`home-lines.json`, keyed by database) and the // pass's cursors (`held.json`, under `files`). let home_lines = layout.home_lines_json(); if let Some(mut lines) = read_json(&home_lines)? { if lines.remove(database).is_some() { held = true; write_json(&home_lines, &lines)?; } } let notes = cotton_client::connection::held::HeldNotes::beside(&layout.connection_json()); if notes.read(database).is_some() { held = true; notes.forget(database).map_err(|error| MethodError::new("io", format!("this phone's notes could not be changed ({error})")))?; } Ok(held) }