Skip to content

Commit 7a286ba

Browse files
committed
Never write Health Connect imports back, and make wger a clean two-way sync
A measurement imported from Health Connect was exported back as a record of ours next to the original app's. No app can change another app's record, so Health Connect now never gets back what was imported from it, not even after an edit in openScale. Other services still get everything. wger 2.4 and later allow any number of entries per date, so the blind POST left a duplicate whenever a time already existed there. Exports are now an upsert: an entry in the same second is patched, otherwise a new one is posted. The import keeps wger's own time instead of midnight, so an edit made in openScale reaches wger as well. - import several wger weigh-ins per day, matched to the second; entries without a real time (wger <= 2.3, and their 2.4 migration to midnight) are still matched by day - read every page of wger entries, not just the first 999 - send and read weights in the unit of the wger profile (kg/lb), rounded to the 2 decimals wger accepts - every sync follows the direction set for each service: "Sync now" exported even with the direction set to import only, and never imported. The global and the periodic sync import from all services first, then export, so every service gets every import of the same run Fixes #51
1 parent edb10c0 commit 7a286ba

13 files changed

Lines changed: 833 additions & 134 deletions

File tree

‎src/app/src/main/java/com/health/openscale/sync/core/service/HealthConnectService.kt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,9 @@ class HealthConnectService(
132132
// HealthConnect can read foreign records → bidirectional.
133133
override val supportsInbound: Boolean get() = true
134134

135+
// A foreign record cannot be changed, only copied next to it: never write an import back (#51).
136+
override val exportsImported: Boolean get() = false
137+
135138
// HealthConnect writes the whole batch in one insertRecords call. Updates take the same path:
136139
// the write is a clientRecordId upsert, so a batch of updates is a batch of writes — no reason
137140
// to fall back to the per-item default loop (a forced full sync would otherwise be one round

‎src/app/src/main/java/com/health/openscale/sync/core/service/ServiceInterface.kt‎

Lines changed: 91 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,16 @@ data class InboundStats(
9898
val updated: Int = 0
9999
) {
100100
val total: Int get() = imported + updated
101+
102+
operator fun plus(o: InboundStats) = InboundStats(imported + o.imported, updated + o.updated)
103+
}
104+
105+
/** What a manual sync did in both directions: [exported] to the backend, [imported] from it. */
106+
data class FullSyncStats(
107+
val exported: ReconcileStats = ReconcileStats(),
108+
val imported: InboundStats = InboundStats()
109+
) {
110+
operator fun plus(o: FullSyncStats) = FullSyncStats(exported + o.exported, imported + o.imported)
101111
}
102112

103113
/**
@@ -171,6 +181,16 @@ abstract class ServiceInterface (
171181
/** Whether this backend can pull data INTO openScale (bidirectional). HealthConnect/Wger = true. */
172182
open val supportsInbound: Boolean get() = false
173183

184+
/**
185+
* Whether measurements imported from this backend are still exported back to it. True wherever
186+
* writing back is harmless: Wger patches the entry the measurement came from, and MQTT reads
187+
* `<base>/inbound/…` but publishes openScale's complete state, which consumers expect to include
188+
* imported values — so an edit made in openScale reaches the source too. False where it is not:
189+
* Health Connect lets no app change another app's record, so writing back only adds a copy of
190+
* ours next to the original.
191+
*/
192+
open val exportsImported: Boolean get() = true
193+
174194
/** Outbound active unless the user set this backend to import-only. */
175195
fun exportEnabled(): Boolean = viewModel().syncDirection.value != SyncDirection.IMPORT
176196

@@ -185,13 +205,29 @@ abstract class ServiceInterface (
185205
exportEnabled() && (isMultiUser || userId == viewModel().selectedUserId.value)
186206

187207
/**
188-
* Full manual sync of all measurements of the selected user to this backend.
189-
* Returns what was actually pushed on success, or null on failure (the error is surfaced via the
190-
* error banner). Only call from the UI context where openScaleService/openScaleDataService are
191-
* wired.
208+
* Full manual sync with this backend, in the direction the user set for it: import first, then
209+
* export — the order every sync uses, so whatever comes from this backend is known as the
210+
* source's before anything is exported to it (see [isImported]). Returns what was actually
211+
* imported and pushed on success, or null on failure (the error is surfaced via the error
212+
* banner). Only call from the UI context where openScaleService/openScaleDataService are wired.
192213
*/
193-
suspend fun runFullSync() : ReconcileStats? {
194-
// Multi-user backends sync all users; single-user backends only their selected user.
214+
suspend fun runFullSync() : FullSyncStats? {
215+
var imported = InboundStats()
216+
if (importEnabled()) {
217+
when (val r = runInbound(if (isMultiUser) -1 else viewModel().selectedUserId.value)) {
218+
is SyncResult.Success -> imported = r.data
219+
is SyncResult.Failure -> {
220+
setErrorMessage(r)
221+
return null
222+
}
223+
}
224+
}
225+
if (!exportEnabled()) {
226+
viewModel().setLastSync(Instant.now())
227+
return FullSyncStats(imported = imported)
228+
}
229+
// Read after the import, so what it just added goes out to this backend as well. Multi-user
230+
// backends sync all users; single-user backends only their selected user.
195231
val measurements = try {
196232
val allUsers = openScaleDataService.getUsers()
197233
val users = if (isMultiUser) allUsers else allUsers.filter { it.id == viewModel().selectedUserId.value }
@@ -215,7 +251,7 @@ abstract class ServiceInterface (
215251
return when (result) {
216252
is SyncResult.Success -> {
217253
viewModel().setLastSync(Instant.now())
218-
result.data
254+
FullSyncStats(result.data, imported)
219255
}
220256
is SyncResult.Failure -> {
221257
setErrorMessage(result)
@@ -317,6 +353,12 @@ abstract class ServiceInterface (
317353
skippedNoWeight++
318354
continue
319355
}
356+
// Imported from this very backend: nothing of ours to send. Also stays in currentIds,
357+
// so an earlier echo of it is neither re-pushed nor deleted.
358+
if (isImported(m)) {
359+
unchanged++
360+
continue
361+
}
320362
val prev = ledger[m.id]
321363
when {
322364
prev == null -> inserts += m
@@ -395,7 +437,7 @@ abstract class ServiceInterface (
395437
// so the periodic worker doesn't rewrite unchanged snapshots every run. Best-effort.
396438
val snapshotUsers = if (force) current.mapTo(HashSet()) { it.userId } else changedUsers
397439
if (snapshotUsers.isNotEmpty()) {
398-
runCatching { onReconciled(current, snapshotUsers) }
440+
runCatching { onReconciled(current.filterNot { isImported(it) }, snapshotUsers) }
399441
.onFailure { Timber.w(it, "onReconciled hook failed") }
400442
}
401443

@@ -414,6 +456,31 @@ abstract class ServiceInterface (
414456
*/
415457
protected open suspend fun onReconciled(current: List<OpenScaleMeasurement>, changedUserIds: Set<Int>) {}
416458

459+
// --- Inbound origin (no write-back to the source, issue #51) -------------------------
460+
// Per-backend set of the measurements runInbound took FROM this backend, as "userId:timeMs",
461+
// kept only where [exportsImported] is false. Such a measurement is never exported back to that
462+
// backend, not even after an edit in openScale: on Health Connect it would sit as a record of
463+
// ours next to the original app's (Google's write guidance forbids writing back what was read).
464+
// The source keeps its own record; a correction belongs there and comes back with the next
465+
// import. Other backends still get everything. Per measurement, not per value: an inbound
466+
// reading always carries the weight, which every backend anchors its payload on, so no part of
467+
// such a measurement is ours to send.
468+
private val originPrefs by lazy {
469+
context.getSharedPreferences("inbound_origin_${viewModel().getName()}", Context.MODE_PRIVATE)
470+
}
471+
472+
private fun originKey(userId: Int, timeMs: Long) = "$userId:$timeMs"
473+
474+
private fun originRecord(keys: Set<String>) {
475+
if (keys.isEmpty()) return
476+
synchronized(ledgerLock) {
477+
originPrefs.edit { putStringSet("origin", originPrefs.getStringSet("origin", emptySet()).orEmpty() + keys) }
478+
}
479+
}
480+
481+
private fun isImported(m: OpenScaleMeasurement): Boolean =
482+
!exportsImported && originKey(m.userId, m.date.time) in originPrefs.getStringSet("origin", emptySet()).orEmpty()
483+
417484
// --- Inbound (Phase 4: external source → openScale) ---------------------------------
418485
/**
419486
* Inbound-capable backends ([supportsInbound]) override this to pull measurements from their
@@ -460,6 +527,10 @@ abstract class ServiceInterface (
460527
.mapTo(HashSet()) { it.date.time }
461528
}
462529

530+
// Recorded BEFORE writing, so no export running meanwhile (the periodic worker, a manual
531+
// sync) can see one of these measurements without knowing it is the source's.
532+
if (!exportsImported) originRecord(items.mapTo(HashSet()) { originKey(it.userId ?: userId, it.timeMs) })
533+
463534
var updated = 0
464535
val attempted = HashMap<Int, MutableList<Long>>()
465536
for (m in items) {
@@ -585,7 +656,17 @@ abstract class ServiceInterface (
585656
* the ledger is a MOVE — backends key records by (user, time), so we drop the stale record at the
586657
* old time and recreate at the new one. No retry-enqueue here; submit()/drainQueue() own that.
587658
*/
588-
private suspend fun dispatchOp(op: PendingOp): SyncResult<Unit> = when (op.type) {
659+
private suspend fun dispatchOp(op: PendingOp): SyncResult<Unit> {
660+
// A measurement imported from this backend is the source's: nothing to send, and no ledger
661+
// entry either, since nothing was exported. Deletes still go out unchanged — suppressing one
662+
// would only let the next import bring the measurement straight back.
663+
if ((op.type == "insert" || op.type == "update") && isImported(op.toMeasurement())) {
664+
return SyncResult.Success(Unit)
665+
}
666+
return dispatchWire(op)
667+
}
668+
669+
private suspend fun dispatchWire(op: PendingOp): SyncResult<Unit> = when (op.type) {
589670
"insert" -> op.toMeasurement().let { m ->
590671
insert(m).also { if (it is SyncResult.Success) ledgerRecord(op.id, m) }
591672
}
@@ -770,6 +851,7 @@ abstract class ServiceInterface (
770851
fun resetSyncState() {
771852
ledgerStore(emptyMap())
772853
dirtyStore(emptyMap())
854+
synchronized(ledgerLock) { originPrefs.edit { clear() } } // keyed by that install's user ids
773855
viewModel().setSelectedUserId(-1) // user ids belong to that install too
774856
}
775857

‎src/app/src/main/java/com/health/openscale/sync/core/service/WgerService.kt‎

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,7 @@ import kotlinx.coroutines.launch
4646
import okhttp3.OkHttpClient
4747
import retrofit2.Retrofit
4848
import retrofit2.converter.gson.GsonConverterFactory
49-
import java.text.SimpleDateFormat
5049
import java.util.Date
51-
import java.util.Locale
52-
import java.util.TimeZone
5350

5451
class WgerService(
5552
private val context: Context,
@@ -94,21 +91,18 @@ class WgerService(
9491
else SyncResult.Failure(SyncResult.ErrorType.PERMISSION_DENIED)
9592

9693
/**
97-
* Inbound source (bidirectional): read weight entries from Wger. Wger has no data origin and
98-
* only a date, so we apply openScale-as-master day-level gap-fill: only return entries for days
99-
* openScale has no measurement yet (avoids echo/duplicates). The base [runInbound] writes them.
94+
* Inbound source (bidirectional): read weight entries from Wger and return those openScale has
95+
* no measurement for yet — several per day included ([WgerSync.unknownToOpenScale]). The base
96+
* [runInbound] writes them, at wger's own time, which is what lets an export of them patch the
97+
* entry they came from.
10098
*/
10199
override suspend fun readInbound(userId: Int, sinceMs: Long): List<InboundMeasurement> {
102100
if (!::wgerSync.isInitialized || !viewModel.connectAvailable.value || !viewModel.allPermissionsGranted.value) {
103101
throw IllegalStateException("Wger not connected")
104102
}
105-
val entries = wgerSync.readInboundWeights()
106-
val dayKey = SimpleDateFormat("yyyy-MM-dd", Locale.US).apply { timeZone = TimeZone.getDefault() }
107-
val existingDays = openScaleDataService.getMeasurements(OpenScaleUser(userId, ""))
108-
.map { dayKey.format(it.date) }.toSet()
109-
return entries.mapNotNull { (dateMs, kg) ->
110-
if (dayKey.format(Date(dateMs)) in existingDays) null else InboundMeasurement(dateMs, kg)
111-
}
103+
val openScaleTimes = openScaleDataService.getMeasurements(OpenScaleUser(userId, "")).map { it.date.time }
104+
return WgerSync.unknownToOpenScale(wgerSync.readInboundWeights(), openScaleTimes)
105+
.map { InboundMeasurement(it.timeMs, it.weightKg) }
112106
}
113107

114108
private suspend fun connectWger() {

0 commit comments

Comments
 (0)