Cotton code
207 lines · 9.3 KB · RustRaw
//! 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;use crate::object::{ObjectClient, ObjectError};use crate::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)]pub struct Pace {    pub page_rows: usize,    pub pause: std::time::Duration,}impl Default for Pace {    fn default() -> Pace {        Pace { page_rows: PAGE_ROWS, pause: std::time::Duration::ZERO }    }}/// The object, over HTTPS, as the migration asks it.pub struct ObjectLine<'a> {    object: &'a ObjectClient,    patience: Option<&'a crate::patience::Patience>,    pace: Pace,}impl<'a> ObjectLine<'a> {    pub fn 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.    pub fn 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.    pub fn 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 },    }}impl MigrateLine for ObjectLine<'_> {    fn page(&mut self, 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 = match self.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(&mut self, 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(&mut self, 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`.pub struct StoreProgress<'a> {    store: &'a Store,}impl<'a> StoreProgress<'a> {    pub fn new(store: &'a Store) -> StoreProgress<'a> {        StoreProgress { store }    }    pub fn source(table: &str) -> String {        format!("seal:{table}")    }}impl Progress for StoreProgress<'_> {    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(&mut self, 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.pub fn sealed_tables(definitions: &Value) -> Result<BTreeMap<String, SealSpec>, String> {    let mut out = BTreeMap::new();    for table in definitions.get("tables").and_then(Value::as_array).ok_or("the object's definitions hold no tables")? {        let Some(id) = table.get("id").and_then(Value::as_str) else { continue };        if let Some(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.pub fn data_key_row(line: &mut dyn MigrateLine) -> Result<Map<String, Value>, String> {    let mut 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))?;        if let Some(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 => return Err("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.pub fn 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.pub fn 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() };    if let Some(open) = chosen.iter().find(|t| !sealed.contains_key(*t)) {        return Err(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) as Arc<dyn DataKeyStore>);    let mut line = ObjectLine::paced(object, pace);    learn_keys(&sealer, &mut line)?;    let mut progress = StoreProgress::new(store);    let mut 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.pub fn 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(),    )}