//! `join.*`, `bootstrap.*` and `migrate.*` — the three long-running commands, //! as methods with events. //! //! Design P15 and P16. Each of them takes minutes, so none of them is a call //! that returns an answer: `*.start` returns AT ONCE, the work runs on a //! thread, progress arrives on the `client` event stream, and `*.status` //! answers where it got to for a screen that missed an event or was not //! subscribed yet. //! //! **One shape for all three**, because a screen that had to learn three would //! be three screens: //! //! ```json //! { "kind": "client", "payload": { "phase": "join|download|migrate", "stage": …, … } } //! ``` //! //! `bootstrap.*` and `migrate.*` are ONE thread and one command in the code: //! the ladder runs inside `open_replica`, which is inside the bootstrap. They //! are two method families because they are two SCREENS — "Downloading your //! database" and "Updating your database" — and a screen asking after the one //! it is drawing should not have to know that. use std::sync::Mutex; use cotton_client::connection::read_connection; use cotton_client::replica::MigrationEvent; use cotton_core::device::pairing::DevicePlatform; use serde_json::{json, Value}; use crate::events::EventKind; use crate::handle::CottonHandle; use crate::methods::MethodError; /// The method names this module answers. pub const COMMAND_METHODS: &[&str] = &[ "records.move", "bootstrap.start", "bootstrap.status", // The scene phases. Two methods rather than one with a flag, because they // are not each other's inverse: coming forward RESETS the backoff ladder, // going back leaves the timer exactly where it was. "sync.background", "sync.foreground", // **A phone starts a database of its own.** The other half of the first // screen: a fresh device could only ever Join, which meant a person needed // a Mac in the room before they could write anything down — and it meant // the RECOVERY path, where the phone is the copy that survived, had no // first step. Its own method rather than a flag on `join.start`: the two // share no argument, no event and no ending. "workspace.startLocal", ]; /// `migrate.*` — the same thread, a different screen. pub const MIGRATE_METHODS: [&str; 1] = ["migrate.status"]; /// Where the bootstrap and the ladder have got to, for whoever asks. #[derive(Debug, Clone, Default)] pub struct Progress { pub migration: Option, /// The ladder's `from` and `to`, kept from its `start` — a `step` does /// not carry them, and the upgrade screen names both versions. pub migration_span: Option<(u32, u32)>, pub running: bool, pub opened: bool, } impl Progress { /// One rung of a ladder, and the span its `start` named. fn record_migration(&mut self, step: MigrationEvent) { if let MigrationEvent::Start { from, to, .. } = step { self.migration_span = Some((from, to)); } self.migration = Some(step); } } /// The commands' shared state, held for the life of the handle. #[derive(Debug, Default)] pub struct Commands { pub progress: Mutex, } impl Commands { pub(crate) fn progress(&self) -> Progress { self.progress .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .clone() } pub fn edit(&self, change: impl FnOnce(&mut Progress)) { change( &mut self .progress .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()), ); } } /// Dispatch one command. pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { match method { "bootstrap.start" => bootstrap_start(handle), "bootstrap.status" => Ok(bootstrap_status(handle)), "migrate.status" => Ok(migrate_status(handle)), "sync.foreground" => foreground(handle), "sync.background" => Ok(background(handle, request)), "workspace.startLocal" => start_local(handle, request), other => Err(MethodError::new( "unknown_method", format!("this core answers no `{other}`"), )), } } // ── join ────────────────────────────────────────────────────────────────── /// What this build IS, when the caller does not say. /// /// **A Mac that STARTS a workspace was filed as an iPhone.** `join.start` /// carries a platform because the Mac's join form sends `"mac"`; /// `workspace.startLocal` carries none — its Swift request is /// `{deviceName, appVersion}` — and the fallback here was a flat /// `DevicePlatform::Ios`, so the self row of every Mac that pressed Start /// said `platform: "ios"` for ever after. `list_devices` then answered a /// household of iPhones, and anything asking "which of these can host a /// session" had nothing truthful to filter on. /// /// The fallback is THE SLICE'S OWN TARGET rather than a word: the macOS slice /// is the only one built for macOS, and a device cannot be wrong about the /// operating system it is running. An explicit platform still wins — a caller /// that names one is answering for itself. pub(crate) const THIS_BUILDS_PLATFORM: DevicePlatform = if cfg!(target_os = "macos") { DevicePlatform::Mac } else if cfg!(target_os = "linux") { DevicePlatform::Linux } else if cfg!(target_os = "android") { DevicePlatform::Android } else { DevicePlatform::Ios }; /// The platform a request names, or this build's own. pub(crate) fn asked_platform(named: Option<&str>) -> DevicePlatform { named .and_then(DevicePlatform::parse) .unwrap_or(THIS_BUILDS_PLATFORM) } // ── starting a database on this device ──────────────────────────────────── /// `workspace.startLocal {name?, deviceName?, appVersion?}` → /// `{workspaceId, ownerId, deviceId, mode: "local", state: "noServerYet"}`. /// /// **Start, the other half of the first screen.** A fresh phone could only /// Join, because a workspace was born in `cotton_server::provision` and iOS /// links no server — so a person needed a Mac in the room before they could /// write anything down, and the recovery path (the phone is the copy that /// survived) had no first step at all. /// /// It returns when the database EXISTS, not at once: the whole act is a file /// created and two rows written, which is milliseconds, and a screen that had /// to poll for it would be a screen waiting on nothing. `join.start` is the /// long one, and it is long because somebody has to walk to another device. /// /// **No server is started.** Nothing listens, nothing is served, no registry /// exists ([eventually-cotton-is-a-mac-or-android-app-acting-as-a-self-hosted]). /// What comes back is a connection record in /// [`cotton_client::connection::ConnectionMode::Local`], which `read.boot` /// reads as `paired` and `read.syncStatus` reports as `state: "noServerYet"` — /// the phone's "No Mac yet". /// /// The `bootstrap/ready` frame goes out at the end, the same one /// `bootstrap.start` emits, because it is the same fact: there is a file and /// the app may open on it. A screen that learned to wait for one after a join /// must not have to learn a second word after a start. pub(crate) fn start_local(handle: &CottonHandle, request: &Value) -> Result { let text = |key: &str| { request .get(key) .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) }; let layout = handle.layout().clone(); let clock = cotton_client::seams::SystemClock; let random = cotton_client::seams::SystemRandom; // The KEY, read rather than minted. A device row keyed by anything but the // real Ed25519 public half is a row no server will ever match, so a launch // whose keychain was unavailable writes no row at all and still gets its // database — `StartLocal::device_key_id` says why that is a state. let device_key_id = handle.identity().device_id.clone(); let started = cotton_client::start_local(cotton_client::StartLocal { layout: &layout, clock: &clock, random: &random, name: text("name"), device_key_id: device_key_id.as_deref(), // What this device is called in the list. The phone's own name, which // Swift reads off `UIDevice`; a caller that sends none is filed under // the same placeholder a join would use. device_name: text("deviceName").unwrap_or("This phone"), platform: asked_platform(text("platform")), app_version: text("appVersion").or(Some(handle.app_version())), // The device key signs the new file's first author and seed rows. receipt_signer: handle.client().receipt_signer_slot(), }) .map_err(|error| MethodError::new(error.code(), error.to_string()))?; // OPEN ON IT NOW. The controller re-reads the connection record on every // attach, so this is only the difference between the app drawing its first // screen in this frame and in the one after the next question. let _ = handle.client().attach_now(); handle.events().emit( EventKind::Client, json!({ "phase": "bootstrap", "stage": "ready", "workspaceId": started.workspace_id, }), ); Ok(json!({ "workspaceId": started.workspace_id, "ownerId": started.owner_id, // `null` on a device with no key yet — and then there is no device row // either, which the Your devices screen draws as this phone alone. "deviceId": started.device_id, "mode": "local", // The word the phone renders as "No Mac yet". "state": crate::shell::client::NO_SERVER_YET, })) } // ── bootstrap and the ladder ────────────────────────────────────────────── fn bootstrap_start(handle: &CottonHandle) -> Result { let Some(stored) = read_connection(&handle.layout().connection_json()) .ok() .flatten() .filter(|stored| stored.workspace_id.is_some()) else { return Err(MethodError::new( "no_server", "this phone has not joined a server yet", )); }; // A COPY FROM A SERVER was fetched through this device's signed // transport, which it no longer has. if stored.mode.has_server() { return Err(MethodError::new( "device_key_unreadable", "this phone has no device identity to sign with", )); } let workspace_id = stored .workspace_id .clone() .expect("a workspace, filtered above"); // **A LOCAL DATABASE IS ALREADY DOWNLOADED.** A phone that started its own // has the file the bootstrap exists to fetch, and there is no server to // fetch it from — so the answer is the `ready` frame straight away rather // than a `no_server` refusal painted over a database that is perfectly // well. The gate treats this event exactly as it treats a download's. let _ = handle.client().attach_now(); handle.commands().edit(|progress| { progress.running = false; progress.opened = true; }); handle.events().emit( EventKind::Client, json!({ "phase": "bootstrap", "stage": "ready", "workspaceId": workspace_id }), ); Ok(json!({ "started": true, "alreadyRunning": false })) } /// The migration event as a screen reads it. /// /// `pub(crate)` because the CONTROLLER reports the ladder too now — a launch /// with an existing file runs it inside `attach` — and both reporters must /// emit the one shape, or a screen would have two vocabularies for one ladder. pub(crate) fn migration_json(step: &MigrationEvent) -> Value { match step { MigrationEvent::Start { from, to, total } => json!({ "phase": "migrate", "stage": "start", "from": from, "to": to, "total": total, }), MigrationEvent::Step { version, index, total, } => json!({ "phase": "migrate", "stage": "step", "version": version, "index": index, "total": total, }), MigrationEvent::Done { from, to, dropped_from_outbox, replayed, } => json!({ "phase": "migrate", "stage": "done", "from": from, "to": to, "droppedFromOutbox": dropped_from_outbox, "replayed": replayed, }), // The page names this sentence: the move's own reason, never a guess. MigrationEvent::Failed { from, to, message } => json!({ "phase": "migrate", "stage": "failed", "from": from, "to": to, "version": to, "message": message, }), } } fn bootstrap_status(handle: &CottonHandle) -> Value { let mut answer = status_of(handle.commands().progress()); // WHY THE COPY WAS NOT MOVED, while that stands: the move's own reason, // written before anything else (`cotton_client::bootstrap::not_moved`). let layout = handle.layout(); if let Some(why) = read_connection(&layout.connection_json()) .ok() .flatten() .and_then(|stored| stored.workspace_id) .and_then(|workspace_id| cotton_client::bootstrap::not_moved::why(layout, &workspace_id)) { answer["notMoved"] = json!(why); } answer } fn status_of(progress: Progress) -> Value { json!({ "running": progress.running, "ready": progress.opened, }) } fn migrate_status(handle: &CottonHandle) -> Value { let progress = handle.commands().progress(); let mut answer = match progress.migration { // An ordinary launch paints NOTHING: no start, no settle, no frame held // for a screen with one step in it. None => json!({ "running": false }), Some(step) => { let mut answer = migration_json(&step); // A failed move is not running: the page stops on its reason. answer["running"] = json!(!matches!( step, MigrationEvent::Done { .. } | MigrationEvent::Failed { .. } )); // A `step` names both versions too, so a screen that came up after // the `start` can still say "from A to B". if let (MigrationEvent::Step { .. }, Some((from, to))) = (&step, progress.migration_span) { answer["from"] = json!(from); answer["to"] = json!(to); } answer } }; // **THE REST OF AN OPEN, NAMED BY THE CORE.** With no ladder running, the // wait is the open itself, and the controller says which step it is on — // `recovering` when the last run left saved changes in the write-ahead // log, `reading` otherwise. Absent when no open is running. The wait // screen names this and never guesses a reason of its own. if answer["running"] != json!(true) { if let Some(step) = handle.client().opening() { answer["opening"] = json!(step.as_str()); } } answer } impl Commands { /// Record one rung of a ladder the CONTROLLER is running. /// /// The same slot `note` writes for a ladder inside a bootstrap, so /// `migrate.status` answers the same shape whichever ran it: the screen /// asks one question and does not care which path opened the file. pub fn note_migration(&self, step: MigrationEvent) { self.edit(|progress| progress.record_migration(step)); } } #[cfg(test)] pub fn migration_json_for_test(step: &MigrationEvent) -> Value { migration_json(step) } // ── the scene phases ────────────────────────────────────────────────────── /// The app came to the front. /// /// The failure count goes back to its bottom rung and one cycle is asked for, /// off the caller's thread. A person who has just unlocked their phone is /// saying the conditions changed — a train came out of a tunnel, a hotspot /// came up — and answering that with "in half an hour, because the ladder says /// so" is an app that looks broken while working exactly as written. fn foreground(handle: &CottonHandle) -> Result { // A counter, so synchronous: a screen that asks `sync.status` in the next // frame must see it. crate::phone::trim::came_forward(); let reset = handle.client().sync_wake_and_reset(); Ok(json!({ "ladder": if reset { "reset" } else { "no schedule" }, })) } /// The app went to the back. /// /// The sync timer stays. iOS hands a backgrounded app time it did not ask /// for — a background fetch, a push arriving — and a loop that stopped itself /// would waste it. fn background(handle: &CottonHandle, request: &Value) -> Value { // `budgetMs`: what is left of the time iOS gives the app in the back — // the box closes there, and `0` (the time ran out) cuts the pass now. let left = request .get("budgetMs") .and_then(Value::as_u64) .map(std::time::Duration::from_millis); handle.client().sync_background(left); crate::phone::trim::went_back(&handle.client(), left); // And fold the write-ahead log back into the file WHILE THE APP IS STILL // ALIVE. `cotton_close` runs from a Swift `deinit` and a force-quit runs no // `deinit`, so without this the launch after one pays the recovery of // everything written since the last checkpoint — a SQLite open, on the // boundary that answers one call at a time, in front of a person looking at // the splash. Going to the back is the moment nobody is waiting. let checkpointed = handle.client().checkpoint(); json!({ "timer": "kept", "checkpoint": checkpointed }) }