//! Rows recovered into a local SQLite file, landed on the object sealed: the//! coordinator's recovery step for a database whose messages and mail were//! kept in the clear somewhere local (on one Mac only) and must reach the//! object without a sealed word ever leaving this Mac in the clear.//!//! The file holds the object's own row shape (`rows`, as the Worker's store//! keeps it, or as a sync dump writes it)://!//! ```sql//! CREATE TABLE rows (table_id TEXT NOT NULL, id TEXT NOT NULL, data TEXT NOT NULL,//! created_at TEXT, updated_at TEXT, deleted INTEGER NOT NULL DEFAULT 0,//! PRIMARY KEY (table_id, id));//! ```//!//! Each row of a table the object seals is sealed here with the object's data//! key (`Sealer::seal`, its blind tokens beside it), its id keyed when the id//! says something (a reaction's `react:<message>:<phone>`, as the importer's//! copy keys it), and goes up through `import_rows` in batches of at most//! [`crate::object::IMPORT_ROWS`]. Fail closed://!//! - a table the object does not seal is refused by name (`not_sealed`)//! unless the run says `allow_open`, so nothing is sent clear by accident;//! - a key table (`seal_key`, `vault_key`, `person_key`, the window tables)//! is refused (`not_imported`), as the object refuses it;//! - every act is checked by [`cotton_client::seal::guard_act`] before it is//! sent: a sealed column in the clear stops the run (`seal_clear_refused`).//!//! Resumable: each landed `(table, id)` is written to the progress file once//! its batch is answered, and a run skips what is there; a batch sent twice//! lands as a patch and changes nothing twice. Tables go parents first (by//! their link columns), so a link never names a row the object lacks.//!//! Verified: after landing, every landed row is read back from the object//! (`/v1/sync`), and each sealed one must carry its seal, no sealed column in//! the clear, and open under the data key to the file's own columns. The//! answer is counts and ids, never content.use std::collections::{BTreeMap, BTreeSet};use std::path::Path;use std::sync::Arc;use rusqlite::{params, Connection, OpenFlags, OptionalExtension};use serde_json::{json, Map, Value};use cotton_client::seal::{guard_act, DataKeyStore, HeldDataKeys, Sealer, SEAL_KEY_TABLE};use cotton_core::definitions::seal::SealSpec;use cotton_core::seal::DataKey;usecrate::object::{ObjectClient, IMPORT_ROWS};usecrate::seal_migrate::ObjectLine;/// Tables never landed: the key plumbing, as `import_rows` refuses it.const NOT_IMPORTED: &[&str] = &[SEAL_KEY_TABLE, "vault_key", "person_key", "unlock_request", "unlock_grant", "assistant_read"];/// The frame a stored row carries beside its columns, never sent as data.const FRAME: &[&str] = &["id", "created_at", "updated_at", "version", "owner", "deleted"];/// What a run is asked to do.#[derive(Debug, Clone, Default)]pubstructLandOptions {/// The tables to land; every table the file holds when empty.pub tables: Vec<String>,/// Land rows of a table the object does not seal, as they are.pub allow_open: bool,/// Rows per `import_rows` call (at most [`IMPORT_ROWS`]; 0 means that).pub batch: usize,}/// One table's run, in counts and ids.#[derive(Debug, Clone, Default, PartialEq, Eq)]pubstructLanded {pub table: String,pub sealed: bool,/// Live rows of the table in the file.pub in_file: usize,/// Rows sent by this run.pub sent: usize,/// Rows a former run had landed already.pub already: usize,/// Rows the object holds changed after the file's own copy (or the file cannot say when its copy was): left as/// the object holds them, never sealed back over (STALE WRITES 2, 25 Nov 2026).pub kept_newer: usize,/// Rows read back from the object that opened to the file's columns.pub verified: usize,/// Rows that did not read back as they should, by id, with why.pub mismatched: Vec<(String, String)>,}implLanded {pubfn done(&self) -> bool {self.mismatched.is_empty() && self.verified + self.kept_newer == self.in_file }}/// The progress file's one table.const PROGRESS_DDL: &str = "CREATE TABLE IF NOT EXISTS landed (table_id TEXT NOT NULL, id TEXT NOT NULL, object_id TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (table_id, id)) WITHOUT ROWID;";/// Open the recovered file read-only: this run never writes to it.pubfn open_file(path: &Path) -> Result<Connection, String> {let conn = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY).map_err(|e| format!("{} could not be opened: {e}", path.display()))?;let has_rows: Option<String> = conn .query_row("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'rows'", [], |r| r.get(0)) .optional() .map_err(|e| e.to_string())?;if has_rows.is_none() {returnErr(format!("{} holds no `rows` table (table_id, id, data, created_at, updated_at, deleted)", path.display())); }Ok(conn)}/// Open (or make) the progress file.pubfn open_progress(path: &Path) -> Result<Connection, String> {let conn = Connection::open(path).map_err(|e| format!("{} could not be opened: {e}", path.display()))?; conn.execute_batch(PROGRESS_DDL).map_err(|e| e.to_string())?;Ok(conn)}/// One table's shape as the object defines it: its columns, its links and its seal.structShape { columns: BTreeSet<String>, links: BTreeSet<String>,/// The single-link columns that name a row of this same table (a reply's `reply_to_id`). own_links: Vec<String>, seal: Option<SealSpec>,}fn shapes(definitions: &Value) -> Result<BTreeMap<String, Shape>, String> {letmut out = BTreeMap::new();for table in definitions.get("tables").and_then(Value::as_array).ok_or("the object's definitions hold no tables")? {letSome(id) = table.get("id").and_then(Value::as_str) else { continue };let columns = table.get("columns").and_then(Value::as_array).cloned().unwrap_or_default();let keys = columns.iter().filter_map(|c| c.get("key").and_then(Value::as_str).map(str::to_string)).collect();let links = columns .iter() .filter(|c| c.get("type").and_then(Value::as_str) == Some("link")) .filter_map(|c| c.get("link_to").and_then(Value::as_str).map(str::to_string)) .filter(|to| to != id) .collect();let own_links = columns .iter() .filter(|c| c.get("type").and_then(Value::as_str) == Some("link") && c.get("link_to").and_then(Value::as_str) == Some(id)) .filter_map(|c| c.get("key").and_then(Value::as_str).map(str::to_string)) .collect();let seal = cotton_client::seal::spec_of_definition(table)?; out.insert(id.to_string(), Shape { columns: keys, links, own_links, seal }); }Ok(out)}/// `chosen` parents first: a table after every table its links name.fn parents_first(chosen: &[String], shapes: &BTreeMap<String, Shape>) -> Vec<String> {let set: BTreeSet<&String> = chosen.iter().collect();letmut out: Vec<String> = Vec::new();letmut seen = BTreeSet::new();fn visit(t: &String, set: &BTreeSet<&String>, shapes: &BTreeMap<String, Shape>, seen: &mut BTreeSet<String>, out: &mutVec<String>) {if !seen.insert(t.clone()) {return; }ifletSome(shape) = shapes.get(t) {for parent in &shape.links {if set.contains(parent) { visit(parent, set, shapes, seen, out); } } } out.push(t.clone()); }for t in chosen { visit(t, &set, shapes, &mut seen, &mut out); } out}/// `rows` with every row after the rows of its own table it names (a reply/// after the message it answers), otherwise in the order given: the object/// refuses a link to a row it does not hold yet.fn named_rows_first(rows: Vec<FileRow>, own_links: &[String]) -> Vec<FileRow> {if own_links.is_empty() {return rows; }let at: BTreeMap<String, usize> = rows.iter().enumerate().map(|(i, r)| (r.id.clone(), i)).collect();let named = |row: &FileRow| -> Vec<usize> {letmut out = Vec::new();for key in own_links {match row.data.get(key) {Some(Value::String(id)) => out.extend(at.get(id).copied()),Some(Value::Array(ids)) => out.extend(ids.iter().filter_map(Value::as_str).filter_map(|id| at.get(id).copied())), _ => {} } } out };letmut placed = vec![false; rows.len()];letmut order: Vec<usize> = Vec::with_capacity(rows.len());for start in0..rows.len() {if placed[start] {continue; }// Depth first without recursion: a long chain of replies must not overflow the stack.letmut stack: Vec<(usize, Vec<usize>)> = vec![(start, named(&rows[start]))]; placed[start] = true;whileletSome((i, waiting)) = stack.last_mut() {match waiting.pop() {Some(parent) if !placed[parent] => { placed[parent] = true;let theirs = named(&rows[parent]); stack.push((parent, theirs)); }Some(_) => {}None => { order.push(*i); stack.pop(); } } } }letmut slots: Vec<Option<FileRow>> = rows.into_iter().map(Some).collect(); order.into_iter().filter_map(|i| slots[i].take()).collect()}/// The id a recovered row of a sealed table lands under: itself when it is/// uuid-shaped, else the keyed id only the data key makes from it (the rule/// the importer's copy keeps, `copy::Copy::object_id`), so an id such as/// `react:<message>:<phone>` never reaches the object.fn object_id(dk: &DataKey, database_id: &str, table: &str, sealed: bool, id: &str) -> Result<String, String> {if !sealed {returnOk(id.to_string()); } cotton_client::seal::keyed_row_id(dk, database_id, table, id).map_err(|e| e.to_string())}structFileRow { id: String, data: Map<String, Value>, created_at: Option<String>, updated_at: Option<String>,}fn file_rows(file: &Connection, table: &str, shape: &Shape) -> Result<Vec<FileRow>, String> {letmut stmt = file .prepare("SELECT id, data, created_at, updated_at FROM rows WHERE table_id = ?1 AND coalesce(deleted, 0) = 0 ORDER BY created_at, id") .map_err(|e| e.to_string())?;let rows = stmt .query_map([table], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option<String>>(2)?, r.get::<_, Option<String>>(3)?))) .map_err(|e| e.to_string())?;letmut out = Vec::new();for row in rows {let (id, text, created_at, updated_at) = row.map_err(|e| e.to_string())?;let parsed: Value = serde_json::from_str(&text).map_err(|e| format!("{table}/{id}: its data is not JSON ({e})"))?;letValue::Object(all) = parsed else { returnErr(format!("{table}/{id}: its data is not an object")) };if cotton_core::seal::row::is_sealed(&all) {returnErr(format!("already_sealed: {table}/{id} in the file is sealed already; this verb lands clear rows only")); }// Only the object's columns go up: a recovered row's extra keys (a former column) stay here.let data: Map<String, Value> = all.into_iter().filter(|(k, _)| !FRAME.contains(&k.as_str()) && shape.columns.contains(k)).collect(); out.push(FileRow { id, data, created_at, updated_at }); }Ok(out)}/// Land the file's rows of `options.tables` (every table it holds when empty)/// on `object`, sealed under `dk`, resuming from `progress`; then verify every/// landed row as the object holds it.pubfn land(object: &ObjectClient, file: &Connection, progress: &Connection, database_id: &str, dk: &DataKey, options: &LandOptions) -> Result<Vec<Landed>, String> {let definitions = object.definitions().map_err(|e| format!("the object's definitions could not be read: {e}"))?;let shapes = shapes(&definitions)?;let in_file: Vec<String> = {letmut stmt = file.prepare("SELECT DISTINCT table_id FROM rows WHERE coalesce(deleted, 0) = 0 ORDER BY table_id").map_err(|e| e.to_string())?;let rows = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?; rows.collect::<Result<_, _>>().map_err(|e| e.to_string())? };let chosen: Vec<String> = if options.tables.is_empty() { in_file } else { options.tables.clone() };// Every refusal before anything is sent.for table in &chosen {if NOT_IMPORTED.contains(&table.as_str()) {returnErr(format!("not_imported: {table} is never landed")); }let shape = shapes.get(table).ok_or_else(|| format!("no_such_table: the object defines no {table}"))?;if shape.seal.is_none() && !options.allow_open {returnErr(format!("not_sealed: the object does not seal {table}, so its rows would go up in the clear (say allow_open to land them as they are)")); } }let order = parents_first(&chosen, &shapes);let batch = if options.batch == 0 { IMPORT_ROWS } else { options.batch.min(IMPORT_ROWS) };let keys = HeldDataKeys::new(); keys.hold(database_id, dk);let sealer = Sealer::new(database_id, Arc::clone(&keys) asArc<dynDataKeyStore>); cotton_client::seal::migrate::learn_keys(&sealer, &mutObjectLine::new(object))?;let spec_of = |t: &str| shapes.get(t).and_then(|s| s.seal.clone());letmut out = Vec::new();for table in &order {let shape = &shapes[table];let rows = named_rows_first(file_rows(file, table, shape)?, &shape.own_links);letmut landed = Landed { table: table.clone(), sealed: shape.seal.is_some(), in_file: rows.len(), ..Landed::default() };let done: BTreeMap<String, String> = {letmut stmt = progress.prepare("SELECT id, object_id FROM landed WHERE table_id = ?1").map_err(|e| e.to_string())?;let rows = stmt.query_map([table], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(|e| e.to_string())?; rows.collect::<Result<_, _>>().map_err(|e| e.to_string())? };letmut wire: Vec<(String, String, Value)> = Vec::new();let held = held_at(object, table)?;for row in &rows {if done.contains_key(&row.id) { landed.already += 1;continue; }let id = object_id(dk, database_id, table, shape.seal.is_some(), &row.id)?;// A row the object holds is sealed back only when the file's copy is at least as new: a recovery file// never puts an old copy over what the phone changed since it was dumped.ifletSome(at) = held.get(&id) {if row.updated_at.as_deref().is_none_or(|file_at| file_at < at.as_str()) { landed.kept_newer += 1;continue; } }letmut item = json!({ "table": table, "id": id });match &shape.seal {Some(spec) => {let sealed = sealer.seal(table, &id, spec, &row.data, None).map_err(|e| format!("{}: {table}/{id} did not seal ({e})", e.code()))?; item["data"] = Value::Object(sealed.data); item["blind"] = json!(sealed.blind); }None => item["data"] = Value::Object(row.data.clone()), }ifletSome(at) = &row.created_at { item["created_at"] = json!(at); }ifletSome(at) = &row.updated_at { item["updated_at"] = json!(at); } wire.push((row.id.clone(), id, item)); }// Cut by rows and by the call's blind-token budget (a mail's body alone carries hundreds): copy::import_calls.for outer in wire.chunks(batch) {let items: Vec<Value> = outer.iter().map(|(_, _, item)| item.clone()).collect();letmut at = 0;for call incrate::copy::import_calls(&items) {let chunk = &outer[at..at + call.len()]; at += call.len();let args = json!({ "rows": call }); guard_act(spec_of, "import_rows", &args)?; object.import_rows(call).map_err(|e| format!("import_rows refused a batch of {table}: {e}"))?;let when = cotton_client::seams::iso(chrono::Utc::now());let tx = progress.unchecked_transaction().map_err(|e| e.to_string())?;for (file_id, object_id, _) in chunk { tx.execute("INSERT OR REPLACE INTO landed (table_id, id, object_id, at) VALUES (?1, ?2, ?3, ?4)", params![table, file_id, object_id, when]) .map_err(|e| e.to_string())?; } tx.commit().map_err(|e| e.to_string())?; landed.sent += chunk.len(); } } verify(object, &sealer, progress, table, shape, &rows, &mut landed)?; out.push(landed); } keys.forget(database_id);Ok(out)}/// Read every landed row of `table` back from the object and check it.fn verify(object: &ObjectClient, sealer: &Sealer, progress: &Connection, table: &str, shape: &Shape, rows: &[FileRow], landed: &mutLanded) -> Result<(), String> {letmut by_object: BTreeMap<String, &FileRow> = BTreeMap::new(); {letmut stmt = progress.prepare("SELECT id, object_id FROM landed WHERE table_id = ?1").map_err(|e| e.to_string())?;let ids: BTreeMap<String, String> = stmt .query_map([table], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))) .map_err(|e| e.to_string())? .collect::<Result<_, _>>() .map_err(|e| e.to_string())?;for row in rows {ifletSome(object_id) = ids.get(&row.id) { by_object.insert(object_id.clone(), row); } } }letmut seen = BTreeSet::new();letmut cursor: Option<String> = None;loop {let page = object.sync_page(0, &[table], cursor.as_deref()).map_err(|e| format!("{table} could not be read back: {e}"))?;for stored in page.get("rows").and_then(Value::as_array).into_iter().flatten() {if stored.get("table").and_then(Value::as_str) != Some(table) || stored.get("deleted") == Some(&Value::Bool(true)) {continue; }letSome(id) = stored.get("id").and_then(Value::as_str) else { continue };letSome(source) = by_object.get(id) else { continue }; seen.insert(id.to_string());let data = stored.get("data").and_then(Value::as_object).cloned().unwrap_or_default();match check(sealer, table, id, shape, &data, &source.data) {Ok(()) => landed.verified += 1,Err(why) => landed.mismatched.push((id.to_string(), why)), } }match page.get("next").and_then(Value::as_str) {Some(next) => cursor = Some(next.to_string()),None => break, } }for id in by_object.keys().filter(|id| !seen.contains(*id)) { landed.mismatched.push((id.clone(), "missing: the object holds no live row under this id".into())); }Ok(())}fn check(sealer: &Sealer, table: &str, id: &str, shape: &Shape, stored: &Map<String, Value>, source: &Map<String, Value>) -> Result<(), String> {let opened = match &shape.seal {Some(spec) => {if !cotton_core::seal::row::is_sealed(stored) {returnErr("open: the object holds this row unsealed".into()); }ifletSome(clear) = stored.iter().find(|(k, v)| !cotton_core::seal::row::RESERVED.contains(&k.as_str()) && spec.seals(k) && !v.is_null()) {returnErr(format!("sealed_in_clear: {} is held in the clear", clear.0)); } sealer.open(table, id, stored).map_err(|e| format!("{}: {e}", e.code()))? }None => stored.clone(), };let present = |m: &Map<String, Value>, k: &str| m.get(k).filter(|v| !v.is_null()).cloned();for column in source.keys().chain(opened.keys()).collect::<BTreeSet<_>>() {if FRAME.contains(&column.as_str()) || cotton_core::seal::row::RESERVED.contains(&column.as_str()) {continue; }if present(source, column) != present(&opened, column) {returnErr(format!("differs: {column}")); } }Ok(())}/// A run's answer: counts and ids only, never a row's content.pubfn report(runs: &[Landed]) -> Value {Value::Array( runs.iter() .map(|r| { json!({"table": r.table, "sealed": r.sealed, "inFile": r.in_file, "sent": r.sent, "already": r.already,"verified": r.verified, "done": r.done(),"mismatched": r.mismatched.iter().map(|(id, why)| json!({"id": id, "why": why})).collect::<Vec<_>>(), }) }) .collect(), )}/// Every live row of `table` the object holds, by id, with when it last changed.fn held_at(object: &ObjectClient, table: &str) -> Result<BTreeMap<String, String>, String> {letmut held = BTreeMap::new();letmut cursor: Option<String> = None;loop {let page = object.sync_page(0, &[table], cursor.as_deref()).map_err(|e| format!("{table} could not be read: {e}"))?;for stored in page.get("rows").and_then(Value::as_array).into_iter().flatten() {if stored.get("table").and_then(Value::as_str) != Some(table) || stored.get("deleted") == Some(&Value::Bool(true)) {continue; }iflet (Some(id), Some(at)) = (stored.get("id").and_then(Value::as_str), stored.get("updated_at").and_then(Value::as_str)) { held.insert(id.to_string(), at.to_string()); } }match page.get("next").and_then(Value::as_str) {Some(next) => cursor = Some(next.to_string()),None => returnOk(held), } }}#[cfg(test)]mod order_tests {usesuper::*;fn row(id: &str, reply_to: Option<&str>) -> FileRow {letmut data = Map::new();ifletSome(to) = reply_to { data.insert("reply_to_id".into(), json!(to)); }FileRow { id: id.into(), data, created_at: None, updated_at: None } } #[test]fn a_reply_lands_after_the_message_it_answers() {// The file's order has the reply first, a chain, and a reply to a row the file lacks.let rows = vec![row("c", Some("b")), row("b", Some("a")), row("x", None), row("a", None), row("d", Some("gone"))];let ids: Vec<String> = named_rows_first(rows, &["reply_to_id".to_string()]).into_iter().map(|r| r.id).collect(); assert_eq!(ids, ["a", "b", "c", "x", "d"]); } #[test]fn a_table_that_names_no_row_of_its_own_keeps_its_order() {let rows = vec![row("c", Some("b")), row("b", None)];let ids: Vec<String> = named_rows_first(rows, &[]).into_iter().map(|r| r.id).collect(); assert_eq!(ids, ["c", "b"]); }}