Modern Apps git

← Modern-Apps.git

everysync: fix google health syncing

Commit
99f4cc1e84b8fa11e57a59279695080913b6a58b
Author
Vayun Mathur <[email protected]>
When
2026-07-20 19:42 UTC (4 months ago)
Parents
814a45b

Diff

everysync/src/main/AndroidManifest.xml
diff --git a/everysync/src/main/AndroidManifest.xml b/everysync/src/main/AndroidManifest.xmlindex b465078716..02fc34828a 100644--- a/everysync/src/main/AndroidManifest.xml+++ b/everysync/src/main/AndroidManifest.xml@@ -3,6 +3,7 @@      <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />      <!-- Contacts -->     <uses-permission android:name="android.permission.READ_CONTACTS" />@@ -60,12 +61,19 @@     <uses-permission android:name="android.permission.health.WRITE_VO2_MAX" />     <uses-permission android:name="android.permission.health.READ_HYDRATION" />     <uses-permission android:name="android.permission.health.WRITE_HYDRATION" />+    <uses-permission android:name="android.permission.health.READ_ELEVATION_GAINED" />+    <uses-permission android:name="android.permission.health.WRITE_ELEVATION_GAINED" />+    <uses-permission android:name="android.permission.health.READ_EXERCISE" />+    <uses-permission android:name="android.permission.health.WRITE_EXERCISE" />+    <uses-permission android:name="android.permission.health.READ_NUTRITION" />+    <uses-permission android:name="android.permission.health.WRITE_NUTRITION" />     <uses-permission android:name="android.permission.health.READ_SLEEP" />     <uses-permission android:name="android.permission.health.WRITE_SLEEP" />     <uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />      <application         android:allowBackup="true"+        android:name=".EverySyncApplication"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"@@ -159,6 +167,17 @@                 android:resource="@xml/syncadapter_calendar" />         </service> +        <!-- Re-schedules the periodic sync after reboot / app update. -->+        <receiver+            android:name=".BootReceiver"+            android:exported="true"+            android:enabled="true">+            <intent-filter>+                <action android:name="android.intent.action.BOOT_COMPLETED" />+                <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />+            </intent-filter>+        </receiver>+     </application>  </manifest>
everysync/src/main/java/com/vayunmathur/everysync/BootReceiver.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/BootReceiver.kt b/everysync/src/main/java/com/vayunmathur/everysync/BootReceiver.ktnew file mode 100644index 0000000000..b968919585--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/BootReceiver.kt@@ -0,0 +1,21 @@+package com.vayunmathur.everysync++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.everysync.sync.SyncScheduler++/**+ * Re-registers the periodic sync after a reboot or app update. WorkManager also+ * restores its own jobs across reboots, but this is a belt-and-suspenders+ * guarantee the schedule survives even if that ever fails.+ */+class BootReceiver : BroadcastReceiver() {+    override fun onReceive(context: Context, intent: Intent) {+        when (intent.action) {+            Intent.ACTION_BOOT_COMPLETED,+            Intent.ACTION_MY_PACKAGE_REPLACED,+            -> SyncScheduler.schedulePeriodic(context.applicationContext)+        }+    }+}
everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt b/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.ktnew file mode 100644index 0000000000..7f62bacf30--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/EverySyncApplication.kt@@ -0,0 +1,16 @@+package com.vayunmathur.everysync++import android.app.Application+import com.vayunmathur.everysync.sync.SyncScheduler++/**+ * Ensures the periodic background sync is scheduled whenever the process starts —+ * including when WorkManager or the sync framework spins the app up in the+ * background — so syncing keeps running without the user reopening the UI.+ */+class EverySyncApplication : Application() {+    override fun onCreate() {+        super.onCreate()+        SyncScheduler.schedulePeriodic(this)+    }+}
everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt b/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.ktindex 6e35c540aa..50fc37ac5d 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt@@ -6,7 +6,6 @@ import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.compose.runtime.Composable-import com.vayunmathur.everysync.sync.SyncScheduler import com.vayunmathur.everysync.ui.AccountDetailScreen import com.vayunmathur.everysync.ui.AccountsScreen import com.vayunmathur.everysync.ui.AddAccountScreen@@ -27,7 +26,6 @@ class MainActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()-        SyncScheduler.schedulePeriodic(this)         setContent {             DynamicTheme {                 Navigation(viewModel)
everysync/src/main/java/com/vayunmathur/everysync/model/RemoteModels.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/model/RemoteModels.kt b/everysync/src/main/java/com/vayunmathur/everysync/model/RemoteModels.ktindex 29d66a216c..186b104c59 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/model/RemoteModels.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/model/RemoteModels.kt@@ -69,6 +69,14 @@ data class RemoteMeasurement(     val endMillis: Long = startMillis,     /** Sleep-stage segments; populated only for [MeasurementType.SLEEP]. */     val sleepStages: List<RemoteSleepStage> = emptyList(),+    /** Health Connect `ExerciseSessionRecord.EXERCISE_TYPE_*`; only for [MeasurementType.EXERCISE]. */+    val exerciseType: Int = 0,+    /** Session title (exercise) or food name (nutrition). */+    val title: String? = null,+    /** Free-form notes; only for [MeasurementType.EXERCISE]. */+    val notes: String? = null,+    /** Nutrition payload; populated only for [MeasurementType.NUTRITION]. */+    val nutrition: RemoteNutrition? = null, )  /** One sleep-stage segment. [stage] is a Health Connect `SleepSessionRecord.STAGE_TYPE_*` value. */@@ -78,6 +86,16 @@ data class RemoteSleepStage(     val stage: Int, ) +/**+ * A logged food / nutrition entry. Energy is in kilocalories; [nutrientGrams] holds+ * each nutrient's mass in grams keyed by Google Health nutrient name (e.g. "PROTEIN",+ * "SODIUM"), plus the synthetic keys "TOTAL_FAT" and "TOTAL_CARBOHYDRATE".+ */+data class RemoteNutrition(+    val energyKcal: Double? = null,+    val nutrientGrams: Map<String, Double> = emptyMap(),+)+ /**  * Health metrics synced from Google Health into Health Connect. Each maps to one  * Health Connect record type; the trailing comment is the canonical unit stored in@@ -103,10 +121,13 @@ enum class MeasurementType {     STEPS, // count     DISTANCE, // meters     FLOORS, // count+    ELEVATION, // meters gained     ACTIVE_CALORIES, // kilocalories     TOTAL_CALORIES, // kilocalories -    // Lifestyle+    // Sessions / lifestyle     HYDRATION, // liters     SLEEP, // session (start/end + sleepStages)+    EXERCISE, // session (exerciseType/title)+    NUTRITION, // logged food (nutrition payload) }
everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.ktindex e0f10b5d41..f1c0eda7ad 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.kt@@ -51,13 +51,45 @@ class GoogleHealthProvider : SyncProvider {     override suspend fun sync(context: Context, config: AccountConfig, direction: SyncDirection) {         if (DataType.HEALTH !in config.enabledTypes || direction == SyncDirection.PUSH) return         val token = OAuthManager.validAccessToken(context, config.accountName, id) ?: return-        val since = SyncState.get(context, config.accountName, "googlehealth_since")?.toLongOrNull() ?: 0L-        HealthSink.upsert(context, GoogleHealthClient(token).getMeasurements(since))-        SyncState.set(context, config.accountName, "googlehealth_since", System.currentTimeMillis().toString())+        val client = GoogleHealthClient(token)+        val account = config.accountName+        val now = System.currentTimeMillis()++        // 1. Forward window: pull everything new since the last run (with a small+        // overlap so late-arriving data isn't missed). Idempotent via clientRecordId.+        val watermark = SyncState.get(context, account, KEY_WATERMARK)?.toLongOrNull()+        val recentFrom = (watermark?.minus(RECENT_OVERLAP_MILLIS) ?: (now - RECENT_SEED_DAYS * DAY_MILLIS))+            .coerceAtLeast(0)+        Log.i(TAG, "sync $account: recent window [$recentFrom, $now]")+        HealthSink.upsert(context, client.getMeasurements(recentFrom, now))+        SyncState.set(context, account, KEY_WATERMARK, now.toString())++        // 2. Backfill older history one chunk at a time, writing each chunk as it+        // lands so data appears progressively rather than after one huge request.+        // The cursor is persisted after every chunk, so if the worker is killed the+        // next run resumes where this one left off instead of restarting.+        val floor = now - BACKFILL_DAYS * DAY_MILLIS+        var cursor = SyncState.get(context, account, KEY_BACKFILL_CURSOR)?.toLongOrNull()+            ?: (now - RECENT_SEED_DAYS * DAY_MILLIS)+        while (cursor > floor) {+            val chunkStart = maxOf(cursor - BACKFILL_CHUNK_DAYS * DAY_MILLIS, floor)+            Log.i(TAG, "sync $account: backfill chunk [$chunkStart, $cursor]")+            HealthSink.upsert(context, client.getMeasurements(chunkStart, cursor))+            cursor = chunkStart+            SyncState.set(context, account, KEY_BACKFILL_CURSOR, cursor.toString())+        }+        Log.i(TAG, "sync $account: complete (backfilled to $cursor)")     }      companion object {         private const val TAG = "GoogleHealthProvider"         private val JSON = Json { ignoreUnknownKeys = true }+        private const val DAY_MILLIS = 86_400_000L+        private const val KEY_WATERMARK = "googlehealth_watermark"+        private const val KEY_BACKFILL_CURSOR = "googlehealth_backfill_cursor"+        private const val RECENT_SEED_DAYS = 30L // recent window pulled on the first sync+        private const val RECENT_OVERLAP_MILLIS = DAY_MILLIS // re-check the last day for late data+        private const val BACKFILL_CHUNK_DAYS = 30L // one window of history written per step+        private const val BACKFILL_DAYS = 365L // total history to backfill (1 year)     } }
everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleHealthClient.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleHealthClient.kt b/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleHealthClient.ktindex 4b3639c147..c30ebe59a2 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleHealthClient.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleHealthClient.kt@@ -2,9 +2,11 @@ package com.vayunmathur.everysync.remote  import android.net.Uri import android.util.Log+import androidx.health.connect.client.records.ExerciseSessionRecord import androidx.health.connect.client.records.SleepSessionRecord import com.vayunmathur.everysync.model.MeasurementType import com.vayunmathur.everysync.model.RemoteMeasurement+import com.vayunmathur.everysync.model.RemoteNutrition import com.vayunmathur.everysync.model.RemoteSleepStage import com.vayunmathur.library.network.NetworkClient import java.time.Instant@@ -12,6 +14,12 @@ import java.time.LocalDate import java.time.OffsetDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter+import kotlinx.coroutines.Deferred+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.sync.Semaphore+import kotlinx.coroutines.sync.withPermit import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement@@ -27,16 +35,16 @@ import kotlinx.serialization.json.jsonPrimitive  *  * Fetch strategy per type:  * - [Mode.ROLLUP] — `dataPoints:dailyRollUp`, one aggregated value per civil day- *   (steps, distance, floors, calories, heart rate).- * - [Mode.LIST_SAMPLE] — `dataPoints` list of instantaneous samples at their real- *   timestamps (weight, height, body fat, glucose, temperature, VO2 max, HRV).- * - [Mode.LIST_DAILY] — `dataPoints` list of per-day summaries (resting HR,- *   oxygen saturation, respiratory rate).- * - [Mode.LIST_SESSION] — `dataPoints` list of sessions with a scalar value- *   (hydration).- * - Sleep is fetched separately with its stage segments.+ *   (steps, distance, floors, elevation, calories, heart rate).+ * - [Mode.LIST_SAMPLE] — instantaneous samples at their real timestamps (weight,+ *   height, body fat, glucose, temperature, VO2 max, HRV).+ * - [Mode.LIST_DAILY] — per-day summaries (resting HR, oxygen saturation,+ *   respiratory rate).+ * - [Mode.LIST_SESSION] — sessions with a scalar value (hydration).+ * - Sleep, exercise and nutrition are fetched separately (they carry extra data).  *- * The point/day/session start makes the clientRecordId idempotent across syncs.+ * Every request is chunked to the API's 14–90 day range limit; idempotent+ * clientRecordIds make re-pulling overlapping windows a safe upsert.  */ class GoogleHealthClient(private val accessToken: String) {     private val json = Json { ignoreUnknownKeys = true }@@ -45,20 +53,51 @@ class GoogleHealthClient(private val accessToken: String) {         "Content-Type" to "application/json",     ) -    suspend fun getMeasurements(sinceMillis: Long): List<RemoteMeasurement> {-        val out = mutableListOf<RemoteMeasurement>()+    /**+     * Fetch everything recorded in the half-open window `[fromMillis, toMillis)`,+     * chunked to the API range limit. Callers pull a small recent window each run+     * and one older backfill window at a time rather than the whole history at once.+     *+     * Independent requests (each type × each chunk, plus the session fetches) run+     * concurrently with bounded parallelism; pagination within a request stays+     * sequential since it depends on the previous page token.+     */+    suspend fun getMeasurements(fromMillis: Long, toMillis: Long): List<RemoteMeasurement> = coroutineScope {+        val zone = ZoneId.systemDefault()+        if (fromMillis >= toMillis) return@coroutineScope emptyList()+        val semaphore = Semaphore(MAX_CONCURRENCY)+        val jobs = mutableListOf<Deferred<List<RemoteMeasurement>>>()         for (spec in SPECS) {-            out += if (spec.mode == Mode.ROLLUP) dailyRollUp(spec, sinceMillis) else listDataPoints(spec, sinceMillis)+            // High-frequency raw types would explode over a multi-year backfill, so+            // clamp how far back each type goes independently of the deep backfill.+            val specFrom = backfillFloor(fromMillis, spec.maxBackfillDays)+            if (specFrom >= toMillis) continue+            for ((start, end) in chunks(specFrom, toMillis, spec.maxRangeDays, zone)) {+                jobs += async {+                    semaphore.withPermit {+                        if (spec.mode == Mode.ROLLUP) dailyRollUp(spec, start, end, zone)+                        else listDataPoints(spec, start, end, zone)+                    }+                }+            }         }-        out += fetchSleep(sinceMillis)-        return out+        for ((start, end) in chunks(fromMillis, toMillis, MAX_RANGE_DEFAULT, zone)) {+            jobs += async { semaphore.withPermit { fetchSleep(start, end, zone) } }+            jobs += async { semaphore.withPermit { fetchExercise(start, end, zone) } }+            jobs += async { semaphore.withPermit { fetchNutrition(start, end, zone) } }+        }+        jobs.awaitAll().flatten()     } -    // --- dailyRollUp (steps, distance, floors, calories, heart rate) ---+    /** Never look back further than [maxBackfillDays] for a given type. */+    private fun backfillFloor(fromMillis: Long, maxBackfillDays: Int): Long {+        if (maxBackfillDays >= UNBOUNDED_DAYS) return fromMillis+        return maxOf(fromMillis, System.currentTimeMillis() - maxBackfillDays.toLong() * DAY_MILLIS)+    } -    private suspend fun dailyRollUp(spec: Spec, sinceMillis: Long): List<RemoteMeasurement> {-        val zone = ZoneId.systemDefault()-        val (start, end) = window(spec.maxRangeDays, sinceMillis, zone)+    // --- dailyRollUp (steps, distance, floors, elevation, calories, heart rate) ---++    private suspend fun dailyRollUp(spec: Spec, start: LocalDate, end: LocalDate, zone: ZoneId): List<RemoteMeasurement> {         val body = """             {               "range": {@@ -75,6 +114,10 @@ class GoogleHealthClient(private val accessToken: String) {                 "https://health.googleapis.com/v4/users/me/dataTypes/${spec.dataType}/dataPoints:dailyRollUp",                 "POST", headers(), body,             )+            if (!resp.isSuccess) {+                Log.e(TAG, "dailyRollUp ${spec.dataType} HTTP ${resp.status}: ${resp.body.take(500)}")+                return out+            }             val root = json.parseToJsonElement(resp.body) as? JsonObject ?: return out             (root["rollupDataPoints"] as? JsonArray)?.forEach { el ->                 val rollup = el.jsonObject@@ -96,9 +139,7 @@ class GoogleHealthClient(private val accessToken: String) {      // --- dataPoints list (samples, daily summaries, hydration sessions) --- -    private suspend fun listDataPoints(spec: Spec, sinceMillis: Long): List<RemoteMeasurement> {-        val zone = ZoneId.systemDefault()-        val (start, end) = window(spec.maxRangeDays, sinceMillis, zone)+    private suspend fun listDataPoints(spec: Spec, start: LocalDate, end: LocalDate, zone: ZoneId): List<RemoteMeasurement> {         val filter = when (spec.mode) {             Mode.LIST_DAILY ->                 "${spec.filterField}.date >= \"$start\" AND ${spec.filterField}.date < \"$end\""@@ -139,14 +180,11 @@ class GoogleHealthClient(private val accessToken: String) {      // --- sleep (sessions with stage segments) --- -    private suspend fun fetchSleep(sinceMillis: Long): List<RemoteMeasurement> {-        val zone = ZoneId.systemDefault()-        val (start, end) = window(MAX_RANGE_DEFAULT, sinceMillis, zone)+    private suspend fun fetchSleep(start: LocalDate, end: LocalDate, zone: ZoneId): List<RemoteMeasurement> {         val filter = "sleep.interval.end_time >= \"${iso(start, zone)}\" AND sleep.interval.end_time < \"${iso(end, zone)}\""-         val out = mutableListOf<RemoteMeasurement>()         try {-            forEachDataPoint("sleep", filter) { dp ->+            forEachDataPoint("sleep", filter, SESSION_PAGE_SIZE) { dp ->                 val sleep = dp["sleep"]?.jsonObject ?: return@forEachDataPoint                 val interval = sleep["interval"]?.jsonObject ?: return@forEachDataPoint                 val startMs = sampleMillis(interval["startTime"]) ?: return@forEachDataPoint@@ -171,38 +209,118 @@ class GoogleHealthClient(private val accessToken: String) {         return out     } +    // --- exercise (workout sessions) ---++    private suspend fun fetchExercise(start: LocalDate, end: LocalDate, zone: ZoneId): List<RemoteMeasurement> {+        val filter = "exercise.interval.civil_start_time >= \"$start\" AND exercise.interval.civil_start_time < \"$end\""+        val out = mutableListOf<RemoteMeasurement>()+        try {+            forEachDataPoint("exercise", filter, SESSION_PAGE_SIZE) { dp ->+                val ex = dp["exercise"]?.jsonObject ?: return@forEachDataPoint+                val interval = ex["interval"]?.jsonObject ?: return@forEachDataPoint+                val startMs = sampleMillis(interval["startTime"]) ?: return@forEachDataPoint+                val endMs = sampleMillis(interval["endTime"]) ?: return@forEachDataPoint+                out += RemoteMeasurement(+                    clientRecordId = recordId(MeasurementType.EXERCISE, startMs),+                    type = MeasurementType.EXERCISE,+                    startMillis = startMs,+                    endMillis = endMs,+                    exerciseType = exerciseType(ex["exerciseType"]?.jsonPrimitive?.content),+                    title = ex["displayName"]?.jsonPrimitive?.content,+                    notes = ex["notes"]?.jsonPrimitive?.content,+                )+            }+        } catch (e: Exception) {+            Log.e(TAG, "fetchExercise failed", e)+        }+        return out+    }++    // --- nutrition (logged food) ---++    private suspend fun fetchNutrition(start: LocalDate, end: LocalDate, zone: ZoneId): List<RemoteMeasurement> {+        val filter = "nutrition_log.interval.civil_start_time >= \"$start\" AND nutrition_log.interval.civil_start_time < \"$end\""+        val out = mutableListOf<RemoteMeasurement>()+        try {+            forEachDataPoint("nutrition-log", filter) { dp ->+                val nl = dp["nutritionLog"]?.jsonObject ?: return@forEachDataPoint+                val interval = nl["interval"]?.jsonObject ?: return@forEachDataPoint+                val startMs = sampleMillis(interval["startTime"]) ?: return@forEachDataPoint+                val endMs = sampleMillis(interval["endTime"]) ?: startMs+                out += RemoteMeasurement(+                    clientRecordId = recordId(MeasurementType.NUTRITION, startMs),+                    type = MeasurementType.NUTRITION,+                    startMillis = startMs,+                    endMillis = endMs,+                    title = nl["foodDisplayName"]?.jsonPrimitive?.content,+                    nutrition = parseNutrition(nl),+                )+            }+        } catch (e: Exception) {+            Log.e(TAG, "fetchNutrition failed", e)+        }+        return out+    }++    private fun parseNutrition(nl: JsonObject): RemoteNutrition {+        val grams = mutableMapOf<String, Double>()+        nl.nestedDouble("totalFat", "grams")?.let { grams["TOTAL_FAT"] = it }+        nl.nestedDouble("totalCarbohydrate", "grams")?.let { grams["TOTAL_CARBOHYDRATE"] = it }+        (nl["nutrients"] as? JsonArray)?.forEach { el ->+            val o = el.jsonObject+            val name = o["nutrient"]?.jsonPrimitive?.content ?: return@forEach+            val g = o.nestedDouble("quantity", "grams") ?: return@forEach+            grams[name] = g+        }+        return RemoteNutrition(energyKcal = nl.nestedDouble("energy", "kcal"), nutrientGrams = grams)+    }+     /** GET dataPoints for [dataType] with [filter], following pagination. */-    private suspend fun forEachDataPoint(dataType: String, filter: String, onPoint: (JsonObject) -> Unit) {+    private suspend fun forEachDataPoint(dataType: String, filter: String, pageSize: Int = LIST_PAGE_SIZE, onPoint: (JsonObject) -> Unit) {         var pageToken: String? = null         var pages = 0+        var total = 0         do {             val url = buildString {                 append("https://health.googleapis.com/v4/users/me/dataTypes/$dataType/dataPoints")-                append("?pageSize=1000&filter=").append(Uri.encode(filter))+                append("?pageSize=").append(pageSize).append("&filter=").append(Uri.encode(filter))                 pageToken?.let { append("&pageToken=").append(Uri.encode(it)) }             }             val resp = NetworkClient.performRequest(url, "GET", headers(), null)+            if (!resp.isSuccess) {+                Log.e(TAG, "list $dataType HTTP ${resp.status}: ${resp.body.take(500)} (filter=$filter)")+                break+            }             val root = json.parseToJsonElement(resp.body) as? JsonObject ?: break-            (root["dataPoints"] as? JsonArray)?.forEach { onPoint(it.jsonObject) }+            val points = root["dataPoints"] as? JsonArray+            points?.forEach { onPoint(it.jsonObject); total++ }             pageToken = root["nextPageToken"]?.jsonPrimitive?.content?.ifBlank { null }         } while (pageToken != null && ++pages < MAX_PAGES)+        Log.i(TAG, "list $dataType -> $total points")     }      // --- helpers ---      private fun recordId(type: MeasurementType, millis: Long) = "googlehealth:${type.name}:$millis" -    /** Inclusive start / exclusive end civil-day window, clamped to the type's max range. */-    private fun window(maxRangeDays: Int, sinceMillis: Long, zone: ZoneId): Pair<LocalDate, LocalDate> {+    /** Split `[fromMillis, toMillis)` into inclusive-start/exclusive-end windows of [chunkDays]. */+    private fun chunks(fromMillis: Long, toMillis: Long, chunkDays: Int, zone: ZoneId): List<Pair<LocalDate, LocalDate>> {         val today = LocalDate.now(zone)-        val sinceDate = if (sinceMillis > 0) {-            Instant.ofEpochMilli(sinceMillis).atZone(zone).toLocalDate()-        } else {-            today.minusDays(DEFAULT_LOOKBACK_DAYS)+        // Round the end up a day so the final partial day is covered; never past today.+        val endExclusive = minOf(+            Instant.ofEpochMilli(toMillis.coerceAtLeast(0)).atZone(zone).toLocalDate().plusDays(1),+            today.plusDays(1),+        )+        var start = Instant.ofEpochMilli(fromMillis.coerceAtLeast(0)).atZone(zone).toLocalDate()+        if (start.isAfter(today)) start = today+        val out = mutableListOf<Pair<LocalDate, LocalDate>>()+        var s = start+        while (s.isBefore(endExclusive)) {+            val e = minOf(s.plusDays(chunkDays.toLong()), endExclusive)+            out += s to e+            s = e         }-        val earliest = today.minusDays(maxRangeDays.toLong())-        val start = if (sinceDate.isBefore(earliest)) earliest else sinceDate-        return start to today.plusDays(1)+        return out     }      private fun dateJson(d: LocalDate): String =@@ -241,6 +359,73 @@ class GoogleHealthClient(private val accessToken: String) {         else -> SleepSessionRecord.STAGE_TYPE_UNKNOWN     } +    /** Map a Google Health exercise enum to a Health Connect EXERCISE_TYPE_* value. */+    private fun exerciseType(google: String?): Int = when (google) {+        "BADMINTON" -> ExerciseSessionRecord.EXERCISE_TYPE_BADMINTON+        "BASEBALL" -> ExerciseSessionRecord.EXERCISE_TYPE_BASEBALL+        "BASKETBALL" -> ExerciseSessionRecord.EXERCISE_TYPE_BASKETBALL+        "BIKING", "OUTDOOR_BIKE" -> ExerciseSessionRecord.EXERCISE_TYPE_BIKING+        "STATIONARY_BIKE", "ASSAULT_BIKE", "SPINNING" -> ExerciseSessionRecord.EXERCISE_TYPE_BIKING_STATIONARY+        "BOOTCAMP" -> ExerciseSessionRecord.EXERCISE_TYPE_BOOT_CAMP+        "BOXING" -> ExerciseSessionRecord.EXERCISE_TYPE_BOXING+        "CALISTHENICS" -> ExerciseSessionRecord.EXERCISE_TYPE_CALISTHENICS+        "CRICKET" -> ExerciseSessionRecord.EXERCISE_TYPE_CRICKET+        "DANCING", "BALLET", "BALLROOM_DANCE", "HIP_HOP", "JAZZ_DANCE", "MODERN_DANCE", "TANGO", "ZUMBA" ->+            ExerciseSessionRecord.EXERCISE_TYPE_DANCING+        "ELLIPTICAL" -> ExerciseSessionRecord.EXERCISE_TYPE_ELLIPTICAL+        "EXERCISE_CLASS", "BARRE_CLASS", "CARDIO_SCULPT" -> ExerciseSessionRecord.EXERCISE_TYPE_EXERCISE_CLASS+        "FENCING" -> ExerciseSessionRecord.EXERCISE_TYPE_FENCING+        "FOOTBALL_AMERICAN" -> ExerciseSessionRecord.EXERCISE_TYPE_FOOTBALL_AMERICAN+        "FOOTBALL_AUSTRALIAN" -> ExerciseSessionRecord.EXERCISE_TYPE_FOOTBALL_AUSTRALIAN+        "GOLF" -> ExerciseSessionRecord.EXERCISE_TYPE_GOLF+        "GUIDED_BREATHING", "MEDITATE" -> ExerciseSessionRecord.EXERCISE_TYPE_GUIDED_BREATHING+        "GYMNASTICS" -> ExerciseSessionRecord.EXERCISE_TYPE_GYMNASTICS+        "HANDBALL" -> ExerciseSessionRecord.EXERCISE_TYPE_HANDBALL+        "HIIT", "INTERVAL_WORKOUT", "TABATA_WORKOUT", "CIRCUIT_TRAINING", "CROSSFIT" ->+            ExerciseSessionRecord.EXERCISE_TYPE_HIGH_INTENSITY_INTERVAL_TRAINING+        "HIKING" -> ExerciseSessionRecord.EXERCISE_TYPE_HIKING+        "HOCKEY", "FIELD_HOCKEY" -> ExerciseSessionRecord.EXERCISE_TYPE_ICE_HOCKEY+        "ICE_SKATING", "SPEED_SKATING" -> ExerciseSessionRecord.EXERCISE_TYPE_ICE_SKATING+        "MARTIAL_ARTS", "KARATE", "TAEKWONDO", "MUAY_THAI", "JIU_JITSU", "KICKBOXING" ->+            ExerciseSessionRecord.EXERCISE_TYPE_MARTIAL_ARTS+        "PADDLEBOARDING", "KAYAKING", "CANOEING", "ROWING" -> ExerciseSessionRecord.EXERCISE_TYPE_ROWING+        "ROWING_MACHINE" -> ExerciseSessionRecord.EXERCISE_TYPE_ROWING_MACHINE+        "PARAGLIDING" -> ExerciseSessionRecord.EXERCISE_TYPE_PARAGLIDING+        "PILATES" -> ExerciseSessionRecord.EXERCISE_TYPE_PILATES+        "RACQUETBALL" -> ExerciseSessionRecord.EXERCISE_TYPE_RACQUETBALL+        "ROCK_CLIMBING", "CLIMBING", "INDOOR_CLIMBING" -> ExerciseSessionRecord.EXERCISE_TYPE_ROCK_CLIMBING+        "RUGBY" -> ExerciseSessionRecord.EXERCISE_TYPE_RUGBY+        "RUNNING", "TRAIL_RUN", "INCLINE_RUN" -> ExerciseSessionRecord.EXERCISE_TYPE_RUNNING+        "TREADMILL" -> ExerciseSessionRecord.EXERCISE_TYPE_RUNNING_TREADMILL+        "SAILING", "FOILING" -> ExerciseSessionRecord.EXERCISE_TYPE_SAILING+        "SCUBA_DIVING", "DIVING" -> ExerciseSessionRecord.EXERCISE_TYPE_SCUBA_DIVING+        "SKATING", "ROLLER_SKATING", "ROLLERBLADING" -> ExerciseSessionRecord.EXERCISE_TYPE_SKATING+        "SKIING", "CROSS_COUNTRY_SKI" -> ExerciseSessionRecord.EXERCISE_TYPE_SKIING+        "SNOWBOARDING" -> ExerciseSessionRecord.EXERCISE_TYPE_SNOWBOARDING+        "SNOWSHOEING" -> ExerciseSessionRecord.EXERCISE_TYPE_SNOWSHOEING+        "SOCCER" -> ExerciseSessionRecord.EXERCISE_TYPE_SOCCER+        "SOFTBALL" -> ExerciseSessionRecord.EXERCISE_TYPE_SOFTBALL+        "SQUASH" -> ExerciseSessionRecord.EXERCISE_TYPE_SQUASH+        "STAIRCLIMBER", "STAIR_CLIMBING" -> ExerciseSessionRecord.EXERCISE_TYPE_STAIR_CLIMBING+        "STEP_TRAINING" -> ExerciseSessionRecord.EXERCISE_TYPE_STAIR_CLIMBING_MACHINE+        "STRENGTH_TRAINING", "POWERLIFTING", "FUNCTIONAL_STRENGTH_TRAINING", "FREE_WEIGHTS", "WEIGHT_MACHINES", "CORE_TRAINING", "RESISTANCE_BANDS" ->+            ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING+        "STRETCHING", "TAI_CHI" -> ExerciseSessionRecord.EXERCISE_TYPE_STRETCHING+        "SURFING" -> ExerciseSessionRecord.EXERCISE_TYPE_SURFING+        "SWIMMING_OPEN_WATER" -> ExerciseSessionRecord.EXERCISE_TYPE_SWIMMING_OPEN_WATER+        "SWIMMING_POOL", "SWIMMING", "SYNCHRONIZED_SWIMMING" -> ExerciseSessionRecord.EXERCISE_TYPE_SWIMMING_POOL+        "TABLE_TENNIS" -> ExerciseSessionRecord.EXERCISE_TYPE_TABLE_TENNIS+        "TENNIS", "PADEL", "PICKELBALL", "RACKET_SPORTS" -> ExerciseSessionRecord.EXERCISE_TYPE_TENNIS+        "VOLLEYBALL", "VOLLEYBALL_BEACH" -> ExerciseSessionRecord.EXERCISE_TYPE_VOLLEYBALL+        "WALKING", "POWER_WALKING", "NORDIC_WALKING", "STROLLER_WALK", "WALK_WITH_WEIGHTS", "RUCKING", "TREADMILL_WALK", "INCLINE_WALK" ->+            ExerciseSessionRecord.EXERCISE_TYPE_WALKING+        "WATER_POLO" -> ExerciseSessionRecord.EXERCISE_TYPE_WATER_POLO+        "WEIGHTLIFTING", "WEIGHTS" -> ExerciseSessionRecord.EXERCISE_TYPE_WEIGHTLIFTING+        "WHEELCHAIR" -> ExerciseSessionRecord.EXERCISE_TYPE_WHEELCHAIR+        "YOGA", "YOGA_BIKRAM", "YOGA_HATHA", "YOGA_POWER", "YOGA_VINYASA" -> ExerciseSessionRecord.EXERCISE_TYPE_YOGA+        else -> ExerciseSessionRecord.EXERCISE_TYPE_OTHER_WORKOUT+    }+     private fun JsonObject.nestedObject(vararg path: String): JsonObject? {         var cur: JsonElement = this         for (key in path) cur = (cur as? JsonObject)?.get(key) ?: return null@@ -269,33 +454,40 @@ class GoogleHealthClient(private val accessToken: String) {         val filterField: String = "",         /** Server-side max civil-day range for this type/method. */         val maxRangeDays: Int = MAX_RANGE_DEFAULT,+        /** Cap on how far back to backfill (raw high-frequency types stay bounded). */+        val maxBackfillDays: Int = UNBOUNDED_DAYS,         /** Multiplier applied to the raw value (unit conversion). */         val scale: Double = 1.0,     )      companion object {         private const val TAG = "GoogleHealthClient"-        private const val DEFAULT_LOOKBACK_DAYS = 30L-        private const val MAX_PAGES = 50+        private const val MAX_PAGES = 100+        private const val MAX_CONCURRENCY = 6 // parallel in-flight requests+        private const val LIST_PAGE_SIZE = 10000 // API max for dataPoints+        private const val SESSION_PAGE_SIZE = 25 // API max for exercise + sleep         private const val MAX_RANGE_DEFAULT = 90         private const val MAX_RANGE_14 = 14 // heart-rate & total-calories are capped at 14 days+        private const val UNBOUNDED_DAYS = 1_000_000 // effectively no per-type backfill cap         private const val DAY_MILLIS = 86_400_000L         private const val GRAMS_PER_KG = 1000.0         private const val MM_PER_METER = 1000.0         private const val ML_PER_LITER = 1000.0          private val SPECS = listOf(-            // Activity — dailyRollUp aggregates over each civil day.-            Spec("steps", MeasurementType.STEPS, Mode.ROLLUP, "steps", arrayOf("countSum")),-            Spec("distance", MeasurementType.DISTANCE, Mode.ROLLUP, "distance", arrayOf("millimetersSum"), scale = 1.0 / MM_PER_METER),+            // Activity — raw intervals (the API's native ~per-minute buckets) for full resolution.+            Spec("steps", MeasurementType.STEPS, Mode.LIST_SESSION, "steps", arrayOf("count"), filterField = "steps"),+            Spec("distance", MeasurementType.DISTANCE, Mode.LIST_SESSION, "distance", arrayOf("millimeters"), filterField = "distance", scale = 1.0 / MM_PER_METER),+            Spec("altitude", MeasurementType.ELEVATION, Mode.LIST_SESSION, "altitude", arrayOf("gainMillimeters"), filterField = "altitude", scale = 1.0 / MM_PER_METER),+            Spec("active-energy-burned", MeasurementType.ACTIVE_CALORIES, Mode.LIST_SESSION, "activeEnergyBurned", arrayOf("kcal"), filterField = "active_energy_burned"),+            // floors is not list-able and total-calories is rollup-only, so both stay daily rollups.             Spec("floors", MeasurementType.FLOORS, Mode.ROLLUP, "floors", arrayOf("countSum")),-            Spec("active-energy-burned", MeasurementType.ACTIVE_CALORIES, Mode.ROLLUP, "activeEnergyBurned", arrayOf("kcalSum")),             Spec("total-calories", MeasurementType.TOTAL_CALORIES, Mode.ROLLUP, "totalCalories", arrayOf("kcalSum"), maxRangeDays = MAX_RANGE_14), -            // Vitals — heart rate rolls up; the rest are samples / daily summaries.-            Spec("heart-rate", MeasurementType.HEART_RATE, Mode.ROLLUP, "heartRate", arrayOf("beatsPerMinuteAvg"), maxRangeDays = MAX_RANGE_14),+            // Vitals — raw samples where the API provides them.+            Spec("heart-rate", MeasurementType.HEART_RATE, Mode.LIST_SAMPLE, "heartRate", arrayOf("beatsPerMinute"), filterField = "heart_rate", maxRangeDays = MAX_RANGE_14),+            Spec("oxygen-saturation", MeasurementType.OXYGEN_SATURATION, Mode.LIST_SAMPLE, "oxygenSaturation", arrayOf("percentage"), filterField = "oxygen_saturation"),             Spec("daily-resting-heart-rate", MeasurementType.RESTING_HEART_RATE, Mode.LIST_DAILY, "dailyRestingHeartRate", arrayOf("beatsPerMinute"), filterField = "daily_resting_heart_rate"),-            Spec("daily-oxygen-saturation", MeasurementType.OXYGEN_SATURATION, Mode.LIST_DAILY, "dailyOxygenSaturation", arrayOf("averagePercentage"), filterField = "daily_oxygen_saturation"),             Spec("daily-respiratory-rate", MeasurementType.RESPIRATORY_RATE, Mode.LIST_DAILY, "dailyRespiratoryRate", arrayOf("breathsPerMinute"), filterField = "daily_respiratory_rate"),             Spec("heart-rate-variability", MeasurementType.HEART_RATE_VARIABILITY, Mode.LIST_SAMPLE, "heartRateVariability", arrayOf("rootMeanSquareOfSuccessiveDifferencesMilliseconds"), filterField = "heart_rate_variability"),             Spec("blood-glucose", MeasurementType.BLOOD_GLUCOSE, Mode.LIST_SAMPLE, "bloodGlucose", arrayOf("bloodGlucoseMilligramsPerDeciliter"), filterField = "blood_glucose"),
everysync/src/main/java/com/vayunmathur/everysync/sink/HealthSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sink/HealthSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/sink/HealthSink.ktindex 70ff4b7099..ab735c0b60 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sink/HealthSink.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sink/HealthSink.kt@@ -8,11 +8,14 @@ import androidx.health.connect.client.records.BloodGlucoseRecord import androidx.health.connect.client.records.BodyFatRecord import androidx.health.connect.client.records.BodyTemperatureRecord import androidx.health.connect.client.records.DistanceRecord+import androidx.health.connect.client.records.ElevationGainedRecord+import androidx.health.connect.client.records.ExerciseSessionRecord import androidx.health.connect.client.records.FloorsClimbedRecord import androidx.health.connect.client.records.HeartRateRecord import androidx.health.connect.client.records.HeartRateVariabilityRmssdRecord import androidx.health.connect.client.records.HeightRecord import androidx.health.connect.client.records.HydrationRecord+import androidx.health.connect.client.records.NutritionRecord import androidx.health.connect.client.records.OxygenSaturationRecord import androidx.health.connect.client.records.Record import androidx.health.connect.client.records.RespiratoryRateRecord@@ -32,8 +35,14 @@ import androidx.health.connect.client.units.Temperature import androidx.health.connect.client.units.Volume import com.vayunmathur.everysync.model.MeasurementType import com.vayunmathur.everysync.model.RemoteMeasurement+import com.vayunmathur.everysync.model.RemoteNutrition import java.time.Instant import java.time.ZoneId+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.sync.Semaphore+import kotlinx.coroutines.sync.withPermit  /**  * Writes [RemoteMeasurement]s into Health Connect. Uses a stable `clientRecordId`@@ -42,18 +51,83 @@ import java.time.ZoneId  */ object HealthSink {     private const val TAG = "HealthSink"+    private const val INSERT_BATCH = 1000+    private const val INSERT_CONCURRENCY = 4+    private const val HR_SAMPLES_PER_RECORD = 1000+    private const val HR_RECORDS_PER_INSERT = 50 // bounds samples-per-insert (~50k)     private val zone = ZoneId.systemDefault()      suspend fun upsert(context: Context, measurements: List<RemoteMeasurement>) {         if (measurements.isEmpty()) return         val client = HealthConnectClient.getOrCreate(context)-        val records = measurements.mapNotNull { toRecord(it) }-        if (records.isEmpty()) return-        try {-            client.insertRecords(records)-        } catch (e: Exception) {-            Log.e(TAG, "insertRecords failed", e)+        // Heart rate is a *series* record: collapse the many per-second/minute+        // samples into a handful of multi-sample records instead of one record+        // each. Same resolution, but ~1000x fewer records to insert.+        val (heartRate, other) = measurements.partition { it.type == MeasurementType.HEART_RATE }+        val hrRecords = heartRateSeries(heartRate)+        Log.i(+            TAG,+            "upsert: ${measurements.size} measurements " ++                "(${heartRate.size} HR samples -> ${hrRecords.size} HR series); " ++                measurements.groupingBy { it.type }.eachCount(),+        )+        // Batch sizes: HR series records each carry up to HR_SAMPLES_PER_RECORD+        // samples, so a batch of them is far larger than a batch of scalar records.+        // Keep HR batches small so a single insert doesn't blow past Health+        // Connect's per-transaction limits (which silently fails the whole call).+        val scalar = other.mapNotNull { toRecord(it) }+        val batches = scalar.chunked(INSERT_BATCH) + hrRecords.chunked(HR_RECORDS_PER_INSERT)+        val semaphore = Semaphore(INSERT_CONCURRENCY)+        var inserted = 0+        coroutineScope {+            batches.map { batch ->+                async {+                    semaphore.withPermit {+                        try {+                            client.insertRecords(batch)+                            synchronized(this@HealthSink) { inserted += batch.size }+                        } catch (e: Exception) {+                            Log.e(TAG, "insertRecords failed (${batch.size} records)", e)+                        }+                    }+                }+            }.awaitAll()         }+        Log.i(TAG, "upsert: inserted $inserted / ${scalar.size + hrRecords.size} records")+    }++    /**+     * Group heart-rate samples into series [HeartRateRecord]s (bucketed by civil+     * day, capped at [HR_SAMPLES_PER_RECORD] samples each). Deterministic+     * clientRecordIds keep re-syncing an overlapping window an idempotent upsert.+     */+    private fun heartRateSeries(measurements: List<RemoteMeasurement>): List<Record> {+        if (measurements.isEmpty()) return emptyList()+        val out = mutableListOf<Record>()+        measurements.groupBy { Instant.ofEpochMilli(it.startMillis).atZone(zone).toLocalDate() }+            .forEach { (day, dayMeasurements) ->+                dayMeasurements.sortedBy { it.startMillis }+                    .chunked(HR_SAMPLES_PER_RECORD)+                    .forEachIndexed { bucket, chunk ->+                        val samples = chunk.map {+                            HeartRateRecord.Sample(Instant.ofEpochMilli(it.startMillis), it.value.toLong())+                        }+                        val startInst = Instant.ofEpochMilli(chunk.first().startMillis)+                        var endInst = Instant.ofEpochMilli(chunk.last().startMillis)+                        if (!endInst.isAfter(startInst)) endInst = startInst.plusMillis(1)+                        out += HeartRateRecord(+                            startTime = startInst,+                            startZoneOffset = zone.rules.getOffset(startInst),+                            endTime = endInst,+                            endZoneOffset = zone.rules.getOffset(endInst),+                            samples = samples,+                            metadata = Metadata.manualEntry(+                                clientRecordId = "googlehealth:HEART_RATE:$day:$bucket",+                            ),+                        )+                    }+            }+        return out     }      private fun toRecord(m: RemoteMeasurement): Record? {@@ -114,6 +188,11 @@ object HealthSink {                 endTime = end, endZoneOffset = endOffset,                 floors = m.value, metadata = meta,             )+            MeasurementType.ELEVATION -> ElevationGainedRecord(+                startTime = start, startZoneOffset = startOffset,+                endTime = end, endZoneOffset = endOffset,+                elevation = Length.meters(m.value), metadata = meta,+            )             MeasurementType.ACTIVE_CALORIES -> ActiveCaloriesBurnedRecord(                 startTime = start, startZoneOffset = startOffset,                 endTime = end, endZoneOffset = endOffset,@@ -130,7 +209,7 @@ object HealthSink {                 volume = Volume.liters(m.value), metadata = meta,             ) -            // --- Lifestyle (session) ---+            // --- Sessions ---             MeasurementType.SLEEP -> SleepSessionRecord(                 startTime = start,                 startZoneOffset = startOffset,@@ -145,6 +224,76 @@ object HealthSink {                 },                 metadata = meta,             )+            MeasurementType.EXERCISE -> ExerciseSessionRecord(+                startTime = start,+                startZoneOffset = startOffset,+                endTime = end,+                endZoneOffset = endOffset,+                exerciseType = m.exerciseType,+                title = m.title,+                notes = m.notes,+                metadata = meta,+            )+            MeasurementType.NUTRITION -> nutritionRecord(m, start, startOffset, end, endOffset, meta)         }     }++    private fun nutritionRecord(+        m: RemoteMeasurement,+        start: Instant,+        startOffset: java.time.ZoneOffset,+        end: Instant,+        endOffset: java.time.ZoneOffset,+        meta: Metadata,+    ): NutritionRecord {+        val n: RemoteNutrition = m.nutrition ?: RemoteNutrition()+        fun g(key: String) = n.nutrientGrams[key]?.let { Mass.grams(it) }+        return NutritionRecord(+            startTime = start, startZoneOffset = startOffset,+            endTime = end, endZoneOffset = endOffset,+            name = m.title,+            energy = n.energyKcal?.let { Energy.kilocalories(it) },+            totalFat = g("TOTAL_FAT"),+            totalCarbohydrate = g("TOTAL_CARBOHYDRATE"),+            protein = g("PROTEIN"),+            dietaryFiber = g("DIETARY_FIBER"),+            sugar = g("SUGAR"),+            sodium = g("SODIUM"),+            biotin = g("BIOTIN"),+            caffeine = g("CAFFEINE"),+            calcium = g("CALCIUM"),+            chloride = g("CHLORIDE"),+            cholesterol = g("CHOLESTEROL"),+            chromium = g("CHROMIUM"),+            copper = g("COPPER"),+            folate = g("FOLATE"),+            folicAcid = g("FOLIC_ACID"),+            iodine = g("IODINE"),+            iron = g("IRON"),+            magnesium = g("MAGNESIUM"),+            manganese = g("MANGANESE"),+            molybdenum = g("MOLYBDENUM"),+            monounsaturatedFat = g("MONOUNSATURATED_FAT"),+            niacin = g("NIACIN"),+            pantothenicAcid = g("PANTOTHENIC_ACID"),+            phosphorus = g("PHOSPHORUS"),+            polyunsaturatedFat = g("POLYUNSATURATED_FAT"),+            potassium = g("POTASSIUM"),+            riboflavin = g("RIBOFLAVIN"),+            saturatedFat = g("SATURATED_FAT"),+            selenium = g("SELENIUM"),+            thiamin = g("THIAMIN"),+            transFat = g("TRANS_FAT"),+            unsaturatedFat = g("UNSATURATED_FAT"),+            vitaminA = g("VITAMIN_A"),+            vitaminB12 = g("VITAMIN_B12"),+            vitaminB6 = g("VITAMIN_B6"),+            vitaminC = g("VITAMIN_C"),+            vitaminD = g("VITAMIN_D"),+            vitaminE = g("VITAMIN_E"),+            vitaminK = g("VITAMIN_K"),+            zinc = g("ZINC"),+            metadata = meta,+        )+    } }