//! Cotton Health on the phone: what the Swift shell asks HealthKit for, the//! anchors it keeps per type, the batches it lands, Apple's export read in//! place, and what the faces draw. The rules are the core's//! (`cotton_core::health`); this module owns the order and the two things//! only a device knows: its anchors and its data key.//!//! - `health.types {}` — every HealthKit type to request READ access to (the//! app never asks to share), each with the unit it is sent in, what is//! sent for it and, for a day's statistics, the option to ask.//! - `health.anchor { type }` → `{ type, anchor }` (null when none); with//! `anchor` (a string, the shell's archived `HKQueryAnchor`) it is kept,//! with `anchor: null` forgotten; `{ reset: true }` forgets every one, so//! the next read is a whole read again.//! - `health.held { type }` → `{ type, from, to }`: the first and last day//! this copy holds a day row of the metrics that type feeds (null when//! none), so the shell can read those days again after HealthKit reports//! a deletion (a deleted object names no day).//! - `health.land { …batch, anchors? }` — a batch (`cotton_core::health::land`//! says its shape), landed in one write per thousand rows. `anchors` (type//! to anchor) are kept only once every row is written, so a batch that//! failed is read again. Answers what was put and removed.//! - `health.readExport { path }` — Apple Health's export.zip (or its bare//! export.xml) read in place and landed as `export` rows.//! - `health.summary { day }` / `{ from, to }` — a day against its four//! weeks, or a range (`cotton_core::health::summary`).//!//! The tables are sealed, so a row's id is keyed by this database's data key//! (`cotton_client::seal::keyed_row_id`) and nothing lands while this device//! holds none: `seal_key_missing`, the shell unlocks and lands again.use std::collections::BTreeMap;use std::io::BufReader;use std::path::Path;use serde_json::{json, Map, Value};use cotton_client::seal::DataKeyStoreas _;use cotton_core::health::export::{read_export_xml, read_export_zip};use cotton_core::health::land::{plan, Plan};use cotton_core::health::rows::{day_key, is_day, DAY_TABLE, MEASUREMENT_TABLE, WORKOUT_TABLE};use cotton_core::health::{catalog, summary};use cotton_core::seal::DataKey;usecrate::handle::CottonHandle;usecrate::methods::{dispatch, MethodError};usecrate::phone::io_trouble::io_refusal;usecrate::phone::whatsapp_import::FileRanges;usecrate::shell::client::ClientController;pubconst METHODS: [&str; 6] = ["health.anchor", "health.held", "health.land", "health.readExport", "health.summary", "health.types"];/// This device's anchors, one map per database.pubconst ANCHORS_FILE: &str = "health-anchors.json";/// Rows per write.const CHUNK: usize = 1000;/// The longest range a summary reads, in days.const LONGEST_RANGE: i64 = 400;fn bad(why: implInto<String>) -> MethodError {MethodError::new("bad_request", why.into())}pubfn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {match method {"health.types" => Ok(json!({ "types": catalog::read_types(), "metrics": catalog::METRICS, "measures": catalog::MEASURES })),"health.anchor" => anchor(&handle.client(), request),"health.held" => held(handle, request),"health.land" => land(handle, request),"health.readExport" => read_export(handle, request),"health.summary" => summarise(handle, request), other ifsuper::health_app::METHODS.contains(&other) => super::health_app::call(handle, other, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a health method"))), }}// ── anchors ─────────────────────────────────────────────────────────────────typeAnchors = BTreeMap<String, BTreeMap<String, String>>;fn anchors_path(client: &ClientController) -> std::path::PathBuf { client.layout().client_dir().join(ANCHORS_FILE)}fn read_anchors(client: &ClientController) -> Result<Anchors, MethodError> {let path = anchors_path(client);match std::fs::read(&path) {Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| MethodError::new("unreadable", format!("{ANCHORS_FILE} is not valid JSON: {error}"))),Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Anchors::new()),Err(error) => Err(MethodError::new("unreadable", io_refusal(format!("{ANCHORS_FILE} could not be read"), &path, &error))), }}fn write_anchors(client: &ClientController, anchors: &Anchors) -> Result<(), MethodError> {let path = anchors_path(client);let unwritable = |error: std::io::Error| MethodError::new("unwritable", io_refusal(format!("{ANCHORS_FILE} could not be written"), &path, &error));ifletSome(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(unwritable)?; }let partial = path.with_extension("json.partial");// not a copy: health files. std::fs::write(&partial, serde_json::to_vec_pretty(anchors).expect("anchors serialise")).map_err(unwritable)?;// not a copy: health files. std::fs::rename(&partial, &path).map_err(unwritable)}pub(crate) fn database(client: &ClientController) -> Result<String, MethodError> { client.current_database().map_err(|why| MethodError::new("not_attached", why))}fn known_type(kind: &str) -> bool { catalog::read_types().iter().any(|read| read.healthkit == kind)}fn anchor(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let database = database(client)?;letmut anchors = read_anchors(client)?;if request.get("reset").and_then(Value::as_bool) == Some(true) {let forgotten = anchors.remove(&database).map(|held| held.len()).unwrap_or(0); write_anchors(client, &anchors)?;returnOk(json!({ "forgotten": forgotten })); }let kind = request.get("type").and_then(Value::as_str).filter(|kind| known_type(kind)).ok_or_else(|| bad("this names a HealthKit type health.types lists"))?;match request.get("anchor") {None => Ok(json!({ "type": kind, "anchor": anchors.get(&database).and_then(|held| held.get(kind)) })),Some(Value::Null) => {ifletSome(held) = anchors.get_mut(&database) { held.remove(kind); } write_anchors(client, &anchors)?;Ok(json!({ "type": kind, "anchor": null })) }Some(Value::String(text)) if !text.is_empty() => { anchors.entry(database).or_default().insert(kind.to_string(), text.clone()); write_anchors(client, &anchors)?;Ok(json!({ "type": kind, "anchor": text })) }Some(_) => Err(bad("an anchor is the archived anchor's text, or null")), }}fn held(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let kind = request.get("type").and_then(Value::as_str).filter(|kind| known_type(kind)).ok_or_else(|| bad("this names a HealthKit type health.types lists"))?;letmut days: Vec<String> = Vec::new();for metric in catalog::METRICS.iter().filter(|metric| metric.healthkit == kind) {for record in records(handle, DAY_TABLE, json!({ "metric": metric.key }))? {ifletSome(day) = record["data"]["day"].as_str().filter(|day| is_day(day)) { days.push(day.to_string()); } } } days.sort();Ok(json!({ "type": kind, "from": days.first(), "to": days.last() }))}// ── landing ─────────────────────────────────────────────────────────────────/// This database's data key, or the refusal that says to unlock.pub(crate) fn data_key(client: &ClientController, database: &str) -> Result<DataKey, MethodError> { client .data_keys() .data_key(database) .map_err(|why| MethodError::new("unreadable", why))? .ok_or_else(|| MethodError::new(cotton_client::seal::SEAL_KEY_MISSING, "Health's rows are sealed: unlock this phone's key before they land"))}pub(crate) structKeys {pub(crate) dk: DataKey,pub(crate) database: String,}implKeys {pub(crate) fn id(&self, table: &str, planned: &str) -> Result<String, MethodError> { cotton_client::seal::keyed_row_id(&self.dk, &self.database, table, planned).map_err(|error| MethodError::new("unreadable", error.to_string())) }}/// One write: a row to put (its data carries its keyed id as `key`), or a/// row to remove by id.enumWrite {Put(&'static str, Map<String, Value>),Remove(&'static str, String),}pub(crate) fn records(handle: &CottonHandle, table: &str, filter: Value) -> Result<Vec<Value>, MethodError> {letmut out = Vec::new();letmut page = 0u64;loop {let listed = dispatch(handle, "records.list", &json!({ "table": table, "where": filter, "limit": 500, "page": page, "total": false }))?;let got = listed["records"].as_array().cloned().unwrap_or_default();let count = got.len() as u64; out.extend(got);match listed["next_page"].as_u64() {Some(next) if count > 0 && next > page => page = next, _ => break, } }Ok(out)}pub(crate) fn exists(handle: &CottonHandle, table: &str, id: &str) -> Result<bool, MethodError> {match dispatch(handle, "records.get", &json!({ "table": table, "id": id })) {Ok(_) => Ok(true),Err(error) ifcrate::phone::copy_standing::absent(&error.code) => Ok(false),Err(error) => Err(error), }}/// Every day `from` to `to`, inclusive.fn days_between(from: &str, to: &str) -> Vec<String> {let (Ok(mut at), Ok(end)) = (chrono::NaiveDate::parse_from_str(from, "%Y-%m-%d"), chrono::NaiveDate::parse_from_str(to, "%Y-%m-%d")) else { returnVec::new() };letmut out = Vec::new();while at <= end { out.push(at.format("%Y-%m-%d").to_string()); at = at.succ_opt().expect("a next day"); } out}/// The writes a plan makes on this copy.fn writes(handle: &CottonHandle, keys: &Keys, plan: &Plan) -> Result<Vec<Write>, MethodError> {letmut out = Vec::new();for row in &plan.days { out.push(Write::Put(DAY_TABLE, row.data(&keys.id(DAY_TABLE, &row.key())?))); }for row in &plan.workouts { out.push(Write::Put(WORKOUT_TABLE, row.data(&keys.id(WORKOUT_TABLE, &row.key())?))); }for row in &plan.measurements { out.push(Write::Put(MEASUREMENT_TABLE, row.data(&keys.id(MEASUREMENT_TABLE, &row.key())?))); }// A day the phone said holds none, or sent whole without a measure it// held before: that row goes, by the id it was put under.letmut gone: Vec<(&'static str, String)> = plan.cleared.clone();for (metrics, from, to) in &plan.replaced {for day in days_between(from, to) {for metric in metrics {if plan.removes_day(metric, &day) { gone.push((metric, day.clone())); } } } }for (metric, day) in gone {let id = keys.id(DAY_TABLE, &day_key(metric, &day))?;if exists(handle, DAY_TABLE, &id)? { out.push(Write::Remove(DAY_TABLE, id)); } }for uuid in &plan.deleted {for table in [WORKOUT_TABLE, MEASUREMENT_TABLE] {for record in records(handle, table, json!({ "sample": uuid }))? {ifletSome(id) = record["id"].as_str() { out.push(Write::Remove(table, id.to_string())); } } } }Ok(out)}/// What a chunk answers when every row it put was already as sent: the/// write is let go (an act that changes nothing is no act).pub(crate) const UNCHANGED_CHUNK: &str = "health.land: every row was already as sent";/// Write `writes` a thousand at a time; answers how many rows changed and/// how many were removed. A row put as it already stands is no change.fn apply(handle: &CottonHandle, writes: Vec<Write>) -> Result<(usize, usize), MethodError> {let unchanged = cotton_core::records::RecordError::NothingToChange.to_string();let (mut put, mut removed) = (0usize, 0usize);letmut writes = writes.into_iter().peekable();while writes.peek().is_some() {let chunk: Vec<Write> = writes.by_ref().take(CHUNK).collect();let (mut changed, mut gone) = (0usize, 0usize);let written = handle.client().write_rows("health.land", &mut |ctx| { (changed, gone) = (0, 0);for write in &chunk {match write {Write::Put(table, data) => {let args = json!({ "table": table, "data": Value::Object(data.clone()) });match cotton_tools::mcp::handlers::tables::create_produced_record(ctx, args.as_object().expect("an object")) {Ok(_) => changed += 1,Err(failure) if failure.to_string() == unchanged => {}Err(failure) => returnErr(failure.to_string()), } }Write::Remove(table, id) => {let args = json!({ "table": table, "id": id }); cotton_tools::mcp::handlers::tables::delete_record(ctx, args.as_object().expect("an object")).map_err(|failure| failure.to_string())?; gone += 1; } } }if changed + gone == 0 {returnErr(UNCHANGED_CHUNK.to_string()); }Ok(Value::Null) });match written {Ok(_) => { put += changed; removed += gone; }Err(reason) if reason == UNCHANGED_CHUNK => {}Err(reason) => returnErr(MethodError::new("write_refused", reason)), } }Ok((put, removed))}fn land(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let client = handle.client();let anchors: BTreeMap<String, String> = match request.get("anchors") {None | Some(Value::Null) => BTreeMap::new(),Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad("anchors map a HealthKit type to its anchor's text"))?, };ifletSome(kind) = anchors.keys().find(|kind| !known_type(kind)) {returnErr(bad(format!("{kind} is not a type health.types lists"))); }let made = plan(request).map_err(bad)?;let database = database(&client)?;let keys = Keys { dk: data_key(&client, &database)?, database: database.clone() };let planned = writes(handle, &keys, &made)?;let (put, removed) = apply(handle, planned)?;if !anchors.is_empty() {letmut held = read_anchors(&client)?; held.entry(database).or_default().extend(anchors); write_anchors(&client, &held)?; }Ok(json!({ "put": put, "removed": removed, "days": made.days.len(), "workouts": made.workouts.len(), "measurements": made.measurements.len() }))}fn read_export(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let client = handle.client();let database = database(&client)?;let keys = Keys { dk: data_key(&client, &database)?, database };let path = request.get("path").and_then(Value::as_str).filter(|path| !path.is_empty()).ok_or_else(|| bad("this names the export's path"))?;let path = Path::new(path);let shown = path.file_name().map(|name| name.to_string_lossy().to_string()).unwrap_or_else(|| "the export".to_string());let refused = |error: cotton_core::health::export::ExportError| MethodError::new("unreadable", error.to_string());let export = if path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("xml")) {let file = std::fs::File::open(path).map_err(|error| MethodError::new("unreadable", io_refusal(format!("{shown} could not be read"), path, &error)))?; read_export_xml(BufReader::with_capacity(1 << 16, file)).map_err(refused)? } else { read_export_zip(&FileRanges::open(path, &shown)?).map_err(refused)? };let (read, skipped) = (export.read, export.skipped);let made = Plan::of_export(export);let planned = writes(handle, &keys, &made)?;let (put, _) = apply(handle, planned)?;Ok(json!({ "read": read, "skipped": skipped, "put": put, "days": made.days.len(), "workouts": made.workouts.len(), "measurements": made.measurements.len() }))}// ── summaries ───────────────────────────────────────────────────────────────/// A record's data, its id beside it.pub(crate) fn data_of(record: &Value) -> Map<String, Value> {letmut data = record["data"].as_object().cloned().unwrap_or_default();ifletSome(id) = record["id"].as_str() { data.insert("id".into(), json!(id)); } data}fn rows_on(handle: &CottonHandle, table: &str, days: &[String]) -> Result<Vec<Map<String, Value>>, MethodError> {letmut out = Vec::new();for day in days { out.extend(records(handle, table, json!({ "day": day }))?.iter().map(data_of)); }Ok(out)}fn summarise(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let text = |key: &str| request.get(key).and_then(Value::as_str).filter(|day| is_day(day));ifletSome(day) = text("day") {let from = summary::day_before(day, summary::USUAL_DAYS).expect("a day");let days = rows_on(handle, DAY_TABLE, &days_between(&from, day))?;let one = [day.to_string()];let workouts = rows_on(handle, WORKOUT_TABLE, &one)?;let measurements = rows_on(handle, MEASUREMENT_TABLE, &one)?;returnOk(summary::day(day, &days, &workouts, &measurements)); }let (Some(from), Some(to)) = (text("from"), text("to")) else {returnErr(bad("a summary names its day, or the days from and to (YYYY-MM-DD)")); };let span = days_between(from, to);if span.is_empty() || span.len() as i64 > LONGEST_RANGE {returnErr(bad(format!("a range runs from a day to a later one, {LONGEST_RANGE} days at most"))); }let days = rows_on(handle, DAY_TABLE, &span)?;let workouts = rows_on(handle, WORKOUT_TABLE, &span)?;Ok(summary::range(from, to, &days, &workouts))}#[cfg(test)]#[path = "health_tests.rs"]pub(crate) mod tests;