ProfileSessionRoomTest.kt
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileSessionRoomTest.kt
1package eu.friedcutlet.yokan.app.profiles23import androidx.sqlite.driver.bundled.BundledSQLiteDriver4import androidx.sqlite.execSQL5import eu.friedcutlet.yokan.database.DbManga6import eu.friedcutlet.yokan.database.room.RoomYokanDatabase7import eu.friedcutlet.yokan.database.room.createDesktopProfileRoomDatabase8import eu.friedcutlet.yokan.services.files.createDesktopProfileFileService9import eu.friedcutlet.yokan.services.files.JvmLocalArchiveService10import eu.friedcutlet.yokan.services.notifications.NotificationService11import eu.friedcutlet.yokan.services.notifications.NotificationPayload12import eu.friedcutlet.yokan.services.notifications.NotificationChannel13import eu.friedcutlet.yokan.services.logging.LogSink14import java.nio.file.Files15import kotlinx.coroutines.runBlocking16import kotlinx.coroutines.TimeoutCancellationException17import kotlin.test.Test18import kotlin.test.assertEquals19import kotlin.test.assertFailsWith20import kotlin.test.assertSame21import kotlin.test.assertTrue22import eu.friedcutlet.yokan.domain.ProfileId23import eu.friedcutlet.yokan.domain.ProfileStorageNamespace2425class ProfileSessionRoomTest {26 @Test fun roomCloseDrainsQueuedWritesRejectsStaleMutationsAndReopensIndependently() = runBlocking {27 val root = Files.createTempDirectory("yokan-profile-retire").toFile()28 try {29 val db = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A))30 (1L..100L).forEach { db.upsertManga(DbManga(id = it, privateNote = "A $it")) }31 db.close(); db.close()32 val before = db.snapshot()33 assertFailsWith<IllegalStateException> { db.upsertManga(DbManga(id = 42, privateNote = "Stale")) }34 assertEquals(before, db.snapshot())35 assertFailsWith<IllegalStateException> { db.updateSettings(db.settings()) }36 assertFailsWith<IllegalStateException> { db.batch { db.removeManga(42) } }37 assertFailsWith<IllegalStateException> { db.awaitPersistence() }38 val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A))39 try { assertEquals(100, reopened.mangas().size); assertEquals("A 42", reopened.manga(42)?.privateNote) }40 finally { reopened.close() }41 val b = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, B))42 try { assertTrue(b.mangas().isEmpty()) } finally { b.close() }43 } finally { root.deleteRecursively() }44 }4546 @Test fun busyRoomCloseTimesOutWithoutDroppingWritesAndCanBeRetried() = runBlocking {47 val root = Files.createTempDirectory("yokan-profile-busy").toFile()48 val room = createDesktopProfileRoomDatabase(root, A)49 val db = RoomYokanDatabase(room, closeTimeoutMillis = 200)50 try {51 db.awaitPersistence()52 val lock = BundledSQLiteDriver().open(java.io.File(root, ProfileStorageNamespace(A).databaseRelativePath).path)53 var transactionStarted = false54 try {55 // Room's empty flush barrier can still be finishing its transaction.56 // Wait for that brief contention before deliberately holding the write lock.57 lock.execSQL("PRAGMA busy_timeout = 5000")58 lock.execSQL("BEGIN IMMEDIATE")59 transactionStarted = true60 db.upsertManga(DbManga(id = 42, privateNote = "Queued"))61 assertFailsWith<TimeoutCancellationException> { db.close() }62 // The failed close has not released Room or discarded its queue.63 db.upsertManga(DbManga(id = 43, privateNote = "Retry"))64 } finally {65 try { if (transactionStarted) lock.execSQL("ROLLBACK") }66 finally { lock.close() }67 }68 db.awaitPersistence(); db.close()69 val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, A))70 try { assertEquals("Queued", reopened.manga(42)?.privateNote); assertEquals("Retry", reopened.manga(43)?.privateNote) }71 finally { reopened.close() }72 } finally { room.close(); root.deleteRecursively() }73 }7475 @Test fun defaultServiceGraphSharesSessionScopeAndRetiresActualRoomAndObservers() = runBlocking {76 val root = Files.createTempDirectory("yokan-default-session").toFile()77 try {78 val owner = ProfileSession(ProfileId.Default,79 databaseFactory = { RoomYokanDatabase(createDesktopProfileRoomDatabase(root, it)) },80 filesFactory = { createDesktopProfileFileService(root, it) },81 archivesFactory = { JvmLocalArchiveService(createDesktopProfileFileService(root, it).cacheRoot) },82 notificationsFactory = { SilentNotifications },83 )84 val db = owner.database85 val capturedHttp = owner.services.http86 val capturedTogether = owner.together87 val capturedReaderContent = owner.readerContent88 val capturedSpeech = owner.services.textToSpeech89 val capturedSpeechReader = capturedSpeech.reader()90 val capturedPlayerServices = owner.playerServices91 val capturedPlayerReader = capturedPlayerServices.reader()92 assertEquals(ProfileId.Default, capturedPlayerServices.profileId)93 assertSame(capturedReaderContent, owner.readerContent)94 assertEquals(ProfileId.Default, capturedReaderContent.profileId)95 assertEquals("Inline chapter", capturedReaderContent.novelText(null, "Novel", "Inline chapter"))96 assertSame(owner.scope, owner.services.scope)97 assertSame(db, owner.services.database)98 owner.settings; owner.libraryIndex; owner.migration; owner.chapterPages99 db.upsertManga(DbManga(id = 42, privateNote = "Default"))100 owner.close()101 assertEquals(ProfileSessionStatus.Closed, owner.status.value)102 assertEquals(false, capturedSpeech.isAvailable)103 assertEquals(false, capturedPlayerServices.isAvailable)104 assertFailsWith<kotlinx.coroutines.CancellationException> {105 capturedPlayerReader.configuration(eu.friedcutlet.yokan.database.DbSettings())106 }107 assertFailsWith<kotlinx.coroutines.CancellationException> {108 capturedPlayerReader.streamProxy.proxyUrl("https://retired.test/video", mapOf("Referer" to "retired"))109 }110 assertFailsWith<kotlinx.coroutines.CancellationException> { capturedSpeech.voices(null) }111 assertFailsWith<kotlinx.coroutines.CancellationException> {112 capturedSpeechReader.speak("Retired chapter", eu.friedcutlet.yokan.services.tts.TextToSpeechRequest()) { _, _ ->113 error("Retired owner reported speech progress")114 }115 }116 assertEquals(null, capturedTogether.hubSession())117 assertEquals(null, capturedTogether.client.value)118 assertFailsWith<IllegalStateException> { owner.repository }119 assertFailsWith<kotlinx.coroutines.CancellationException> {120 capturedReaderContent.novelText(null, "Novel", "Retired chapter")121 }122 // Stale UI/extension references must fail before settings/cookies or the closed engine.123 assertFailsWith<kotlinx.coroutines.CancellationException> {124 capturedHttp.request(eu.friedcutlet.yokan.services.http.HttpRequest("https://source.test/"))125 }126 assertFailsWith<kotlinx.coroutines.CancellationException> {127 capturedHttp.stream(eu.friedcutlet.yokan.services.http.HttpRequest("https://source.test/")) {128 error("Retired owner wrote bytes")129 }130 }131 val reopened = RoomYokanDatabase(createDesktopProfileRoomDatabase(root, ProfileId.Default))132 try { assertEquals("Default", reopened.manga(42)?.privateNote) } finally { reopened.close() }133 } finally { root.deleteRecursively() }134 }135136 @Test fun staleLoggingOwnerCannotDetachNewTargetEvenWhenBothUseSameFileService() {137 val root = Files.createTempDirectory("yokan-log-owner").toFile()138 try {139 val files = createDesktopProfileFileService(root, ProfileId.Default)140 val old = LogSink.attach(files) { false }; val current = LogSink.attach(files) { false }141 LogSink.detach(old)142 assertEquals("${files.cacheRoot}/logs/yokan.log", LogSink.logFilePath())143 LogSink.detach(current); assertEquals(null, LogSink.logFilePath())144 } finally { root.deleteRecursively() }145 }146147 private object SilentNotifications : NotificationService {148 override fun supported() = false149 override fun notify(payload: NotificationPayload) = Unit150 override fun cancel(channel: NotificationChannel, tag: String?) = Unit151 }152 companion object { val A = ProfileId("p_${"a".repeat(32)}"); val B = ProfileId("p_${"b".repeat(32)}") }153}154