import { healthStore } from "./health-store-files"; import { isFixtureData } from "./health-seed"; import { healthExportEnabledSetting, healthExportUrlSetting, healthExportKeySetting } from "../ui/dashboard-settings"; import { getStringSetting, setStringSetting } from "../native/settings-store"; import { fetchTextWithUserAgent } from "../util/http"; let running = false; let started = false; let status = "Not synchronized"; export function healthExportStatus(): string { return status; } /** One bounded batch, with durable acknowledgement and no overlapping requests. */ export async function syncHealthExport(): Promise { if (running) return; running = true; try { if (!healthExportEnabledSetting.get()) { status = "Export disabled"; return; } if (isFixtureData()) { status = "Sample data is never exported"; return; } const url = healthExportUrlSetting.get(); const key = healthExportKeySetting.get(); if (!url || healthExportUrlSetting.validationError() || !key) { status = "Configure an HTTPS endpoint and API key"; return; } const generation = getStringSetting("health.export.generation", "0"); let held: { url?: string; generation?: string; offsets?: Record } = {}; try { held = JSON.parse(getStringSetting("health.export.cursor", "{}")) ?? {}; } catch { /* First sync. */ } const offsets = held.url === url && held.generation === generation ? held.offsets ?? {} : {}; let limit = 200; let batch = healthStore().exportBatch(offsets, limit); let body = JSON.stringify({ version: 1, samples: batch.samples, sleep: batch.sleep }); // Normalized records contain only ASCII keys, numbers and metric names. // Large sleep histories must fit the server body limit as well as its record limit. while (body.length > 240_000 && limit > 1) { limit = Math.max(1, Math.floor(limit / 2)); batch = healthStore().exportBatch(offsets, limit); body = JSON.stringify({ version: 1, samples: batch.samples, sleep: batch.sleep }); } if (body.length > 240_000) { status = "A health record exceeds the export size limit"; return; } if (!batch.scanned) { status = "Up to date"; return; } if (batch.samples.length || batch.sleep.length) { status = "Sending health data"; const response = await fetchTextWithUserAgent(url, { method: "POST", headers: { "Authorization": `Bearer ${key}`, "Content-Type": "application/json" }, body, timeoutMs: 30_000, dontFollowRedirects: true, }); if (response.status !== 200) { status = response.status === 401 || response.status === 403 ? "API key refused; check configuration" : `Server refused batch (HTTP ${response.status}); will retry`; return; } const ack = await response.json<{ accepted?: boolean }>(); if (ack.accepted !== true) { status = "Invalid server acknowledgement; will retry"; return; } } // An edit during the request must not acknowledge data on a different destination. if (url !== healthExportUrlSetting.get() || generation !== getStringSetting("health.export.generation", "0")) return; setStringSetting("health.export.cursor", JSON.stringify({ url, generation, offsets: batch.cursor })); status = "Batch synchronized; remaining history follows automatically"; } catch { // Errors may include request headers or data: never log or display them. status = "Synchronization failed; will retry automatically"; } finally { running = false; } } /** Android app process only; no extra BLE pulls, wake locks, or background service. */ export function startHealthExport(): void { if (started) return; started = true; setTimeout(() => { void syncHealthExport(); }, 10_000); setInterval(() => { void syncHealthExport(); }, 60_000); }