package eu.friedcutlet.yokan.app.profiles import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.database.room.RoomYokanDatabase import eu.friedcutlet.yokan.database.room.createDesktopProfileRoomDatabase import eu.friedcutlet.yokan.services.files.createDesktopProfileFileService import java.io.File import java.nio.file.Files import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertFailsWith import kotlin.test.assertTrue import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.domain.ProfileStorageNamespace class ProfileStorageTest { @Test fun fileRegistryCommitsAtomicallyAndIndependentInstancesDoNotLoseUpdates() = runBlocking { val root = Files.createTempDirectory("yokan-profile-registry").toFile() try { val file = File(root, "profiles/registry.json") val one = ProfileRegistry(FileProfileRegistryPersistence(file)) val two = ProfileRegistry(FileProfileRegistryPersistence(file)) one.refresh() coroutineScope { val a = async { one.beginCreate("A", A) }; val b = async { two.beginCreate("B", B) }; a.await(); b.await() } val registry = ProfileRegistry(FileProfileRegistryPersistence(file)) assertEquals(setOf(ProfileId.Default, A, B), registry.refresh().profiles.map { it.id }.toSet()) assertFalse(file.parentFile.listFiles().orEmpty().any { it.extension == "tmp" }) registry.markReady(A); registry.recordActive(A) assertEquals(A, ProfileRegistry(FileProfileRegistryPersistence(file)).refresh().lastActive) // An abandoned staging file never replaces a committed registry on restart. File(file.parentFile, "registry-abandoned.tmp").writeText("{") assertEquals(A, ProfileRegistry(FileProfileRegistryPersistence(file)).refresh().lastActive) } finally { root.deleteRecursively() } } @Test fun corruptAndOversizedFileRegistryPreserveBytesAndDefaultData() = runBlocking { val root = Files.createTempDirectory("yokan-profile-corrupt").toFile() try { val original = File(root, "yokan-room.db").apply { writeText("existing default sentinel") } val file = File(root, "profiles/registry.json").apply { parentFile.mkdirs() } for (bytes in listOf("{".encodeToByteArray(), byteArrayOf(0xFF.toByte()), ByteArray(MaxProfileRegistryBytes + 1))) { file.writeBytes(bytes) assertFailsWith { ProfileRegistry(FileProfileRegistryPersistence(file)).refresh() } assertTrue(file.readBytes().contentEquals(bytes)) assertEquals("existing default sentinel", original.readText()) } } finally { root.deleteRecursively() } } @Test fun twoNativeDatabasesWithIdenticalIdsRemainIndependentAcrossReopenAndDefaultAdoption() = runBlocking { val root = Files.createTempDirectory("yokan-profile-room").toFile() try { val legacy = seedDatabaseSnapshot().copy(mangas = listOf(DbManga(id = 42, name = "Default", favorite = true, privateNote = "Legacy note"))) val defaultRoom = createDesktopProfileRoomDatabase(root, ProfileId.Default) try { val default = RoomYokanDatabase(defaultRoom, legacySnapshotProvider = { legacy }) default.awaitPersistence() assertEquals("Legacy note", default.manga(42)?.privateNote) } finally { defaultRoom.close() } assertTrue(File(root, "yokan-room.db").isFile) val rooms = listOf(A, B).map { createDesktopProfileRoomDatabase(root, it) } try { val databases = rooms.map { RoomYokanDatabase(it) } assertTrue(databases.all { it.mangas().isEmpty() && it.syncPreferences().isEmpty() && it.trackPreferences().isEmpty() }) databases[0].upsertManga(DbManga(id = 42, name = "A", favorite = true, privateNote = "A note")) databases[1].upsertManga(DbManga(id = 42, name = "B", favorite = true, privateNote = "B note")) databases[0].updateSettings(databases[0].settings().copy(readerHoldToScroll = true, automaticReaderLayout = true)) databases[1].updateSettings(databases[1].settings().copy(readerHoldToScroll = false, automaticReaderLayout = false)) databases.forEach { it.awaitPersistence() } } finally { rooms.forEach { it.close() } } for ((id, name, note) in listOf(Triple(ProfileId.Default, "Default", "Legacy note"), Triple(A, "A", "A note"), Triple(B, "B", "B note"))) { val room = createDesktopProfileRoomDatabase(root, id) try { val db = RoomYokanDatabase(room, legacySnapshotProvider = { error("Existing profile must not load legacy data") }) assertEquals(name, db.manga(42)?.name); assertEquals(note, db.manga(42)?.privateNote) assertEquals(id == A, db.settings().readerHoldToScroll) db.awaitPersistence() } finally { room.close() } } } finally { root.deleteRecursively() } } @Test fun profileOwnedDownloadBackupAndCacheRootsDoNotTouchDefaultOrExports() { val root = Files.createTempDirectory("yokan-profile-files").toFile() try { val default = createDesktopProfileFileService(root, ProfileId.Default) val a = createDesktopProfileFileService(root, A) val b = createDesktopProfileFileService(root, B) assertEquals(File(root, "Yokan/downloads").path, default.downloadRoot) assertEquals(File(root, "Yokan/backups").path, default.backupRoot) assertEquals(File(root, "cache").path, default.cacheRoot) for ((index, files) in listOf(default, a, b).withIndex()) for (path in listOf(files.downloadRoot, files.backupRoot, files.cacheRoot)) { files.writeBytes("$path/same-name.txt", "owner $index".encodeToByteArray()) } val exported = File(root, "exported-backup.zip").apply { writeText("user export") } assertTrue(File(ProfileStorageNamespace(A).ownedRoot(root.path)).deleteRecursively()) for ((files, index) in listOf(default to 0, b to 2)) { for (path in listOf(files.downloadRoot, files.backupRoot, files.cacheRoot)) { assertEquals("owner $index", files.readBytes("$path/same-name.txt").decodeToString()) } } assertEquals("user export", exported.readText()) } finally { root.deleteRecursively() } } @Test fun explicitSnapshotFlushPersistsOnlyItsOwningStoreAndFailureCanBeRetried() = runBlocking { val raw = mutableMapOf(); var rejected: String? = null fun open(id: ProfileId): YokanDatabase { val key = ProfileStorageNamespace(id).browserSnapshotKey return SnapshotYokanDatabase(object : DatabaseSnapshotStore { override fun load() = raw[key]?.let(::decodeDatabaseSnapshot) override fun save(snapshot: YokanDatabaseSnapshot) { if (key == rejected) error("Quota exceeded") raw[key] = encodeDatabaseSnapshot(snapshot) } }) } val default = open(ProfileId.Default); default.upsertManga(DbManga(id = 42, privateNote = "Default")); default.awaitPersistence() val defaultRaw = raw.getValue("yokan-database-v1") val a = open(A); val b = open(B) assertTrue(a.mangas().isEmpty()); assertTrue(b.mangas().isEmpty()) a.upsertManga(DbManga(id = 42, privateNote = "A")); b.upsertManga(DbManga(id = 42, privateNote = "B")) rejected = ProfileStorageNamespace(B).browserSnapshotKey a.awaitPersistence(); assertFailsWith { b.awaitPersistence() } assertEquals(defaultRaw, raw.getValue("yokan-database-v1")) assertEquals("A", open(A).manga(42)?.privateNote) rejected = null; b.awaitPersistence(); assertEquals("B", open(B).manga(42)?.privateNote) assertEquals("Default", open(ProfileId.Default).manga(42)?.privateNote) } companion object { val A = ProfileId("p_${"a".repeat(32)}"); val B = ProfileId("p_${"b".repeat(32)}") } }