//! 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};usesuper::adopt::{AdoptLog, Landing, Rekey, ADOPT_DISCARDED_WHY, ADOPT_STOPPED};usesuper::*;/// The rows one `restore` act carries at most (the object takes 500).pubconst RESTORE_BATCH: usize = 200;/// How many calls running the object may leave unanswered before a restore/// gives up; a call that lands restores it.pubconst 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)]pubstructWholeRow {/// 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>,}implWholeRow {/// `table\tid`, as the adopt's log names it.pubfn address(&self) -> String { format!("{}\t{}", self.table, self.id) }}/// What a restore is handed.pubstructRestoreInto<'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)]pubenumWritten {/// 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)]pubstructRestored {/// 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).pubtypeRestoreLanded<'a> = &'a mutdynFnMut(&WholeRow, &Landing) -> bool;/// What an adopt's log says of the rows restored before.#[derive(Debug, Clone, Default, PartialEq, Eq)]pubstructRestoreMemory {/// `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>,}implRestoreMemory {/// Whether `row` needs sending: never answered, or changed since.pubfn 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()) }}implAdoptLog {/// 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`]).pubfn 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.pubfn 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.pubfn restored(&self) -> RestoreMemory {letmut memory = RestoreMemory::default();for line inself.lines() {ifletSome(rest) = line.strip_prefix("restored ") {letmut parts = rest.splitn(3, '\t');iflet (Some(table), Some(id)) = (parts.next(), parts.next()) { memory.restored.insert(format!("{table}\t{id}"), parts.next().unwrap_or_default().to_string()); } } elseifletSome(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.pubfn object_definitions(path: &Path) -> Result<Vec<Value>, String> {if !path.exists() {returnOk(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() {returnOk(Vec::new()); }let unreadable = |error: rusqlite::Error| format!("cotton_table_definitions could not be read ({error})");letmut 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)?;letmut 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; }ifletSome(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).pubfn restore_order(served: &[Value], tables: &[String]) -> Vec<String> {let wanted: BTreeSet<&str> = tables.iter().map(String::as_str).collect();letmut placed: Vec<String> = Vec::with_capacity(tables.len());letmut 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 {letmut said = json!({"table": row.table, "id": rekey.text(&row.id), "data": data});ifletSome(blind) = blind { said["blind"] = json!(blind); }ifletSome(at) = created_at { said["created_at"] = json!(at); }ifletSome(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.pubfn whole_rows(path: &Path, into: &RestoreInto<'_>) -> Result<Vec<WholeRow>, String> {if !path.exists() {returnOk(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})"))?;letmut rows = Vec::new();for name in restore_order(into.served_tables, into.tables) {letSome(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);letmut 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.pubfn unnamed_tables(path: &Path, into: &RestoreInto<'_>) -> Result<Vec<(String, usize)>, String> {if !path.exists() {returnOk(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).letmut held: Vec<Value> = into.served_tables.to_vec();if !file_columns(&file, "cotton_table_definitions")?.is_empty() {letmut 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())); }letmut declared: BTreeSet<String> = BTreeSet::new();for definition in &held {// A definition that does not read declares nothing here: its table stays unnamed.ifletOk(Some(tables)) = cotton_store::schema::package_shape::declared(definition) { declared.extend(tables.into_iter().map(|table| table.table.name)); } }letmut 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)?;letmut 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.pubfn 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())?;letSome(held) = cursors.get(CURSOR_KEY) else { returnOk(false) };let (_, since, page) = read_cursor(held);Ok(page.is_none() && since >= version)}/// Where one row of a call ended.enumAnswer {Landed,/// Refused for a link to a row the object lacks: it waits for a round.Waits(String),Lost(String),}implObjectTransport {/// 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.pubfn 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.pubfn restore_rows_except(&self, into: &RestoreInto<'_>, landed: RestoreLanded<'_>, kept_here: &dynFn(&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.pubfn held_rows(&self, tables: &[String]) -> Result<BTreeSet<String>, ObjectRefusal> {if tables.is_empty() {returnOk(BTreeSet::new()); }matchself.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> {letmut held = BTreeSet::new();letmut path = format!("{}?tables={}", routes::HELD, tables.join(","));letmut first = true;loop {let answer = matchself.ask_page(&path) {Ok((answer, _)) => answer,Err(refusal) if first && refusal.status == 404 => returnOk(None),Err(refusal) => returnErr(refusal), };letSome(tables) = answer["held"].as_object() else {if first {returnOk(None); }returnErr(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 => returnOk(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> {letmut held = BTreeSet::new();letmut 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() {iflet (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 => returnOk(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).pubfn 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.pubfn 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() {returnOk(Vec::new()); }letmut 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);letmut sent = Restored::default();if queue.is_empty() {returnOk(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> {letSome(table) = map.object(&row.table) else { returnOk(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)?;letmut table = table.clone(); table.columns.retain(|(_, ours, _)| held.contains(ours));let table = &table;letSome(mut data) = row_now(&file, table, &row.id).map_err(io)? else { returnOk(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 {returnOk(()); }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 {returnOk(()); } log.append(&format!("lost {}", row.address())).map_err(io) };let write_landed = |row: &WholeRow| -> Result<(), ObjectRefusal> {if !logged {returnOk(()); } log.append(&format!("restored {}\t{}", row.address(), row.updated_at.clone().unwrap_or_default())).map_err(io) };letmut tell = |row: &WholeRow, landing: Landing, sent: &mutRestored| -> 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.letmut stripped = false;letmut batch = RESTORE_BATCH;letmut patience = RESTORE_PATIENCE;loop {letmut waiting: Vec<(WholeRow, String)> = Vec::new();letmut moved = false;letmut at = 0;while at < queue.len() {let chunk = &queue[at..(at + batch).min(queue.len())];letmut rows = Vec::with_capacity(chunk.len());letmut 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 = matchself.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}");returnErr(ObjectRefusal { message, ..refusal }); }Err(refusal) => returnErr(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() {returnOk(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)?; }returnOk(sent); }// Nothing more landed: each waiting row goes without the links// it still lacks, and then whole. stripped = true;letmut 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();letSome(body) = said(&row, &links)? else { continue };matchself.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() {returnOk(Vec::new()); }let count = rows.len();let args = json!({"rows": rows.clone()});self.guard("restore", &args)?;matchself.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 {returnErr(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 => {letmut 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() {ifletSome(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() }}