Cotton code
715 lines · 35.5 KB · RustRaw
//! A FORMER OBJECT'S COPY GOES WHOLE INTO THE NEW OBJECT (restore-from-phone,//! owner, 10 Nov 2026).//!//! The live Worker and every object were deleted on 9 Nov; the only whole//! copies of the owner's rows were the copies on his phone, one per app. A//! copy that was an object's cache holds almost no unsent receipts — its rows//! were pulled, or already delivered — so an adopt of its receipts alone//! ([`ObjectTransport::adopt_writes`]) would send next to nothing. A copy//! that names a database other than the one the sign-in answered is brought//! in WHOLE here: every live row of every table the app's kit keeps, pulled,//! delivered or unsent alike, read from the tables as the copy holds them//! now, ids kept, the old database's id and owner rewritten to the new//! object's ([`Rekey`]), each with its own `created_at` and `updated_at`.//!//! - **Through the object's `restore` act** (`apps/business`), at most//!   [`RESTORE_BATCH`] rows a call: a row the object lacks is made, one it//!   holds live takes the phone's version when the phone's `updated_at` is//!   not older than its own (rows imported from a backup meanwhile), one it//!   deleted stays deleted. A held id is answered, never refused, so a call//!   that landed unheard is sent again and changes nothing.//! - **Parents before children**: the tables go in the order their links//!   make ([`restore_order`]), the kit's order otherwise, as the object//!   refuses a link to a row it lacks (`bad_link`). A row refused for that//!   alone waits for the next round; a round that lands nothing more sends//!   each waiting row once without the links it still lacks and then whole//!   (a transfer and its twin name each other).//! - **Resumable**: every row the object answered is written in the adopt's//!   log beside the copy (`restored <table>\t<id>\t<updated_at>`), so an//!   adopt stopped part way sends only what is left, and a row changed since//!   it went is sent again.//! - **Nothing is lost quietly**: a row the object refuses for good (any//!   status but a transient one or a 401) is written down//!   ([`crate::unsent::record_discarded`], filed in Feedback once the new//!   copy opens) and counted refused; a transient refusal or a 401 stops the//!   restore with the object's word and the copy whole.//! - **Tombstoned rows are not sent**, nor a row in this copy's bin; a view//!   (a table whose definition reads another's, `source`) holds no rows of//!   its own; and a computed column is the object's to work out.use std::collections::{BTreeMap, BTreeSet};use super::adopt::{AdoptLog, Landing, Rekey, ADOPT_DISCARDED_WHY, ADOPT_STOPPED};use super::*;/// The rows one `restore` act carries at most (the object takes 500).pub const RESTORE_BATCH: usize = 200;/// How many calls running the object may leave unanswered before a restore/// gives up; a call that lands restores it.pub const RESTORE_PATIENCE: u32 = 8;/// The pause before rows the object did not answer for are sent again.#[cfg(not(test))]const RESTORE_PAUSE: std::time::Duration = std::time::Duration::from_secs(2);#[cfg(test)]const RESTORE_PAUSE: std::time::Duration = std::time::Duration::from_millis(1);/// The tables whose links the object does not check (`engine.ts`/// `checkLinks`): no order waits on them.const UNCHECKED_LINKS: &[&str] = &["person", "photo"];/// One live row of a former object's copy.#[derive(Debug, Clone, PartialEq, Eq)]pub struct WholeRow {    /// The object's table (`todo`).    pub table: String,    /// Where this copy keeps it (`cotton_todos`).    pub store: String,    /// The row's id in this copy (the object's id is it, rekeyed).    pub id: String,    /// When it last changed, as this copy holds it.    pub updated_at: Option<String>,}impl WholeRow {    /// `table\tid`, as the adopt's log names it.    pub fn address(&self) -> String {        format!("{}\t{}", self.table, self.id)    }}/// What a restore is handed.pub struct RestoreInto<'a> {    pub layout: &'a crate::layout::Layout,    /// The new object's database: what is written down is filed under it.    pub object_id: &'a str,    /// The object's tables as it serves them (`/v1/definitions`' `tables`),    /// or, before any is asked, the ones this copy holds: what places a    /// table's rows and says its links.    pub served_tables: &'a [Value],    /// The object tables the app keeps (its kit's), in the kit's order.    pub tables: &'a [String],    pub rekey: &'a Rekey,    /// ISO 8601, for what is written down.    pub at: &'a str,}/// What is written of each row a send answers for.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Written {    /// Each answer in the adopt's log, and each row refused for good written    /// down (a former copy's restore, which resumes from the log).    Logged,    /// Each row refused for good written down with its id and the object's    /// reason (filed in Feedback); no log. Before a copy is deleted.    Down,    /// Nothing: the next run asks the object again.    Nothing,}/// What one restore sent.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Restored {    /// Rows the object answered for, this call.    pub sent: usize,    /// The object's version after the last call that landed: a copy that has    /// pulled through it holds every row restored.    pub version: i64,    /// Rows it refused for good, written down.    pub refused: usize,}/// What the restore is told of each row as the object answers for it; it/// answers whether to go on (false: the person stopped backing up).pub type RestoreLanded<'a> = &'a mut dyn FnMut(&WholeRow, &Landing) -> bool;/// What an adopt's log says of the rows restored before.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct RestoreMemory {    /// `table\tid` → the `updated_at` the object answered for.    pub restored: BTreeMap<String, String>,    /// `table\tid` of each row refused for good, written down.    pub lost: BTreeSet<String>,}impl RestoreMemory {    /// Whether `row` needs sending: never answered, or changed since.    pub fn owes(&self, row: &WholeRow) -> bool {        let key = row.address();        !self.lost.contains(&key) && self.restored.get(&key) != Some(&row.updated_at.clone().unwrap_or_default())    }}impl AdoptLog {    /// The object has every row of this copy through `version`, and its new    /// copy is connected: once that copy has pulled through it, this one    /// goes ([`AdoptLog::restored_into`]).    pub fn restored_whole(&self, object: &str, version: i64) -> Result<(), String> {        self.append(&format!("into {object} {version}"))    }    /// The object this copy was restored whole into, and the version its new    /// copy must pull through before this one goes.    pub fn restored_into(&self) -> Option<(String, i64)> {        self.lines().iter().rev().find_map(|line| {            let (object, version) = line.strip_prefix("into ")?.split_once(' ')?;            Some((object.to_string(), version.parse().ok()?))        })    }    /// The rows earlier restores of this copy answered for, and lost.    pub fn restored(&self) -> RestoreMemory {        let mut memory = RestoreMemory::default();        for line in self.lines() {            if let Some(rest) = line.strip_prefix("restored ") {                let mut parts = rest.splitn(3, '\t');                if let (Some(table), Some(id)) = (parts.next(), parts.next()) {                    memory.restored.insert(format!("{table}\t{id}"), parts.next().unwrap_or_default().to_string());                }            } else if let Some(row) = line.strip_prefix("lost ") {                memory.lost.insert(row.to_string());            }        }        memory    }}/// The object's table definitions a copy holds, as the object wrote them:/// none in a database this phone started itself. A copy holding any was an/// object's cache.pub fn object_definitions(path: &Path) -> Result<Vec<Value>, String> {    if !path.exists() {        return Ok(Vec::new());    }    let file = rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)        .map_err(|error| format!("this phone's copy could not be read ({error})"))?;    if file_columns(&file, "cotton_table_definitions")?.is_empty() {        return Ok(Vec::new());    }    let unreadable = |error: rusqlite::Error| format!("cotton_table_definitions could not be read ({error})");    let mut statement = file.prepare("SELECT definition, _hlc FROM cotton_table_definitions").map_err(unreadable)?;    let rows = statement.query_map([], |row| Ok((row.get::<_, Option<String>>(0)?, row.get::<_, Option<String>>(1)?))).map_err(unreadable)?;    let mut out = Vec::new();    for row in rows {        let (definition, stamp) = row.map_err(unreadable)?;        if cotton_store::fold::author_of(stamp.as_deref().unwrap_or_default()) != Some(OBJECT_AUTHOR) {            continue;        }        if let Some(definition) = definition.and_then(|text| serde_json::from_str(&text).ok()) {            out.push(definition);        }    }    Ok(out)}/// The definition of `table` among `served`.fn definition_of<'a>(served: &'a [Value], table: &str) -> Option<&'a Value> {    served.iter().find(|definition| definition["id"] == json!(table))}/// The links of `table` the object checks, by column: `(column, linked table)`.fn checked_links(served: &[Value], table: &str) -> Vec<(String, String)> {    definition_of(served, table)        .and_then(|definition| definition["columns"].as_array())        .into_iter()        .flatten()        .filter(|column| column["type"] == json!("link") && column["computed"].is_null())        .filter_map(|column| Some((column["key"].as_str()?.to_string(), column["link_to"].as_str()?.to_string())))        .filter(|(_, to)| !UNCHECKED_LINKS.contains(&to.as_str()))        .collect()}/// `tables` in the order their links make — each after the tables it links/// to among them — and the kit's order where nothing decides (a cycle/// keeps it too; the rounds settle what it leaves).pub fn restore_order(served: &[Value], tables: &[String]) -> Vec<String> {    let wanted: BTreeSet<&str> = tables.iter().map(String::as_str).collect();    let mut placed: Vec<String> = Vec::with_capacity(tables.len());    let mut left: Vec<&String> = tables.iter().collect();    while !left.is_empty() {        let ready = left.iter().position(|table| {            checked_links(served, table).iter().all(|(_, to)| to == *table || !wanted.contains(to.as_str()) || placed.contains(to))        });        let next = left.remove(ready.unwrap_or(0));        placed.push(next.clone());    }    placed}/// One row as the `restore` act takes it: `data` already in the object's/// ids (and sealed, for a sealed table, with its `blind` tokens).fn restore_row(row: &WholeRow, data: Value, blind: Option<Vec<String>>, created_at: Option<String>, rekey: &Rekey) -> Value {    let mut said = json!({"table": row.table, "id": rekey.text(&row.id), "data": data});    if let Some(blind) = blind {        said["blind"] = json!(blind);    }    if let Some(at) = created_at {        said["created_at"] = json!(at);    }    if let Some(at) = &row.updated_at {        said["updated_at"] = json!(at);    }    said}/// A stored time, as the object keeps one.fn stamp_of(file: &rusqlite::Connection, table: &StoredTable, id: &str, column: &str) -> Result<Option<String>, String> {    let sql = format!("SELECT \"{column}\" FROM \"{}\" WHERE \"{}\" = ?1", table.store, table.key_column);    let value: Option<SqlValue> = file        .query_row(&sql, [id], |row| row.get::<_, SqlValue>(0))        .map(Some)        .or_else(|error| if matches!(error, rusqlite::Error::QueryReturnedNoRows) { Ok(None) } else { Err(error) })        .map_err(|error| format!("{} {id} could not be read ({error})", table.store))?;    Ok(value        .and_then(|value| decode_value(Codec::Timestamp, &value).ok())        .and_then(|value| value.as_str().map(str::to_string))        .filter(|at| !at.is_empty()))}/// Every live row of the kit's tables in the copy at `path`,/// in the order they are sent: the tables by [`restore_order`], each by/// id. A table this copy does not hold, or holds no row of, gives none.pub fn whole_rows(path: &Path, into: &RestoreInto<'_>) -> Result<Vec<WholeRow>, String> {    if !path.exists() {        return Ok(Vec::new());    }    let map = ObjectTables::personal().with_defined(into.served_tables.iter())?.answered(into.served_tables);    let file = rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)        .map_err(|error| format!("this phone's copy could not be read ({error})"))?;    let mut rows = Vec::new();    for name in restore_order(into.served_tables, into.tables) {        let Some(table) = map.object(&name) else { continue };        // A view reads another table's rows and holds none.        if definition_of(into.served_tables, &name).is_some_and(|definition| !definition["source"].is_null()) {            continue;        }        let columns = file_columns(&file, &table.store)?;        if columns.is_empty() {            continue;        }        let has_updated = columns.iter().any(|column| column == "updated_at");        let unreadable = |error: rusqlite::Error| format!("{} could not be read ({error})", table.store);        let mut statement = file.prepare(&format!("SELECT \"{0}\" FROM \"{1}\" ORDER BY \"{0}\"", table.key_column, table.store)).map_err(unreadable)?;        let ids: Vec<String> = statement.query_map([], |row| row.get::<_, SqlValue>(0)).map_err(unreadable)?            .filter_map(|id| match id { Ok(SqlValue::Text(id)) => Some(Ok(id)), Ok(_) => None, Err(error) => Some(Err(unreadable(error))) })            .collect::<Result<_, _>>()?;        for id in ids {            if row_binned(&file, table, &id)? {                continue;            }            let updated_at = if has_updated { stamp_of(&file, table, &id, "updated_at")? } else { None };            rows.push(WholeRow { table: name.clone(), store: table.store.clone(), id, updated_at });        }    }    Ok(rows)}/// The tables of the copy at `path` that hold live rows and that nothing/// here has a name for, each with how many: a `cotton_` table this build's/// store does not compile and no definition the copy holds declares, the/// object's or its own build's — one an earlier build kept and this one dropped. [`whole_rows`] cannot say its/// rows to the object, so a copy holding one is never deleted.pub fn unnamed_tables(path: &Path, into: &RestoreInto<'_>) -> Result<Vec<(String, usize)>, String> {    if !path.exists() {        return Ok(Vec::new());    }    let file = rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)        .map_err(|error| format!("this phone's copy could not be read ({error})"))?;    let unreadable = |error: rusqlite::Error| format!("this phone's copy could not be read ({error})");    // Every definition the copy holds, whoever laid it: the object's, and the    // ones the build that made the copy laid itself (its lines).    let mut held: Vec<Value> = into.served_tables.to_vec();    if !file_columns(&file, "cotton_table_definitions")?.is_empty() {        let mut statement = file.prepare("SELECT definition FROM cotton_table_definitions").map_err(unreadable)?;        let texts: Vec<Option<String>> = statement.query_map([], |row| row.get(0)).map_err(unreadable)?.collect::<Result<_, _>>().map_err(unreadable)?;        held.extend(texts.into_iter().flatten().filter_map(|text| serde_json::from_str(&text).ok()));    }    let mut declared: BTreeSet<String> = BTreeSet::new();    for definition in &held {        // A definition that does not read declares nothing here: its table stays unnamed.        if let Ok(Some(tables)) = cotton_store::schema::package_shape::declared(definition) {            declared.extend(tables.into_iter().map(|table| table.table.name));        }    }    let mut statement = file.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND substr(name, 1, 7) = 'cotton_' ORDER BY name").map_err(unreadable)?;    let stores: Vec<String> = statement.query_map([], |row| row.get::<_, String>(0)).map_err(unreadable)?.collect::<Result<_, _>>().map_err(unreadable)?;    let mut unnamed = Vec::new();    for store in stores {        if cotton_store::schema::specs::spec_for(&store).is_some() || declared.contains(&store) {            continue;        }        let live = if file_columns(&file, &store)?.iter().any(|column| column == "deleted_at") { " WHERE \"deleted_at\" IS NULL" } else { "" };        let rows: i64 = file.query_row(&format!("SELECT COUNT(*) FROM \"{store}\"{live}"), [], |row| row.get(0)).map_err(|error| format!("{store} could not be read ({error})"))?;        if rows > 0 {            unnamed.push((store, rows as usize));        }    }    Ok(unnamed)}/// Whether the copy at `path` has pulled the object through `version`:/// its cursor is past it, with no page of a pass still to come.pub fn caught_up(path: &Path, version: i64) -> Result<bool, String> {    let db = cotton_store::Driver::open_snapshot_reader(path).map_err(|error| format!("the new copy could not be read ({error})"))?;    let cursors = cotton_store::cursors::read_cursors(&db).map_err(|error| error.to_string())?;    let Some(held) = cursors.get(CURSOR_KEY) else { return Ok(false) };    let (_, since, page) = read_cursor(held);    Ok(page.is_none() && since >= version)}/// Where one row of a call ended.enum Answer {    Landed,    /// Refused for a link to a row the object lacks: it waits for a round.    Waits(String),    Lost(String),}impl ObjectTransport {    /// Send every row of [`whole_rows`] the adopt's log does not say    /// the object answered for (see the module's note), telling `landed` of    /// each as it is answered. An `Err` is the object's refusal that stops    /// the restore (nothing answered, failing, the credential not taken, or    /// the person stopped it), or the copy not answering: what landed stays    /// written in the log, and the rest waits for the next adopt.    pub fn restore_rows(&self, into: &RestoreInto<'_>, landed: RestoreLanded<'_>) -> Result<Restored, ObjectRefusal> {        self.restore_rows_except(into, landed, &|_, _| false)    }    /// [`Self::restore_rows`], leaving out each row `kept_here` names by `(store, id)`: rows the person chose to keep    /// only on this phone (Cotton Sites' "Keep only on this phone") never go up.    pub fn restore_rows_except(&self, into: &RestoreInto<'_>, landed: RestoreLanded<'_>, kept_here: &dyn Fn(&str, &str) -> bool) -> Result<Restored, ObjectRefusal> {        let io = |message: String| ObjectRefusal { status: 0, code: "io".into(), message };        let memory = AdoptLog::beside(&self.replica).restored();        let queue: Vec<WholeRow> = whole_rows(&self.replica, into).map_err(io)?.into_iter().filter(|row| memory.owes(row) && !kept_here(&row.store, &row.id)).collect();        self.send_rows(into, queue, landed, Written::Logged)    }    /// Every row the object holds of `tables`, live or binned, as    /// `table\tid`: what the object says it holds, asked now; nothing this    /// copy remembers. Asked by ids alone ([`routes::HELD`]); an object    /// older than that route (404 on its first page, or an answer naming no    /// `held`) is asked by every page of `GET /v1/sync?since=0&tables=…`,    /// every row with its data, as it was before the route.    pub fn held_rows(&self, tables: &[String]) -> Result<BTreeSet<String>, ObjectRefusal> {        if tables.is_empty() {            return Ok(BTreeSet::new());        }        match self.held_ids(tables)? {            Some(held) => Ok(held),            None => self.held_by_pull(tables),        }    }    /// Every page of `GET /v1/held?tables=…`; `None` when the object does    /// not serve it.    fn held_ids(&self, tables: &[String]) -> Result<Option<BTreeSet<String>>, ObjectRefusal> {        let mut held = BTreeSet::new();        let mut path = format!("{}?tables={}", routes::HELD, tables.join(","));        let mut first = true;        loop {            let answer = match self.ask_page(&path) {                Ok((answer, _)) => answer,                Err(refusal) if first && refusal.status == 404 => return Ok(None),                Err(refusal) => return Err(refusal),            };            let Some(tables) = answer["held"].as_object() else {                if first {                    return Ok(None);                }                return Err(ObjectRefusal { status: 0, code: "bad_answer".into(), message: "a later page of the held ids named none".into() });            };            for (table, ids) in tables {                for id in ids["live"].as_array().into_iter().chain(ids["binned"].as_array()).flatten().filter_map(Value::as_str) {                    held.insert(format!("{table}\t{id}"));                }            }            first = false;            match answer["next"].as_str() {                Some(next) => path = format!("{}?cursor={next}", routes::HELD),                None => return Ok(Some(held)),            }        }    }    /// Every page of `GET /v1/sync?since=0&tables=…`: an object without    /// [`routes::HELD`].    fn held_by_pull(&self, tables: &[String]) -> Result<BTreeSet<String>, ObjectRefusal> {        let mut held = BTreeSet::new();        let mut path = format!("{}?since=0&tables={}", routes::SYNC, tables.join(","));        loop {            let (answer, _) = self.ask_page(&path)?;            for row in answer["rows"].as_array().into_iter().flatten() {                if let (Some(table), Some(id)) = (row["table"].as_str(), row["id"].as_str()) {                    held.insert(format!("{table}\t{id}"));                }            }            match answer["next"].as_str() {                Some(next) => path = format!("{}?cursor={next}", routes::SYNC),                None => return Ok(held),            }        }    }    /// A COPY IS NEVER TRUSTED AS ONLY A CACHE (owner, 11 Nov 2026): the    /// object is asked what it holds ([`ObjectTransport::held_rows`]) and    /// every live row of this copy it lacks goes up through its `restore`    /// act, whatever the database's id and whatever this copy's cursor,    /// receipts or adopt log say was sent. A row the object binned is one it    /// holds, so it stays binned; a row it holds live is left as it stands    /// (a pass carries changes); a run after one that landed everything    /// finds nothing lacking and sends nothing. Nothing is written in the    /// adopt's log: the next run asks again. `written` says whether a row    /// the object refuses for good is written down with its id and the    /// object's reason ([`Written::Down`]: before a copy is deleted).    pub fn top_up(&self, into: &RestoreInto<'_>, landed: RestoreLanded<'_>, written: Written) -> Result<Restored, ObjectRefusal> {        let queue = self.lacking(into)?;        self.send_rows(into, queue, landed, written)    }    /// Every live row of this copy the object does not hold, asked now, in    /// the order a restore sends them.    pub fn lacking(&self, into: &RestoreInto<'_>) -> Result<Vec<WholeRow>, ObjectRefusal> {        let io = |message: String| ObjectRefusal { status: 0, code: "io".into(), message };        let whole = whole_rows(&self.replica, into).map_err(io)?;        if whole.is_empty() {            return Ok(Vec::new());        }        let mut tables: Vec<String> = Vec::new();        for row in &whole {            if !tables.contains(&row.table) {                tables.push(row.table.clone());            }        }        let held = self.held_rows(&tables)?;        Ok(whole.into_iter().filter(|row| !held.contains(&row.address())).collect())    }    /// Send `queue` through the object's `restore` act, parents before    /// children as the queue orders them; what is written of each answer is    /// `written`'s to say.    fn send_rows(&self, into: &RestoreInto<'_>, mut queue: Vec<WholeRow>, landed: RestoreLanded<'_>, written: Written) -> Result<Restored, ObjectRefusal> {        let logged = written == Written::Logged;        let io = |message: String| ObjectRefusal { status: 0, code: "io".into(), message };        let log = AdoptLog::beside(&self.replica);        let mut sent = Restored::default();        if queue.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_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)            .map_err(|error| io(format!("this phone's copy could not be read ({error})")))?;        // The row as the act takes it, `without` the links it names; a        // sealed table's sealed (no key stops the send, the copy whole).        let said = |row: &WholeRow, without: &[String]| -> Result<Option<Value>, ObjectRefusal> {            let Some(table) = map.object(&row.table) else { return Ok(None) };            // A column the object defines now that this copy never held (its            // build pulled an older definition) is not this copy's to say.            let held = file_columns(&file, &table.store).map_err(io)?;            let mut table = table.clone();            table.columns.retain(|(_, ours, _)| held.contains(ours));            let table = &table;            let Some(mut data) = row_now(&file, table, &row.id).map_err(io)? else { return Ok(None) };            for column in without {                if data.contains_key(column) {                    data.insert(column.clone(), Value::Null);                }            }            let created_at = if held.iter().any(|column| column == "created_at") {                stamp_of(&file, table, &row.id, "created_at").map_err(io)?            } else {                None            };            let (data, blind) = self.sealed_whole(table, &into.rekey.text(&row.id), into.rekey.value(Value::Object(data)))?;            Ok(Some(restore_row(row, data, blind, created_at, into.rekey)))        };        // What the object refused for good, written down; what it answered, in the log.        let write_down = |row: &WholeRow, why: &str| -> Result<(), ObjectRefusal> {            if written == Written::Nothing {                return Ok(());            }            let op_id = format!("restore:{}:{}", row.store, row.id);            let change = crate::unsent::UnsentChange {                op_id: op_id.clone(),                table: row.store.clone(),                row_id: row.id.clone(),                kind: "upsert".into(),                made_at: row.updated_at.clone().unwrap_or_default(),                waiting: crate::unsent::Waiting::Queued,            };            crate::unsent::record_discarded(into.layout, into.object_id, vec![change], BTreeMap::from([(op_id, why.to_string())]), ADOPT_DISCARDED_WHY, into.at).map_err(io)?;            if !logged {                return Ok(());            }            log.append(&format!("lost {}", row.address())).map_err(io)        };        let write_landed = |row: &WholeRow| -> Result<(), ObjectRefusal> {            if !logged {                return Ok(());            }            log.append(&format!("restored {}\t{}", row.address(), row.updated_at.clone().unwrap_or_default())).map_err(io)        };        let mut tell = |row: &WholeRow, landing: Landing, sent: &mut Restored| -> Result<(), ObjectRefusal> {            match &landing {                Landing::Delivered => {                    write_landed(row)?;                    sent.sent += 1;                }                Landing::Refused(why) => {                    write_down(row, why)?;                    sent.refused += 1;                }            }            if landed(row, &landing) { Ok(()) } else { Err(stopped()) }        };        // A link's row the object lacks: each round sends what waits again        // while one lands more; then once without the links still lacking,        // and whole.        let mut stripped = false;        let mut batch = RESTORE_BATCH;        let mut patience = RESTORE_PATIENCE;        loop {            let mut waiting: Vec<(WholeRow, String)> = Vec::new();            let mut moved = false;            let mut at = 0;            while at < queue.len() {                let chunk = &queue[at..(at + batch).min(queue.len())];                let mut rows = Vec::with_capacity(chunk.len());                let mut posted = Vec::with_capacity(chunk.len());                for row in chunk {                    match said(row, &[])? {                        Some(body) => {                            rows.push(body);                            posted.push(row);                        }                        // Gone from this copy since it was counted: nothing to send.                        None => {}                    }                }                // AN OBJECT THAT DID NOT ANSWER IS ASKED AGAIN, never the end                // of the backup (owner's phone, 12 Nov 2026: one call ran out                // of time and the whole backup stopped): the same rows go                // again after a pause, half as many a call, while patience                // lasts; a call that lands restores it. A row that landed                // unheard is answered as held, so nothing goes twice.                let began = std::time::Instant::now();                let answers = match self.restore_chunk(rows, &mut sent.version) {                    Ok(answers) => {                        patience = RESTORE_PATIENCE;                        answers                    }                    Err(refusal) if refusal.status == 0 && refusal.code == "offline" && patience > 0 => {                        patience -= 1;                        batch = (batch / 2).max(1);                        eprintln!("[restore] {}; asked again, {batch} rows a call, {patience} more tries", call_said(chunk, began.elapsed(), &refusal));                        std::thread::sleep(RESTORE_PAUSE);                        continue;                    }                    // THE CALL THAT FAILED IS NAMED (owner's phone, 12 Nov                    // 2026): its tables, how many rows it carried and how                    // long it waited, so the card says which call was slow.                    Err(refusal) if refusal.status != 401 && refusal.code != ADOPT_STOPPED => {                        let message = call_said(chunk, began.elapsed(), &refusal);                        eprintln!("[restore] {message}");                        return Err(ObjectRefusal { message, ..refusal });                    }                    Err(refusal) => return Err(refusal),                };                at += chunk.len();                for (row, answer) in posted.iter().zip(answers) {                    match answer {                        Answer::Landed => {                            moved = true;                            tell(row, Landing::Delivered, &mut sent)?;                        }                        Answer::Waits(why) => waiting.push(((*row).clone(), why)),                        Answer::Lost(why) => tell(row, Landing::Refused(why), &mut sent)?,                    }                }            }            if waiting.is_empty() {                return Ok(sent);            }            if moved {                queue = waiting.into_iter().map(|(row, _)| row).collect();                continue;            }            if stripped {                for (row, why) in waiting {                    tell(&row, Landing::Refused(why), &mut sent)?;                }                return Ok(sent);            }            // Nothing more landed: each waiting row goes without the links            // it still lacks, and then whole.            stripped = true;            let mut whole = Vec::new();            for (row, why) in waiting {                let links: Vec<String> = checked_links(into.served_tables, &row.table).into_iter().map(|(column, _)| column).collect();                let Some(body) = said(&row, &links)? else { continue };                match self.restore_chunk(vec![body], &mut sent.version)?.into_iter().next() {                    Some(Answer::Landed) => whole.push(row),                    Some(Answer::Waits(again) | Answer::Lost(again)) => tell(&row, Landing::Refused(format!("{why}; and without its links: {again}")), &mut sent)?,                    None => tell(&row, Landing::Refused(why), &mut sent)?,                }            }            queue = whole;        }    }    /// One `restore` call; a call the object refuses for one of its rows is    /// sent again row by row, so that row alone is answered.    fn restore_chunk(&self, rows: Vec<Value>, version: &mut i64) -> Result<Vec<Answer>, ObjectRefusal> {        if rows.is_empty() {            return Ok(Vec::new());        }        let count = rows.len();        let args = json!({"rows": rows.clone()});        self.guard("restore", &args)?;        match self.address.send(self.exchange.as_ref(), "POST", routes::ACT, self.act_headers(), Some(&json!({"act": "restore", "args": {"rows": rows.clone()}}))) {            Ok(answer) => {                let restored = answer["restored"].as_array().cloned().unwrap_or_default();                *version = (*version).max(answer["version"].as_i64().unwrap_or(0));                if restored.len() != count {                    return Err(ObjectRefusal { status: 0, code: "bad_answer".into(), message: format!("the object answered for {} of {count} rows restored", restored.len()) });                }                Ok(restored.iter().map(|_| Answer::Landed).collect())            }            // RESTORE 2: the server was put back; nothing landed and nothing is lost: the adopt stops as it stands.            Err(refusal) if refusal.transient() || refusal.signs_out() || refusal.status == 0 || refusal.code == GENERATION_MOVED => Err(self.refused_restore(refusal)),            Err(_) if count > 1 => {                let mut answers = Vec::with_capacity(count);                for row in rows {                    answers.extend(self.restore_chunk(vec![row], version)?);                }                Ok(answers)            }            Err(refusal) if refusal.code == "bad_link" => Ok(vec![Answer::Waits(refusal.message)]),            Err(refusal) => Ok(vec![Answer::Lost(refusal.message)]),        }    }    fn refused_restore(&self, refusal: ObjectRefusal) -> ObjectRefusal {        if refusal.signs_out() {            if let Some(signed_out) = &self.signed_out {                signed_out.say(&refusal);            }        }        refusal    }}/// A restore call that failed, in the kit's words (`backup` `call.*`): the/// tables its rows were of, how many it carried, the seconds it waited, and/// what the object or the line said.fn call_said(chunk: &[WholeRow], waited: std::time::Duration, refusal: &ObjectRefusal) -> String {    let tables: BTreeSet<&str> = chunk.iter().map(|row| row.table.as_str()).collect();    let tables = tables.into_iter().collect::<Vec<_>>().join(", ");    let line = if refusal.status == 0 { "call.unanswered" } else { "call.refused" };    cotton_core::rules::shell_lines::LineSet::shipped("backup")        .and_then(|lines| lines.say(line, &[("tables", &tables), ("rows", &chunk.len().to_string()), ("seconds", &waited.as_secs().to_string()), ("why", &refusal.message)]))        .unwrap_or_else(|| refusal.message.clone())}fn stopped() -> ObjectRefusal {    ObjectRefusal { status: 0, code: ADOPT_STOPPED.into(), message: "the backup was stopped".into() }}