HubSyncRoundTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncRoundTest.kt
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.database.DbManga4import eu.friedcutlet.yokan.database.DbChapter5import eu.friedcutlet.yokan.database.DbDownload6import eu.friedcutlet.yokan.database.DbHistory7import eu.friedcutlet.yokan.database.DbUpdate8import eu.friedcutlet.yokan.database.DbOutboxOp9import eu.friedcutlet.yokan.database.DbSyncPreference10import eu.friedcutlet.yokan.database.InMemoryYokanDatabase11import eu.friedcutlet.yokan.database.decodeDatabaseSnapshot12import eu.friedcutlet.yokan.database.encodeDatabaseSnapshot13import eu.friedcutlet.yokan.database.emptySnapshot14import eu.friedcutlet.yokan.services.http.HttpResponse15import eu.friedcutlet.yokan.database.sync.SyncPaths16import kotlin.test.Test17import kotlin.test.assertEquals18import kotlin.test.assertFalse19import kotlin.test.assertNotNull20import kotlin.test.assertNull21import kotlin.test.assertTrue22import kotlinx.coroutines.test.runTest23import kotlinx.coroutines.CompletableDeferred24import kotlinx.coroutines.awaitCancellation25import kotlinx.coroutines.cancelAndJoin26import kotlinx.coroutines.launch27import kotlinx.serialization.json.Json28import kotlinx.serialization.json.jsonArray29import kotlinx.serialization.json.jsonObject30import kotlinx.serialization.json.jsonPrimitive31import kotlinx.serialization.json.long3233class HubSyncRoundTest {34 @Test35 fun roundPushesOutboxAppliesDeltaAndStoresCursor() = runTest {36 val db = InMemoryYokanDatabase(emptySnapshot())37 loggedIn(db)38 db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1))39 val manga = db.upsertManga(DbManga(name = "Local", link = "/t", sourceId = 5))40 val hub = FakeHub()41 hub.responses += HttpResponse(200, """{"epoch":1,"head":40,"hlc":6,"ents":[]}""") // seed chunk42 hub.responses += HttpResponse(43 200,44 """{"epoch":1,"head":42,"hlc":7,"more":false,"lost":1,"applied":2,"ents":[45 {"k":2,"id":${manga.id},"doc":{"name":"Remote","favorite":true,"categories":{"7":true}}},46 {"k":1,"id":7,"doc":{"name":"Reading","forItemType":"Manga","position":0}}47 ]}""",48 )49 val result = service(db, hub).sync(1, db.settings())5051 assertEquals(2, hub.requests.size, "first sync from a device seeds its full state before the outbox")52 val seed = Json.parseToJsonElement(hub.requests[0].body!!).jsonObject53 assertEquals(HubSyncService.NO_DELTA, seed["since"]!!.jsonPrimitive.long)54 val seedOp = seed["ops"]!!.jsonArray.map { it.jsonObject }.single { it["p"]!!.jsonPrimitive.content == "name" }55 assertEquals(manga.id, seedOp["id"]!!.jsonPrimitive.long)56 assertEquals(HubSyncService.SEED_CLOCK, seedOp["t"]!!.jsonPrimitive.long, "seeded values never beat what the hub already has")5758 val body = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject59 assertEquals(0L, body["since"]!!.jsonPrimitive.long)60 val ops = body["ops"]!!.jsonArray61 assertTrue(ops.any { it.jsonObject["p"]!!.jsonPrimitive.content == "name" && it.jsonObject["id"]!!.jsonPrimitive.long == manga.id })62 assertEquals("Bearer tok", hub.requests[1].headers["Authorization"])6364 assertTrue(db.outbox().isEmpty(), "sent ops are cleared")65 val updated = db.manga(manga.id)!!66 assertEquals("Remote", updated.name)67 assertTrue(updated.favorite)68 assertEquals(listOf(7L), updated.categories)69 assertEquals("Reading", db.categories().single { it.id == 7L }.name)70 val pref = db.syncPreferences().single()71 assertEquals(42L, pref.hubHead)72 assertEquals(1, pref.hubEpoch)73 assertEquals(seed["ops"]!!.jsonArray.size + ops.size, result.uploadedChanges)74 assertEquals(2, result.downloadedChanges)75 assertTrue(result.errors.single().contains("took precedence"))76 assertTrue(db.outbox().isEmpty(), "applying hub docs did not create new ops")77 }7879 @Test80 fun dataThatPredatesTheOutboxReachesTheHub() = runTest {81 // Restored backups and pre-sync installs have entities with no outbox rows at all.82 val db = InMemoryYokanDatabase(emptySnapshot())83 loggedIn(db)84 val manga = db.applyRemote { db.upsertManga(DbManga(name = "Old", link = "/o", sourceId = 5, favorite = true)) }85 assertTrue(db.outbox().isEmpty())86 val hub = FakeHub()87 hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":1,"ents":[]}""")88 hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":2,"ents":[]}""")89 service(db, hub).sync(1, db.settings())90 val seedOps = Json.parseToJsonElement(hub.requests[0].body!!).jsonObject["ops"]!!.jsonArray.map { it.jsonObject }91 assertTrue(seedOps.any { it["k"]!!.jsonPrimitive.content == "2" && it["id"]!!.jsonPrimitive.long == manga.id && it["p"]!!.jsonPrimitive.content == "favorite" })9293 // An established device (cursor > 0) does not re-seed on a normal sync…94 hub.requests.clear()95 hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":3,"ents":[]}""")96 service(db, hub).sync(1, db.settings())97 assertEquals(1, hub.requests.size)98 assertTrue(Json.parseToJsonElement(hub.requests[0].body!!).jsonObject["ops"]!!.jsonArray.isEmpty())99100 // …but "Upload only" re-sends everything with fresh clocks so local state wins.101 hub.requests.clear()102 hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":4,"ents":[]}""")103 hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":5,"ents":[]}""")104 service(db, hub).pushChanges(1)105 val overwrite = Json.parseToJsonElement(hub.requests[0].body!!).jsonObject106 assertEquals(HubSyncService.NO_DELTA, overwrite["since"]!!.jsonPrimitive.long)107 val op = overwrite["ops"]!!.jsonArray.map { it.jsonObject }.single { it["p"]!!.jsonPrimitive.content == "favorite" }108 assertTrue(op["t"]!!.jsonPrimitive.long > HubSyncService.SEED_CLOCK)109 assertEquals(1L, db.syncPreferences().single().hubHead, "upload-only leaves the pull cursor alone")110 }111112 @Test113 fun conflictTriggersOneResyncFromZero() = runTest {114 val db = InMemoryYokanDatabase(emptySnapshot())115 loggedIn(db)116 db.upsertSyncPreference(db.syncPreferences().single().copy(hubHead = 900, hubEpoch = 1))117 val hub = FakeHub()118 hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")119 hub.responses += HttpResponse(200, """{"epoch":2,"head":3,"hlc":1,"ents":[]}""")120 val result = service(db, hub).pullChanges(1)121 assertTrue(result.errors.isEmpty(), result.errors.toString())122 assertEquals(2, hub.requests.size)123 val second = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject124 assertEquals(0L, second["since"]!!.jsonPrimitive.long)125 assertEquals(2, second["epoch"]!!.jsonPrimitive.content.toInt())126 assertEquals(3L, db.syncPreferences().single().hubHead)127 }128129 @Test130 fun higherEpochResyncDropsStaleOpsButRetriesCurrentGeneration() = runTest {131 val db = InMemoryYokanDatabase(132 emptySnapshot().copy(133 syncPreferences = listOf(134 DbSyncPreference(135 syncId = 1,136 server = "https://hub.test",137 authToken = "tok",138 syncOn = true,139 hubHead = 1,140 hubEpoch = 1,141 ),142 ),143 outbox = listOf(144 DbOutboxOp(SyncPaths.KIND_MANGA, 21, "name", "\"Old\"", 1, 1, epoch = 1),145 DbOutboxOp(SyncPaths.KIND_MANGA, 22, "favorite", "true", 2, 2, epoch = 2),146 ),147 ),148 )149150 val hub = FakeHub()151 hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")152 hub.responses += HttpResponse(200, """{"epoch":2,"head":4,"hlc":1,"ents":[]}""")153154 service(db, hub).sync(1, db.settings())155156 assertEquals(2, hub.requests.size)157 val retried = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject["ops"]!!.jsonArray158 assertEquals(listOf("favorite"), retried.map { it.jsonObject["p"]!!.jsonPrimitive.content })159 assertEquals(2, db.syncPreferences().single().hubEpoch)160 assertTrue(db.outbox().isEmpty())161 }162163 @Test164 fun conflictAtCurrentEpochDoesNotDiscardUnrelatedOutboxOps() = runTest {165 val db = InMemoryYokanDatabase(emptySnapshot())166 loggedIn(db)167 db.upsertSyncPreference(db.syncPreferences().single().copy(hubHead = 1, hubEpoch = 2))168 val manga = db.upsertManga(DbManga(name = "Local", link = "/t", sourceId = 5))169 val hub = FakeHub()170 hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")171 hub.responses += HttpResponse(200, """{"epoch":2,"head":2,"hlc":1,"ents":[]}""")172173 service(db, hub).sync(1, db.settings())174175 val retried = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject["ops"]!!.jsonArray176 assertTrue(retried.any { it.jsonObject["id"]!!.jsonPrimitive.long == manga.id })177 }178179 @Test180 fun completedRollbackWithEmptyHeadDoesNotReseedRestoredMonotoneState() = runTest {181 val db = InMemoryYokanDatabase(emptySnapshot())182 loggedIn(db)183 db.upsertSyncPreference(184 db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true),185 )186 db.applyRemote { db.upsertManga(DbManga(id = 99, name = "local", lastRead = 42)) }187 val hub = FakeHub()188 hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")189 hub.responses += HttpResponse(190 200,191 """{"epoch":2,"head":0,"hlc":1,"ents":[{"k":2,"id":99,"doc":{"name":"restored","lastRead":7}}]}""",192 )193 service(db, hub).sync(1, db.settings())194 assertFalse(db.syncPreferences().single().hubRecoveryPending)195 assertTrue(db.syncPreferences().single().hubBootstrapComplete)196 assertEquals(7, db.manga(99)!!.lastRead)197198 hub.requests.clear()199 hub.responses += HttpResponse(200, """{"epoch":2,"head":0,"hlc":2,"ents":[]}""")200 service(db, hub).sync(1, db.settings())201202 val next = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject203 assertTrue(next["ops"]!!.jsonArray.isEmpty())204 assertFalse(hub.requests.single().body!!.contains("restored"))205 }206207 @Test208 fun firstEpochAdoptionPreservesInitialSeedUploads() = runTest {209 val db = InMemoryYokanDatabase(emptySnapshot())210 val manga = db.upsertManga(DbManga(name = "preexisting", link = "/local"))211 val hub = FakeHub()212 hub.responses += HttpResponse(200, """{"supported":["1"]}""")213 hub.responses += HttpResponse(200, """{"token":"abc"}""")214 hub.responses += HttpResponse(409, """{"resync":true,"epoch":1}""")215 hub.responses += HttpResponse(200, """{"epoch":1,"head":10,"hlc":1,"ents":[]}""")216 hub.responses += HttpResponse(200, """{"epoch":1,"head":10,"hlc":2,"ents":[]}""")217 val service = service(db, hub)218219 assertTrue(service.login(1, "hub.test", "a@b", "pw").success)220 service.sync(1, db.settings())221222 val firstSeed = Json.parseToJsonElement(hub.requests[2].body!!).jsonObject223 val adoptedSeed = Json.parseToJsonElement(hub.requests[3].body!!).jsonObject224 assertEquals(0, firstSeed["epoch"]!!.jsonPrimitive.content.toInt())225 assertEquals(1, adoptedSeed["epoch"]!!.jsonPrimitive.content.toInt())226 assertTrue(firstSeed["ops"]!!.jsonArray.any { it.jsonObject["id"]!!.jsonPrimitive.long == manga.id })227 assertTrue(adoptedSeed["ops"]!!.jsonArray.any { it.jsonObject["id"]!!.jsonPrimitive.long == manga.id })228 assertFalse(db.syncPreferences().single().hubRecoveryPending)229 assertTrue(db.syncPreferences().single().hubBootstrapComplete)230 }231232 @Test233 fun epochZeroToTwoRollbackDropsStaleSeedWorkBeforeRetry() = runTest {234 val db = InMemoryYokanDatabase(emptySnapshot())235 loggedIn(db)236 val manga = db.upsertManga(DbManga(name = "stale", link = "/stale"))237 val hub = FakeHub()238 hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")239 hub.responses += HttpResponse(200, """{"epoch":2,"head":0,"hlc":1,"ents":[]}""")240 hub.responses += HttpResponse(200, """{"epoch":2,"head":0,"hlc":2,"ents":[]}""")241242 service(db, hub).sync(1, db.settings())243244 assertTrue(hub.requests[0].body!!.contains(manga.id.toString()))245 assertTrue(hub.requests.drop(1).all { request ->246 Json.parseToJsonElement(request.body!!).jsonObject["ops"]!!.jsonArray.isEmpty()247 })248 assertFalse(db.syncPreferences().single().hubRecoveryPending)249 assertTrue(db.syncPreferences().single().hubBootstrapComplete)250 }251252 @Test253 fun establishedSerializedPreferenceDoesNotReseedStaleLocalState() = runTest {254 val legacyRaw = encodeDatabaseSnapshot(255 emptySnapshot().copy(256 syncPreferences = listOf(257 DbSyncPreference(258 syncId = 1,259 server = "https://hub.test",260 authToken = "old-token",261 syncOn = true,262 ),263 ),264 mangas = listOf(DbManga(id = 77, name = "stale", lastRead = 101)),265 ),266 ).replace("\"hubRecoveryPending\": false", "\"legacyRecoveryPending\": false")267 .replace("\"hubBootstrapComplete\": false", "\"legacyBootstrapComplete\": false")268 val db = InMemoryYokanDatabase(decodeDatabaseSnapshot(legacyRaw)!!)269270 assertTrue(db.syncPreferences().single().hubBootstrapComplete)271272 val fresh = InMemoryYokanDatabase(273 emptySnapshot().copy(274 syncPreferences = listOf(275 DbSyncPreference(276 syncId = 1,277 server = "https://hub.test",278 authToken = "new-token",279 syncOn = true,280 ),281 ),282 ),283 )284 assertFalse(fresh.syncPreferences().single().hubBootstrapComplete)285 val hub = FakeHub()286 hub.responses += HttpResponse(200, """{"epoch":1,"head":0,"hlc":1,"ents":[]}""")287288 service(db, hub).sync(1, db.settings())289290 val body = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject291 assertTrue(body["ops"]!!.jsonArray.isEmpty())292 }293294 @Test295 fun interruptedMultiChunkBootstrapRestartsFromTheBeginning() = runTest {296 val db = InMemoryYokanDatabase(297 emptySnapshot().copy(298 syncPreferences = listOf(299 DbSyncPreference(300 syncId = 1,301 server = "https://hub.test",302 authToken = "tok",303 syncOn = true,304 hubEpoch = 1,305 ),306 ),307 mangas = (1L..2_000L).map { id -> DbManga(id = id, name = "m$id") },308 ),309 )310 db.upsertSyncPreference(db.syncPreferences().single().copy(hubBootstrapComplete = false))311 val hub = FakeHub()312 hub.responses += HttpResponse(200, """{"epoch":1,"head":1,"hlc":1,"ents":[]}""")313 hub.responses += HttpResponse(503, """{"error":"interrupted"}""")314 service(db, hub).sync(1, db.settings())315 assertFalse(db.syncPreferences().single().hubBootstrapComplete)316317 val reopened = InMemoryYokanDatabase(db.snapshot())318 reopened.removeManga(1L, recordChange = false)319 reopened.upsertManga(DbManga(id = 3_000L, name = "added-before-retry"))320 hub.requests.clear()321 // Enough acknowledgements for every bootstrap chunk; the count depends on title document fields.322 repeat(6) { hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":${it + 2},"ents":[]}""") }323 service(reopened, hub).sync(1, reopened.settings())324325 val restarted = hub.requests.first().body!!326 assertTrue(Json.parseToJsonElement(restarted).jsonObject["ops"]!!.jsonArray.isNotEmpty())327 assertTrue(hub.requests.any { it.body!!.contains("3000") })328 assertTrue(hub.requests.any { it.body!!.contains("2") })329 assertTrue(reopened.syncPreferences().single().hubBootstrapComplete)330 }331332 @Test333 fun interruptedRollbackRecoveryNeverSeedsExtremeDocuments() = runTest {334 val db = InMemoryYokanDatabase(emptySnapshot())335 loggedIn(db)336 db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 0))337 db.upsertManga(DbManga(id = Long.MIN_VALUE, name = "min"))338 db.upsertManga(DbManga(id = Long.MAX_VALUE, name = "max"))339340 val hub = FakeHub()341 hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")342 hub.responses += HttpResponse(503, """{"error":"interrupted"}""")343 service(db, hub).sync(1, db.settings())344345 assertTrue(db.syncPreferences().single().hubRecoveryPending)346 assertTrue(hub.requests[0].body!!.contains(Long.MIN_VALUE.toString()))347 assertTrue(hub.requests[0].body!!.contains(Long.MAX_VALUE.toString()))348 val interruptedRetry = Json.parseToJsonElement(hub.requests[1].body!!).jsonObject349 assertEquals(0L, interruptedRetry["since"]!!.jsonPrimitive.long)350 assertTrue(interruptedRetry["ops"]!!.jsonArray.isEmpty())351352 hub.requests.clear()353 hub.responses += HttpResponse(200, """{"epoch":2,"head":8,"hlc":1,"ents":[]}""")354 service(db, hub).sync(1, db.settings())355356 val recovered = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject357 assertEquals(0L, recovered["since"]!!.jsonPrimitive.long)358 assertTrue(recovered["ops"]!!.jsonArray.isEmpty())359 assertFalse(db.syncPreferences().single().hubRecoveryPending)360 }361362 @Test363 fun capturedSeedChunkIsNotRetriedAfterGenerationChange() = runTest {364 val db = InMemoryYokanDatabase(emptySnapshot())365 loggedIn(db)366 db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 0))367 val manga = db.upsertManga(DbManga(name = "seed", link = "/seed"))368 val hub = FakeHub()369 hub.responses += HttpResponse(409, """{"resync":true,"epoch":2}""")370 hub.responses += HttpResponse(200, """{"epoch":2,"head":5,"hlc":1,"ents":[]}""")371 hub.responses += HttpResponse(200, """{"epoch":2,"head":6,"hlc":2,"ents":[]}""")372373 service(db, hub).sync(1, db.settings())374375 assertTrue(hub.requests[0].body!!.contains(manga.id.toString()))376 assertTrue(hub.requests.drop(1).all { request ->377 Json.parseToJsonElement(request.body!!).jsonObject["ops"]!!.jsonArray.isEmpty()378 })379 }380381 @Test382 fun legacyEpochRowsAreDroppedAndOnlyCurrentEpochIsSent() = runTest {383 val db = InMemoryYokanDatabase(384 emptySnapshot().copy(385 syncPreferences = listOf(386 DbSyncPreference(387 syncId = 1,388 server = "https://hub.test",389 authToken = "tok",390 syncOn = true,391 hubHead = 1,392 hubEpoch = 2,393 ),394 ),395 outbox = listOf(396 DbOutboxOp(SyncPaths.KIND_MANGA, 31, "name", "\"legacy\"", 1, 1),397 DbOutboxOp(SyncPaths.KIND_MANGA, 32, "name", "\"current\"", 2, 2, epoch = 2),398 ),399 ),400 )401 val hub = FakeHub()402 hub.responses += HttpResponse(200, """{"epoch":2,"head":2,"hlc":1,"ents":[]}""")403404 service(db, hub).pushChanges(1)405406 val body = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject407 assertEquals(listOf(32L), body["ops"]!!.jsonArray.map { it.jsonObject["id"]!!.jsonPrimitive.long })408 assertEquals(1, body["generation"]!!.jsonPrimitive.content.toInt())409 }410411 @Test412 fun editCreatedDuringRecoveryIsSentAfterRecoveryCompletes() = runTest {413 val db = InMemoryYokanDatabase(emptySnapshot())414 loggedIn(db)415 db.upsertSyncPreference(416 db.syncPreferences().single().copy(hubEpoch = 2, hubHead = 0, hubRecoveryPending = true),417 )418 val hub = FakeHub()419 hub.onRequest = { if (hub.requests.size == 1) db.upsertManga(DbManga(name = "after recovery")) }420 hub.responses += HttpResponse(200, """{"epoch":2,"head":8,"hlc":1,"ents":[]}""")421 service(db, hub).sync(1, db.settings())422 assertFalse(db.outbox().isEmpty())423 assertTrue(db.outbox().all { it.epoch == 2 })424 assertFalse(db.syncPreferences().single().hubRecoveryPending)425426 hub.onRequest = {}427 hub.responses += HttpResponse(200, """{"epoch":2,"head":9,"hlc":2,"ents":[]}""")428 service(db, hub).sync(1, db.settings())429430 val sent = Json.parseToJsonElement(hub.requests.last().body!!).jsonObject["ops"]!!.jsonArray431 assertTrue(sent.isNotEmpty())432 assertEquals(1, Json.parseToJsonElement(hub.requests.last().body!!).jsonObject["generation"]!!.jsonPrimitive.content.toInt())433 }434435 @Test436 fun editsMadeDuringTheRequestWinOverTheIncomingDoc() = runTest {437 val db = InMemoryYokanDatabase(emptySnapshot())438 loggedIn(db)439 db.upsertSyncPreference(440 db.syncPreferences().single().copy(hubHead = 1, hubEpoch = 1, hubBootstrapComplete = true),441 ) // established device: no seed round442 val manga = db.upsertManga(DbManga(name = "Local", link = "/t", sourceId = 5, favorite = false))443 val hub = FakeHub()444 hub.onRequest = { db.upsertManga(db.manga(manga.id)!!.copy(favorite = true)) } // user taps while the request is in flight445 hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":2,"id":${manga.id},"doc":{"name":"Remote","favorite":false}}]}""")446 service(db, hub).sync(1, db.settings())447 val after = db.manga(manga.id)!!448 assertEquals("Remote", after.name)449 assertTrue(after.favorite, "the in-flight local edit is kept")450 assertEquals(listOf("favorite"), db.outbox().map { it.path }, "and still pending for the next round")451 }452453 @Test454 fun pendingTitleDeleteSuppressesAnInFlightLiveDocument() = runTest {455 val id = 42L456 val db = InMemoryYokanDatabase(457 emptySnapshot().copy(458 syncPreferences = listOf(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true)),459 outbox = listOf(DbOutboxOp(SyncPaths.KIND_MANGA, id, SyncPaths.DELETED, "true", 1, 1, epoch = 1)),460 ),461 )462 val hub = FakeHub()463 hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":2,"id":$id,"doc":{"name":"resurrected"}}]}""")464465 service(db, hub).pullChanges(1)466467 assertNull(db.manga(id))468 assertEquals("true", db.outbox().single().value)469 assertEquals(2L, db.syncPreferences().single().hubHead)470 }471472 @Test473 fun remoteTitleTombstoneRemovesDependentRowsWithoutCreatingOutboxOps() = runTest {474 val db = InMemoryYokanDatabase(emptySnapshot())475 loggedIn(db)476 db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true))477 val manga = db.upsertManga(DbManga(name = "Title"))478 val chapter = db.upsertChapter(DbChapter(mangaId = manga.id, name = "Chapter"))479 db.upsertHistory(DbHistory(mangaId = manga.id, chapterId = chapter.id, itemType = eu.friedcutlet.yokan.database.DbItemType.Manga))480 db.upsertUpdate(DbUpdate(mangaId = manga.id, chapterId = chapter.id))481 val pendingOutbox = db.outbox()482 val hub = FakeHub()483 hub.responses += HttpResponse(200, """{"epoch":1,"head":2,"hlc":1,"ents":[{"k":2,"id":${manga.id},"del":true}]}""")484485 service(db, hub).pullChanges(1)486487 assertNull(db.manga(manga.id))488 assertTrue(db.chapters(manga.id).isEmpty())489 assertTrue(db.histories().isEmpty())490 assertTrue(db.updates().isEmpty())491 assertEquals(pendingOutbox, db.outbox(), "remote deletion creates no echo ops or discards unrelated pending ops")492 assertEquals(2L, db.syncPreferences().single().hubHead)493 }494495 @Test496 fun historyAndUpdateTombstonesSyncWhileTheirContentFlagsAreOff() = runTest {497 val db = InMemoryYokanDatabase(498 emptySnapshot().copy(499 syncPreferences = listOf(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true, syncHistories = false, syncUpdates = false)),500 outbox = listOf(501 DbOutboxOp(SyncPaths.KIND_HISTORY, 11, SyncPaths.DELETED, "true", 1, 1, epoch = 1),502 DbOutboxOp(SyncPaths.KIND_HISTORY, 11, "date", "\"today\"", 2, 2, epoch = 1),503 DbOutboxOp(SyncPaths.KIND_UPDATE, 12, SyncPaths.DELETED, "true", 3, 3, epoch = 1),504 DbOutboxOp(SyncPaths.KIND_UPDATE, 12, "chapterName", "\"Chapter\"", 4, 4, epoch = 1),505 ),506 ),507 )508 val hub = FakeHub()509 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"}}]}""")510511 service(db, hub).sync(1, db.settings())512513 val sent = Json.parseToJsonElement(hub.requests.single().body!!).jsonObject["ops"]!!.jsonArray514 assertEquals(setOf(5, 6), sent.map { it.jsonObject["k"]!!.jsonPrimitive.content.toInt() }.toSet())515 assertTrue(sent.all { it.jsonObject["p"]!!.jsonPrimitive.content == SyncPaths.DELETED })516 assertEquals(setOf("date", "chapterName"), db.outbox().map { it.path }.toSet())517 assertTrue(db.histories().isEmpty())518 assertTrue(db.updates().isEmpty())519 assertEquals(2L, db.syncPreferences().single().hubHead)520 }521522 @Test523 fun activeDownloadDefersRemoteTitleDeleteAndKeepsCursor() = runTest {524 val db = InMemoryYokanDatabase(emptySnapshot())525 loggedIn(db)526 db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true))527 val manga = db.upsertManga(DbManga(name = "Downloading"))528 val chapter = db.upsertChapter(DbChapter(mangaId = manga.id))529 db.upsertDownload(DbDownload(chapterId = chapter.id, isStartDownload = true, isDownload = false))530 val hub = FakeHub()531 hub.responses += HttpResponse(200, """{"epoch":1,"head":9,"hlc":1,"ents":[{"k":2,"id":${manga.id},"del":true}]}""")532533 val result = service(db, hub).pullChanges(1)534535 assertTrue(result.errors.any { it.contains("active chapter download") }, result.errors.toString())536 assertEquals(1L, db.syncPreferences().single().hubHead)537 assertNotNull(db.manga(manga.id))538 assertNotNull(db.chapter(chapter.id))539 }540541 @Test542 fun maintenanceAndExpiredSessionAreReportedNotRetried() = runTest {543 val db = InMemoryYokanDatabase(emptySnapshot())544 loggedIn(db)545 val hub = FakeHub()546 hub.responses += HttpResponse(503, """{"error":"maintenance"}""")547 assertTrue(service(db, hub).pullChanges(1).errors.single().contains("maintenance"))548 hub.responses += HttpResponse(401, "")549 assertTrue(service(db, hub).pullChanges(1).errors.single().contains("log in"))550 assertNull(db.syncPreferences().single().authToken)551 }552553 @Test554 fun pagedPullReportsProgressAgainstTheHubTip() = runTest {555 val db = InMemoryYokanDatabase(emptySnapshot())556 loggedIn(db)557 db.upsertSyncPreference(db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 100, hubBootstrapComplete = true))558 val monitor = SyncOperationMonitor()559 val hub = FakeHub()560 hub.responses += HttpResponse(200, """{"epoch":1,"head":150,"tip":300,"hlc":1,"more":true}""")561 hub.responses += HttpResponse(200, """{"epoch":1,"head":300,"tip":300,"hlc":2,"more":false}""")562 val seen = mutableListOf<Float?>()563 hub.onRequest = { seen += monitor.state.value.progress }564565 service(db, hub, monitor).pullChanges(1)566567 assertEquals(listOf(null, 0.25f), seen)568 assertNull(monitor.state.value.progress, "finished rounds drop stale progress")569 }570571 @Test572 fun cancellingHttpRoundCleansObservableOperationState() = runTest {573 val db = InMemoryYokanDatabase(emptySnapshot())574 loggedIn(db)575 db.upsertSyncPreference(576 db.syncPreferences().single().copy(hubEpoch = 1, hubHead = 1, hubBootstrapComplete = true),577 )578 val started = CompletableDeferred<Unit>()579 val hub = FakeHub().apply {580 suspendOnRequest = {581 started.complete(Unit)582 awaitCancellation()583 }584 }585 val monitor = SyncOperationMonitor()586 val service = service(db, hub, monitor)587 val job = launch { service.pullChanges(1) }588 started.await()589 assertTrue(monitor.state.value.isActive)590591 job.cancelAndJoin()592593 assertFalse(monitor.state.value.isActive)594 assertEquals(SyncOperationOutcome.Cancelled, monitor.state.value.lastOutcome)595 }596}597