//! A USED LOCAL DATABASE BROUGHT INTO THE OBJECT (owner, 1 Nov 2026). //! //! Before anyone signs in, the phone's own database is the authority; once //! an object exists it is. Backup is adopt: every write a person made on the //! phone before signing in — queued, parked, or held because no server ever //! checked the phone's clock — is posted to the object as a pass posts one //! ([`ObjectTransport`]'s acts on the row as the file holds it now), and only //! then is the phone's copy made from the object as a sign-in makes it //! (`cotton_ffi::phone::adopt`). //! //! What this half does, on the LOCAL database ([`ObjectTransport::replica`] //! is that file here): //! //! - **Each receipt is marked delivered in the local database as it lands** //! ([`mark_delivered`]: out of `_outbox` and `_parked`, `held` cleared on //! its `_writes` or `_tombstones` row), so an adopt stopped part way — a //! dropped line, the app killed — begins again from the receipts still //! unsent and posts nothing twice. The one op in flight when the app died //! is named in the adopt's log ([`AdoptLog`]) before it is posted: a create //! of it the object answers `duplicate_id` is this phone's own, landed //! before the kill, and is posted again as the row stands. //! - **The local database's id becomes the object's** in every value sent //! ([`Rekey`]): a media key is `/photos/…` and the object //! keeps only its own, and a one-row settings table is keyed by the //! database. The owner's person id likewise becomes the object's owner. //! - **The object's version stands** (the object wins): a create of an id //! the object already holds (a shell row, the owner row, a kit definition) //! is refused, as is every later change to that row and every change to a //! row this adopt did not make here; each is written down //! ([`crate::unsent::record_discarded`], filed in Feedback once the copy is //! open) and counted refused, never lost silently. //! - **A book the object holds by its file is that book** (books-4-walk, //! 6 Nov 2026: the same EPUB added on a phone before sign-in and already in //! the object from another phone became two books): before anything is //! posted the object's books are read ([`ObjectTransport::object_books`]), //! and a book made here whose file the object's book names is taken as the //! object's — its create is never posted, the object's version stands, and //! its id becomes the object's book's in every value sent after it, so a //! list or a highlight made on it here lands on the object's book. What the //! person then did to it here (read it, finished it, rated it) is posted to //! the object's book as the columns each change wrote (books-android-leftovers //! walk, 6 Nov 2026: a book finished before sign-in came back Want to read). //! - **Definitions go after rows**, through the same definition act as a //! connected phone, with the object's own refusal recorded when refused. //! - **A refusal for good** (any status but a transient one or a 401) is //! written down the same way and the adopt goes on; a transient one or a //! 401 stops it with the object's word and the local database whole. use std::collections::BTreeSet; use std::io::Write as _; use crate::unsent::UnsentChange; use super::*; /// What the object's version standing says, for the Feedback row. pub const OBJECT_STANDS: &str = "the object already holds this record, and its version stands"; /// The tables a database's definitions are kept in. pub const DEFINITION_TABLES: &[&str] = &["cotton_tool_definitions", "cotton_table_definitions", "cotton_board_definitions", "cotton_theme_definitions"]; /// Why the written-down changes of an adopt went. pub const ADOPT_DISCARDED_WHY: &str = "the object did not take them when this phone's own database was backed up"; /// The ids a local database's values carry that name it, and what the /// object calls the same thing: the database itself and its owner. #[derive(Debug, Clone, Default)] pub struct Rekey { pub pairs: Vec<(String, String)>, } impl Rekey { pub fn new(pairs: impl IntoIterator) -> Rekey { Rekey { pairs: pairs.into_iter().filter(|(from, to)| !from.is_empty() && !to.is_empty() && from != to).collect() } } pub fn text(&self, text: &str) -> String { let mut out = text.to_string(); for (from, to) in &self.pairs { if out.contains(from.as_str()) { out = out.replace(from.as_str(), to); } } out } pub fn value(&self, value: Value) -> Value { match value { Value::String(text) => Value::String(self.text(&text)), Value::Array(items) => Value::Array(items.into_iter().map(|item| self.value(item)).collect()), Value::Object(map) => Value::Object(map.into_iter().map(|(key, item)| (key, self.value(item))).collect()), other => other, } } } /// The adopt's own log, beside the local database (`adopt.log`): appended to /// as it goes, so a later adopt of the same database knows the op that was /// in flight, the rows it made in the object, and the rows whose object /// version stands. Gone with the local database's folder. #[derive(Debug)] pub struct AdoptLog { path: PathBuf, } /// What an [`AdoptLog`] says of the adopts before this one. #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct AdoptMemory { /// The op posted last, whose answer may never have been heard. pub in_flight: Option, /// `table\trow` of each row an earlier adopt made in the object. pub made: BTreeSet, /// `table\trow` of each row whose object version stands. pub standing: BTreeSet, /// The rows the adopt counted, as its screen says them ("n of m"). pub rows: Option, /// This phone's row id → the object's row id it is taken as: a book the /// object holds by its file. pub aliases: BTreeMap, } impl AdoptLog { pub fn beside(local: &Path) -> AdoptLog { AdoptLog { path: local.with_file_name("adopt.log") } } pub fn read(&self) -> AdoptMemory { let mut memory = AdoptMemory::default(); let Ok(text) = std::fs::read_to_string(&self.path) else { return memory }; for line in text.lines() { let mut words = line.splitn(2, ' '); match (words.next(), words.next()) { (Some("sending"), Some(op)) => memory.in_flight = Some(op.to_string()), (Some("landed"), _) => memory.in_flight = None, (Some("made"), Some(row)) => { memory.made.insert(row.to_string()); } (Some("standing"), Some(row)) => { memory.standing.insert(row.to_string()); } (Some("rows"), Some(rows)) => memory.rows = rows.parse().ok().or(memory.rows), (Some("alias"), Some(pair)) => { if let Some((here, object)) = pair.split_once(' ') { memory.aliases.insert(here.to_string(), object.to_string()); } } _ => {} } } memory } /// The rows the adopt counts, said again whenever they grow. pub fn rows(&self, rows: u64) -> Result<(), String> { self.append(&format!("rows {rows}")) } /// The adopt connected `object`'s copy before its rows went, to take the /// object's data key there: what it sends next waits for that key /// ([`AdoptLog::waits_in`]), and a later launch connected to `object` /// sends it. pub fn waits_key(&self, object: &str) -> Result<(), String> { self.append(&format!("waits {object}")) } /// The object whose copy this adopt connected to wait for its key. pub fn waits_in(&self) -> Option { self.lines().iter().rev().find_map(|line| line.strip_prefix("waits ").map(str::to_string)) } /// Every line the log holds, oldest first. pub(super) fn lines(&self) -> Vec { std::fs::read_to_string(&self.path).map(|text| text.lines().map(str::to_string).collect()).unwrap_or_default() } pub(super) fn append(&self, line: &str) -> Result<(), String> { let mut file = std::fs::OpenOptions::new() .create(true) .append(true) .open(&self.path) .map_err(|error| format!("the adopt's log could not be written ({error})"))?; writeln!(file, "{line}").map_err(|error| format!("the adopt's log could not be written ({error})")) } } /// The tables whose rows are one per file, and the column naming it: a row /// made here whose file the object's row names is that row. const ONE_PER_FILE: &[(&str, &str)] = &[("book", "file")]; fn row_key(table: &str, row: &str) -> String { format!("{table}\t{row}") } /// Where one op of an adopt ended. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Landing { /// The object took it (or it had nowhere to go: this phone's own table). Delivered, /// Written down, with why. Refused(String), } /// What the adopt is told of each op as it lands, to count rows by; it /// answers whether to go on (false: the person stopped backing up). pub type AdoptLanded<'a> = &'a mut dyn FnMut(&UnsentChange, &Landing) -> bool; /// The code an adopt the person stopped part way answers. pub const ADOPT_STOPPED: &str = "adopt_stopped"; /// What one adopt pass sent. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Adopted { pub delivered: usize, pub refused: usize, } /// What an adopt is handed. pub struct AdoptInto<'a> { pub layout: &'a crate::layout::Layout, /// The object's database: the discarded changes are filed under it. pub object_id: &'a str, /// The object's tables as it serves them (`/v1/definitions`' `tables`): /// a table the object defines as data (`face_settings`) is placed by /// these, never by this local database's own definitions. pub served_tables: &'a [Value], pub rekey: &'a Rekey, /// Whether a write's row, `(store table, row id)`, is the person's: one /// that is not (the app's own usage counts, admissions, vault entries, /// an act's history) stays with the local database and is never posted. pub sends: &'a dyn Fn(&str, &str) -> bool, /// ISO 8601, for what is written down. pub at: &'a str, } impl ObjectTransport { /// Post every write the local database at [`Self::replica`] has not sent /// (see the module's note), marking each delivered in that database as /// it lands and telling `landed`. An `Err` is the object's refusal that /// stops the adopt (nothing answered, failing, or the credential not /// taken), or the local file not answering: what has landed stays /// landed, and the rest waits for the next adopt. pub fn adopt_writes(&self, into: &AdoptInto<'_>, landed: AdoptLanded<'_>) -> Result { let io = |message: String| ObjectRefusal { status: 0, code: "io".into(), message }; if !self.replica.exists() { return Err(io("this phone's own database is not there".into())); } let mut receipts: Vec<_> = { let db = cotton_store::Driver::open_snapshot_reader(&self.replica).map_err(|error| io(format!("this phone's own database could not be opened ({error})")))?; crate::unsent::receipts(&db).map_err(io)? } .into_iter() .filter(|(op, _)| (into.sends)(&op.table, &op.row_id)) .collect(); receipts.sort_by_key(|(op, _)| DEFINITION_TABLES.contains(&op.table.as_str())); let mut sent = Adopted::default(); if receipts.is_empty() { return Ok(sent); } let map = self.map().with_defined(into.served_tables.iter()).map_err(io)?.answered(into.served_tables); let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX) .map_err(cotton_store::StoreError::from) .and_then(|file| cotton_store::Driver::from_connection(file, true)) .map_err(|error| io(format!("this phone's own database could not be opened for its writes ({error})")))?; let log = AdoptLog::beside(&self.replica); let mut memory = log.read(); // The object's rows by their file, read once a pass that makes one. let mut by_file: BTreeMap<(String, String), String> = BTreeMap::new(); for (table, column) in ONE_PER_FILE { let makes = receipts.iter().any(|(op, _)| map.ours(&op.table).is_some_and(|stored| stored.table == *table)); if makes { for (file, id) in self.object_files(table, column)? { by_file.insert(((*table).to_string(), file), id); } } } // A row goes up as it stands now, so its create can name a row made after it here (Story's first scene, // made before its place was chosen: the place came later in this queue). The object refuses that link // (`bad_link`); the row, and every later write to it, waits for the rest of the queue and is posted again // after it, pass by pass while a pass lands anything. Only a link still missing when nothing more lands is // written down (launch-story walk, 22 Nov 2026: a scene and its lines written before sign-in were discarded // as "story_scene.place names no story_place", and the script came back empty). let mut pending = receipts; let mut last_try = false; loop { let mut waits = Vec::new(); let mut waiting_rows: BTreeSet = BTreeSet::new(); let mut landed_any = false; for (op, waiting) in &pending { let change = UnsentChange::of(op, *waiting); let row = row_key(&op.table, &op.row_id); if waiting_rows.contains(&row) { waits.push((op.clone(), *waiting)); continue; } log.append(&format!("sending {}", op.op_id)).map_err(io)?; let landing = match self.adopt_op(file.connection(), &map, op, into, &mut memory, &by_file, &log) { Ok(Err(refusal)) if refusal.code == "bad_link" && !last_try => { waiting_rows.insert(row); waits.push((op.clone(), *waiting)); continue; } Ok(Ok(made)) => { if let Some(made_row) = made { log.append(&format!("made {made_row}")).map_err(io)?; memory.made.insert(made_row); } Landing::Delivered } Ok(Err(refusal)) if refusal.transient() || refusal.signs_out() => return Err(refusal), Ok(Err(refusal)) => { if refusal.code == "duplicate_id" || refusal.message == OBJECT_STANDS { let row = row_key(&op.table, &op.row_id); log.append(&format!("standing {row}")).map_err(io)?; memory.standing.insert(row); } Landing::Refused(refusal.message) } Err(unreadable) => Landing::Refused(unreadable), }; // KEPT FOUR 3 B: a founding row the object refused (another device founded the account first: // `vault_founded`) is never a kept row, never written down as discarded and never counted: the local // vault key it carried lives in its own file (`vault_keep::secure`), and the adopt goes on as into an // account with a vault. Nothing of it shows on the Sync screen. // Marked sent below like any write the object answered for good, so it is never posted again. let founding_given_way = matches!(landing, Landing::Refused(_)) && crate::founding::is_founding(&op.table); if founding_given_way { log.append(&format!("founding given way {}", op.op_id)).map_err(io)?; eprintln!("[adopt] the object took another device's founding first ({} {}): this one is dropped, its key kept locally", op.table, op.row_id); } else if let Landing::Refused(why) = &landing { // The row as it stands here is kept on this phone before its write is let go, and said in the // log: a refusal for good never takes away what a person wrote. if !change.is_bookkeeping() { if let Some(table) = map.ours(&op.table) { if let Ok(Some(data)) = row_now(file.connection(), table, &op.row_id) { let rekey = Rekey::new(into.rekey.pairs.iter().cloned().chain(memory.aliases.iter().map(|(here, object)| (here.clone(), object.clone())))); let kept = crate::unsent::KeptRow { table: table.table.clone(), row_id: rekey.text(&op.row_id), data: rekey.value(Value::Object(data)), why: why.clone(), at: into.at.to_string() }; crate::unsent::keep_row(into.layout, into.object_id, kept).map_err(io)?; eprintln!("[adopt] the object refused {} {} ({why}); the row is kept on this phone", op.table, op.row_id); } } } crate::unsent::record_discarded( into.layout, into.object_id, vec![change.clone()], BTreeMap::from([(op.op_id.clone(), why.clone())]), ADOPT_DISCARDED_WHY, into.at, ) .map_err(io)?; if !change.is_bookkeeping() { sent.refused += 1; } } else if !matches!(landing, Landing::Refused(_)) { sent.delivered += 1; } mark_delivered(&file, &op.op_id).map_err(|error| io(format!("the write could not be marked sent in this phone's own database ({error})")))?; log.append(&format!("landed {}", op.op_id)).map_err(io)?; memory.in_flight = None; landed_any = true; if !landed(&change, &landing) { return Err(ObjectRefusal { status: 0, code: ADOPT_STOPPED.into(), message: "the backup was stopped".into() }); } } if waits.is_empty() || last_try { break; } last_try = !landed_any; pending = waits; } Ok(sent) } /// One write of the local database posted as the act it is, rekeyed to /// the object. `Ok(Ok(Some(row)))` is a row this adopt made in the object. #[allow(clippy::too_many_arguments)] fn adopt_op( &self, file: &rusqlite::Connection, map: &ObjectTables, op: &CottonOp, into: &AdoptInto<'_>, memory: &mut AdoptMemory, by_file: &BTreeMap<(String, String), String>, log: &AdoptLog, ) -> Result, ObjectRefusal>, String> { if DEFINITION_TABLES.contains(&op.table.as_str()) { return self.send_definition(file, op, Some(into.rekey)).map(|answer| answer.map(|_| None)); } let Some(table) = map.ours(&op.table) else { // This phone's own table (its preferences, the store's bookkeeping): nowhere else for it to go. return Ok(Ok(None)); }; let row = row_key(&op.table, &op.row_id); let stands = || ObjectRefusal { status: 409, code: "object_stands".into(), message: OBJECT_STANDS.into() }; let receipt = canonical::decode(op.receipt.as_bytes()).map_err(|error| error.to_string())?; let kind = receipt.kind; // A row taken as the object's: its create is the object's, whose // version stands; what the person then did to it here — read it, // finished it, rated it — lands on the object's row, column by // column, as a connected phone's change would. if let Some(theirs) = memory.aliases.get(&op.row_id).cloned() { if !matches!(kind, Kind::Change) || row_binned(file, table, &op.row_id)? { return Ok(Ok(None)); } let Some(data) = row_now(file, table, &op.row_id)? else { return Ok(Ok(None)) }; let rekey = Rekey::new(into.rekey.pairs.iter().cloned().chain(memory.aliases.iter().map(|(here, object)| (here.clone(), object.clone())))); // A sealed table takes no clear patch: the row as it stands here // goes up whole, sealed under the object's id, as a connected // phone's write does. if table.seal.is_some() { let (data, blind) = match self.sealed_whole(table, &theirs, rekey.value(Value::Object(data))) { Ok(sealed) => sealed, Err(refusal) => return Ok(Err(refusal)), }; let mut args = json!({"table": table.table, "id": theirs, "data": data}); if let Some(blind) = blind { args["blind"] = json!(blind); } return Ok(self.post("update", args).map(|_| None)); } let changed: BTreeSet<&str> = table .columns .iter() .filter(|(_, ours, _)| receipt.fields.contains_key(ours)) .map(|(object, _, _)| object.as_str()) .chain(receipt.fields.keys().map(String::as_str)) .collect(); let data: Map = data.into_iter().filter(|(object, _)| changed.contains(object.as_str())).collect(); if data.is_empty() { return Ok(Ok(None)); } return Ok(self.post("update", json!({"table": table.table, "id": theirs, "data": rekey.value(Value::Object(data))})).map(|_| None)); } if matches!(kind, Kind::Create) { if let Some(column) = ONE_PER_FILE.iter().find(|(one, _)| *one == table.table).map(|(_, column)| *column) { let theirs = row_now(file, table, &op.row_id)? .and_then(|data| data.get(column).and_then(Value::as_str).map(|named| into.rekey.text(named))) .and_then(|named| by_file.get(&(table.table.clone(), named))); if let Some(theirs) = theirs { log.append(&format!("alias {} {theirs}", op.row_id))?; memory.aliases.insert(op.row_id.clone(), theirs.clone()); return Ok(Ok(None)); } } } let rekey = Rekey::new(into.rekey.pairs.iter().cloned().chain(memory.aliases.iter().map(|(here, object)| (here.clone(), object.clone())))); let into = &AdoptInto { rekey: &rekey, ..*into }; let id = into.rekey.text(&op.row_id); Ok(match kind { Kind::Retract if memory.standing.contains(&row) || !memory.made.contains(&row) => Err(stands()), Kind::Retract => self.post("delete", json!({"table": table.table, "id": id})).or_else(|refusal| if refusal.code == "no_such_record" { Ok(()) } else { Err(refusal) }).map(|_| None), Kind::Change if memory.standing.contains(&row) || !memory.made.contains(&row) => Err(stands()), Kind::Create if memory.standing.contains(&row) => Err(stands()), Kind::Create | Kind::Change => match row_now(file, table, &op.row_id)? { // Gone since: its retract follows in this queue. None => Ok(None), Some(data) => { // Put in the bin here: the object's delete, after its create. let binned = row_binned(file, table, &op.row_id)?; let gone = || self.post("delete", json!({"table": table.table, "id": id})).or_else(|refusal| if refusal.code == "no_such_record" { Ok(()) } else { Err(refusal) }); let data = into.rekey.value(Value::Object(data)); // A sealed table's row goes sealed, as a connected phone's write does. let (data, blind) = match self.sealed_whole(table, &id, data) { Ok(sealed) => sealed, Err(refusal) => return Ok(Err(refusal)), }; let mut args = json!({"table": table.table, "id": id, "data": data}); if let Some(blind) = blind { args["blind"] = json!(blind); } if matches!(kind, Kind::Change) { if binned { gone() } else { self.post("update", args) }.map(|_| None) } else { match self.post("create", args.clone()) { Ok(()) => Ok(Some(row)), // This phone's own create, posted before the app // stopped and never heard back: the row as it // stands replaces it. Err(refusal) if refusal.code == "duplicate_id" && memory.in_flight.as_deref() == Some(op.op_id.as_str()) => self.post("update", args).map(|_| Some(row)), Err(refusal) if refusal.code == "duplicate_id" => Err(ObjectRefusal { message: OBJECT_STANDS.into(), ..refusal }), Err(refusal) => Err(refusal), } .and_then(|made| if binned { gone().map(|()| made) } else { Ok(made) }) } } }, }) } } impl ObjectTransport { /// The object's live rows of `table` by the file `column` names: `file /// → row id`, every page of `GET /v1/sync?since=0&tables=`. fn object_files(&self, table: &str, column: &str) -> Result, ObjectRefusal> { let mut files = BTreeMap::new(); let mut path = format!("{}?since=0&tables={table}", routes::SYNC); loop { let (answer, _) = self.ask_page(&path)?; for row in answer["rows"].as_array().into_iter().flatten() { if row["table"] != json!(table) || row["deleted"] == json!(true) || !row["deleted_at"].is_null() || !row["data"]["deleted_at"].is_null() { continue; } if let (Some(id), Some(named)) = (row["id"].as_str(), row["data"][column].as_str()) { files.entry(named.to_string()).or_insert_with(|| id.to_string()); } } match answer["next"].as_str() { Some(next) => path = format!("{}?cursor={next}", routes::SYNC), None => return Ok(files), } } } } /// A receipt the object has: no longer queued, parked, or held in the local /// database, so no later adopt or pass sends it again. Its park ends as a /// delivered push (`cotton_store::rejected::delivered`), the one way a park /// the peer took ends. pub fn mark_delivered(file: &cotton_store::Driver, op_id: &str) -> cotton_store::Result<()> { use rusqlite::types::Value as SqlValue; let op = [SqlValue::Text(op_id.to_string())]; // `transaction` begins IMMEDIATE: the app writes this database while the // adopt runs (its usage, its device statements), and a deferred // transaction that read before such a write commits cannot then write — // SQLite answers SQLITE_BUSY_SNAPSHOT at once, past the busy timeout // (walk, 1 Nov 2026: a relaunched adopt stopped on it). Taking the write // lock first waits its turn and reads what is there now. file.transaction(|db| { let has = |table: &str| -> cotton_store::Result { Ok(db.get("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(table.to_string())])?.is_some()) }; if has("_outbox")? { // not a copy: a change the object has (mark_delivered): it leaves the queue once it is held there. db.run("DELETE FROM _outbox WHERE op_id = ?", &op)?; } if has("_parked")? { cotton_store::rejected::delivered(db, op_id)?; } for table in ["_writes", "_tombstones"] { if has(table)? { db.run(&format!("UPDATE {table} SET held = 0 WHERE op_id = ? AND held = 1"), &op)?; } } Ok(()) }) } #[cfg(test)] mod tests { use super::mark_delivered; use std::time::Duration; /// RULE: marking a write sent waits for the app's own write to the local database and then lands — never "database is locked" because the app wrote in between (walk, 1 Nov 2026). #[test] fn marking_a_write_sent_waits_for_the_apps_own_write() { let dir = tempfile::tempdir().expect("a dir"); let path = dir.path().join("replica.db"); let file = cotton_store::Driver::from_connection(rusqlite::Connection::open(&path).expect("the file"), true).expect("the driver"); file.connection().execute_batch( "PRAGMA journal_mode = WAL; CREATE TABLE _outbox (op_id TEXT PRIMARY KEY); CREATE TABLE _writes (op_id TEXT PRIMARY KEY, held INTEGER NOT NULL); CREATE TABLE cotton_usage (n INTEGER); INSERT INTO _outbox VALUES ('op-1'); INSERT INTO _writes VALUES ('op-1', 1);", ) .expect("the shape"); // The app holds the write lock and commits a moment later. let app = rusqlite::Connection::open(&path).expect("the app's connection"); app.execute_batch("BEGIN IMMEDIATE; INSERT INTO cotton_usage VALUES (1);").expect("the app writes"); let committing = std::thread::spawn(move || { std::thread::sleep(Duration::from_millis(300)); app.execute_batch("COMMIT").expect("the app commits"); }); mark_delivered(&file, "op-1").expect("marked sent once the app's write is in"); committing.join().expect("the app's thread"); let outbox: i64 = file.connection().query_row("SELECT COUNT(*) FROM _outbox", [], |row| row.get(0)).expect("a count"); let held: i64 = file.connection().query_row("SELECT held FROM _writes WHERE op_id = 'op-1'", [], |row| row.get(0)).expect("the write"); assert_eq!((outbox, held), (0, 0)); } }