//! How often a Mac and an agent account are sampled, and how long the readings//! are kept.//!//! The DEVICE row and the ACCOUNT row each carry the latest reading — what the//! phone draws on a card, and what the dispatcher decides from. This module is//! about the two SAMPLE tables under them (`cotton_device_samples`,//! `cotton_account_usage_samples`): the strip a person scrubs to answer "is//! that Mac usually free at this hour" rather than only "is it free now".//!//! Both numbers are here, with the reason on them, because a cadence and a//! retention written in two places is a cadence and a retention that disagree://! the helper that TAKES a sample and the sweep that DELETES one are different//! processes on different machines, and neither may guess what the other meant.//!//! No clock, no database, no `Ctx` — every function is of its arguments, which//! is what lets `samples_tests.rs` state the rules as arithmetic.use chrono::{DateTime, Duration, Utc};/// Minutes between one reading of a Mac (or of an agent account) and the next.////// **Fifteen, and deliberately not finer.** A sample answers a question about/// a WORKING DAY — was this Mac busy this morning, did that login burn its/// five-hour window before lunch — and a question at that scale is not answered/// any better by a reading every minute. What a finer cadence would cost is/// paid by every device in the household: each sample is a synced row, so a/// one-minute cadence is fifteen times the rows on every phone, fifteen times/// the outbox on a Mac that has been offline, and a sync that spends its first/// page on telemetry.////// At this cadence four Macs and four accounts hold under twelve thousand live/// rows between them, which is a table nothing has to page.pubconst SAMPLE_INTERVAL_MINUTES: i64 = 15;/// Days a sample is kept before the `samples-retention` sweep deletes it.////// **About a month** ([keep-machine-stats-and-account-usage-history-for-about-a-month-a])./// Thirty days is the window in which "this is not how that Mac usually/// behaves" is a judgement a person can actually make: it spans four working/// weeks, so a weekday pattern shows up four times rather than once, and it/// outlives a single bad week without turning into an archive nobody reads.////// The delete REPLICATES like any other write — it is not a local prune — so/// the window is the same on every device, and a phone that has been off for a/// fortnight comes back to the same strip the Mac has.pubconst RETENTION_DAYS: i64 = 30;/// The instant at and before which a sample is past the window.////// The sweep deletes `sampled_at < retention_cutoff(now)`. Strictly less than,/// so a sample taken exactly on the boundary survives its last tick rather than/// being deleted by a run that happened to land on the same millisecond.#[must_use]pubfn retention_cutoff(now: DateTime<Utc>) -> DateTime<Utc> { now - Duration::days(RETENTION_DAYS)}/// Is it time to take another sample?////// `last` is when this device (or account) was last sampled, or `None` for one/// that never has been — which is always due, because the first reading is the/// one that turns an empty card into a card.////// A reading stamped in the FUTURE is not due. That is the honest answer rather/// than a defensive one: two Macs' clocks disagree by seconds, and treating a/// future stamp as "overdue" would make the two of them take turns resampling/// each other's rows for as long as the skew lasts.#[must_use]pubfn should_sample(last: Option<DateTime<Utc>>, now: DateTime<Utc>) -> bool {letSome(last) = last else {returntrue; }; now - last >= Duration::minutes(SAMPLE_INTERVAL_MINUTES)}/// How many samples a device (or account) holds when the window is full.////// Not a limit anything enforces — the sweep works on age, not on count. It is/// here so the size of the thing can be stated in one place and checked by a/// test rather than estimated in a comment.#[must_use]pubconstfn samples_per_subject() -> i64 { RETENTION_DAYS * 24 * 60 / SAMPLE_INTERVAL_MINUTES}/// How many points a thirty-day strip is drawn from.////// **Ninety-six**, which at [`RETENTION_DAYS`] is one point per seven and a/// half hours — a working morning, an afternoon, an evening, a night, four/// times a day for thirty days. The whole window holds/// [`samples_per_subject`] readings (2,880 at the fifteen-minute cadence), and/// handing every one of them to a phone would be a read that answers thirty/// times more than the strip can draw: a strip is at most a few hundred points/// wide in pixels, so a point per reading is a point per third of a pixel.////// The thinning happens in the CRATE rather than in Swift, for the reason every/// other `read.*` gives: one implementation of the answer, and a screen decodes/// what it draws.pubconst STRIP_POINTS: usize = 96;/// One reading, as [`thin`] takes it: when, and the single number this strip is/// about.////// A sample row carries several numbers (a Mac's load, its free memory, its/// disk, its running sessions); a STRIP draws one series. The caller picks/// which, so this module never has to know what a device sample's columns are.#[derive(Debug, Clone, Copy, PartialEq)]pubstructReading {pub at: DateTime<Utc>,pub value: f64,}/// One column of a thinned strip.////// `value` is `None` for a bucket no reading fell in — a Mac that was asleep,/// a phone that had not synced that stretch yet. That is drawn as a GAP and/// never as a zero: a zero is a reading, and "nothing was reported" is not.#[derive(Debug, Clone, Copy, PartialEq)]pubstructStripPoint {/// The instant this bucket STARTS at.pub at: DateTime<Utc>,/// The mean of the readings in the bucket, or `None` if there were none.pub value: Option<f64>,/// How many readings went into it. Zero is the gap above.pub samples: usize,}/// Thin a window of readings down to at most [`STRIP_POINTS`] columns.////// The window is the retention window ending at `now`/// (`[now - RETENTION_DAYS, now]`), cut into [`STRIP_POINTS`] equal buckets and/// answered oldest first, so the strip a screen draws is always the same width/// whether the Mac reported four times or four hundred. A reading outside the/// window is DROPPED rather than clamped into the first or last bucket: the/// sweep is about to delete it, and a stale reading pushed onto today's column/// would be a line that moves when nothing happened.////// **The bucket's value is the MEAN of its readings, never the peak.** A bucket/// is seven and a half hours wide and the question the strip answers is "is/// that Mac usually free at this hour"; a maximum would make one thirty-second/// spike look like an afternoon of load, which is the reading a person would/// act on wrongly.////// No clock: `now` is passed in, the way every function in this module takes/// its instant.#[must_use]pubfn thin(readings: &[Reading], now: DateTime<Utc>) -> Vec<StripPoint> {let start = retention_cutoff(now);let span_ms = (now - start).num_milliseconds().max(1);letmut sums = vec![0.0_f64; STRIP_POINTS];letmut counts = vec![0_usize; STRIP_POINTS];for reading in readings {let offset = (reading.at - start).num_milliseconds();if offset < 0 || reading.at > now {continue; }// The last bucket is CLOSED at `now`: a reading taken this instant// belongs to the newest column rather than to a hundred-and-first that// does not exist.let bucket = ((offset as i128 * STRIP_POINTS as i128) / span_ms as i128) as usize;let bucket = bucket.min(STRIP_POINTS - 1); sums[bucket] += reading.value; counts[bucket] += 1; } (0..STRIP_POINTS) .map(|index| {let at = start + Duration::milliseconds(span_ms * index as i64 / STRIP_POINTS as i64);StripPoint { at, value: (counts[index] > 0).then(|| sums[index] / counts[index] as f64), samples: counts[index], } }) .collect()}#[cfg(test)]#[path = "samples_tests.rs"]mod tests;