Colota - Android GPS Location tracker
fix(sync): stop a pass on a rate limit or an unreachable server (#934)
Max Dietrichd3a1aad6f256
diff --git a/apps/docs/docs/api-reference.md b/apps/docs/docs/api-reference.mdindex 3d0b7a2b..78018d0e 100644--- a/apps/docs/docs/api-reference.md+++ b/apps/docs/docs/api-reference.md@@ -93,7 +93,7 @@ In the default field-mapped format Colota sends **one location per HTTP request*The Overland format, and Dawarich in batch mode, instead send **an array of locations in a single request**. Batch size is configurable (1 to 500, default 50) and up to 10 batches are sent per cycle, so one cycle can move considerably more than 500 points.-Your server should handle multiple simultaneous POST requests. If you have rate limiting, some requests may fail and be retried.+Your server should handle multiple simultaneous POST requests. If it rate limits, a 429 stops the sync pass and the remaining points go out on the next sync.## Testing with curl@@ -134,12 +134,14 @@ Your server only needs to return a 2xx status code. The response body is not rea## Error Handling-| Error Type | Behavior |-| ------------------------ | ------------------------------------------ |-| **Any non-2xx response** | Queued for retry |-| **Network timeout** | Retried (10s connection, 10s read timeout) |+| Outcome | Behavior |+| --- | --- |+| **429 Too Many Requests** | The sync pass stops. The points stay queued in their place for the next sync |+| **502, 503, 504 or a network error** | The point stays queued in its place. The pass stops when a group of 10 points got nothing through (10s connection, 10s read timeout) |+| **Other 5xx** | The point stays queued and moves behind the others. The pass stops when a group of 10 points got nothing through |+| **Other 4xx** | The point stays queued and moves behind the others |-There is no distinction between 4xx and 5xx in retry behavior - all failures are retried indefinitely, and failed items stay in the queue until they succeed.+Failed points are retried indefinitely and stay in the queue until they succeed. With a batch API (Overland, Dawarich batch) a rejected batch is split to find the point the server refuses, while a 429, a 5xx or a network error stops the pass instead.Clearing the queue in **Settings > Data management** deletes those locations outright, not just their place in the queue, so anything not yet sent is lost.diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex b1e4b4ac..88dad607 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -203,6 +203,7 @@ Orchestrates batch location uploads with:- Configurable batch size (50 items per batch, 10 concurrent HTTP requests)- Exponential backoff on failure+- A pass stops on a 429, and in the per-point format on a 5xx or a network error once a group of 10 requests got nothing through, so an unreachable server costs one group of requests. A batch upload stops on its first 429, 5xx or network error- 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/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.ktindex c3792205..ebfe811a 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt@@ -191,14 +191,14 @@ class NetworkManager(private val context: Context) {extraHeaders: Map<String, String> = emptyMap(),httpMethod: String = "POST",apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED- ): Boolean {+ ): BatchResult {val result = runRequest(payload, endpoint, extraHeaders, httpMethod, apiFormat, emptyMap())if (result.ok) {AppLogger.d(TAG, "Location successfully sent")} else if (result.errorMessage != null) {AppLogger.e(TAG, result.errorMessage)}- return result.ok+ return if (result.httpStatus == 0) BatchResult.NetworkError else verdictFor(result.httpStatus, result.retryAfterSeconds)}private fun buildConnection(@@ -309,7 +309,7 @@ class NetworkManager(private val context: Context) {}}- /** Same as [sendToEndpoint] but returns status + error text instead of Boolean. */+ /** Same as [sendToEndpoint] but returns status + error text instead of a verdict. */suspend fun testEndpoint(payload: JSONObject,endpoint: String,@@ -321,7 +321,7 @@ class NetworkManager(private val context: Context) {/*** Shared request implementation. Returns a fully-populated [TestEndpointResult];- * production callers project this to Boolean via [sendToEndpoint], while the+ * production callers project this to a [BatchResult] via [sendToEndpoint], while the* Test Connection path exposes it directly via [testEndpoint].*/private suspend fun runRequest(@@ -376,7 +376,8 @@ class NetworkManager(private val context: Context) {TestEndpointResult(false,httpStatus = responseCode,- errorMessage = "Server returned $responseCode: $errorBody"+ errorMessage = "Server returned $responseCode: $errorBody",+ retryAfterSeconds = if (responseCode == 429) retryAfterOf(connection) else null)}} catch (e: SSLHandshakeException) {@@ -429,6 +430,11 @@ class NetworkManager(private val context: Context) {AppLogger.d(TAG, "Batch of $batchSize sent successfully")BatchResult.Success}+ 429 -> {+ val retryAfter = retryAfterOf(connection)+ AppLogger.w(TAG, "Batch rate limited (429)" + (retryAfter?.let { ", retry after ${it}s" } ?: ""))+ BatchResult.RateLimited(retryAfter)+ }in 400..499 -> {val errorBody = readErrorBody(connection)AppLogger.w(TAG, "Batch rejected (4xx): $responseCode - $errorBody")@@ -446,6 +452,9 @@ class NetworkManager(private val context: Context) {}}+ private fun retryAfterOf(connection: HttpURLConnection): Long? =+ parseRetryAfter(connection.getHeaderField("Retry-After"), System.currentTimeMillis())+/*** Bounded and single-line. A rate-limited flush logs one of these per rejected point, and an* nginx error page is 7 lines each - enough to push real events out of the rolling log file.diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkResults.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkResults.ktindex 9187763d..2046c1c1 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkResults.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkResults.kt@@ -5,19 +5,44 @@package com.Colota.sync+import java.time.ZonedDateTime+import java.time.format.DateTimeFormatter+/*** Distinguishes 4xx from 5xx so the caller can split-on-4xx (poison row) without- * amplifying 5xx outages into N more requests per cycle.+ * amplifying 5xx outages into N more requests per cycle. A 429 is its own case: it+ * is about the client's pace, never about one row.*- * Returned by [NetworkManager.sendBatchToEndpoint].+ * Returned by [NetworkManager.sendBatchToEndpoint] and [NetworkManager.sendToEndpoint].*/sealed class BatchResult {object Success : BatchResult()data class ClientError(val code: Int) : BatchResult()data class ServerError(val code: Int) : BatchResult()+ data class RateLimited(val retryAfterSeconds: Long?) : BatchResult()object NetworkError : BatchResult()}+internal fun verdictFor(status: Int, retryAfterSeconds: Long?): BatchResult = when (status) {+ in 200..299 -> BatchResult.Success+ 429 -> BatchResult.RateLimited(retryAfterSeconds)+ in 400..499 -> BatchResult.ClientError(status)+ else -> BatchResult.ServerError(status)+}++/** `Retry-After` is either delta-seconds or an HTTP date (RFC 9110); anything else is ignored. */+internal fun parseRetryAfter(value: String?, nowMs: Long): Long? {+ val trimmed = value?.trim().orEmpty()+ if (trimmed.isEmpty()) return null+ trimmed.toLongOrNull()?.let { return it.coerceAtLeast(0) }+ return try {+ val at = ZonedDateTime.parse(trimmed, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli()+ ((at - nowMs) / 1000).coerceAtLeast(0)+ } catch (_: Exception) {+ null+ }+}+/*** Returned by [NetworkManager.testEndpoint]. Carries enough detail for the* Test Connection UI to show a precise error.@@ -26,4 +51,5 @@ data class TestEndpointResult(val ok: Boolean,val httpStatus: Int = 0,val errorMessage: String? = null,+ val retryAfterSeconds: Long? = null,)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 f1ee37c9..7f65031c 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@@ -13,6 +13,7 @@ import kotlinx.coroutines.*import kotlinx.coroutines.channels.Channelimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLock+import org.json.JSONExceptionimport org.json.JSONObjectimport java.util.concurrent.ConcurrentHashMap@@ -171,11 +172,7 @@ class SyncManager(}} finally {waitingFlushTotal = null- // A pass caps at MAX_BATCHES_PER_SYNC and stops when a batch moves nothing, so the- // running count need not reach the queue it started with. Only this event ends the pass,- // and a throw or a cancellation, even one while waiting for the lock, must still send it or- // the caller waits out its own timeout and reports a failure over an upload that worked.- // The totals come from the pass, not from the last progress tick.+ // Only this event ends the pass for the screen, so it goes out even after a throw or a cancel while waitinginvalidateQueueCache()val remaining = runCatching { dbHelper.getQueuedCount() }.getOrDefault(total - pass.sent)LocationServiceModule.sendSyncProgressEvent(pass.sent, pass.failed, pass.sent + pass.failed, remaining)@@ -197,7 +194,6 @@ class SyncManager(return}- // Immediate send mode (syncInterval = 0)if ((syncIntervalSeconds == 0 || bypassInterval) && isSyncAllowed()) {// Registered before the lock check: a later pass skips this row, a running one may already hold itinstantInFlight.add(queueId)@@ -207,21 +203,20 @@ class SyncManager(return}AppLogger.d(TAG, "Instant send")- val success = networkManager.sendToEndpoint(payload, endpoint, authHeaders, httpMethod, apiFormat)+ val result = networkManager.sendToEndpoint(payload, endpoint, authHeaders, httpMethod, apiFormat)- if (success) {+ if (result == BatchResult.Success) {dbHelper.markLocationsSent(listOf(locationId))dbHelper.removeFromQueueByLocationId(locationId)invalidateQueueCache()markSuccess()} else {- dbHelper.incrementRetryCount(queueId, "Send failed")+ retryReason(result)?.let { dbHelper.incrementRetryCount(queueId, it) }}} finally {instantInFlight.remove(queueId)}}- // Otherwise the periodic sync job will handle it}fun isSyncAllowed(): Boolean {@@ -258,7 +253,6 @@ class SyncManager(return success}- // Exponential backoff: 30s → 60s → 5min → 15minprivate suspend fun applyBackoffDelay() {val backoffSeconds = when (consecutiveFailures) {1 -> 30L@@ -287,6 +281,8 @@ class SyncManager(var totalFailed = 0var skippedInFlight = 0var batchNumber = 1+ // Rows that failed without a bump stay at the head of the queue, so a later fetch would post them again+ val keptInPlace = mutableSetOf<Long>()// Every chunk reports, sent or not: silence reads as a dead service and frees Sync Now mid-passfun reportProgress() {@@ -297,18 +293,18 @@ class SyncManager(while (isActive && batchNumber <= MAX_BATCHES_PER_SYNC) {val fetchSize = if (currentApiFormat == ApiFormat.OVERLAND_BATCH) currentBatchSize else 50val fetched = dbHelper.getQueuedLocations(fetchSize)- val queued = fetched.filterNot { it.queueId in instantInFlight }- skippedInFlight += fetched.size - queued.size+ val queued = fetched.filterNot { it.queueId in instantInFlight || it.queueId in keptInPlace }+ skippedInFlight += fetched.count { it.queueId in instantInFlight }if (queued.isEmpty()) {if (totalProcessed > 0) {- AppLogger.d(TAG, "Sync complete: $totalProcessed items in $batchNumber batches")+ val kept = if (keptInPlace.isEmpty()) "" else ", ${keptInPlace.size} kept for the next sync"+ AppLogger.d(TAG, "Sync complete: $totalProcessed items in ${batchNumber - 1} batches$kept")}break}AppLogger.d(TAG, "Processing batch $batchNumber/$MAX_BATCHES_PER_SYNC: ${queued.size} items")- // Chunks of 10 concurrent HTTP requests to avoid flooding the serverval processedBefore = totalProcessedif (currentApiFormat == ApiFormat.OVERLAND_BATCH) {@@ -318,37 +314,45 @@ class SyncManager(totalFailed += result.failedreportProgress()if (result.stop) {- AppLogger.d(TAG, "Sync pass aborted by transport failure")+ AppLogger.d(TAG, "Sync pass stopped: the server is unreachable, failing or rate limiting")break}} else {+ var stopped: String? = nullfor (chunk in queued.chunked(10)) {val successfulIds = mutableListOf<Long>()val results = chunk.map { item ->async {- try {- val itemPayload = JSONObject(item.payload)- val success = networkManager.sendToEndpoint(- itemPayload,+ val result = try {+ networkManager.sendToEndpoint(+ JSONObject(item.payload),currentEndpoint,currentAuthHeaders,currentHttpMethod,currentApiFormat)- item.queueId to success+ } catch (e: JSONException) {+ AppLogger.e(TAG, "Corrupt queue row ${item.queueId}", e)+ null} catch (e: Exception) {AppLogger.e(TAG, "Failed to send item ${item.queueId}", e)- item.queueId to false+ BatchResult.NetworkError}+ item.queueId to result}}.awaitAll()- results.forEach { (queueId, success) ->- if (success) {+ results.forEach { (queueId, result) ->+ if (result == BatchResult.Success) {successfulIds.add(queueId)} else {- dbHelper.incrementRetryCount(queueId, "Send failed")+ val reason = if (result == null) "Corrupt payload" else retryReason(result)+ if (reason != null) {+ dbHelper.incrementRetryCount(queueId, reason)+ } else {+ keptInPlace.add(queueId)+ }totalFailed++}}@@ -363,11 +367,16 @@ class SyncManager(}reportProgress()+ stopped = stopReason(results.map { it.second }, anySent = successfulIds.isNotEmpty())+ if (stopped != null) breakyield()}+ if (stopped != null) {+ AppLogger.d(TAG, "Sync pass stopped: $stopped")+ break+ }}- // No items removed from queue. Stop re-fetching the same failing itemsif (totalProcessed == processedBefore) {AppLogger.d(TAG, "No progress in batch $batchNumber, stopping sync pass")break@@ -389,6 +398,24 @@ class SyncManager(SyncPass(totalSucceeded, totalFailed, skippedInFlight)}+ /** Only a verdict about the row moves it back in the queue; an outage or a rate limit is the server's. */+ private fun retryReason(result: BatchResult): String? = when (result) {+ is BatchResult.ClientError -> "4xx: ${result.code}"+ is BatchResult.ServerError -> if (result.code in 502..504) null else "5xx: ${result.code}"+ BatchResult.Success, BatchResult.NetworkError, is BatchResult.RateLimited -> null+ }++ /** A 429 ends the pass outright; an outage or a 5xx does once a whole chunk got nothing through. */+ private fun stopReason(results: List<BatchResult?>, anySent: Boolean): String? {+ results.filterIsInstance<BatchResult.RateLimited>().firstOrNull()?.let { limited ->+ return "rate limited" + (limited.retryAfterSeconds?.let { ", retry after ${it}s" } ?: "")+ }+ if (anySent) return null+ results.filterIsInstance<BatchResult.ServerError>().firstOrNull()?.let { return "server error ${it.code}" }+ if (BatchResult.NetworkError in results) return "server unreachable"+ return null+ }+private data class BatchSendResult(val processed: Int, val failed: Int, val stop: Boolean)/**@@ -402,8 +429,7 @@ class SyncManager(): BatchSendResult {if (items.isEmpty()) return BatchSendResult(0, 0, false)- // Isolate corrupt rows so one bad payload doesn't poison the whole batch- // (matches the per-item path's per-item try/catch).+ // One corrupt payload must not fail the whole batchval parsed = items.mapNotNull { item ->try {item to JSONObject(item.payload)@@ -442,6 +468,7 @@ class SyncManager(} else {val mid = parseableItems.size / 2val left = sendBatchRecursive(parseableItems.take(mid), endpoint, authHeaders)+ if (left.stop) return BatchSendResult(left.processed, left.failed + corruptedFailed, stop = true)yield()val right = sendBatchRecursive(parseableItems.drop(mid), endpoint, authHeaders)BatchSendResult(@@ -452,13 +479,13 @@ class SyncManager(}}is BatchResult.ServerError -> {- parseableItems.forEach { dbHelper.incrementRetryCount(it.queueId, "5xx: ${result.code}") }+ retryReason(result)?.let { reason ->+ parseableItems.forEach { dbHelper.incrementRetryCount(it.queueId, reason) }+ }BatchSendResult(processed = 0, failed = parseableItems.size + corruptedFailed, stop = true)}- BatchResult.NetworkError -> {- parseableItems.forEach { dbHelper.incrementRetryCount(it.queueId, "network") }+ is BatchResult.RateLimited, BatchResult.NetworkError ->BatchSendResult(processed = 0, failed = parseableItems.size + corruptedFailed, stop = true)- }}}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.ktindex d6e06883..18129890 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt@@ -244,6 +244,49 @@ class NetworkManagerTest {assertEquals("Invalid URL: masked(htps://ha.example.com/api/webhook/abc)", result.errorMessage)}+ // --- verdicts ---++ @Test+ fun `a status maps to the verdict the sync pass acts on`() {+ assertEquals(BatchResult.Success, verdictFor(204, null))+ assertEquals(BatchResult.RateLimited(30), verdictFor(429, 30))+ assertEquals(BatchResult.ClientError(400), verdictFor(400, null))+ assertEquals(BatchResult.ServerError(503), verdictFor(503, null))+ }++ @Test+ fun `a send that never got a response is a network error`() {+ val result = kotlinx.coroutines.runBlocking { createNetworkManagerViaReflection().sendToEndpoint(JSONObject(), "") }++ assertEquals(BatchResult.NetworkError, result)+ }++ @Test+ fun `Retry-After is read as seconds or as an HTTP date`() {+ val now = java.time.ZonedDateTime.parse(+ "Sat, 19 Sep 2026 12:00:00 GMT", java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME+ ).toInstant().toEpochMilli()++ assertEquals(120L, parseRetryAfter("120", now))+ assertEquals(90L, parseRetryAfter("Sat, 19 Sep 2026 12:01:30 GMT", now))+ assertEquals("a date in the past means now", 0L, parseRetryAfter("Sat, 19 Sep 2026 11:00:00 GMT", now))+ assertNull(parseRetryAfter("soon", now))+ assertNull(parseRetryAfter(null, now))+ }++ @Test+ fun `a rate-limited batch carries the server's Retry-After`() {+ val connection = io.mockk.mockk<java.net.HttpURLConnection>(relaxed = true)+ io.mockk.every { connection.responseCode } returns 429+ io.mockk.every { connection.getHeaderField("Retry-After") } returns "30"+ val method = NetworkManager::class.java.getDeclaredMethod(+ "readBatchResponse", java.net.HttpURLConnection::class.java, Int::class.javaPrimitiveType+ )+ method.isAccessible = true++ assertEquals(BatchResult.RateLimited(30), method.invoke(createNetworkManagerViaReflection(), connection, 50))+ }+private fun invokeReadErrorBody(body: String?): String {val connection = io.mockk.mockk<java.net.HttpURLConnection>(relaxed = true)io.mockk.every { connection.errorStream } returns body?.byteInputStream()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 232a20df..d3291e0a 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@@ -29,6 +29,7 @@ class SyncManagerTest {networkManager = mockk(relaxed = true)scope = TestScope(UnconfinedTestDispatcher())syncManager = SyncManager(dbHelper, networkManager, scope)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.NetworkErrormockkObject(AppLogger)every { AppLogger.d(any(), any()) } just Runs@@ -98,7 +99,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.Successval payload = JSONObject().put("lat", 52.0)syncManager.queueAndSend(1L, payload)@@ -122,12 +123,12 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns false+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.ServerError(500)val payload = JSONObject().put("lat", 52.0)syncManager.queueAndSend(1L, payload)- verify { dbHelper.incrementRetryCount(42L, "Send failed") }+ verify { dbHelper.incrementRetryCount(42L, "5xx: 500") }verify(exactly = 0) { dbHelper.removeFromQueueByLocationId(any()) }}@@ -189,7 +190,7 @@ class SyncManagerTest {coEvery { networkManager.isNetworkAvailable() } returns trueevery { networkManager.isUnmeteredConnection() } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.Successval payload = JSONObject().put("lat", 52.0)syncManager.queueAndSend(1L, payload)@@ -234,7 +235,7 @@ class SyncManagerTest {coEvery { networkManager.isNetworkAvailable() } returns trueevery { networkManager.isConnectedToSsid("HomeNetwork") } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.Successval payload = JSONObject().put("lat", 52.0)syncManager.queueAndSend(1L, payload)@@ -279,7 +280,7 @@ class SyncManagerTest {coEvery { networkManager.isNetworkAvailable() } returns trueevery { networkManager.isVpnConnected() } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.Successval payload = JSONObject().put("lat", 52.0)syncManager.queueAndSend(1L, payload)@@ -326,7 +327,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.Successval payload = JSONObject().put("lat", 52.0)syncManager.queueAndSend(1L, payload, bypassInterval = true)@@ -373,12 +374,12 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns false+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.ClientError(400)val payload = JSONObject().put("lat", 52.0)syncManager.queueAndSend(1L, payload, bypassInterval = true)- verify { dbHelper.incrementRetryCount(42L, "Send failed") }+ verify { dbHelper.incrementRetryCount(42L, "4xx: 400") }verify(exactly = 0) { dbHelper.removeFromQueueByLocationId(any()) }}@@ -399,7 +400,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.SuccesssyncManager.queueAndSend(1L, JSONObject().put("lat", 52.0))@@ -421,7 +422,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.SuccessassertEquals(0L, syncManager.lastSuccessfulSyncTime)@@ -444,7 +445,7 @@ class SyncManagerTest {authHeaders = emptyMap())coEvery { networkManager.isNetworkAvailable() } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.SuccesssyncManager.queueAndSend(1L, JSONObject().put("lat", 52.0))@@ -488,7 +489,7 @@ class SyncManagerTest {QueuedLocation(1L, 100L, """{"lat":52.0}""", 0))every { dbHelper.getQueuedLocations(50) } returnsMany listOf(queued, emptyList())- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.SuccesssyncManager.manualFlush()@@ -511,7 +512,7 @@ class SyncManagerTest {val item = QueuedLocation(1L, 100L, """{"lat":52.0}""", 0)// Always return the same item (it stays in queue after failure)every { dbHelper.getQueuedLocations(50) } returns listOf(item)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns false+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.ClientError(400)syncManager.manualFlush()@@ -596,7 +597,7 @@ class SyncManagerTest {// Always return items - loop should still stop at batch 10val item = QueuedLocation(1L, 100L, """{"lat":52.0}""", 0)every { dbHelper.getQueuedLocations(50) } returns listOf(item)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.SuccesssyncManager.manualFlush()@@ -618,7 +619,7 @@ class SyncManagerTest {// 25 items → 3 chunks (10 + 10 + 5)val items = (1L..25L).map { QueuedLocation(it, it + 100, """{"lat":52.0}""", 0) }every { dbHelper.getQueuedLocations(50) } returnsMany listOf(items, emptyList())- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.SuccesssyncManager.manualFlush()@@ -747,7 +748,7 @@ class SyncManagerTest {listOf(QueuedLocation(1L, 100L, """{"lat":52.0}""", 0)),emptyList())- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.Successevery { dbHelper.removeBatchFromQueue(any()) } answers { queuedCount = 0 }syncManager.startPeriodicSync()@@ -780,7 +781,7 @@ class SyncManagerTest {listOf(QueuedLocation(1L, 100L, """{"lat":52.0}""", 0)),emptyList())- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns BatchResult.Successevery { dbHelper.removeBatchFromQueue(any()) } answers { queuedCount = 0 }syncManager.startPeriodicSync()@@ -1043,14 +1044,14 @@ class SyncManagerTest {listOf(corrupted, valid),emptyList())- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.SuccesssyncManager.manualFlush()// Valid item should still be sent despite corrupted siblingcoVerify(atLeast = 1) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }// Corrupted item gets retry increment, valid item gets removed- verify { dbHelper.incrementRetryCount(1L, "Send failed") }+ verify { dbHelper.incrementRetryCount(1L, "Corrupt payload") }verify { dbHelper.markLocationsSent(listOf(101L)) }unmockkObject(LocationServiceModule.Companion)@@ -1075,7 +1076,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns true- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.SuccesssyncManager.queueAndSend(1L, JSONObject().put("lat", 52.0))@@ -1098,7 +1099,7 @@ class SyncManagerTest {val item = QueuedLocation(1L, 100L, """{"lat":52.0}""", 0)every { dbHelper.getQueuedLocations(50) } returnsMany listOf(listOf(item), emptyList())- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.SuccesssyncManager.manualFlush()@@ -1154,14 +1155,14 @@ class SyncManagerTest {QueuedLocation(it, it + 100, """{"lat":52.0,"lon":13.0,"tst":1700000000}""", 0)}every { dbHelper.getQueuedLocations(50) } returns items- coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } returns BatchResult.ServerError(503)+ coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } returns BatchResult.ServerError(500)syncManager.manualFlush()// Critical: exactly ONE HTTP call. NOT recursive splits, that would amplify the outage.coVerify(exactly = 1) { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) }// Each row gets one retry bump- items.forEach { verify { dbHelper.incrementRetryCount(it.queueId, "5xx: 503") } }+ items.forEach { verify { dbHelper.incrementRetryCount(it.queueId, "5xx: 500") } }}@Test@@ -1187,7 +1188,7 @@ class SyncManagerTest {syncManager.manualFlush()coVerify(exactly = 1) { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) }- items.forEach { verify { dbHelper.incrementRetryCount(it.queueId, "network") } }+ verify(exactly = 0) { dbHelper.incrementRetryCount(any(), any()) }}@Test@@ -1361,7 +1362,7 @@ class SyncManagerTest {authHeaders = emptyMap())fakeQueue(20)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_000); true }+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_000); BatchResult.Success }launch { syncManager.manualFlush() }launch { syncManager.manualFlush() }@@ -1384,7 +1385,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns truefakeQueue(20)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_500); true }+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_500); BatchResult.Success }launch { syncManager.manualFlush() }syncManager.startPeriodicSync()@@ -1409,7 +1410,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns truefakeQueue(10)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_000); true }+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_000); BatchResult.Success }launch { syncManager.manualFlush() }syncManager.queueAndSend(500L, JSONObject().put("lat", 53.0))@@ -1435,7 +1436,7 @@ class SyncManagerTest {authHeaders = emptyMap())fakeQueue(10)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns false+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.NetworkErrorsyncManager.manualFlush()@@ -1490,7 +1491,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns truefakeQueue(20)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_500); true }+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_500); BatchResult.Success }syncManager.startPeriodicSync()advanceTimeBy(1_200)@@ -1519,7 +1520,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns truefakeQueue(0)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(5_000); true }+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(5_000); BatchResult.Success }launch { syncManager.queueAndSend(1L, JSONObject().put("lat", 1.0)) }advanceTimeBy(1_000)@@ -1545,7 +1546,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns truefakeQueue(0)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_000); true }+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_000); BatchResult.Success }launch { syncManager.queueAndSend(500L, JSONObject().put("lat", 53.0), bypassInterval = true) }launch { syncManager.manualFlush() }@@ -1571,7 +1572,7 @@ class SyncManagerTest {authHeaders = emptyMap())fakeQueue(20)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_500); true }+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_500); BatchResult.Success }launch { syncManager.manualFlush() }val waiting = launch { syncManager.manualFlush() }@@ -1599,7 +1600,7 @@ class SyncManagerTest {)coEvery { networkManager.isNetworkAvailable() } returns truefakeQueue(0)- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(3_000); true }+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(3_000); BatchResult.Success }launch { syncManager.queueAndSend(500L, JSONObject().put("lat", 53.0)) }syncManager.startPeriodicSync()@@ -1626,6 +1627,203 @@ class SyncManagerTest {}}+ // --- What a failed send tells the pass ---++ private fun configurePerItem() {+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 0,+ retryIntervalSeconds = 30,+ isOfflineMode = false,+ syncCondition = "any",+ syncSsid = "",+ authHeaders = emptyMap()+ )+ }++ /** A dead host fails every row the same way, so one chunk is enough to know it. */+ @Test+ fun `an unreachable server costs one chunk, not a whole batch`() = scope.runTest {+ configurePerItem()+ fakeQueue(50)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.NetworkError++ syncManager.manualFlush()++ coVerify(exactly = 10) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ verify(exactly = 0) { dbHelper.incrementRetryCount(any(), any()) }+ }++ /** A flaky link still delivers, so a chunk that got rows through keeps the pass going. */+ @Test+ fun `a chunk that gets some rows through keeps going`() = scope.runTest {+ configurePerItem()+ fakeQueue(20)+ var calls = 0+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers {+ if (calls++ % 2 == 0) BatchResult.Success else BatchResult.NetworkError+ }++ syncManager.manualFlush()++ coVerify(atLeast = 20) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ verify(exactly = 0) { dbHelper.incrementRetryCount(any(), any()) }+ }++ @Test+ fun `a chunk with a server error keeps going while rows get through`() = scope.runTest {+ configurePerItem()+ fakeQueue(20)+ var calls = 0+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers {+ if (calls++ % 2 == 0) BatchResult.Success else BatchResult.ServerError(500)+ }++ syncManager.manualFlush()++ coVerify(atLeast = 20) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ }++ @Test+ fun `a chunk of server errors with nothing sent ends the pass`() = scope.runTest {+ configurePerItem()+ fakeQueue(50)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.ServerError(500)++ syncManager.manualFlush()++ coVerify(exactly = 10) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ verify(exactly = 10) { dbHelper.incrementRetryCount(any(), "5xx: 500") }+ }++ /** A 502 to 504 is the proxy saying the app behind it is down, which says nothing about the row. */+ @Test+ fun `a gateway outage keeps the rows in place`() = scope.runTest {+ configurePerItem()+ fakeQueue(50)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.ServerError(503)++ syncManager.manualFlush()++ coVerify(exactly = 10) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ verify(exactly = 0) { dbHelper.incrementRetryCount(any(), any()) }+ }++ /** A row kept in place stays at the head of the queue, so each later fetch in the pass would post it again. */+ @Test+ fun `a row that failed in transport is not posted again in the same pass`() = scope.runTest {+ configurePerItem()+ fakeQueue(15)+ var calls = 0+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers {+ if (++calls == 1) BatchResult.NetworkError else BatchResult.Success+ }++ syncManager.manualFlush()++ coVerify(exactly = 15) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ }++ /** One rejected row must not stall the good rows behind it. */+ @Test+ fun `rejected rows do not stop the rows behind them`() = scope.runTest {+ configurePerItem()+ fakeQueue(20)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.ClientError(400)++ syncManager.manualFlush()++ coVerify(exactly = 20) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ verify(exactly = 20) { dbHelper.incrementRetryCount(any(), "4xx: 400") }+ }++ /** A 429 asks the client to slow down, so nothing more goes out in this pass. */+ @Test+ fun `a rate limit ends the pass after the chunk that hit it`() = scope.runTest {+ configurePerItem()+ fakeQueue(50)+ var calls = 0+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers {+ if (++calls == 3) BatchResult.RateLimited(30) else BatchResult.Success+ }++ syncManager.manualFlush()++ coVerify(exactly = 10) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ verify { dbHelper.markLocationsSent(match { it.size == 9 }) }+ verify(exactly = 0) { dbHelper.incrementRetryCount(any(), any()) }+ }++ /** An outage is the server's fault, so the row keeps its place and points reach the server in order. */+ @Test+ fun `an instant send that cannot connect keeps its place in the queue`() = scope.runTest {+ configurePerItem()+ every { dbHelper.addToQueue(any(), any()) } returns 42L+ coEvery { networkManager.isNetworkAvailable() } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.NetworkError++ syncManager.queueAndSend(1L, JSONObject().put("lat", 52.0))++ coVerify(exactly = 1) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ verify(exactly = 0) { dbHelper.incrementRetryCount(any(), any()) }+ verify(exactly = 0) { dbHelper.removeFromQueueByLocationId(any()) }+ }++ /** Splitting a rate-limited batch would turn one refused request into many more. */+ @Test+ fun `batch path stops on a rate limit without splitting`() = scope.runTest {+ syncManager.updateConfig(+ endpoint = "https://dawarich.example/api/v1/overland/batches",+ syncIntervalSeconds = 300,+ retryIntervalSeconds = 30,+ isOfflineMode = false,+ syncCondition = "any",+ syncSsid = "",+ authHeaders = emptyMap(),+ apiFormat = ApiFormat.OVERLAND_BATCH,+ overlandBatchSize = 50+ )+ val items = (1L..3L).map {+ QueuedLocation(it, it + 100, """{"lat":52.0,"lon":13.0,"tst":1700000000}""", 0)+ }+ every { dbHelper.getQueuedLocations(50) } returns items+ coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } returns BatchResult.RateLimited(null)++ syncManager.manualFlush()++ coVerify(exactly = 1) { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) }+ verify(exactly = 0) { dbHelper.incrementRetryCount(any(), any()) }+ }++ /** A rate limit met while bisecting ends the pass, so the other half is not sent either. */+ @Test+ fun `batch path stops bisecting when a half is rate limited`() = scope.runTest {+ syncManager.updateConfig(+ endpoint = "https://dawarich.example/api/v1/overland/batches",+ syncIntervalSeconds = 300,+ retryIntervalSeconds = 30,+ isOfflineMode = false,+ syncCondition = "any",+ syncSsid = "",+ authHeaders = emptyMap(),+ apiFormat = ApiFormat.OVERLAND_BATCH,+ overlandBatchSize = 50+ )+ val items = (1L..4L).map {+ QueuedLocation(it, it + 100, """{"lat":52.0,"lon":13.0,"tst":1700000000}""", 0)+ }+ every { dbHelper.getQueuedLocations(50) } returns items+ coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } returnsMany listOf(+ BatchResult.ClientError(400),+ BatchResult.RateLimited(null),+ BatchResult.Success+ )++ syncManager.manualFlush()++ coVerify(exactly = 2) { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) }+ }+/** Rows leave only when a pass or an instant send removes them, so two senders running together see the same rows. */private fun fakeQueue(size: Int) {val queue = (1L..size.toLong()).map { QueuedLocation(it, it + 100, """{"lat":52.0}""", 0) }.toMutableList()diff --git a/fastlane/metadata/android/en-US/changelogs/52.txt b/fastlane/metadata/android/en-US/changelogs/52.txtindex 4536015a..04b62ff5 100644--- a/fastlane/metadata/android/en-US/changelogs/52.txt+++ b/fastlane/metadata/android/en-US/changelogs/52.txt@@ -1,3 +1,4 @@- Colota is now available in Spanish- Profiles no longer skip a pause zone's entry delay- The Dashboard no longer cuts off the sync interval and says Offline mode when that is on+- Sync stops early on a rate limit or an unreachable server instead of trying every queued point