Cotton code
276 lines · 15.0 KB · RustRaw
//! RESTORE AN EARLIER DAY (RESTORE PHONE 2, 28 Nov 2026; `assets/design/shared/RESTORE-2-CONTRACT.md` 8, the page//! for both phones `restore2-methods.md`). The owner, on their own signed-in phone, puts the whole account back to the//! end of a day the server kept. The server does all of it (`apps/business/src/restore_owner.ts`): it freezes the//! account, checks every part of the copy, lays the rows back, replays what must never come back (signed-out devices,//! erased tables), raises the version and writes a new generation, then unfreezes by itself. This phone only asks,//! steps it while it watches, and says where it stands; every word is `kits/shell/lines/restore.json`.//!//! ```text//! restore.points {}                 → the days that can be restored, and where a restore stands//! restore.begin { id, anyway? }     → it begins (the progress answer), or asks first when older devices are signed in//! restore.progress {}               → a few parts more, and where it stands (call it every second while under way)//! restore.cancel {}                 → taken back while it still checks; nothing changed//! restore.after {}                  → what the account shows after a restore: the day, this phone's copy, what is kept aside//! ```//!//! KEYS NEVER LEAVE THE PHONE. Nothing here sends a key, a sealed value or a row: the server's copy holds the rows as//! stored (sealed rows stay sealed) and lays them back inside the account. RESTORE'S FILES ARE NEVER SERVED: the//! server answers these routes only to the owner's own phone signed in with its device credential (an assistant's//! key, the admin, another person's phone are refused `owner_device_only`), and no route hands out a copy's bytes.//!//! THE OFF SWITCH. The server answers these routes only where its restore routes are on (dev and test); anywhere else//! they are 404, and `restore.points` answers `available: false` with one line, so the shell shows the row as not//! available (or hides it). Nothing is retried or said as a fault.//!//! AFTER. Each phone, this one included, sees the new generation on its next pull (or a 409 on its next write) and//! sets its copy aside and makes it again (`personal_object` `Heal::run_restored`): the Sync line says "Bringing it to//! this phone…" until the new copy catches up. `restore.after` says the same for a Restore page, and how many changes//! this phone made before then are kept aside (listed in Sync, never sent by themselves).use cotton_client::transport::object::{bearer, ObjectRefusal};use cotton_core::rules::shell_lines::resolve;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::personal_object::ObjectDoor;/// The server's routes (`apps/business/src/restore_owner.ts`).pub const LIST: &str = "/v1/restore";pub const BEGIN: &str = "/v1/restore/begin";pub const STEP: &str = "/v1/restore/step";pub const STATE: &str = "/v1/restore/state";pub const CANCEL: &str = "/v1/restore/cancel";pub const METHODS: [&str; 5] = ["restore.points", "restore.begin", "restore.progress", "restore.cancel", "restore.after"];/// One line of the restore set, filled.pub fn say(line: &str, fills: &[(&str, &str)]) -> String {    resolve("restore", line, &[], fills).unwrap_or_default()}pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    let zone = client.time_zone().unwrap_or("UTC").to_string();    if method == "restore.after" {        return Ok(after(handle, &zone));    }    let door = client.object_door().ok_or_else(|| MethodError::new("sign_in", say("refused.sign_in", &[])))?;    match method {        "restore.points" => points(&door, &zone),        "restore.begin" => begin(&door, request, &zone),        "restore.progress" => progress(&door, &zone),        "restore.cancel" => cancel(&door, &zone),        other => Err(MethodError::new("unknown_method", format!("{other} is not a restore method"))),    }}fn send(door: &ObjectDoor, method: &str, path: &str, body: Option<&Value>) -> Result<Value, ObjectRefusal> {    door.address.send(door.exchange.as_ref(), method, path, bearer(&door.credential), body)}/// Whether the server answers no restore at all (its off switch: the routes are not there).fn unavailable(refusal: &ObjectRefusal) -> bool {    matches!(refusal.status, 404 | 405) && matches!(refusal.code.as_str(), "not_found" | "method_not_allowed" | "refused")}/// A refusal in the set's words, its code kept for the shell.fn said(refusal: ObjectRefusal) -> MethodError {    let line = match refusal.code.as_str() {        _ if unavailable(&refusal) => return MethodError::new("unavailable", say("page.unavailable", &[])),        _ if refusal.transient() => return MethodError::new("unreached", say("refused.unreached", &[])),        "sign_in" | "invalid_credential" | "credential_expired" => "refused.sign_in",        "owner_device_only" => "refused.owner_only",        "account_deleting" | "account_deleted" | "credential_revoked" => "refused.deleting",        "restore_under_way" => "refused.under_way",        "no_such_point" => "refused.gone",        "no_restore" => "progress.stopped",        "restore_laying" => "progress.too_far",        _ => "refused.not_now",    };    let code = match refusal.code.as_str() {        "invalid_credential" | "credential_expired" => "sign_in",        "account_deleted" | "credential_revoked" => "account_deleting",        "sign_in" | "owner_device_only" | "account_deleting" | "restore_under_way" | "no_such_point" | "no_restore" | "restore_laying" => refusal.code.as_str(),        _ => "not_now",    };    MethodError::new(code, say(line, &[])).with_details(json!({ "server": refusal.code }))}/// A moment the server says, in the person's zone: its day ("Friday 20 November") and its time ("6:54 pm").fn day_and_time(iso: &str, zone: &str) -> (String, String) {    let day = cotton_core::kit::local_clock(iso, zone, "%A %-d %B").unwrap_or_else(|| iso.to_string());    let time = cotton_store::protocol::js::parse_date_ms(iso)        .and_then(|ms| cotton_core::cotton_rules::zoned_clock::zoned_parts(ms, zone).or_else(|_| cotton_core::cotton_rules::zoned_clock::zoned_parts(ms, "UTC")).ok())        .map(|at| cotton_core::records::page::DateWords::shipped().clock(at.hour, at.minute))        .unwrap_or_default();    (day, time)}/// The page's words, always the same.fn page_words() -> Value {    json!({        "row": say("page.row", &[]),        "heading": say("page.heading", &[]),        "intro": say("page.intro", &[]),        "choose": say("page.choose", &[]),        "confirmGo": say("page.confirm_go", &[]),        "confirmBack": say("page.confirm_back", &[]),    })}/// `restore.points`: the days, newest first, each with its words and the confirm it asks; where a restore stands.pub fn points(door: &ObjectDoor, zone: &str) -> Result<Value, MethodError> {    let listed = match send(door, "GET", LIST, None) {        Ok(listed) => listed,        Err(refusal) if unavailable(&refusal) => return Ok(json!({ "available": false, "line": say("page.unavailable", &[]), "words": page_words() })),        Err(refusal) => return Err(said(refusal)),    };    let days: Vec<Value> = listed["points"]        .as_array()        .map(|points| {            points                .iter()                .filter_map(|point| {                    let id = point["id"].as_str()?;                    let to = point["to"].as_str()?;                    let (day, time) = day_and_time(to, zone);                    Some(json!({                        "id": id,                        "to": to,                        "label": say("page.day", &[("day", &day), ("time", &time)]),                        "confirmHeading": say("page.confirm_heading", &[("day", &day)]),                        "confirmLine": say("page.confirm_line", &[("day", &day), ("time", &time)]),                    }))                })                .collect()        })        .unwrap_or_default();    let empty = days.is_empty().then(|| say("page.empty", &[]));    Ok(json!({        "available": true,        "words": page_words(),        "days": days,        "empty": empty,        "olderDevices": listed["devices_unready"].as_u64().unwrap_or(0),        "deleting": listed["deleting"].as_bool().unwrap_or(false),        "progress": progress_of(&listed, zone, false),    }))}/// `restore.begin { id, anyway? }`: the progress answer once begun; `{ confirm }` first when older devices are signed/// in (asked again with `anyway: true`). A refusal is a [`MethodError`] in the set's words.pub fn begin(door: &ObjectDoor, request: &Value, zone: &str) -> Result<Value, MethodError> {    let id = request.get("id").and_then(Value::as_str).map(str::trim).filter(|id| !id.is_empty()).ok_or_else(|| MethodError::new("bad_request", "`id` is missing"))?;    let anyway = request.get("anyway").and_then(Value::as_bool).unwrap_or(false);    match send(door, "POST", BEGIN, Some(&json!({ "point": id, "anyway": anyway }))) {        Ok(state) => Ok(progress_of(&state, zone, false)),        Err(refusal) if refusal.code == "devices_without_generation" => {            // The message leads with the count (`<n> device(s) …`, src/business.ts `ownerRestoreRoute`).            let n = refusal.message.split_whitespace().next().and_then(|n| n.parse::<u64>().ok()).unwrap_or(1);            Ok(json!({ "confirm": { "olderDevices": n, "line": say("older.line", &[("n", &n.to_string())]), "go": say("older.go", &[]), "back": say("older.back", &[]) } }))        }        Err(refusal) => Err(said(refusal)),    }}/// `restore.progress`: a few parts more (the server steps it while this phone asks; the alarm otherwise), and where/// it stands. Interrupted (the app closed, the phone restarted), the next call goes on from where the server is.pub fn progress(door: &ObjectDoor, zone: &str) -> Result<Value, MethodError> {    match send(door, "POST", STEP, Some(&json!({}))) {        Ok(state) => Ok(progress_of(&state, zone, true)),        // A step that failed part way is tried again by the server: said as paused, never as a fault.        Err(refusal) if !refusal.transient() && !unavailable(&refusal) && !refusal.signs_out() => {            let state = send(door, "GET", STATE, None).map_err(said)?;            let mut answer = progress_of(&state, zone, true);            answer["line"] = json!(say("progress.paused", &[]));            Ok(answer)        }        Err(refusal) => Err(said(refusal)),    }}/// `restore.cancel`: taken back while it still checks (no row touched, the account unfrozen).pub fn cancel(door: &ObjectDoor, zone: &str) -> Result<Value, MethodError> {    let state = send(door, "POST", CANCEL, Some(&json!({}))).map_err(said)?;    let mut answer = progress_of(&state, zone, false);    answer["line"] = json!(say("progress.stopped", &[]));    Ok(answer)}/// Where a restore stands, from any of the server's answers: `stage` (`none`, `checking`, `laying`, `held`, `done`),/// the day it goes back to, its fraction and line, and whether it may still be stopped.fn progress_of(state: &Value, zone: &str, stepping: bool) -> Value {    let server_stage = state["stage"].as_str().unwrap_or("none");    let finished = state["finished"].as_bool().unwrap_or(false);    let under = &state["restore"];    let to = under["to"].as_str().or_else(|| finished.then(|| state["restored_to"].as_str()).flatten());    let (day, time) = to.map(|to| day_and_time(to, zone)).unwrap_or_default();    let (done, total) = (under["done"].as_u64().unwrap_or(0), under["total"].as_u64().unwrap_or(0));    let stage = if finished && stepping { "done" } else { server_stage };    let line = match stage {        "checking" => Some(say("progress.checking", &[("day", &day), ("done", &under["checked"].as_u64().unwrap_or(0).to_string()), ("total", &under["parts"].as_u64().unwrap_or(0).to_string())])),        "laying" => Some(say("progress.laying", &[("day", &day), ("done", &under["laid"].as_u64().unwrap_or(0).to_string()), ("total", &under["parts"].as_u64().unwrap_or(0).to_string())])),        "held" => Some(say("progress.held", &[])),        "done" => Some(say("progress.done", &[("day", &day)])),        _ => None,    };    let may_cancel = state["may_cancel"].as_bool().unwrap_or(false);    json!({        "stage": stage,        "to": to,        "toLabel": to.map(|_| say("page.day", &[("day", &day), ("time", &time)])),        "done": done,        "total": total,        "fraction": if total > 0 { (done as f64 / total as f64).min(1.0) } else if stage == "done" { 1.0 } else { 0.0 },        "line": line,        "mayCancel": may_cancel,        "stop": may_cancel.then(|| say("progress.stop", &[])),        "underWay": matches!(stage, "checking" | "laying"),    })}/// `restore.after`: what a restored account shows, read from this phone (its copy being made again, the changes it/// kept aside) and, when Cotton answers, from the server (the moment the account was put back to). Offline it says/// what this phone knows; never an error.pub fn after(handle: &CottonHandle, zone: &str) -> Value {    let client = handle.client();    let pass = client.sync_progress().map(|progress| progress.state());    // The copy being made again after a restore: the time it was put back to (empty when the server did not say).    let bringing = pass.as_ref().and_then(|pass| pass.restoring.clone().or_else(|| pass.restored.as_ref().map(|seen| seen.restored_to.clone().unwrap_or_default())));    let from_server = client.object_door().and_then(|door| send(&door, "GET", "/v1/me", None).ok()).and_then(|me| me["restored_to"].as_str().map(str::to_string));    let to = from_server.or_else(|| bringing.clone().filter(|at| !at.is_empty()));    let (day, time) = to.as_deref().map(|to| day_and_time(to, zone)).unwrap_or_default();    let layout = client.layout();    let kept_aside = crate::phone::copy_aside::held(layout)        .and_then(|held| held.workspace_id)        .filter(|id| !id.is_empty())        .map(|database| {            let before: Vec<std::path::PathBuf> = cotton_client::copy_keep::kept(layout, Some(&database)).into_iter().filter(|kept| kept.state.before_restore.is_some()).map(|kept| kept.dir).collect();            cotton_client::copy_keep::kept_changes(layout, &database).iter().filter(|change| before.iter().any(|dir| change.kept.starts_with(dir))).count()        })        .unwrap_or(0);    let line = match (&to, bringing.is_some()) {        (Some(_), true) => Some(say("after.bringing", &[("day", &day)])),        (Some(_), false) => Some(say("after.restored", &[("day", &day)])),        (None, true) => Some(say("after.bringing_undated", &[])),        (None, false) => None,    };    json!({        "restored": to.is_some() || bringing.is_some(),        "to": to,        "toLabel": to.as_ref().map(|_| say("page.day", &[("day", &day), ("time", &time)])),        "bringing": bringing.is_some(),        "line": line,        "keptAside": kept_aside,        "keptLine": (kept_aside > 0).then(|| say("after.kept", &[("n", &kept_aside.to_string())])),    })}#[cfg(test)]#[path = "restore_tests.rs"]mod tests;#[cfg(test)]#[path = "restore_e2e.rs"]mod e2e;