Yokan / rebuild
Course 1 8624561

IsolatedBrowserHttpEngine.kt

composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/http/IsolatedBrowserHttpEngine.kt

implementation166 lines
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, io.ktor.utils.io.InternalAPI::class,2    kotlin.io.encoding.ExperimentalEncodingApi::class)34package eu.friedcutlet.yokan.services.http56import io.ktor.client.engine.HttpClientEngineBase7import io.ktor.client.engine.HttpClientEngineConfig8import io.ktor.client.engine.HttpClientEngineCapability9import io.ktor.client.plugins.HttpTimeoutCapability10import io.ktor.client.engine.callContext11import io.ktor.client.engine.mergeHeaders12import io.ktor.client.request.HttpRequestData13import io.ktor.client.request.HttpResponseData14import io.ktor.http.Headers15import io.ktor.http.HttpProtocolVersion16import io.ktor.http.HttpStatusCode17import io.ktor.http.content.OutgoingContent18import io.ktor.util.date.GMTDate19import io.ktor.utils.io.readBuffer20import io.ktor.utils.io.ByteChannel21import io.ktor.utils.io.writeFully22import io.ktor.utils.io.writer23import kotlinx.coroutines.CoroutineScope24import kotlinx.coroutines.CoroutineStart25import kotlinx.coroutines.launch26import kotlinx.coroutines.CancellationException27import kotlinx.coroutines.Job28import kotlinx.coroutines.NonCancellable29import kotlinx.coroutines.await30import kotlinx.coroutines.currentCoroutineContext31import kotlinx.coroutines.ensureActive32import kotlinx.coroutines.withContext33import kotlinx.io.readByteArray34import kotlinx.serialization.json.Json35import kotlin.io.encoding.Base6436import kotlin.js.JsAny37import kotlin.js.Promise3839/**40 * Ktor 3.1.0's browser engine cannot configure fetch credentials. This small separate transport41 * always omits ambient cookies/HTTP authentication and disables browser response caching. Browser42 * cookie logins and WebSockets need a separately isolated backend, so they are explicitly refused.43 * Default retains the original Ktor engine unchanged.44 */45internal class IsolatedBrowserHttpEngine : HttpClientEngineBase("yokan-isolated-fetch") {46    override val config = HttpClientEngineConfig()47    override val supportedCapabilities: Set<HttpClientEngineCapability<*>> = setOf(HttpTimeoutCapability)4849    override suspend fun execute(data: HttpRequestData): HttpResponseData {50        check(data.body !is OutgoingContent.ProtocolUpgrade) { "Browser WebSockets are unavailable in additional profiles" }51        check(data.headers["Cookie"].isNullOrBlank()) { "Cookie authentication is unavailable in additional browser profiles" }52        val context = callContext()53        val body = bodyBytes(data.body, context)54        currentCoroutineContext().ensureActive()55        val headers = mutableMapOf<String, String>()56        mergeHeaders(data.headers, data.body) { name, value -> headers[name] = value }57        val started = GMTDate()58        val operation = startFetch(data.url.toString(), data.method.value, Json.encodeToString(headers), body?.let(Base64::encode))59        val promise = fetchPromise(operation)60        val abort = requireNotNull(context[Job]).invokeOnCompletion { abortFetch(operation) }61        val result = try { promise.await<JsAny>().also { currentCoroutineContext().ensureActive() } }62        catch (error: Throwable) {63            abortFetch(operation)64            withContext(NonCancellable) {65                runCatching { promise.await<JsAny>() }66                runCatching { finishFetch(operation).await<JsAny?>() }67            }68            abort.dispose()69            throw error70        }71        // The bounded channel backpressures Fetch. Large episodes do not accumulate as one body72        // in JS/Wasm memory or hit the old 64 MiB response cap.73        val incoming = ByteChannel(autoFlush = true)74        CoroutineScope(context).launch(start = CoroutineStart.UNDISPATCHED) {75            try {76                while (true) {77                    currentCoroutineContext().ensureActive()78                    val chunk = readFetchChunk(operation).await<JsAny>()79                    if (chunkDone(chunk)) break80                    incoming.writeFully(Base64.decode(chunkBody(chunk)))81                }82                incoming.flushAndClose()83            } catch (error: Throwable) {84                incoming.cancel(error)85                if (error is CancellationException) throw error86            } finally {87                abortFetch(operation)88                try { withContext(NonCancellable) { finishFetch(operation).await<JsAny?>() } }89                finally { abort.dispose() }90            }91        }92        val responseHeaders = Json.decodeFromString<List<List<String>>>(headerJson(result))93        return HttpResponseData(94            HttpStatusCode(status(result), statusText(result)), started,95            Headers.build { responseHeaders.forEach { pair ->96                // Fetch exposes decoded bytes and may hide encoding headers for cross-origin calls.97                if (!pair[0].equals("Content-Encoding", true) && !pair[0].equals("Content-Length", true)) append(pair[0], pair[1])98            } }, HttpProtocolVersion.HTTP_1_1, incoming, context,99        )100    }101102    private suspend fun bodyBytes(content: OutgoingContent, context: kotlin.coroutines.CoroutineContext): ByteArray? = when (content) {103        is OutgoingContent.ByteArrayContent -> content.bytes()104        is OutgoingContent.ReadChannelContent -> content.readFrom().readBuffer().readByteArray()105        is OutgoingContent.WriteChannelContent -> CoroutineScope(context).writer {106            content.writeTo(channel)107        }.channel.readBuffer().readByteArray()108        is OutgoingContent.ContentWrapper -> bodyBytes(content.delegate(), context)109        is OutgoingContent.NoContent -> null110        is OutgoingContent.ProtocolUpgrade -> error("Isolated browser WebSockets are unavailable")111    }112}113114private fun fetchPromise(operation: JsAny): Promise<JsAny> = js("operation.promise")115private fun abortFetch(operation: JsAny): Unit = js("operation.controller.abort()")116private fun status(result: JsAny): Int = js("result.status")117private fun statusText(result: JsAny): String = js("result.statusText")118private fun headerJson(result: JsAny): String = js("result.headers")119private fun chunkDone(result: JsAny): Boolean = js("result.done")120private fun chunkBody(result: JsAny): String = js("result.body")121private fun readFetchChunk(operation: JsAny): Promise<JsAny> = js(122    """(() => {123        operation.readPromise = (async () => {124            if (!operation.reader) return { done: true, body: '' };125            const chunk = await operation.reader.read();126            if (chunk.done) return { done: true, body: '' };127            let binary = '';128            for (let i = 0; i < chunk.value.length; i += 32768)129                binary += String.fromCharCode(...chunk.value.subarray(i, i + 32768));130            return { done: false, body: btoa(binary) };131        })();132        return operation.readPromise;133    })()""",134)135private fun finishFetch(operation: JsAny): Promise<JsAny?> = js(136    """(async () => {137        if (operation.readPromise) await operation.readPromise.catch(() => {});138        if (operation.reader) {139            await operation.reader.cancel().catch(() => {});140            operation.reader.releaseLock();141            operation.reader = null;142        }143        return null;144    })()""",145)146private fun startFetch(url: String, method: String, headersJson: String, body: String?): JsAny = js(147    """148    (() => {149        const controller = new AbortController();150        let bytes;151        if (body !== null) {152            const binary = atob(body);153            bytes = Uint8Array.from(binary, c => c.charCodeAt(0));154        }155        const operation = { controller, reader: null, readPromise: null, promise: null };156        operation.promise = (async () => {157            const response = await fetch(url, { method, headers: JSON.parse(headersJson), body: bytes,158                credentials: 'omit', cache: 'no-store', signal: controller.signal });159            operation.reader = response.body && response.body.getReader();160            return { status: response.status, statusText: response.statusText,161                headers: JSON.stringify(Array.from(response.headers.entries())) };162        })();163        return operation;164    })()165    """,166)167

Search chapters, reference and source filenames.