Cotton code
150 lines · 6.8 KB · RustRaw
//! A Mac's presence — when it was last heard, and the free disk it last said//! — as ONE fact every surface reads (295 rule 8, walker294 rows 26, 42, 114).//!//! Devices said one Mac was "asleep 19 h" off its `sampled_at` while Copies//! said "heard 3 min ago" off the later of that and the last exchange its//! reported state carries; Machines said "yesterday" and another disk figure//! off the serving Mac's file. One row, one reading://!//! - **heard** is the later of the Mac's own last sample (`sampled_at`) and//!   its last exchange (`reported_state.last_exchange_at`) — both are the Mac//!   speaking for itself, and a Mac that exchanged three minutes ago is not//!   asleep whatever its last sample says.//! - **the sample** (its stamp and its disk) is the newest row of the Mac the//!   reader holds: a Mac writes its sample into the household's own database//!   (the one every Mac attaches or serves first), and into the others only//!   while it serves them, so a non-serving Mac's row in any other database//!   is as old as the last time it served. [`Presence::newest`] keeps the//!   newer of two rows whole, so a disk figure always travels with its own//!   stamp.use chrono::{DateTime, Utc};use serde_json::{Map, Value};/// One Mac's presence, read off one `cotton_devices` row or the newest of/// several.#[derive(Debug, Clone, Default, PartialEq)]pub struct Presence {    /// The later of its last sample and its last exchange, as it was spelt.    pub heard_at: Option<String>,    /// When it took the sample `disk_free_gb` and `disk_total_gb` are from.    pub sampled_at: Option<String>,    pub disk_free_gb: Option<f64>,    pub disk_total_gb: Option<f64>,}impl Presence {    /// Read off a row's columns: its sample stamp, its reported state (the    /// JSON object, or the text the column holds) and its disk.    #[must_use]    pub fn of(        sampled_at: Option<&str>,        reported_state: Option<&Value>,        disk_free_gb: Option<f64>,        disk_total_gb: Option<f64>,    ) -> Presence {        let parsed = match reported_state {            Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),            Some(object @ Value::Object(_)) => Some(object.clone()),            _ => None,        };        let exchanged = parsed            .as_ref()            .and_then(super::reported_state::ReportedState::accept)            .and_then(|state| state.last_exchange_at);        let sampled_at = sampled_at.map(str::trim).filter(|at| !at.is_empty()).map(str::to_string);        Presence {            heard_at: later(sampled_at.as_deref(), exchanged.as_deref()),            sampled_at,            disk_free_gb,            disk_total_gb,        }    }    /// Read off one `list_devices` row (camelCase keys). A `heardAt` a reader    /// already put on the row (from the household's newest row) counts too.    #[must_use]    pub fn of_listed(row: &Map<String, Value>) -> Presence {        let number = |key: &str| row.get(key).and_then(Value::as_f64);        let mut presence = Presence::of(            row.get("sampledAt").and_then(Value::as_str),            row.get("reportedState"),            number("diskFreeGb"),            number("diskTotalGb"),        );        presence.heard_at = later(presence.heard_at.as_deref(), row.get("heardAt").and_then(Value::as_str));        presence    }    /// The newer of two readings of one Mac: heard at the later of the two,    /// and the sample (stamp and disk together) of the row sampled later.    #[must_use]    pub fn newest(self, other: Presence) -> Presence {        let heard_at = later(self.heard_at.as_deref(), other.heard_at.as_deref());        let theirs = match (instant(self.sampled_at.as_deref()), instant(other.sampled_at.as_deref())) {            (Some(mine), Some(theirs)) => theirs > mine,            (None, Some(_)) => true,            _ => false,        };        let sample = if theirs { other } else { self };        Presence { heard_at, ..sample }    }    /// Put this reading on a `list_devices` row, so every word said of the    /// row (its state, its last seen, its free disk) is said of it. Answers    /// whether the row changed.    pub fn put_on_listed(&self, row: &mut Map<String, Value>) -> bool {        let merged = Presence::of_listed(row).newest(self.clone());        if merged == Presence::of_listed(row) {            return false;        }        let mut put = |key: &str, value: Value| {            row.insert(key.to_string(), value);        };        put("sampledAt", merged.sampled_at.clone().map_or(Value::Null, Value::from));        put("diskFreeGb", merged.disk_free_gb.map_or(Value::Null, Value::from));        put("diskTotalGb", merged.disk_total_gb.map_or(Value::Null, Value::from));        put("heardAt", merged.heard_at.clone().map_or(Value::Null, Value::from));        true    }}/// The later of two RFC 3339 stamps by instant, never by spelling, as it was/// spelt; an unreadable stamp is no stamp.#[must_use]pub fn later(first: Option<&str>, second: Option<&str>) -> Option<String> {    [first, second]        .into_iter()        .flatten()        .filter_map(|at| instant(Some(at)).map(|when| (when, at)))        .max_by_key(|(when, _)| *when)        .map(|(_, at)| at.trim().to_string())}fn instant(at: Option<&str>) -> Option<DateTime<Utc>> {    DateTime::parse_from_rfc3339(at?.trim()).ok().map(|at| at.with_timezone(&Utc))}#[cfg(test)]mod tests {    use super::*;    use serde_json::json;    /// RULE: a Mac is heard at the later of its own last sample and its last    /// exchange — Devices said one Mac was "asleep 19 h" off a sample while    /// Copies said "heard 3 min ago" off its exchange (walker294 row 114) —    /// and the newer of two rows keeps its disk with its own stamp, so a    /// disk figure is never a stale row's beside a fresh row's time.    #[test]    fn heard_is_the_later_of_sample_and_exchange_and_the_newer_row_keeps_its_disk() {        let state = json!({"last_exchange_at": "2026-10-17T09:57:00Z"}).to_string();        let stale = Presence::of(Some("2026-10-16T14:19:00Z"), Some(&Value::from(state)), Some(25.4), Some(228.0));        assert_eq!(stale.heard_at.as_deref(), Some("2026-10-17T09:57:00Z"));        let fresh = Presence::of(Some("2026-10-17T09:50:00Z"), None, Some(45.0), Some(228.0));        let merged = stale.clone().newest(fresh.clone());        assert_eq!(merged.heard_at.as_deref(), Some("2026-10-17T09:57:00Z"));        assert_eq!((merged.sampled_at.as_deref(), merged.disk_free_gb), (Some("2026-10-17T09:50:00Z"), Some(45.0)));        assert_eq!(fresh.clone().newest(stale), merged, "the newer row wins whichever side it is on");        assert_eq!(later(Some("2026-10-17T09:00:00+05:30"), Some("2026-10-17T04:00:00Z")).as_deref(), Some("2026-10-17T04:00:00Z"), "by instant: 09:00 IST is 03:30 UTC");    }}