DownloadConcurrencyAndSerializationTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadConcurrencyAndSerializationTest.kt
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.database.DbChapter4import eu.friedcutlet.yokan.database.DbItemType5import eu.friedcutlet.yokan.database.DbManga6import eu.friedcutlet.yokan.database.DbPageUrl7import eu.friedcutlet.yokan.database.DbSource8import eu.friedcutlet.yokan.database.InMemoryYokanDatabase9import eu.friedcutlet.yokan.database.seedDatabaseSnapshot10import eu.friedcutlet.yokan.domain.Chapter11import eu.friedcutlet.yokan.domain.Manga12import eu.friedcutlet.yokan.domain.Source13import eu.friedcutlet.yokan.services.files.LocalFileService14import eu.friedcutlet.yokan.services.files.MemoryFiles15import eu.friedcutlet.yokan.services.files.NoArchives16import eu.friedcutlet.yokan.services.http.HttpRequest17import eu.friedcutlet.yokan.services.http.HttpResponse18import eu.friedcutlet.yokan.services.http.HttpService19import eu.friedcutlet.yokan.services.http.HttpStreamResponse20import kotlin.random.Random21import kotlin.test.Test22import kotlin.test.assertEquals23import kotlin.test.assertFalse24import kotlin.test.assertTrue25import kotlinx.coroutines.CompletableDeferred26import kotlinx.coroutines.ExperimentalCoroutinesApi27import kotlinx.coroutines.delay28import kotlinx.coroutines.test.StandardTestDispatcher29import kotlinx.coroutines.test.TestScope30import kotlinx.coroutines.test.advanceUntilIdle31import kotlinx.coroutines.test.runTest32import kotlinx.coroutines.withTimeout3334@OptIn(ExperimentalCoroutinesApi::class)35class DownloadConcurrencyAndSerializationTest {3637 /** A downloader whose chapters each resolve to the single page URL in [pages]. */38 private fun TestScope.downloader(39 database: InMemoryYokanDatabase,40 http: HttpService,41 pages: Map<Long, String>,42 files: LocalFileService = MemoryFiles(),43 ) = PersistentDownloadService(44 database = database,45 http = http,46 files = files,47 archives = NoArchives,48 scope = this,49 resolvePages = { chapterId, _ -> listOf(DbPageUrl(url = pages.getValue(chapterId))) },50 ioDispatcher = StandardTestDispatcher(testScheduler),51 )5253 private fun databaseWithDownloadParents(54 snapshot: eu.friedcutlet.yokan.database.YokanDatabaseSnapshot,55 chapterSources: Map<Long, Long>,56 ) = InMemoryYokanDatabase(57 snapshot.copy(58 sources = snapshot.sources + chapterSources.values.distinct().map { id -> DbSource(id = id, name = "Source $id") },59 mangas = snapshot.mangas + chapterSources.map { (chapterId, sourceId) ->60 DbManga(id = chapterId, name = "Title $chapterId", sourceId = sourceId, itemType = DbItemType.Manga)61 },62 chapters = snapshot.chapters + chapterSources.map { (id, _) ->63 DbChapter(id = id, mangaId = id, name = "Chapter $id", url = "/chapter/$id")64 },65 ),66 )6768 private class PromotionFailingFiles(private var failuresRemaining: Int) : MemoryFiles() {69 override fun promote(sourcePath: String, targetPath: String): Boolean {70 if (failuresRemaining > 0) {71 failuresRemaining -= 172 error("simulated promotion failure")73 }74 return super.promote(sourcePath, targetPath)75 }76 }7778 @Test79 fun resolveDownloadSourceKeyPrefersSourceIdThenDatabaseThenLabelThenId() {80 val seed = seedDatabaseSnapshot()81 val database = InMemoryYokanDatabase(82 seed.copy(83 mangas = listOf(84 DbManga(id = 10L, name = "Test Manga", source = "MangaDex", lang = "en", sourceId = 42L, itemType = DbItemType.Manga),85 DbManga(id = 11L, name = "No SourceId Manga", source = "CustomSource", lang = "fr", sourceId = null, itemType = DbItemType.Manga),86 ),87 chapters = listOf(88 DbChapter(id = 100L, mangaId = 10L, name = "Chapter 1", url = "/1"),89 DbChapter(id = 101L, mangaId = 11L, name = "Chapter 1", url = "/1"),90 ),91 ),92 )9394 // 1. Explicit sourceId in request takes highest precedence95 val reqExplicit = DownloadRequest(96 taskId = "task-1",97 chapterId = 100L,98 itemType = DbItemType.Manga,99 sourceId = 999L,100 )101 assertEquals("source-999", resolveDownloadSourceKey(reqExplicit, 1L, database))102103 // 2. Resolved from database manga.sourceId104 val reqFromDb = DownloadRequest(105 taskId = "task-2",106 chapterId = 100L,107 itemType = DbItemType.Manga,108 )109 assertEquals("source-42", resolveDownloadSourceKey(reqFromDb, 2L, database))110111 // 3. Resolved from database manga.source|lang when sourceId is null112 val reqNoSourceId = DownloadRequest(113 taskId = "task-3",114 chapterId = 101L,115 itemType = DbItemType.Manga,116 )117 assertEquals("source-CustomSource|fr", resolveDownloadSourceKey(reqNoSourceId, 3L, database))118119 // 4. Fallback to sourceLabel when not in database120 val reqLabel = DownloadRequest(121 taskId = "task-4",122 chapterId = 9999L,123 itemType = DbItemType.Manga,124 sourceLabel = "FallbackSource",125 )126 assertEquals("source-FallbackSource", resolveDownloadSourceKey(reqLabel, 4L, database))127128 // 5. Fallback to downloadId when unknown129 val reqUnknown = DownloadRequest(130 taskId = "",131 chapterId = 0L,132 itemType = DbItemType.Manga,133 )134 assertEquals("download-7", resolveDownloadSourceKey(reqUnknown, 7L, database))135 }136137 @Test138 fun downloadStartDelayCalculatesBaseAndJitter() {139 assertEquals(0L, downloadStartDelayMs(0))140 assertEquals(0L, downloadStartDelayMs(-1))141142 val mockRandomMin = object : Random() {143 override fun nextBits(bitCount: Int): Int = 0144 override fun nextDouble(): Double = 0.0145 }146 val mockRandomMax = object : Random() {147 override fun nextBits(bitCount: Int): Int = 0148 override fun nextDouble(): Double = 1.0149 }150151 // Base 2 seconds = 2000 ms. Jitter ranges from 25% (500 ms) to 100% (2000 ms).152 val minDelay = downloadStartDelayMs(2, mockRandomMin)153 val maxDelay = downloadStartDelayMs(2, mockRandomMax)154155 assertEquals(2500L, minDelay)156 assertEquals(4000L, maxDelay)157 }158159 @Test160 fun perSourceSerializationPreventsConcurrentDownloadsFromSameSource() = runTest {161 val seed = seedDatabaseSnapshot()162 val database = databaseWithDownloadParents(163 seed.copy(164 settings = seed.settings.copy(165 allowConcurrentDownloads = true,166 concurrentDownloads = 4,167 downloadDelaySeconds = 0,168 ),169 ),170 mapOf(10L to 100L, 11L to 100L, 20L to 200L),171 )172173 val ch10Started = CompletableDeferred<Unit>()174 val ch10Blocker = CompletableDeferred<Unit>()175 val ch11Started = CompletableDeferred<Unit>()176 val ch20Started = CompletableDeferred<Unit>()177178 val blockingHttp = object : HttpService {179 override suspend fun request(request: HttpRequest): HttpResponse =180 HttpResponse(statusCode = 200, headers = emptyMap(), body = "")181182 override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {183 if (request.url.contains("ch10")) {184 ch10Started.complete(Unit)185 ch10Blocker.await()186 } else if (request.url.contains("ch11")) {187 ch11Started.complete(Unit)188 } else if (request.url.contains("ch20")) {189 ch20Started.complete(Unit)190 }191 onChunk("test-content".encodeToByteArray())192 return HttpStreamResponse(statusCode = 200, headers = emptyMap())193 }194 }195196 val downloader = downloader(197 database,198 blockingHttp,199 mapOf(200 10L to "https://example.com/ch10/page1.jpg",201 11L to "https://example.com/ch11/page1.jpg",202 20L to "https://example.com/ch20/page1.jpg",203 ),204 )205 downloader.initialize(poolSize = 4)206207 // Enqueue Chapter 10 (Source 100)208 downloader.enqueue(209 DownloadRequest(210 taskId = "task-10",211 chapterId = 10L,212 itemType = DbItemType.Manga,213 chapterName = "Chapter 10",214 sourceId = 100L,215 ),216 ) {}217218 // Enqueue Chapter 11 (Same Source 100)219 downloader.enqueue(220 DownloadRequest(221 taskId = "task-11",222 chapterId = 11L,223 itemType = DbItemType.Manga,224 chapterName = "Chapter 11",225 sourceId = 100L,226 ),227 ) {}228229 // Enqueue Chapter 20 (Different Source 200)230 downloader.enqueue(231 DownloadRequest(232 taskId = "task-20",233 chapterId = 20L,234 itemType = DbItemType.Manga,235 chapterName = "Chapter 20",236 sourceId = 200L,237 ),238 ) {}239240 // Wait for ch10 to start241 withTimeout(5_000) { ch10Started.await() }242 assertFalse(downloader.activeDownloadProgress.value.single { it.taskId == "task-10" }.isPaused)243 downloader.pause("task-10")244 assertTrue(downloader.activeDownloadProgress.value.single { it.taskId == "task-10" }.isPaused)245 downloader.resume("task-10")246 assertFalse(downloader.activeDownloadProgress.value.single { it.taskId == "task-10" }.isPaused)247248 // Chapter 20 (different source) should run in parallel even while Chapter 10 is blocked249 withTimeout(5_000) { ch20Started.await() }250251 // Chapter 11 (same source 100) MUST NOT have started while Chapter 10 is active252 assertFalse(ch11Started.isCompleted, "Chapter 11 from the same source should be serialized and not start yet")253254 // Unblock Chapter 10255 ch10Blocker.complete(Unit)256257 // Now Chapter 11 should start258 withTimeout(5_000) { ch11Started.await() }259 assertTrue(ch11Started.isCompleted)260 }261262 @Test263 fun allowConcurrentDownloadsFalseEnforcesGlobalSingleConcurrency() = runTest {264 val seed = seedDatabaseSnapshot()265 val database = databaseWithDownloadParents(266 seed.copy(267 settings = seed.settings.copy(268 allowConcurrentDownloads = false, // Concurrency disabled269 concurrentDownloads = 5,270 downloadDelaySeconds = 0,271 ),272 ),273 mapOf(1L to 100L, 2L to 200L),274 )275276 val task1Started = CompletableDeferred<Unit>()277 val task1Blocker = CompletableDeferred<Unit>()278 val task2Started = CompletableDeferred<Unit>()279280 val blockingHttp = object : HttpService {281 override suspend fun request(request: HttpRequest): HttpResponse =282 HttpResponse(statusCode = 200, headers = emptyMap(), body = "")283284 override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {285 if (request.url.contains("task1")) {286 task1Started.complete(Unit)287 task1Blocker.await()288 } else if (request.url.contains("task2")) {289 task2Started.complete(Unit)290 }291 onChunk("test-content".encodeToByteArray())292 return HttpStreamResponse(statusCode = 200, headers = emptyMap())293 }294 }295296 val downloader = downloader(database, blockingHttp, mapOf(1L to "https://example.com/task1/p.jpg", 2L to "https://example.com/task2/p.jpg"))297 downloader.initialize(poolSize = 1)298299 downloader.enqueue(300 DownloadRequest(301 taskId = "task-1",302 chapterId = 1L,303 itemType = DbItemType.Manga,304 chapterName = "Task 1",305 sourceId = 100L,306 ),307 ) {}308309 downloader.enqueue(310 DownloadRequest(311 taskId = "task-2",312 chapterId = 2L,313 itemType = DbItemType.Manga,314 chapterName = "Task 2",315 sourceId = 200L, // Different source316 ),317 ) {}318319 withTimeout(5_000) { task1Started.await() }320321 // Give a short delay to see if task2 starts322 delay(100)323 assertFalse(task2Started.isCompleted, "Task 2 must not start while Task 1 is running when concurrency is disabled")324325 // Unblock task 1326 task1Blocker.complete(Unit)327328 // Now task 2 runs329 withTimeout(5_000) { task2Started.await() }330 assertTrue(task2Started.isCompleted)331 }332333 @Test334 fun stalledStreamFailsTheChapterInsteadOfStayingInProgress() = runTest {335 val database = databaseWithDownloadParents(seedDatabaseSnapshot(), mapOf(555L to 100L))336 var attempts = 0337 // What Ktor's socket timeout surfaces when a connection stops sending mid-page.338 val stallingHttp = object : HttpService {339 override suspend fun request(request: HttpRequest) = HttpResponse(statusCode = 200, headers = emptyMap(), body = "")340 override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {341 attempts += 1342 onChunk("partial".encodeToByteArray())343 throw IllegalStateException("Socket timeout has expired")344 }345 }346 val downloader = downloader(database, stallingHttp, mapOf(555L to "https://example.com/p1.jpg"))347348 downloader.enqueue(DownloadRequest(taskId = "stall-task", chapterId = 555L, itemType = DbItemType.Manga, retries = 1))349 advanceUntilIdle()350351 assertEquals(2, attempts)352 val downloadRecord = database.downloads().single { it.chapterId == 555L }353 assertFalse(downloadRecord.isDownload == true, "isDownload should be false on failure")354 assertFalse(downloadRecord.isStartDownload == true, "isStartDownload should be false on failure")355 assertTrue((downloadRecord.failed ?: 0) >= 1, "failed count should be at least 1")356 assertTrue(downloader.activeDownloads().isEmpty(), "a failed chapter must not stay in progress")357 }358359 @Test360 fun downloadQueueOrderSortsExplicitIdsFirstThenArrivalOrder() {361 val d1 = eu.friedcutlet.yokan.database.DbDownload(id = 10L, chapterId = 10L)362 val d2 = eu.friedcutlet.yokan.database.DbDownload(id = 20L, chapterId = 20L)363 val d3 = eu.friedcutlet.yokan.database.DbDownload(id = 30L, chapterId = 30L)364 val d4 = eu.friedcutlet.yokan.database.DbDownload(id = 40L, chapterId = 40L)365 val items = listOf(d1, d2, d3, d4)366367 // Empty order preserves incoming list368 assertEquals(items, DownloadQueueOrder.sorted(items, emptyList()))369370 // Manual order [30, 10] puts 30 and 10 first, then 20 and 40 in original order371 val sorted = DownloadQueueOrder.sorted(items, listOf(30L, 10L))372 assertEquals(listOf(30L, 10L, 20L, 40L), sorted.map { it.id })373 }374375 @Test376 fun downloadServiceReorderQueuePrioritizesMovedTask() = runTest {377 val seed = seedDatabaseSnapshot()378 val database = databaseWithDownloadParents(379 seed.copy(380 settings = seed.settings.copy(381 allowConcurrentDownloads = false,382 concurrentDownloads = 1,383 downloadDelaySeconds = 0,384 ),385 ),386 mapOf(1L to 100L, 2L to 100L, 3L to 100L),387 )388389 val task1Started = CompletableDeferred<Unit>()390 val task1Blocker = CompletableDeferred<Unit>()391 val executionOrder = mutableListOf<String>()392393 val testHttp = object : HttpService {394 override suspend fun request(request: HttpRequest) =395 HttpResponse(statusCode = 200, headers = emptyMap(), body = "")396397 override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {398 if (request.url.contains("task1")) {399 executionOrder.add("task1")400 task1Started.complete(Unit)401 task1Blocker.await()402 } else if (request.url.contains("task2")) {403 executionOrder.add("task2")404 } else if (request.url.contains("task3")) {405 executionOrder.add("task3")406 }407 onChunk("ok".encodeToByteArray())408 return HttpStreamResponse(statusCode = 200, headers = emptyMap())409 }410 }411412 val downloader = downloader(413 database,414 testHttp,415 mapOf(416 1L to "https://example.com/task1/1.jpg",417 2L to "https://example.com/task2/1.jpg",418 3L to "https://example.com/task3/1.jpg",419 ),420 )421 downloader.initialize(poolSize = 1)422423 val task2Done = CompletableDeferred<Unit>()424 val task3Done = CompletableDeferred<Unit>()425426 // 1. Enqueue task 1 (starts immediately and blocks)427 downloader.enqueue(428 DownloadRequest(429 taskId = "task1",430 chapterId = 1L,431 itemType = DbItemType.Manga,432 chapterName = "Task 1",433 ),434 ) {}435436 withTimeout(5_000) { task1Started.await() }437438 // 2. Enqueue task 2 and task 3 (they wait in queue)439 downloader.enqueue(440 DownloadRequest(441 taskId = "task2",442 chapterId = 2L,443 itemType = DbItemType.Manga,444 chapterName = "Task 2",445 ),446 ) { if (it.isCompleted) task2Done.complete(Unit) }447448 downloader.enqueue(449 DownloadRequest(450 taskId = "task3",451 chapterId = 3L,452 itemType = DbItemType.Manga,453 chapterName = "Task 3",454 ),455 ) { if (it.isCompleted) task3Done.complete(Unit) }456457 // Find downloadId for task 3 to prioritize it over task 2458 val d3 = database.downloads().first { it.chapterId == 3L }459 val d2 = database.downloads().first { it.chapterId == 2L }460461 // 3. Reorder queue putting task 3 ahead of task 2462 downloader.reorderQueue(listOf(d3.id, d2.id))463464 // 4. Release task 1465 task1Blocker.complete(Unit)466467 withTimeout(5_000) {468 task3Done.await()469 task2Done.await()470 }471472 // Task 3 must have run BEFORE Task 2473 assertEquals(listOf("task1", "task3", "task2"), executionOrder)474 }475476 @Test477 fun promotionExceptionReportsFailureAndQueueContinues() = runTest {478 val seed = seedDatabaseSnapshot()479 val database = databaseWithDownloadParents(480 seed.copy(481 settings = seed.settings.copy(482 allowConcurrentDownloads = false,483 concurrentDownloads = 1,484 downloadDelaySeconds = 0,485 ),486 ),487 mapOf(1L to 100L, 2L to 100L),488 )489 val files = PromotionFailingFiles(failuresRemaining = 1)490 val failed = CompletableDeferred<DownloadProgress>()491 val completed = CompletableDeferred<Unit>()492 val executionOrder = mutableListOf<String>()493 val http = object : HttpService {494 override suspend fun request(request: HttpRequest) =495 HttpResponse(statusCode = 200, headers = emptyMap(), body = "")496497 override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {498 executionOrder += request.url.substringAfter("/task").substringBefore('/')499 onChunk("ok".encodeToByteArray())500 return HttpStreamResponse(statusCode = 200, headers = emptyMap())501 }502 }503 val downloader = downloader(504 database,505 http,506 mapOf(1L to "https://example.com/task1/1.jpg", 2L to "https://example.com/task2/1.jpg"),507 files,508 )509 downloader.initialize(poolSize = 1)510511 downloader.enqueue(512 DownloadRequest(513 taskId = "task1",514 chapterId = 1L,515 itemType = DbItemType.Manga,516 retries = 0,517 ),518 ) { progress ->519 if (progress.failed > 0 && !failed.isCompleted) failed.complete(progress)520 }521 downloader.enqueue(522 DownloadRequest(523 taskId = "task2",524 chapterId = 2L,525 itemType = DbItemType.Manga,526 retries = 0,527 ),528 ) { progress ->529 if (progress.isCompleted && progress.failed == 0 && !completed.isCompleted) completed.complete(Unit)530 }531532 withTimeout(5_000) {533 failed.await()534 completed.await()535 }536 assertEquals(listOf("1", "2"), executionOrder)537 }538}539