Cotton code
238 lines · 13.5 KB · RustRaw
//! seal-files: a person's files, sealed on this Mac (e2e rulings R6). This//! Mac is a device that holds the person's data key (`seal-device`, approved//! once from the phone); nothing here ever goes up open, and no key, token or//! file's contents is printed.//!//!   seal-files put    <device> --list <items.jsonl> [--threads n]//!       Each line `{ "key": "<db>/films/<id>/video/seg00001.m4s", "path": "/…", "content_type"?: "…" }`//!       is sealed as it is read and stored under its key. The film and fetch//!       importers send every file through this. One JSON line per file on stdout,//!       as each finishes.//!       What the object already stores sealed is left. An object that stops//!       answering is waited for, up to 30 minutes with no answer at all.//!//!   seal-files get    <device> --key <key> --out <path>//!       The stored file, opened: a film a phone sent as `source.*` for this//!       Mac to convert.//!//!   seal-files get    <device> --list <items.jsonl> [--threads n] [--tries n]//!       Each line `{ "key": "<db>/films/<id>/video/seg00001.m4s", "out": "/…" }`//!       brought down opened, n at a time (default 8) under one sign-in: a file//!       already at its `out` is left (`had`), any other lands at `<out>.part`,//!       renamed when whole (`got`), tried again with backoff (default 4 tries)//!       before it is `failed`. One JSON line per file on stdout as each//!       finishes (`film:open`); exit 1 when any failed.//!//!   seal-files serve  <device>//!       The importers' creates and updates, written as this Mac (token scopes, 24 Nov 2026: an owner `ctn_`//!       token reaches no device route once the switch is on). One JSON line in,//!       `{ "act": "create" | "update", "table", "id", "data" }`; one line out each, in order://!       `{ "ok": true, "answer" }` or `{ "ok": false, "status", "code", "message" }`. A row of a sealed//!       table goes sealed by this device; one of an open table goes as it is. Ends with its input.//!//!   seal-files queue  <device>//!       The fetch queue's rows, opened on this Mac (the object holds a//!       sealed row's link and title only inside its seal): one JSON line//!       `{ "id", "source", "title" }` per live row, for `fetch:run` alone,//!       on its own pipe.//!//!   seal-files rows   <device> --table <table>//!       Every live row of a sealed table, opened on this Mac: one JSON line//!       `{ "id", "data" }` each, for an importer reading back what it laid//!       (film:import), on its own pipe.//!//!   seal-files row    <device> --table <table> --id <id> [--since <version>]//!       One live row of a sealed table by its id, opened on this Mac: one//!       JSON line `{ "id", "data" }`, or nothing when there is no such row.//!       Read over /v1/sync from --since (a version before the row's last//!       change: film:subtitles passes the one GET /v1/films/subtitles/asked//!       named, less one; 0, the default, reads the table whole) and opened//!       alone, no other row and not the whole copy.//!//!   seal-files reseal <device> [--kinds photos,videos,books,music,films,messages,people] --dry-run//!   seal-files reseal <device> [--kinds …] --keep <dir> [--keep-clear] [--progress <file>] [--limit n] [--threads n]//!       Every file of those kinds the person's rows name that the object//!       still stores in the clear: fetched into --keep, checked against the//!       sha256 its key names, stored again sealed under the same key, read//!       back and opened, and only then its clear copy in --keep deleted//!       (--keep-clear leaves them, as a backup). A dry run only counts.//!       Stopped anywhere, run again: what is sealed is counted and left.//!       Exit 0 when nothing is left in the clear.//!       For messages and people (kinds the object lists plain itself, `GET /v1/media-plain`) every plain//!       file the object holds is taken too, named by a row or not; and while the object holds such a kind//!       back (a device of the person's reads it on an app from before, and would find a sealed file//!       unreadable) the devices are named and a real run touches none of that kind (`heldBack`, exit 1).//!       AVATAR SEAL (27 Nov 2026), faces on live, for the coordinator alone://!         seal-files reseal <device> --kinds people --dry-run//!         seal-files reseal <device> --kinds people --keep <dir> --progress <dir>/people.done//!//!   <device> = --base <url> --device-id <id> --token-file <device credential> [--key-file <path>] [--data-dir <dir>]//!//! Tests: `cargo test -p cotton-mac --test files`.use std::path::PathBuf;use std::process::ExitCode;use cotton_client::media::sealed::SEALED_KINDS;use cotton_mac::device::{Device, DeviceArgs};use cotton_mac::files::{fetch_listed, fetch_opened, put_listed_telling, report, reseal, reseal_plan, Fetch, Item, ResealOptions};use cotton_mac::object::ObjectError;use cotton_mac::patience::Patience;const USAGE: &str = "seal-files put|get|serve|queue|rows|row|reseal --base <url> --device-id <id> --token-file <path> [--key-file <path>] [--data-dir <dir>] …  (see the file's head)";fn no_seal_door() -> ObjectError {    ObjectError::File("this client holds no seal door".to_string())}/// Every live row of `table`, an object that is away for now waited for.fn patient_rows(device: &Device, table: &str) -> Result<Vec<serde_json::Value>, String> {    Patience::default().run(|| device.object.device_rows(table).unwrap_or_else(|| Err(no_seal_door()))).map_err(|e| e.to_string())}fn run() -> Result<bool, String> {    let mut argv = std::env::args().skip(1);    let verb = argv.next().ok_or(USAGE)?;    let argv: Vec<String> = argv.collect();    let mut device = DeviceArgs::default();    let (mut list, mut key, mut out, mut keep, mut progress) = (None, None, None, None, None);    let mut table: Option<String> = None;    let (mut id, mut since): (Option<String>, i64) = (None, 0);    let (mut threads, mut limit, mut tries): (Option<usize>, Option<usize>, u32) = (None, None, 4);    let (mut dry_run, mut keep_clear) = (false, false);    let mut kinds: Vec<String> = SEALED_KINDS.iter().map(|kind| kind.to_string()).collect();    let mut at = 0;    while at < argv.len() {        let flag = argv[at].as_str();        match flag {            "--dry-run" => dry_run = true,            "--keep-clear" => keep_clear = true,            _ => {                let value = argv.get(at + 1).filter(|v| !v.starts_with("--")).ok_or_else(|| format!("{flag} needs a value"))?;                at += 1;                if !device.take(flag, value) {                    match flag {                        "--list" => list = Some(PathBuf::from(value)),                        "--key" => key = Some(value.clone()),                        "--table" => table = Some(value.clone()),                        "--id" => id = Some(value.clone()),                        "--since" => since = value.parse().map_err(|_| "--since takes a version")?,                        "--out" => out = Some(PathBuf::from(value)),                        "--keep" => keep = Some(PathBuf::from(value)),                        "--progress" => progress = Some(PathBuf::from(value)),                        "--threads" => threads = Some(value.parse().map_err(|_| "--threads takes a number")?),                        "--tries" => tries = value.parse().map_err(|_| "--tries takes a number")?,                        "--limit" => limit = Some(value.parse().map_err(|_| "--limit takes a number")?),                        "--kinds" => {                            kinds = value.split(',').filter(|k| !k.is_empty()).map(str::to_string).collect();                            if let Some(stray) = kinds.iter().find(|kind| !SEALED_KINDS.contains(&kind.as_str())) {                                return Err(format!("--kinds: {stray} is not one of {}", SEALED_KINDS.join(", ")));                            }                        }                        other => return Err(format!("unknown argument {other}\n{USAGE}")),                    }                }            }        }        at += 1;    }    let device = device.open()?;    match verb.as_str() {        "put" => {            let list = list.ok_or("put needs --list <items.jsonl>")?;            let text = std::fs::read_to_string(&list).map_err(|e| format!("{}: {e}", list.display()))?;            let items: Vec<Item> = text.lines().filter(|line| !line.trim().is_empty()).map(|line| serde_json::from_str(line).map_err(|e| format!("--list: {e}"))).collect::<Result<_, _>>()?;            let said = std::sync::Mutex::new(());            let outcomes = put_listed_telling(&device.object, &items, threads.unwrap_or(4), &Patience::default(), &|outcome| {                let _one_line = said.lock();                println!("{}", serde_json::to_string(outcome).unwrap_or_default());            });            Ok(outcomes.len() == items.len() && outcomes.iter().all(|o| o.state != "failed"))        }        "get" if list.is_some() => {            let list = list.unwrap_or_default();            let text = std::fs::read_to_string(&list).map_err(|e| format!("{}: {e}", list.display()))?;            let items: Vec<Fetch> = text.lines().filter(|line| !line.trim().is_empty()).map(|line| serde_json::from_str(line).map_err(|e| format!("--list: {e}"))).collect::<Result<_, _>>()?;            let said = std::sync::Mutex::new(());            let outcomes = fetch_listed(&device.object, &items, threads.unwrap_or(8), tries, std::time::Duration::from_secs(1), &|outcome| {                let _one_line = said.lock();                println!("{}", serde_json::to_string(outcome).unwrap_or_default());            });            Ok(outcomes.len() == items.len() && outcomes.iter().all(|o| o.state != "failed"))        }        "get" => {            let (key, out) = (key.ok_or("get needs --key")?, out.ok_or("get needs --out")?);            let bytes = fetch_opened(&device.object, &key, &out)?;            println!("{}", serde_json::json!({ "key": key, "bytes": bytes }));            Ok(true)        }        "serve" => {            // The importers' rows, written as this Mac (token scopes, 24 Nov 2026): sealed by the device, one act a line.            let stdin = std::io::stdin();            let served = cotton_mac::files::serve_acts(stdin.lock(), std::io::stdout(), |act, table, id, data| device.object.act(act, table, id, data))?;            eprintln!("seal-files serve: {served} acts");            Ok(true)        }        "queue" => {            let rows = patient_rows(&device, "fetch")?;            for row in rows {                let data = &row["data"];                println!("{}", serde_json::json!({ "id": row["id"], "source": data["source"], "title": data["title"] }));            }            Ok(true)        }        "rows" => {            let table = table.ok_or("rows needs --table")?;            let rows = patient_rows(&device, &table)?;            for row in rows {                println!("{}", serde_json::json!({ "id": row["id"], "data": row["data"] }));            }            Ok(true)        }        "row" => {            let (table, id) = (table.ok_or("row needs --table")?, id.ok_or("row needs --id")?);            let found = Patience::default().run(|| device.object.device_row(&table, &id, since).unwrap_or_else(|| Err(no_seal_door()))).map_err(|e| e.to_string())?;            if let Some(row) = found {                println!("{}", serde_json::json!({ "id": row["id"], "data": row["data"] }));            }            Ok(true)        }        "reseal" => {            if !dry_run && keep.is_none() {                return Err("reseal needs --keep <dir> (where each clear copy waits until its sealed one is verified), or --dry-run".to_string());            }            let plan = reseal_plan(&device.object, &device.database_id, &kinds, dry_run)?;            let keys = plan.keys;            eprintln!("{} files named by the person's rows or listed plain by the object", keys.len());            for (kind, devices) in &plan.held_back {                // Device names only (the person's own), never a key's contents.                eprintln!("{kind}: held back by the object while {} device(s) read it on an app from before: {}{}", devices.len(), devices.join(", "), if dry_run { " (counted anyway: a dry run reads only)" } else { " (none of it touched)" });            }            let options = ResealOptions { dry_run, keep: keep.unwrap_or_default(), keep_clear, progress, limit, threads: threads.unwrap_or(4) };            let mut done = 0usize;            let outcomes = reseal(&device.object, &keys, &options, &mut |outcome| {                done += 1;                if outcome.state != "held" {                    // The key names a kind and a digest or id, never a title.                    eprintln!("{done:>7}/{}  {:<8} {}{}", keys.len(), outcome.state, outcome.key, outcome.why.as_deref().map(|why| format!("  ({why})")).unwrap_or_default());                }            })?;            let mut summary = report(&outcomes, dry_run);            summary["heldBack"] = serde_json::json!(plan.held_back);            println!("{}", serde_json::to_string_pretty(&summary).unwrap_or_default());            Ok(outcomes.len() == keys.len() && summary["left"] == 0 && plan.held_back.is_empty())        }        other => Err(format!("no verb {other}\n{USAGE}")),    }}fn main() -> ExitCode {    match run() {        Ok(true) => ExitCode::SUCCESS,        Ok(false) => ExitCode::from(1),        Err(why) => {            eprintln!("seal-files: {why}");            ExitCode::from(2)        }    }}