feat(sync): paginate Android sync with change tokens
Lint / Lint (push) Successful in 1m8s
Tests / Go backend (push) Failing after 1m23s
Tests / Dashboard checks (push) Failing after 38s
Docker / Docker Build & Push (push) Failing after 6m29s

This commit is contained in:
Gabriel20xx committed 2026-10-20 15:27:53 +00:00
1 parent 0ff94f9b10
commit 97c237be80
76 files changed
+3401 -851

No files matched your search

@@ -12,6 +12,7 @@ import retrofit2.http.Query
data class SyncRequest(
val lastSyncTimestamp: Long,
val lastSyncToken: Long,
val lists: List<CollabList>,
val fields: List<Field>,
val items: List<Item>,
@@ -24,6 +25,9 @@ data class SyncResponse(
val items: List<Item>,
val itemValues: List<ItemValue>,
val serverTimestamp: Long,
val serverChangeToken: Long,
val nextSyncToken: Long,
val hasMore: Boolean,
)
interface CollabTableApi {
@@ -0,0 +1,15 @@
package com.collabtable.app.data.repository
import com.collabtable.app.data.api.SyncResponse
internal data class SyncPageProgress(
val cursor: Long,
val firstPage: Boolean = true,
) {
fun after(response: SyncResponse): SyncPageProgress? {
if (response.hasMore && response.nextSyncToken <= cursor) {
throw IllegalStateException("Sync page cursor did not advance")
}
return if (response.hasMore) SyncPageProgress(response.nextSyncToken, firstPage = false) else null
}
}
@@ -52,6 +52,12 @@ class SyncRepository(
return prefs.getLong("last_server_sync_ts", 0)
}
private fun getLastServerSyncToken(): Long = prefs.getLong("last_server_sync_token", 0)
private fun setLastServerSyncToken(token: Long) {
prefs.edit().putLong("last_server_sync_token", token).apply()
}
private fun setLastServerSyncTs(ts: Long) {
prefs
.edit()
@@ -101,30 +107,29 @@ class SyncRepository(
return@withContext Result.success(Unit)
}
val lastServerTs = getLastServerSyncTs()
val lastServerToken = getLastServerSyncToken()
val lastLocalTs = getLastLocalSyncTs()
// Capture a snapshot timestamp BEFORE reading local changes to avoid missing
// updates that happen during an in-flight sync. We'll advance the local watermark
// to this snapshot once the sync completes successfully.
val localSnapshotTs = System.currentTimeMillis()
val isInitialSync = lastServerTs == 0L
// If our local DB appears empty or this install still has the legacy timestamp cursor,
// request a full down-sync through the server change-token cursor.
val hasAnyLists = database.listDao().getAllListIds().isNotEmpty()
val hasAnyItems = database.itemDao().getAllItemIds().isNotEmpty()
val effectiveLastServerToken =
when {
// App start can request a full down-sync regardless of local contents
forceFullDown && (lastServerTs > 0L || lastServerToken > 0L) -> 0L
// Fallback: if local has no lists or items but we have a watermark, do a full down-sync
(lastServerTs > 0L || lastServerToken > 0L) && (!hasAnyLists && !hasAnyItems) -> 0L
else -> lastServerToken
}
val isInitialSync = effectiveLastServerToken == 0L
if (isInitialSync) {
Logger.i("Sync", "[SYNC] Starting initial sync with server")
}
// If our local DB appears empty but we have a nonzero server watermark (e.g., after reinstall
// or clearing local data), request a one-time full down-sync by resetting the effective
// lastSyncTimestamp to 0 for this request. This avoids permanently missing historical rows.
val hasAnyLists = database.listDao().getAllListIds().isNotEmpty()
val hasAnyItems = database.itemDao().getAllItemIds().isNotEmpty()
val effectiveLastServerTs =
when {
// App start can request a full down-sync regardless of local contents
forceFullDown && lastServerTs > 0L -> 0L
// Fallback: if local looks empty but we have a watermark, do a one-time full down-sync
lastServerTs > 0L && (!hasAnyLists || !hasAnyItems) -> 0L
else -> lastServerTs
}
if (effectiveLastServerTs == 0L && lastServerTs > 0L) {
if (effectiveLastServerToken == 0L && (lastServerTs > 0L || lastServerToken > 0L)) {
val reason = if (forceFullDown) "startup forced" else "local empty"
Logger.w("Sync", "$reason full down-sync requested")
}
@@ -162,125 +167,137 @@ class SyncRepository(
)
}
// Send to server and get updates
val syncRequest =
SyncRequest(
lastSyncTimestamp = effectiveLastServerTs,
lists = localLists,
fields = localFields,
items = localItems,
itemValues = localValues,
)
// HTTP-only sync
val response =
try {
api.sync(syncRequest)
} catch (e: UnknownHostException) {
// Host could not be resolved; apply exponential backoff and surface a warning once.
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
Logger.w("Sync", "Network host unresolved (DNS). Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
} catch (e: Exception) {
if (e.message?.contains("Unable to resolve host", ignoreCase = true) == true) {
// Upload local changes once, then follow the server's bounded pages without
// replaying the same writes on every request.
var cursor = effectiveLastServerToken
var pageProgress = SyncPageProgress(cursor)
var serverTimestamp = lastServerTs
while (true) {
val response =
try {
api.sync(
SyncRequest(
lastSyncTimestamp = lastServerTs,
lastSyncToken = pageProgress.cursor,
lists = if (pageProgress.firstPage) localLists else emptyList(),
fields = if (pageProgress.firstPage) localFields else emptyList(),
items = if (pageProgress.firstPage) localItems else emptyList(),
itemValues = if (pageProgress.firstPage) localValues else emptyList(),
),
)
} catch (e: UnknownHostException) {
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
Logger.w("Sync", "DNS failure. Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
Logger.w("Sync", "Network host unresolved (DNS). Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
}
throw e
}
if (!response.isSuccessful) {
if (response.code() == 401) {
// Unauthorized: likely bad/missing API token. Reset sync baseline and surface a clear error.
setLastServerSyncTs(0)
setLastLocalSyncTs(0)
// Apply exponential backoff on repeated auth failures
authBackoffMs = if (authBackoffMs == 0L) 2_000L else (authBackoffMs * 2).coerceAtMost(300_000L)
authBackoffUntil = System.currentTimeMillis() + authBackoffMs
return@withContext Result.failure(Exception("Unauthorized (401). Please verify server API token."))
}
return@withContext Result.failure(Exception("Sync failed: ${response.code()}"))
}
val syncResponse = response.body()!!
// Only log receive when there are actual server changes
val inTotal =
syncResponse.lists.size +
syncResponse.fields.size +
syncResponse.items.size +
syncResponse.itemValues.size
if (inTotal > 0) {
Logger.i(
"Sync",
"[IN] Received changes " +
"(lists=${syncResponse.lists.size}, fields=${syncResponse.fields.size}, " +
"items=${syncResponse.items.size}, values=${syncResponse.itemValues.size})",
)
}
// Apply server changes to local database atomically in correct order
database.withTransaction {
// 1) Upsert lists first, preserving local orderIndex when present
val localIdToOrder = database.listDao().getListIdsAndOrder().associate { it.id to it.orderIndex }
// Build a map of local updatedAt to avoid overwriting newer local changes with older server data
val localUpdatedMap = database.listDao().getListsUpdatedSince(0).associateBy({ it.id }, { it.updatedAt })
val listsPreservingOrder =
syncResponse.lists
.filter { incoming ->
val localUpdated = localUpdatedMap[incoming.id]
localUpdated == null || incoming.updatedAt >= localUpdated
}.map { incoming ->
val localOrder = localIdToOrder[incoming.id]
if (localOrder != null) incoming.copy(orderIndex = localOrder) else incoming
} catch (e: Exception) {
if (e.message?.contains("Unable to resolve host", ignoreCase = true) == true) {
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
Logger.w("Sync", "DNS failure. Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
}
if (listsPreservingOrder.isNotEmpty()) {
database.listDao().insertLists(listsPreservingOrder)
}
// Build set of existing list ids to guard child inserts
val existingListIds = database.listDao().getAllListIds().toSet()
// 2) Filter and upsert fields whose parent list exists
val filteredFields = syncResponse.fields.filter { f -> f.listId in existingListIds }
if (filteredFields.size != syncResponse.fields.size) {
val dropped = syncResponse.fields.size - filteredFields.size
Logger.w("Sync", "Dropping $dropped field(s) with missing parent list to avoid FK errors")
}
if (filteredFields.isNotEmpty()) {
database.fieldDao().insertFields(filteredFields)
}
// 3) Filter and upsert items whose parent list exists
val filteredItems = syncResponse.items.filter { i -> i.listId in existingListIds }
if (filteredItems.size != syncResponse.items.size) {
val dropped = syncResponse.items.size - filteredItems.size
Logger.w("Sync", "Dropping $dropped item(s) with missing parent list to avoid FK errors")
}
if (filteredItems.isNotEmpty()) {
database.itemDao().insertItems(filteredItems)
}
// 4) Filter item values to only those whose parents (item and field) exist locally
val existingItemIds = database.itemDao().getAllItemIds().toSet()
val existingFieldIds = database.fieldDao().getAllFieldIds().toSet()
val filteredValues =
syncResponse.itemValues.filter { v ->
v.itemId in existingItemIds && v.fieldId in existingFieldIds
throw e
}
if (filteredValues.size != syncResponse.itemValues.size) {
val dropped = syncResponse.itemValues.size - filteredValues.size
Logger.w("Sync", "Dropping $dropped item value(s) with missing parents to avoid FK errors")
if (!response.isSuccessful) {
if (response.code() == 401) {
setLastServerSyncTs(0)
setLastServerSyncToken(0)
setLastLocalSyncTs(0)
authBackoffMs = if (authBackoffMs == 0L) 2_000L else (authBackoffMs * 2).coerceAtMost(300_000L)
authBackoffUntil = System.currentTimeMillis() + authBackoffMs
return@withContext Result.failure(Exception("Unauthorized (401). Please verify server API token."))
}
return@withContext Result.failure(Exception("Sync failed: ${response.code()}"))
}
if (filteredValues.isNotEmpty()) {
database.itemValueDao().insertValues(filteredValues)
val syncResponse = response.body() ?: return@withContext Result.failure(Exception("Sync response was empty"))
val inTotal =
syncResponse.lists.size +
syncResponse.fields.size +
syncResponse.items.size +
syncResponse.itemValues.size
if (inTotal > 0) {
Logger.i(
"Sync",
"[IN] Received changes " +
"(lists=${syncResponse.lists.size}, fields=${syncResponse.fields.size}, " +
"items=${syncResponse.items.size}, values=${syncResponse.itemValues.size})",
)
}
database.withTransaction {
// 1) Upsert lists first, preserving local orderIndex when present
val localIdToOrder = database.listDao().getListIdsAndOrder().associate { it.id to it.orderIndex }
// Build a map of local updatedAt to avoid overwriting newer local changes with older server data
val localUpdatedMap =
database.listDao().getListsUpdatedSince(0).associateBy({ it.id }, { it.updatedAt })
val listsPreservingOrder =
syncResponse.lists
.filter { incoming ->
val localUpdated = localUpdatedMap[incoming.id]
localUpdated == null || incoming.updatedAt >= localUpdated
}.map { incoming ->
val localOrder = localIdToOrder[incoming.id]
if (localOrder != null) incoming.copy(orderIndex = localOrder) else incoming
}
if (listsPreservingOrder.isNotEmpty()) {
database.listDao().insertLists(listsPreservingOrder)
}
// Build set of existing list ids to guard child inserts
val existingListIds = database.listDao().getAllListIds().toSet()
// 2) Filter and upsert fields whose parent list exists
val filteredFields = syncResponse.fields.filter { f -> f.listId in existingListIds }
if (filteredFields.size != syncResponse.fields.size) {
val dropped = syncResponse.fields.size - filteredFields.size
Logger.w("Sync", "Dropping $dropped field(s) with missing parent list to avoid FK errors")
}
if (filteredFields.isNotEmpty()) {
database.fieldDao().insertFields(filteredFields)
}
// 3) Filter and upsert items whose parent list exists
val filteredItems = syncResponse.items.filter { i -> i.listId in existingListIds }
if (filteredItems.size != syncResponse.items.size) {
val dropped = syncResponse.items.size - filteredItems.size
Logger.w("Sync", "Dropping $dropped item(s) with missing parent list to avoid FK errors")
}
if (filteredItems.isNotEmpty()) {
database.itemDao().insertItems(filteredItems)
}
// 4) Filter item values to only those whose parents (item and field) exist locally
val existingItemIds = database.itemDao().getAllItemIds().toSet()
val existingFieldIds = database.fieldDao().getAllFieldIds().toSet()
val filteredValues =
syncResponse.itemValues.filter { v ->
v.itemId in existingItemIds && v.fieldId in existingFieldIds
}
if (filteredValues.size != syncResponse.itemValues.size) {
val dropped = syncResponse.itemValues.size - filteredValues.size
Logger.w("Sync", "Dropping $dropped item value(s) with missing parents to avoid FK errors")
}
if (filteredValues.isNotEmpty()) {
database.itemValueDao().insertValues(filteredValues)
}
}
val nextPage = try {
pageProgress.after(syncResponse)
} catch (e: IllegalStateException) {
return@withContext Result.failure(e)
}
cursor = syncResponse.nextSyncToken
serverTimestamp = syncResponse.serverTimestamp
if (nextPage == null) break
pageProgress = nextPage
}
// Update watermarks: server ts from response, local ts from device clock now
setLastServerSyncTs(syncResponse.serverTimestamp)
// Save the server-owned change cursor only after every page has been applied.
setLastServerSyncToken(cursor)
setLastServerSyncTs(serverTimestamp)
// Advance local watermark to the snapshot taken before reading local changes.
// This avoids missing updates that occurred while the sync was in-flight.
setLastLocalSyncTs(localSnapshotTs)
@@ -298,6 +315,7 @@ class SyncRepository(
// If WS indicated unauthorized, align behavior with HTTP path
if (e.message?.contains("Unauthorized") == true) {
setLastServerSyncTs(0)
setLastServerSyncToken(0)
setLastLocalSyncTs(0)
}
// Do not reset network backoff here; it's managed where thrown.
@@ -0,0 +1,50 @@
package com.collabtable.app.data.repository
import com.collabtable.app.data.api.SyncResponse
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
class SyncPageProgressTest {
@Test
fun `first page advances and marks later pages as download only`() {
val first = SyncPageProgress(cursor = 4)
assertTrue(first.firstPage)
val second = first.after(response(nextToken = 9, hasMore = true))
assertEquals(9, second?.cursor)
assertFalse(second?.firstPage ?: true)
}
@Test
fun `final page ends the loop`() {
val progress = SyncPageProgress(cursor = 9, firstPage = false)
assertNull(progress.after(response(nextToken = 12, hasMore = false)))
}
@Test
fun `non advancing page is rejected`() {
val progress = SyncPageProgress(cursor = 9)
assertThrows(IllegalStateException::class.java) {
progress.after(response(nextToken = 9, hasMore = true))
}
}
private fun response(nextToken: Long, hasMore: Boolean) =
SyncResponse(
lists = emptyList(),
fields = emptyList(),
items = emptyList(),
itemValues = emptyList(),
serverTimestamp = 0,
serverChangeToken = nextToken,
nextSyncToken = nextToken,
hasMore = hasMore,
)
}