@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.services.http.* import kotlinx.coroutines.* import kotlinx.coroutines.test.* import kotlinx.coroutines.flow.collect import kotlinx.serialization.json.* import kotlin.test.* class ExternalDownloadsTest { @Test fun oldServerReceiptsCannotDelayNewServerAdmissions() = runTest { val f = Fixture(this) for (id in 1L..6L) { f.db.upsertChapter(DbChapter(id = id, mangaId = 1, name = "Chapter $id")) f.service.enqueue(f.request.copy(chapterId = id)) } f.updatePrefs { it.copy(endpoint = "https://new-aria.example.org/jsonrpc", secret = "new-account") } f.service.enqueue(f.request) f.service.reconcile() assertEquals(1, f.server.adds) assertEquals(6, f.prefs().jobs.count { it.problem == RemoteDownloadProblem.ServerChanged }) assertEquals(listOf("token:new-account"), f.server.tokens) } @Test fun idleQueueDoesNotPollAndPersistedProgressDoesNotCreateATightRequestLoop() = runTest { val f = Fixture(this, polling = true) runCurrent() advanceTimeBy(10_000); runCurrent() assertTrue(f.server.methods.isEmpty()) backgroundScope.launch { f.service.jobs.collect {} } f.service.enqueue(f.request); runCurrent() assertEquals(1, f.server.adds) val afterAdmission = f.server.methods.size advanceTimeBy(1999); runCurrent() assertEquals(afterAdmission, f.server.methods.size) advanceTimeBy(1); runCurrent() assertEquals(afterAdmission + 1, f.server.methods.size) } @Test fun acceptedServerWorkDoesNotPollWhenQueueIsNotVisible() = runTest { val f = Fixture(this, polling = true) f.service.enqueue(f.request); runCurrent() assertEquals(1, f.server.methods.size) advanceTimeBy(20_000); runCurrent() assertEquals(1, f.server.methods.size) val watching = backgroundScope.launch { f.service.jobs.collect {} } runCurrent() assertEquals(2, f.server.methods.size) watching.cancelAndJoin() advanceTimeBy(20_000); runCurrent() assertEquals(2, f.server.methods.size) } @Test fun retiringOneProfileDoesNotAffectAnotherProfilesRemoteQueue() = runTest { val first = Fixture(this); val second = Fixture(this) first.updatePrefs { it.copy(secret = "profile-one") } second.updatePrefs { it.copy(secret = "profile-two") } first.service.enqueue(first.request); first.service.reconcile() second.service.enqueue(second.request); second.service.reconcile() assertNotEquals(first.job().accountBinding, second.job().accountBinding) assertNotEquals(first.job().files.single().gid, second.job().files.single().gid) first.owner.cancelAndJoin() assertFailsWith { first.service.reconcile() } second.server.states[second.job().files.single().gid] = "complete" second.service.reconcile() assertTrue(second.job().complete) assertTrue(first.server.tokens.all { it == "token:profile-one" }) assertTrue(second.server.tokens.all { it == "token:profile-two" }) } @Test fun admissionsAreDurableAndCompletionNeverCreatesLocalOfflineMarks() = runTest { val f = Fixture(this) f.server.onAdd = { gid -> assertTrue(f.durable.any { jobs -> jobs.any { job -> job.files.any { it.gid == gid && it.state == RemoteDownloadState.Submitting } } }) } assertTrue(f.service.enqueue(f.request)) val receipt = f.job() assertEquals(RemoteDownloadState.Pending, receipt.files.single().state) f.service.reconcile() assertEquals(RemoteDownloadState.Waiting, f.job().files.single().state) assertTrue(f.job().files.single().url.isBlank()) f.server.states[f.job().files.single().gid] = "complete" f.service.reconcile() assertTrue(f.job().complete) assertTrue(f.db.downloads().isEmpty()) assertEquals("", f.db.chapter(1)?.archivePath) assertEquals(1, f.server.adds) } @Test fun lostAdmissionReplyIsRecoveredByGidInsteadOfSubmittingAnotherTask() = runTest { val f = Fixture(this) f.server.loseAddReply = true f.service.enqueue(f.request) assertFails { f.service.reconcile() } assertEquals(RemoteDownloadState.Submitting, f.job().files.single().state) val encoded = DatabaseJson.encodeToString(DbSettings.serializer(), f.db.settings()) val restarted = InMemoryYokanDatabase(f.db.snapshot().copy(settings = DatabaseJson.decodeFromString(DbSettings.serializer(), encoded))) val recovered = f.newService(restarted) recovered.reconcile() val restored = restarted.settings().features.externalDownloads.jobs.single() assertEquals(RemoteDownloadState.Active, restored.files.single().state) assertEquals(1, f.server.adds) assertTrue(restored.files.single().headers.isEmpty()) } @Test fun unverifiedMissingTaskRequiresAttentionAndNeverBlindlyRetries() = runTest { val f = Fixture(this) f.server.rejectBeforeAdmission = true f.service.enqueue(f.request) assertFails { f.service.reconcile() } val recovered = f.newService() recovered.reconcile() assertEquals(RemoteDownloadState.Attention, f.job().files.single().state) assertEquals(RemoteDownloadProblem.MissingOrRejected, f.job().problem) assertFails { recovered.retry(f.job().id) } recovered.reconcile() assertEquals(1, f.server.adds) } @Test fun pauseResumeCancelAndRemovalOnlyTouchOwnedRemoteTasks() = runTest { val f = Fixture(this) f.service.enqueue(f.request); f.service.reconcile() val id = f.job().id val gid = f.job().files.single().gid f.server.states["1111111111111111"] = "active" f.service.setIntent(id, RemoteDownloadIntent.Pause); f.service.reconcile(id) assertEquals("paused", f.server.states[gid]) f.service.setIntent(id, RemoteDownloadIntent.Run); f.service.reconcile(id) assertEquals("waiting", f.server.states[gid]) f.service.setIntent(id, RemoteDownloadIntent.Cancel); f.service.reconcile(id); f.service.reconcile(id) assertEquals("removed", f.server.states[gid]) assertTrue(f.job().terminal) f.service.remove(id) assertTrue(f.service.jobs.value.isEmpty()) assertEquals("active", f.server.states["1111111111111111"]) assertFalse(f.server.methods.any { it.endsWith("All") }) } @Test fun accountChangesBlockOldControlsAndRestoringItResumesReconciliation() = runTest { val f = Fixture(this) f.service.enqueue(f.request); f.service.reconcile() val original = f.prefs() f.updatePrefs { it.copy(endpoint = "https://other.example.org/jsonrpc", secret = "different") } val requests = f.server.methods.size f.service.reconcile() assertEquals(requests, f.server.methods.size) assertEquals(RemoteDownloadProblem.ServerChanged, f.job().problem) f.updatePrefs { original.copy(jobs = it.jobs) } f.service.reconcile() assertEquals(RemoteDownloadProblem.None, f.job().problem) } @Test fun accountChangeDuringStatusQueryPreventsFollowingControlCommands() = runTest { val f = Fixture(this) f.service.enqueue(f.request); f.service.reconcile() f.service.setIntent(f.job().id, RemoteDownloadIntent.Pause) f.server.onStatus = { f.updatePrefs { it.copy(secret = "new account") } } f.service.reconcile() assertEquals(RemoteDownloadProblem.ServerChanged, f.job().problem) assertFalse("aria2.forcePause" in f.server.methods) } @Test fun confirmedErroredFilesRetryWithFreshUrlsAndNewIds() = runTest { val f = Fixture(this) f.service.enqueue(f.request); f.service.reconcile() val old = f.job().files.single().gid val oldName = f.job().files.single().name f.server.states[old] = "error" f.service.reconcile() assertEquals(RemoteDownloadState.Error, f.job().files.single().state) f.pages = listOf(DbPageUrl(url = "https://images.example.org/fresh.png", headers = mapOf("Referer" to "https://source.example.org/new"))) f.service.retry(f.job().id) assertTrue(f.forcedRefresh) assertNotEquals(old, f.job().files.single().gid) assertNotEquals(oldName, f.job().files.single().name, "Changed resources must not append to an old partial file") f.service.reconcile() assertEquals(2, f.server.adds) assertEquals("error", f.server.states[old]) assertEquals("https://images.example.org/fresh.png", f.server.lastUrl) } @Test fun replacingLibraryRowsWithReusedIdsCannotRetryAnOldRemoteJob() = runTest { val f = Fixture(this) f.service.enqueue(f.request); f.service.reconcile() f.server.states[f.job().files.single().gid] = "error"; f.service.reconcile() f.db.upsertManga(requireNotNull(f.db.manga(1)).copy(link = "https://other.example.org/title")) assertFailsWith { f.service.retry(f.job().id) } assertEquals(1, f.server.adds) } @Test fun duplicateManualRequestsAreDeduplicatedAndHlsAndNovelsUseLocalBackend() = runTest { val f = Fixture(this) f.service.enqueue(f.request); f.service.enqueue(f.request) assertEquals(1, f.prefs().jobs.size) assertFalse(f.service.enqueue(f.request.copy(itemType = DbItemType.Novel))) val hls = Fixture(this) hls.pages = listOf(DbPageUrl(url = "https://video.example.org/master.m3u8?key=abc")) assertFalse(hls.service.enqueue(hls.request.copy(itemType = DbItemType.Anime))) assertTrue(hls.prefs().jobs.isEmpty()) } @Test fun persistenceFailurePreventsRemoteAdmission() = runTest { val f = Fixture(this) f.failPersistence = true assertFails { f.service.enqueue(f.request) } assertFails { f.service.reconcile() } assertEquals(0, f.server.adds) } @Test fun ownerRetirementJoinsSourceWorkAndPreventsLateAdmission() = runTest { val f = Fixture(this) val entered = CompletableDeferred(); val release = CompletableDeferred() f.beforeResolve = { entered.complete(Unit); withContext(NonCancellable) { release.await() } } val task = async { f.service.enqueue(f.request) } entered.await() val retiring = launch { f.owner.cancelAndJoin() } runCurrent(); assertFalse(retiring.isCompleted) release.complete(Unit); retiring.join() assertFailsWith { task.await() } assertTrue(f.prefs().jobs.isEmpty()) assertEquals(0, f.server.adds) assertFailsWith { f.service.testConnection() } } @Test fun queuePassesAreBoundedAndLargeChaptersDoNotStarveOtherJobs() = runTest { val f = Fixture(this) f.pages = (1..20).map { DbPageUrl(url = "https://images.example.org/$it.jpg") } f.service.enqueue(f.request) f.db.upsertChapter(DbChapter(id = 2, mangaId = 1, name = "Second")) f.service.enqueue(f.request.copy(chapterId = 2)) f.service.reconcile() assertEquals(8, f.server.adds) assertTrue(f.prefs().jobs.all { it.files.count { file -> file.state == RemoteDownloadState.Waiting } == 4 }) } @Test fun removingReceiptNeverCancelsOrDeletesServerFiles() = runTest { val f = Fixture(this) f.service.enqueue(f.request); f.service.reconcile() val gid = f.job().files.single().gid assertFails { f.service.remove(f.job().id) } f.service.remove(f.job().id, forgetUnverified = true) assertTrue(f.prefs().jobs.isEmpty()) assertEquals("active", f.server.states[gid]) assertFalse("aria2.forceRemove" in f.server.methods) } private class Fixture(private val test: TestScope, private val polling: Boolean = false) { val memory = InMemoryYokanDatabase(emptySnapshot()).apply { upsertSource(DbSource(id = 1, name = "Source")) upsertManga(DbManga(id = 1, name = "Title", sourceId = 1)) upsertChapter(DbChapter(id = 1, mangaId = 1, name = "Chapter")) updateSettings(settings().let { it.copy(features = it.features.copy(externalDownloads = DbExternalDownloads(PreferredDownloader.Aria2, "https://aria.example.org/jsonrpc", "secret", "/downloads"))) }) } val durable = mutableListOf>() var failPersistence = false val db = object : YokanDatabase by memory { override suspend fun awaitPersistence() { check(!failPersistence) { "disk failure" }; durable += prefs().jobs } } val owner = SupervisorJob(test.backgroundScope.coroutineContext[Job]) private val scope = CoroutineScope(test.backgroundScope.coroutineContext + owner) val server = Server() var pages = listOf(DbPageUrl(url = "https://images.example.org/page.jpg", headers = mapOf("Referer" to "https://source.example.org"))) var beforeResolve: suspend () -> Unit = {} var forcedRefresh = false val request = DownloadRequest("chapter-1", 1, DbItemType.Manga, mangaName = "Title", chapterName = "Chapter", sourceId = 1) val service = newService() fun newService(database: YokanDatabase = db) = ExternalDownloads(database, server, scope, { _, forced -> beforeResolve(); forcedRefresh = forced; pages }, clock = { test.testScheduler.currentTime }, startPolling = polling) fun prefs() = memory.settings().features.externalDownloads fun job() = prefs().jobs.single() fun updatePrefs(change: (DbExternalDownloads) -> DbExternalDownloads) { val old = memory.settings(); memory.updateSettings(old.copy(features = old.features.copy(externalDownloads = change(prefs())))) } } private class Server : HttpService { val states = mutableMapOf() val methods = mutableListOf() val tokens = mutableListOf() var adds = 0 var lastUrl = "" var loseAddReply = false var rejectBeforeAdmission = false var onAdd: (String) -> Unit = {} var onStatus: () -> Unit = {} override suspend fun request(request: HttpRequest): HttpResponse { val body = Json.parseToJsonElement(requireNotNull(request.body)) val response = if (body is JsonArray) JsonArray(body.map { answer(it.jsonObject) }) else answer(body.jsonObject) return HttpResponse(200, response.toString()) } private fun answer(call: JsonObject): JsonObject { val method = call.getValue("method").jsonPrimitive.content methods += method tokens += call.getValue("params").jsonArray.first().jsonPrimitive.content val params = call.getValue("params").jsonArray.drop(1) var missing = false val result: JsonElement = when (method) { "aria2.addUri" -> { adds++ if (rejectBeforeAdmission) error("Connection failed before submission") val options = params[1].jsonObject val gid = options.getValue("gid").jsonPrimitive.content onAdd(gid) states[gid] = "active"; lastUrl = params[0].jsonArray.single().jsonPrimitive.content if (loseAddReply) { loseAddReply = false; error("Lost acknowledgement") } JsonPrimitive(gid) } "aria2.tellStatus" -> { onStatus() val gid = params[0].jsonPrimitive.content val status = states[gid] if (status == null) { missing = true; JsonNull } else buildJsonObject { put("gid", gid); put("status", status); put("totalLength", "100"); put("completedLength", if (status == "complete") "100" else "50"); put("downloadSpeed", "10"); put("errorCode", if (status == "error") "3" else "0") } } "aria2.forcePause", "aria2.unpause", "aria2.forceRemove" -> { val gid = params[0].jsonPrimitive.content states[gid] = when (method) { "aria2.forcePause" -> "paused"; "aria2.unpause" -> "waiting"; else -> "removed" } JsonPrimitive(gid) } "aria2.getVersion" -> buildJsonObject { put("version", "1.37.0") } else -> error("Unexpected method $method") } return buildJsonObject { put("jsonrpc", "2.0"); put("id", call.getValue("id")) if (missing) put("error", buildJsonObject { put("code", 1); put("message", "GID not found") }) else put("result", result) } } } }