Files
kuentagym/api/vitals.js
T
dsantillan f7b884be81
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
Salud: dos dispositivos, una caminata — el cubo guarda sus fuentes y muestra una
"En mi Apple Salud me dice 946 y en opengym 1700 y pico", y antes 499 contra 840. Ese factor —1,80 y
1,68— es la prueba: una suma de valores acumulados daría 12× o 24× al final del día, no 1,8×. Lo que
da 1,8× es **sumar dos dispositivos**. HealthKit de-duplica la misma caminata entre el Apple Watch y
el iPhone, la app Salud la cuenta una vez, y un payload que trae los dos como puntos separados no la
ha de-duplicado nadie. La tarjeta estaba leyendo dos cosas, exactamente como se sospechó.

Ahora cada cubo —una hora, y el día cuando el teléfono manda un total por día— **guarda sus fuentes
por separado y muestra una**: la que más reportó en ese cubo, después la más nueva, después la más
grande. No es una suma, no es un promedio y no es "el máximo": es el agregado propio de un
dispositivo, o sea el número que ese dispositivo muestra.

Y la elección es **por hora**, no por día, que es lo que hace correctas las dos situaciones a la vez:
una hora que solo registró el teléfono es del teléfono (no se pierde nada), y una hora que
registraron los dos se cuenta una vez (no se duplica nada). Con la elección por día, el caso
"caminata sin el reloj" se habría perdido.

Tres cosas que había que cuidar y están cubiertas por tests:

  · **Un payload sin `source`** —casi todos, y en iOS 27+ es lo normal para datos acumulados— vive en
    una sola fuente sin nombre, así que un cubo es el cubo y nada cambia para quien tiene un solo
    dispositivo. Los 22 tests que ya existían pasaron sin tocarlos, que es la evidencia de eso.
  · **Un cubo guardado antes de esto** se adopta como la fuente sin nombre en vez de tirarse: una
    actualización no pierde el día que ya tenía, y las dos compiten por cantidad de muestras.
  · **Reemplazar una hora borra solo la de esa fuente.** La hora en curso crece en cada envío de un
    automatismo de cinco minutos y por eso se reemplaza, pero reemplazar el cubo entero es cómo un
    dispositivo borraría en silencio el reporte del otro — que es lo contrario de lo que esto hace.

La hoja lo dice al final: `N días con datos · Apple Watch, iPhone · se usa Apple Watch`, para que el
número se pueda cotejar contra el dispositivo que lo produjo.

Cinco tests del merge más el orden de desempate. Mutation-check de las dos mitades: sin aplicar la
fuente ganadora fallan cuatro, y si reemplazar una hora borra la del otro dispositivo fallan tres.
API 267 en verde, frontend 1705, build OK.
2026-09-23 18:29:56 -04:00

