Cotton code
136 lines · 6.4 KB · RustRaw
//! The seal migration (sealing plan §7 step 3), run on the Mac that is a//! vault device of the object: every open row of each sealed table is sealed//! through a twin this Mac verifies, then the act log is purged//! (`cotton_mac::seal_migrate`).//!//!   cargo run -p cotton-mac --bin seal-migrate -- --base <url> --data-dir <dir> \//!     --device-id <id> --token-file <path> [--key-file <path>] [--tables a,b]//!//! --base        the object's address (<the dev Worker's address (config/dev-server.json)>//!               for the dev Worker; the live one only by the coordinator)//! --data-dir    the importer's data folder, which holds importer.db (each//!               table's progress is kept there, so a stopped run resumes)//! --device-id   this Mac's device id: its vault key is the login Keychain item//!               of that id, and its vault_key row the object holds//! --token-file  a file holding this Mac's DEVICE credential (a sign-in's, not a//!               `ctn_` token: the object lets only the owner's own devices seal);//!               never printed//! --tables      the tables to migrate; every table the object seals when absent//! --page-rows   the rows a page (so a stage) holds; 2000 when absent//! --pause-ms    a rest after each committed stage, so the owner's phones still//!               sync while a large table seals; 0 when absent//! --from-start  read the named --tables from their first row again, forgetting//!               where an earlier run got to: what a table whose clear list//!               narrowed needs (LOCK TABLES 1), since its rows sealed long ago//!               are behind any kept cursor. Rows sealed as the table says are//!               skipped; only those still holding a sealed column in the clear//!               are sealed again.//!//! stdout is the run's summary as JSON: counts and row ids, never content.//! Exit 0 when every table finished with nothing left open; 1 otherwise.use std::path::PathBuf;use std::process::ExitCode;use cotton_mac::object::ObjectClient;use cotton_mac::seal_migrate::{data_key_row, report, run_paced, ObjectLine, Pace, StoreProgress};use cotton_mac::store::Store;use cotton_mac::vault::{tool_keyring, ImporterVault};const USAGE: &str = "seal-migrate --base <url> --data-dir <dir> --device-id <id> --token-file <path> [--key-file <path>] [--tables a,b] [--page-rows n] [--pause-ms n] [--from-start]";struct Args {    base: String,    data_dir: PathBuf,    device_id: String,    token_file: PathBuf,    key_file: Option<PathBuf>,    tables: Vec<String>,    pace: Pace,    from_start: bool,}fn parse(argv: &[String]) -> Result<Args, String> {    let (mut base, mut data_dir, mut device_id, mut token_file, mut tables) = (None, None, None, None, Vec::new());    let mut key_file = None;    let mut pace = Pace::default();    let mut from_start = false;    let mut at = 0;    while at < argv.len() {        let flag = argv[at].as_str();        if flag == "--from-start" {            from_start = true;            at += 1;            continue;        }        let value = argv.get(at + 1).filter(|v| !v.starts_with("--")).ok_or_else(|| format!("{flag} needs a value"))?.clone();        match flag {            "--base" => base = Some(value),            "--data-dir" => data_dir = Some(PathBuf::from(value)),            "--device-id" => device_id = Some(value),            "--token-file" => token_file = Some(PathBuf::from(value)),            "--key-file" => key_file = Some(PathBuf::from(value)),            "--tables" => tables = value.split(',').filter(|t| !t.is_empty()).map(str::to_string).collect(),            "--page-rows" => pace.page_rows = value.parse().ok().filter(|n| (50..=5000).contains(n)).ok_or("--page-rows is 50 to 5000")?,            "--pause-ms" => pace.pause = std::time::Duration::from_millis(value.parse().ok().filter(|n| *n <= 600_000).ok_or("--pause-ms is 0 to 600000")?),            other => return Err(format!("unknown argument {other}")),        }        at += 2;    }    if from_start && tables.is_empty() {        return Err("--from-start names its --tables".into());    }    Ok(Args {        base: base.ok_or("--base is needed")?,        data_dir: data_dir.ok_or("--data-dir is needed")?,        device_id: device_id.ok_or("--device-id is needed")?,        token_file: token_file.ok_or("--token-file is needed")?,        key_file,        from_start,        tables,        pace,    })}fn go(args: Args) -> Result<bool, String> {    let token = std::fs::read_to_string(&args.token_file).map_err(|e| format!("{} could not be read: {e}", args.token_file.display()))?.trim().to_string();    let object = ObjectClient::new(args.base, Some(token)).map_err(|e| e.to_string())?;    let store = Store::open(&args.data_dir.join("importer.db")).map_err(|e| e.to_string())?;    let database_id = object.database_id().map_err(|e| format!("the object's database id could not be read: {e}"))?;    let keyring = tool_keyring(&args.device_id, args.key_file.as_deref());    let vault = ImporterVault::new(keyring.as_ref(), &args.device_id, "");    let open = vault        .open_only(&object)        .map_err(|e| e.to_string())?        .ok_or("vault_locked: this Mac's vault is not open (no key in the Keychain, or the phone has not approved this Mac in Keys › Devices)")?;    let dk = open.data_key(&data_key_row(&mut ObjectLine::new(&object))?).map_err(|e| format!("{}: the data key did not open ({e})", e.code()))?;    drop(open);    if args.from_start {        let at = cotton_client::seams::iso(chrono::Utc::now());        for table in &args.tables {            store.advance(&StoreProgress::source(table), Some("0"), 0, &at).map_err(|e| e.to_string())?;        }    }    let runs = run_paced(&object, &store, &database_id, &dk, &args.tables, args.pace)?;    println!("{}", serde_json::to_string_pretty(&report(&runs)).unwrap_or_default());    Ok(runs.iter().all(|r| r.done && r.unverified.is_empty()))}fn main() -> ExitCode {    let argv: Vec<String> = std::env::args().skip(1).collect();    let args = match parse(&argv) {        Ok(args) => args,        Err(why) => {            eprintln!("{why}\n{USAGE}");            return ExitCode::from(2);        }    };    match go(args) {        Ok(true) => ExitCode::SUCCESS,        Ok(false) => ExitCode::from(1),        Err(why) => {            eprintln!("{why}");            ExitCode::from(1)        }    }}