ExtensionRuntimeStressTest.kt
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/ExtensionRuntimeStressTest.kt
1package eu.friedcutlet.yokan.services.extensions.js23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.DbSource5import eu.friedcutlet.yokan.database.DbSourceCodeLanguage6import eu.friedcutlet.yokan.services.extensions.lnreader.LnReaderExtensionRuntimeService7import eu.friedcutlet.yokan.services.http.HttpResponse8import eu.friedcutlet.yokan.services.http.HttpService9import java.util.concurrent.ConcurrentHashMap10import kotlin.test.Test11import kotlin.test.assertEquals12import kotlin.test.assertFailsWith13import kotlin.time.Duration.Companion.seconds14import kotlinx.coroutines.Dispatchers15import kotlinx.coroutines.async16import kotlinx.coroutines.awaitAll17import kotlinx.coroutines.delay18import kotlinx.coroutines.test.runTest1920class ExtensionRuntimeStressTest {21 @Test22 fun concurrentCallsStayIsolatedAcrossEightNativePluginRuntimes() = runTest(timeout = 60.seconds) {23 val requests = ConcurrentHashMap.newKeySet<String>()24 val http = HttpService { request ->25 delay(1)26 check(requests.add(request.url)) { "Duplicate dispatch: ${request.url}" }27 HttpResponse(200, request.url)28 }29 val runtimes = (0 until 8).map { index ->30 LnReaderExtensionRuntimeService(source(index).copy(sourceCode = """31 exports.default = {32 async popularNovels(page) {33 const response = await(fetchApi('https://source$index.test/' + page));34 return [{name:response.text(),path:String(page)}];35 }36 };37 """), http)38 }39 try {40 val titles = (0 until 400).map { page ->41 async(Dispatchers.Default) { runtimes[page % 8].popular(page).items.single().title }42 }.awaitAll()43 assertEquals((0 until 400).map { "https://source${it % 8}.test/$it" }, titles)44 assertEquals(400, requests.size)45 } finally { runtimes.forEach { it.dispose() } }46 }4748 @Test49 fun repeatedPluginFailureRebootsCleanlyBeforeTheNextSuccessfulCall() = runTest(timeout = 60.seconds) {50 val runtime = LnReaderExtensionRuntimeService(source(0).copy(sourceCode = """51 var calls = 0;52 exports.default = {53 popularNovels(page) {54 calls++;55 if (page < 0) throw new Error('Expected plugin failure');56 return [{name:String(calls),path:String(page)}];57 }58 };59 """), HttpService { error("No network expected") })60 try {61 repeat(50) {62 assertEquals("1", runtime.popular(1).items.single().title)63 assertFailsWith<Exception> { runtime.popular(-1) }64 }65 } finally { runtime.dispose() }66 }6768 private fun source(index: Int) = DbSource(69 id = index.toLong() + 1, name = "Stress $index", baseUrl = "https://source$index.test/", lang = "en",70 itemType = DbItemType.Novel, sourceCodeLanguage = DbSourceCodeLanguage.LnReader,71 )72}73