Cotton code
145 lines · 7.0 KB · RustRaw
//! EVERY MAC'S PRESENCE, from the one row each Mac writes about itself//! (295 rule 8, walker294 rows 26, 42 and 114).//!//! A Mac writes its sample into the household's own database — the file a//! serving Mac serves first and a client Mac attaches (`SessionHostShell:://! mirror`) — and into the others only while it serves them; its reported//! state is written where its exchanges are signed, the same database. So a//! Mac that serves nothing has a fresh row in Personal and a row as old as//! its last serve in every other database. Devices, Machines and Copies each//! read the device rows of the database they show: Machines said every Mac//! read "yesterday" with another free disk than Devices, and Copies said the//! mini was heard 3 min ago while Devices said "asleep 19 h".//!//! [`household`] is the one reader: each Mac's newest reading in the//! household's own database, and every surface takes the newer of it and//! its own row ([`cotton_core::device::presence::Presence::newest`]), so the//! three say the same last-heard and free-disk figures for the same Mac.use std::collections::BTreeMap;use cotton_core::device::presence::Presence;use rusqlite::types::Value as Sql;use serde_json::{Map, Value};use crate::shell::client::ClientController;/// Each device's newest reading in the household's own database, by its/// credential id. Empty when that file cannot be read now — every surface/// then says its own row, never nothing.pub(crate) fn household(client: &ClientController) -> BTreeMap<String, Presence> {    // THE HOUSEHOLD'S OWN FILE whichever database this call names: the    // device's own (`None`).    let Ok(_own) = client.name_database(None) else { return BTreeMap::new() };    client        .with_file(|file| {            let rows = file                .driver                .all(                    "SELECT device_id, sampled_at, reported_state, disk_free_gb, disk_total_gb \                       FROM cotton_devices WHERE workspace_id = ? AND revoked_at IS NULL",                    &[Sql::Text(file.workspace_id.to_string())],                )                .map_err(|error| error.to_string())?;            let mut found: BTreeMap<String, Presence> = BTreeMap::new();            for row in &rows {                let Some(id) = row.text("device_id").filter(|id| !id.is_empty()) else { continue };                let state = row.text("reported_state").map(Value::from);                let reading = Presence::of(                    row.text("sampled_at"),                    state.as_ref(),                    row.real("disk_free_gb"),                    row.real("disk_total_gb"),                );                let merged = match found.remove(id) {                    Some(held) => held.newest(reading),                    None => reading,                };                found.insert(id.to_string(), merged);            }            Ok(found)        })        .unwrap_or_default()}/// Put each device's household reading on its `list_devices` row, newer/// wins; answers the ids whose rows changed.pub(crate) fn put_on_listed(    presence: &BTreeMap<String, Presence>,    rows: &mut [Value],) -> Vec<String> {    let mut changed = Vec::new();    for row in rows.iter_mut().filter_map(Value::as_object_mut) {        let Some(id) = row.get("deviceId").and_then(Value::as_str).map(str::to_string) else { continue };        if presence.get(&id).is_some_and(|reading| reading.put_on_listed(row)) {            changed.push(id);        }    }    changed}/// The `device` table's records as the household reads them: a record whose/// own row is older than the household's reading of that Mac has its words/// said again over the newer reading — its state, last seen and free disk —/// from the same core that said them (`cotton_core::device::words`)./// Nothing is read again unless some record is older.pub(crate) fn on_device_records(client: &ClientController, answer: &mut Value) {    let presence = household(client);    if presence.is_empty() {        return;    }    let mut records: Vec<&mut Map<String, Value>> = match answer.get_mut("records") {        Some(Value::Array(records)) => records.iter_mut().filter_map(Value::as_object_mut).collect(),        _ => answer.as_object_mut().filter(|record| record.contains_key("data")).into_iter().collect(),    };    let older = |record: &Map<String, Value>| {        let id = record.get("id").and_then(Value::as_str).unwrap_or_default();        let data = record.get("data").and_then(Value::as_object);        presence.get(id).is_some_and(|reading| {            let own = Presence {                heard_at: data.and_then(|data| data.get("last_seen_at")).and_then(Value::as_str).map(str::to_string),                sampled_at: None,                disk_free_gb: data.and_then(|data| data.get("disk_free_gb")).and_then(Value::as_f64),                disk_total_gb: data.and_then(|data| data.get("disk_total_gb")).and_then(Value::as_f64),            };            cotton_core::device::presence::later(own.heard_at.as_deref(), reading.heard_at.as_deref()) != own.heard_at                || (reading.disk_free_gb.is_some() && reading.disk_free_gb != own.disk_free_gb)        })    };    if !records.iter().any(|record| older(record)) {        return;    }    let Ok(listed) = client.read_tool("list_devices", &Map::new()) else { return };    let mut rows = listed.get("devices").and_then(Value::as_array).cloned().unwrap_or_default();    let changed = put_on_listed(&presence, &mut rows);    if changed.is_empty() {        return;    }    use cotton_core::device::words::{serving_order, table_words, Clock, DeviceFacts};    let facts: Vec<DeviceFacts> = rows.iter().filter_map(Value::as_object).map(DeviceFacts::from_listed).collect();    let order = serving_order(&facts);    let clock = Clock::in_zone(client.clock().now().timestamp_millis(), client.time_zone().unwrap_or("UTC"));    for record in records.iter_mut() {        let id = record.get("id").and_then(Value::as_str).unwrap_or_default().to_string();        if !changed.contains(&id) {            continue;        }        let Some(own) = facts.iter().find(|device| device.device_id.as_deref() == Some(id.as_str())) else { continue };        let words = table_words(own, &facts, &order, &clock);        let Some(data) = record.get_mut("data").and_then(Value::as_object_mut) else { continue };        // The reading device's own row keeps the word it says of itself.        let reader = data.get("status").and_then(Value::as_str) == Some(cotton_core::device::words::THIS_DEVICE);        for key in ["last_seen_at", "load", "state"] {            if key == "state" && reader {                continue;            }            data.insert(key.to_string(), words.get(key).cloned().unwrap_or(Value::Null));        }        data.insert("disk_free_gb".into(), own.disk_free_gb.map_or(Value::Null, Value::from));        data.insert("disk_total_gb".into(), own.disk_total_gb.map_or(Value::Null, Value::from));    }}#[cfg(test)]#[path = "presence_tests.rs"]mod tests;