Colota - Android GPS Location tracker
fix(sync): apply a changed sync interval to the wait already running (#895)
Max Dietrichdb24a4865af9
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex 6f9a8985..c6363a36 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -201,7 +201,7 @@ Orchestrates batch location uploads with:- Configurable batch size (50 items per batch, 10 concurrent HTTP requests)- Exponential backoff on failure-- Periodic sync scheduling+- Periodic sync scheduling. A new interval (a profile switch) applies to the wait already running, measured from when it began; a send or a backoff in progress finishes first- Manual flush support- One pass at a time: a periodic tick and a manual flush wait for the running pass. An instant send leaves its row queued while a pass runs, and a pass skips rows an instant send is still postingdiff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.mdindex f0a8f9e9..6f559020 100644--- a/apps/docs/docs/guides/tracking-profiles.md+++ b/apps/docs/docs/guides/tracking-profiles.md@@ -77,7 +77,7 @@ Each profile overrides the default tracking configuration with:- **Activation Delay** - How long the condition must keep matching before the profile is applied (seconds, default 0 = immediate). Prevents activating on brief spikes, e.g. a momentary speed reading. For the Stationary condition it instead sets how long the device must be still before the profile activates (default 60s).- **Deactivation Delay** - How long the profile stays active after its condition stops matching, also when a lower-priority profile matches (seconds). Prevents rapid toggling when conditions fluctuate.-When creating a new profile, the tracking interval, movement threshold and sync interval are pre-filled with your current Tracking & sync values, and each field says which value it replaces. The values a profile hands back to are the ones the service loaded when tracking started; a Tracking & sync change applies at the next restart.+When creating a new profile, the tracking interval, movement threshold and sync interval are pre-filled with your current Tracking & sync values, and each field says which value it replaces. The values a profile hands back to are the ones the service loaded when tracking started; a Tracking & sync change applies at the next restart. A profile's sync interval applies at the switch, counted from the last scheduled sync; a shorter one syncs at once when that much time has already passed.**Choosing delay values:** together the two delays make a profile "sticky" - hard to switch on by accident, hard to switch off by accident. Clean on/off signals like Charging and Android Auto want activation 0 (switch the instant you plug in or connect) plus a small deactivation delay so a brief disconnect or cable wiggle does not drop you. Noisy signals like speed want both: an activation delay to ignore short spikes (a Driving profile won't trigger from one GPS glitch while you walk) and a longer deactivation delay to ride through red lights, traffic and tunnels without flapping. Rule of thumb: if a profile keeps flickering on and off, raise the delays; if it reacts too slowly, lower them. Tracking never stops during either wait - you stay on your defaults through an activation delay, and on the profile through a deactivation delay.diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.ktindex 13cc45ef..f1ee37c9 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt@@ -10,6 +10,7 @@ import com.Colota.bridge.LocationServiceModuleimport com.Colota.data.DatabaseHelperimport com.Colota.util.TimedCacheimport kotlinx.coroutines.*+import kotlinx.coroutines.channels.Channelimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLockimport org.json.JSONObject@@ -22,7 +23,8 @@ import java.util.concurrent.ConcurrentHashMapclass SyncManager(private val dbHelper: DatabaseHelper,private val networkManager: NetworkManager,- private val scope: CoroutineScope+ private val scope: CoroutineScope,+ private val clock: () -> Long = System::currentTimeMillis) {companion object {private const val TAG = "SyncManager"@@ -64,6 +66,8 @@ class SyncManager(/** Queue rows an instant send is posting; a pass skips them instead of posting them a second time. */private val instantInFlight: MutableSet<Long> = ConcurrentHashMap.newKeySet()+ private val intervalChanged = Channel<Unit>(Channel.CONFLATED)+fun updateConfig(endpoint: String,syncIntervalSeconds: Int,@@ -77,7 +81,9 @@ class SyncManager(overlandBatchSize: Int = 50,) {this.endpoint = endpoint+ val intervalDiffers = syncIntervalSeconds != this.syncIntervalSecondsthis.syncIntervalSeconds = syncIntervalSeconds+ if (intervalDiffers) intervalChanged.trySend(Unit)this.retryIntervalSeconds = retryIntervalSecondsthis.isOfflineMode = isOfflineModethis.syncCondition = syncCondition@@ -91,9 +97,11 @@ class SyncManager(fun startPeriodicSync() {AppLogger.d(TAG, "Starting periodic sync: interval=${syncIntervalSeconds}s, endpoint=${if (endpoint.isBlank()) "NONE" else AppLogger.maskSensitiveUrlValues(endpoint)}")syncJob = scope.launch {+ var resumingWait = falsewhile (isActive) {- val baseDelay = calculateNextSyncDelay()- delay(baseDelay * 1000L)+ val baseDelay = calculateNextSyncDelay(resumingWait)+ resumingWait = withTimeoutOrNull(baseDelay * 1000L) { intervalChanged.receive() } != null+ if (resumingWait) continueval queued = getCachedQueuedCount()val allowed = isSyncAllowed()@@ -454,7 +462,7 @@ class SyncManager(}}- private fun calculateNextSyncDelay(): Long {+ private fun calculateNextSyncDelay(resumingWait: Boolean): Long {if (syncIntervalSeconds <= 0) {return if (getCachedQueuedCount() > 0) {retryIntervalSeconds.toLong()@@ -463,7 +471,7 @@ class SyncManager(}}- val now = System.currentTimeMillis()+ val now = clock()if (!syncInitialized) {lastSyncTime = nowsyncInitialized = true@@ -473,11 +481,13 @@ class SyncManager(val elapsedSeconds = (now - lastSyncTime) / 1000val remaining = syncIntervalSeconds - elapsedSeconds- return if (remaining <= 0) {- lastSyncTime = now- syncIntervalSeconds.toLong()- } else {- remaining+ return when {+ remaining > 0 -> remaining+ resumingWait -> 0L+ else -> {+ lastSyncTime = now+ syncIntervalSeconds.toLong()+ }}}}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.ktindex 03b979e5..232a20df 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt@@ -929,6 +929,94 @@ class SyncManagerTest {verify(exactly = 0) { dbHelper.getQueuedLocations(any()) }}+ // ========================================================================+ // Interval change mid-wait (a profile switch swaps the sync interval)+ // ========================================================================++ private var ticks = 0++ private fun startPeriodicSyncOnVirtualClock(intervalSeconds: Int, queuedCount: Int = 0): SyncManager {+ val manager = SyncManager(dbHelper, networkManager, scope, clock = { scope.testScheduler.currentTime })+ manager.switchInterval(intervalSeconds)+ coEvery { networkManager.isNetworkAvailable() } returns true+ every { dbHelper.getQueuedCount() } returns queuedCount+ every { dbHelper.getQueuedLocations(50) } returns emptyList()+ every { AppLogger.d("SyncManager", match { it.startsWith("Sync tick:") }) } answers { ticks += 1 }+ manager.startPeriodicSync()+ return manager+ }++ private fun SyncManager.switchInterval(seconds: Int) = updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = seconds,+ retryIntervalSeconds = 30,+ isOfflineMode = false,+ syncCondition = "any",+ syncSsid = "",+ authHeaders = emptyMap()+ )++ @Test+ fun `a shorter interval applies to the wait already running instead of after it`() = scope.runTest {+ val manager = startPeriodicSyncOnVirtualClock(300)++ advanceTimeBy(10_000)+ manager.switchInterval(60)++ advanceTimeBy(49_000)+ assertEquals("60 s from the start of the wait has not passed yet", 0, ticks)+ advanceTimeBy(2_000)+ assertEquals("the profile's 60 s is honoured, not the 300 s the wait began with", 1, ticks)+ advanceTimeBy(60_000)+ assertEquals("the new interval sets the cadence from then on", 2, ticks)+ manager.stopPeriodicSync()+ }++ @Test+ fun `a shorter interval already served by the running wait syncs at once`() = scope.runTest {+ val manager = startPeriodicSyncOnVirtualClock(300)++ advanceTimeBy(200_000)+ manager.switchInterval(60)+ runCurrent()++ assertEquals("200 s have passed, more than the new 60 s, so no further wait is owed", 1, ticks)+ advanceTimeBy(59_000)+ assertEquals(1, ticks)+ advanceTimeBy(2_000)+ assertEquals(2, ticks)+ manager.stopPeriodicSync()+ }++ @Test+ fun `a longer interval extends the wait already running`() = scope.runTest {+ val manager = startPeriodicSyncOnVirtualClock(60)++ advanceTimeBy(30_000)+ manager.switchInterval(300)++ advanceTimeBy(269_000)+ assertEquals("the old 60 s must not fire once more before the new interval takes over", 0, ticks)+ advanceTimeBy(2_000)+ assertEquals(1, ticks)+ manager.stopPeriodicSync()+ }++ @Test+ fun `an interval change during a backoff does not cut the backoff short`() = scope.runTest {+ val manager = startPeriodicSyncOnVirtualClock(10, queuedCount = 5)++ advanceTimeBy(20_000)+ verify(exactly = 1) { dbHelper.getQueuedLocations(50) }+ manager.switchInterval(5)++ advanceTimeBy(24_000)+ verify(exactly = 1) { dbHelper.getQueuedLocations(50) }+ advanceTimeBy(2_000)+ verify(exactly = 2) { dbHelper.getQueuedLocations(50) }+ manager.stopPeriodicSync()+ }+// ========================================================================// Async exception isolation (fix: one bad item must not kill the chunk)// ========================================================================diff --git a/fastlane/metadata/android/en-US/changelogs/51.txt b/fastlane/metadata/android/en-US/changelogs/51.txtindex 153a2326..71a76a80 100644--- a/fastlane/metadata/android/en-US/changelogs/51.txt+++ b/fastlane/metadata/android/en-US/changelogs/51.txt@@ -1,3 +1,4 @@- A tracking profile keeps its deactivation delay when a lower-priority profile starts to match- Setup links show the full server address with its host on its own line, name the server they replace and are rejected as a whole when the address hides its host- Placing a geofence shows where you are and the locate button puts the zone there+- A tracking profile's sync interval takes effect as soon as the profile switches