Yokan / rebuild
Course 1 8624561

JavaScriptHost.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptHost.kt

implementation210 lines
1package eu.friedcutlet.yokan.services.extensions.js23import eu.friedcutlet.yokan.database.DbSource4import eu.friedcutlet.yokan.database.DbSourcePreference5import eu.friedcutlet.yokan.database.YokanDatabase6import eu.friedcutlet.yokan.services.blockingDispatcher7import eu.friedcutlet.yokan.services.http.HttpRequest8import eu.friedcutlet.yokan.services.http.HttpResponse9import eu.friedcutlet.yokan.services.http.HttpService10import eu.friedcutlet.yokan.services.extensions.ExtensionLogger11import eu.friedcutlet.yokan.services.catchingNonCancellation12import eu.friedcutlet.yokan.services.runBlockingCompat13import kotlinx.coroutines.Job14import kotlinx.coroutines.ensureActive15import kotlinx.coroutines.job16import kotlinx.coroutines.sync.Mutex17import kotlinx.coroutines.sync.withLock18import kotlinx.coroutines.withContext19import kotlin.concurrent.Volatile20import kotlin.coroutines.EmptyCoroutineContext21import kotlinx.serialization.json.JsonNull22import kotlinx.serialization.json.JsonObject23import kotlinx.serialization.json.JsonPrimitive24import kotlinx.serialization.json.buildJsonArray25import kotlinx.serialization.json.buildJsonObject26import kotlinx.serialization.json.contentOrNull2728/**29 * Owns one extension's JavaScript engine and the host side of its `__bridge`.30 *31 * The engine boots lazily through [boot]. Every [call] is serialized by a per-host [Mutex] and runs32 * on [blockingDispatcher], so runtimes may be invoked from the main thread. A failed call closes the33 * engine so the next call boots a fresh one. Channels shared by every extension flavour (HTTP, log,34 * preferences, CSS selectors) are answered here, runtime-specific ones by [channels]; unknown35 * channels fail loudly.36 */37internal class JavaScriptHost(38    private val source: DbSource,39    private val http: HttpService,40    private val database: YokanDatabase?,41    private val engineFactory: (JavaScriptMessageBridge) -> JavaScriptEngine,42    private val boot: (JavaScriptEngine) -> Unit,43    private val channels: (channel: String, payload: String) -> String? = { _, _ -> null },44) {45    private val mutex = Mutex()46    private var engine: JavaScriptEngine? = null4748    // The job of the call holding [mutex]; QuickJS polls it from its own thread.49    @Volatile50    private var callerJob: Job? = null5152    private val sourcePreferenceDefaults by lazy {53        buildMap<String, String> {54            sourcePreferencesFromJson(source.preferenceList).forEach { getOrPut(it.key) { it.value } }55        }56    }5758    // Values written while no database is attached; with a database, the settings are the source of truth.59    private val detachedPreferences = mutableMapOf<String, String>()6061    suspend fun <T> call(block: (JavaScriptEngine) -> T): T = mutex.withLock {62        withContext(blockingDispatcher) {63            callerJob = coroutineContext.job64            try {65                val current = engine ?: bootEngine()66                try {67                    block(current)68                } catch (error: Throwable) {69                    close()70                    throw error71                }72            } catch (error: Throwable) {73                // A cancelled call fails with the engine's interrupt error; report the cancellation instead.74                ensureActive()75                throw error76            } finally {77                callerJob = null78            }79        }80    }8182    /**83     * Blocks a bridge callback on [block] as a child of the current [call], so cancelling the call84     * cancels it too. Failures are rethrown outside the child so they reach JavaScript without85     * cancelling the call.86     */87    fun <T> blockingBridgeCall(block: suspend () -> T): T =88        runBlockingCompat(callerJob ?: EmptyCoroutineContext) { catchingNonCancellation { block() } }.getOrThrow()8990    /** Closes the engine. Must not race [call]; the runtime cache only disposes idle runtimes. */91    fun close() {92        val current = engine ?: return93        engine = null94        runCatching { current.close() }95    }9697    private fun bootEngine(): JavaScriptEngine {98        check(source.sourceCode.isNotBlank()) { "${source.name} does not contain JavaScript source code." }99        val created = engineFactory(JavaScriptMessageBridge(::sendMessage)).let { raw ->100            object : JavaScriptEngine by raw {101                override fun evaluate(script: String, isCancelled: () -> Boolean): String =102                    raw.evaluate(script) { isCancelled() || callerJob?.isCancelled == true }103            }104        }105        try {106            boot(created)107        } catch (error: Throwable) {108            runCatching { created.close() }109            throw error110        }111        engine = created112        return created113    }114115    private fun sendMessage(channel: String, payload: String): String = when (channel) {116        "http_head", "http_get", "http_post", "http_put", "http_delete", "http_patch" -> {117            val request = httpRequestFromMessage(channel, payload)118            // ponytail: QuickJS host functions are synchronous (zipline exposes no promise/job-queue API119            // to host bindings), so HTTP blocks the engine's background lane until the response arrives.120            // Non-blocking needs promise-returning host calls plus a job pump in the engine. On wasm121            // the engine itself is unsupported, so this is never reached there.122            blockingBridgeCall { http.request(request) }.toJson().toString()123        }124        "log" -> {125            val message = payloadArray(payload).joinToString(" ") { element ->126                element.primitiveOrNull()?.contentOrNull.orEmpty()127            }128            if (message.isNotBlank()) ExtensionLogger.log(source.name, message)129            "null"130        }131        "get", "getString" -> preferenceValue(payload)132        "setString" -> setPreferenceValue(payload)133        "querySelector", "querySelectorAll" -> querySelectorBridge(channel, payload)134        else -> channels(channel, payload)135            ?: throw UnsupportedOperationException("JavaScript bridge channel '$channel' is not ported yet.")136    }137138    private fun preferenceValue(payload: String): String {139        val args = payloadArray(payload)140        val key = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()141        val defaultValue = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty()142        return storedPreference(key) ?: sourcePreferenceDefaults[key] ?: defaultValue143    }144145    private fun storedPreference(key: String): String? = if (database == null) {146        detachedPreferences[key]147    } else {148        database.settings().sourcePreferences.orEmpty()149            .lastOrNull { it.sourceId == source.id && it.key == key }150            ?.value151    }152153    private fun setPreferenceValue(payload: String): String {154        val args = payloadArray(payload)155        val key = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()156        val value = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty()157        if (key.isBlank()) return value158        if (database == null) {159            detachedPreferences[key] = value160        } else {161            val settings = database.settings()162            val others = settings.sourcePreferences.orEmpty().filterNot { it.sourceId == source.id && it.key == key }163            database.updateSettings(164                settings.copy(sourcePreferences = others + DbSourcePreference(sourceId = source.id, key = key, value = value)),165            )166        }167        return value168    }169170    private fun querySelectorBridge(channel: String, payload: String): String {171        val args = payloadArray(payload)172        val html = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()173        val selector = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty()174        if (html.isBlank() || selector.isBlank()) return "[]"175        val matches = HtmlSelectorMatcher.match(html, selector)176        return if (channel == "querySelector") {177            matches.firstOrNull()?.let { JsonPrimitive(it).toString() } ?: "null"178        } else {179            buildJsonArray { matches.forEach { add(JsonPrimitive(it)) } }.toString()180        }181    }182}183184/** Decodes the `[null, reqcopyWith, url, headers, body]` payload sent by the bootstraps' HTTP clients. */185private fun httpRequestFromMessage(channel: String, payload: String): HttpRequest {186    val args = payloadArray(payload)187    val url = args.getOrNull(2)?.primitiveOrNull()?.contentOrNull188        ?: throw IllegalArgumentException("Missing JavaScript HTTP url")189    val body = when (val bodyElement = args.getOrNull(4)) {190        null, JsonNull -> null191        is JsonPrimitive -> bodyElement.contentOrNull192        else -> bodyElement.toString()193    }194    return HttpRequest(195        url = url,196        method = channel.removePrefix("http_").uppercase(),197        headers = headersFromJsonElement(args.getOrNull(3)),198        body = body,199    )200}201202private fun HttpResponse.toJson(): JsonObject = buildJsonObject {203    put("body", JsonPrimitive(body))204    put("statusCode", JsonPrimitive(statusCode))205    put("headers", buildJsonObject { headers.forEach { (key, value) -> put(key, JsonPrimitive(value)) } })206    put("isRedirect", JsonPrimitive(statusCode in 300..399))207    put("persistentConnection", JsonPrimitive(false))208    put("reasonPhrase", JsonPrimitive(""))209    put("request", buildJsonObject {})210}211

Search chapters, reference and source filenames.