//! The seal migration, run by this Mac as the vault device with the RAM//! (sealing plan §7 step 3, Q21): every open row of each sealed table the//! object defines is sealed through a verified twin//! ([`cotton_client::seal::migrate`]). The object never holds a key that opens//! a row; this Mac opens the data key from its `seal_key` row with the vault//! key the phone wrapped for it ([`crate::vault::OpenVault::data_key`]).//!//! Where each table got to is kept in `importer.db` as the source//! `seal:<table>` (its cursor the next pass's `since`), so a run stopped//! anywhere resumes; deleting it only reads every table from the start again,//! and rows sealed already are skipped.use std::collections::BTreeMap;use std::sync::Arc;use serde_json::{json, Map, Value};use cotton_client::seal::migrate::{learn_keys, migrate, MigrateLine, Migrated, Page, Progress};use cotton_client::seal::{spec_of_definition, DataKeyStore, HeldDataKeys, Sealer, DK_ROW, SEAL_KEY_TABLE};use cotton_client::transport::object::ObjectRefusal;use cotton_core::definitions::seal::SealSpec;use cotton_core::seal::DataKey;usecrate::object::{ObjectClient, ObjectError};usecrate::store::Store;/// The rows a sync page asks for while migrating.const PAGE_ROWS: usize = 2000;/// How hard a run leans on the object: the rows a page (and so a stage) holds, and a rest after each stage is/// committed, so the owner's phones still finish their sync passes while a large table seals (live, 25 Nov 2026:/// unpaced, the object was too busy for a phone's first page inside 120 s).#[derive(Debug, Clone, Copy)]pubstructPace {pub page_rows: usize,pub pause: std::time::Duration,}implDefaultforPace {fn default() -> Pace {Pace { page_rows: PAGE_ROWS, pause: std::time::Duration::ZERO } }}/// The object, over HTTPS, as the migration asks it.pubstructObjectLine<'a> { object: &'a ObjectClient, patience: Option<&'a crate::patience::Patience>, pace: Pace,}impl<'a> ObjectLine<'a> {pubfn new(object: &'a ObjectClient) -> ObjectLine<'a> {ObjectLine { object, patience: None, pace: Pace::default() } }/// A line whose reads wait out an object that is not answering for now.pubfn patient(object: &'a ObjectClient, patience: &'a crate::patience::Patience) -> ObjectLine<'a> {ObjectLine { object, patience: Some(patience), pace: Pace::default() } }/// A line that asks pages of `pace.page_rows` and rests `pace.pause` after each committed stage.pubfn paced(object: &'a ObjectClient, pace: Pace) -> ObjectLine<'a> {ObjectLine { object, patience: None, pace } }}fn refusal(error: ObjectError) -> ObjectRefusal {match error {ObjectError::Refused { status, code, message } => ObjectRefusal { status, code, message },ObjectError::SignedOut => ObjectRefusal { status: 401, code: "signed_out".into(), message: "sign in again".into() },ObjectError::Transport(message) | ObjectError::File(message) => ObjectRefusal { status: 0, code: "offline".into(), message },ObjectError::Decode(message) => ObjectRefusal { status: 502, code: "bad_answer".into(), message }, }}implMigrateLineforObjectLine<'_> {fn page(&mutself, table: &str, since: i64, cursor: Option<&str>) -> Result<Page, ObjectRefusal> {let query: Vec<(&str, String)> = match cursor {Some(cursor) => vec![("cursor", cursor.to_string())],None => vec![("since", since.to_string()), ("tables", table.to_string()), ("limit", self.pace.page_rows.to_string())], };let read = || self.object.get_json("/v1/sync", &query);let answer = matchself.patience {Some(patience) => patience.run(read),None => read(), } .map_err(refusal)?;Ok(Page { rows: answer.get("rows").and_then(Value::as_array).cloned().unwrap_or_default(), next: answer.get("next").and_then(Value::as_str).map(str::to_string), version: answer.get("version").and_then(Value::as_i64).unwrap_or(since), }) }fn act(&mutself, act: &str, args: Value) -> Result<Value, ObjectRefusal> {let answer = self.object.post_act(act, &args).map_err(refusal)?;// A stage is done once committed: the object rests before the next, so other requests are answered.if act == "seal_commit" && !self.pace.pause.is_zero() { std::thread::sleep(self.pace.pause); }Ok(answer) }fn twins(&mutself, table: &str, twins: &[String]) -> Result<Vec<Value>, ObjectRefusal> {let answer = self.object.get_json("/v1/seal/twins", &[("table", table.to_string()), ("twins", twins.join(","))]).map_err(refusal)?;Ok(answer.get("twins").and_then(Value::as_array).cloned().unwrap_or_default()) }}/// Each table's pass cursor, in `importer.db`.pubstructStoreProgress<'a> { store: &'a Store,}impl<'a> StoreProgress<'a> {pubfn new(store: &'a Store) -> StoreProgress<'a> {StoreProgress { store } }pubfn source(table: &str) -> String { format!("seal:{table}") }}implProgressforStoreProgress<'_> {fn since(&self, table: &str) -> Result<i64, String> {let cursor = self.store.cursor(&Self::source(table)).map_err(|e| e.to_string())?; cursor.map_or(Ok(0), |c| c.parse::<i64>().map_err(|_| format!("importer.db holds no version for {}: {c:?}", Self::source(table)))) }fn keep(&mutself, table: &str, version: i64) -> Result<(), String> {let at = cotton_client::seams::iso(chrono::Utc::now());self.store.advance(&Self::source(table), Some(&version.to_string()), 0, &at).map_err(|e| e.to_string()) }}/// The sealed tables the object defines, by id, with their seal blocks.pubfn sealed_tables(definitions: &Value) -> Result<BTreeMap<String, SealSpec>, 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 };ifletSome(spec) = spec_of_definition(table)? { out.insert(id.to_string(), spec); } }Ok(out)}/// The object's `seal_key` row `dk`: the data key's wrap under the vault key.pubfn data_key_row(line: &mutdynMigrateLine) -> Result<Map<String, Value>, String> {letmut cursor: Option<String> = None;loop {let page = line.page(SEAL_KEY_TABLE, 0, cursor.as_deref()).map_err(|r| format!("the object's seal keys could not be read: {}", r.message))?;ifletSome(row) = page.rows.iter().find(|row| row.get("table").and_then(Value::as_str) == Some(SEAL_KEY_TABLE) && row.get("id").and_then(Value::as_str) == Some(DK_ROW)) {return row.get("data").and_then(Value::as_object).cloned().ok_or_else(|| "the data key's row holds no data".to_string()); }match page.next {Some(next) => cursor = Some(next),None => returnErr("seal_key_not_minted: the object holds no data key yet (a phone mints it: seal.mintKey)".into()), } }}/// Migrate `tables` (every sealed table the object defines when empty) with/// the data key `dk`, resuming each from `importer.db`. A table named that the/// object does not seal is refused before anything is sent.pubfn run(object: &ObjectClient, store: &Store, database_id: &str, dk: &DataKey, tables: &[String]) -> Result<Vec<Migrated>, String> { run_paced(object, store, database_id, dk, tables, Pace::default())}/// [`run`] at a pace: smaller pages and a rest after each committed stage.pubfn run_paced(object: &ObjectClient, store: &Store, database_id: &str, dk: &DataKey, tables: &[String], pace: Pace) -> Result<Vec<Migrated>, String> {let definitions = object.get_json("/v1/definitions", &[]).map_err(|e| format!("the object's definitions could not be read: {e}"))?;let sealed = sealed_tables(&definitions)?;let chosen: Vec<String> = if tables.is_empty() { sealed.keys().cloned().collect() } else { tables.to_vec() };ifletSome(open) = chosen.iter().find(|t| !sealed.contains_key(*t)) {returnErr(format!("not_sealed: the object does not seal {open}")); }let keys = HeldDataKeys::new(); keys.hold(database_id, dk);let sealer = Sealer::new(database_id, Arc::clone(&keys) asArc<dynDataKeyStore>);letmut line = ObjectLine::paced(object, pace); learn_keys(&sealer, &mut line)?;letmut progress = StoreProgress::new(store);letmut out = Vec::new();for table in &chosen { out.push(migrate(&sealer, table, &sealed[table], &mut line, &mut progress)?); } keys.forget(database_id);Ok(out)}/// A run's answer, as counts and ids only: never a row's content.pubfn report(runs: &[Migrated]) -> Value {Value::Array( runs.iter() .map(|r| { json!({"table": r.table, "sealed": r.sealed, "keptOpen": r.kept_open, "passes": r.passes, "done": r.done, "purged": r.purged,"left": r.left.iter().map(|(id, code)| json!({"id": id, "code": code})).collect::<Vec<_>>(),"unverified": r.unverified.iter().map(|(id, why)| json!({"id": id, "why": why})).collect::<Vec<_>>(), }) }) .collect(), )}