package eu.friedcutlet.yokan.services.extensions.js import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.services.http.HttpService import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import kotlin.test.Test import kotlin.test.assertEquals import kotlin.time.Duration.Companion.seconds class JavaScriptHostCancellationTest { @Test fun cancellingRunawayScriptReleasesHostForNextCall() = assertCancelledCallReleasesHost( script = "__bridge.sendMessage('entered', ''); while (true) {}", ) @Test fun cancellingCallBlockedOnBridgeHttpReleasesHostForNextCall() = assertCancelledCallReleasesHost( script = "__bridge.sendMessage('entered', ''); __bridge.sendMessage('http_get', JSON.stringify([null, null, 'https://example.org', {}, null]));", ) private fun assertCancelledCallReleasesHost(script: String) = runBlocking { val entered = CompletableDeferred() val host = JavaScriptHost( source = DbSource(id = 1L, name = "Runaway", sourceCode = "var ready = true;"), http = HttpService { awaitCancellation() }, database = null, engineFactory = { bridge -> QuickJsJavaScriptEngine(bridge) }, boot = { engine -> engine.evaluate("var ready = true;") }, channels = { channel, _ -> if (channel == "entered") "null".also { entered.complete(Unit) } else null }, ) try { val blocked = launch(Dispatchers.Default) { host.call { it.evaluate(script) } } entered.await() blocked.cancel() // Without cancellation support the first call holds the host for the 30 s evaluation timeout. val next = withTimeout(5.seconds) { host.call { it.evaluate("1 + 1") } } assertEquals("2", next) } finally { host.close() } } }