//! A batch the phone sends (`health.land`), read into the rows it makes. //! //! The phone keeps one HealthKit anchor per type and sends what changed //! since it. What it sends, per [`super::catalog::ReadType::sends`]: //! //! ```json //! { "source": "healthkit", //! "days": [{ "type": "HKQuantityTypeIdentifierStepCount", "day": "2026-11-12", "value": 8123 }, //! { "type": "HKQuantityTypeIdentifierRestingHeartRate", "day": "2026-11-12", "value": 58, "min": 55, "max": 61 }], //! "intervals": [{ "type": "HKCategoryTypeIdentifierSleepAnalysis", "from": "2026-11-11", "to": "2026-11-12", //! "samples": [{ "start": "2026-11-11T23:10:00+05:30", "end": "2026-11-12T06:40:00+05:30", "value": 3, "device": "Watch" }] }], //! "workouts": [{ "uuid": "…", "activity": 37, "start": "…", "end": "…", "distance_m": 5010, "energy_kcal": 320, //! "heart_rate_avg": 148, "heart_rate_max": 171, "device": "Watch" }], //! "measurements": [{ "type": "HKQuantityTypeIdentifierBodyMass", "uuid": "…", "at": "…", "value": 71.4 }, //! { "type": "HKCorrelationTypeIdentifierBloodPressure", "uuid": "…", "at": "…", "systolic": 118, "diastolic": 76 }, //! { "type": "HKQuantityTypeIdentifierBloodGlucose", "uuid": "…", "at": "…", "value": 96, "meal": 1 }], //! "deleted": [""] } //! ``` //! //! - A `days` entry is a day's statistics for one quantity type, in the //! unit `health.types` named, for every day the anchor said changed. The //! day is sent whole and replaces its row; `value: null` says the day now //! holds none and its row goes. //! - An `intervals` entry is every sample of a category type touching the //! days `from`..`to`, sent whole: those days' rows of that type are //! folded again, and a day's row the fold no longer makes goes. //! - Workouts and measurements are samples; `deleted` is HealthKit's //! deleted objects, by uuid, whichever table holds them. //! //! A batch that does not read is refused whole, by name: nothing lands, the //! phone's anchor stays, and the next read sends it again. use serde_json::Value; use super::catalog::{self, Dimension}; use super::fold::{fold_intervals, CategoryValue, Interval}; use super::rows::{instant, is_day, DayRow, MeasurementRow, Source, WorkoutRow}; /// What a batch does to the tables. #[derive(Debug, Default, PartialEq)] pub struct Plan { /// Day rows to put (each replaces its key's row). pub days: Vec, /// Day rows to remove: (metric, day). pub cleared: Vec<(&'static str, String)>, /// Days sent whole for these metrics: a row of one of them on a day in /// `from..=to` that `days` does not put goes. pub replaced: Vec<(Vec<&'static str>, String, String)>, pub workouts: Vec, pub measurements: Vec, /// HealthKit uuids whose rows go. pub deleted: Vec, } fn refuse(why: impl Into) -> String { why.into() } fn list<'a>(request: &'a Value, key: &str) -> Result<&'a [Value], String> { match request.get(key) { None | Some(Value::Null) => Ok(&[]), Some(Value::Array(items)) => Ok(items), Some(_) => Err(refuse(format!("{key} is a list"))), } } fn text<'a>(item: &'a Value, key: &str) -> Option<&'a str> { item.get(key).and_then(Value::as_str).map(str::trim).filter(|text| !text.is_empty()) } fn num(item: &Value, key: &str) -> Option { item.get(key).and_then(Value::as_f64).filter(|value| value.is_finite()) } /// The metrics a category type's days are folded into. fn interval_metrics(healthkit: &str) -> Vec<&'static str> { catalog::METRICS.iter().filter(|metric| metric.healthkit == healthkit).map(|metric| metric.key).collect() } /// Read a batch. `source` defaults to HealthKit. pub fn plan(request: &Value) -> Result { let source = match text(request, "source") { None => Source::HealthKit, Some(word) => Source::of(word).ok_or_else(|| refuse(format!("source {word} is not healthkit, health_connect or export")))?, }; let mut plan = Plan::default(); for item in list(request, "days")? { let kind = text(item, "type").ok_or_else(|| refuse("a day names its type"))?; let metric = catalog::quantity_metric(kind).ok_or_else(|| refuse(format!("{kind} is not a type Cotton Health sums by day")))?; let day = text(item, "day").filter(|day| is_day(day)).ok_or_else(|| refuse(format!("a {kind} day names its day as YYYY-MM-DD")))?; let convert = |key: &str| -> Result, String> { match num(item, key) { None => Ok(None), Some(raw) => catalog::canonical(metric.dimension, raw, metric.healthkit_unit).map(Some).ok_or_else(|| refuse(format!("{kind} {key} does not read"))), } }; match convert("value")? { None => plan.cleared.push((metric.key, day.to_string())), Some(value) => plan.days.push(DayRow { metric: metric.key, day: day.to_string(), value: Some(value), min: convert("min")?, max: convert("max")?, samples: item.get("samples").and_then(Value::as_i64), state: None, source, }), } } for item in list(request, "intervals")? { let kind = text(item, "type").ok_or_else(|| refuse("intervals name their type"))?; let metrics = interval_metrics(kind); if metrics.is_empty() || catalog::quantity_metric(kind).is_some() { return Err(refuse(format!("{kind} is not a type Cotton Health reads as intervals"))); } let from = text(item, "from").filter(|day| is_day(day)).ok_or_else(|| refuse(format!("{kind} intervals say from which day")))?; let to = text(item, "to").filter(|day| is_day(day) && *day >= from).ok_or_else(|| refuse(format!("{kind} intervals say to which day, on or after from")))?; let mut intervals = Vec::new(); for sample in list(item, "samples")? { let start = text(sample, "start").and_then(instant).ok_or_else(|| refuse(format!("a {kind} sample's start does not read")))?; let end = text(sample, "end").and_then(instant).ok_or_else(|| refuse(format!("a {kind} sample's end does not read")))?; let value = match sample.get("value") { Some(Value::Number(number)) => CategoryValue::Raw(number.as_i64().ok_or_else(|| refuse(format!("a {kind} sample's value is a whole number")))?), Some(Value::String(word)) => CategoryValue::Word(word.clone()), // A mindful session carries no value. _ => CategoryValue::Raw(0), }; intervals.push(Interval { healthkit: kind.to_string(), value, start, end, device: text(sample, "device").map(str::to_string) }); } plan.days.extend(fold_intervals(&intervals, source).into_iter().filter(|row| row.day.as_str() >= from && row.day.as_str() <= to)); plan.replaced.push((metrics, from.to_string(), to.to_string())); } for item in list(request, "workouts")? { let start = text(item, "start").and_then(instant).ok_or_else(|| refuse("a workout's start does not read"))?; let end = text(item, "end").and_then(instant).ok_or_else(|| refuse("a workout's end does not read"))?; let kind = match item.get("activity") { Some(Value::Number(number)) => catalog::workout_kind_of_raw(number.as_i64().unwrap_or(3000)), Some(Value::String(word)) => catalog::workout_kind_of_word(word), _ => "other", }; let positive = |key: &str| num(item, key).filter(|value| *value > 0.0); plan.workouts.push(WorkoutRow { kind, started_ms: start.ms, ended_ms: end.ms, day: start.day.clone(), minutes: num(item, "minutes").unwrap_or((end.ms - start.ms) as f64 / 60_000.0), distance_m: positive("distance_m"), energy_kcal: positive("energy_kcal"), heart_rate_avg: positive("heart_rate_avg"), heart_rate_max: positive("heart_rate_max"), device: text(item, "device").map(str::to_string), sample: text(item, "uuid").map(str::to_string), source, }); } for item in list(request, "measurements")? { let kind = text(item, "type").ok_or_else(|| refuse("a measurement names its type"))?; let measure = catalog::MEASURES.iter().find(|measure| measure.healthkit == kind).ok_or_else(|| refuse(format!("{kind} is not a measurement Cotton Health keeps")))?; let at = text(item, "at").and_then(instant).ok_or_else(|| refuse(format!("a {kind} measurement's time does not read")))?; let (value, second) = if measure.kind == "blood_pressure" { let systolic = num(item, "systolic").ok_or_else(|| refuse("a blood pressure says its systolic"))?; let diastolic = num(item, "diastolic").ok_or_else(|| refuse("a blood pressure says its diastolic"))?; (systolic, Some(diastolic)) } else { let raw = num(item, "value").ok_or_else(|| refuse(format!("a {kind} measurement says its value")))?; (catalog::canonical(measure.dimension, raw, measure.healthkit_unit).ok_or_else(|| refuse(format!("{kind} value does not read")))?, None) }; let context = match (measure.dimension, item.get("meal").and_then(Value::as_i64)) { (Dimension::Glucose, Some(1)) => Some("before_meal".to_string()), (Dimension::Glucose, Some(2)) => Some("after_meal".to_string()), _ => None, }; plan.measurements.push(MeasurementRow { kind: measure.kind, measured_ms: at.ms, day: at.day.clone(), value, second, unit: measure.unit, context, device: text(item, "device").map(str::to_string), sample: text(item, "uuid").map(str::to_string), source, }); } for uuid in list(request, "deleted")? { plan.deleted.push(uuid.as_str().map(str::trim).filter(|uuid| !uuid.is_empty()).ok_or_else(|| refuse("deleted names uuids"))?.to_string()); } Ok(plan) } impl Plan { /// The plan an export makes: every row put, nothing cleared. pub fn of_export(export: super::export::Export) -> Plan { Plan { days: export.days, workouts: export.workouts, measurements: export.measurements, ..Plan::default() } } /// Does this plan remove the day row of `metric` on `day` that the /// table holds now? pub fn removes_day(&self, metric: &str, day: &str) -> bool { if self.cleared.iter().any(|(gone, on)| *gone == metric && on == day) { return true; } let replaced = self.replaced.iter().any(|(metrics, from, to)| metrics.contains(&metric) && day >= from.as_str() && day <= to.as_str()); replaced && !self.days.iter().any(|row| row.metric == metric && row.day == day) } }