//! 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:
` (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 {
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 {
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, 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 {
let cursor = self.store.cursor(&Self::source(table)).map_err(|e| e.to_string())?;
cursor.map_or(Ok(0), |c| c.parse::().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, 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