@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.app.profiles import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskOutcome import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskStatus import eu.friedcutlet.yokan.services.scheduling.shouldRetry import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.cancel import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace class ProfileBackgroundWorkTest { @Test fun alreadyExpiredCallerCannotDispatchIntoALiveSession() = runTest { val owner = ProfileSession(A, dispatcher = UnconfinedTestDispatcher(testScheduler)) var effects = 0 val caller = launch { currentCoroutineContext().cancel() assertFailsWith { owner.runBackgroundWork { effects++ } } } caller.join() assertEquals(0, effects); assertEquals(ProfileSessionStatus.Open, owner.status.value) assertEquals(ProfileWorkResult.Completed("Still usable"), owner.runBackgroundWork { "Still usable" }) owner.close() } @Test fun delayedWorkUsesRecordedOwnerAfterRenameAndActiveProfileChange() = runTest { val registry = ProfileRegistry(MemoryStore()) registry.beginCreate("A", A); registry.markReady(A) registry.beginCreate("B", B); registry.markReady(B) registry.rename(A, "Renamed A"); registry.recordActive(B) val a = InMemoryYokanDatabase(); val b = InMemoryYokanDatabase() val owners = mapOf( A to ProfileSession(A, databaseFactory = { a }, dispatcher = StandardTestDispatcher(testScheduler)), B to ProfileSession(B, databaseFactory = { b }, dispatcher = StandardTestDispatcher(testScheduler)), ) val routing = openingWork(registry, { true }) { owners.getValue(it) } assertEquals(ProfileWorkResult.Completed(A), routing.run(A.value) { it.database.upsertManga(DbManga(id = 42, privateNote = "A's progress")); it.id }) assertEquals("A's progress", a.manga(42)?.privateNote) assertEquals(null, b.manga(42)) assertEquals(B, registry.refresh().lastActive) owners.values.forEach { it.close() } } @Test fun freshRegistryRejectsUnknownProvisioningDeletingAndRetiredWithoutOpeningStorage() = runTest { val store = MemoryStore(); val registry = ProfileRegistry(store) var opens = 0 val routing = openingWork(registry, { true }) { opens++; error("Must not open") } suspend fun rejected() = assertEquals(ProfileWorkResult.Skipped, routing.run(A.value) { error("Must not execute") }) rejected() registry.beginCreate("A", A); rejected() registry.markReady(A) // Mutate through another instance: admission must refresh rather than trust its cached Ready state. val other = ProfileRegistry(store) other.beginDelete(A); rejected() other.finishDelete(A); rejected() assertEquals(0, opens) assertEquals(listOf(A), registry.refresh().retiredIds) } @Test fun malformedExplicitIdsNeverBecomeDefaultAndLegacyAdoptionIsOptIn() = runTest { val registry = ProfileRegistry(MemoryStore()) val owner = ProfileSession(ProfileId.Default, dispatcher = StandardTestDispatcher(testScheduler)) var opens = 0 val routing = openingWork(registry, { true }) { opens++; assertEquals(ProfileId.Default, it); owner } for (raw in listOf("", "../default", "DEFAULT", "p_123", "default ")) { assertEquals(ProfileWorkResult.Skipped, routing.run(raw, allowLegacyDefault = true) { error("Invalid owner") }) } assertEquals(ProfileWorkResult.Skipped, routing.run(null) { error("No recorded owner") }) assertEquals(0, opens) assertEquals(ProfileWorkResult.Completed(ProfileId.Default), routing.run(null, allowLegacyDefault = true) { it.id }) assertEquals(ProfileWorkResult.Completed(ProfileId.Default), routing.run("default") { it.id }) assertEquals(2, opens) owner.close() } @Test fun unsupportedReadyOwnerIsSkippedWithoutFallingBackToDefault() = runTest { val registry = ProfileRegistry(MemoryStore()) registry.beginCreate("A", A); registry.markReady(A) val routing = openingWork(registry, { it == ProfileId.Default }) { error("Unsupported owner opened") } assertEquals(ProfileWorkResult.Skipped, routing.run(A.value) { error("Unsupported owner executed") }) } @Test fun unavailableRegistryRetriesWithoutOpeningOrOverwritingMetadata() = runTest { for (raw in listOf("{broken", "{\"version\":999}")) { val store = MemoryStore(raw) val routing = openingWork(ProfileRegistry(store), { true }) { error("Unreadable metadata opened storage") } assertEquals(ProfileWorkResult.Retry, routing.run("default") { error("Must not execute") }) assertEquals(raw, store.raw) } val store = object : ProfileRegistryPersistence { override suspend fun read(): String? = throw IllegalStateException("Disk unavailable") override suspend fun compareAndSet(expected: String?, replacement: String) = error("Must not write") } val routing = openingWork(ProfileRegistry(store), { true }) { error("Must not open") } assertEquals(ProfileWorkResult.Retry, routing.run("default") { error("Must not execute") }) } @Test fun cancellationDuringAdmissionPropagatesRatherThanRetrying() = runTest { val store = object : ProfileRegistryPersistence { override suspend fun read(): String? = throw CancellationException("Expired worker") override suspend fun compareAndSet(expected: String?, replacement: String) = error("Must not write") } val routing = openingWork(ProfileRegistry(store), { true }) { error("Must not open") } assertFailsWith { routing.run("default") { error("Must not execute") } } } @Test fun providerCannotRouteWorkToAnotherProfile() = runTest { val registry = ProfileRegistry(MemoryStore()) registry.beginCreate("A", A); registry.markReady(A) val wrong = ProfileSession(ProfileId.Default, dispatcher = StandardTestDispatcher(testScheduler)) val routing = openingWork(registry, { true }) { wrong } assertFailsWith { routing.run(A.value) { error("Wrong profile executed") } } wrong.close() } @Test fun callerExpiryCancelsAndJoinsItsWorkWhileSiblingSessionWorkSurvives() = runTest { val owner = ProfileSession(A, dispatcher = StandardTestDispatcher(testScheduler)) val entered = CompletableDeferred(); val release = CompletableDeferred() var finalized = false val sibling = owner.scope.launch { awaitCancellation() } val caller = launch { owner.runBackgroundWork { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } } } entered.await(); caller.cancel(); testScheduler.runCurrent() assertFalse(caller.isCompleted); assertFalse(finalized); assertTrue(sibling.isActive) release.complete(Unit); caller.join() assertTrue(finalized); assertTrue(sibling.isActive) assertEquals(ProfileWorkResult.Completed("Next job"), owner.runBackgroundWork { "Next job" }) owner.close() } @Test fun retirementJoinsBackgroundFinalProgressBeforeDatabaseCloseAndRejectsLateWork() = runTest { val db = ClosingDatabase() val owner = ProfileSession(A, databaseFactory = { db }, dispatcher = StandardTestDispatcher(testScheduler)) val entered = CompletableDeferred(); val release = CompletableDeferred() val caller = async { owner.runBackgroundWork { val captured = it.database try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); captured.upsertManga(DbManga(id = 42, privateNote = "Final")) } } } } entered.await() val closing = launch { owner.close() }; testScheduler.runCurrent() assertFalse(db.closed); assertFalse(closing.isCompleted) assertEquals(ProfileWorkResult.Skipped, owner.runBackgroundWork { error("Late work") }) release.complete(Unit); closing.join() assertFailsWith { caller.await() } assertTrue(db.closed); assertEquals("Final", db.noteAtClose) assertEquals(ProfileWorkResult.Skipped, owner.runBackgroundWork { error("Closed work") }) } @Test fun workFailureDoesNotRetireOwnerOrCancelSiblingJobs() = runTest { val owner = ProfileSession(A, dispatcher = StandardTestDispatcher(testScheduler)) val sibling = owner.scope.launch { awaitCancellation() } assertFailsWith { owner.runBackgroundWork { error("Task failed") } } assertTrue(sibling.isActive) assertEquals(ProfileSessionStatus.Open, owner.status.value) assertEquals(ProfileWorkResult.Completed(42), owner.runBackgroundWork { 42 }) sibling.cancelAndJoin(); owner.close() } @Test fun workNamesPreserveDefaultAndPartitionScheduleCancellationByStableId() { for (name in listOf("yokan.metadata_refresh", "yokan.library_update", "yokan.auto_sync", "yokan.auto_backup")) { val names = listOf(ProfileId.Default, A, B).map { ProfileWorkNamespace(it).uniqueName(name) } assertEquals(name, names.first()); assertEquals(3, names.distinct().size) assertEquals("$name.${A.value}", names[1]) } } @Test fun onlyRecoverableAdmissionAndTaskFailuresRetry() { assertFalse((ProfileWorkResult.Skipped as ProfileWorkResult).shouldRetry) assertTrue((ProfileWorkResult.Retry as ProfileWorkResult).shouldRetry) assertFalse(ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Completed, "Done")).shouldRetry) assertTrue(ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Failed, "Retry")).shouldRetry) } /** Routes work into whatever session [openSession] returns, checking it is the requested owner. */ private fun openingWork( registry: ProfileRegistry, supported: (ProfileId) -> Boolean, openSession: suspend (ProfileId) -> ProfileSession, ) = ProfileBackgroundWork(registry, supported, object : ProfileWorkSessions { override suspend fun run(id: ProfileId, action: suspend (ProfileSession) -> T): ProfileWorkResult { val session = openSession(id) check(session.id == id) { "Background work opened a different profile" } return session.runBackgroundWork(action) } }) private class MemoryStore(var raw: String? = null) : ProfileRegistryPersistence { override suspend fun read() = raw override suspend fun compareAndSet(expected: String?, replacement: String): Boolean { if (raw != expected) return false raw = replacement; return true } } private class ClosingDatabase(private val delegate: InMemoryYokanDatabase = InMemoryYokanDatabase()) : YokanDatabase by delegate { var closed = false var noteAtClose: String? = null override suspend fun close() { noteAtClose = delegate.manga(42)?.privateNote; closed = true } } private companion object { val A = ProfileId("p_" + "a".repeat(32)) val B = ProfileId("p_" + "b".repeat(32)) } }