Yokan / rebuild
Course 1 8624561

ExtensionLiveFlowTest.kt

composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/ExtensionLiveFlowTest.kt

test / fixture309 lines
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.DbSource5import eu.friedcutlet.yokan.database.InMemoryYokanDatabase6import eu.friedcutlet.yokan.services.files.JvmLocalFileService7import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService8import eu.friedcutlet.yokan.services.http.EnhancedHttpService9import eu.friedcutlet.yokan.services.http.cookies.CookieJar10import eu.friedcutlet.yokan.services.http.createPlatformHttpService11import eu.friedcutlet.yokan.services.webview.WebViewRequest12import eu.friedcutlet.yokan.services.webview.createPlatformWebViewService13import java.nio.file.Path14import kotlin.test.Test15import org.junit.Assume.assumeTrue16import kotlin.test.fail17import kotlinx.coroutines.Dispatchers18import kotlinx.coroutines.async19import kotlinx.coroutines.awaitAll20import kotlinx.coroutines.runBlocking21import kotlinx.coroutines.withTimeout22import kotlinx.coroutines.withTimeoutOrNull23import eu.friedcutlet.yokan.services.extensions.js.JavaScriptExtensionRuntimeService2425/**26 * Live end-to-end flow for repository extensions, exercised through the real27 * QuickJS runtime and real OkHttp network stack. For each selected source it28 * runs: popular -> latest (if supported) -> search -> detail -> page/video links29 * (validating the returned links), and reports Cloudflare handling.30 *31 * Opt-in and network-bound, so it never runs in the default suite. Enable with:32 *33 *   ./gradlew :composeApp:desktopTest --tests '*ExtensionLiveFlowTest*' \34 *     -Dyokan.generated.repository=/abs/path/build/repository/anime_index.json \35 *     -Dyokan.live.extensions=all            # or sample:12, or a comma list of names/ids36 *     -Dyokan.live.parallelism=8              # source flows; QuickJS itself is globally bounded37 *     -Dyokan.live.itemType=anime             # anime (default), manga, or novel38 *     -Dyokan.live.resolveCloudflare=true     # defaults off for all-source audits39 *     -Dyokan.live.fullFlow=true              # all-mode defaults to popular-page smoke coverage40 *41 * The test fails only on genuine host/runtime defects (missing globals, QuickJS42 * exceptions, unported bridge calls). External outcomes — network errors,43 * geo-blocks, and Cloudflare challenges — are classified and reported, not44 * failed, because they are properties of the live site, not of Yokan.45 */46class ExtensionLiveFlowTest {47    @Test48    fun runsLiveFlowForSelectedExtensions() {49        val selection = System.getProperty(SelectionProperty)?.trim().orEmpty()50        val repoProperty = System.getProperty(RepositoryProperty)?.trim().orEmpty()51        assumeTrue(52            "set -D$SelectionProperty and -D$RepositoryProperty to run.",53            selection.isNotBlank() && repoProperty.isNotBlank(),54        )5556        val repositoryPath = Path.of(repoProperty).toAbsolutePath().normalize()57        val repositoryUrl = repositoryPath.toUri().toString()58        val itemType = when (System.getProperty(ItemTypeProperty)?.trim()?.lowercase()) {59            null, "", "anime" -> DbItemType.Anime60            "manga" -> DbItemType.Manga61            "novel" -> DbItemType.Novel62            else -> error("$ItemTypeProperty must be anime, manga, or novel.")63        }64        val catalogDatabase = InMemoryYokanDatabase()65        val catalogCookieJar = CookieJar(catalogDatabase)66        val catalogHttp = EnhancedHttpService(createPlatformHttpService(), catalogDatabase, catalogCookieJar)67        val files = JvmLocalFileService(68            downloadRoot = repositoryPath.parent.toString(),69            backupRoot = repositoryPath.parent.toString(),70            cacheRoot = repositoryPath.parent.toString(),71        )72        val catalog = HttpSourceCatalogService(catalogHttp, files)7374        val allSources = runBlocking { catalog.fetchSources(repositoryUrl, itemType) }75        val selected = selectSources(allSources, selection)76        check(selected.isNotEmpty()) { "No sources matched selection '$selection' (of ${allSources.size})." }7778        val parallelism = System.getProperty(ParallelismProperty)?.toIntOrNull()?.coerceIn(1, 8) ?: 879        val resolveCloudflare = System.getProperty(ResolveCloudflareProperty)?.toBooleanStrictOrNull()80            ?: !selection.equals("all", ignoreCase = true)81        val completeFlow = System.getProperty(FullFlowProperty)?.toBooleanStrictOrNull()82            ?: !selection.equals("all", ignoreCase = true)83        println(84            "[live-flow] running ${selected.size} source(s) with parallelism $parallelism " +85                "mode=${if (completeFlow) "complete" else "popular-smoke"} from $repositoryUrl",86        )87        val prepared = selected.map { source ->88            val payload = runBlocking { catalog.fetchSourcePayload(source) }89            source to payload90        }91        val dispatcher = Dispatchers.IO.limitedParallelism(parallelism)92        val reports = runBlocking {93            prepared.map { (source, payload) ->94                async(dispatcher) {95                    if (payload == null) {96                        FlowReport(source.name).apply { hostError = "missing payload" }97                    } else {98                        runFlow(source.copy(sourceCode = payload.decodeToString()), resolveCloudflare, completeFlow)99                    }100                }101            }.awaitAll()102        }103        reports.forEachIndexed { index, report ->104            println("[live-flow] (${index + 1}/${selected.size}) ${report.render()}")105        }106107        val hostFailures = reports.filter { it.hostError != null }108        println(summary(reports))109        if (hostFailures.isNotEmpty()) {110            fail(111                "Host/runtime defects in ${hostFailures.size} source(s):\n" +112                    hostFailures.joinToString("\n") { "  ${it.name}: ${it.hostError}" },113            )114        }115    }116117    private fun runFlow(source: DbSource, resolveCloudflare: Boolean, completeFlow: Boolean): FlowReport {118        val database = InMemoryYokanDatabase()119        val cookieJar = CookieJar(database)120        val http = EnhancedHttpService(createPlatformHttpService(), database, cookieJar)121        val webView = createPlatformWebViewService(http, cookieJar, createPlatformLocalFileService())122        val report = FlowReport(source.name)123        val runtime = JavaScriptExtensionRuntimeService(source = source, http = http, database = database)124        try {125            // 1. Popular (with a Cloudflare cookie-refresh retry through the WebView resolver).126            val popular = step(report, "popular") { runtime.popular(1) }127            if (resolveCloudflare && report.cloudflare && popular == null) {128                report.cloudflareResolveAttempted = true129                val resolved = runCatching {130                    runBlocking {131                        webView.resolveCloudflare(WebViewRequest(url = source.baseUrl, title = source.name))132                        withTimeoutOrNull(StepTimeoutMs) { runtime.popular(1) }133                    }134                }.getOrNull()135                report.cloudflareResolved = resolved != null && resolved.items.isNotEmpty()136            }137            val listing = popular ?: (if (report.cloudflareResolved) runCatching { runBlocking { runtime.popular(1) } }.getOrNull() else null)138            report.popularCount = listing?.items?.size ?: report.popularCount139            if (!completeFlow) return report140141            // 2. Latest (only when advertised).142            if (source.supportLatest == true || runCatching { runBlocking { runtime.supportsLatest() } }.getOrDefault(false)) {143                val latest = step(report, "latest") { runtime.latest(1) }144                report.latestCount = latest?.items?.size ?: -1145            } else {146                report.latestCount = -2 // not supported147            }148149            // 3. Search — reuse a popular title so the query is meaningful.150            val query = listing?.items?.firstOrNull()?.title?.split(Regex("\\s+"))?.firstOrNull()?.takeIf { it.length > 1 } ?: "a"151            val search = step(report, "search") { runtime.search(query, 1, runtime.filterList()) }152            report.searchCount = search?.items?.size ?: report.searchCount153154            // 4. Detail of the first popular (or search) item.155            val entry = listing?.items?.firstOrNull() ?: search?.items?.firstOrNull()156            if (entry != null) {157                val detail = step(report, "detail") { runtime.detail(entry.url) }158                if (detail != null) {159                    report.detailTitle = detail.title160                    report.chapterCount = detail.chapters.size161                    // 5. Page list / video list for the first chapter/episode; validate links.162                    val chapter = detail.chapters.firstOrNull()163                    if (chapter != null) {164                        if (source.itemType == DbItemType.Anime) {165                            val videos = step(report, "videoList") { runtime.videoList(chapter.url) }166                            report.linkCount = videos?.size ?: -1167                            report.validLinks = videos?.count { isValidLink(it.url) } ?: 0168                            report.firstLink = videos?.firstOrNull()?.url169                        } else {170                            val pages = step(report, "pageList") { runtime.pageList(chapter.url) }171                            report.linkCount = pages?.size ?: -1172                            report.validLinks = pages?.count { isValidLink(it.url) } ?: 0173                            report.firstLink = pages?.firstOrNull()?.url174                        }175                    }176                }177            }178        } finally {179            runtime.dispose()180        }181        return report182    }183184    /** Run one flow step; classify host defects vs external failures; note Cloudflare. */185    private fun <T> step(report: FlowReport, name: String, block: suspend () -> T): T? {186        return try {187            runBlocking { withTimeout(StepTimeoutMs) { block() } }188        } catch (error: Throwable) {189            val message = (generateSequence(error) { it.cause }.lastOrNull()?.message ?: error.message).orEmpty()190            if (message.contains("stack overflow", ignoreCase = true)) {191                println("[live-flow] ${report.name} $name stack trace:\n${error.stackTraceToString()}")192            }193            if (isCloudflare(message)) {194                report.cloudflare = true195                report.notes += "$name: cloudflare"196            } else if (isHostDefect(message)) {197                report.hostError = "$name: ${message.take(160)}"198            } else {199                report.notes += "$name: ${message.take(80)}"200            }201            null202        }203    }204205    private fun selectSources(sources: List<DbSource>, selection: String): List<DbSource> = when {206        selection.equals("all", ignoreCase = true) -> sources207        selection.startsWith("sample:", ignoreCase = true) -> {208            val n = selection.substringAfter(":").toIntOrNull() ?: 12209            // Spread the sample across the catalog rather than taking a contiguous block.210            val stride = (sources.size / n).coerceAtLeast(1)211            sources.filterIndexed { i, _ -> i % stride == 0 }.take(n)212        }213        else -> {214            val tokens = selection.split(",").map { it.trim().lowercase() }.filter { it.isNotEmpty() }.toSet()215            sources.filter { it.name.lowercase() in tokens || it.id.toString() in tokens }216        }217    }218219    private fun summary(reports: List<FlowReport>): String {220        val popular = reports.count { it.popularCount > 0 }221        val search = reports.count { it.searchCount > 0 }222        val detail = reports.count { it.detailTitle != null }223        val links = reports.count { it.validLinks > 0 }224        val cloudflare = reports.count { it.cloudflare }225        val cfResolved = reports.count { it.cloudflareResolved }226        val hostErrors = reports.count { it.hostError != null }227        return buildString {228            appendLine("[live-flow] summary of ${reports.size} source(s):")229            appendLine("  popular>0:   $popular")230            appendLine("  search>0:    $search")231            appendLine("  detail ok:   $detail")232            appendLine("  video/page links>0: $links")233            appendLine("  cloudflare detected: $cloudflare (resolved via WebView: $cfResolved)")234            appendLine("  host/runtime defects: $hostErrors")235        }236    }237238    private companion object {239        const val SelectionProperty = "yokan.live.extensions"240        const val RepositoryProperty = "yokan.generated.repository"241        const val ItemTypeProperty = "yokan.live.itemType"242        const val ParallelismProperty = "yokan.live.parallelism"243        const val ResolveCloudflareProperty = "yokan.live.resolveCloudflare"244        const val FullFlowProperty = "yokan.live.fullFlow"245        const val StepTimeoutMs = 30_000L246247        fun isValidLink(url: String): Boolean {248            val trimmed = url.trim()249            if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return false250            val host = trimmed.removePrefix("https://").removePrefix("http://").substringBefore("/").substringBefore("?")251            return host.contains(".") && host.length > 3252        }253254        fun isCloudflare(message: String): Boolean {255            val lower = message.lowercase()256            return "cloudflare" in lower || "anti-bot" in lower || "just a moment" in lower ||257                "challenge" in lower || "http 403" in lower || "http 503" in lower ||258                "ddos-guard" in lower259        }260261        fun isHostDefect(message: String): Boolean {262            val lower = message.lowercase()263            if (isCloudflare(message)) return false264            // Network/transport failures are external, not host defects.265            if ("unknownhost" in lower || "sslhandshake" in lower || "connect" in lower ||266                "timeout" in lower || "timed out" in lower || "closedbytechannel" in lower ||267                "econnreset" in lower || "no route" in lower || "interrupted" in lower268            ) return false269            return "not a function" in lower || "is not defined" in lower || "no setter" in lower ||270                "quickjsexception" in lower || "not a constructor" in lower ||271                "cannot read prop" in lower || "not implemented" in lower ||272                "bridge channel" in lower || "undefined is not" in lower ||273                "not iterable" in lower || "is not an object" in lower || "is undefined" in lower ||274                "stack overflow" in lower || "syntaxerror" in lower || "unexpected token" in lower ||275                "redeclaration of" in lower || "invalid property name" in lower276        }277    }278279    private class FlowReport(val name: String) {280        var popularCount = -1281        var latestCount = -3 // -3 unrun, -2 unsupported, -1 error, >=0 count282        var searchCount = -1283        var detailTitle: String? = null284        var chapterCount = -1285        var linkCount = -1286        var validLinks = 0287        var firstLink: String? = null288        var cloudflare = false289        var cloudflareResolveAttempted = false290        var cloudflareResolved = false291        var hostError: String? = null292        val notes = mutableListOf<String>()293294        fun render(): String {295            val latest = when (latestCount) { -3 -> "-"; -2 -> "n/a"; -1 -> "err"; else -> "$latestCount" }296            val cf = when {297                cloudflareResolved -> "cf:resolved"298                cloudflareResolveAttempted -> "cf:unresolved"299                cloudflare -> "cf:detected"300                else -> "cf:none"301            }302            val link = firstLink?.let { " first=${it.take(60)}" } ?: ""303            val err = hostError?.let { " HOST-ERROR[$it]" } ?: ""304            val note = if (notes.isEmpty()) "" else " notes[${notes.joinToString("; ")}]"305            return "$name: popular=$popularCount latest=$latest search=$searchCount " +306                "detail=${detailTitle?.take(24) ?: "-"} chapters=$chapterCount links=$validLinks/$linkCount $cf$link$err$note"307        }308    }309}310

Search chapters, reference and source filenames.