833 lines
40 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* vitals.js — Apple Health ingestion (Health Auto Export → KuentaGYM).
*
* The phone runs a "REST API" automation in Health Auto Export (HAE) that POSTs its JSON export
* to /api/vitals/ingest. This module is the whole of what happens to that payload: parse, fold
* into per-day buckets, merge with what is already stored, prune. Nothing here touches the
* filesystem or the network — server.js owns the file, this owns the arithmetic, which is what
* makes it testable without a phone (see test/vitals.test.js).
*
* ── Why this is not just "append the samples" ───────────────────────────────────────────────
*
* A five-minute automation re-sends overlapping windows: with Date Range = "Today" or the
* default ("previous day + today so far") every sync carries the whole day again, so appending
* would double every step count. With Date Range = "Since Last Sync" the windows are disjoint
* and *replacing* would throw away everything but the last five minutes. The same receiver has to
* survive both without knowing which one the phone is configured for, so the rule is chosen per
* payload from the payload's own shape:
*
* dayAggregated() every datapoint sits exactly on midnight
* → HAE already grouped by day ("Time Grouping: Days"), and a grouped day is a *total*:
* a day total only ever replaces another one. Wait, "replaces" is wrong for the current
* day, which legitimately grows all day long — and that is precisely why replacement is
* right here: the newer, larger total is the better answer, and re-sending the same
* number is a no-op. Idempotent by construction, no ledger needed.
*
* hourAggregated() every datapoint sits exactly on the hour ("Time Grouping: Hours")
* → the *hour* bucket is replaced, for the same reason a day total is: the hour in progress
* is re-sent with a larger value on every run, so union would count 512 steps as
* 512 + 900 + 1340. The day is then recomputed as the sum of its hours (deriveDay), which
* is what keeps the day number and the hourly detail from ever disagreeing.
*
* otherwise real timestamps (raw samples, or grouped by minute/second)
* → union: a sample is identified by its instant plus its numbers and seen once. A repeat
* is skipped, a genuinely new sample is added. Overlapping and disjoint windows both
* come out right, because "have I seen this exact sample" is the question that does not
* depend on the window at all.
*
* The one configuration neither rule can fully rescue is grouping by *minutes* with an
* overlapping window: the minute still in progress is re-sent with a larger value each time, so
* it is a new sample by the union rule and its value is added twice. The error is bounded by one
* partial minute of the cheapest metric (a handful of steps, a few hundredths of a kcal) and the
* setup steps in docs/HEALTH.md say to group by Days or Hours. Being explicit about that beats a
* "smart" rule that silently miscounts a whole day.
*
* ── Why the hours are kept at all ────────────────────────────────────────────────────────────
*
* A day total is the number people quote and the one thing a day is worth here, but it is also a
* dead end: "8,123 steps today" is a figure you cannot look into, and the phone that sent it sent
* 288 readings to build it. Grouping by Hours is the setting that keeps that shape — each hour
* arrives as its own bucket with a real instant — and the buckets are stored beside the day, so
* tapping a card can show the day hour by hour. Days grouping sends one point per metric per day
* and there is no intraday detail in the payload to keep; that is a property of the automation,
* not of this file, and the Salud screen says so rather than showing an empty hour list.
*
* ── What a stored document looks like ────────────────────────────────────────────────────────
*
* Buckets are **per day, keyed by the day the phone wrote**, never by the server's own timezone:
* HAE stamps each sample with the phone's local offset, so grouping by a server-local date would
* slide every evening's steps into the next day for anyone not on UTC. The day key is therefore
* taken straight from the payload's own date text.
*
* {
* v: 1, updatedAt: 1699999999999,
* last: { ts, metrics, points, duplicates, workouts, source },
* metrics: {
* step_count: {
* units: 'count', sources: ['iPhone'],
* days: { '2026-05-01': { n: 288, lastTs: 1699999999999,
* f: { qty: { sum, min, max, last, n } },
* h: { '13': { n: 12, lastTs: …, f: { qty: {…} } } } } },
* seen: { '2026-05-01 13:05:00 +0200|qty:12': 1699999999999 }
* }
* },
* workouts: [ { name, start, end, durMin, fields: { activeEnergy: { qty, units } } } ]
* }
*
* Numeric fields are kept generically (`f`) rather than decoded per metric, because a health
* catalogue is wide and keeps growing: heart_rate carries Min/Avg/Max, blood_pressure carries
* systolic/diastolic, sleep carries asleep/inBed/core/deep/rem — and a metric this code has never
* heard of still lands in `f` under whatever HAE called it. Which field a *card* shows is a
* presentation decision, and it lives in frontend/src/lib/vitals-view.js with the labels. That
* split is deliberate: it means a metric added to HAE next year shows up without a server change.
*/
export const VITALS_VERSION = 1;
/** Ledger lives 72 h: the longest overlap a sane automation cadence can span. */
export const LEDGER_MS = 72 * 3600 * 1000;
/** Days kept per metric. A little over a year, so "same day last year" still exists. */
export const RETENTION_DAYS = 400;
export const MAX_WORKOUTS = 300;
/**
* Days whose *hourly* buckets are kept. Detail is what makes a file grow (24 buckets × every
* metric × every day), and it is only interesting for the last few days: "what did this morning
* look like" is a question about today and yesterday, never about March. The day aggregates
* survive this and live RETENTION_DAYS.
*/
export const HOURS_KEPT_DAYS = 7;
/**
* How long a day the phone totalled itself stays the day's number while hours keep arriving. In the
* shape this exists for the total is re-sent on every sync, so it never goes stale; an automation
* that was reconfigured to hours only stops sending it, and after this the sum of the hours takes
* over instead of the number freezing for the rest of the day.
*/
export const DECLARED_STALE_MS = 6 * 3600 * 1000;
/** Sources remembered per metric — decorative, but it answers "which watch sent this?" */
const MAX_SOURCES = 4;
const MAX_LEDGER_KEYS = 20000; // hard ceiling; the time-based prune is the real bound
export function emptyVitals() {
return { v: VITALS_VERSION, updatedAt: 0, last: null, metrics: {}, workouts: [] };
}
/** A stored document that is missing pieces (hand-edited, or written by an older version). */
export function normalizeDoc(doc) {
const d = doc && typeof doc === 'object' && !Array.isArray(doc) ? doc : {};
const out = {
v: VITALS_VERSION,
updatedAt: Number(d.updatedAt) || 0,
last: d.last && typeof d.last === 'object' ? d.last : null,
metrics: {},
workouts: Array.isArray(d.workouts) ? d.workouts.filter(w => w && typeof w === 'object') : [],
// The last sync's receipt per metric (see receiptFor): replaced every time, never read by
// anything that computes a number.
shape: d.shape && typeof d.shape === 'object' && !Array.isArray(d.shape) ? d.shape : {}
};
const metrics = d.metrics && typeof d.metrics === 'object' && !Array.isArray(d.metrics) ? d.metrics : {};
for (const [name, m] of Object.entries(metrics)) {
if (!m || typeof m !== 'object') continue;
const days = m.days && typeof m.days === 'object' && !Array.isArray(m.days) ? m.days : {};
out.metrics[name] = {
units: typeof m.units === 'string' ? m.units : '',
sources: Array.isArray(m.sources) ? m.sources.filter(s => typeof s === 'string').slice(0, MAX_SOURCES) : [],
days,
seen: m.seen && typeof m.seen === 'object' && !Array.isArray(m.seen) ? m.seen : {}
};
}
return out;
}
/* ---------- parsing ---------- */
// HAE writes "2021-12-24 00:04:00 +0800", or "2021-12-24 3:04:05 PM -0700" when the phone is on
// a 12-hour clock — and that separator is U+202F (narrow no-break space), not a plain space, which
// is exactly the kind of thing that turns into NaN three weeks later. Both are normalised below.
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{1,2}):(\d{2}):(\d{2})(?:[\s\u202f\u00a0]*([AaPp])\.?[Mm]\.?)?(?:[\s\u202f\u00a0]*([+-]\d{2}):?(\d{2})|Z)?$/;
/**
* Parse one HAE timestamp.
* @returns {{ms:number, day:string, time:string, raw:string}|null} `day` is the date the phone
* wrote (its own local day), `time` is "HH:MM:SS" in 24-hour form, `ms` an epoch instant.
*/
export function parseHaeDate(value) {
if (typeof value !== 'string') return null;
const raw = value.trim();
const m = DATE_RE.exec(raw);
if (!m) return null;
const [, y, mo, d, h, mi, s, ap, offH, offM] = m;
let hour = Number(h);
if (ap) {
// 12 AM is 00, 12 PM is 12 — the two hours the naive modulo gets wrong.
const pm = ap.toLowerCase() === 'p';
if (hour === 12) hour = pm ? 12 : 0;
else if (pm) hour += 12;
}
if (hour > 23 || Number(mi) > 59 || Number(s) > 59) return null;
const time = `${String(hour).padStart(2, '0')}:${mi}:${s}`;
const day = `${y}-${mo}-${d}`;
const offset = offH ? `${offH}:${offM || '00'}` : 'Z'; // no offset in the payload means UTC
const ms = Date.parse(`${day}T${time}${offset}`);
if (!Number.isFinite(ms)) return null;
return { ms, day, time, raw };
}
/** True when HAE grouped this datapoint onto a boundary rather than sampling it in real time. */
const isMidnight = t => t.time === '00:00:00';
/** ...and onto an hour: the shape "Time Grouping: Hours" produces, so each bucket is a total. */
const onTheHour = t => t.time.slice(3) === '00:00';
// Fields on a datapoint that are not measurements. Everything else numeric is kept, so a metric
// this file has never seen still stores its numbers instead of being dropped.
const NON_VALUE_KEYS = new Set(['date', 'startDate', 'endDate', 'sleepStart', 'sleepEnd', 'inBedStart', 'inBedEnd', 'source', 'Source', 'value']);
const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null);
/** The numeric measurements on one datapoint, keyed exactly as HAE named them. */
export function fieldsOf(point) {
const out = {};
for (const [k, v] of Object.entries(point)) {
if (NON_VALUE_KEYS.has(k)) continue;
const n = num(v);
if (n != null) out[k] = n;
}
return out;
}
/** The instant of a datapoint: metrics carry `date`, sleep carries `sleepStart`/`startDate`. */
function instantOf(point) {
for (const k of ['date', 'sleepStart', 'startDate', 'inBedStart']) {
const t = parseHaeDate(point[k]);
if (t) return t;
}
return null;
}
const str = v => (typeof v === 'string' ? v : '');
/**
* Validate and normalise an HAE export body into what mergeVitals() expects.
*
* Version 2 wraps everything in `data`; the older flat shape puts the arrays at the top level and
* is accepted too, since it costs one line and a user pasting an old export should not get a
* blank page. A metric with `data: null` is normal (HAE sends the metric because it is selected
* but has no samples) and is dropped here rather than stored as an empty day.
*
* @throws {Error} with `.code` of 'shape' (not an export at all) or 'empty' (an export with
* nothing in it) — server.js turns both into a 400 that names the problem.
*/
export function parsePayload(body) {
if (!body || typeof body !== 'object' || Array.isArray(body)) throw err('shape');
const data = body.data && typeof body.data === 'object' && !Array.isArray(body.data) ? body.data : body;
const rawMetrics = Array.isArray(data.metrics) ? data.metrics : [];
const rawWorkouts = Array.isArray(data.workouts) ? data.workouts : [];
if (!rawMetrics.length && !rawWorkouts.length && !('metrics' in data) && !('workouts' in data)) throw err('shape');
const metrics = [];
for (const m of rawMetrics) {
if (!m || typeof m !== 'object') continue;
const name = str(m.name).trim();
if (!name) continue;
const points = [];
for (const p of Array.isArray(m.data) ? m.data : []) {
if (!p || typeof p !== 'object') continue;
const at = instantOf(p);
if (!at) continue; // a datapoint with no readable date is unusable
const fields = fieldsOf(p);
if (!Object.keys(fields).length) continue; // ...and so is one with no numbers
points.push({ at, fields, source: str(p.source) || str(p.Source) });
}
metrics.push({ name, units: str(m.units), points });
}
const workouts = [];
for (const w of rawWorkouts) {
if (!w || typeof w !== 'object') continue;
const name = str(w.name).trim();
const start = parseHaeDate(w.start);
if (!name || !start) continue;
const end = parseHaeDate(w.end);
const fields = {};
for (const [k, v] of Object.entries(w)) {
if (['name', 'start', 'end', 'route', 'heartRateData', 'heartRateRecovery'].includes(k)) continue;
const q = v && typeof v === 'object' && !Array.isArray(v) ? num(v.qty) : num(v);
if (q == null) continue;
fields[k] = { qty: q, units: v && typeof v === 'object' ? str(v.units) : '' };
}
const mins = end ? Math.round((end.ms - start.ms) / 60000) : null;
workouts.push({
name,
start: start.ms,
end: end ? end.ms : null,
day: start.day,
durMin: mins != null && mins >= 0 ? mins : null,
avgHr: hrAvg(w.heartRateData) ?? fields.heartRate?.qty ?? null,
maxHr: hrMax(w.heartRateData) ?? null,
fields
});
}
if (!metrics.length && !workouts.length) throw err('empty');
return { metrics, workouts };
}
const err = code => Object.assign(new Error(code), { code });
/** Average of HAE's per-second/minute workout heart-rate samples. */
function hrAvg(samples) {
if (!Array.isArray(samples) || !samples.length) return null;
const vals = samples.map(s => num(s?.Avg) ?? num(s?.qty)).filter(v => v != null);
if (!vals.length) return null;
return Math.round((vals.reduce((a, b) => a + b, 0) / vals.length) * 10) / 10;
}
function hrMax(samples) {
if (!Array.isArray(samples) || !samples.length) return null;
const vals = samples.map(s => num(s?.Max) ?? num(s?.qty)).filter(v => v != null);
return vals.length ? Math.max(...vals) : null;
}
/* ---------- merging ---------- */
/**
* A midnight-stamped datapoint that carries more than everything else in its payload put together
* is the day's own total, not hour 00: an hour cannot hold more than the day it belongs to. Returns
* the day keys it applies to, so the loop can treat exactly those points as day totals.
*/
function declaredDay(points) {
const rest = points.filter(p => !isMidnight(p.at))
.map(p => headline(p.fields))
.filter(Boolean)
.reduce((n, h) => n + h.value, 0);
const keys = new Set();
for (const p of points) {
if (!isMidnight(p.at)) continue;
const h = headline(p.fields);
if (h && h.value > rest) keys.add(p.at.day);
}
return keys;
}
/** Does this metric payload look like HAE's own day-by-day grouping? */
function dayGrouped(points) {
return points.length > 0 && points.every(p => isMidnight(p.at));
}
/**
* ...and does it look like its hour-by-hour one? Decided from the whole payload, never from a
* single timestamp, because a raw 5-minute automation also has samples that sit exactly on the
* hour: treating one of those as an hour *total* would wipe the hour it belongs to. Homogeneity
* is the tell — HAE stamps every point the way its Time Grouping says, so a payload where the
* minutes and seconds are all zero is grouping by hour, and one with a single stray minute is not.
*
* A raw payload that happens to be entirely on the hour is read as grouped, and that is benign:
* for an hour being sent for the first time the two rules agree, and for one already stored HAE
* would only re-send it identically.
*/
function hourGrouped(points) {
return points.length > 0 && points.every(p => onTheHour(p.at));
}
const dayKeyOk = k => /^\d{4}-\d{2}-\d{2}$/.test(k);
/* ── Two devices, one walk ────────────────────────────────────────────────────────────────────
*
* HealthKit de-duplicates: the same walk recorded by an iPhone and an Apple Watch is one walk in the
* Health app. A payload that carries both as separate points has been de-duplicated by nobody, so
* adding them is what turns 946 steps into 1,700 — a live report, and a ratio of about 1.8, which is
* exactly the share of the time only one of the two devices was recording.
*
* So a bucket keeps its sources *apart* and shows one of them: the source that reported most in that
* bucket, which is the device that was actually being worn. Per bucket, never per day, because that
* is what makes both cases right — an hour where only the phone recorded is the phone's hour, and an
* hour where both recorded is counted once. A metric with a single source (most people, and every
* metric whose payload has no `source` at all) behaves exactly as it did before: one sub-bucket,
* which is the bucket.
*
* The choice is deliberately not a sum, not an average, and not a "max": it is one device's own
* aggregate. A number that exists on the wrist is the number the wrist's app shows. */
/** This source's own aggregates inside a bucket, created on first sight. */
function sourceBucket(bucket, source) {
const all = bucket.s || (bucket.s = {});
const key = source || '';
return all[key] || (all[key] = { n: 0, lastTs: 0, f: {} });
}
/** How much a source reports in a bucket — used only to break a tie, never to compute a value. */
function totalOf(b) {
const sums = Object.values(b.f || {}).map(v => v.sum).filter(v => typeof v === 'number');
return sums.length ? Math.max(...sums) : 0;
}
/**
* The source a bucket shows: most samples, then the newest, then the largest total. Sample count
* first because it says who was actually recording (a watch taking a reading every five minutes
* against a phone that caught one); the newest next because a payload that stops mid-bucket leaves
* the other device holding the end of it; the total last, which is the only tie-break left for a
* day-level point from each device.
*/
export function pickSource(bucket) {
const all = bucket && bucket.s;
if (!all) return null;
let best = null, bestN = -1, bestTs = -1, bestTotal = -1;
for (const [key, b] of Object.entries(all)) {
const total = totalOf(b);
const better = b.n > bestN
|| (b.n === bestN && b.lastTs > bestTs)
|| (b.n === bestN && b.lastTs === bestTs && total > bestTotal);
if (better) { best = key; bestN = b.n; bestTs = b.lastTs; bestTotal = total; }
}
return best;
}
/**
* A bucket written before this existed has an aggregate and no sources: it is adopted as the
* unnamed source rather than thrown away, so an upgrade never loses the day it already had — and
* the two then compete on samples like any other pair.
*/
function seedLegacy(bucket, ms) {
if (!bucket.s && bucket.f && Object.keys(bucket.f).length) {
bucket.s = { '': { n: bucket.n || 0, lastTs: bucket.lastTs || ms, f: bucket.f } };
}
}
/** Fold one sample into its own source's bucket, then show the winning one. */
function addPoint(bucket, source, fields, ms) {
seedLegacy(bucket, ms);
const b = sourceBucket(bucket, source);
addFields(b, fields);
b.lastTs = Math.max(b.lastTs, ms);
return applySource(bucket);
}
/**
* One datapoint that *is* a bucket — an hour HAE grouped itself, or a day it totalled — where that
* source's earlier report of the same bucket is superseded rather than added to (the hour in
* progress grows on every run of a five-minute automation).
*
* Only that source's sub-bucket is superseded. A device re-sending its own hour says nothing about
* the other device's, and wiping the whole bucket is how one device's report would silently delete
* the other's — which is the opposite of what this is for.
*/
function setPoint(bucket, source, fields, ms) {
seedLegacy(bucket, ms);
const b = sourceBucket(bucket, source);
b.n = 0;
b.f = {};
b.lastTs = ms;
addFields(b, fields);
return applySource(bucket);
}
/** What this source last reported for a bucket, whether the bucket knows about sources or not. */
function sourceReport(bucket, source) {
if (!bucket) return null;
if (bucket.s) return bucket.s[source || ''] || null;
return bucket;
}
/** Make the bucket show its winning source; returns the key that won (or null). */
function applySource(bucket) {
const key = pickSource(bucket);
if (key == null) return null;
const b = bucket.s[key];
bucket.src = key || null;
bucket.n = b.n;
bucket.f = b.f;
return key;
}
function addFields(bucket, fields) {
for (const [k, v] of Object.entries(fields)) {
const f = bucket.f[k] || (bucket.f[k] = { n: 0, sum: 0, min: v, max: v, last: v });
f.n++; f.sum += v;
if (v < f.min) f.min = v;
if (v > f.max) f.max = v;
f.last = v;
}
bucket.n++;
}
const bucketFrom = (fields, ts) => {
const b = { n: 0, lastTs: ts, f: {} };
addFields(b, fields);
return b;
};
/**
* Recompute a day from its hours.
*
* A day with hours is not a bucket anybody increments — it is a *projection* of them, so the two
* can never disagree: fourteen hourly buckets of 500 steps and "7,000 today" are the same number
* by construction, and a partial hour replaced by a fuller one moves both. Aggregates are per
* field the way the reading side wants them (`sum` for a counter, `n` so a rate averages), and
* `last` comes from the newest hour that carried the field, because the hours are walked in order.
*/
function deriveDay(day) {
const f = {};
let n = 0;
for (const hh of Object.keys(day.h || {}).sort()) {
const hb = day.h[hh];
n += hb.n || 0;
for (const [k, v] of Object.entries(hb.f || {})) {
const cur = f[k] || (f[k] = { n: 0, sum: 0, min: null, max: null, last: null });
cur.n += v.n || 0;
cur.sum += v.sum || 0;
if (v.min != null && (cur.min == null || v.min < cur.min)) cur.min = v.min;
if (v.max != null && (cur.max == null || v.max > cur.max)) cur.max = v.max;
cur.last = v.last;
}
}
day.f = f;
day.n = n;
day.hsum = sumHours(day);
/* Which device the day is mostly made of. Each hour has already been reduced to one source (two
devices recording the same hour are one hour), so the day's answer is the device that reported
most of it — worth saying out loud on the sheet, because "the watch, mostly, plus two hours the
phone had to itself" is what the number actually is. */
const bySrc = {};
for (const hb of Object.values(day.h || {})) {
// `|| ''`: an hour stored before sources existed has none, and its samples are still the day's.
const key = hb.src || '';
bySrc[key] = (bySrc[key] || 0) + (hb.n || 0);
}
const winner = Object.entries(bySrc).sort((a, b) => b[1] - a[1])[0];
day.src = winner ? (winner[0] || null) : null;
}
/**
* What a day's hours add up to, per field — kept beside the day whether or not the day's own number
* came from them. When the phone also declares a total the two can disagree, and that disagreement
* is the most useful thing there is to show: "the hours add up to 840 and the newest one says 499"
* explains a wrong number, where the wrong number alone explains nothing.
*/
function sumHours(day) {
const out = {};
for (const hb of Object.values(day.h || {})) {
for (const [k, v] of Object.entries(hb.f || {})) out[k] = Math.round(((out[k] || 0) + (v.sum || 0)) * 100) / 100;
}
return out;
}
/**
* Fold one parsed payload into a stored document. Pure: the input document is not modified.
*
* @returns {{doc:object, stats:{metrics:number, points:number, duplicates:number, workouts:number}}}
*/
export function mergeVitals(doc, payload, now = Date.now()) {
const out = normalizeDoc(doc);
const stats = { metrics: 0, points: 0, duplicates: 0, workouts: 0 };
for (const m of payload.metrics) {
if (!m.points.length) continue;
stats.metrics++;
const cur = out.metrics[m.name] || { units: '', sources: [], days: {}, seen: {} };
if (m.units) cur.units = m.units;
const replace = dayGrouped(m.points);
// The hour rule only applies when the payload is not a day total: a day-grouped point is
// midnight-stamped and would otherwise also read as "on the hour".
const byHour = !replace && hourGrouped(m.points);
// The ledger is only consulted by the union path, and only for instants recent enough to be
// re-sent by the next automation run — anything older is pruned and can no longer be a repeat.
pruneLedger(cur.seen, now);
// The receipt is written once per metric, from the payload as it arrived.
out.shape[m.name] = receiptFor(m.points, now);
/* A midnight-stamped datapoint inside a payload that also carries hours is the day's own total,
not hour 00 of it — an hour cannot hold more than the day does. Reading it as an hour is what
turns "499 today" into 840, so when its value exceeds everything else in the payload added
together, it is taken as the day. Anything smaller is left where it is: a genuine 00:00 bucket
is a handful of steps, never more than the rest of the day. */
// A Set, and empty is not "yes": `declared.has(day)` is what the loop asks, because a truthy
// empty Set would turn every midnight point into a day total.
const declared = replace ? null : declaredDay(m.points);
for (const p of m.points) {
const key = p.at.day;
if (!dayKeyOk(key)) continue;
if (p.source && !cur.sources.includes(p.source)) {
cur.sources = [p.source, ...cur.sources].slice(0, MAX_SOURCES);
}
if (replace || (declared && declared.has(p.at.day) && isMidnight(p.at))) {
const prev = cur.days[key];
// Nothing to do when this source re-sends the value it already reported (the common case
// for every run after the first). `f` is compared as a whole because a day total and a
// once-a-day gauge both live in it.
const own = sourceReport(prev, p.source);
if (own && own.n === 1 && sameFields(own.f, p.fields)) { stats.duplicates++; continue; }
// The hours already stored for that day ride along, and so does any other source's total:
// the phone's own number is the better day value, but it says nothing about the shape of
// the day, and one device's total does not replace another's — the two are compared, and
// the one that reported more wins (`own` records that the day's number is a declared total
// rather than the sum of its hours; see below).
const dayBucket = prev ? { ...prev, own: true, ownAt: now } : { h: {}, own: true, ownAt: now, n: 0, lastTs: p.at.ms, f: {} };
cur.days[key] = dayBucket;
setPoint(dayBucket, p.source, p.fields, p.at.ms);
dayBucket.hsum = sumHours(dayBucket);
stats.points++;
continue;
}
const day = cur.days[key] || (cur.days[key] = { n: 0, lastTs: p.at.ms, f: {}, h: {} });
const hours = day.h || (day.h = {});
const hh = p.at.time.slice(0, 2);
if (byHour) {
// An hour the phone grouped itself: replaced — that source's hour, never unioned, because
// the hour in progress grows on every run of a five-minute automation. Another device's
// report of the same hour is a separate sub-bucket and is not touched.
const prev = sourceReport(hours[hh], p.source);
if (prev && sameFields(prev.f, p.fields)) { stats.duplicates++; continue; }
const hb = hours[hh] || (hours[hh] = { n: 0, lastTs: p.at.ms, f: {} });
setPoint(hb, p.source, p.fields, p.at.ms);
// The exact datapoint is remembered anyway: a payload grouped by hour and a later one
// carrying real minutes can describe the same instant — the automation was reconfigured,
// or two of them write to one profile — and the union path can only see the ledger, so
// without this row it would count that instant a second time.
cur.seen[sampleId(p)] = p.at.ms;
} else {
const id = sampleId(p);
if (cur.seen[id] != null) { stats.duplicates++; continue; }
cur.seen[id] = p.at.ms;
const hb = hours[hh] || (hours[hh] = { n: 0, lastTs: p.at.ms, f: {} });
addPoint(hb, p.source, p.fields, p.at.ms);
hb.lastTs = Math.max(hb.lastTs, p.at.ms);
}
day.lastTs = Math.max(day.lastTs, p.at.ms);
/* Recompute the day from its hours, which keeps this idempotent: the same hour arriving
three times, or a partial hour replaced by a fuller one, leaves the same number behind.
Three days are the exceptions, and all three are days whose aggregate is not "the hours so
far":
own — the phone totalled this day itself. Its total is the number the Health app shows,
and hours were re-folded into it once already (that is the bug this replaced:
499 declared plus 341 of hours became 840). So the total stays the day, and the
hours stay the shape of it. The escape hatch is time: if no fresh total has
arrived for six hours while hours keep coming, the automation was clearly
reconfigured to hours only, and the day goes back to the sum of them.
!hc — a day stored by an older version of this file, whose samples have no hour
attribution. Summing its (empty, or partly filled) hours would delete what is
already there, so the new sample is added to the day the old way and the hours
beside it stay what they honestly are: the part that has a time of its own. */
const declaredStale = day.own && now - (day.ownAt || 0) > DECLARED_STALE_MS;
if (declaredStale) { delete day.own; delete day.ownAt; day.hc = true; }
if (day.own) {
/* The phone declared this day, so its number *is* the day: adding the hour to it would
count the morning twice, which is the whole failure this branch exists to prevent. The
hours still move — they are the shape of the day and the detail sheet draws them — and
the sum beside them moves with them so the two can be compared. */
day.hsum = sumHours(day);
} else if (day.hc || day.n === 0) {
day.hc = true;
deriveDay(day);
} else {
addFields(day, p.fields);
}
stats.points++;
}
pruneLedger(cur.seen, now, true);
out.metrics[m.name] = cur;
}
if (payload.workouts.length) {
const seen = new Set(out.workouts.map(w => wkey(w)));
for (const w of payload.workouts) {
const k = wkey(w);
if (seen.has(k)) { stats.duplicates++; continue; }
seen.add(k);
out.workouts.push(w);
stats.workouts++;
}
// Newest first, and the oldest are dropped: a wrist that records every walk produces
// thousands of entries a year, and nobody scrolls past the last few hundred.
out.workouts.sort((a, b) => b.start - a.start);
if (out.workouts.length > MAX_WORKOUTS) out.workouts.length = MAX_WORKOUTS;
}
pruneDays(out, now);
out.updatedAt = now;
out.last = { ts: now, ...stats };
return { doc: out, stats };
}
const wkey = w => `${w.name}|${w.start}|${w.end ?? ''}`;
/** Same numbers as the stored bucket? `raw` is a payload's plain field map, `stored` a bucket's. */
function sameFields(stored, raw) {
const ka = Object.keys(stored), kb = Object.keys(raw);
if (ka.length !== kb.length) return false;
return ka.every(k => raw[k] === stored[k].last);
}
/** A sample's identity: when it happened plus what it says. */
function sampleId(p) {
const f = Object.keys(p.fields).sort().map(k => `${k}:${p.fields[k]}`).join(',');
return `${p.at.raw}|${f}`;
}
function pruneLedger(seen, now, enforceCap = false) {
for (const [k, ts] of Object.entries(seen)) if (now - ts > LEDGER_MS) delete seen[k];
if (!enforceCap) return;
const keys = Object.keys(seen);
if (keys.length <= MAX_LEDGER_KEYS) return;
// Oldest first — a repeat can only be recent, so the tail is what may be given up.
keys.sort((a, b) => seen[a] - seen[b]);
for (const k of keys.slice(0, keys.length - MAX_LEDGER_KEYS)) delete seen[k];
}
function pruneDays(doc, now) {
const oldest = new Date(now - RETENTION_DAYS * 86400000).toISOString().slice(0, 10);
// Hours are the detail, and detail is what makes a file grow: 24 buckets × every metric × every
// day of a year is a document nobody wants to load. A week of them is what "what did today look
// like" needs — the day aggregates underneath are untouched and live out the full year.
const hoursOldest = new Date(now - HOURS_KEPT_DAYS * 86400000).toISOString().slice(0, 10);
for (const m of Object.values(doc.metrics)) {
for (const [day, b] of Object.entries(m.days)) {
if (day < oldest) { delete m.days[day]; continue; }
if (b && b.h && day < hoursOldest) {
// `hc` goes with them: it means "this day is the sum of its hours", and with the hours
// gone that claim would make the next sample for that day rebuild it from nothing.
delete b.h;
delete b.hc;
}
}
}
}
/* ---------- the receipt: what actually arrived ----------
*
* One entry per metric, replaced on every sync: how many datapoints came, how they were stamped
* (a day total, an hour, or a real instant), from which sources, what they add up to, and the first
* and last few values as the phone wrote them. It exists because "the number in the app does not
* match the Health app" is unanswerable from the number alone, and the answer is always in the
* shape of what arrived: hourly values that are really running totals add up to more than the day,
* and two devices recording the same walk add up to more than either.
*
* Bounded on purpose (three values at each end), and it is a *receipt*, not a reading: the headline
* field is picked by a fixed order rather than by the metric's meaning, because this module does not
* have the catalogue. Nothing here is used to compute a day. */
/** The field a receipt quotes for a point: the one a person would read if they had to pick one. */
const HEADLINE_FIELDS = ['qty', 'Avg', 'avg', 'value', 'asleep', 'totalSleep', 'systolic'];
function headline(fields) {
for (const k of HEADLINE_FIELDS) if (typeof fields[k] === 'number') return { field: k, value: fields[k] };
for (const [k, v] of Object.entries(fields)) if (typeof v === 'number') return { field: k, value: v };
return null;
}
const stampKind = t => (isMidnight(t) ? 'day' : onTheHour(t) ? 'hour' : 'sample');
function receiptFor(points, now) {
const kinds = new Set(points.map(p => stampKind(p.at)));
const valued = points.map(p => ({ at: p.at, h: headline(p.fields) })).filter(x => x.h);
const sum = valued.reduce((n, x) => n + x.h.value, 0);
const last = valued.length ? valued[valued.length - 1] : null;
const pair = x => [x.at.raw, x.h.value];
return {
at: now,
points: points.length,
field: valued.length ? valued[0].h.field : null,
stamps: kinds.size > 1 ? 'mixed' : [...kinds][0],
sources: [...new Set(points.map(p => p.source).filter(Boolean))].slice(0, MAX_SOURCES),
sum: Math.round(sum * 100) / 100,
newest: last ? { stamp: last.at.raw, value: last.h.value, ms: last.at.ms } : null,
head: valued.slice(0, 3).map(pair),
tail: valued.slice(-3).map(pair)
};
}
/* ---------- reading ---------- */
/** One bucket's fields, as the client wants them: the count, the total, and the mean it implies. */
function projectFields(f) {
const out = {};
for (const [k, v] of Object.entries(f || {})) {
out[k] = { n: v.n, sum: v.sum, min: v.min, max: v.max, last: v.last, avg: v.n ? v.sum / v.n : null };
}
return out;
}
/**
* Project a stored document into the compact series the view renders, oldest day first.
* Aggregates are per *field* — `qty.sum` for a counter, `Avg.last` for a rate — so the client
* never has to know how HAE grouped things.
*
* Each day also says how many hourly buckets it has. That count is the difference between a card
* whose detail is a single number and one you can open up, and sending the number instead of the
* buckets keeps this response the size of a card list: the hours themselves are one metric and
* one day per request (vitalsHours below), fetched when somebody actually taps in.
*/
export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) {
const d = normalizeDoc(doc);
// `days` counts calendar days *including today*, so `days: 1` is today alone. Day keys are the
// phone's own local dates (see the header), which is why this is a plain string comparison
// rather than an instant one: an evening sample in Manila and one in Lima each keep their own
// day, and neither is dragged across a boundary by the server's timezone.
const from = new Date(now - Math.max(0, days - 1) * 86400000).toISOString().slice(0, 10);
const metrics = {};
for (const [name, m] of Object.entries(d.metrics)) {
const out = [];
for (const day of Object.keys(m.days).sort()) {
if (day < from) continue;
const b = m.days[day];
out.push({
day,
n: b.n,
lastTs: b.lastTs,
hours: Object.keys(b.h || {}).length,
// `own`: this day's number is the total the phone declared, not the sum of its hours.
// `hours_sum`: what its hours add up to, so a disagreement between the two is visible
// instead of hidden — the screen shows it, and so does anybody debugging a wrong number.
own: !!b.own,
// Which device the day is mostly made of, when more than one reported into it. Two devices
// recording the same hour are one hour, and saying which one won is the difference between a
// number somebody can check against their watch and a number they cannot.
source: b.src || null,
hours_sum: b.hsum || null,
f: projectFields(b.f)
});
}
if (out.length) metrics[name] = { units: m.units, sources: m.sources, days: out, shape: d.shape[name] || null };
}
return { updatedAt: d.updatedAt, last: d.last, metrics, workouts: d.workouts };
}
/**
* Forget one metric, keeping everything else.
*
* The whole-file delete exists and is two taps, but it is the wrong size for the question people
* actually arrive with: "these numbers look wrong, let me start that one over". With a Date Range
* of a week or a month the phone re-sends the metric on its next sync, so this is a *reset* rather
* than a loss — and every other metric, the workouts and the ingest key are untouched, which is
* what makes it safe to do without thinking about the rest of the profile.
*
* @returns {{doc:object|null, days:number, found:boolean}} `doc` is null when the profile has no
* health file at all, so the caller can leave the file alone instead of writing an empty one.
*/
export function dropMetric(doc, metric) {
if (!doc || typeof doc !== 'object') return { doc: null, days: 0, found: false };
const out = normalizeDoc(doc);
const name = String(metric || '');
if (!Object.prototype.hasOwnProperty.call(out.metrics, name)) return { doc, days: 0, found: false };
const days = Object.keys(out.metrics[name].days || {}).length;
delete out.metrics[name];
return { doc: out, days, found: true };
}
/**
* One metric's hours on one day, oldest first — what the detail sheet opens.
*
* A day that HAE grouped itself (Days grouping) has no hours and comes back empty rather than
* invented: the honest answer to "what did the hours look like" for a payload that never carried
* hours is "the automation does not send them", and the screen says that instead.
*/
export function vitalsHours(doc, { metric, day } = {}) {
const d = normalizeDoc(doc);
const name = String(metric || '');
const m = Object.prototype.hasOwnProperty.call(d.metrics, name) ? d.metrics[name] : null;
const key = String(day || '');
const b = m && dayKeyOk(key) ? m.days[key] : null;
const hours = [];
for (const hh of Object.keys((b && b.h) || {}).sort()) {
const hb = b.h[hh];
hours.push({ h: hh, n: hb.n, ts: hb.lastTs, f: projectFields(hb.f) });
}
return { metric: m ? name : null, day: b ? key : null, units: m ? m.units : '', hours };
}