Cotton code
421 lines · 17.6 KB · RustRaw
//! A Mac's own host settings, read and set on its Device page (Spec 10.4;//! COORDINATOR 06:48Z (b)) — the rows Settings › This Mac drew by hand.//!//! `read.device {deviceId}` answers a `host` section only when the row IS this//! Mac: the serving state from the server, and four switches and two//! addresses kept in `host-settings.json` beside the data. Any other device's page answers//! `host: null` with `hostAnsweredBy: "not_this_mac"`, and `device.setHost`//! for it is refused: a Mac's switches are said by that Mac, never by a copy.//! The app applies them (the login item, the power assertion, the reporter,//! the updater); Rust holds the one answer of what they are.use serde::{Deserialize, Serialize};use serde_json::{json, Map, Value};use crate::methods::MethodError;use crate::shell::client::ClientController;/// The switches, in the order the page draws them, with their words.pub const SWITCHES: [(&str, &str); 4] = [    ("startAtLogin", "Start at login"),    ("stayAwake", "Stay awake"),    ("errorReports", "Error reports"),    ("autoUpdates", "Updates"),];/// The two addresses a Mac can be pointed at, in the order the page draws/// them, with their words: where its error reports go, and where its updates/// come from.////// Each is `None` until the person says otherwise, and `None` is "what this/// build was stamped with" — the app's own `CottonSentryDSN` and `SUFeedURL`./// They are settings and not constants because neither service is Cotton's to/// insist on: a household that runs its own relay may run its own error/// service and mirror its own updates, and one that wants neither turns the/// switch beside each off.pub const ADDRESSES: [(&str, &str); 2] = [    ("errorReportsTo", "Error reports go to"),    ("updateFeed", "Updates come from"),];/// Every switch is ON until the person turns it off — the defaults the Mac/// app had (`HostSettings.swift`) — and neither address is set.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", default)]pub struct HostSettings {    pub start_at_login: bool,    pub stay_awake: bool,    pub error_reports: bool,    pub auto_updates: bool,    /// The DSN this Mac's error reports are sent to instead of the build's.    pub error_reports_to: Option<String>,    /// The https feed this Mac's updates are read from instead of the    /// build's. The app honours it only where the build already is an update    /// channel, and every update is still verified against the build's own    /// key — a feed can offer a release, never vouch for one.    pub update_feed: Option<String>,}impl Default for HostSettings {    fn default() -> Self {        HostSettings {            start_at_login: true,            stay_awake: true,            error_reports: true,            auto_updates: true,            error_reports_to: None,            update_feed: None,        }    }}impl HostSettings {    fn slot(&mut self, key: &str) -> Option<&mut bool> {        match key {            "startAtLogin" => Some(&mut self.start_at_login),            "stayAwake" => Some(&mut self.stay_awake),            "errorReports" => Some(&mut self.error_reports),            "autoUpdates" => Some(&mut self.auto_updates),            _ => None,        }    }    fn address(&mut self, key: &str) -> Option<&mut Option<String>> {        match key {            "errorReportsTo" => Some(&mut self.error_reports_to),            "updateFeed" => Some(&mut self.update_feed),            _ => None,        }    }}/// An address a person typed for one of [`ADDRESSES`], as it is kept — or why/// it is not one. Refused rather than repaired: the app hands the value to/// the reporter or the updater as it stands.////// * `updateFeed` — an `https://` URL with a host and no credentials or///   fragment: the appcast./// * `errorReportsTo` — a DSN, `https://<key>@<host>/<project>`: the form///   every Sentry-protocol service gives out (Bugsink, GlitchTip, Sentry).fn address_of(key: &str, typed: &str) -> Result<String, String> {    let said = |why: &str| format!("`{key}` {why}");    let url = url::Url::parse(typed).map_err(|_| said("is not an address"))?;    if url.scheme() != "https" {        return Err(said("is an https:// address"));    }    if url.host_str().is_none_or(str::is_empty) || url.fragment().is_some() {        return Err(said("is not an address"));    }    match key {        "errorReportsTo" => {            let project = url.path_segments().and_then(|mut parts| parts.next_back()).unwrap_or_default();            if url.username().is_empty() || url.password().is_some() || project.is_empty() || url.query().is_some() {                return Err(said("is the address your error service gives a project: https://<key>@<host>/<project>"));            }        }        _ => {            if !url.username().is_empty() || url.password().is_some() {                return Err(said("carries no name or password"));            }        }    }    Ok(typed.to_string())}/// What a receipt says about an address: the host, never the whole value — a/// DSN's key stays out of every sentence.fn host_shown(address: Option<&str>) -> Option<String> {    url::Url::parse(address?).ok()?.host_str().map(str::to_string)}/// What the file says, or the defaults when there is none (a file that does/// not read is also the defaults: these are a Mac's preferences, not records).pub fn read_settings(path: &std::path::Path) -> HostSettings {    std::fs::read(path)        .ok()        .and_then(|bytes| serde_json::from_slice(&bytes).ok())        .unwrap_or_default()}/// The patch, refused whole before anything is written: only the four/// switches, each a boolean, and the two addresses, each an address or/// nothing (`null` or blank puts the build's own back); at least one. Answers/// the new settings and the old value of each setting it named, switches in/// [`SWITCHES`] order and then addresses in [`ADDRESSES`] order.pub fn apply(current: &HostSettings, patch: &Map<String, Value>) -> Result<(HostSettings, Vec<(&'static str, Value)>), String> {    const NAMES: &str = "startAtLogin, stayAwake, errorReports, autoUpdates, errorReportsTo, updateFeed";    let mut next = current.clone();    let mut before = Vec::new();    let mut addresses: Vec<(&'static str, Option<String>)> = Vec::new();    for (key, value) in patch {        if key == "deviceId" {            continue;        }        if let Some((name, _)) = ADDRESSES.iter().find(|(name, _)| name == key) {            let typed = match value {                Value::Null => None,                Value::String(text) => Some(text.trim()).filter(|text| !text.is_empty()),                _ => return Err(format!("`{key}` is an address, or nothing for this build's own")),            };            addresses.push((name, typed.map(|typed| address_of(key, typed)).transpose()?));            continue;        }        if !SWITCHES.iter().any(|(name, _)| name == key) {            return Err(format!("`{key}` is not a host setting — only {NAMES}"));        }        if !value.is_boolean() {            return Err(format!("`{key}` is on or off: true or false"));        }    }    for (key, _) in SWITCHES {        if let Some(value) = patch.get(key).and_then(Value::as_bool) {            let slot = next.slot(key).expect("a switch");            before.push((key, json!(*slot)));            *slot = value;        }    }    for (key, _) in ADDRESSES {        if let Some((_, value)) = addresses.iter().find(|(name, _)| *name == key) {            let slot = next.address(key).expect("an address");            before.push((key, json!(*slot)));            *slot = value.clone();        }    }    if before.is_empty() {        return Err(format!("nothing to set: name one of {NAMES}"));    }    Ok((next, before))}/// What a set says it did, a phrase per setting it named: "Stay awake off",/// "Error reports go to errors.example.org", "Updates come from this build's/// own feed".pub fn receipt(next: &HostSettings, named: &[(&'static str, Value)]) -> String {    let mut next = next.clone();    named        .iter()        .map(|(key, _)| {            if let Some((_, words)) = SWITCHES.iter().find(|(name, _)| name == key) {                let on = next.slot(key).map(|value| *value).unwrap_or_default();                return format!("{words} {}", if on { "on" } else { "off" });            }            let words = ADDRESSES.iter().find(|(name, _)| name == key).map_or(*key, |(_, words)| *words);            let set = next.address(key).and_then(|value| value.clone());            match (host_shown(set.as_deref()), *key) {                (Some(host), _) => format!("{words} {host}"),                (None, "updateFeed") => format!("{words} this build's own feed"),                (None, _) => format!("{words} this build's own service"),            }        })        .collect::<Vec<_>>()        .join(" · ")}/// `read.device`'s answer before a host says anything: a phone, or a Mac/// looking at another device's page.pub fn device_page(client: &ClientController, args: &Map<String, Value>) -> Result<Value, String> {    let device = args        .get("deviceId")        .and_then(Value::as_str)        .filter(|id| !id.is_empty())        .ok_or("read.device needs deviceId")?;    let this = client.self_device_id().as_deref() == Some(device);    Ok(json!({        "deviceId": device,        "thisDevice": this,        "host": null,        "backup": null,        "hostAnsweredBy": if this { "not_a_mac" } else { "not_this_mac" },        "backupAnsweredBy": if this { "not_a_mac" } else { "no_serving_mac" },    }))}/// What a look at the backup found, in the person's words: the backup's one/// line (`records::backup`) when it is not getting through, naming the Mac.pub fn backup_receipt(backup: &Value, device: &str) -> String {    if let Some(line) = cotton_core::records::backup::receipt_line(backup, device, chrono::Utc::now()) { return line; }    match backup["state"].as_str() {        Some("ok") => "Backed up".to_string(),        Some("running") => "Backing up".to_string(),        _ => "Not backed up".to_string(),    }}/// The device page's backup line, from the daily copies' health/// (`cotton_server::daily_copies::health`): `{state: never|ok|failing,/// lastAt, lastError, nextAt, keptBytes, since, databases}`. `never` is a Mac/// that serves nothing; a database whose newest copy on every backup disk is/// older than the health's `staleAfterHours` (or that has none, or no backup/// disk mounted) is `failing` with its reason, since its newest copy. `lastAt`/// is the oldest of the databases' newest copies — when EVERY database was/// last copied. `databases` is each served database's own line, by id, so one/// failing is never hidden behind the whole line.pub fn backup_section(health: &Value) -> Value {    let disk = health["disk"] == true;    let hours = health["staleAfterHours"].as_i64().unwrap_or(26);    let stale: Vec<&str> = health["stale"].as_array().into_iter().flatten().filter_map(|row| row["database"].as_str()).collect();    let mut newest: Vec<(String, Option<String>)> = Vec::new();    for volume in health["volumes"].as_array().into_iter().flatten() {        for row in volume["databases"].as_array().into_iter().flatten() {            let Some(id) = row["database"].as_str() else { continue };            let at = row["newestCopyAt"].as_str().map(str::to_string);            match newest.iter_mut().find(|(known, _)| known == id) {                Some((_, held)) => {                    if at.as_deref().map(instant) > held.as_deref().map(instant) {                        *held = at;                    }                }                None => newest.push((id.to_string(), at)),            }        }    }    for row in health["stale"].as_array().into_iter().flatten() {        if let Some(id) = row["database"].as_str().filter(|id| !newest.iter().any(|(known, _)| known == id)) {            newest.push((id.to_string(), row["newestCopyAt"].as_str().map(str::to_string)));        }    }    let reason = if disk {        format!("no copy on the backup disk in the last {hours} hours")    } else {        "no backup disk is mounted".to_string()    };    let databases: Vec<Value> = newest        .iter()        .map(|(id, at)| {            let failing = stale.contains(&id.as_str());            json!({                "databaseId": id,                "name": Value::Null,                "state": if failing { "failing" } else { "ok" },                "lastError": if failing { Some(reason.clone()) } else { None },                "since": if failing { at.clone() } else { None },                "lastAt": at,            })        })        .collect();    let failing = databases.iter().any(|row| row["state"] == "failing");    let last_at = newest        .iter()        .map(|(_, at)| at.clone())        .collect::<Option<Vec<String>>>()        .and_then(|ats| ats.into_iter().min_by_key(|at| instant(at)));    let state = if databases.is_empty() { "never" } else if failing { "failing" } else { "ok" };    json!({        "state": state,        "lastAt": last_at,        "lastError": if failing { Some(reason.clone()) } else { None },        "nextAt": Value::Null,        "keptBytes": Value::Null,        "since": if failing { last_at.clone() } else { None },        "databases": databases,    })}/// The `backup` table's rows, one per database this Mac serves, from the/// daily copies' health: `state` is `ok`, `stale` (no copy within the health's/// stale window on any backup disk) or `no disk` (no backup disk mounted);/// `last_error` is the reason when it is not ok, else the last check's error/// when that check failed; `last_at` is the newest copy's file time and/// `kept` how many copies the fullest backup disk keeps of it.pub fn backup_rows(health: &Value) -> Vec<(String, Map<String, Value>)> {    let section = backup_section(health);    let disk = health["disk"] == true;    let rows_of = |id: &str| -> Vec<Value> {        health["volumes"]            .as_array()            .into_iter()            .flatten()            .flat_map(|volume| volume["databases"].as_array().into_iter().flatten())            .filter(|row| row["database"].as_str() == Some(id))            .cloned()            .collect()    };    let mut rows = Vec::new();    for database in section["databases"].as_array().into_iter().flatten() {        let Some(id) = database["databaseId"].as_str().map(str::to_string) else { continue };        let own = rows_of(&id);        let kept = own.iter().filter_map(|row| row["kept"].as_u64()).max();        let check_error = own            .iter()            .filter(|row| row["lastCheck"]["ok"] == false)            .find_map(|row| row["lastCheck"]["error"].as_str().map(str::to_string));        let state = if !disk {            "no disk"        } else if database["state"] == "failing" {            "stale"        } else {            "ok"        };        let last_error = if state == "ok" { check_error.map(Value::from).unwrap_or(Value::Null) } else { database["lastError"].clone() };        let mut data = Map::new();        let mut put = |key: &str, value: Value| {            if !value.is_null() {                data.insert(key.into(), value);            }        };        put("state", json!(state));        put("last_error", last_error);        put("last_at", database["lastAt"].clone());        put("kept", json!(kept));        rows.push((id, data));    }    rows}/// An ISO instant as a sortable time; one that does not parse sorts last.fn instant(at: &str) -> i64 {    chrono::DateTime::parse_from_rfc3339(at).map_or(i64::MAX, |at| at.timestamp_millis())}// ── Home's backup notice ────────────────────────────────────────────────/// `read.servingBackup` before anyone answers: no Mac said. The serving Mac/// answers itself (`attach_serving`). Silence stays `no_serving_mac` — a/// device that is not the serving Mac says nothing new, never "not backed up".pub fn serving_backup_page(_client: &ClientController, _args: &Map<String, Value>) -> Result<Value, String> {    Ok(json!({        "deviceId": null,        "deviceName": null,        "backup": null,        "backupAnsweredBy": "no_serving_mac",    }))}/// The answering Mac's own name, off this database's device rows; null when/// the row is not here (yet)./// The backup's one line on `read.servingBackup`'s answer, the same the/// device page and Feedback say (`records::backup`); null while its backup is/// getting through. Written here, beside the read's own controller, so the/// key lives with the answer it belongs to.pub fn say_backup_line(answer: &mut Value, now: chrono::DateTime<chrono::Utc>) {    answer["backupLine"] = serde_json::json!(cotton_core::records::backup::receipt_line(        &answer["backup"],        answer["deviceName"].as_str().unwrap_or_default(),        now,    ));}pub fn name_the_mac(client: &ClientController, answer: &mut Value) {    let Some(device) = answer["deviceId"].as_str().map(str::to_string) else {        return;    };    answer["deviceName"] = json!(mac_name(client, &device));}/// A device's name off the device rows; none when its row is not here.pub fn mac_name(client: &ClientController, device: &str) -> Option<String> {    let listed = client.read_tool("list_devices", &Map::new()).ok()?;    listed["devices"]        .as_array()        .into_iter()        .flatten()        .find(|row| row["deviceId"].as_str() == Some(device))        .and_then(|row| row["name"].as_str())        .map(str::trim)        .filter(|name| !name.is_empty())        .map(str::to_string)}