package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbDownload import eu.friedcutlet.yokan.database.DbHistory import eu.friedcutlet.yokan.database.DbUpdate import eu.friedcutlet.yokan.database.DbOutboxOp import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.decodeDatabaseSnapshot import eu.friedcutlet.yokan.database.encodeDatabaseSnapshot import eu.friedcutlet.yokan.database.emptySnapshot import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.database.sync.SyncPaths import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlinx.coroutines.test.runTest import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.long class HubSyncRoundTest { @Test fun roundPushesOutboxAppliesDeltaAndStoresCursor() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1)) val manga = db.upsertManga(DbManga(name = "Local", link = "/t", sourceId = 5)) val hub = FakeHub() hub.responses += HttpResponse(200, """{"epoch":1,"head":40,"hlc":6,"ents":[]}""") // seed chunk hub.responses += HttpResponse( 200, """{"epoch":1,"head":42,"hlc":7,"more":false,"lost":1,"applied":2,"ents":[ {"k":2,"id":${manga.id},"doc":{"name":"Remote","favorite":true,"categories":{"7":true}}}, {"k":1,"id":7,"doc":{"name":"Reading","forItemType":"Manga","position":0}} ]}""", ) val result = service(db, hub).sync(1, db.settings()) assertEquals(2, hub.requests.size, "first sync from a device seeds its full state before the outbox") val seed = Json.parseToJsonElement(hub.requests[0].body!!).jsonObject assertEquals(HubSyncService.NO_DELTA, seed["since"]!!.jsonPrimitive.long) val seedOp = seed["ops"]!!.jsonArray.map { it.jsonObject }.single { it["p"]!!.jsonPrimitive.content == "name" } assertEquals(manga.id, seedOp["id"]!!.jsonPrimitive.long) assertEquals(HubSyncService.SEED_CLOCK, seedOp["t"]!!.jsonPrimitive.long, "seeded values never beat what the hub already has") val body = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject assertEquals(0L, body["since"]!!.jsonPrimitive.long) val ops = body["ops"]!!.jsonArray assertTrue(ops.any { it.jsonObject["p"]!!.jsonPrimitive.content == "name" && it.jsonObject["id"]!!.jsonPrimitive.long == manga.id }) assertEquals("Bearer tok", hub.requests[1].headers["Authorization"]) assertTrue(db.outbox().isEmpty(), "sent ops are cleared") val updated = db.manga(manga.id)!! assertEquals("Remote", updated.name) assertTrue(updated.favorite) assertEquals(listOf(7L), updated.categories) assertEquals("Reading", db.categories().single { it.id == 7L }.name) val pref = db.syncPreferences().single() assertEquals(42L, pref.hubHead) assertEquals(1, pref.hubEpoch) assertEquals(seed["ops"]!!.jsonArray.size + ops.size, result.uploadedChanges) assertEquals(2, result.downloadedChanges) assertTrue(result.errors.single().contains("took precedence")) assertTrue(db.outbox().isEmpty(), "applying hub docs did not create new ops") } @Test fun dataThatPredatesTheOutboxReachesTheHub() = runTest { // Restored backups and pre-sync installs have entities with no outbox rows at all. val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) val manga = db.applyRemote { db.upsertManga(DbManga(name = "Old", link = "/o", sourceId = 5, favorite = true)) } assertTrue(db.outbox().isEmpty()) val hub = FakeHub() hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":1,"ents":[]}""") hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":2,"ents":[]}""") service(db, hub).sync(1, db.settings()) val seedOps = Json.parseToJsonElement(hub.requests[0].body!!).jsonObject["ops"]!!.jsonArray.map { it.jsonObject } assertTrue(seedOps.any { it["k"]!!.jsonPrimitive.content == "2" && it["id"]!!.jsonPrimitive.long == manga.id && it["p"]!!.jsonPrimitive.content == "favorite" }) // An established device (cursor > 0) does not re-seed on a normal sync… hub.requests.clear() hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":3,"ents":[]}""") service(db, hub).sync(1, db.settings()) assertEquals(1, hub.requests.size) assertTrue(Json.parseToJsonElement(hub.requests[0].body!!).jsonObject["ops"]!!.jsonArray.isEmpty()) // …but "Upload only" re-sends everything with fresh clocks so local state wins. hub.requests.clear() hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":4,"ents":[]}""") hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":5,"ents":[]}""") service(db, hub).pushChanges(1) val overwrite = Json.parseToJsonElement(hub.requests[0].body!!).jsonObject assertEquals(HubSyncService.NO_DELTA, overwrite["since"]!!.jsonPrimitive.long) val op = overwrite["ops"]!!.jsonArray.map { it.jsonObject }.single { it["p"]!!.jsonPrimitive.content == "favorite" } assertTrue(op["t"]!!.jsonPrimitive.long > HubSyncService.SEED_CLOCK) assertEquals(1L, db.syncPreferences().single().hubHead, "upload-only leaves the pull cursor alone") } @Test fun conflictTriggersOneResyncFromZero() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference(db.syncPreferences().single().copy(hubHead = 900, hubEpoch = 1)) val hub = FakeHub() hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""") hub.responses += HttpResponse(200, """{"epoch":2,"head":3,"hlc":1,"ents":[]}""") val result = service(db, hub).pullChanges(1) assertTrue(result.errors.isEmpty(), result.errors.toString()) assertEquals(2, hub.requests.size) val second = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject assertEquals(0L, second["since"]!!.jsonPrimitive.long) assertEquals(2, second["epoch"]!!.jsonPrimitive.content.toInt()) assertEquals(3L, db.syncPreferences().single().hubHead) } @Test fun higherEpochResyncDropsStaleOpsButRetriesCurrentGeneration() = runTest { val db = InMemoryYokanDatabase( emptySnapshot().copy( syncPreferences = listOf( DbSyncPreference( syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubHead = 1, hubEpoch = 1, ), ), outbox = listOf( DbOutboxOp(SyncPaths.KIND_MANGA, 21, "name", "\"Old\"", 1, 1, epoch = 1), DbOutboxOp(SyncPaths.KIND_MANGA, 22, "favorite", "true", 2, 2, epoch = 2), ), ), ) val hub = FakeHub() hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""") hub.responses += HttpResponse(200, """{"epoch":2,"head":4,"hlc":1,"ents":[]}""") service(db, hub).sync(1, db.settings()) assertEquals(2, hub.requests.size) val retried = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject["ops"]!!.jsonArray assertEquals(listOf("favorite"), retried.map { it.jsonObject["p"]!!.jsonPrimitive.content }) assertEquals(2, db.syncPreferences().single().hubEpoch) assertTrue(db.outbox().isEmpty()) } @Test fun conflictAtCurrentEpochDoesNotDiscardUnrelatedOutboxOps() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference(db.syncPreferences().single().copy(hubHead = 1, hubEpoch = 2)) val manga = db.upsertManga(DbManga(name = "Local", link = "/t", sourceId = 5)) val hub = FakeHub() hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""") hub.responses += HttpResponse(200, """{"epoch":2,"head":2,"hlc":1,"ents":[]}""") service(db, hub).sync(1, db.settings()) val retried = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject["ops"]!!.jsonArray assertTrue(retried.any { it.jsonObject["id"]!!.jsonPrimitive.long == manga.id }) } @Test fun completedRollbackWithEmptyHeadDoesNotReseedRestoredMonotoneState() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference( db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true), ) db.applyRemote { db.upsertManga(DbManga(id = 99, name = "local", lastRead = 42)) } val hub = FakeHub() hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""") hub.responses += HttpResponse( 200, """{"epoch":2,"head":0,"hlc":1,"ents":[{"k":2,"id":99,"doc":{"name":"restored","lastRead":7}}]}""", ) service(db, hub).sync(1, db.settings()) assertFalse(db.syncPreferences().single().hubRecoveryPending) assertTrue(db.syncPreferences().single().hubBootstrapComplete) assertEquals(7, db.manga(99)!!.lastRead) hub.requests.clear() hub.responses += HttpResponse(200, """{"epoch":2,"head":0,"hlc":2,"ents":[]}""") service(db, hub).sync(1, db.settings()) val next = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject assertTrue(next["ops"]!!.jsonArray.isEmpty()) assertFalse(hub.requests.single().body!!.contains("restored")) } @Test fun firstEpochAdoptionPreservesInitialSeedUploads() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) val manga = db.upsertManga(DbManga(name = "preexisting", link = "/local")) val hub = FakeHub() hub.responses += HttpResponse(200, """{"supported":["1"]}""") hub.responses += HttpResponse(200, """{"token":"abc"}""") hub.responses += HttpResponse(409, """{"resync":true,"epoch":1}""") hub.responses += HttpResponse(200, """{"epoch":1,"head":10,"hlc":1,"ents":[]}""") hub.responses += HttpResponse(200, """{"epoch":1,"head":10,"hlc":2,"ents":[]}""") val service = service(db, hub) assertTrue(service.login(1, "hub.test", "a@b", "pw").success) service.sync(1, db.settings()) val firstSeed = Json.parseToJsonElement(hub.requests[2].body!!).jsonObject val adoptedSeed = Json.parseToJsonElement(hub.requests[3].body!!).jsonObject assertEquals(0, firstSeed["epoch"]!!.jsonPrimitive.content.toInt()) assertEquals(1, adoptedSeed["epoch"]!!.jsonPrimitive.content.toInt()) assertTrue(firstSeed["ops"]!!.jsonArray.any { it.jsonObject["id"]!!.jsonPrimitive.long == manga.id }) assertTrue(adoptedSeed["ops"]!!.jsonArray.any { it.jsonObject["id"]!!.jsonPrimitive.long == manga.id }) assertFalse(db.syncPreferences().single().hubRecoveryPending) assertTrue(db.syncPreferences().single().hubBootstrapComplete) } @Test fun epochZeroToTwoRollbackDropsStaleSeedWorkBeforeRetry() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) val manga = db.upsertManga(DbManga(name = "stale", link = "/stale")) val hub = FakeHub() hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""") hub.responses += HttpResponse(200, """{"epoch":2,"head":0,"hlc":1,"ents":[]}""") hub.responses += HttpResponse(200, """{"epoch":2,"head":0,"hlc":2,"ents":[]}""") service(db, hub).sync(1, db.settings()) assertTrue(hub.requests[0].body!!.contains(manga.id.toString())) assertTrue(hub.requests.drop(1).all { request -> Json.parseToJsonElement(request.body!!).jsonObject["ops"]!!.jsonArray.isEmpty() }) assertFalse(db.syncPreferences().single().hubRecoveryPending) assertTrue(db.syncPreferences().single().hubBootstrapComplete) } @Test fun establishedSerializedPreferenceDoesNotReseedStaleLocalState() = runTest { val legacyRaw = encodeDatabaseSnapshot( emptySnapshot().copy( syncPreferences = listOf( DbSyncPreference( syncId = 1, server = "https://hub.test", authToken = "old-token", syncOn = true, ), ), mangas = listOf(DbManga(id = 77, name = "stale", lastRead = 101)), ), ).replace("\"hubRecoveryPending\": false", "\"legacyRecoveryPending\": false") .replace("\"hubBootstrapComplete\": false", "\"legacyBootstrapComplete\": false") val db = InMemoryYokanDatabase(decodeDatabaseSnapshot(legacyRaw)!!) assertTrue(db.syncPreferences().single().hubBootstrapComplete) val fresh = InMemoryYokanDatabase( emptySnapshot().copy( syncPreferences = listOf( DbSyncPreference( syncId = 1, server = "https://hub.test", authToken = "new-token", syncOn = true, ), ), ), ) assertFalse(fresh.syncPreferences().single().hubBootstrapComplete) val hub = FakeHub() hub.responses += HttpResponse(200, """{"epoch":1,"head":0,"hlc":1,"ents":[]}""") service(db, hub).sync(1, db.settings()) val body = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject assertTrue(body["ops"]!!.jsonArray.isEmpty()) } @Test fun interruptedMultiChunkBootstrapRestartsFromTheBeginning() = runTest { val db = InMemoryYokanDatabase( emptySnapshot().copy( syncPreferences = listOf( DbSyncPreference( syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 1, ), ), mangas = (1L..2_000L).map { id -> DbManga(id = id, name = "m$id") }, ), ) db.upsertSyncPreference(db.syncPreferences().single().copy(hubBootstrapComplete = false)) val hub = FakeHub() hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":1,"ents":[]}""") hub.responses += HttpResponse(503, """{"error":"interrupted"}""") service(db, hub).sync(1, db.settings()) assertFalse(db.syncPreferences().single().hubBootstrapComplete) val reopened = InMemoryYokanDatabase(db.snapshot()) reopened.removeManga(1L, recordChange = false) reopened.upsertManga(DbManga(id = 3_000L, name = "added-before-retry")) hub.requests.clear() // Enough acknowledgements for every bootstrap chunk; the count depends on title document fields. repeat(6) { hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":${it + 2},"ents":[]}""") } service(reopened, hub).sync(1, reopened.settings()) val restarted = hub.requests.first().body!! assertTrue(Json.parseToJsonElement(restarted).jsonObject["ops"]!!.jsonArray.isNotEmpty()) assertTrue(hub.requests.any { it.body!!.contains("3000") }) assertTrue(hub.requests.any { it.body!!.contains("2") }) assertTrue(reopened.syncPreferences().single().hubBootstrapComplete) } @Test fun interruptedRollbackRecoveryNeverSeedsExtremeDocuments() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 0)) db.upsertManga(DbManga(id = Long.MIN_VALUE, name = "min")) db.upsertManga(DbManga(id = Long.MAX_VALUE, name = "max")) val hub = FakeHub() hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""") hub.responses += HttpResponse(503, """{"error":"interrupted"}""") service(db, hub).sync(1, db.settings()) assertTrue(db.syncPreferences().single().hubRecoveryPending) assertTrue(hub.requests[0].body!!.contains(Long.MIN_VALUE.toString())) assertTrue(hub.requests[0].body!!.contains(Long.MAX_VALUE.toString())) val interruptedRetry = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject assertEquals(0L, interruptedRetry["since"]!!.jsonPrimitive.long) assertTrue(interruptedRetry["ops"]!!.jsonArray.isEmpty()) hub.requests.clear() hub.responses += HttpResponse(200, """{"epoch":2,"head":8,"hlc":1,"ents":[]}""") service(db, hub).sync(1, db.settings()) val recovered = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject assertEquals(0L, recovered["since"]!!.jsonPrimitive.long) assertTrue(recovered["ops"]!!.jsonArray.isEmpty()) assertFalse(db.syncPreferences().single().hubRecoveryPending) } @Test fun capturedSeedChunkIsNotRetriedAfterGenerationChange() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 0)) val manga = db.upsertManga(DbManga(name = "seed", link = "/seed")) val hub = FakeHub() hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""") hub.responses += HttpResponse(200, """{"epoch":2,"head":5,"hlc":1,"ents":[]}""") hub.responses += HttpResponse(200, """{"epoch":2,"head":6,"hlc":2,"ents":[]}""") service(db, hub).sync(1, db.settings()) assertTrue(hub.requests[0].body!!.contains(manga.id.toString())) assertTrue(hub.requests.drop(1).all { request -> Json.parseToJsonElement(request.body!!).jsonObject["ops"]!!.jsonArray.isEmpty() }) } @Test fun legacyEpochRowsAreDroppedAndOnlyCurrentEpochIsSent() = runTest { val db = InMemoryYokanDatabase( emptySnapshot().copy( syncPreferences = listOf( DbSyncPreference( syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubHead = 1, hubEpoch = 2, ), ), outbox = listOf( DbOutboxOp(SyncPaths.KIND_MANGA, 31, "name", "\"legacy\"", 1, 1), DbOutboxOp(SyncPaths.KIND_MANGA, 32, "name", "\"current\"", 2, 2, epoch = 2), ), ), ) val hub = FakeHub() hub.responses += HttpResponse(200, """{"epoch":2,"head":2,"hlc":1,"ents":[]}""") service(db, hub).pushChanges(1) val body = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject assertEquals(listOf(32L), body["ops"]!!.jsonArray.map { it.jsonObject["id"]!!.jsonPrimitive.long }) assertEquals(1, body["generation"]!!.jsonPrimitive.content.toInt()) } @Test fun editCreatedDuringRecoveryIsSentAfterRecoveryCompletes() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference( db.syncPreferences().single().copy(hubEpoch = 2, hubHead = 0, hubRecoveryPending = true), ) val hub = FakeHub() hub.onRequest = { if (hub.requests.size == 1) db.upsertManga(DbManga(name = "after recovery")) } hub.responses += HttpResponse(200, """{"epoch":2,"head":8,"hlc":1,"ents":[]}""") service(db, hub).sync(1, db.settings()) assertFalse(db.outbox().isEmpty()) assertTrue(db.outbox().all { it.epoch == 2 }) assertFalse(db.syncPreferences().single().hubRecoveryPending) hub.onRequest = {} hub.responses += HttpResponse(200, """{"epoch":2,"head":9,"hlc":2,"ents":[]}""") service(db, hub).sync(1, db.settings()) val sent = Json.parseToJsonElement(hub.requests.last().body!!).jsonObject["ops"]!!.jsonArray assertTrue(sent.isNotEmpty()) assertEquals(1, Json.parseToJsonElement(hub.requests.last().body!!).jsonObject["generation"]!!.jsonPrimitive.content.toInt()) } @Test fun editsMadeDuringTheRequestWinOverTheIncomingDoc() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference( db.syncPreferences().single().copy(hubHead = 1, hubEpoch = 1, hubBootstrapComplete = true), ) // established device: no seed round val manga = db.upsertManga(DbManga(name = "Local", link = "/t", sourceId = 5, favorite = false)) val hub = FakeHub() hub.onRequest = { db.upsertManga(db.manga(manga.id)!!.copy(favorite = true)) } // user taps while the request is in flight hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":2,"id":${manga.id},"doc":{"name":"Remote","favorite":false}}]}""") service(db, hub).sync(1, db.settings()) val after = db.manga(manga.id)!! assertEquals("Remote", after.name) assertTrue(after.favorite, "the in-flight local edit is kept") assertEquals(listOf("favorite"), db.outbox().map { it.path }, "and still pending for the next round") } @Test fun pendingTitleDeleteSuppressesAnInFlightLiveDocument() = runTest { val id = 42L val db = InMemoryYokanDatabase( emptySnapshot().copy( syncPreferences = listOf(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true)), outbox = listOf(DbOutboxOp(SyncPaths.KIND_MANGA, id, SyncPaths.DELETED, "true", 1, 1, epoch = 1)), ), ) val hub = FakeHub() hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":2,"id":$id,"doc":{"name":"resurrected"}}]}""") service(db, hub).pullChanges(1) assertNull(db.manga(id)) assertEquals("true", db.outbox().single().value) assertEquals(2L, db.syncPreferences().single().hubHead) } @Test fun remoteTitleTombstoneRemovesDependentRowsWithoutCreatingOutboxOps() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true)) val manga = db.upsertManga(DbManga(name = "Title")) val chapter = db.upsertChapter(DbChapter(mangaId = manga.id, name = "Chapter")) db.upsertHistory(DbHistory(mangaId = manga.id, chapterId = chapter.id, itemType = eu.friedcutlet.yokan.database.DbItemType.Manga)) db.upsertUpdate(DbUpdate(mangaId = manga.id, chapterId = chapter.id)) val pendingOutbox = db.outbox() val hub = FakeHub() hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":2,"id":${manga.id},"del":true}]}""") service(db, hub).pullChanges(1) assertNull(db.manga(manga.id)) assertTrue(db.chapters(manga.id).isEmpty()) assertTrue(db.histories().isEmpty()) assertTrue(db.updates().isEmpty()) assertEquals(pendingOutbox, db.outbox(), "remote deletion creates no echo ops or discards unrelated pending ops") assertEquals(2L, db.syncPreferences().single().hubHead) } @Test fun historyAndUpdateTombstonesSyncWhileTheirContentFlagsAreOff() = runTest { val db = InMemoryYokanDatabase( emptySnapshot().copy( syncPreferences = listOf(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true, syncHistories = false, syncUpdates = false)), outbox = listOf( DbOutboxOp(SyncPaths.KIND_HISTORY, 11, SyncPaths.DELETED, "true", 1, 1, epoch = 1), DbOutboxOp(SyncPaths.KIND_HISTORY, 11, "date", "\"today\"", 2, 2, epoch = 1), DbOutboxOp(SyncPaths.KIND_UPDATE, 12, SyncPaths.DELETED, "true", 3, 3, epoch = 1), DbOutboxOp(SyncPaths.KIND_UPDATE, 12, "chapterName", "\"Chapter\"", 4, 4, epoch = 1), ), ), ) val hub = FakeHub() hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":5,"id":21,"del":true},{"k":6,"id":22,"del":true},{"k":5,"id":23,"doc":{"date":"today","itemType":"Manga"}},{"k":6,"id":24,"doc":{"chapterName":"Chapter"}}]}""") service(db, hub).sync(1, db.settings()) val sent = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject["ops"]!!.jsonArray assertEquals(setOf(5, 6), sent.map { it.jsonObject["k"]!!.jsonPrimitive.content.toInt() }.toSet()) assertTrue(sent.all { it.jsonObject["p"]!!.jsonPrimitive.content == SyncPaths.DELETED }) assertEquals(setOf("date", "chapterName"), db.outbox().map { it.path }.toSet()) assertTrue(db.histories().isEmpty()) assertTrue(db.updates().isEmpty()) assertEquals(2L, db.syncPreferences().single().hubHead) } @Test fun activeDownloadDefersRemoteTitleDeleteAndKeepsCursor() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true)) val manga = db.upsertManga(DbManga(name = "Downloading")) val chapter = db.upsertChapter(DbChapter(mangaId = manga.id)) db.upsertDownload(DbDownload(chapterId = chapter.id, isStartDownload = true, isDownload = false)) val hub = FakeHub() hub.responses += HttpResponse(200, """{"epoch":1,"head":9,"hlc":1,"ents":[{"k":2,"id":${manga.id},"del":true}]}""") val result = service(db, hub).pullChanges(1) assertTrue(result.errors.any { it.contains("active chapter download") }, result.errors.toString()) assertEquals(1L, db.syncPreferences().single().hubHead) assertNotNull(db.manga(manga.id)) assertNotNull(db.chapter(chapter.id)) } @Test fun maintenanceAndExpiredSessionAreReportedNotRetried() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) val hub = FakeHub() hub.responses += HttpResponse(503, """{"error":"maintenance"}""") assertTrue(service(db, hub).pullChanges(1).errors.single().contains("maintenance")) hub.responses += HttpResponse(401, "") assertTrue(service(db, hub).pullChanges(1).errors.single().contains("log in")) assertNull(db.syncPreferences().single().authToken) } @Test fun pagedPullReportsProgressAgainstTheHubTip() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 100, hubBootstrapComplete = true)) val monitor = SyncOperationMonitor() val hub = FakeHub() hub.responses += HttpResponse(200, """{"epoch":1,"head":150,"tip":300,"hlc":1,"more":true}""") hub.responses += HttpResponse(200, """{"epoch":1,"head":300,"tip":300,"hlc":2,"more":false}""") val seen = mutableListOf() hub.onRequest = { seen += monitor.state.value.progress } service(db, hub, monitor).pullChanges(1) assertEquals(listOf(null, 0.25f), seen) assertNull(monitor.state.value.progress, "finished rounds drop stale progress") } @Test fun cancellingHttpRoundCleansObservableOperationState() = runTest { val db = InMemoryYokanDatabase(emptySnapshot()) loggedIn(db) db.upsertSyncPreference( db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true), ) val started = CompletableDeferred() val hub = FakeHub().apply { suspendOnRequest = { started.complete(Unit) awaitCancellation() } } val monitor = SyncOperationMonitor() val service = service(db, hub, monitor) val job = launch { service.pullChanges(1) } started.await() assertTrue(monitor.state.value.isActive) job.cancelAndJoin() assertFalse(monitor.state.value.isActive) assertEquals(SyncOperationOutcome.Cancelled, monitor.state.value.lastOutcome) } }