Cotton code
289 lines · 11.7 KB · RustRaw
//! What the app says of itself that only the app knows, for the device's//! reported state (`cotton_core::device::reported_state`, phone diagnostics,//! 12 Oct 2026): its build number and commit (the bundle's), how many//! databases its sheet lists against how many the Mac answered, and the//! sentence its open card shows. Said by `diagnostics.say`; read by//! [`super::client::ClientController::device_state`] as each exchange body is//! built. One app per process, so one record.use serde_json::{json, Value};use std::collections::VecDeque;use std::sync::{LazyLock, Mutex};use std::time::Duration;use crate::handle::CottonHandle;use crate::methods::MethodError;#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Said {    pub build: Option<String>,    pub bundle_id: Option<String>,    pub sha: Option<String>,    pub databases_listed: Option<String>,    pub open_problem: Option<String>,    /// The last MetricKit payload's four figures (`DeviceUsage`).    pub usage: Option<cotton_core::device::reported_state::DeviceUsage>,    /// Comms' live Sites pages (`SitesMemory`, SITES 5).    pub sites: Option<cotton_core::device::reported_state::SitesMemory>,    /// Albums' first look (`AlbumsLook`, LOOK-ONLY): counts and timings only.    pub albums: Option<cotton_core::device::reported_state::AlbumsLook>,}static SAID: LazyLock<Mutex<Said>> = LazyLock::new(Default::default);/// `diagnostics.say { build?, sha?, databasesListed?, openProblem?, usage?, sites?, albums? }`/// — each key present replaces what was said (null or empty clears it); a key/// left out stays. Anything else is ignored. `usage` is the typed/// `DeviceUsage` object; one that does not parse clears it.pub fn say(request: &Value) -> Value {    let mut said = SAID.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    let put = |key: &str, slot: &mut Option<String>| {        if let Some(value) = request.get(key) {            *slot = value.as_str().map(str::trim).filter(|text| !text.is_empty()).map(str::to_string);        }    };    put("build", &mut said.build);    put("bundleId", &mut said.bundle_id);    put("sha", &mut said.sha);    put("databasesListed", &mut said.databases_listed);    put("openProblem", &mut said.open_problem);    if let Some(usage) = request.get("usage") {        said.usage = serde_json::from_value(usage.clone()).ok();    }    if let Some(sites) = request.get("sites") {        said.sites = serde_json::from_value(sites.clone()).ok();    }    if let Some(albums) = request.get("albums") {        said.albums = serde_json::from_value(albums.clone()).ok();    }    json!({ "said": true })}/// What has been said.pub fn said() -> Said {    SAID.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()}// ── The Debug group (phone diagnostics part 4, owner 12 Oct 2026) ─────────//// "Add any other debug stuff that helps you find things fast": plain lines at// the end of This phone / This Mac, every one of them also in the report// (`shell::report`). One method answers the whole group, so the app draws one// view it can hide and the report and the screen never disagree./// A read this slow or slower is kept.pub const SLOW_READ: Duration = Duration::from_millis(200);/// How many slow reads are kept, newest first.pub const SLOW_READS_KEPT: usize = 200;/// One `read.*` that took [`SLOW_READ`] or more.#[derive(Debug, Clone, PartialEq, Eq)]pub struct SlowRead {    pub at: String,    pub name: String,    pub ms: u64,    /// SQLite VM steps this thread took answering it (`Driver::thread_steps`).    pub steps: u64,    /// Rows in the answer's largest list; `None` for an answer with none.    pub rows: Option<usize>,}impl SlowRead {    #[must_use]    pub fn line(&self) -> String {        let at = self.at.get(11..19).unwrap_or(&self.at);        let rows = self.rows.map_or_else(String::new, |rows| format!(" · {rows} rows"));        format!("{at}Z · {} · {} ms · {} steps{rows}", self.name, self.ms, self.steps)    }}static SLOW_READS: LazyLock<Mutex<VecDeque<SlowRead>>> = LazyLock::new(Default::default);/// Note one read; kept only when it took [`SLOW_READ`] or more.pub fn read_took(name: &str, took: Duration, steps: u64, answer: &Value) {    if took < SLOW_READ {        return;    }    let read = SlowRead {        at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),        name: name.to_string(),        ms: u64::try_from(took.as_millis()).unwrap_or(u64::MAX),        steps,        rows: rows_in(answer),    };    let mut kept = SLOW_READS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    kept.push_front(read);    kept.truncate(SLOW_READS_KEPT);}/// Every slow read since launch, newest first.pub fn slow_reads() -> Vec<SlowRead> {    SLOW_READS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).iter().cloned().collect()}/// The length of the answer's largest list — the rows a screen drew.fn rows_in(answer: &Value) -> Option<usize> {    match answer {        Value::Array(items) => Some(items.len()),        Value::Object(fields) => fields.values().filter_map(Value::as_array).map(Vec::len).max(),        _ => None,    }}// ── Opens and copies ─────────────────────────────────────────────────────/// The last open of one database: when, and each step with its ms/// (`Replica::opened`).#[derive(Debug, Clone, PartialEq, Eq)]struct Opened {    at: String,    steps: Vec<(&'static str, u64)>,}static OPENS: LazyLock<Mutex<std::collections::BTreeMap<String, Opened>>> = LazyLock::new(Default::default);/// Note one database's open; the newest replaces the last.pub fn opened(database: &str, steps: &[(&'static str, u64)]) {    let at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);    OPENS        .lock()        .unwrap_or_else(|poisoned| poisoned.into_inner())        .insert(database.to_string(), Opened { at, steps: steps.to_vec() });}/// `<db8> · 10:32:01Z · open 12 ms · ladder 0 ms · identity 1 ms …`pub(crate) fn open_lines() -> Vec<String> {    OPENS        .lock()        .unwrap_or_else(|poisoned| poisoned.into_inner())        .iter()        .map(|(database, opened)| {            let steps: Vec<String> = opened.steps.iter().map(|(step, ms)| format!("{step} {ms} ms")).collect();            let total: u64 = opened.steps.iter().map(|(_, ms)| ms).sum();            format!(                "{} · {}Z · {} · total {total} ms",                short(database),                opened.at.get(11..19).unwrap_or(&opened.at),                steps.join(" · ")            )        })        .collect()}fn short(database: &str) -> &str {    database.get(..8).unwrap_or(database)}/// The Copy group: no whole-file copy runs on this device any more (the/// snapshot download went with the serving Mac), so it says the standing/// state, or none, and that none ran since launch.fn copy_lines(standing: Option<String>) -> Vec<String> {    vec![        standing.unwrap_or_else(|| "no copy in progress".to_string()),        "no copy since launch".to_string(),    ]}/// One headed group of plain lines.#[derive(Debug, Clone, PartialEq, Eq)]pub struct DebugSection {    pub heading: &'static str,    pub lines: Vec<String>,}/// Retain the underlying failure on both builds, before the person receives plain words./// Redaction happens before storage or emission, including the host tracing path.pub fn method_failed(log: &super::log_ring::LogRing, events: &crate::events::EventBus, method: &str, raw: &str) {    let text = cotton_core::device::reported_state::redact_line(&format!("{method} failed: {raw}"));    tracing::warn!(message = %text, "a failure was said in plain words");    super::log_ring::push_line(log, events, super::log_ring::LogLevel::Warn, "core", &text);}/// Where a call not used on this device is logged — never `core`, so it is/// never a failure line.const NOT_USED: &str = "not_used";/// A server-bound call made on a database no server serves answered the typed/// `not_served` (`phone::database_calls::not_served`): a state, never a/// failure, so Debug lists it apart (architect's ruling C1, 22 Oct 2026).pub fn not_used(log: &super::log_ring::LogRing, events: &crate::events::EventBus, method: &str) {    super::log_ring::push_line(log, events, super::log_ring::LogLevel::Info, NOT_USED, method);}fn not_used_lines(log: &super::log_ring::LogRing) -> Vec<String> {    let mut methods: Vec<String> = Vec::new();    for line in log.lines().iter().filter(|line| line.source == NOT_USED) {        if !methods.contains(&line.text) {            methods.push(line.text.clone());        }    }    if methods.is_empty() {        methods.push("every call since launch had its server".to_string());    }    methods}fn failure_lines(log: &super::log_ring::LogRing) -> Vec<String> {    let mut lines: Vec<String> = log.lines().iter().rev()        .filter(|line| line.source == "core")        .map(super::log_ring::file_line)        .collect();    if lines.is_empty() {        lines.push("no failure since launch".to_string());    }    lines}/// The Debug group, in the order it is drawn.pub fn debug_sections(handle: &CottonHandle) -> Vec<DebugSection> {    let client = handle.client();    let mut exchanges: Vec<String> = client.exchanges().iter().rev().map(cotton_client::sync::Exchange::line).collect();    if exchanges.is_empty() {        exchanges.push("no exchange since launch".to_string());    }    let mut slow: Vec<String> = slow_reads().iter().map(SlowRead::line).collect();    if slow.is_empty() {        slow.push(format!("no read over {} ms since launch", SLOW_READ.as_millis()));    }    let state = client.device_state();    let standing = state.as_ref().and_then(|state| state.get("copy")).and_then(Value::as_str).map(str::to_string);    let mut opens = open_lines();    if opens.is_empty() {        opens.push("no database opened since launch".to_string());    }    let mut sections = vec![        DebugSection { heading: "Exchanges", lines: exchanges },        DebugSection { heading: "Open", lines: opens },        DebugSection { heading: "Failures", lines: failure_lines(handle.log()) },        DebugSection { heading: "Not used on this device", lines: not_used_lines(handle.log()) },        DebugSection { heading: "Slow reads", lines: slow },        DebugSection { heading: "Copy", lines: copy_lines(standing) },    ];    sections.push(DebugSection { heading: "State", lines: super::report::state_lines(state.as_ref()) });    sections}/// `diagnostics.debug` — `{sections: [{heading, lines}]}`, every line/// redacted the way the report's are.pub fn debug(handle: &CottonHandle) -> Result<Value, MethodError> {    let sections: Vec<Value> = debug_sections(handle)        .into_iter()        .map(|section| {            let lines: Vec<String> =                section.lines.iter().map(|line| cotton_core::device::reported_state::redact_line(line)).collect();            json!({ "heading": section.heading, "lines": lines })        })        .collect();    Ok(json!({ "sections": sections, "removals": super::refused_copies::offers(&handle.client()) }))}#[cfg(test)]#[path = "diagnostics_tests.rs"]mod tests;/// The offered Debug act, scoped to this handle and consumed exactly once.pub fn remove_copy(handle:&CottonHandle,request:&Value)->Result<Value,MethodError> {    let token=request["token"].as_str().ok_or_else(||MethodError::new("bad_request","Choose the removal act offered in Debug."))?;    let kept=super::refused_copies::remove(&handle.client(),token).map_err(|reason|MethodError::new("copy_removal_refused",reason))?;    Ok(json!({"removed":true,"keptAt":kept.to_string_lossy()}))}