Cotton code
228 lines · 8.1 KB · RustRaw
//! The three tables a reading lands in, and the keys that make a re-read//! land on the row it wrote before.//!//! - `health_day`: one row per metric per day, keyed by (metric, day). A//!   day is always sent whole, so the new row replaces the old.//! - `health_workout`: keyed by (kind, start, end) to the second, so the//!   same workout read from HealthKit and from an export is one row.//! - `health_measurement`: keyed by (kind, instant) to the second.//!//! The sample's own id (HealthKit's uuid) is kept in `sample`, so a//! deletion HealthKit reports by uuid finds its row.//!//! A key here is the row's PLANNED id, plain words (`day|steps|2026-11-12`).//! The tables are sealed, so the id a row keeps on the object is the keyed//! id only the database's data key makes from it//! (`cotton_client::seal::keyed_row_id`): every device makes the same one,//! and the Worker cannot tell a glucose day from a step day by its id.use serde_json::{json, Map, Value};pub const DAY_TABLE: &str = "health_day";pub const WORKOUT_TABLE: &str = "health_workout";pub const MEASUREMENT_TABLE: &str = "health_measurement";/// Where a reading came from (`source` on every row).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Source {    /// HealthKit on the iPhone.    HealthKit,    /// Health Connect on Android (a later reader).    HealthConnect,    /// Apple Health's export.zip, read anywhere.    Export,}impl Source {    pub fn as_str(self) -> &'static str {        match self {            Source::HealthKit => "healthkit",            Source::HealthConnect => "health_connect",            Source::Export => "export",        }    }    pub fn of(word: &str) -> Option<Source> {        Some(match word {            "healthkit" => Source::HealthKit,            "health_connect" => Source::HealthConnect,            "export" => Source::Export,            _ => return None,        })    }}/// A day's summary of one metric.#[derive(Debug, Clone, PartialEq)]pub struct DayRow {    pub metric: &'static str,    /// `YYYY-MM-DD`, the person's own day where the reading was made.    pub day: String,    pub value: Option<f64>,    pub min: Option<f64>,    pub max: Option<f64>,    /// How many samples made it, where the reader counted them.    pub samples: Option<i64>,    /// A word for the day where the metric is one (menstrual flow).    pub state: Option<String>,    pub source: Source,}/// One workout.#[derive(Debug, Clone, PartialEq)]pub struct WorkoutRow {    pub kind: &'static str,    pub started_ms: i64,    pub ended_ms: i64,    /// The day it started on, the person's own.    pub day: String,    pub minutes: f64,    pub distance_m: Option<f64>,    pub energy_kcal: Option<f64>,    pub heart_rate_avg: Option<f64>,    pub heart_rate_max: Option<f64>,    /// The app or watch that recorded it.    pub device: Option<String>,    pub sample: Option<String>,    pub source: Source,}/// One point measurement.#[derive(Debug, Clone, PartialEq)]pub struct MeasurementRow {    pub kind: &'static str,    pub measured_ms: i64,    pub day: String,    pub value: f64,    /// Blood pressure's diastolic; `value` is the systolic.    pub second: Option<f64>,    pub unit: &'static str,    /// What the reading was taken around (glucose: fasting, before a meal…).    pub context: Option<String>,    pub device: Option<String>,    pub sample: Option<String>,    pub source: Source,}pub fn day_key(metric: &str, day: &str) -> String {    format!("day|{metric}|{day}")}pub fn workout_key(kind: &str, started_ms: i64, ended_ms: i64) -> String {    format!("workout|{kind}|{}|{}", started_ms.div_euclid(1000), ended_ms.div_euclid(1000))}pub fn measurement_key(kind: &str, measured_ms: i64) -> String {    format!("measurement|{kind}|{}", measured_ms.div_euclid(1000))}/// An instant as the rows keep it: UTC, to the millisecond.pub fn iso(ms: i64) -> String {    chrono::DateTime::from_timestamp_millis(ms).unwrap_or_default().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}/// A number as a row keeps it: three decimals at most, so a unit/// conversion's dust never reads as a change.pub fn kept(value: f64) -> Value {    let rounded = (value * 1000.0).round() / 1000.0;    if rounded.fract() == 0.0 && rounded.abs() < 9.0e15 {        json!(rounded as i64)    } else {        json!(rounded)    }}fn put(map: &mut Map<String, Value>, key: &str, value: Option<Value>) {    map.insert(key.to_string(), value.unwrap_or(Value::Null));}impl DayRow {    pub fn key(&self) -> String {        day_key(self.metric, &self.day)    }    /// The row's data, `id` (the row's keyed id) as its key.    pub fn data(&self, id: &str) -> Map<String, Value> {        let unit = super::catalog::metric_of(self.metric).map(|metric| metric.unit).unwrap_or_default();        let mut map = Map::new();        map.insert("key".into(), json!(id));        map.insert("metric".into(), json!(self.metric));        map.insert("day".into(), json!(self.day));        put(&mut map, "value", self.value.map(kept));        put(&mut map, "min", self.min.map(kept));        put(&mut map, "max", self.max.map(kept));        map.insert("unit".into(), json!(unit));        put(&mut map, "samples", self.samples.map(Value::from));        put(&mut map, "state", self.state.clone().map(Value::from));        map.insert("source".into(), json!(self.source.as_str()));        map    }}impl WorkoutRow {    pub fn key(&self) -> String {        workout_key(self.kind, self.started_ms, self.ended_ms)    }    pub fn data(&self, id: &str) -> Map<String, Value> {        let mut map = Map::new();        map.insert("key".into(), json!(id));        map.insert("kind".into(), json!(self.kind));        map.insert("day".into(), json!(self.day));        map.insert("started_at".into(), json!(iso(self.started_ms)));        map.insert("ended_at".into(), json!(iso(self.ended_ms)));        map.insert("minutes".into(), kept(self.minutes));        put(&mut map, "distance_m", self.distance_m.map(kept));        put(&mut map, "energy_kcal", self.energy_kcal.map(kept));        put(&mut map, "heart_rate_avg", self.heart_rate_avg.map(kept));        put(&mut map, "heart_rate_max", self.heart_rate_max.map(kept));        put(&mut map, "device", self.device.clone().map(Value::from));        put(&mut map, "sample", self.sample.clone().map(Value::from));        map.insert("source".into(), json!(self.source.as_str()));        map    }}impl MeasurementRow {    pub fn key(&self) -> String {        measurement_key(self.kind, self.measured_ms)    }    pub fn data(&self, id: &str) -> Map<String, Value> {        let mut map = Map::new();        map.insert("key".into(), json!(id));        map.insert("kind".into(), json!(self.kind));        map.insert("day".into(), json!(self.day));        map.insert("measured_at".into(), json!(iso(self.measured_ms)));        map.insert("value".into(), kept(self.value));        put(&mut map, "second", self.second.map(kept));        map.insert("unit".into(), json!(self.unit));        put(&mut map, "context", self.context.clone().map(Value::from));        put(&mut map, "device", self.device.clone().map(Value::from));        put(&mut map, "sample", self.sample.clone().map(Value::from));        map.insert("source".into(), json!(self.source.as_str()));        map    }}/// An instant read from a source's text, with the person's own day and/// hour where it was made: RFC 3339 (`2026-11-12T07:12:00+05:30`, what the/// phone sends) or the export's `2026-11-12 07:12:00 +0530`.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Instant {    pub ms: i64,    pub day: String,    pub hour: u32,}pub fn instant(text: &str) -> Option<Instant> {    let text = text.trim();    let parsed = chrono::DateTime::parse_from_rfc3339(text).or_else(|_| chrono::DateTime::parse_from_str(text, "%Y-%m-%d %H:%M:%S %z")).ok()?;    use chrono::Timelike;    Some(Instant { ms: parsed.timestamp_millis(), day: parsed.format("%Y-%m-%d").to_string(), hour: parsed.hour() })}/// Is `day` a calendar date (`YYYY-MM-DD`)?pub fn is_day(day: &str) -> bool {    day.len() == 10 && chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d").is_ok()}