Colota - Android GPS Location tracker
fix(sync): wait out a rate limit before sending again (#938)
Max Dietrichc37affa36cf7
diff --git a/apps/docs/docs/api-reference.md b/apps/docs/docs/api-reference.mdindex 78018d0e..ff478464 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 it rate limits, a 429 stops the sync pass and the remaining points go out on the next sync.+Your server should handle multiple simultaneous POST requests. If it rate limits, a 429 stops the sync pass and Colota waits as long as the `Retry-After` header asks (60 seconds without one, at most 15 minutes) before it sends again.## Testing with curl@@ -136,7 +136,7 @@ Your server only needs to return a 2xx status code. The response body is not rea| Outcome | Behavior || --- | --- |-| **429 Too Many Requests** | The sync pass stops. The points stay queued in their place for the next sync |+| **429 Too Many Requests** | The sync pass stops and nothing is sent until the `Retry-After` wait is over (60 seconds without the header, at most 15 minutes). The points stay queued in their place || **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 |diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex 88dad607..463a2485 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -203,7 +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+- A pass stops on a 429, and nothing is sent until its `Retry-After` wait is over (60 s without one, capped at 15 min): the periodic tick, a manual or zone-entry flush and an instant send all hold. In the per-point format a pass also stops 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/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.ktindex 05af73b3..481b4d32 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt@@ -206,12 +206,13 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :/** `remaining` is present only on the event that ends a pass, and is what says the pass ended. */@JvmStatic- fun sendSyncProgressEvent(sent: Int, failed: Int, total: Int, remaining: Int? = null): Boolean =+ fun sendSyncProgressEvent(sent: Int, failed: Int, total: Int, remaining: Int? = null, retryAfterSeconds: Long? = null): Boolean =emit("onSyncProgress") {putInt("sent", sent)putInt("failed", failed)putInt("total", total)if (remaining != null) putInt("remaining", remaining)+ if (retryAfterSeconds != null) putInt("retryAfterSeconds", retryAfterSeconds.toInt())}@JvmStaticdiff --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 7f65031c..029293f3 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@@ -30,6 +30,8 @@ class SyncManager(companion object {private const val TAG = "SyncManager"private const val MAX_BATCHES_PER_SYNC = 10+ private const val DEFAULT_RATE_LIMIT_WAIT_SECONDS = 60L+ private const val MAX_RATE_LIMIT_WAIT_SECONDS = 900L}@Volatile private var endpoint: String = ""@@ -113,6 +115,11 @@ class SyncManager(if (!allowed) {continue}+ val rateLimitWait = rateLimitWaitSeconds()+ if (rateLimitWait > 0) {+ AppLogger.d(TAG, "Sync skipped: rate limited for ${rateLimitWait}s")+ continue+ }if (endpoint.isNotBlank() && queued > 0) {if (syncMutex.isLocked) AppLogger.d(TAG, "Sync tick waiting for the running sync")@@ -167,15 +174,22 @@ class SyncManager(syncMutex.withLock {waitingFlushTotal = nulltotal = dbHelper.getQueuedCount()- AppLogger.d(TAG, "Manual flush started: $total items in queue")- pass = syncQueue { sent, failed -> LocationServiceModule.sendSyncProgressEvent(sent, failed, total) }+ val rateLimitWait = rateLimitWaitSeconds()+ if (rateLimitWait > 0) {+ AppLogger.d(TAG, "Manual flush skipped: rate limited for ${rateLimitWait}s")+ } else {+ AppLogger.d(TAG, "Manual flush started: $total items in queue")+ pass = syncQueue { sent, failed -> LocationServiceModule.sendSyncProgressEvent(sent, failed, total) }+ }}} finally {waitingFlushTotal = null// 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)+ LocationServiceModule.sendSyncProgressEvent(+ pass.sent, pass.failed, pass.sent + pass.failed, remaining, rateLimitWaitSeconds().takeIf { it > 0 }+ )}}@@ -202,6 +216,10 @@ class SyncManager(AppLogger.d(TAG, "Instant send deferred: a sync is running")return}+ if (rateLimitWaitSeconds() > 0) {+ AppLogger.d(TAG, "Instant send deferred: rate limited")+ return+ }AppLogger.d(TAG, "Instant send")val result = networkManager.sendToEndpoint(payload, endpoint, authHeaders, httpMethod, apiFormat)@@ -211,6 +229,7 @@ class SyncManager(invalidateQueueCache()markSuccess()} else {+ if (result is BatchResult.RateLimited) noteRateLimit(result.retryAfterSeconds)retryReason(result)?.let { dbHelper.incrementRetryCount(queueId, it) }}} finally {@@ -253,6 +272,19 @@ class SyncManager(return success}+ /** Clamped to the cap, because the wall clock can be set back. */+ fun rateLimitWaitSeconds(): Long {+ val left = (SyncState.rateLimitedUntil - clock()).coerceAtMost(MAX_RATE_LIMIT_WAIT_SECONDS * 1000)+ return if (left > 0) (left + 999) / 1000 else 0+ }++ /** Capped so a bad `Retry-After` cannot hold the queue for a day. */+ private fun noteRateLimit(retryAfterSeconds: Long?) {+ val wait = (retryAfterSeconds ?: DEFAULT_RATE_LIMIT_WAIT_SECONDS).coerceIn(1, MAX_RATE_LIMIT_WAIT_SECONDS)+ SyncState.holdUntil(clock() + wait * 1000)+ AppLogger.w(TAG, "Rate limited: holding uploads for ${wait}s")+ }+private suspend fun applyBackoffDelay() {val backoffSeconds = when (consecutiveFailures) {1 -> 30L@@ -367,6 +399,10 @@ class SyncManager(}reportProgress()+ val limited = results.mapNotNull { it.second as? BatchResult.RateLimited }+ if (limited.isNotEmpty()) {+ noteRateLimit(limited.maxOf { it.retryAfterSeconds ?: DEFAULT_RATE_LIMIT_WAIT_SECONDS })+ }stopped = stopReason(results.map { it.second }, anySent = successfulIds.isNotEmpty())if (stopped != null) breakyield()@@ -484,7 +520,11 @@ class SyncManager(}BatchSendResult(processed = 0, failed = parseableItems.size + corruptedFailed, stop = true)}- is BatchResult.RateLimited, BatchResult.NetworkError ->+ is BatchResult.RateLimited -> {+ noteRateLimit(result.retryAfterSeconds)+ BatchSendResult(processed = 0, failed = parseableItems.size + corruptedFailed, stop = true)+ }+ BatchResult.NetworkError ->BatchSendResult(processed = 0, failed = parseableItems.size + corruptedFailed, stop = true)}}diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncState.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncState.ktindex 90e37c96..e74043a6 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncState.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncState.kt@@ -8,7 +8,8 @@ package com.Colota.sync/*** What the last sync passes learned, readable from the bridge without a handle on the service's* SyncManager: the time of the last success and the masked message of the last failure that- * crossed the consecutive-failure gate, cleared on the next success.+ * crossed the consecutive-failure gate, cleared on the next success. The rate-limit wait lives here+ * too, because a Sync now while tracking is off runs on a service that stops after the pass.*/object SyncState {@Volatile var lastSuccessTime: Long = 0L@@ -17,6 +18,15 @@ object SyncState {@Volatile var lastSyncError: String = ""private set+ @Volatile var rateLimitedUntil: Long = 0L+ private set++ /** A later, shorter Retry-After must not cut a longer wait. */+ @Synchronized+ fun holdUntil(untilMs: Long) {+ if (untilMs > rateLimitedUntil) rateLimitedUntil = untilMs+ }+fun recordSuccess(timeMs: Long) {lastSuccessTime = timeMslastSyncError = ""@@ -29,5 +39,6 @@ object SyncState {fun reset() {lastSuccessTime = 0LlastSyncError = ""+ rateLimitedUntil = 0L}}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.ktindex 9e77013e..754e2516 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt@@ -246,6 +246,18 @@ class LocationServiceModuleTest {assertEquals(3, payloads[1].getInt("failed"))}+ @Test+ fun `only a rate-limited pass end carries retryAfterSeconds`() {+ val payloads = mutableListOf<WritableMap>()+ every { mockEmitter.emit("onSyncProgress", capture(payloads)) } just Runs++ LocationServiceModule.sendSyncProgressEvent(10, 0, 10, 0)+ LocationServiceModule.sendSyncProgressEvent(9, 1, 10, 403, 120)++ assertFalse(payloads[0].hasKey("retryAfterSeconds"))+ assertEquals(120, payloads[1].getInt("retryAfterSeconds"))+ }+@Testfun `sendSyncProgressEvent returns false when no context`() {setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))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 d3291e0a..bff1e9e2 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@@ -28,6 +28,7 @@ class SyncManagerTest {dbHelper = mockk(relaxed = true)networkManager = mockk(relaxed = true)scope = TestScope(UnconfinedTestDispatcher())+ SyncState.reset()syncManager = SyncManager(dbHelper, networkManager, scope)coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.NetworkError@@ -41,6 +42,7 @@ class SyncManagerTest {@Afterfun tearDown() {unmockkObject(AppLogger)+ SyncState.reset()scope.cancel()}@@ -1824,6 +1826,187 @@ class SyncManagerTest {coVerify(exactly = 2) { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) }}+ // --- The wait a 429 asks for ---++ private var now = 0L++ private fun rateLimitedManager(apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED): SyncManager {+ val manager = SyncManager(dbHelper, networkManager, scope, clock = { now })+ manager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 0,+ retryIntervalSeconds = 30,+ isOfflineMode = false,+ syncCondition = "any",+ syncSsid = "",+ authHeaders = emptyMap(),+ apiFormat = apiFormat+ )+ coEvery { networkManager.isNetworkAvailable() } returns true+ return manager+ }++ @Test+ fun `a flush inside the Retry-After wait sends nothing, and the next one after it does`() = scope.runTest {+ val manager = rateLimitedManager()+ fakeQueue(5)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.RateLimited(30)+ manager.manualFlush()+ clearMocks(networkManager, answers = false)++ now += 29_000+ manager.manualFlush()+ coVerify(exactly = 0) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }++ now += 2_000+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.Success+ manager.manualFlush()+ coVerify(exactly = 5) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ }++ @Test+ fun `a 429 without Retry-After waits 60 s`() = scope.runTest {+ val manager = rateLimitedManager()+ fakeQueue(1)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.RateLimited(null)++ manager.manualFlush()++ assertEquals(60L, manager.rateLimitWaitSeconds())+ }++ @Test+ fun `a Retry-After longer than 15 min is capped`() = scope.runTest {+ val manager = rateLimitedManager()+ fakeQueue(1)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.RateLimited(86_400)++ manager.manualFlush()++ assertEquals(900L, manager.rateLimitWaitSeconds())+ }++ @Test+ fun `a flush that ends rate limited tells the screen how long to wait`() = scope.runTest {+ mockkObject(LocationServiceModule)+ every { LocationServiceModule.sendSyncProgressEvent(any(), any(), any(), any(), any()) } returns true+ val manager = rateLimitedManager()+ fakeQueue(1)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.RateLimited(45)++ try {+ manager.manualFlush()++ verify { LocationServiceModule.sendSyncProgressEvent(0, 1, 1, 1, 45L) }+ } finally {+ unmockkObject(LocationServiceModule)+ }+ }++ @Test+ fun `a flush skipped inside the wait still ends the screen's pass and says how long is left`() = scope.runTest {+ mockkObject(LocationServiceModule)+ every { LocationServiceModule.sendSyncProgressEvent(any(), any(), any(), any(), any()) } returns true+ val manager = rateLimitedManager()+ fakeQueue(3)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.RateLimited(60)+ try {+ manager.manualFlush()+ now += 15_000+ manager.manualFlush()++ verify { LocationServiceModule.sendSyncProgressEvent(0, 0, 0, 3, 45L) }+ } finally {+ unmockkObject(LocationServiceModule)+ }+ }++ /** With tracking off every Sync now runs on a service that stops after it. */+ @Test+ fun `the wait outlives the SyncManager that met the 429`() = scope.runTest {+ fakeQueue(3)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.RateLimited(300)+ rateLimitedManager().manualFlush()+ clearMocks(networkManager, answers = false)++ rateLimitedManager().manualFlush()++ coVerify(exactly = 0) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ }++ @Test+ fun `a clock set back cannot hold uploads longer than the cap`() = scope.runTest {+ val manager = rateLimitedManager()+ fakeQueue(1)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.RateLimited(60)+ manager.manualFlush()++ now -= 2 * 60 * 60 * 1000L++ assertEquals(900L, manager.rateLimitWaitSeconds())+ }++ @Test+ fun `the longest Retry-After in a chunk sets the wait`() = scope.runTest {+ val manager = rateLimitedManager()+ fakeQueue(10)+ var calls = 0+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers {+ when (++calls) {+ 1 -> BatchResult.RateLimited(null)+ 4 -> BatchResult.RateLimited(600)+ else -> BatchResult.Success+ }+ }++ manager.manualFlush()++ assertEquals(600L, manager.rateLimitWaitSeconds())+ }++ @Test+ fun `an instant send inside the wait stays queued without a request`() = scope.runTest {+ val manager = rateLimitedManager()+ fakeQueue(1)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.RateLimited(30)+ manager.queueAndSend(1L, JSONObject().put("lat", 52.0))+ clearMocks(networkManager, answers = false)++ manager.queueAndSend(2L, JSONObject().put("lat", 52.1))++ coVerify(exactly = 0) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ verify(exactly = 0) { dbHelper.removeFromQueueByLocationId(any()) }+ }++ @Test+ fun `a batch 429 starts the wait too`() = scope.runTest {+ val manager = rateLimitedManager(ApiFormat.OVERLAND_BATCH)+ 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(120)++ manager.manualFlush()+ manager.manualFlush()++ coVerify(exactly = 1) { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) }+ assertEquals(120L, manager.rateLimitWaitSeconds())+ }++ @Test+ fun `a periodic tick inside the wait sends nothing`() = scope.runTest {+ val manager = startPeriodicSyncOnVirtualClock(60, queuedCount = 5)+ fakeQueue(5)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns BatchResult.RateLimited(300)+ manager.manualFlush()+ clearMocks(networkManager, answers = false)++ advanceTimeBy(61_000)++ assertEquals("the tick itself still runs and logs", 1, ticks)+ coVerify(exactly = 0) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }+ manager.stopPeriodicSync()+ }+/** 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/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncStateTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncStateTest.ktindex f082cf72..4d577457 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncStateTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncStateTest.kt@@ -25,4 +25,13 @@ class SyncStateTest {assertEquals(1_700_000_000_000L, SyncState.lastSuccessTime)assertEquals("Sync failed", SyncState.lastSyncError)}++ /** Two senders can meet a 429 at once. */+ @Test+ fun `a shorter rate-limit wait never replaces a longer one`() {+ SyncState.holdUntil(600_000L)+ SyncState.holdUntil(60_000L)++ assertEquals(600_000L, SyncState.rateLimitedUntil)+ }}diff --git a/apps/mobile/src/i18n/locales/en.json b/apps/mobile/src/i18n/locales/en.jsonindex b0364f8e..469b10d3 100644--- a/apps/mobile/src/i18n/locales/en.json+++ b/apps/mobile/src/i18n/locales/en.json@@ -377,6 +377,7 @@"data.sync.nothingAuto": "Nothing queued. New locations upload on their own.","data.sync.nothingLast": "Nothing queued. Last upload {{when}}.","data.sync.progress": "Sent {{sent}} of {{total}}.",+ "data.sync.rateLimited": "Your server asked Colota to wait. Uploads resume in {{duration}}.","data.sync.someFailed": "Some uploads failed.","data.sync.stillQueued": "{{n}} still queued; press again.","data.syncIdle_one": "{{n}} queued. Uploads it now, whatever Sync only on says.",diff --git a/apps/mobile/src/i18n/locales/es.json b/apps/mobile/src/i18n/locales/es.jsonindex 33583043..a781b5a5 100644--- a/apps/mobile/src/i18n/locales/es.json+++ b/apps/mobile/src/i18n/locales/es.json@@ -377,6 +377,7 @@"data.sync.nothingAuto": "Nada en cola. Las ubicaciones nuevas se suben por sí solas.","data.sync.nothingLast": "Nada en cola. Último envío {{when}}.","data.sync.progress": "Enviadas {{sent}} de {{total}}.",+ "data.sync.rateLimited": "Tu servidor pidió esperar. Los envíos se reanudan en {{duration}}.","data.sync.someFailed": "Algunos envíos fallaron.","data.sync.stillQueued": "Aún hay {{n}} en cola; presiona de nuevo.","data.syncIdle_one": "{{n}} en cola. La envía ahora, sin importar la opción Sincronizar solo en.",diff --git a/apps/mobile/src/i18n/locales/zh.json b/apps/mobile/src/i18n/locales/zh.jsonindex 6e2a0048..dbf23060 100644--- a/apps/mobile/src/i18n/locales/zh.json+++ b/apps/mobile/src/i18n/locales/zh.json@@ -377,6 +377,7 @@"data.sync.nothingAuto": "没有队列内容,新位置会自行上传。","data.sync.nothingLast": "没有队列内容,上次上传于 {{when}}。","data.sync.progress": "已发送 {{sent}}/{{total}}。",+ "data.sync.rateLimited": "服务器要求 Colota 稍后再试。{{duration}}后恢复上传。","data.sync.someFailed": "部分上传失败。","data.sync.stillQueued": "仍有 {{n}} 个正在等待队列;请重试。","data.syncIdle_one": "{{n}} 个队列内容。现在上传,不受“仅同步”设置影响。",diff --git a/apps/mobile/src/screens/DataManagementScreen.tsx b/apps/mobile/src/screens/DataManagementScreen.tsxindex 8ac3e858..8d0737b2 100644--- a/apps/mobile/src/screens/DataManagementScreen.tsx+++ b/apps/mobile/src/screens/DataManagementScreen.tsx@@ -40,6 +40,7 @@ import { parseWholeNumber, wholeNumberError } from "../utils/settingsValidation"import { formatWhen } from "../utils/geo"import { logger } from "../utils/logger"import { formatBytes } from "../utils/format"+import { formatDuration } from "../utils/dashboardState"import { useTranslation } from "../i18n/useTranslation"/** Only a placeholder in the custom field. Nothing is selected until the user selects it. */@@ -48,7 +49,7 @@ const PLACEHOLDER_DAYS = 90/** A hundred years. Past this the value stops being an age and starts being a typo. */const MAX_RETENTION_DAYS = 36500-type Message = { text: string; failed?: boolean }+type Message = { text: string; failed?: boolean; warning?: boolean }type Preview = { days: number; total: number; cutoffSeconds: number } | nullconst EMPTY_STATS: DatabaseStats = {@@ -273,7 +274,7 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Managconst sub = DeviceEventEmitter.addListener("onSyncProgress",- (event: { sent: number; failed: number; total: number; remaining?: number }) => {+ (event: { sent: number; failed: number; total: number; remaining?: number; retryAfterSeconds?: number }) => {// Only the event that ends a pass carries `remaining`. A pass caps at a fixed number of// batches, so the running count reaching the queue it started with is not the signal.if (event.remaining === undefined) {@@ -289,6 +290,12 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Managsent: event.sent.toLocaleString(),total: queuedBefore.toLocaleString()})+ if (event.retryAfterSeconds) {+ const s = event.retryAfterSeconds+ const wait = t("data.sync.rateLimited", { duration: formatDuration(s >= 60 ? Math.ceil(s / 60) * 60 : s) })+ finish({ text: event.sent > 0 ? `${sent} ${wait}` : wait, warning: true })+ return+ }const left =event.remaining > 0 ? ` ${t("data.sync.stillQueued", { n: event.remaining.toLocaleString() })}` : ""if (event.failed > 0) {@@ -425,7 +432,9 @@ export function DataManagementScreen({ navigation }: RootScreenProps<"Data Manag/></Card>{syncResult ? (- <FieldMessage variant={syncResult.failed ? "error" : "info"}>{syncResult.text}</FieldMessage>+ <FieldMessage variant={syncResult.failed ? "error" : syncResult.warning ? "warning" : "info"}>+ {syncResult.text}+ </FieldMessage>) : null}{compactMessage ? <FieldMessage>{compactMessage.text}</FieldMessage> : null}</View>diff --git a/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx b/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsxindex 60656308..ad2a8fc9 100644--- a/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx@@ -588,6 +588,65 @@ describe("DataManagementScreen", () => {expect(line.props.accessibilityValue.text).toBe("error")})+ it("says the server asked to wait, as a warning, instead of asking for another press", async () => {+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("sync-now-row"))+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())+ act(() => {+ DeviceEventEmitter.emit("onSyncProgress", {+ sent: 9,+ failed: 1,+ total: 10,+ remaining: 403,+ retryAfterSeconds: 120+ })+ })++ const line = await api.findByText("Sent 9 of 412. Your server asked Colota to wait. Uploads resume in 2 min.")+ expect(line.props.accessibilityValue.text).toBe("warning")+ expect(api.queryByText(/press again/)).toBeNull()+ })++ it("says only the wait when a press lands inside it and nothing was sent", async () => {+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("sync-now-row"))+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())+ act(() => {+ DeviceEventEmitter.emit("onSyncProgress", {+ sent: 0,+ failed: 0,+ total: 0,+ remaining: 412,+ retryAfterSeconds: 45+ })+ })++ expect(await api.findByText("Your server asked Colota to wait. Uploads resume in 45 s.")).toBeTruthy()+ })++ it("rounds a wait of a minute or more up to whole minutes", async () => {+ const api = renderScreen()+ await api.findByText("12,480")++ fireEvent.press(api.getByTestId("sync-now-row"))+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())+ act(() => {+ DeviceEventEmitter.emit("onSyncProgress", {+ sent: 0,+ failed: 0,+ total: 0,+ remaining: 412,+ retryAfterSeconds: 847+ })+ })++ expect(await api.findByText("Your server asked Colota to wait. Uploads resume in 15 min.")).toBeTruthy()+ })+it("says how many are left when a pass hits the batch cap", async () => {mockGetStats.mockResolvedValue(stats({ queued: 620 }))const api = renderScreen()diff --git a/fastlane/metadata/android/en-US/changelogs/52.txt b/fastlane/metadata/android/en-US/changelogs/52.txtindex 9ff4f10a..75b860a8 100644--- a/fastlane/metadata/android/en-US/changelogs/52.txt+++ b/fastlane/metadata/android/en-US/changelogs/52.txt@@ -3,3 +3,4 @@- 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- A setup link applied while tracking now takes effect at once instead of after the next start+- After a rate limit, sync waits as long as the server asks and Sync now says so