Cotton code
229 lines · 10.0 KB · RustRaw
//! The words a `device` row is read in — the sentences the app's//! `DeviceTableSource` said in Swift, answered by the generic read from the//! one copy in `cotton_core::device::words`, so a page draws them off//! `records.list` / `records.get` like every other table's.//!//! The serving order and an approver's name are read against EVERY device of//! the file, so the words are said over `list_devices`' whole answer, not the//! page's rows alone. A time is named in the reader's zone, else the//! workspace's. The reading device marks its own row (`this device`) — no//! shared read knows its reader.use cotton_core::definitions::TableDefinition;use cotton_core::device::words::{serving_order, table_words, Clock, DeviceFacts};use serde_json::{Map, Value};use super::{sql_err, Stored};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{workspace_timezone, Valid};use crate::mcp::handlers::devices::list_devices;use cotton_store::storage_rules;use rusqlite::types::Value as SqlValue;use std::collections::HashSet;/// One approval per device key, using the same live/newest order as every/// device operation. Filter before paging so the count and list agree.pub(super) fn effective_approvals(ctx: &Ctx<'_>) -> Valid<HashSet<String>> {    let rows = ctx        .read        .driver()        .all(            &format!(                "SELECT id, device_id FROM cotton_devices WHERE workspace_id = ? {}",                crate::devices::KEY_ORDER            ),            &[SqlValue::Text(ctx.workspace_id.to_string())],        )        .map_err(sql_err)?;    let mut seen = HashSet::new();    Ok(rows        .iter()        .filter_map(|row| {            let key = row.text("device_id")?;            if seen.insert(key) {                row.text("id").map(str::to_string)            } else {                None            }        })        .collect())}/// The storage row behind the public device key, never an approval-id alias.pub(super) fn approval_for(ctx: &Ctx<'_>, key: &str) -> Valid<Option<String>> {    Ok(ctx        .read        .driver()        .get(            &format!(                "SELECT id FROM cotton_devices WHERE workspace_id = ? AND device_id = ? {} LIMIT 1",                crate::devices::KEY_ORDER            ),            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(key.to_string()),            ],        )        .map_err(sql_err)?        .and_then(|row| row.text("id").map(str::to_string)))}/// Answer the words of every `device` record read.pub(super) fn device_words(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    records: &mut [Stored],    reader_zone: Option<&str>,) -> Valid<()> {    if !definition.has_engine() || definition.id != "device" || records.is_empty() {        return Ok(());    }    let zone = match reader_zone {        Some(zone) => zone.to_string(),        None => workspace_timezone(ctx)?,    };    let clock = Clock::in_zone(ctx.now.timestamp_millis(), &zone);    let listed = list_devices(ctx, &Map::new())?;    let approvals = effective_approvals(ctx)?;    let rows: Vec<&Map<String, Value>> = listed["devices"]        .as_array()        .into_iter()        .flatten()        .filter_map(Value::as_object)        .filter(|row| {            row.get("id")                .and_then(Value::as_str)                .is_some_and(|id| approvals.contains(id))        })        .collect();    let all: Vec<DeviceFacts> = rows        .iter()        .map(|row| DeviceFacts::from_listed(row))        .collect();    let order = serving_order(&all);    for record in records.iter_mut() {        let Some(index) = rows.iter().position(|row| {            row.get("deviceId").and_then(Value::as_str) == Some(record.id.as_str())        }) else {            continue;        };        record            .data            .extend(table_words(&all[index], &all, &order, &clock));        record.data.extend(live_facts(rows[index], &record.data));        // Holds are facts, not the sentence older workers stored here.        record.data.remove("ai_holds");        record.data.insert("held_until".into(), Value::Null);        record.data.insert("hold_reason".into(), Value::Null);        if let Some(hold) = cotton_core::device::ai_hold::AiHold::from_value(&rows[index]["aiHolds"]) {            record.data.extend(hold.columns());        }        let settings = cotton_core::device::disk::device_disk_rows(ctx.read.driver(), &record.id).map_err(sql_err)?;        if let Some(total_gb) = cotton_core::device::disk::device_disk_total_gb(&settings) {            let effective = cotton_core::device::disk::read_device_keep_free_bytes(&settings, (total_gb * 1_073_741_824.0) as u64);            record.data.insert("keep_free_bytes".into(), Value::from(effective));            // The rule the reserve comes from, said beside its size, so a            // floor is read as a rule and never as a fault.            let total = total_gb * 1_073_741_824.0;            record.data.insert("keep_free_percent".into(), Value::from((effective as f64 * 100.0 / total).round() as i64));            record.data.insert("keep_free_size".into(), Value::from(cotton_core::records::page::bytes_words(effective as f64)));        }        // Without capacity, retain the explicit stored setting. The percentage        // and effective size need telemetry; the person's saved intent does not.        if let Some(permission) = rows[index].get("pushAuthorization").and_then(Value::as_str) {            let permission = cotton_core::device::words::notifications_permission(permission);            record.data.insert("notifications_permission".into(), Value::from(permission));            record.data.insert("notifications".into(), Value::from(permission));        }        if all[index].platform.as_deref() == Some("mac")        {            record.data.insert("keeps_answered_by".into(), Value::from("mac"));            if let Some(key) = all[index].device_id.as_deref() {                let keeps = storage_rules::mac_keeps(ctx.read.driver(), ctx.workspace_id, key)                    .map_err(sql_err)?;                // Explicit synced intent wins even while this Mac is offline.                // Only legacy NULL rows read their existing per-tool policy.                if record.data.get("keep_bytes").is_none_or(Value::is_null) {                    record.data.insert("keep_bytes".into(), match keeps {                        storage_rules::MacKeeps::PerTool => Value::Null,                        choice => Value::from(choice.as_str()),                    });                }                if record.data.get("serving").and_then(Value::as_bool) == Some(true) {                    record.data.insert(                        "keep_bytes_note".to_string(),                        Value::from("While serving, this Mac keeps everything."),                    );                }            }        }        // WHEN THIS DEVICE WAS LAST RE-KEYED: the replacement fact its key        // wrote over its predecessor's row when the approval retired it (the        // hardware twin rule) — read, never a column of its own to fall out        // of step with the fact.        let rekeyed = ctx.read.driver().get(            "SELECT MAX(revoked_at) AS at FROM cotton_revocations WHERE subject_table = 'cotton_devices' AND replaced_by = ?",            &[SqlValue::Text(record.id.clone())],        ).map_err(sql_err)?.and_then(|row| row.text("at").map(str::to_string));        record.data.insert("rekeyed_at".into(), rekeyed.map_or(Value::Null, Value::from));        // The stored column is `load1`; the definition's key is `load_1`.        if let Some(load) = rows[index].get("load1").filter(|load| !load.is_null()) {            record.data.insert("load_1".to_string(), load.clone());        }    }    Ok(())}/// The live Device page facts are a projection of the same `list_devices`/// row the generic table reader already has. Keep it here, rather than adding/// a second database read in FFI: list/get stay ordinary synced reads.fn live_facts(row: &Map<String, Value>, words: &Map<String, Value>) -> Map<String, Value> {    let mut facts = Map::new();    if let Some(place) = words.get("serving_place").filter(|value| !value.is_null()) {        facts.insert("serving_order".to_string(), place.clone());    }    let Some(state) = row.get("reportedState").and_then(Value::as_object) else {        return facts;    };    for key in ["build", "last_answer", "unreachable_since"] {        if let Some(value) = state.get(key).filter(|value| !value.is_null()) {            facts.insert(key.to_string(), value.clone());        }    }    // The table definition presents these numeric / structured values as    // text, so preserve their public value while using the definition's    // declared scalar shape.    for key in ["schema"] {        if let Some(value) = state.get(key).filter(|value| !value.is_null()) {            facts.insert(key.to_string(), Value::from(value.to_string()));        }    }    facts}#[cfg(test)]mod tests {    use super::*;    use serde_json::json;    /// RULE: Device live columns come from the reported device state already    /// folded into its row; an empty or unrelated state cannot manufacture a    /// live answer.    #[test]    fn projects_reported_state_and_the_serving_words() {        let row = json!({            "reportedState": {                "build": "254", "schema": 135, "last_answer": "ok",                "unsent": 3,                "unreachable_since": "2026-10-13T07:16:00Z"            }        });        let words = json!({"serving_place":"1st — asked to serve first"});        let facts = live_facts(row.as_object().unwrap(), words.as_object().unwrap());        assert_eq!(facts["build"], "254");        assert_eq!(facts["schema"], "135");        assert!(!facts.contains_key("unsent"), "a device's sync state is its copy row's, not a reported count");        assert_eq!(facts["serving_order"], "1st — asked to serve first");        assert_eq!(facts["unreachable_since"], "2026-10-13T07:16:00Z");    }}