//! The words a person reads of a device — one copy, said by every read of a //! device row: the generic read of the `device` table //! (`cotton_tools::mcp::handlers::tables`) and the phone's `read.devices`. //! //! Each word is the app's sentence ported line for line from the Swift that //! said it (`DeviceRowFacts.swift`, `DeviceStatus.swift`, `DeviceWords.swift`, //! `DeviceTableSource.swift`), cited above it. **Nothing here invents a //! fact**: every word is built from a column the file holds, and a fact the //! row does not carry is a part of the sentence that is not said. //! //! Two facts no file read can know are the READER's: which row is the device //! asking, and what it calls itself ("this phone", "this Mac"). A shared read //! says every row as another device's; the reading device marks its own //! ([`this_device`]). use chrono::{DateTime, Datelike, TimeZone, Utc}; use chrono_tz::Tz; use serde_json::{Map, Value}; /// A device row's facts, as `list_devices` answers them (camelCase keys). #[derive(Debug, Clone, Default, PartialEq)] pub struct DeviceFacts { pub device_id: Option, pub name: Option, pub platform: Option, pub approved_at: Option, pub approved_by: Option, pub revoked_at: Option, pub revoked_reason: Option, pub serving_rank: Option, pub sampled_at: Option, /// A contact newer than its sample — its last exchange, or the newest /// row of it the reader holds ([`super::presence`]). The device is heard /// at the later of this and `sampled_at` ([`DeviceFacts::heard_at`]). pub heard_at: Option, pub host_version: Option, pub publishes_relay_identity: bool, pub mem_committed_gb: Option, pub mem_budget_gb: Option, pub disk_free_gb: Option, pub disk_total_gb: Option, pub load1: Option, pub cpu_count: Option, pub sessions_running: Option, pub sessions_cap: Option, /// The schema this Mac's own file is at, as it last said. pub schema_version: Option, /// The moment this Mac's copy was last level with the Mac that serves. pub copy_as_of: Option, pub os_version: Option, pub repositories: Option, } impl DeviceFacts { /// Read off one `list_devices` row. A blank text is no text, as the /// app's `JSONValue.text` reads one. pub fn from_listed(row: &Map) -> Self { let text = |key: &str| { row.get(key) .and_then(Value::as_str) .map(str::trim) .filter(|words| !words.is_empty()) .map(str::to_string) }; let number = |key: &str| row.get(key).and_then(Value::as_f64); DeviceFacts { repositories: row.get("reportedState") .and_then(super::reported_state::ReportedState::accept) .and_then(|state| state.repositories), device_id: row .get("deviceId") .and_then(Value::as_str) .map(str::to_string), name: text("name"), platform: text("platform"), approved_at: text("approvedAt"), approved_by: text("approvedBy"), revoked_at: text("revokedAt"), revoked_reason: text("revokedReason"), serving_rank: row .get("servingRank") .and_then(Value::as_f64) .map(|rank| rank as i64), sampled_at: text("sampledAt"), heard_at: super::presence::Presence::of_listed(row).heard_at, host_version: text("hostVersion"), publishes_relay_identity: row.get("publishesRelayIdentity").and_then(Value::as_bool) == Some(true), mem_committed_gb: number("memCommittedGb"), mem_budget_gb: number("memBudgetGb"), disk_free_gb: number("diskFreeGb"), disk_total_gb: number("diskTotalGb"), load1: number("load1"), cpu_count: number("cpuCount"), sessions_running: number("sessionsRunning"), sessions_cap: number("sessionsCap"), schema_version: row.get("schemaVersion").and_then(Value::as_i64), copy_as_of: text("copyAsOf"), os_version: text("osVersion"), } } fn removed(&self) -> bool { self.revoked_at.is_some() } /// When the device was last heard: the later of its own last sample and /// any newer contact — one fact Devices, Machines and Copies all say /// (295 rule 8). #[must_use] pub fn heard_at(&self) -> Option { super::presence::later(self.sampled_at.as_deref(), self.heard_at.as_deref()) } } /// The `notifications_permission` choice for what the system last told a /// device about Cotton's notifications (`cotton_devices.push_authorization`): /// granted, denied or undetermined; another word passes as it is. pub fn notifications_permission(stored: &str) -> &str { match stored { "not_determined" => "undetermined", "authorized" | "provisional" | "ephemeral" => "granted", other => other, } } /// The `notify_system` choice on this device's page: `declined` when the /// system declined Cotton's notifications, else `on` — the five switches are /// the person's while the system lets them ring (walker292: 'notifications 5 /// of 5 on' on a phone that declined them at first launch). pub fn notify_system(stored: Option<&str>) -> &'static str { if stored == Some("denied") { "declined" } else { "on" } } /// Running and capacity come from the same engine reading. Missing numbers /// remain unknown instead of claiming idle capacity. pub fn sessions_line(running: Option, capacity: Option) -> Option { let (running, capacity) = (running?, capacity?); if !running.is_finite() || !capacity.is_finite() || running < 0.0 || capacity < 0.0 || running.fract() != 0.0 || capacity.fract() != 0.0 { return None; } Some(format!("{running:.0} of {capacity:.0}")) } /// The minute the words are said at, and the zone a day is named in. #[derive(Debug, Clone, Copy)] pub struct Clock { pub now_ms: i64, pub zone: Tz, } impl Clock { /// A clock in the named IANA zone; a zone no table names reads as UTC. pub fn in_zone(now_ms: i64, zone: &str) -> Self { Clock { now_ms, zone: zone.parse().unwrap_or(chrono_tz::UTC), } } } /// The `status` a row is grouped by: `approved`, or `revoked` / `erased` once /// removed (DeviceTableSource.swift:266). The reading device says `this /// device` of its own row ([`this_device`]); a pairing still waiting is the /// serving Mac's, never a row of the file. pub const APPROVED: &str = "approved"; pub const REVOKED: &str = "revoked"; pub const ERASED: &str = "erased"; pub const THIS_DEVICE: &str = "this device"; /// "iPhone", "Android", "Mac" — DeviceWords.swift `platform`. pub fn kind(platform: Option<&str>) -> Option<&'static str> { match platform { Some("ios") => Some("iPhone"), Some("android") => Some("Android"), Some("mac") => Some("Mac"), Some("linux") => Some("Linux"), _ => None, } } /// Whether the row runs the server — it says it is a Mac, or has reported /// in (DeviceTableSource.swift:290; a Mac that started its own workspace was /// filed `ios`). `yes`, the `machine` column's one value, or nothing. pub fn machine(device: &DeviceFacts) -> Option<&'static str> { let runs = device.platform.as_deref() == Some("mac") || device.sampled_at.is_some() || device.host_version.is_some(); runs.then_some("yes") } /// The group a row stands in, said by a read that does not know its reader. pub fn status(device: &DeviceFacts) -> &'static str { match (device.removed(), device.revoked_reason.as_deref()) { (true, Some(ERASED)) => ERASED, (true, _) => REVOKED, (false, _) => APPROVED, } } /// Why a Mac could not hold the line for this database, or `None` when it /// could (DeviceRowFacts.swift:83 `cannotServe`). pub fn cannot_serve(device: &DeviceFacts) -> Option<&'static str> { if device.sampled_at.is_none() && device.host_version.is_none() { return Some("This machine has never run the server, so nothing can be placed on it."); } if !device.publishes_relay_identity { return Some("This Mac has no identity on the relay yet, so it cannot be reached by name."); } None } /// The Macs that could serve, in the order they would be asked: serving rank /// ascending, then name, the unplaced last (DeviceRowFacts.swift:32). pub fn serving_order(devices: &[DeviceFacts]) -> Vec { let mut placed: Vec<(&str, &str, Option)> = devices .iter() .filter(|device| !device.removed() && cannot_serve(device).is_none()) .filter_map(|device| { let id = device.device_id.as_deref()?; Some(( id, device.name.as_deref().unwrap_or(id), device.serving_rank, )) }) .collect(); placed.sort_by(|left, right| match (left.2, right.2) { (Some(a), Some(b)) if a != b => a.cmp(&b), (Some(_), None) => std::cmp::Ordering::Less, (None, Some(_)) => std::cmp::Ordering::Greater, _ => (left.1, left.0).cmp(&(right.1, right.0)), }); placed .into_iter() .map(|(id, _, _)| id.to_string()) .collect() } /// "1st", "2nd", "3rd", "11th" (DeviceRowFacts.swift:52). pub fn ordinal(place: usize) -> String { let tens = place % 100; if (11..=13).contains(&tens) { return format!("{place}th"); } match place % 10 { 1 => format!("{place}st"), 2 => format!("{place}nd"), 3 => format!("{place}rd"), _ => format!("{place}th"), } } /// Where a Mac stands in the serving order, or why it cannot be placed; /// nothing for a removed row (DeviceRowFacts.swift:66). pub fn serving_place(device: &DeviceFacts, order: &[String]) -> Option { if device.removed() { return None; } if let Some(why) = cannot_serve(device) { return Some(why.to_string()); } let index = order .iter() .position(|id| Some(id.as_str()) == device.device_id.as_deref())?; Some(if index == 0 { "1st — asked to serve first".to_string() } else { format!("{} — in line", ordinal(index + 1)) }) } /// Free disk space only; missing measurements remain unknown. pub fn load_line(device: &DeviceFacts) -> Option { let free = device.disk_free_gb?; let mut remainder = Vec::new(); if let Some(total) = device.disk_total_gb { remainder.push(format!("of {}", one_decimal(total))); } let first = format!("{} GB free", one_decimal(free)); Some(if remainder.is_empty() { first } else { format!("{first}\n{}", remainder.join(" \u{00B7} ")) }) } /// A number with one decimal and no trailing `.0` (DeviceRowFacts.swift:137). pub fn one_decimal(value: f64) -> String { let rounded = (value * 10.0).round() / 10.0; if rounded == rounded.round() { format!("{}", rounded as i64) } else { format!("{rounded:.1}") } } /// Who approved a device, by name: "the server" for none (or the server's /// own `self`), "the recovery kit" for the row a restore wrote, another row's /// name, else "another device" /// (DeviceWords.swift `actor`). pub fn approver(approved_by: Option<&str>, devices: &[DeviceFacts]) -> String { match approved_by { None | Some("") | Some("self") => "the server".to_string(), Some("recovery-kit") => "the recovery kit".to_string(), Some(id) => match devices .iter() .find(|device| device.device_id.as_deref() == Some(id)) { Some(named) => named.name.clone().unwrap_or_default(), None => "another device".to_string(), }, } } /// How long ago a reachable answer still counts: a registry stamp within two /// minutes, a Mac's own reading within twenty (DeviceStatus.swift). const REACHABLE_WITHIN_MS: i64 = 120 * 1000; const REPORTED_WITHIN_MS: i64 = 20 * 60 * 1000; /// The state word, with its place in the serving order where the state /// carries one (DeviceStatus.swift `state` + `pill`, /// DeviceRowFacts.swift:100 `stateLine`). `last_seen_at` is a registry's /// stamp, which the file never holds; `reader` is the reading device's own /// word for itself, said only when this row is the reader. pub fn state_line( device: &DeviceFacts, last_seen_at: Option<&str>, reader: Option<&str>, place: Option, clock: &Clock, ) -> String { if device.removed() { return "removed".to_string(); } if let Some(reader) = reader { return reader.to_string(); } let heard = match ( last_seen_at.and_then(parse), device.heard_at().as_deref().and_then(parse), ) { (Some(at), _) => Some((at, REACHABLE_WITHIN_MS, true)), (None, Some(at)) => Some((at, REPORTED_WITHIN_MS, false)), (None, None) => None, }; let Some((at, within, registry)) = heard else { return match device.approved_at.as_deref().and_then(parse) { Some(on) => format!("joined {}", short_date(on, clock)), None => "not seen yet".to_string(), }; }; let reachable = clock.now_ms - at.timestamp_millis() <= within; if device.platform.as_deref() != Some("mac") { return format!("synced {}", synced_label(at, clock)); } let suffix = |word: String| match place { Some(place) if place > 0 => format!("{word} \u{00B7} {} in line", ordinal(place)), _ => word, }; if !reachable { return suffix(format!("asleep {}", age(at, clock))); } // The app never says `serving` of a row (`DeviceTableSource` reads no // serving fact into the state), so a reachable Mac heard by its own // reading is awake and one the registry stamped is serving. if registry { "serving".to_string() } else { "awake".to_string() } } /// "0m", "5m", "3h", "2d", then the short date (DeviceStatus.swift `age`, /// DateFormats.swift `RecordAge.of`). fn age(at: DateTime, clock: &Clock) -> String { let minutes = (clock.now_ms - at.timestamp_millis()).div_euclid(60_000); let hours = minutes / 60; let days = hours / 24; if minutes < 1 { "0m".to_string() } else if minutes < 60 { format!("{minutes}m") } else if hours < 24 { format!("{hours}h") } else if days < 7 { format!("{days}d") } else { short_date(at, clock) } } /// The clock today, "Yesterday", else the weekday date /// (DeviceStatus.swift `syncedLabel`, DateFormats.swift `recent`). fn synced_label(at: DateTime, clock: &Clock) -> String { let local = at.with_timezone(&clock.zone); let today = clock .zone .timestamp_millis_opt(clock.now_ms) .single() .map(|now| now.date_naive()); let Some(today) = today else { return local.format("%a %-d %b").to_string(); }; if local.date_naive() == today { return local.format("%-I:%M %p").to_string().to_lowercase(); } if today.pred_opt() == Some(local.date_naive()) { return "Yesterday".to_string(); } if local.year() == today.year() { local.format("%a %-d %b").to_string() } else { local.format("%a %-d %b %Y").to_string() } } /// "5 Oct", or "5 Oct 2025" in another year (DateFormats.swift `shortDate`). fn short_date(at: DateTime, clock: &Clock) -> String { let local = at.with_timezone(&clock.zone); let this_year = clock .zone .timestamp_millis_opt(clock.now_ms) .single() .map(|now| now.year()); if this_year == Some(local.year()) { local.format("%-d %b").to_string() } else { local.format("%-d %b %Y").to_string() } } fn parse(at: &str) -> Option> { DateTime::parse_from_rfc3339(at) .ok() .map(|at| at.with_timezone(&Utc)) } /// Mark the reading device's own row: its status is `this device` and its /// state the word it calls itself ("this phone", "this Mac" — /// HostNoun.swift `lowerCase`). Only the reading device can say it. pub fn this_device(data: &mut Map, reader: &str) { if data.get("status").and_then(Value::as_str) == Some(APPROVED) { data.insert("status".into(), Value::from(THIS_DEVICE)); data.insert("state".into(), Value::from(reader)); } } /// The words `read.devices` carries on each row: `serving` and `role` /// ("Serves this database" for the device the file's newest serving fact /// names, "Keeps a copy" for every other device still admitted), `health` /// ("Fine" or "Busy", only where the device has reported) and `diskLine` /// ("60 GB free of 926 GB"). pub fn read_devices_words(device: &DeviceFacts, serving: Option<&str>) -> Map { let serves = serving.is_some() && device.device_id.as_deref() == serving; let admitted = !device.removed(); let role = match (admitted, serves) { (false, _) => Value::Null, (true, true) => Value::from("Serves this database"), (true, false) => Value::from("Keeps a copy"), }; // Busy is more work than the machine has room for: memory promised past // its budget, or more runnable work than it has processors. let over = |held: Option, room: Option| matches!((held, room), (Some(held), Some(room)) if held > room); let health = if device.sampled_at.is_none() { Value::Null } else if over(device.mem_committed_gb, device.mem_budget_gb) || over(device.load1, device.cpu_count) { Value::from("Busy") } else { Value::from("Fine") }; let disk_line = match (device.disk_free_gb, device.disk_total_gb) { (Some(free), Some(total)) => { Value::from(format!("{} GB free of {} GB", free.round(), total.round())) } _ => Value::Null, }; let mut words = Map::new(); words.insert("serving".to_string(), Value::Bool(serves && admitted)); words.insert("role".to_string(), role); words.insert("health".to_string(), health); words.insert("diskLine".to_string(), disk_line); words } /// The serving Mac's Claude API spend as its row says it — "Claude API today · /// $1.40 · describe 0.60, sweep 0.50" — off `ai_spend`'s `{totalUsd, byWork}`, /// largest first. `None` when the Mac has said nothing. pub fn ai_spend_line(spend: &Value) -> Option { let total = spend.get("totalUsd").and_then(Value::as_f64)?; let mut line = format!("Claude API today · ${total:.2}"); let mut by_work: Vec<(&String, f64)> = spend .get("byWork") .and_then(Value::as_object) .map(|works| { works .iter() .filter_map(|(work, usd)| usd.as_f64().map(|usd| (work, usd))) .collect() }) .unwrap_or_default(); by_work.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(b.0))); if !by_work.is_empty() { let parts: Vec = by_work .iter() .map(|(work, usd)| format!("{work} {usd:.2}")) .collect(); line.push_str(" · "); line.push_str(&parts.join(", ")); } Some(line) } /// The words for writes a device holds until it has the Mac's time: "1 /// waiting for the Mac's time", or `None` when it holds none. pub fn waiting_for_the_macs_time(held: u64) -> Option { (held > 0).then(|| format!("{held} waiting for the Mac's time")) } /// What a device said of itself with its last exchange /// (`cotton_devices.reported_state`), as plain lines for its row on the Mac: /// /// last answer: ok · 4:02 pm · unsent 0 /// build 254 · c76d108 · schema 135 /// databases 5 / 6 /// open: /// copy: copying · 400 MB to go /// /// `None` when the device has said nothing. pub fn reported_state_lines(state: &Value, clock: &Clock) -> Option { let state = super::reported_state::ReportedState::accept(state)?; let mut lines = Vec::new(); let mut answer = vec![format!( "last answer: {}", state.last_answer.as_deref().unwrap_or("none yet") )]; if let Some(at) = state.last_exchange_at.as_deref().and_then(parse) { answer.push(synced_label(at, clock)); } if let Some(unsent) = state.unsent { answer.push(format!("unsent {unsent}")); } if let Some(line) = state.held.and_then(waiting_for_the_macs_time) { answer.push(line); } lines.push(answer.join(" · ")); let build: Vec = [ state.build.map(|build| format!("build {build}")), state.sha, state.schema.map(|schema| format!("schema {schema}")), ] .into_iter() .flatten() .collect(); if !build.is_empty() { lines.push(build.join(" · ")); } if let Some(listed) = state.databases_listed { lines.push(format!("databases {listed}")); } if let Some(problem) = state.open_problem { lines.push(format!("open: {problem}")); } if let Some(copy) = state.copy { lines.push(format!("copy: {copy}")); } Some(lines.join("\n")) } /// The device's usage columns off what it said of itself /// ([`super::reported_state::DeviceUsage`]): `smooth_scrolling` (percent of /// scrolling time without a hitch), `hangs_today`, `cpu_time_today` /// (seconds) and `peak_memory` (bytes). Numbers only; the definition's /// columns name and format them. A figure the payload did not carry is null. #[must_use] pub fn usage_columns(state: Option<&Value>) -> Map { let usage = state.and_then(super::reported_state::ReportedState::accept).and_then(|state| state.usage); let usage = usage.as_ref(); let mut columns = Map::new(); let smooth = usage.and_then(|usage| usage.hitch_us_per_s).map(|hitch| { // 100 % less the hitch share, to one decimal: 8 ms/s hitching reads 99.2. let tenths = 1000_u64.saturating_sub((hitch + 500) / 1000); Value::from(tenths as f64 / 10.0) }); columns.insert("smooth_scrolling".to_string(), smooth.unwrap_or(Value::Null)); columns.insert("hangs_today".to_string(), usage.and_then(|usage| usage.hangs).map_or(Value::Null, Value::from)); columns.insert( "cpu_time_today".to_string(), usage.and_then(|usage| usage.cpu_ms).map_or(Value::Null, |ms| Value::from((ms + 500) / 1000)), ); columns.insert( "peak_memory".to_string(), usage.and_then(|usage| usage.peak_memory_bytes).map_or(Value::Null, Value::from), ); columns } /// A copy within this of the Mac that serves is level with it: each Mac says /// where its copy stands with its five-minute sample, and a sync runs every /// minute, so two level Macs can read this far apart. const LEVEL_WITHIN_MINUTES: i64 = 10; /// What "Serve from this Mac" says of one device, for the owner /// (architect's ruling 12 Oct 2026): `None` for a device the act is never /// about — a phone, a removed device, the Mac that already serves. Otherwise /// `offered`, with `whyNot` when it is not, and `behind` when this Mac's copy /// is not level with the serving Mac's — the sheet's first line. /// /// NOT OFFERED on a Mac whose copy is on an older schema than the Mac that /// serves, or that has never said which schema it holds: it could not serve /// the file as it stands. A Mac that is merely behind IS offered — choosing /// it is how an outage ends — and the sheet says by how much. pub fn serve_from( device: &DeviceFacts, serving: Option<&DeviceFacts>, ) -> Option> { let is_serving = serving.is_some_and(|serving| serving.device_id == device.device_id); if device.removed() || is_serving || machine(device).is_none() { return None; } let name = device.name.as_deref().unwrap_or("This Mac"); let serving_name = serving .and_then(|serving| serving.name.as_deref()) .unwrap_or("the Mac that serves"); let why_not = if !device.publishes_relay_identity { Some(format!("{name} has not yet said which key it reaches the relay with. Open Cotton on it once, then try again.")) } else { match (device.schema_version, serving.and_then(|serving| serving.schema_version)) { (None, _) => Some(format!( "{name} has not said which version of the database it holds. Update Cotton on it, then try again." )), (Some(own), Some(served)) if own < served => Some(format!( "{name}'s copy is on an older version of the database than {serving_name} serves. Update Cotton on {name} first." )), _ => None, } }.or_else(|| match &device.repositories { None => Some(format!("{name} has not checked its repositories yet. Open Cotton on it to check ownership and refs.")), Some(readiness) => readiness.problems.first().map(|problem| problem.reason.clone()), }); let minutes = |stamp: &Option| { stamp .as_deref() .and_then(|stamp| DateTime::parse_from_rfc3339(stamp).ok()) .map(|at| at.timestamp() / 60) }; let merge = format!("writes {serving_name} still holds will merge when it returns"); let behind = match ( minutes(&device.copy_as_of), serving.and_then(|serving| minutes(&serving.copy_as_of)), ) { (Some(own), Some(served)) if served - own < LEVEL_WITHIN_MINUTES => None, (Some(own), Some(served)) => Some(format!( "{name} is {} behind {serving_name}; {merge}", span(served - own) )), // One of the two has never said where its copy stands. _ => Some(format!( "{name} has not said how far behind {serving_name} it is; {merge}" )), }; let mut words = Map::new(); words.insert("offered".to_string(), Value::Bool(why_not.is_none())); words.insert( "whyNot".to_string(), why_not.map_or(Value::Null, Value::from), ); words.insert( "behind".to_string(), behind.map_or(Value::Null, Value::from), ); Some(words) } /// "40 minutes", "3 hours", "2 days" — the largest whole unit. fn span(minutes: i64) -> String { let (count, unit) = match minutes { minutes if minutes < 90 => (minutes, "minute"), minutes if minutes < 36 * 60 => (minutes / 60, "hour"), minutes => (minutes / (24 * 60), "day"), }; format!("{count} {unit}{}", if count == 1 { "" } else { "s" }) } /// The lines the act's sheet shows before the owner confirms, in order: how /// far behind the chosen Mac is (when it is), the databases it will serve, /// each of the owner's databases it holds no copy of — served again only when /// the Mac that serves now returns, as is anything made since a Mac that is /// behind last synced — and what must be typed again. pub fn serve_from_sheet( name: &str, serving_name: &str, behind: Option<&str>, will_serve: &[String], holds_no_copy_of: &[String], ) -> Vec { let mut lines: Vec = behind .map(|behind| format!("{behind}.")) .into_iter() .collect(); lines.push(match will_serve { [] => format!("{name} will serve your databases."), [one] => format!("{name} will serve {one}."), [first @ .., last] => format!("{name} will serve {} and {last}.", first.join(", ")), }); for database in holds_no_copy_of { lines.push(format!( "{name} holds no copy of {database}; it is served again when {serving_name} returns." )); } // A COPY THAT IS BEHIND CANNOT LIST WHAT WAS MADE SINCE: a database made // after the chosen Mac last synced has that Mac's row in it from birth, // so nothing read here tells it from one the Mac holds — and it is handed // to the chosen Mac whole by the Mac that serves now, when that returns // (architect's ruling, 12 Oct 2026 11:00 IST). if behind.is_some() { lines.push(format!( "Databases made since {name} last synced are served again when {serving_name} returns." )); } lines.push(format!( "Repository variables must be entered again on {name}." )); lines } /// Every word the `device` table's columns say of each row, keyed by the /// definition's column: `kind`, `machine`, `status`, `state`, /// `approved_by_device` (the approver's name), `serving_place`, `load`, /// `last_seen_at` (the Mac's own last reading, the one stamp the file holds) /// and typed access/serving facts. Said for a reader that is none of the rows. pub fn table_words( device: &DeviceFacts, all: &[DeviceFacts], order: &[String], clock: &Clock, ) -> Map { let mut words = Map::new(); let mut put = |key: &str, value: Option| { if let Some(value) = value.filter(|value| !value.is_empty()) { words.insert(key.to_string(), Value::from(value)); } }; put("kind", kind(device.platform.as_deref()).map(str::to_string)); put("machine", machine(device).map(str::to_string)); put("status", Some(status(device).to_string())); let place = order .iter() .position(|id| Some(id.as_str()) == device.device_id.as_deref()) .map(|index| index + 1); put("state", Some(state_line(device, None, None, place, clock))); put( "approved_by_device", device .approved_by .as_ref() .map(|_| approver(device.approved_by.as_deref(), all)), ); put("serving_place", serving_place(device, order)); put( "load", (!device.removed()).then(|| load_line(device)).flatten(), ); put("sessions", sessions_line(device.sessions_running, device.sessions_cap)); put("last_seen_at", device.heard_at()); let os = match (device.platform.as_deref(), device.os_version.as_deref()) { (Some("mac"), Some(version)) => Some(format!("macOS {version}")), (Some("ios"), Some(version)) => Some(format!("iOS {version}")), (Some("android"), Some(version)) => Some(format!("Android {version}")), _ => None, }; put("os_version", os); words.insert("has_access".into(), Value::Bool(!device.removed())); words.insert("can_serve".into(), Value::Bool(!device.removed() && cannot_serve(device).is_none())); words } #[cfg(test)] #[path = "words_tests.rs"] mod tests;