//! 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
\t\t`), 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,
}
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,
/// `table\tid` of each row refused for good, written down.
pub lost: BTreeSet,
}
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, 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>(0)?, row.get::<_, Option>(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 {
let wanted: BTreeSet<&str> = tables.iter().map(String::as_str).collect();
let mut placed: Vec = 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>, created_at: Option, 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