Apple Health (Salud): a per-profile ingest endpoint, and a tab that draws it
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
An iOS automation in Health Auto Export POSTs Apple Health to /api/vitals/ingest, and the new Salud tab (next to Plan) draws whatever arrived: steps, heart rate, sleep, weight, oxygen, workouts and every other metric HAE can export, grouped into cards with a trend, a sparkline and a 7/30/90/365-day range. Nothing on that screen is an input, and the watch's workouts stay out of the history on purpose — they carry no sets and no weights, so folding them into progression, PRs and the recovery model would be inventing data. The interesting part is duplicates. A five-minute automation re-sends overlapping windows: with Date Range "Today", appending would count a day of steps again on every run, and with "Since Last Sync", replacing would throw away everything but the last five minutes. So the endpoint decides per payload instead. Datapoints that sit on midnight are HAE's own day grouping, i.e. a *total*, and a day total replaces the day it names — re-sending the same day all afternoon converges on that day's total. Anything else is a real sample, identified by its instant plus its numbers and stored once, which is right for overlapping and disjoint windows alike. Every sync answers with a receipt (received / duplicates / stored), so a misconfigured automation is visible rather than silent, and day keys come from the date the phone wrote — never the server's clock, or every evening's steps would land on tomorrow. Per profile and private by construction. Each profile mints its own ingest key (Salud → ⚙), which is write-only: it can add to that one profile's health file and cannot read a single number back, so a key leaking out of a phone is a nuisance rather than a disclosure. It is its own credential, so rotating it disconnects a phone without signing anybody out anywhere. The data lives in data/vitals-<uid>.json, outside the synced state document, so a year of heart rate never round-trips through localStorage on every device, and it is bounded on write: 400 days per metric, a 72 h dedupe ledger, the newest 300 workouts. Two traps that only exist in production, both fixed here and both of which would have shipped broken. api/Dockerfile copies the modules server.js imports by name, and vitals.js was not on that list — a container that boots straight into ERR_MODULE_NOT_FOUND. And the web container's nginx capped every /api body at 5 MB, which a health export with Summarize Data off exceeds; that one route now gets the API's own 32 MB while every other path keeps 5 MB, with the shared proxy settings hoisted to server level so the two locations cannot drift apart. Coverage: vitals.js (13 tests — overlapping, disjoint, day-grouped, raw, heart rate, sleep, blood pressure, pruning, timezones), the routes against a real server (4 — isolation between profiles, a key that cannot read, ten re-sends changing nothing), the card model (18) and the screen (4). docs/HEALTH.md has the Health Auto Export settings and the merge table; the five endpoints are in api/openapi.yaml under the health tag, and website/api.html is rebuilt from it.
This commit is contained in:
1 parent
0819d03efb
commit
691e664d3f
22 files changed
+2897
-42
No files matched your search
@@ -0,0 +1,239 @@
|
||||
/* The health ingest endpoint, end to end against the real server: a five-minute automation must
|
||||
not double a day of steps, one profile's key must never reach another profile's file, and the
|
||||
ingest key must be good for exactly one thing (writing). */
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import net from 'node:net';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const SECRET = crypto.randomBytes(32).toString('hex');
|
||||
|
||||
// Same construction as server.js makeSession(): payload `uid:exp:sv`, HMAC-SHA256 over SECRET.
|
||||
function mintSession(uid, sv = 0) {
|
||||
const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
|
||||
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
|
||||
}
|
||||
const cookie = uid => ({ Cookie: `gymsid=${mintSession(uid)}` });
|
||||
|
||||
const freePort = () => new Promise(r => {
|
||||
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
|
||||
});
|
||||
|
||||
const USERS = [
|
||||
{ id: 'u_h1', name: 'One', created: '2026-01-01T00:00:00.000Z' },
|
||||
{ id: 'u_h2', name: 'Two', created: '2026-01-01T00:00:00.000Z' },
|
||||
// A disabled account keeps whatever key it had; the route has to refuse it anyway.
|
||||
{ id: 'u_h3', name: 'Three', created: '2026-01-01T00:00:00.000Z', disabled: true, healthKey: 'kghealth_' + 'x'.repeat(32) }
|
||||
];
|
||||
|
||||
async function startServer(t) {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-vitals-'));
|
||||
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
|
||||
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: USERS, creds: [], subs: [], invites: [] }));
|
||||
const port = await freePort();
|
||||
const child = spawn(process.execPath, ['server.js'], {
|
||||
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', AUDIT_LOG: '1' }
|
||||
});
|
||||
const h = { api: `http://127.0.0.1:${port}`, dataDir, log: '' };
|
||||
child.stdout.on('data', d => h.log += d);
|
||||
child.stderr.on('data', d => h.log += d);
|
||||
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
|
||||
let up = false;
|
||||
for (let i = 0; i < 100 && !up; i++) {
|
||||
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
|
||||
if (!up) await new Promise(r => setTimeout(r, 100));
|
||||
}
|
||||
assert.ok(up, `server never came up:\n${h.log}`);
|
||||
return h;
|
||||
}
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const yday = new Date(Date.now() - 86400000).toISOString().slice(0, 10);
|
||||
|
||||
/** One sync's worth of payload: a day-grouped step total, raw heart rate, and a workout. */
|
||||
const payload = () => ({
|
||||
data: {
|
||||
metrics: [
|
||||
{ name: 'step_count', units: 'count', data: [{ qty: 8000, date: `${today} 00:00:00 +0000` }] },
|
||||
{ name: 'heart_rate', units: 'bpm', data: [{ date: `${today} 09:00:00 +0000`, Min: 55, Avg: 70, Max: 95 }] },
|
||||
{ name: 'weight_body_mass', units: 'kg', data: [{ qty: 80.5, date: `${today} 07:30:00 +0000` }] }
|
||||
],
|
||||
workouts: [{
|
||||
name: 'Walking',
|
||||
start: `${today} 17:00:00 +0000`,
|
||||
end: `${today} 18:00:00 +0000`,
|
||||
activeEnergy: { qty: 210, units: 'kcal' }
|
||||
}]
|
||||
}
|
||||
});
|
||||
|
||||
const ingest = (h, key, body) => fetch(`${h.api}/api/vitals/ingest`, {
|
||||
method: 'POST',
|
||||
headers: key ? { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` } : { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
|
||||
test('the ingest key: created once, writes the profile\'s own file, and cannot read', async t => {
|
||||
const h = await startServer(t);
|
||||
const keyOf = async uid => (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie(uid) })).json()).key;
|
||||
|
||||
// Signed out, there is no key to mint.
|
||||
assert.equal((await fetch(`${h.api}/api/vitals/key`, { method: 'POST' })).status, 401);
|
||||
|
||||
const key1 = await keyOf('u_h1');
|
||||
assert.match(key1, /^kghealth_[A-Za-z0-9_-]{32}$/);
|
||||
assert.equal(await keyOf('u_h1'), key1, 'asking again returns the same key, not a new one');
|
||||
const key2 = await keyOf('u_h2');
|
||||
assert.notEqual(key1, key2);
|
||||
|
||||
// A payload with no key at all, and one with a made-up key.
|
||||
assert.equal((await ingest(h, '', payload())).status, 401);
|
||||
assert.equal((await ingest(h, 'kghealth_' + 'nope'.repeat(8), payload())).status, 401);
|
||||
|
||||
// One profile's key cannot write another profile's file, and a disabled account's key is dead.
|
||||
assert.equal((await ingest(h, USERS[2].healthKey, payload())).status, 401);
|
||||
|
||||
const first = await ingest(h, key1, payload());
|
||||
assert.equal(first.status, 200);
|
||||
const body1 = await first.json();
|
||||
assert.equal(body1.ok, true);
|
||||
assert.equal(body1.received.points, 3);
|
||||
assert.equal(body1.received.workouts, 1);
|
||||
assert.deepEqual(body1.stored, { metrics: 3, days: 3, workouts: 1 }, '3 metrics, one day each, one workout');
|
||||
|
||||
// The whole point: the same window again, ten times over, changes nothing.
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const again = await (await ingest(h, key1, payload())).json();
|
||||
assert.equal(again.received.points, 0, 'a re-sent window adds no points');
|
||||
assert.equal(again.stored.days, 3);
|
||||
}
|
||||
|
||||
// The ingest key is write-only: it can add to the file and never read it back.
|
||||
assert.equal((await fetch(`${h.api}/api/vitals`, { headers: { Authorization: `Bearer ${key1}` } })).status, 401, 'an ingest key must not read health data');
|
||||
|
||||
// Reading needs a session, and each profile sees only its own file.
|
||||
const read = async uid => (await (await fetch(`${h.api}/api/vitals`, { headers: cookie(uid) })).json());
|
||||
const mine = await read('u_h1');
|
||||
assert.equal(mine.ok, true);
|
||||
assert.equal(mine.key, key1);
|
||||
assert.deepEqual(Object.keys(mine.metrics).sort(), ['heart_rate', 'step_count', 'weight_body_mass']);
|
||||
assert.deepEqual(mine.metrics.step_count.days.map(d => d.f.qty.sum), [8000], 'the day total is 8000, not 88000');
|
||||
assert.equal(mine.metrics.heart_rate.days[0].f.Avg.avg, 70);
|
||||
assert.equal(mine.metrics.weight_body_mass.days[0].f.qty.last, 80.5);
|
||||
assert.equal(mine.workouts.length, 1);
|
||||
assert.equal(mine.workouts[0].durMin, 60);
|
||||
|
||||
const other = await read('u_h2');
|
||||
assert.deepEqual(other.metrics, {}, 'the other profile has no health data at all');
|
||||
assert.deepEqual(other.workouts, []);
|
||||
assert.equal(other.key, key2);
|
||||
|
||||
// Rotating invalidates the old key everywhere, and the key that replaces it works.
|
||||
const rotated = await (await fetch(`${h.api}/api/vitals/key/rotate`, { method: 'POST', headers: cookie('u_h1') })).json();
|
||||
assert.match(rotated.key, /^kghealth_/);
|
||||
assert.notEqual(rotated.key, key1);
|
||||
assert.equal((await ingest(h, key1, payload())).status, 401, 'the old key is dead');
|
||||
assert.equal((await ingest(h, rotated.key, payload())).status, 200);
|
||||
|
||||
// ...and rotating did not touch the other profile's key.
|
||||
assert.equal((await ingest(h, key2, payload())).status, 200);
|
||||
});
|
||||
|
||||
test('a payload that is not an export is refused; an export with nothing in it is not an error', async t => {
|
||||
const h = await startServer(t);
|
||||
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
|
||||
|
||||
const bad = await ingest(h, key, { hello: 'world' });
|
||||
assert.equal(bad.status, 400);
|
||||
assert.match((await bad.json()).error, /Health Auto Export/);
|
||||
// Nothing stored by the refusals.
|
||||
const after = await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json();
|
||||
assert.deepEqual(after.metrics, {});
|
||||
|
||||
// "Nothing to report" — the automation fired, the range was empty. 200, with zeroes.
|
||||
const empty = await ingest(h, key, { data: { metrics: [], workouts: [] } });
|
||||
assert.equal(empty.status, 200);
|
||||
const e = await empty.json();
|
||||
assert.equal(e.ok, true);
|
||||
assert.deepEqual(e.received, { metrics: 0, points: 0, workouts: 0, duplicates: 0 });
|
||||
assert.deepEqual(e.stored, { metrics: 0, days: 0, workouts: 0 });
|
||||
|
||||
// A metric that is selected but has no samples is equally a no-op, and it must not wipe what
|
||||
// is already stored: that is the shape the phone sends all night.
|
||||
await ingest(h, key, payload());
|
||||
const quiet = await ingest(h, key, { data: { metrics: [{ name: 'step_count', units: 'count', data: null }] } });
|
||||
assert.equal(quiet.status, 200);
|
||||
assert.deepEqual((await quiet.json()).stored, { metrics: 3, days: 3, workouts: 1 });
|
||||
});
|
||||
|
||||
test('a raw-sample automation accumulates a day without double counting, and a fresh day still lands', async t => {
|
||||
const h = await startServer(t);
|
||||
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
|
||||
const sample = (day, time, qty) => ({ name: 'step_count', units: 'count', data: [{ qty, date: `${day} ${time} +0000` }] });
|
||||
|
||||
// Date Range "Since Last Sync": five minutes at a time.
|
||||
for (const [time, qty] of [['09:00:00', 300], ['09:05:00', 700], ['09:10:00', 200]]) {
|
||||
assert.equal((await ingest(h, key, { data: { metrics: [sample(today, time, qty)] } })).status, 200);
|
||||
}
|
||||
const read = async () => (await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json());
|
||||
let doc = await read();
|
||||
const sum = d => d.metrics.step_count.days.reduce((n, day) => n + day.f.qty.sum, 0);
|
||||
assert.equal(sum(doc), 1200);
|
||||
|
||||
// Date Range "Today": the same three samples again, plus a new one.
|
||||
const todayWindow = { data: { metrics: [{ name: 'step_count', units: 'count', data: [
|
||||
{ qty: 300, date: `${today} 09:00:00 +0000` },
|
||||
{ qty: 700, date: `${today} 09:05:00 +0000` },
|
||||
{ qty: 200, date: `${today} 09:10:00 +0000` },
|
||||
{ qty: 1000, date: `${today} 09:15:00 +0000` }
|
||||
] }] } };
|
||||
const overlap = await (await ingest(h, key, todayWindow)).json();
|
||||
assert.equal(overlap.received.points, 1, 'only the new sample counts');
|
||||
assert.equal(overlap.received.duplicates, 3);
|
||||
doc = await read();
|
||||
assert.equal(sum(doc), 2200);
|
||||
|
||||
// The default range also carries yesterday, which must land as its own day.
|
||||
await ingest(h, key, { data: { metrics: [sample(yday, '09:00:00', 5000)] } });
|
||||
doc = await read();
|
||||
assert.equal(doc.metrics.step_count.days.length, 2);
|
||||
assert.equal(doc.metrics.step_count.days[0].day, yday);
|
||||
|
||||
// ...and a window narrowing to one day is still one day.
|
||||
const narrow = await (await fetch(`${h.api}/api/vitals?days=1`, { headers: cookie('u_h1') })).json();
|
||||
assert.deepEqual(narrow.metrics.step_count.days.map(d => d.day), [today]);
|
||||
});
|
||||
|
||||
test('DELETE /api/vitals wipes the health file and leaves the account, the key and the workouts alone', async t => {
|
||||
const h = await startServer(t);
|
||||
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
|
||||
await ingest(h, key, payload());
|
||||
|
||||
// A workout logged in the app lives in the state document, not in the health file.
|
||||
const state = { unit: 'kg', lang: 'es', workouts: [{ id: 'w1', d: today, name: 'Full body', entries: [] }], routines: [] };
|
||||
const put = await fetch(`${h.api}/api/data`, { method: 'PUT', headers: { ...cookie('u_h1'), 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' }, body: JSON.stringify({ state }) });
|
||||
assert.equal(put.status, 200);
|
||||
|
||||
assert.equal((await fetch(`${h.api}/api/vitals`, { method: 'DELETE' })).status, 401, 'a session is required');
|
||||
assert.equal((await fetch(`${h.api}/api/vitals`, { method: 'DELETE', headers: cookie('u_h2') })).status, 200, 'wiping an empty profile is fine');
|
||||
|
||||
assert.equal((await fetch(`${h.api}/api/vitals`, { method: 'DELETE', headers: cookie('u_h1') })).status, 200);
|
||||
const after = await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json();
|
||||
assert.deepEqual(after.metrics, {});
|
||||
assert.deepEqual(after.workouts, []);
|
||||
assert.equal(after.key, key, 'the key survives, so the phone does not need re-configuring');
|
||||
|
||||
const data = await (await fetch(`${h.api}/api/data`, { headers: cookie('u_h1') })).json();
|
||||
assert.equal(data.state.workouts.length, 1, 'the workout history is untouched');
|
||||
|
||||
// The phone can simply sync again.
|
||||
assert.equal((await ingest(h, key, payload())).status, 200);
|
||||
assert.equal((await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json()).metrics.step_count.days.length, 1);
|
||||
});
|
||||
@@ -0,0 +1,288 @@
|
||||
/* The merge rule is the whole point of vitals.js: an automation that runs every five minutes
|
||||
must not turn a day of steps into three days of steps. These tests are all about that, plus
|
||||
the shapes HAE actually sends (day-grouped totals, raw samples, Min/Avg/Max heart rate,
|
||||
aggregated and segmented sleep, blood pressure, a metric that is selected but empty).
|
||||
|
||||
Every merge is given an explicit `now`, because the dedupe ledger is pruned against the wall
|
||||
clock: a test that let the real clock in would delete its own fixtures the moment they were a
|
||||
few days old, and start passing for the wrong reason. */
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
parsePayload, mergeVitals, vitalsSeries, emptyVitals, parseHaeDate, normalizeDoc,
|
||||
RETENTION_DAYS, LEDGER_MS
|
||||
} from '../vitals.js';
|
||||
|
||||
const NOW = Date.parse('2026-05-01T23:30:00Z');
|
||||
const merge = (doc, payload, now = NOW) => mergeVitals(doc, payload, now);
|
||||
const at = (day, time = '00:00:00', off = '+0000') => `${day} ${time} ${off}`;
|
||||
/** One metric, one payload. */
|
||||
const metric = (name, units, data) => ({ data: { metrics: [{ name, units, data }] } });
|
||||
|
||||
/* ---------- parsing ---------- */
|
||||
|
||||
test('parses both HAE date spellings, including the 12-hour one with a narrow no-break space', () => {
|
||||
const a = parseHaeDate('2026-05-01 13:04:05 +0200');
|
||||
assert.equal(a.day, '2026-05-01');
|
||||
assert.equal(a.time, '13:04:05');
|
||||
assert.equal(a.ms, Date.parse('2026-05-01T13:04:05+02:00'));
|
||||
|
||||
// U+202F between the time and the meridiem — what HAE writes on a 12-hour phone.
|
||||
const b = parseHaeDate('2026-05-01 1:04:05\u202fPM -0700');
|
||||
assert.equal(b.time, '13:04:05');
|
||||
assert.equal(b.ms, Date.parse('2026-05-01T13:04:05-07:00'));
|
||||
|
||||
// The two hours a naive modulo gets wrong.
|
||||
assert.equal(parseHaeDate('2026-05-01 12:00:00\u202fAM +0000').time, '00:00:00');
|
||||
assert.equal(parseHaeDate('2026-05-01 12:30:00\u202fPM +0000').time, '12:30:00');
|
||||
// No offset at all means UTC, not "whatever the server is".
|
||||
assert.equal(parseHaeDate('2026-05-01 08:00:00').ms, Date.parse('2026-05-01T08:00:00Z'));
|
||||
assert.equal(parseHaeDate('not a date'), null);
|
||||
assert.equal(parseHaeDate('2026-13-45 08:00:00 +0000'), null);
|
||||
assert.equal(parseHaeDate(undefined), null);
|
||||
});
|
||||
|
||||
test('parsePayload accepts v2 (wrapped in data), the older flat shape, and drops empty metrics', () => {
|
||||
const v2 = parsePayload({
|
||||
data: {
|
||||
metrics: [
|
||||
{ name: 'step_count', units: 'count', data: [{ qty: 100, date: at('2026-05-01', '09:00:00') }] },
|
||||
{ name: 'basal_body_temperature', units: 'degC', data: null }
|
||||
],
|
||||
workouts: []
|
||||
}
|
||||
});
|
||||
assert.equal(v2.metrics.length, 2);
|
||||
assert.equal(v2.metrics[1].points.length, 0, 'a selected-but-empty metric parses to no points');
|
||||
|
||||
const flat = parsePayload({ metrics: [{ name: 'weight_body_mass', units: 'kg', data: [{ qty: 80, date: at('2026-05-01', '07:00:00') }] }] });
|
||||
assert.equal(flat.metrics[0].points[0].fields.qty, 80);
|
||||
|
||||
assert.throws(() => parsePayload({ hello: 'world' }), e => e.code === 'shape');
|
||||
assert.throws(() => parsePayload(null), e => e.code === 'shape');
|
||||
assert.throws(() => parsePayload({ data: { metrics: [], workouts: [] } }), e => e.code === 'empty');
|
||||
// A datapoint with no readable date, or with no numbers at all, is not a datapoint.
|
||||
const junk = parsePayload(metric('foo', 'x', [{ qty: 1, date: 'nonsense' }, { date: at('2026-05-01') }]));
|
||||
assert.equal(junk.metrics[0].points.length, 0);
|
||||
});
|
||||
|
||||
/* ---------- the merge rule ---------- */
|
||||
|
||||
test('raw samples: disjoint windows accumulate, overlapping ones do not double count', () => {
|
||||
const p = (t, qty) => ({ qty, date: at('2026-05-01', t) });
|
||||
|
||||
// "Since Last Sync": each run carries only what happened since the last one.
|
||||
let doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [p('09:00:00', 300), p('09:05:00', 700)]))).doc;
|
||||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1000);
|
||||
const inc = merge(doc, parsePayload(metric('step_count', 'count', [p('09:10:00', 200), p('09:15:00', 800)])));
|
||||
doc = inc.doc;
|
||||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 2000, 'new samples add on');
|
||||
assert.equal(inc.stats.points, 2);
|
||||
|
||||
// "Today": every run re-sends the whole day, with the two samples since the last run added.
|
||||
const today = metric('step_count', 'count', [
|
||||
p('09:00:00', 300), p('09:05:00', 700), p('09:10:00', 200), p('09:15:00', 800),
|
||||
p('09:20:00', 1000), p('09:25:00', 500)
|
||||
]);
|
||||
const first = merge(doc, parsePayload(today));
|
||||
assert.equal(first.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 3500, 'only the two new samples count');
|
||||
assert.equal(first.stats.points, 2);
|
||||
assert.equal(first.stats.duplicates, 4);
|
||||
|
||||
const again = merge(first.doc, parsePayload(today));
|
||||
assert.equal(again.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 3500, 're-sending changes nothing');
|
||||
assert.equal(again.stats.points, 0);
|
||||
assert.equal(again.stats.duplicates, 6);
|
||||
});
|
||||
|
||||
test('day-grouped payloads replace the day: a growing total never adds up', () => {
|
||||
const grouped = sum => metric('step_count', 'count', [{ qty: sum, date: at('2026-05-01') }]);
|
||||
let doc = merge(emptyVitals(), parsePayload(grouped(1200))).doc;
|
||||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1200);
|
||||
|
||||
// Ten more syncs through the day, each carrying the day's total so far — "Time Grouping: Days".
|
||||
for (const total of [1400, 2600, 4100, 9800]) doc = merge(doc, parsePayload(grouped(total))).doc;
|
||||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800, 'replaced, not accumulated');
|
||||
|
||||
const same = merge(doc, parsePayload(grouped(9800)));
|
||||
assert.equal(same.stats.duplicates, 1);
|
||||
assert.equal(same.stats.points, 0, 'the same total again is a no-op');
|
||||
assert.equal(same.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800);
|
||||
|
||||
// A day-grouped payload covering several days corrects each of them independently.
|
||||
const multi = merge(same.doc, parsePayload(metric('step_count', 'count', [
|
||||
{ qty: 9800, date: at('2026-05-01') }, { qty: 3000, date: at('2026-04-30') }
|
||||
])));
|
||||
assert.equal(multi.doc.metrics.step_count.days['2026-04-30'].f.qty.sum, 3000);
|
||||
assert.equal(multi.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800);
|
||||
});
|
||||
|
||||
test('a day total and raw samples for the same day are kept apart by their own payload shape', () => {
|
||||
// Two metrics in one payload, one grouped by day and one raw: each takes its own branch.
|
||||
const body = {
|
||||
data: {
|
||||
metrics: [
|
||||
{ name: 'step_count', units: 'count', data: [{ qty: 5000, date: at('2026-05-01') }] },
|
||||
{ name: 'resting_heart_rate', units: 'bpm', data: [{ qty: 52, date: at('2026-05-01', '06:30:00') }] }
|
||||
]
|
||||
}
|
||||
};
|
||||
const { doc } = merge(emptyVitals(), parsePayload(body));
|
||||
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 5000);
|
||||
assert.equal(doc.metrics.resting_heart_rate.days['2026-05-01'].f.qty.sum, 52);
|
||||
});
|
||||
|
||||
test('the day key is the phone\'s own date, not the server\'s', () => {
|
||||
// 23:30 in Manila is the previous day in UTC. The sample belongs to the phone's day.
|
||||
const { doc } = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
|
||||
{ qty: 500, date: at('2026-05-01', '23:30:00', '+0800') }
|
||||
])));
|
||||
assert.deepEqual(Object.keys(doc.metrics.step_count.days), ['2026-05-01']);
|
||||
});
|
||||
|
||||
/* ---------- the shapes HAE actually sends ---------- */
|
||||
|
||||
test('heart rate keeps Min/Avg/Max per day instead of pretending they are one number', () => {
|
||||
const body = metric('heart_rate', 'bpm', [
|
||||
{ date: at('2026-05-01', '09:00:00'), Min: 58, Avg: 72, Max: 96, source: 'Apple Watch' },
|
||||
{ date: at('2026-05-01', '10:00:00'), Min: 55, Avg: 68, Max: 88, source: 'Apple Watch' }
|
||||
]);
|
||||
const { doc } = merge(emptyVitals(), parsePayload(body));
|
||||
const day = doc.metrics.heart_rate.days['2026-05-01'];
|
||||
assert.equal(day.f.Avg.n, 2);
|
||||
assert.equal(Math.round(day.f.Avg.sum), 140);
|
||||
assert.equal(day.f.Min.min, 55);
|
||||
assert.equal(day.f.Max.max, 96);
|
||||
assert.deepEqual(doc.metrics.heart_rate.sources, ['Apple Watch']);
|
||||
});
|
||||
|
||||
test('sleep: both the aggregated night and the segmented one land as hours per day', () => {
|
||||
const aggregated = metric('sleep_analysis', 'hr', [{
|
||||
date: at('2026-05-01', '07:00:00'),
|
||||
sleepStart: at('2026-04-30', '23:10:00'), sleepEnd: at('2026-05-01', '06:55:00'),
|
||||
inBed: 8.2, asleep: 7.4, core: 4.1, deep: 1.2, rem: 2.1, awake: 0.8, source: 'Apple Watch'
|
||||
}]);
|
||||
const { doc } = merge(emptyVitals(), parsePayload(aggregated));
|
||||
// Keyed by the day the metric's own `date` names — the morning you woke up.
|
||||
assert.equal(doc.metrics.sleep_analysis.days['2026-05-01'].f.asleep.last, 7.4);
|
||||
assert.equal(doc.metrics.sleep_analysis.days['2026-05-01'].f.deep.last, 1.2);
|
||||
|
||||
const segments = [
|
||||
{ startDate: at('2026-05-01', '22:10:00'), endDate: at('2026-05-01', '22:50:00'), qty: 0.67, value: 'asleepCore' },
|
||||
{ startDate: at('2026-05-01', '23:10:00'), endDate: at('2026-05-01', '23:25:00'), qty: 1.33, value: 'asleepDeep' }
|
||||
];
|
||||
const seg = merge(emptyVitals(), parsePayload(metric('sleep_analysis', 'hr', segments))).doc;
|
||||
// Segments carry no `date`, only startDate/endDate, so the day comes from the segment start.
|
||||
assert.equal(seg.metrics.sleep_analysis.days['2026-05-01'].f.qty.sum, 2);
|
||||
assert.equal(seg.metrics.sleep_analysis.days['2026-05-01'].f.qty.n, 2);
|
||||
|
||||
const repeat = merge(seg, parsePayload(metric('sleep_analysis', 'hr', segments)));
|
||||
assert.equal(repeat.stats.duplicates, 2, 'the same segments again are the same segments');
|
||||
assert.equal(repeat.doc.metrics.sleep_analysis.days['2026-05-01'].f.qty.sum, 2, 'and do not add up twice');
|
||||
});
|
||||
|
||||
test('blood pressure keeps both numbers, and an unknown metric is stored rather than dropped', () => {
|
||||
const body = {
|
||||
data: {
|
||||
metrics: [
|
||||
{ name: 'blood_pressure_systolic', units: 'mmHg', data: [{ date: at('2026-05-01', '08:00:00'), systolic: 128, diastolic: 82 }] },
|
||||
{ name: 'walking_steadiness', units: '%', data: [{ date: at('2026-05-01', '08:00:00'), qty: 91 }] }
|
||||
]
|
||||
}
|
||||
};
|
||||
const { doc } = merge(emptyVitals(), parsePayload(body));
|
||||
assert.equal(doc.metrics.blood_pressure_systolic.days['2026-05-01'].f.systolic.last, 128);
|
||||
assert.equal(doc.metrics.blood_pressure_systolic.days['2026-05-01'].f.diastolic.last, 82);
|
||||
assert.equal(doc.metrics.walking_steadiness.days['2026-05-01'].f.qty.last, 91);
|
||||
});
|
||||
|
||||
/* ---------- workouts ---------- */
|
||||
|
||||
test('workouts dedupe on name+start+end, newest first, and a re-send adds nothing', () => {
|
||||
const w = (name, start, end, energy) => ({
|
||||
name, start, end,
|
||||
activeEnergy: { qty: energy, units: 'kcal' },
|
||||
distance: { qty: 3.2, units: 'km' },
|
||||
heartRateData: [{ date: at('2026-05-01', '18:00:00'), Avg: 128 }, { date: at('2026-05-01', '18:05:00'), Avg: 136, Max: 172 }]
|
||||
});
|
||||
const body = {
|
||||
data: {
|
||||
workouts: [
|
||||
w('Walking', at('2026-05-01', '17:00:00'), at('2026-05-01', '18:00:00'), 210),
|
||||
w('Functional Strength Training', at('2026-05-01', '07:00:00'), at('2026-05-01', '07:45:00'), 320)
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
const first = merge(emptyVitals(), parsePayload(body));
|
||||
assert.equal(first.stats.workouts, 2);
|
||||
assert.equal(first.doc.workouts[0].name, 'Walking', 'newest first (17:00 after 07:00)');
|
||||
assert.equal(first.doc.workouts[0].durMin, 60);
|
||||
assert.equal(first.doc.workouts[0].fields.activeEnergy.qty, 210);
|
||||
assert.equal(first.doc.workouts[0].avgHr, 132, 'average of the heart-rate samples');
|
||||
assert.equal(first.doc.workouts[0].maxHr, 172);
|
||||
assert.equal(first.doc.workouts[1].name, 'Functional Strength Training');
|
||||
assert.equal(first.doc.workouts[1].fields.activeEnergy.qty, 320);
|
||||
|
||||
const again = merge(first.doc, parsePayload(body));
|
||||
assert.equal(again.stats.workouts, 0);
|
||||
assert.equal(again.stats.duplicates, 2);
|
||||
assert.equal(again.doc.workouts.length, 2);
|
||||
});
|
||||
|
||||
/* ---------- housekeeping ---------- */
|
||||
|
||||
test('the dedupe ledger and the day buckets are both pruned, so the file stays bounded', () => {
|
||||
const first = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:00:00') }])), NOW);
|
||||
const seen = first.doc.metrics.step_count.seen;
|
||||
assert.equal(Object.keys(seen).length, 1);
|
||||
assert.equal(seen[Object.keys(seen)[0]], Date.parse('2026-05-01T09:00:00Z'));
|
||||
|
||||
// A sync a week later: last week's sample can no longer be a repeat, so its ledger row goes
|
||||
// while the day it belongs to stays.
|
||||
const later = merge(first.doc, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-08', '09:00:00') }])), Date.parse('2026-05-08T12:00:00Z')).doc;
|
||||
assert.equal(Object.keys(later.metrics.step_count.seen).length, 1, 'the stale ledger row is gone');
|
||||
assert.deepEqual(Object.keys(later.metrics.step_count.days), ['2026-05-01', '2026-05-08']);
|
||||
|
||||
// Days past retention are dropped.
|
||||
const old = new Date(NOW - (RETENTION_DAYS + 30) * 86400000).toISOString().slice(0, 10);
|
||||
const withOld = normalizeDoc({ metrics: { step_count: { days: { [old]: { n: 1, f: { qty: { n: 1, sum: 1, min: 1, max: 1, last: 1 } } } } } } });
|
||||
const pruned = merge(withOld, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:00:00') }]))).doc;
|
||||
assert.equal(pruned.metrics.step_count.days[old], undefined);
|
||||
assert.ok(LEDGER_MS === 72 * 3600 * 1000 && RETENTION_DAYS > 365);
|
||||
});
|
||||
|
||||
test('normalizeDoc survives a hand-edited or half-written file', () => {
|
||||
const d = normalizeDoc({ metrics: { step_count: null, heart_rate: { days: 'nope', units: 7, sources: 'x' } }, workouts: 'nope' });
|
||||
assert.deepEqual(d.workouts, []);
|
||||
assert.deepEqual(Object.keys(d.metrics), ['heart_rate']);
|
||||
assert.deepEqual(d.metrics.heart_rate.days, {});
|
||||
assert.deepEqual(d.metrics.heart_rate.sources, []);
|
||||
assert.equal(d.metrics.heart_rate.units, '');
|
||||
assert.deepEqual(normalizeDoc(null).metrics, {});
|
||||
});
|
||||
|
||||
/* ---------- reading it back ---------- */
|
||||
|
||||
test('vitalsSeries gives per-field totals, averages and a window, oldest day first', () => {
|
||||
const body = {
|
||||
data: {
|
||||
metrics: [
|
||||
{ name: 'step_count', units: 'count', data: [{ qty: 4000, date: at('2026-04-30') }, { qty: 6000, date: at('2026-05-01') }] },
|
||||
{ name: 'heart_rate', units: 'bpm', data: [{ date: at('2026-05-01', '09:00:00'), Min: 55, Avg: 70, Max: 90 }] }
|
||||
],
|
||||
workouts: [{ name: 'Walking', start: at('2026-05-01', '09:00:00'), end: at('2026-05-01', '09:30:00'), activeEnergy: { qty: 100, units: 'kcal' } }]
|
||||
}
|
||||
};
|
||||
const { doc } = merge(emptyVitals(), parsePayload(body));
|
||||
const s = vitalsSeries(doc, { days: 90, now: NOW });
|
||||
assert.deepEqual(s.metrics.step_count.days.map(d => d.day), ['2026-04-30', '2026-05-01']);
|
||||
assert.deepEqual(s.metrics.step_count.days.map(d => d.f.qty.sum), [4000, 6000]);
|
||||
assert.equal(s.metrics.heart_rate.days[0].f.Avg.avg, 70);
|
||||
assert.equal(s.metrics.step_count.units, 'count');
|
||||
assert.equal(s.workouts.length, 1);
|
||||
|
||||
// A one-day window keeps only the day inside it.
|
||||
const narrow = vitalsSeries(doc, { days: 1, now: NOW });
|
||||
assert.deepEqual(narrow.metrics.step_count.days.map(d => d.day), ['2026-05-01']);
|
||||
});
|
||||
Reference in new issue
Block a user