//! What a machine's own report says about it — the one rule every reader of a //! device row applies before it draws or dispatches anything. //! //! A computer in the household reports on itself: the session helper on a Mac //! (or the headless server on Linux) samples the machine every //! [`REPORT_INTERVAL_MINUTES`] and writes the reading onto its device row. //! Three places read that row and each used to decide for itself what it //! meant: the dispatcher (which Mac takes a session), the phone's Settings › //! Code page (which login is on which Mac, and how much of it is used), and the //! hold sentence on a queued card. They disagreed — an iPhone that never runs //! a session was named in a hold sentence as a Mac that "has never reported", //! and a Mac that had gone to sleep an hour ago still showed its usage //! percentages as if they were current. //! //! So the rule lives here, once: //! //! * [`can_host`] — may this device run a session at all? //! * [`report_state`] — is what it last said still current? //! * [`window_pct`] — is a usage figure still a figure, or has its window //! already reset? //! * [`received_stamp`] — is a report's stamp believable, or is it a fast //! clock the server must stamp on receipt? //! * [`listed_machines`] — which device rows are the household's machines, //! one per machine, none retired? //! //! No clock, no database: every function takes `now`, which is what lets //! `machines_tests.rs` state each rule as arithmetic. use chrono::{DateTime, Duration, SecondsFormat, Utc}; /// Minutes between one report from a machine and the next. /// /// **Five.** The report is what the dispatcher and the phone decide from, and /// it is one small synced row rewritten in place — not the thirty-day history, /// which keeps its own fifteen-minute cadence /// ([`super::samples::SAMPLE_INTERVAL_MINUTES`]) and is unaffected by this /// number. At fifteen, "has this Mac gone quiet" could only be answered twenty /// minutes late. pub const REPORT_INTERVAL_MINUTES: i64 = 5; /// How late a report may be before its machine reads as silent: the time a /// reading takes to be taken, written into the file and synced to the device /// that reads it. pub const REPORT_GRACE_MINUTES: i64 = 5; /// How recently a machine must have reported for what it said to be current. /// /// **Ten minutes: one interval and the grace.** A machine that has not /// reported in ten minutes has missed its most recent report — it is asleep, /// off, or cannot reach the server — and every reader says so rather than /// drawing its last numbers as if they were live. WRITTEN AS the sum, so the /// window can never again be shorter than the interval it waits for. pub const SEEN_WINDOW_MINUTES: i64 = REPORT_INTERVAL_MINUTES + REPORT_GRACE_MINUTES; /// How far ahead of the receiving clock a machine's stamp may be and still be /// believed as written. /// /// **Two minutes.** Clocks on the owner's machines agree to a few seconds when /// they are synchronised; a stamp further ahead than this is a clock that is /// wrong, and believing it made a Mac one hour fast read as reporting for /// seventy minutes after it went quiet — every reader compares a stamp with its /// own `now`, and a stamp in the future is never old. So the server stamps such /// a report ON RECEIPT ([`received_stamp`]): what it holds is when the report /// arrived, which is the latest it can have been true. pub const REPORT_LEAD_MINUTES: i64 = 2; /// The stamp a report is kept under, given when it was received — `None` to /// keep the machine's own. /// /// A stamp at most [`REPORT_LEAD_MINUTES`] ahead of `received` is kept: a skew /// of seconds must not rewrite every report. One further ahead is replaced by /// `received` itself. A stamp in the PAST is always kept — a machine that was /// offline pushes its last reading late, and that reading is exactly as old as /// it says; stamping it on receipt would draw an hour-old number as fresh. An /// unreadable stamp is kept too: the readers already treat it as no report. #[must_use] pub fn received_stamp(stamp: &str, received: DateTime) -> Option { let at = DateTime::parse_from_rfc3339(stamp).ok()?.with_timezone(&Utc); (at - received > Duration::minutes(REPORT_LEAD_MINUTES)) .then(|| received.to_rfc3339_opts(SecondsFormat::Millis, true)) } /// Can this device run a coding session? /// /// A device can host when it has not been revoked AND either it has reported /// at least once (a `sampled_at` or a `host_version` — only a machine running /// the session helper writes either) or it is a Mac or a Linux machine, which /// can run one even before its first report. /// /// **A phone that has never reported is not a host.** It is a device in the /// household, but no session helper runs on it, and naming it in a hold /// sentence ("the iPhone has never reported") sends the owner to look for a /// problem that does not exist. #[must_use] pub fn can_host( platform: Option<&str>, sampled_at: Option<&str>, host_version: Option<&str>, revoked_at: Option<&str>, ) -> bool { if present(revoked_at) { return false; } let has_reported = present(sampled_at) || present(host_version); has_reported || matches!(platform, Some("mac" | "linux")) } /// Whether a machine's last report is still current. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ReportState { /// It reported within [`SEEN_WINDOW_MINUTES`]. Current, /// It has not. `since` is when it last did, or `None` for a machine that /// never has (or whose stamp cannot be read as an instant). Silent { since: Option }, } /// Is the report stamped `sampled_at` still current at `now`? /// /// **A report exactly [`SEEN_WINDOW_MINUTES`] old is still current** — a /// machine reporting on its own tick must not drop out on a rounding. A stamp /// in the FUTURE counts as received now, so it is current: the server has /// already replaced any stamp more than [`REPORT_LEAD_MINUTES`] ahead of its /// own clock with the time it received the report ([`received_stamp`]), so a /// future stamp a reader sees is at most that lead plus the reader's own skew — /// never an hour a fast clock would keep a silent machine live for. An absent /// or unreadable stamp is `Silent { since: None }`. #[must_use] pub fn report_state(sampled_at: Option<&str>, now: DateTime) -> ReportState { let Some(raw) = sampled_at.filter(|raw| !raw.trim().is_empty()) else { return ReportState::Silent { since: None }; }; match DateTime::parse_from_rfc3339(raw) { Ok(at) if is_current(at.with_timezone(&Utc), now) => ReportState::Current, Ok(_) => ReportState::Silent { since: Some(raw.to_string()), }, Err(_) => ReportState::Silent { since: None }, } } /// [`report_state`] over an instant the caller has already parsed — what the /// dispatcher holds. #[must_use] pub fn report_state_at(sampled_at: Option>, now: DateTime) -> ReportState { match sampled_at { None => ReportState::Silent { since: None }, Some(at) if is_current(at, now) => ReportState::Current, Some(at) => ReportState::Silent { since: Some(at.to_rfc3339_opts(SecondsFormat::Millis, true)), }, } } fn is_current(at: DateTime, now: DateTime) -> bool { now - at <= Duration::minutes(SEEN_WINDOW_MINUTES) } /// A usage window's percentage, or `None` when there is nothing true to show. /// /// **A window whose reset time has passed is not shown as a percentage.** The /// figure was how much of THAT window was used; once it has reset, the agent /// has not yet said how much of the new one is, and showing the old number /// would say the login is nearly out when it has its whole window back. A /// reset exactly at `now` has happened. A window with no reset time (or one /// that cannot be read) keeps its figure — there is nothing to say it is over. #[must_use] pub fn window_pct(pct: Option, resets_at: Option<&str>, now: DateTime) -> Option { let pct = pct?; let reset = resets_at .and_then(|raw| DateTime::parse_from_rfc3339(raw).ok()) .map(|at| at.with_timezone(&Utc)); match reset { Some(at) if at <= now => None, _ => Some(pct), } } /// How long a machine may be silent before it is no longer listed as one of /// the household's machines. /// /// **The history's own thirty days** ([`super::samples::RETENTION_DAYS`]). A /// machine that has not reported for longer than its whole strip is a machine /// that was retired without anyone revoking its key; drawing "has not reported /// since …" beside it for ever is a row about nothing. Its key is untouched — /// the Devices pane still lists it, and revoking is still the person's act. pub const RETIRED_AFTER_DAYS: i64 = super::samples::RETENTION_DAYS; /// The machine a device row's name is about — `Mac (mac-b)` and `mac-b` are one /// computer. /// /// The first is how an earlier build named a Mac when it joined, and the second /// is how this one does. The unwrap is that ONE retired spelling and nothing /// more general — a name is a label a person chose, and this must not start /// matching two computers the person deliberately called similar things. Case /// is ignored and the edges are trimmed, because `mac-b` and `MAC-B ` are one /// machine typed twice. #[must_use] pub fn machine_name(name: &str) -> String { let name = name.trim(); let inner = name .strip_prefix("Mac (") .and_then(|rest| rest.strip_suffix(')')) .unwrap_or(name); inner.trim().to_lowercase() } /// Which of these hosting devices are listed as the household's machines — one /// flag per row, in the order given. Each row is `(name, sampled_at)`. /// /// **ONE ROW PER MACHINE, not per key.** A Mac that joins again under a new key /// leaves its old key's row behind, unrevoked; listing both drew the same Mac /// twice, one of them "has not reported since …". So a row that is NOT current /// is left out when another row for the same machine ([`machine_name`]) /// reported more recently — a never-reported row is older than any report. Two /// rows that are BOTH current are both kept: two live computers that share a /// name are two machines, and hiding one would hide a working Mac. /// /// **A RETIRED MACHINE IS NOT LISTED.** A row whose last report is more than /// [`RETIRED_AFTER_DAYS`] old is left out. A row that has never reported stays /// — a Mac that has just joined says so until its first report. #[must_use] pub fn listed_machines(rows: &[(&str, Option<&str>)], now: DateTime) -> Vec { let parsed: Vec<(String, Option>)> = rows .iter() .map(|(name, sampled_at)| { let at = sampled_at .and_then(|raw| DateTime::parse_from_rfc3339(raw).ok()) .map(|at| at.with_timezone(&Utc)); (machine_name(name), at) }) .collect(); parsed .iter() .enumerate() .map(|(index, (machine, at))| { if at.is_some_and(|at| now - at > Duration::days(RETIRED_AFTER_DAYS)) { return false; } if report_state_at(*at, now) == ReportState::Current { return true; } !parsed.iter().enumerate().any(|(other, (twin, twin_at))| { other != index && twin == machine && twin_at.is_some() && *twin_at > *at }) }) .collect() } fn present(value: Option<&str>) -> bool { value.is_some_and(|value| !value.trim().is_empty()) } #[cfg(test)] #[path = "machines_tests.rs"] mod tests;