@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob 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.assertFalse import kotlin.test.assertFailsWith import kotlin.test.assertNotEquals import kotlin.test.assertNull import kotlin.test.assertSame import kotlin.test.assertTrue class ProfileDownloadBindingsTest { @Test fun alreadyExpiredCallerCannotDispatchIntoALiveDownloadOwner() = runTest { val registry = ProfileDownloadBindings(); val parent = SupervisorJob() val binding = registry.install(A, FakeDownloads(), CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler))) var effects = 0 val caller = launch { currentCoroutineContext().cancel() assertFailsWith { binding.run { effects++ } } } caller.join() assertEquals(0, effects); assertTrue(binding.isActive) assertSame(binding, registry.resolve(A.value, binding.token)) parent.cancelAndJoin() } @Test fun cancelActionsReachOnlyTheirRecordedLiveOwner() = runTest { val registry = ProfileDownloadBindings() val a = FakeDownloads(); val b = FakeDownloads() val parentA = SupervisorJob(); val parentB = SupervisorJob() val scopeA = CoroutineScope(parentA + StandardTestDispatcher(testScheduler)) val scopeB = CoroutineScope(parentB + StandardTestDispatcher(testScheduler)) val left = registry.install(A, a, scopeA); val right = registry.install(B, b, scopeB) registry.resolve(A.value, left.token)?.cancelAll(); testScheduler.runCurrent() assertEquals(1, a.cancels); assertEquals(0, b.cancels) assertNull(registry.resolve(B.value, left.token)); assertNull(registry.resolve(A.value, right.token)) parentA.cancelAndJoin() assertNull(registry.resolve(A.value, left.token)); assertSame(right, registry.resolve(B.value, right.token)) right.cancelAll(); testScheduler.runCurrent(); assertEquals(1, b.cancels) parentB.cancelAndJoin() } @Test fun oldActionsAndCleanupCannotAffectAReplacementSessionForTheSameProfile() = runTest { val registry = ProfileDownloadBindings() val parentOld = SupervisorJob(); val parentNew = SupervisorJob() val oldDownloads = FakeDownloads(); val newDownloads = FakeDownloads() val old = registry.install(A, oldDownloads, CoroutineScope(parentOld + StandardTestDispatcher(testScheduler))) val entered = CompletableDeferred(); val release = CompletableDeferred() val mirror = launch { old.run { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } } entered.await() val next = registry.install(A, newDownloads, CoroutineScope(parentNew + StandardTestDispatcher(testScheduler))) assertNotEquals(old.token, next.token); assertNotEquals(old.actionIdentity, next.actionIdentity) assertNull(registry.resolve(A.value, old.token)); assertSame(next, registry.resolve(A.value, next.token)) old.cancelAll(); testScheduler.runCurrent() assertEquals(0, oldDownloads.cancels); assertEquals(0, newDownloads.cancels) release.complete(Unit); mirror.join(); parentOld.cancelAndJoin() assertSame(next, registry.resolve(A.value, next.token)) next.cancelAll(); testScheduler.runCurrent(); assertEquals(1, newDownloads.cancels) parentNew.cancelAndJoin() } @Test fun expiredServiceMirrorJoinsCleanupWithoutCancelingTheDownloadOwner() = runTest { val registry = ProfileDownloadBindings(); val parent = SupervisorJob() val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val binding = registry.install(A, FakeDownloads(), scope) val downloading = scope.launch { awaitCancellation() } val entered = CompletableDeferred(); val release = CompletableDeferred() var finalized = false val mirror = launch { binding.run { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } } } entered.await(); mirror.cancel(); testScheduler.runCurrent() assertFalse(mirror.isCompleted); assertFalse(finalized); assertTrue(downloading.isActive) release.complete(Unit); mirror.join() assertTrue(finalized); assertTrue(downloading.isActive); assertTrue(binding.isActive) assertSame(binding, registry.resolve(A.value, binding.token)) parent.cancelAndJoin() } @Test fun ownerRetirementRejectsActionsImmediatelyAndJoinsMirrorFinalizers() = runTest { val registry = ProfileDownloadBindings(); val parent = SupervisorJob() val downloads = FakeDownloads() val binding = registry.install(A, downloads, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) val entered = CompletableDeferred(); val release = CompletableDeferred() var finalized = false val mirror = launch { binding.run { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } } } entered.await(); parent.cancel(); testScheduler.runCurrent() assertNull(registry.resolve(A.value, binding.token)); assertFalse(parent.isCompleted) binding.cancelAll(); testScheduler.runCurrent(); assertEquals(0, downloads.cancels) release.complete(Unit); parent.join(); mirror.join() assertTrue(finalized); assertTrue(parent.isCompleted) assertEquals(ProfileWorkResult.Skipped, binding.run { error("Retired work") }) } @Test fun retirementBeforeDispatchNeverRunsAQueuedCancelAction() = runTest { val registry = ProfileDownloadBindings(); val parent = SupervisorJob(); val downloads = FakeDownloads() val binding = registry.install(A, downloads, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) binding.cancelAll(); parent.cancelAndJoin() assertEquals(0, downloads.cancels); assertNull(registry.resolve(A.value, binding.token)) } @Test fun missingMalformedAndUnknownActionsNeverBootstrapOrFallBack() = runTest { val registry = ProfileDownloadBindings(); val parent = SupervisorJob() val binding = registry.install(ProfileId.Default, FakeDownloads(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) for (owner in listOf(null, "", "../default", A.value)) assertNull(registry.resolve(owner, binding.token)) assertNull(registry.resolve("default", null)); assertNull(registry.resolve("default", "old")) assertSame(binding, registry.resolve("default", binding.token)) parent.cancelAndJoin() } @Test fun retiredInstallationCannotDisplaceALiveCapability() = runTest { val registry = ProfileDownloadBindings(); val parent = SupervisorJob(); val retired = SupervisorJob() val binding = registry.install(A, FakeDownloads(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) retired.cancelAndJoin() assertFailsWith { registry.install(A, FakeDownloads(), CoroutineScope(retired + StandardTestDispatcher(testScheduler))) } assertSame(binding, registry.resolve(A.value, binding.token)) parent.cancelAndJoin() } @Test fun resumeNamesAndActionIdentitiesPartitionIdenticalChapterQueues() = runTest { val registry = ProfileDownloadBindings(); val parent = SupervisorJob() val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val ids = listOf(ProfileId.Default, A, B) val names = ids.map { ProfileWorkNamespace(it).uniqueName("yokan.download_resume") } val bindings = ids.map { registry.install(it, FakeDownloads(), scope) } assertEquals("yokan.download_resume", names.first()); assertEquals(3, names.distinct().size) assertEquals(3, bindings.map { it.actionIdentity }.distinct().size) parent.cancelAndJoin() } private class FakeDownloads : DownloadService { var cancels = 0 override suspend fun initialize(poolSize: Int) = Unit override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit override fun cancel(taskId: String) = Unit override fun cancelAll() { cancels++ } override fun pause(taskId: String) = Unit override fun resume(taskId: String) = Unit override fun retry(taskId: String) = false override fun storageLocation(taskId: String): String? = null override fun deleteArtifacts(taskId: String) = Unit override fun activeDownloads(): List = emptyList() } private companion object { val A = ProfileId("p_" + "a".repeat(32)) val B = ProfileId("p_" + "b".repeat(32)) } }