Cotton code
319 lines · 20.7 KB · RustRaw
//! Cotton Health on a phone that started its own database: batches landed//! sealed under a held data key, read again without a duplicate, folded//! again when a day is sent whole, deletions by uuid, anchors kept only//! after a batch lands, an invented export read in place, and the//! summaries. Every reading is synthetic.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use serde_json::{json, Value};use super::*;use crate::handle::{CottonHandle, OpenConfig, OpenMode};const SLEEP: &str = "HKCategoryTypeIdentifierSleepAnalysis";const STEPS: &str = "HKQuantityTypeIdentifierStepCount";/// The manifest Health ships (also the screens' tests' phone).pub(crate) fn health_manifest() -> Value {    serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/health/flavour.json")).expect("Health's manifest")}fn phone(dir: &tempfile::TempDir) -> CottonHandle {    let handle = CottonHandle::open(OpenConfig {        mode: OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(health_manifest()),    })    .expect("an open core");    dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started on the phone");    handle}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {    dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}fn hold_a_key(handle: &CottonHandle) {    ask(handle, "seal.useKey", json!({ "key": URL_SAFE_NO_PAD.encode([7u8; 32]) }));}fn rows(handle: &CottonHandle, table: &str) -> Vec<Value> {    ask(handle, "records.list", json!({ "table": table, "limit": 500 }))["records"].as_array().cloned().unwrap_or_default()}fn day_row(handle: &CottonHandle, metric: &str, day: &str) -> Option<Value> {    rows(handle, DAY_TABLE).into_iter().find(|row| row["data"]["metric"] == metric && row["data"]["day"] == day).map(|row| row["data"].clone())}fn night(stages: &[(i64, &str, &str)]) -> Value {    json!({        "type": SLEEP, "from": "2026-11-12", "to": "2026-11-12",        "samples": stages.iter().map(|(value, start, end)| json!({ "start": start, "end": end, "value": value, "device": "An invented watch" })).collect::<Vec<_>>(),    })}fn batch() -> Value {    json!({        "days": [            { "type": STEPS, "day": "2026-11-12", "value": 8123 },            { "type": STEPS, "day": "2026-11-11", "value": 10233 },            { "type": "HKQuantityTypeIdentifierRestingHeartRate", "day": "2026-11-12", "value": 61, "min": 58, "max": 64 },        ],        "intervals": [night(&[            (3, "2026-11-11T23:00:00+05:30", "2026-11-12T02:00:00+05:30"),            (5, "2026-11-12T02:00:00+05:30", "2026-11-12T03:30:00+05:30"),            (4, "2026-11-12T03:30:00+05:30", "2026-11-12T04:30:00+05:30"),        ])],        "workouts": [{ "uuid": "00000000-0000-4000-8000-00000000a001", "activity": 37, "start": "2026-11-11T06:25:00+05:30", "end": "2026-11-11T06:57:30+05:30", "distance_m": 5200, "energy_kcal": 310, "heart_rate_avg": 152, "heart_rate_max": 174, "device": "An invented watch" }],        "measurements": [            { "type": "HKQuantityTypeIdentifierBodyMass", "uuid": "00000000-0000-4000-8000-00000000b001", "at": "2026-11-12T07:00:00+05:30", "value": 71.6 },            { "type": "HKCorrelationTypeIdentifierBloodPressure", "uuid": "00000000-0000-4000-8000-00000000b002", "at": "2026-11-12T08:00:00+05:30", "systolic": 118, "diastolic": 76 },        ],        "anchors": { STEPS: "an-archived-anchor", SLEEP: "another-anchor" },    })}/// RULE (Cotton Health, 12 Nov 2026): the app asks to read the catalogue's types and nothing lands while this phone holds no data key (the rows are sealed); with one held a batch lands every row under an id only that key makes, a second read of the same batch duplicates nothing, its anchors are kept only once it has landed, and Health's fan is the kit's six views.#[test]fn a_batch_lands_sealed_once_and_keeps_its_anchors() {    let dir = tempfile::tempdir().expect("a temp container");    let handle = phone(&dir);    let fan = ask(&handle, "shell.fan", json!({ "timezone": "Asia/Kolkata" }));    let views: Vec<&str> = fan["tiles"][0]["views"].as_array().expect("views").iter().filter_map(|view| view["id"].as_str()).filter(|id| *id != "account").collect();    assert_eq!(views, ["today", "trends", "workouts", "sleep", "body", "labs", "reports", "people", "devices"], "{fan}");    let types = ask(&handle, "health.types", json!({}));    let asked: Vec<&str> = types["types"].as_array().unwrap().iter().filter_map(|read| read["healthkit"].as_str()).collect();    assert!(asked.contains(&STEPS) && asked.contains(&SLEEP) && asked.contains(&"HKWorkoutTypeIdentifier"));    let refused = dispatch(&handle, "health.land", &batch()).expect_err("no key held");    assert_eq!(refused.code, cotton_client::seal::SEAL_KEY_MISSING);    assert!(rows(&handle, DAY_TABLE).is_empty(), "nothing landed");    assert_eq!(ask(&handle, "health.anchor", json!({ "type": STEPS }))["anchor"], Value::Null, "a refused batch keeps no anchor");    hold_a_key(&handle);    let landed = ask(&handle, "health.land", batch());    assert_eq!((landed["days"].clone(), landed["workouts"].clone(), landed["measurements"].clone()), (json!(7), json!(1), json!(2)), "{landed}");    let days = rows(&handle, DAY_TABLE);    assert_eq!(days.len(), 7);    for row in &days {        let id = row["id"].as_str().unwrap();        assert!(cotton_client::seal::uuid_shaped(id) && !id.contains("steps"), "a keyed id says nothing: {id}");        assert_eq!(row["data"]["key"], json!(id));    }    assert_eq!(day_row(&handle, "steps", "2026-11-12").unwrap()["value"], json!(8123));    let resting = day_row(&handle, "resting_heart_rate", "2026-11-12").unwrap();    assert_eq!((resting["min"].clone(), resting["max"].clone(), resting["unit"].clone()), (json!(58), json!(64), json!("bpm")));    assert_eq!(day_row(&handle, "sleep_asleep", "2026-11-12").unwrap()["value"], json!(330));    assert_eq!(day_row(&handle, "sleep_rem", "2026-11-12").unwrap()["value"], json!(90));    let run = &rows(&handle, WORKOUT_TABLE)[0]["data"];    assert_eq!((run["kind"].clone(), run["minutes"].clone(), run["source"].clone()), (json!("running"), json!(32.5), json!("healthkit")));    let pressure = rows(&handle, MEASUREMENT_TABLE).into_iter().find(|row| row["data"]["kind"] == "blood_pressure").unwrap();    assert_eq!((pressure["data"]["value"].clone(), pressure["data"]["second"].clone()), (json!(118), json!(76)));    assert_eq!(ask(&handle, "health.anchor", json!({ "type": STEPS }))["anchor"], "an-archived-anchor", "kept once the batch landed");    ask(&handle, "health.land", batch());    assert_eq!(rows(&handle, DAY_TABLE).len(), 7, "a re-read lands on the rows it wrote");    assert_eq!(rows(&handle, WORKOUT_TABLE).len(), 1);    assert_eq!(rows(&handle, MEASUREMENT_TABLE).len(), 2);    ask(&handle, "health.anchor", json!({ "type": SLEEP, "anchor": "a-later-anchor" }));    assert_eq!(ask(&handle, "health.anchor", json!({ "type": SLEEP }))["anchor"], "a-later-anchor");    ask(&handle, "health.anchor", json!({ "type": SLEEP, "anchor": null }));    assert_eq!(ask(&handle, "health.anchor", json!({ "type": SLEEP }))["anchor"], Value::Null);    assert_eq!(ask(&handle, "health.anchor", json!({ "reset": true }))["forgotten"], 1);    assert_eq!(dispatch(&handle, "health.anchor", &json!({ "type": "HKQuantityTypeIdentifierCaffeine" })).expect_err("not read").code, "bad_request");}/// RULE: a day sent whole replaces what it held (a stage the night no longer has goes, a day with none now goes), HealthKit's deletions take their rows by uuid, and a batch that does not read lands nothing.#[test]fn a_day_sent_whole_replaces_it_and_deletions_take_their_rows() {    let dir = tempfile::tempdir().expect("a temp container");    let handle = phone(&dir);    hold_a_key(&handle);    ask(&handle, "health.land", batch());    assert!(day_row(&handle, "sleep_rem", "2026-11-12").is_some());    ask(&handle, "health.land", json!({        "intervals": [night(&[(3, "2026-11-11T23:00:00+05:30", "2026-11-12T05:00:00+05:30")])],        "days": [{ "type": STEPS, "day": "2026-11-11", "value": null }],        "deleted": ["00000000-0000-4000-8000-00000000a001", "00000000-0000-4000-8000-00000000b001"],    }));    assert_eq!(day_row(&handle, "sleep_core", "2026-11-12").unwrap()["value"], json!(360));    assert_eq!(day_row(&handle, "sleep_asleep", "2026-11-12").unwrap()["value"], json!(360));    assert!(day_row(&handle, "sleep_rem", "2026-11-12").is_none(), "the night no longer holds REM");    assert!(day_row(&handle, "sleep_deep", "2026-11-12").is_none());    assert!(day_row(&handle, "steps", "2026-11-11").is_none(), "a day with none now");    assert!(day_row(&handle, "steps", "2026-11-12").is_some(), "a day not sent stays");    assert!(rows(&handle, WORKOUT_TABLE).is_empty(), "the deleted workout");    let kinds: Vec<Value> = rows(&handle, MEASUREMENT_TABLE).iter().map(|row| row["data"]["kind"].clone()).collect();    assert_eq!(kinds, [json!("blood_pressure")], "the deleted weighing");    let before = rows(&handle, DAY_TABLE).len();    let refused = dispatch(&handle, "health.land", &json!({ "days": [{ "type": STEPS, "day": "2026-11-13", "value": 1 }, { "type": STEPS, "day": "13 Nov" }] })).expect_err("refused");    assert_eq!(refused.code, "bad_request");    assert_eq!(rows(&handle, DAY_TABLE).len(), before, "nothing of a refused batch lands");}/// RULE: Apple's export is read in place and lands as export rows on the same keys the phone uses: a workout read from HealthKit and from the export is one row, and reading the export twice adds nothing; a summary reads a day against its weeks and a range as series.#[test]fn an_export_lands_on_the_phones_keys_and_the_summaries_read_it() {    let dir = tempfile::tempdir().expect("a temp container");    let handle = phone(&dir);    hold_a_key(&handle);    ask(&handle, "health.land", batch());    let file = dir.path().join("export.xml");    std::fs::write(&file, include_str!("../../../cotton-core/src/health/fixtures/export.xml")).expect("the invented export written");    let read = ask(&handle, "health.readExport", json!({ "path": file.to_string_lossy() }));    assert_eq!(read["workouts"], 2, "{read}");    assert!(read["skipped"].as_u64().unwrap() >= 1);    let workouts = rows(&handle, WORKOUT_TABLE);    assert_eq!(workouts.len(), 2, "the run the phone sent and the export holds is one row, the yoga a second");    let run = workouts.iter().find(|row| row["data"]["kind"] == "running").unwrap();    assert_eq!(run["data"]["source"], "export", "the later read stands");    let count = rows(&handle, DAY_TABLE).len();    ask(&handle, "health.readExport", json!({ "path": file.to_string_lossy() }));    assert_eq!(rows(&handle, DAY_TABLE).len(), count, "a second read adds nothing");    assert_eq!(day_row(&handle, "steps", "2026-11-11").unwrap()["value"], json!(5700), "the export's day stands over the phone's");    let missing = dispatch(&handle, "health.readExport", &json!({ "path": dir.path().join("nothing.zip").to_string_lossy() })).expect_err("no file");    assert_eq!(missing.code, "unreadable");    let today = ask(&handle, "health.summary", json!({ "day": "2026-11-12" }));    let steps = today["metrics"].as_array().unwrap().iter().find(|metric| metric["metric"] == "steps").unwrap();    assert_eq!((steps["value"].clone(), steps["usual"].clone()), (json!(4200), json!(5700)), "{today}");    assert_eq!(today["sleep"]["asleep"], json!(440));    assert_eq!(today["workouts"][0]["kind"], "yoga");    let week = ask(&handle, "health.summary", json!({ "from": "2026-11-06", "to": "2026-11-12" }));    let steps = week["metrics"].as_array().unwrap().iter().find(|metric| metric["metric"] == "steps").unwrap();    assert_eq!((steps["days_with"].clone(), steps["total"].clone()), (json!(2), json!(9900)));    assert_eq!(week["workouts"]["count"], 2);    assert_eq!(dispatch(&handle, "health.summary", &json!({ "from": "2026-11-12", "to": "2026-11-01" })).expect_err("backwards").code, "bad_request");}/// The data of a view's list as the phone deals it, in its order.fn view_rows(handle: &CottonHandle, table: &str, view: &str) -> Vec<Value> {    ask(handle, "records.list", json!({ "table": table, "view": view, "today": "2026-11-12", "timezone": "Asia/Kolkata", "limit": 500 }))["records"]        .as_array()        .cloned()        .unwrap_or_default()        .into_iter()        .map(|row| row["data"].clone())        .collect()}// RULE (coordinator, 12 Nov 2026): Health's views read the object by the clear// day alone; the phone narrows and orders the rows once they are open// (`ToolView::opened`). Sleep deals only the night's stages and its fan tile// counts those; Today orders a day's measures by name, Workouts and Body a// day's rows latest first.#[test]fn the_phone_narrows_and_orders_healths_views_once_their_rows_open() {    let dir = tempfile::tempdir().expect("a temp container");    let handle = phone(&dir);    hold_a_key(&handle);    let mut landed = batch();    landed["workouts"].as_array_mut().unwrap().push(json!({ "uuid": "00000000-0000-4000-8000-00000000a002", "activity": 52, "start": "2026-11-11T18:00:00+05:30", "end": "2026-11-11T18:40:00+05:30", "device": "An invented watch" }));    ask(&handle, "health.land", landed);    let sleep = view_rows(&handle, DAY_TABLE, "health/sleep");    assert!(!sleep.is_empty() && sleep.iter().all(|row| row["metric"].as_str().is_some_and(|metric| metric.starts_with("sleep_"))), "{sleep:?}");    let all = rows(&handle, DAY_TABLE);    assert!(all.len() > sleep.len(), "the table holds more than the nights");    let metrics: Vec<&str> = sleep.iter().map(|row| row["metric"].as_str().unwrap()).collect();    let mut sorted = metrics.clone();    sorted.sort();    assert_eq!(metrics, sorted, "a night's stages stand in their names' order");    let today = view_rows(&handle, DAY_TABLE, "health/today");    let today: Vec<&str> = today.iter().map(|row| row["metric"].as_str().unwrap()).collect();    let mut by_name = today.clone();    by_name.sort();    assert!(today.len() > 2 && today == by_name, "Today's measures stand by name: {today:?}");    let workouts = view_rows(&handle, WORKOUT_TABLE, "health/workouts");    let starts: Vec<&str> = workouts.iter().map(|row| row["started_at"].as_str().unwrap()).collect();    assert_eq!(starts.len(), 2);    assert!(starts[0] > starts[1], "a day's workouts stand latest first: {starts:?}");    let fan = ask(&handle, "shell.fan", json!({ "timezone": "Asia/Kolkata", "today": "2026-11-12" }));    let tile = fan["tiles"][0]["views"].as_array().unwrap().iter().find(|view| view["id"] == "sleep").cloned().expect("Sleep's tile");    assert_eq!(tile["count"], json!(sleep.len()), "Sleep's tile counts the nights' stages: {tile}");}/// RULE (Cotton Health's faces, 13 Nov 2026): each health card carries its face's words, read once with the card: a day's measure its value in its unit, its usual from the weeks before and where the pedometer's hand and the usual's tick stand on a round dial; the night's asleep row its stages as shares of the night; a workout its stopwatch's minutes, distance, energy and heart; a measurement its tag's reading, blood pressure upper over lower.#[test]fn each_health_card_carries_its_faces_words() {    let dir = tempfile::tempdir().expect("a temp container");    let handle = phone(&dir);    hold_a_key(&handle);    ask(&handle, "health.land", batch());    let card = |table: &str, find: &dyn Fn(&Value) -> bool| -> Value {        ask(&handle, "records.list", json!({ "table": table, "limit": 500 }))["records"].as_array().unwrap().iter()            .find(|row| find(&row["data"])).map(|row| row["data"]["@card"]["fields"].clone()).unwrap_or_else(|| panic!("a {table} card"))    };    let steps = card(DAY_TABLE, &|data| data["metric"] == "steps" && data["day"] == "2026-11-12")["reading"].clone();    assert_eq!((steps["label"].as_str(), steps["said"].as_str(), steps["unit"].as_str()), (Some("Steps"), Some("8,123"), Some("steps")), "{steps}");    assert_eq!((steps["usual"].as_str(), steps["top"].as_str()), (Some("usual 10,233"), Some("20,000")), "{steps}");    assert!((steps["dial"].as_f64().unwrap() - 8123.0 / 20000.0).abs() < 1e-9 && steps["usual_dial"].as_f64().unwrap() > steps["dial"].as_f64().unwrap());    let heart = card(DAY_TABLE, &|data| data["metric"] == "resting_heart_rate")["reading"].clone();    assert_eq!((heart["said"].as_str(), heart["unit"].as_str(), heart["range"].as_str()), (Some("61"), Some("bpm"), Some("58 to 64")), "{heart}");    assert!(heart.get("usual").is_none(), "no day before holds it: {heart}");    let asleep = card(DAY_TABLE, &|data| data["metric"] == "sleep_asleep")["reading"].clone();    assert_eq!(asleep["said"], "5 h 30 min", "{asleep}");    let stages: Vec<(&str, &str)> = asleep["night"]["stages"].as_array().unwrap().iter().map(|stage| (stage["stage"].as_str().unwrap(), stage["said"].as_str().unwrap())).collect();    assert_eq!(stages, [("deep", "1 h 0 min"), ("core", "3 h 0 min"), ("rem", "1 h 30 min")], "{asleep}");    let shares: f64 = asleep["night"]["stages"].as_array().unwrap().iter().map(|stage| stage["share"].as_f64().unwrap()).sum();    assert!((shares - 1.0).abs() < 1e-9);    let run = card(WORKOUT_TABLE, &|_| true)["workout"].clone();    assert_eq!((run["minutes"].as_str(), run["distance"].as_str(), run["energy"].as_str(), run["heart"].as_str()),               (Some("33 min"), Some("5.2 km"), Some("310 kcal"), Some("152 avg · 174 high bpm")), "{run}");    assert!(run["kind"].as_str().is_some_and(|kind| !kind.is_empty()) && run["started"].as_str().is_some_and(|said| said.contains("6:25")), "{run}");    let pressure = card(MEASUREMENT_TABLE, &|data| data["kind"] == "blood_pressure")["tag"].clone();    assert_eq!((pressure["said"].as_str(), pressure["unit"].as_str()), (Some("118/76"), Some("mmHg")), "{pressure}");    let weight = card(MEASUREMENT_TABLE, &|data| data["kind"] == "weight")["tag"].clone();    assert_eq!((weight["said"].as_str(), weight["unit"].as_str()), (Some("71.6"), Some("kg")), "{weight}");}/// RULE (health-ios, 20 Nov 2026): `health.held` says the first and last day this copy holds of the metrics a HealthKit type feeds (sleep's every stage), null for a type with none, so the phone reads those days again when HealthKit reports a deletion, which names no day.#[test]fn held_says_the_days_a_type_covers() {    let dir = tempfile::tempdir().expect("a temp container");    let handle = phone(&dir);    hold_a_key(&handle);    ask(&handle, "health.land", batch());    let steps = ask(&handle, "health.held", json!({ "type": STEPS }));    assert_eq!((steps["from"].clone(), steps["to"].clone()), (json!("2026-11-11"), json!("2026-11-12")), "{steps}");    let sleep = ask(&handle, "health.held", json!({ "type": SLEEP }));    assert_eq!((sleep["from"].clone(), sleep["to"].clone()), (json!("2026-11-12"), json!("2026-11-12")));    let none = ask(&handle, "health.held", json!({ "type": "HKQuantityTypeIdentifierDietaryWater" }));    assert_eq!((none["from"].clone(), none["to"].clone()), (Value::Null, Value::Null));    assert_eq!(dispatch(&handle, "health.held", &json!({ "type": "HKQuantityTypeIdentifierNothing" })).expect_err("not read").code, "bad_request");}/// Where the iPhone's HealthKit test reads `health.types` from.const TYPES_FIXTURE: &str = "apps/cotton/Tests/CottonHealthKitTests/Fixtures/health-types.json";fn types_fixture() -> String {    let mut text = serde_json::to_string_pretty(&json!({ "types": catalog::read_types() })).expect("types serialise");    text.push('\n');    text}/// Write the iPhone test's fixture: cargo test -p cotton-ffi --lib generate_health_types_fixture -- --ignored#[test]#[ignore = "writes the iPhone test's fixture; run when the catalogue changes"]fn generate_health_types_fixture() {    std::fs::write(cotton_store::manifest_dir().join("../..").join(TYPES_FIXTURE), types_fixture()).expect("the fixture is written");}/// RULE (health-ios, 20 Nov 2026): the iPhone holds every type the core asks for to HealthKit itself (`HealthTypesTests`: an identifier HealthKit does not know, a unit it cannot read or statistics a type cannot give raise inside HealthKit), from a fixture that is `health.types` as the core answers it; regenerate with generate_health_types_fixture.#[test]fn health_types_fixture_is_the_cores() {    let kept = std::fs::read_to_string(cotton_store::manifest_dir().join("../..").join(TYPES_FIXTURE)).expect("the fixture");    assert_eq!(kept, types_fixture(), "regenerate with generate_health_types_fixture");}