package eu.friedcutlet.yokan.app.profiles import androidx.sqlite.driver.bundled.BundledSQLiteDriver import androidx.sqlite.execSQL import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.room.RoomYokanDatabase import eu.friedcutlet.yokan.database.room.createDesktopProfileRoomDatabase import eu.friedcutlet.yokan.services.files.createDesktopProfileFileService import eu.friedcutlet.yokan.services.files.JvmLocalArchiveService import eu.friedcutlet.yokan.services.notifications.NotificationService import eu.friedcutlet.yokan.services.notifications.NotificationPayload import eu.friedcutlet.yokan.services.notifications.NotificationChannel import eu.friedcutlet.yokan.services.logging.LogSink import java.nio.file.Files import kotlinx.coroutines.runBlocking import kotlinx.coroutines.TimeoutCancellationException import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertSame import kotlin.test.assertTrue import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.domain.ProfileStorageNamespace class ProfileSessionRoomTest { @Test fun roomCloseDrainsQueuedWritesRejectsStaleMutationsAndReopensIndependently() = runBlocking { val root = Files.createTempDirectory("yokan-profile-retire").toFile() try { val db = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A)) (1L..100L).forEach { db.upsertManga(DbManga(id = it, privateNote = "A $it")) } db.close(); db.close() val before = db.snapshot() assertFailsWith { db.upsertManga(DbManga(id = 42, privateNote = "Stale")) } assertEquals(before, db.snapshot()) assertFailsWith { db.updateSettings(db.settings()) } assertFailsWith { db.batch { db.removeManga(42) } } assertFailsWith { db.awaitPersistence() } val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A)) try { assertEquals(100, reopened.mangas().size); assertEquals("A 42", reopened.manga(42)?.privateNote) } finally { reopened.close() } val b = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, B)) try { assertTrue(b.mangas().isEmpty()) } finally { b.close() } } finally { root.deleteRecursively() } } @Test fun busyRoomCloseTimesOutWithoutDroppingWritesAndCanBeRetried() = runBlocking { val root = Files.createTempDirectory("yokan-profile-busy").toFile() val room = createDesktopProfileRoomDatabase(root, A) val db = RoomYokanDatabase(room, closeTimeoutMillis = 200) try { db.awaitPersistence() val lock = BundledSQLiteDriver().open(java.io.File(root, ProfileStorageNamespace(A).databaseRelativePath).path) var transactionStarted = false try { // Room's empty flush barrier can still be finishing its transaction. // Wait for that brief contention before deliberately holding the write lock. lock.execSQL("PRAGMA busy_timeout = 5000") lock.execSQL("BEGIN IMMEDIATE") transactionStarted = true db.upsertManga(DbManga(id = 42, privateNote = "Queued")) assertFailsWith { db.close() } // The failed close has not released Room or discarded its queue. db.upsertManga(DbManga(id = 43, privateNote = "Retry")) } finally { try { if (transactionStarted) lock.execSQL("ROLLBACK") } finally { lock.close() } } db.awaitPersistence(); db.close() val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A)) try { assertEquals("Queued", reopened.manga(42)?.privateNote); assertEquals("Retry", reopened.manga(43)?.privateNote) } finally { reopened.close() } } finally { room.close(); root.deleteRecursively() } } @Test fun defaultServiceGraphSharesSessionScopeAndRetiresActualRoomAndObservers() = runBlocking { val root = Files.createTempDirectory("yokan-default-session").toFile() try { val owner = ProfileSession(ProfileId.Default, databaseFactory = { RoomYokanDatabase(createDesktopProfileRoomDatabase(root, it)) }, filesFactory = { createDesktopProfileFileService(root, it) }, archivesFactory = { JvmLocalArchiveService(createDesktopProfileFileService(root, it).cacheRoot) }, notificationsFactory = { SilentNotifications }, ) val db = owner.database val capturedHttp = owner.services.http val capturedTogether = owner.together val capturedReaderContent = owner.readerContent val capturedSpeech = owner.services.textToSpeech val capturedSpeechReader = capturedSpeech.reader() val capturedPlayerServices = owner.playerServices val capturedPlayerReader = capturedPlayerServices.reader() assertEquals(ProfileId.Default, capturedPlayerServices.profileId) assertSame(capturedReaderContent, owner.readerContent) assertEquals(ProfileId.Default, capturedReaderContent.profileId) assertEquals("Inline chapter", capturedReaderContent.novelText(null, "Novel", "Inline chapter")) assertSame(owner.scope, owner.services.scope) assertSame(db, owner.services.database) owner.settings; owner.libraryIndex; owner.migration; owner.chapterPages db.upsertManga(DbManga(id = 42, privateNote = "Default")) owner.close() assertEquals(ProfileSessionStatus.Closed, owner.status.value) assertEquals(false, capturedSpeech.isAvailable) assertEquals(false, capturedPlayerServices.isAvailable) assertFailsWith { capturedPlayerReader.configuration(eu.friedcutlet.yokan.database.DbSettings()) } assertFailsWith { capturedPlayerReader.streamProxy.proxyUrl("https://retired.test/video", mapOf("Referer" to "retired")) } assertFailsWith { capturedSpeech.voices(null) } assertFailsWith { capturedSpeechReader.speak("Retired chapter", eu.friedcutlet.yokan.services.tts.TextToSpeechRequest()) { _, _ -> error("Retired owner reported speech progress") } } assertEquals(null, capturedTogether.hubSession()) assertEquals(null, capturedTogether.client.value) assertFailsWith { owner.repository } assertFailsWith { capturedReaderContent.novelText(null, "Novel", "Retired chapter") } // Stale UI/extension references must fail before settings/cookies or the closed engine. assertFailsWith { capturedHttp.request(eu.friedcutlet.yokan.services.http.HttpRequest("https://source.test/")) } assertFailsWith { capturedHttp.stream(eu.friedcutlet.yokan.services.http.HttpRequest("https://source.test/")) { error("Retired owner wrote bytes") } } val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, ProfileId.Default)) try { assertEquals("Default", reopened.manga(42)?.privateNote) } finally { reopened.close() } } finally { root.deleteRecursively() } } @Test fun staleLoggingOwnerCannotDetachNewTargetEvenWhenBothUseSameFileService() { val root = Files.createTempDirectory("yokan-log-owner").toFile() try { val files = createDesktopProfileFileService(root, ProfileId.Default) val old = LogSink.attach(files) { false }; val current = LogSink.attach(files) { false } LogSink.detach(old) assertEquals("${files.cacheRoot}/logs/yokan.log", LogSink.logFilePath()) LogSink.detach(current); assertEquals(null, LogSink.logFilePath()) } finally { root.deleteRecursively() } } private object SilentNotifications : NotificationService { override fun supported() = false override fun notify(payload: NotificationPayload) = Unit override fun cancel(channel: NotificationChannel, tag: String?) = Unit } companion object { val A = ProfileId("p_${"a".repeat(32)}"); val B = ProfileId("p_${"b".repeat(32)}") } }