package eu.friedcutlet.yokan.database.sync import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbOutboxOp import eu.friedcutlet.yokan.database.DbPersonalReaderMode import eu.friedcutlet.yokan.database.DbReaderMode import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.emptySnapshot import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotSame import kotlin.test.assertSame import kotlin.test.assertTrue import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest class OutboxTest { private fun loggedIn() = InMemoryYokanDatabase( emptySnapshot().copy( syncPreferences = listOf(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 1)), ), ) @Test fun nothingIsRecordedWithoutALoggedInHubAndUnsendableOpsAreDropped() { val db = InMemoryYokanDatabase( emptySnapshot().copy( outbox = listOf( DbOutboxOp(SyncPaths.KIND_MANGA, 1, "name", "\"never sent\"", hlc = 1, seq = 1), DbOutboxOp(SyncPaths.KIND_MANGA, 2, "name", "\"pending since logout\"", hlc = 2, seq = 2, epoch = 3), ), ), ) assertEquals(listOf(2L), db.outbox().map { it.id }, "epoch-0 ops are dropped, ops of a real hub epoch kept") val manga = db.upsertManga(DbManga(name = "T", link = "/t", sourceId = 1)) db.updateSettings(db.settings().copy(themeIsDark = !db.settings().themeIsDark)) db.removeManga(manga.id) assertEquals(listOf(2L), db.outbox().map { it.id }, "no hub: the first sync seeds full state instead") db.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 3)) val next = db.upsertManga(DbManga(name = "T2", link = "/t2", sourceId = 1)) assertTrue(db.outbox().any { it.id == next.id && it.path == "name" && it.epoch == 3 }) } @Test fun newOutboxOpsUseTheActiveHubEpoch() { val db = InMemoryYokanDatabase( emptySnapshot().copy( syncPreferences = listOf( DbSyncPreference(syncId = 2, server = "https://other.test", authToken = "other", hubEpoch = 99), DbSyncPreference(syncId = 3, server = "cloud://drive", authToken = "cloud", syncOn = true, hubEpoch = 88), DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "hub", syncOn = true, hubEpoch = 7), ), ), ) db.upsertManga(DbManga(name = "T", link = "/t", sourceId = 1)) assertTrue(db.outbox().isNotEmpty()) assertTrue(db.outbox().all { it.epoch == 7 }) } @Test fun insertsRecordEveryFieldAndUpdatesOnlyTheChangedPath() { val db = loggedIn() val saved = db.upsertManga(DbManga(name = "T", link = "/t", sourceId = 1)) assertEquals(SyncIds.forManga(saved), saved.id, "new rows get a stable id") val first = db.outbox() assertTrue(first.any { it.kind == SyncPaths.KIND_MANGA && it.id == saved.id && it.path == "name" && it.value == "\"T\"" }) db.upsertManga(saved.copy(favorite = true)) val delta = db.outbox().filter { it.seq > first.maxOf { o -> o.seq } } assertEquals(listOf("favorite"), delta.map { it.path }) assertEquals("true", delta.single().value) // Coalesced: the second write to the same path replaces the first row db.upsertManga(saved.copy(favorite = false)) assertEquals(1, db.outbox().count { it.path == "favorite" }) assertEquals("false", db.outbox().single { it.path == "favorite" }.value) assertTrue(db.outbox().zipWithNext().all { (a, b) -> a.seq < b.seq }, "outbox is ordered by seq") } @Test fun deleteBecomesTombstoneOpAndRemoteApplyIsSilent() { val db = loggedIn() val cat = db.upsertCategory(DbCategory(name = "Reading", forItemType = DbItemType.Manga)) db.removeCategory(cat.id) val tomb = db.outbox().last() assertEquals(SyncPaths.DELETED, tomb.path) assertEquals("true", tomb.value) val before = db.outbox().size db.applyRemote { db.upsertManga(DbManga(name = "from hub", link = "/h", sourceId = 2)) } assertEquals(before, db.outbox().size, "hub writes are not echoed") } @Test fun settingsDiffIsKeyedPerTitle() { val db = loggedIn() val s0 = db.settings() db.updateSettings(s0.copy(personalReaderModeList = listOf(DbPersonalReaderMode(111, DbReaderMode.Vertical)))) db.updateSettings(db.settings().copy(personalReaderModeList = listOf(DbPersonalReaderMode(111, DbReaderMode.Vertical), DbPersonalReaderMode(222, DbReaderMode.Webtoon)))) val paths = db.outbox().filter { it.kind == SyncPaths.KIND_SETTINGS }.map { it.path } assertEquals(listOf("personalReaderModeList.111", "personalReaderModeList.222"), paths) // device-local settings never produce ops db.updateSettings(db.settings().copy(jrePath = "/opt/jdk")) assertEquals(paths, db.outbox().filter { it.kind == SyncPaths.KIND_SETTINGS }.map { it.path }) } @Test fun removeOutboxOnlyDropsOpsThatWereSent() { val db = loggedIn() val m = db.upsertManga(DbManga(name = "T", link = "/t", sourceId = 1)) val sent = db.outbox() db.upsertManga(m.copy(name = "T2")) // rewrites the "name" path with a newer seq db.removeOutbox(sent) assertEquals(listOf("name"), db.outbox().map { it.path }) assertEquals("\"T2\"", db.outbox().single().value) } @Test fun batchEmitsOneSnapshot() { val db = InMemoryYokanDatabase(emptySnapshot()) var emissions = 0 val start = db.snapshots().value db.batch { db.upsertManga(DbManga(name = "A", link = "/a", sourceId = 1)) db.upsertManga(DbManga(name = "B", link = "/b", sourceId = 1)) if (db.snapshots().value !== start) emissions++ } assertEquals(0, emissions, "nothing emitted inside the batch") assertEquals(2, db.snapshots().value.mangas.size) } @Test fun oneTableMutationReusesUnchangedSnapshotLists() { val db = InMemoryYokanDatabase(emptySnapshot()) val before = db.snapshots().value db.upsertManga(DbManga(name = "A", link = "/a", sourceId = 1)) val after = db.snapshots().value assertNotSame(before.mangas, after.mangas) assertSame(before.chapters, after.chapters) assertSame(before.downloads, after.downloads) } @Test fun aMangaEditIsPublishedEvenWhenNothingElseChanges() { val db = InMemoryYokanDatabase(emptySnapshot()) val manga = db.upsertManga(DbManga(name = "A", link = "/a", sourceId = 1)) db.upsertManga(manga.copy(favorite = true)) assertTrue(db.snapshots().value.mangas.single().favorite, "snapshot flows drop values equal to the current one") } @Test fun concurrentMutationsKeepRowsAndOutboxSequencesConsistent() = runTest { val db = loggedIn() coroutineScope { repeat(4) { worker -> launch(Dispatchers.Default) { repeat(25) { index -> val id = worker * 25L + index + 1L db.upsertManga(DbManga(id = id, name = "M$id", link = "/$id", sourceId = 1)) } } } } assertEquals(100, db.mangas().size) val sequences = db.outbox().map { it.seq } assertEquals(sequences.size, sequences.distinct().size) assertEquals(sequences.sorted(), sequences) } }