package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.seedDatabaseSnapshot import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.files.MemoryFiles import eu.friedcutlet.yokan.services.files.NoArchives import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.HttpStreamResponse import kotlin.random.Random import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withTimeout @OptIn(ExperimentalCoroutinesApi::class) class DownloadConcurrencyAndSerializationTest { /** A downloader whose chapters each resolve to the single page URL in [pages]. */ private fun TestScope.downloader( database: InMemoryYokanDatabase, http: HttpService, pages: Map, files: LocalFileService = MemoryFiles(), ) = PersistentDownloadService( database = database, http = http, files = files, archives = NoArchives, scope = this, resolvePages = { chapterId, _ -> listOf(DbPageUrl(url = pages.getValue(chapterId))) }, ioDispatcher = StandardTestDispatcher(testScheduler), ) private fun databaseWithDownloadParents( snapshot: eu.friedcutlet.yokan.database.YokanDatabaseSnapshot, chapterSources: Map, ) = InMemoryYokanDatabase( snapshot.copy( sources = snapshot.sources + chapterSources.values.distinct().map { id -> DbSource(id = id, name = "Source $id") }, mangas = snapshot.mangas + chapterSources.map { (chapterId, sourceId) -> DbManga(id = chapterId, name = "Title $chapterId", sourceId = sourceId, itemType = DbItemType.Manga) }, chapters = snapshot.chapters + chapterSources.map { (id, _) -> DbChapter(id = id, mangaId = id, name = "Chapter $id", url = "/chapter/$id") }, ), ) private class PromotionFailingFiles(private var failuresRemaining: Int) : MemoryFiles() { override fun promote(sourcePath: String, targetPath: String): Boolean { if (failuresRemaining > 0) { failuresRemaining -= 1 error("simulated promotion failure") } return super.promote(sourcePath, targetPath) } } @Test fun resolveDownloadSourceKeyPrefersSourceIdThenDatabaseThenLabelThenId() { val seed = seedDatabaseSnapshot() val database = InMemoryYokanDatabase( seed.copy( mangas = listOf( DbManga(id = 10L, name = "Test Manga", source = "MangaDex", lang = "en", sourceId = 42L, itemType = DbItemType.Manga), DbManga(id = 11L, name = "No SourceId Manga", source = "CustomSource", lang = "fr", sourceId = null, itemType = DbItemType.Manga), ), chapters = listOf( DbChapter(id = 100L, mangaId = 10L, name = "Chapter 1", url = "/1"), DbChapter(id = 101L, mangaId = 11L, name = "Chapter 1", url = "/1"), ), ), ) // 1. Explicit sourceId in request takes highest precedence val reqExplicit = DownloadRequest( taskId = "task-1", chapterId = 100L, itemType = DbItemType.Manga, sourceId = 999L, ) assertEquals("source-999", resolveDownloadSourceKey(reqExplicit, 1L, database)) // 2. Resolved from database manga.sourceId val reqFromDb = DownloadRequest( taskId = "task-2", chapterId = 100L, itemType = DbItemType.Manga, ) assertEquals("source-42", resolveDownloadSourceKey(reqFromDb, 2L, database)) // 3. Resolved from database manga.source|lang when sourceId is null val reqNoSourceId = DownloadRequest( taskId = "task-3", chapterId = 101L, itemType = DbItemType.Manga, ) assertEquals("source-CustomSource|fr", resolveDownloadSourceKey(reqNoSourceId, 3L, database)) // 4. Fallback to sourceLabel when not in database val reqLabel = DownloadRequest( taskId = "task-4", chapterId = 9999L, itemType = DbItemType.Manga, sourceLabel = "FallbackSource", ) assertEquals("source-FallbackSource", resolveDownloadSourceKey(reqLabel, 4L, database)) // 5. Fallback to downloadId when unknown val reqUnknown = DownloadRequest( taskId = "", chapterId = 0L, itemType = DbItemType.Manga, ) assertEquals("download-7", resolveDownloadSourceKey(reqUnknown, 7L, database)) } @Test fun downloadStartDelayCalculatesBaseAndJitter() { assertEquals(0L, downloadStartDelayMs(0)) assertEquals(0L, downloadStartDelayMs(-1)) val mockRandomMin = object : Random() { override fun nextBits(bitCount: Int): Int = 0 override fun nextDouble(): Double = 0.0 } val mockRandomMax = object : Random() { override fun nextBits(bitCount: Int): Int = 0 override fun nextDouble(): Double = 1.0 } // Base 2 seconds = 2000 ms. Jitter ranges from 25% (500 ms) to 100% (2000 ms). val minDelay = downloadStartDelayMs(2, mockRandomMin) val maxDelay = downloadStartDelayMs(2, mockRandomMax) assertEquals(2500L, minDelay) assertEquals(4000L, maxDelay) } @Test fun perSourceSerializationPreventsConcurrentDownloadsFromSameSource() = runTest { val seed = seedDatabaseSnapshot() val database = databaseWithDownloadParents( seed.copy( settings = seed.settings.copy( allowConcurrentDownloads = true, concurrentDownloads = 4, downloadDelaySeconds = 0, ), ), mapOf(10L to 100L, 11L to 100L, 20L to 200L), ) val ch10Started = CompletableDeferred() val ch10Blocker = CompletableDeferred() val ch11Started = CompletableDeferred() val ch20Started = CompletableDeferred() val blockingHttp = object : HttpService { override suspend fun request(request: HttpRequest): HttpResponse = HttpResponse(statusCode = 200, headers = emptyMap(), body = "") override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse { if (request.url.contains("ch10")) { ch10Started.complete(Unit) ch10Blocker.await() } else if (request.url.contains("ch11")) { ch11Started.complete(Unit) } else if (request.url.contains("ch20")) { ch20Started.complete(Unit) } onChunk("test-content".encodeToByteArray()) return HttpStreamResponse(statusCode = 200, headers = emptyMap()) } } val downloader = downloader( database, blockingHttp, mapOf( 10L to "https://example.com/ch10/page1.jpg", 11L to "https://example.com/ch11/page1.jpg", 20L to "https://example.com/ch20/page1.jpg", ), ) downloader.initialize(poolSize = 4) // Enqueue Chapter 10 (Source 100) downloader.enqueue( DownloadRequest( taskId = "task-10", chapterId = 10L, itemType = DbItemType.Manga, chapterName = "Chapter 10", sourceId = 100L, ), ) {} // Enqueue Chapter 11 (Same Source 100) downloader.enqueue( DownloadRequest( taskId = "task-11", chapterId = 11L, itemType = DbItemType.Manga, chapterName = "Chapter 11", sourceId = 100L, ), ) {} // Enqueue Chapter 20 (Different Source 200) downloader.enqueue( DownloadRequest( taskId = "task-20", chapterId = 20L, itemType = DbItemType.Manga, chapterName = "Chapter 20", sourceId = 200L, ), ) {} // Wait for ch10 to start withTimeout(5_000) { ch10Started.await() } assertFalse(downloader.activeDownloadProgress.value.single { it.taskId == "task-10" }.isPaused) downloader.pause("task-10") assertTrue(downloader.activeDownloadProgress.value.single { it.taskId == "task-10" }.isPaused) downloader.resume("task-10") assertFalse(downloader.activeDownloadProgress.value.single { it.taskId == "task-10" }.isPaused) // Chapter 20 (different source) should run in parallel even while Chapter 10 is blocked withTimeout(5_000) { ch20Started.await() } // Chapter 11 (same source 100) MUST NOT have started while Chapter 10 is active assertFalse(ch11Started.isCompleted, "Chapter 11 from the same source should be serialized and not start yet") // Unblock Chapter 10 ch10Blocker.complete(Unit) // Now Chapter 11 should start withTimeout(5_000) { ch11Started.await() } assertTrue(ch11Started.isCompleted) } @Test fun allowConcurrentDownloadsFalseEnforcesGlobalSingleConcurrency() = runTest { val seed = seedDatabaseSnapshot() val database = databaseWithDownloadParents( seed.copy( settings = seed.settings.copy( allowConcurrentDownloads = false, // Concurrency disabled concurrentDownloads = 5, downloadDelaySeconds = 0, ), ), mapOf(1L to 100L, 2L to 200L), ) val task1Started = CompletableDeferred() val task1Blocker = CompletableDeferred() val task2Started = CompletableDeferred() val blockingHttp = object : HttpService { override suspend fun request(request: HttpRequest): HttpResponse = HttpResponse(statusCode = 200, headers = emptyMap(), body = "") override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse { if (request.url.contains("task1")) { task1Started.complete(Unit) task1Blocker.await() } else if (request.url.contains("task2")) { task2Started.complete(Unit) } onChunk("test-content".encodeToByteArray()) return HttpStreamResponse(statusCode = 200, headers = emptyMap()) } } val downloader = downloader(database, blockingHttp, mapOf(1L to "https://example.com/task1/p.jpg", 2L to "https://example.com/task2/p.jpg")) downloader.initialize(poolSize = 1) downloader.enqueue( DownloadRequest( taskId = "task-1", chapterId = 1L, itemType = DbItemType.Manga, chapterName = "Task 1", sourceId = 100L, ), ) {} downloader.enqueue( DownloadRequest( taskId = "task-2", chapterId = 2L, itemType = DbItemType.Manga, chapterName = "Task 2", sourceId = 200L, // Different source ), ) {} withTimeout(5_000) { task1Started.await() } // Give a short delay to see if task2 starts delay(100) assertFalse(task2Started.isCompleted, "Task 2 must not start while Task 1 is running when concurrency is disabled") // Unblock task 1 task1Blocker.complete(Unit) // Now task 2 runs withTimeout(5_000) { task2Started.await() } assertTrue(task2Started.isCompleted) } @Test fun stalledStreamFailsTheChapterInsteadOfStayingInProgress() = runTest { val database = databaseWithDownloadParents(seedDatabaseSnapshot(), mapOf(555L to 100L)) var attempts = 0 // What Ktor's socket timeout surfaces when a connection stops sending mid-page. val stallingHttp = object : HttpService { override suspend fun request(request: HttpRequest) = HttpResponse(statusCode = 200, headers = emptyMap(), body = "") override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse { attempts += 1 onChunk("partial".encodeToByteArray()) throw IllegalStateException("Socket timeout has expired") } } val downloader = downloader(database, stallingHttp, mapOf(555L to "https://example.com/p1.jpg")) downloader.enqueue(DownloadRequest(taskId = "stall-task", chapterId = 555L, itemType = DbItemType.Manga, retries = 1)) advanceUntilIdle() assertEquals(2, attempts) val downloadRecord = database.downloads().single { it.chapterId == 555L } assertFalse(downloadRecord.isDownload == true, "isDownload should be false on failure") assertFalse(downloadRecord.isStartDownload == true, "isStartDownload should be false on failure") assertTrue((downloadRecord.failed ?: 0) >= 1, "failed count should be at least 1") assertTrue(downloader.activeDownloads().isEmpty(), "a failed chapter must not stay in progress") } @Test fun downloadQueueOrderSortsExplicitIdsFirstThenArrivalOrder() { val d1 = eu.friedcutlet.yokan.database.DbDownload(id = 10L, chapterId = 10L) val d2 = eu.friedcutlet.yokan.database.DbDownload(id = 20L, chapterId = 20L) val d3 = eu.friedcutlet.yokan.database.DbDownload(id = 30L, chapterId = 30L) val d4 = eu.friedcutlet.yokan.database.DbDownload(id = 40L, chapterId = 40L) val items = listOf(d1, d2, d3, d4) // Empty order preserves incoming list assertEquals(items, DownloadQueueOrder.sorted(items, emptyList())) // Manual order [30, 10] puts 30 and 10 first, then 20 and 40 in original order val sorted = DownloadQueueOrder.sorted(items, listOf(30L, 10L)) assertEquals(listOf(30L, 10L, 20L, 40L), sorted.map { it.id }) } @Test fun downloadServiceReorderQueuePrioritizesMovedTask() = runTest { val seed = seedDatabaseSnapshot() val database = databaseWithDownloadParents( seed.copy( settings = seed.settings.copy( allowConcurrentDownloads = false, concurrentDownloads = 1, downloadDelaySeconds = 0, ), ), mapOf(1L to 100L, 2L to 100L, 3L to 100L), ) val task1Started = CompletableDeferred() val task1Blocker = CompletableDeferred() val executionOrder = mutableListOf() val testHttp = object : HttpService { override suspend fun request(request: HttpRequest) = HttpResponse(statusCode = 200, headers = emptyMap(), body = "") override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse { if (request.url.contains("task1")) { executionOrder.add("task1") task1Started.complete(Unit) task1Blocker.await() } else if (request.url.contains("task2")) { executionOrder.add("task2") } else if (request.url.contains("task3")) { executionOrder.add("task3") } onChunk("ok".encodeToByteArray()) return HttpStreamResponse(statusCode = 200, headers = emptyMap()) } } val downloader = downloader( database, testHttp, mapOf( 1L to "https://example.com/task1/1.jpg", 2L to "https://example.com/task2/1.jpg", 3L to "https://example.com/task3/1.jpg", ), ) downloader.initialize(poolSize = 1) val task2Done = CompletableDeferred() val task3Done = CompletableDeferred() // 1. Enqueue task 1 (starts immediately and blocks) downloader.enqueue( DownloadRequest( taskId = "task1", chapterId = 1L, itemType = DbItemType.Manga, chapterName = "Task 1", ), ) {} withTimeout(5_000) { task1Started.await() } // 2. Enqueue task 2 and task 3 (they wait in queue) downloader.enqueue( DownloadRequest( taskId = "task2", chapterId = 2L, itemType = DbItemType.Manga, chapterName = "Task 2", ), ) { if (it.isCompleted) task2Done.complete(Unit) } downloader.enqueue( DownloadRequest( taskId = "task3", chapterId = 3L, itemType = DbItemType.Manga, chapterName = "Task 3", ), ) { if (it.isCompleted) task3Done.complete(Unit) } // Find downloadId for task 3 to prioritize it over task 2 val d3 = database.downloads().first { it.chapterId == 3L } val d2 = database.downloads().first { it.chapterId == 2L } // 3. Reorder queue putting task 3 ahead of task 2 downloader.reorderQueue(listOf(d3.id, d2.id)) // 4. Release task 1 task1Blocker.complete(Unit) withTimeout(5_000) { task3Done.await() task2Done.await() } // Task 3 must have run BEFORE Task 2 assertEquals(listOf("task1", "task3", "task2"), executionOrder) } @Test fun promotionExceptionReportsFailureAndQueueContinues() = runTest { val seed = seedDatabaseSnapshot() val database = databaseWithDownloadParents( seed.copy( settings = seed.settings.copy( allowConcurrentDownloads = false, concurrentDownloads = 1, downloadDelaySeconds = 0, ), ), mapOf(1L to 100L, 2L to 100L), ) val files = PromotionFailingFiles(failuresRemaining = 1) val failed = CompletableDeferred() val completed = CompletableDeferred() val executionOrder = mutableListOf() val http = object : HttpService { override suspend fun request(request: HttpRequest) = HttpResponse(statusCode = 200, headers = emptyMap(), body = "") override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse { executionOrder += request.url.substringAfter("/task").substringBefore('/') onChunk("ok".encodeToByteArray()) return HttpStreamResponse(statusCode = 200, headers = emptyMap()) } } val downloader = downloader( database, http, mapOf(1L to "https://example.com/task1/1.jpg", 2L to "https://example.com/task2/1.jpg"), files, ) downloader.initialize(poolSize = 1) downloader.enqueue( DownloadRequest( taskId = "task1", chapterId = 1L, itemType = DbItemType.Manga, retries = 0, ), ) { progress -> if (progress.failed > 0 && !failed.isCompleted) failed.complete(progress) } downloader.enqueue( DownloadRequest( taskId = "task2", chapterId = 2L, itemType = DbItemType.Manga, retries = 0, ), ) { progress -> if (progress.isCompleted && progress.failed == 0 && !completed.isCompleted) completed.complete(Unit) } withTimeout(5_000) { failed.await() completed.await() } assertEquals(listOf("1", "2"), executionOrder) } }