QuickJsJavaScriptEngine.kt
composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/QuickJsJavaScriptEngine.kt
1@file:OptIn(ExperimentalCoroutinesApi::class)23package eu.friedcutlet.yokan.services.extensions.js45import app.cash.zipline.EngineApi6import app.cash.zipline.InterruptHandler7import app.cash.zipline.QuickJs8import app.cash.zipline.Zipline9import app.cash.zipline.ZiplineService10import kotlinx.coroutines.CloseableCoroutineDispatcher11import kotlinx.coroutines.DelicateCoroutinesApi12import kotlinx.coroutines.ExperimentalCoroutinesApi13import kotlinx.coroutines.GlobalScope14import kotlinx.coroutines.launch15import kotlinx.coroutines.runBlocking16import kotlinx.coroutines.sync.Mutex17import kotlinx.coroutines.sync.withLock18import kotlin.time.Duration19import kotlin.time.Duration.Companion.seconds20import kotlin.time.TimeSource2122private const val BridgeServiceName = "yokanJavaScriptBridge"23private const val BridgeSendMessageFunctionId = "YhSjgGyh"24private const val QuickJsMemoryLimitBytes = 128L * 1024L * 1024L2526/**27 * The QuickJS stack cap. JVM/Android get 8 MiB (~9,000 recursion levels); iOS needs far more for the28 * same depth because zipline's native QuickJS is compiled unoptimized (~22 KiB per JS call).29 */30internal expect val QuickJsMaxStackSizeBytes: Long3132// Headroom above the JS cap for the host bridge frames (HTTP, WebView, extractors) that run on top33// of the deepest JS frame, as zipline recommends (6 MiB cap on 8 MiB threads).34private val QuickJsThreadStackBytes = QuickJsMaxStackSizeBytes + 2L * 1024L * 1024L35private val QuickJsEvaluationTimeout = 30.seconds3637// Creating and closing a runtime touch process-global state: QuickJS's JS_NewClassID bumps an38// unsynchronized counter during creation, and zipline's leak tracking adds/removes each runtime in39// one unsynchronized map. Evaluation only touches the engine's own runtime, so it runs in parallel.40private val QuickJsGlobalState = Mutex()4142/**43 * A dedicated thread with a [stackBytes] native stack for one engine. QuickJS measures its stack44 * limit from the thread that created the runtime, so every native call of an engine must run on45 * that same real thread, and the thread must actually own the stack the limit allows.46 */47internal expect fun quickJsDispatcher(stackBytes: Long): CloseableCoroutineDispatcher4849private interface YokanJavaScriptBridge : ZiplineService {50 fun sendMessage(channel: String, payload: String): String51}5253/**54 * QuickJS-backed JavaScript runtime shared by Android, desktop, and iOS.55 *56 * QuickJS is not thread-safe, so each engine creates its runtime, evaluates, and closes on its own57 * [quickJsDispatcher] thread. The explicit [QuickJsMaxStackSizeBytes] cap supports the large58 * generated parsers used by Aniyomi ports without leaving it unbounded.59 */60@OptIn(EngineApi::class)61internal class QuickJsJavaScriptEngine(62 bridge: JavaScriptMessageBridge,63 private val evaluationTimeout: Duration = QuickJsEvaluationTimeout,64) : JavaScriptEngine {65 // Host bridge calls (HTTP) block this thread until they return.66 private val dispatcher = quickJsDispatcher(QuickJsThreadStackBytes)67 private val zipline = try {68 runBlocking(dispatcher) {69 val runtime = QuickJsGlobalState.withLock { Zipline.create(dispatcher) }70 try {71 runtime.bind<YokanJavaScriptBridge>(72 BridgeServiceName,73 object : YokanJavaScriptBridge {74 override fun sendMessage(channel: String, payload: String): String =75 bridge.sendMessage(channel, payload)76 },77 )78 runtime.quickJs.memoryLimit = QuickJsMemoryLimitBytes79 runtime.quickJs.maxStackSize = QuickJsMaxStackSizeBytes80 runtime.quickJs.evaluate(BridgeBootstrap, "yokan-bridge.js")81 runtime82 } catch (error: Throwable) {83 QuickJsGlobalState.withLock { runtime.close() }84 throw error85 }86 }87 } catch (error: Throwable) {88 dispatcher.close()89 throw error90 }91 private val quickJs: QuickJs = zipline.quickJs92 private var closed = false9394 override fun evaluate(script: String, isCancelled: () -> Boolean): String = runBlocking(dispatcher) {95 check(!closed) { "JavaScript engine is closed." }96 val startedAt = TimeSource.Monotonic.markNow()97 quickJs.interruptHandler = InterruptHandler {98 isCancelled() || startedAt.elapsedNow() >= evaluationTimeout99 }100 try {101 quickJs.evaluate(script, "yokan-extension.js")?.toString().orEmpty()102 } finally {103 quickJs.interruptHandler = null104 }105 }106107 // Fire-and-forget on the engine's own thread so disposing a runtime never blocks its caller108 // (possibly Main); the thread runs it after any in-flight call, then exits.109 @OptIn(DelicateCoroutinesApi::class)110 override fun close() {111 GlobalScope.launch(dispatcher) {112 if (closed) return@launch113 closed = true114 try {115 QuickJsGlobalState.withLock { zipline.close() }116 } finally {117 dispatcher.close()118 }119 }120 }121122 private companion object {123 val BridgeBootstrap =124 """125 globalThis.__bridge = {126 sendMessage: function(channel, payload) {127 var call = JSON.stringify({128 service: "$BridgeServiceName",129 function: "$BridgeSendMessageFunctionId",130 args: [String(channel), String(payload)]131 });132 var result = JSON.parse(globalThis.app_cash_zipline_outboundChannel.call(call));133 if (Object.prototype.hasOwnProperty.call(result, "failure")) {134 var failure = result.failure || {};135 throw new Error(failure.message || failure.stacktraceString || "Host bridge call failed");136 }137 return result.success;138 }139 };140 """.trimIndent()141 }142}143