ProfileBackgroundWorkTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileBackgroundWorkTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)23package eu.friedcutlet.yokan.app.profiles45import eu.friedcutlet.yokan.database.DbManga6import eu.friedcutlet.yokan.database.InMemoryYokanDatabase7import eu.friedcutlet.yokan.database.YokanDatabase8import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskOutcome9import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskStatus10import eu.friedcutlet.yokan.services.scheduling.shouldRetry11import kotlinx.coroutines.CancellationException12import kotlinx.coroutines.CompletableDeferred13import kotlinx.coroutines.NonCancellable14import kotlinx.coroutines.async15import kotlinx.coroutines.awaitCancellation16import kotlinx.coroutines.cancelAndJoin17import kotlinx.coroutines.cancel18import kotlinx.coroutines.currentCoroutineContext19import kotlinx.coroutines.launch20import kotlinx.coroutines.test.StandardTestDispatcher21import kotlinx.coroutines.test.UnconfinedTestDispatcher22import kotlinx.coroutines.test.runTest23import kotlinx.coroutines.withContext24import kotlin.test.Test25import kotlin.test.assertEquals26import kotlin.test.assertFailsWith27import kotlin.test.assertFalse28import kotlin.test.assertTrue29import eu.friedcutlet.yokan.domain.ProfileId30import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult31import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace3233class ProfileBackgroundWorkTest {34 @Test fun alreadyExpiredCallerCannotDispatchIntoALiveSession() = runTest {35 val owner = ProfileSession(A, dispatcher = UnconfinedTestDispatcher(testScheduler))36 var effects = 037 val caller = launch {38 currentCoroutineContext().cancel()39 assertFailsWith<CancellationException> { owner.runBackgroundWork { effects++ } }40 }41 caller.join()42 assertEquals(0, effects); assertEquals(ProfileSessionStatus.Open, owner.status.value)43 assertEquals(ProfileWorkResult.Completed("Still usable"), owner.runBackgroundWork { "Still usable" })44 owner.close()45 }4647 @Test fun delayedWorkUsesRecordedOwnerAfterRenameAndActiveProfileChange() = runTest {48 val registry = ProfileRegistry(MemoryStore())49 registry.beginCreate("A", A); registry.markReady(A)50 registry.beginCreate("B", B); registry.markReady(B)51 registry.rename(A, "Renamed A"); registry.recordActive(B)52 val a = InMemoryYokanDatabase(); val b = InMemoryYokanDatabase()53 val owners = mapOf(54 A to ProfileSession(A, databaseFactory = { a }, dispatcher = StandardTestDispatcher(testScheduler)),55 B to ProfileSession(B, databaseFactory = { b }, dispatcher = StandardTestDispatcher(testScheduler)),56 )57 val routing = openingWork(registry, { true }) { owners.getValue(it) }58 assertEquals(ProfileWorkResult.Completed(A), routing.run(A.value) {59 it.database.upsertManga(DbManga(id = 42, privateNote = "A's progress")); it.id60 })61 assertEquals("A's progress", a.manga(42)?.privateNote)62 assertEquals(null, b.manga(42))63 assertEquals(B, registry.refresh().lastActive)64 owners.values.forEach { it.close() }65 }6667 @Test fun freshRegistryRejectsUnknownProvisioningDeletingAndRetiredWithoutOpeningStorage() = runTest {68 val store = MemoryStore(); val registry = ProfileRegistry(store)69 var opens = 070 val routing = openingWork(registry, { true }) { opens++; error("Must not open") }71 suspend fun rejected() = assertEquals(ProfileWorkResult.Skipped, routing.run(A.value) { error("Must not execute") })72 rejected()73 registry.beginCreate("A", A); rejected()74 registry.markReady(A)75 // Mutate through another instance: admission must refresh rather than trust its cached Ready state.76 val other = ProfileRegistry(store)77 other.beginDelete(A); rejected()78 other.finishDelete(A); rejected()79 assertEquals(0, opens)80 assertEquals(listOf(A), registry.refresh().retiredIds)81 }8283 @Test fun malformedExplicitIdsNeverBecomeDefaultAndLegacyAdoptionIsOptIn() = runTest {84 val registry = ProfileRegistry(MemoryStore())85 val owner = ProfileSession(ProfileId.Default, dispatcher = StandardTestDispatcher(testScheduler))86 var opens = 087 val routing = openingWork(registry, { true }) { opens++; assertEquals(ProfileId.Default, it); owner }88 for (raw in listOf("", "../default", "DEFAULT", "p_123", "default ")) {89 assertEquals(ProfileWorkResult.Skipped, routing.run(raw, allowLegacyDefault = true) { error("Invalid owner") })90 }91 assertEquals(ProfileWorkResult.Skipped, routing.run(null) { error("No recorded owner") })92 assertEquals(0, opens)93 assertEquals(ProfileWorkResult.Completed(ProfileId.Default), routing.run(null, allowLegacyDefault = true) { it.id })94 assertEquals(ProfileWorkResult.Completed(ProfileId.Default), routing.run("default") { it.id })95 assertEquals(2, opens)96 owner.close()97 }9899 @Test fun unsupportedReadyOwnerIsSkippedWithoutFallingBackToDefault() = runTest {100 val registry = ProfileRegistry(MemoryStore())101 registry.beginCreate("A", A); registry.markReady(A)102 val routing = openingWork(registry, { it == ProfileId.Default }) { error("Unsupported owner opened") }103 assertEquals(ProfileWorkResult.Skipped, routing.run(A.value) { error("Unsupported owner executed") })104 }105106 @Test fun unavailableRegistryRetriesWithoutOpeningOrOverwritingMetadata() = runTest {107 for (raw in listOf("{broken", "{\"version\":999}")) {108 val store = MemoryStore(raw)109 val routing = openingWork(ProfileRegistry(store), { true }) { error("Unreadable metadata opened storage") }110 assertEquals(ProfileWorkResult.Retry, routing.run("default") { error("Must not execute") })111 assertEquals(raw, store.raw)112 }113 val store = object : ProfileRegistryPersistence {114 override suspend fun read(): String? = throw IllegalStateException("Disk unavailable")115 override suspend fun compareAndSet(expected: String?, replacement: String) = error("Must not write")116 }117 val routing = openingWork(ProfileRegistry(store), { true }) { error("Must not open") }118 assertEquals(ProfileWorkResult.Retry, routing.run("default") { error("Must not execute") })119 }120121 @Test fun cancellationDuringAdmissionPropagatesRatherThanRetrying() = runTest {122 val store = object : ProfileRegistryPersistence {123 override suspend fun read(): String? = throw CancellationException("Expired worker")124 override suspend fun compareAndSet(expected: String?, replacement: String) = error("Must not write")125 }126 val routing = openingWork(ProfileRegistry(store), { true }) { error("Must not open") }127 assertFailsWith<CancellationException> { routing.run("default") { error("Must not execute") } }128 }129130 @Test fun providerCannotRouteWorkToAnotherProfile() = runTest {131 val registry = ProfileRegistry(MemoryStore())132 registry.beginCreate("A", A); registry.markReady(A)133 val wrong = ProfileSession(ProfileId.Default, dispatcher = StandardTestDispatcher(testScheduler))134 val routing = openingWork(registry, { true }) { wrong }135 assertFailsWith<IllegalStateException> { routing.run(A.value) { error("Wrong profile executed") } }136 wrong.close()137 }138139 @Test fun callerExpiryCancelsAndJoinsItsWorkWhileSiblingSessionWorkSurvives() = runTest {140 val owner = ProfileSession(A, dispatcher = StandardTestDispatcher(testScheduler))141 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()142 var finalized = false143 val sibling = owner.scope.launch { awaitCancellation() }144 val caller = launch {145 owner.runBackgroundWork {146 try { entered.complete(Unit); awaitCancellation() }147 finally { withContext(NonCancellable) { release.await(); finalized = true } }148 }149 }150 entered.await(); caller.cancel(); testScheduler.runCurrent()151 assertFalse(caller.isCompleted); assertFalse(finalized); assertTrue(sibling.isActive)152 release.complete(Unit); caller.join()153 assertTrue(finalized); assertTrue(sibling.isActive)154 assertEquals(ProfileWorkResult.Completed("Next job"), owner.runBackgroundWork { "Next job" })155 owner.close()156 }157158 @Test fun retirementJoinsBackgroundFinalProgressBeforeDatabaseCloseAndRejectsLateWork() = runTest {159 val db = ClosingDatabase()160 val owner = ProfileSession(A, databaseFactory = { db }, dispatcher = StandardTestDispatcher(testScheduler))161 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()162 val caller = async {163 owner.runBackgroundWork {164 val captured = it.database165 try { entered.complete(Unit); awaitCancellation() }166 finally { withContext(NonCancellable) { release.await(); captured.upsertManga(DbManga(id = 42, privateNote = "Final")) } }167 }168 }169 entered.await()170 val closing = launch { owner.close() }; testScheduler.runCurrent()171 assertFalse(db.closed); assertFalse(closing.isCompleted)172 assertEquals(ProfileWorkResult.Skipped, owner.runBackgroundWork { error("Late work") })173 release.complete(Unit); closing.join()174 assertFailsWith<CancellationException> { caller.await() }175 assertTrue(db.closed); assertEquals("Final", db.noteAtClose)176 assertEquals(ProfileWorkResult.Skipped, owner.runBackgroundWork { error("Closed work") })177 }178179 @Test fun workFailureDoesNotRetireOwnerOrCancelSiblingJobs() = runTest {180 val owner = ProfileSession(A, dispatcher = StandardTestDispatcher(testScheduler))181 val sibling = owner.scope.launch { awaitCancellation() }182 assertFailsWith<IllegalStateException> { owner.runBackgroundWork { error("Task failed") } }183 assertTrue(sibling.isActive)184 assertEquals(ProfileSessionStatus.Open, owner.status.value)185 assertEquals(ProfileWorkResult.Completed(42), owner.runBackgroundWork { 42 })186 sibling.cancelAndJoin(); owner.close()187 }188189 @Test fun workNamesPreserveDefaultAndPartitionScheduleCancellationByStableId() {190 for (name in listOf("yokan.metadata_refresh", "yokan.library_update", "yokan.auto_sync", "yokan.auto_backup")) {191 val names = listOf(ProfileId.Default, A, B).map { ProfileWorkNamespace(it).uniqueName(name) }192 assertEquals(name, names.first()); assertEquals(3, names.distinct().size)193 assertEquals("$name.${A.value}", names[1])194 }195 }196197 @Test fun onlyRecoverableAdmissionAndTaskFailuresRetry() {198 assertFalse((ProfileWorkResult.Skipped as ProfileWorkResult<PeriodicTaskOutcome>).shouldRetry)199 assertTrue((ProfileWorkResult.Retry as ProfileWorkResult<PeriodicTaskOutcome>).shouldRetry)200 assertFalse(ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Completed, "Done")).shouldRetry)201 assertTrue(ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Failed, "Retry")).shouldRetry)202 }203204 /** Routes work into whatever session [openSession] returns, checking it is the requested owner. */205 private fun openingWork(206 registry: ProfileRegistry,207 supported: (ProfileId) -> Boolean,208 openSession: suspend (ProfileId) -> ProfileSession,209 ) = ProfileBackgroundWork(registry, supported, object : ProfileWorkSessions {210 override suspend fun <T> run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult<T> {211 val session = openSession(id)212 check(session.id == id) { "Background work opened a different profile" }213 return session.runBackgroundWork(action)214 }215 })216217 private class MemoryStore(var raw: String? = null) : ProfileRegistryPersistence {218 override suspend fun read() = raw219 override suspend fun compareAndSet(expected: String?, replacement: String): Boolean {220 if (raw != expected) return false221 raw = replacement; return true222 }223 }224225 private class ClosingDatabase(private val delegate: InMemoryYokanDatabase = InMemoryYokanDatabase()) : YokanDatabase by delegate {226 var closed = false227 var noteAtClose: String? = null228 override suspend fun close() { noteAtClose = delegate.manga(42)?.privateNote; closed = true }229 }230231 private companion object {232 val A = ProfileId("p_" + "a".repeat(32))233 val B = ProfileId("p_" + "b".repeat(32))234 }235}236