@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, io.ktor.utils.io.InternalAPI::class, kotlin.io.encoding.ExperimentalEncodingApi::class) package eu.friedcutlet.yokan.services.http import io.ktor.client.engine.HttpClientEngineBase import io.ktor.client.engine.HttpClientEngineConfig import io.ktor.client.engine.HttpClientEngineCapability import io.ktor.client.plugins.HttpTimeoutCapability import io.ktor.client.engine.callContext import io.ktor.client.engine.mergeHeaders import io.ktor.client.request.HttpRequestData import io.ktor.client.request.HttpResponseData import io.ktor.http.Headers import io.ktor.http.HttpProtocolVersion import io.ktor.http.HttpStatusCode import io.ktor.http.content.OutgoingContent import io.ktor.util.date.GMTDate import io.ktor.utils.io.readBuffer import io.ktor.utils.io.ByteChannel import io.ktor.utils.io.writeFully import io.ktor.utils.io.writer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.launch import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.await import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import kotlinx.io.readByteArray import kotlinx.serialization.json.Json import kotlin.io.encoding.Base64 import kotlin.js.JsAny import kotlin.js.Promise /** * Ktor 3.1.0's browser engine cannot configure fetch credentials. This small separate transport * always omits ambient cookies/HTTP authentication and disables browser response caching. Browser * cookie logins and WebSockets need a separately isolated backend, so they are explicitly refused. * Default retains the original Ktor engine unchanged. */ internal class IsolatedBrowserHttpEngine : HttpClientEngineBase("yokan-isolated-fetch") { override val config = HttpClientEngineConfig() override val supportedCapabilities: Set> = setOf(HttpTimeoutCapability) override suspend fun execute(data: HttpRequestData): HttpResponseData { check(data.body !is OutgoingContent.ProtocolUpgrade) { "Browser WebSockets are unavailable in additional profiles" } check(data.headers["Cookie"].isNullOrBlank()) { "Cookie authentication is unavailable in additional browser profiles" } val context = callContext() val body = bodyBytes(data.body, context) currentCoroutineContext().ensureActive() val headers = mutableMapOf() mergeHeaders(data.headers, data.body) { name, value -> headers[name] = value } val started = GMTDate() val operation = startFetch(data.url.toString(), data.method.value, Json.encodeToString(headers), body?.let(Base64::encode)) val promise = fetchPromise(operation) val abort = requireNotNull(context[Job]).invokeOnCompletion { abortFetch(operation) } val result = try { promise.await().also { currentCoroutineContext().ensureActive() } } catch (error: Throwable) { abortFetch(operation) withContext(NonCancellable) { runCatching { promise.await() } runCatching { finishFetch(operation).await() } } abort.dispose() throw error } // The bounded channel backpressures Fetch. Large episodes do not accumulate as one body // in JS/Wasm memory or hit the old 64 MiB response cap. val incoming = ByteChannel(autoFlush = true) CoroutineScope(context).launch(start = CoroutineStart.UNDISPATCHED) { try { while (true) { currentCoroutineContext().ensureActive() val chunk = readFetchChunk(operation).await() if (chunkDone(chunk)) break incoming.writeFully(Base64.decode(chunkBody(chunk))) } incoming.flushAndClose() } catch (error: Throwable) { incoming.cancel(error) if (error is CancellationException) throw error } finally { abortFetch(operation) try { withContext(NonCancellable) { finishFetch(operation).await() } } finally { abort.dispose() } } } val responseHeaders = Json.decodeFromString>>(headerJson(result)) return HttpResponseData( HttpStatusCode(status(result), statusText(result)), started, Headers.build { responseHeaders.forEach { pair -> // Fetch exposes decoded bytes and may hide encoding headers for cross-origin calls. if (!pair[0].equals("Content-Encoding", true) && !pair[0].equals("Content-Length", true)) append(pair[0], pair[1]) } }, HttpProtocolVersion.HTTP_1_1, incoming, context, ) } private suspend fun bodyBytes(content: OutgoingContent, context: kotlin.coroutines.CoroutineContext): ByteArray? = when (content) { is OutgoingContent.ByteArrayContent -> content.bytes() is OutgoingContent.ReadChannelContent -> content.readFrom().readBuffer().readByteArray() is OutgoingContent.WriteChannelContent -> CoroutineScope(context).writer { content.writeTo(channel) }.channel.readBuffer().readByteArray() is OutgoingContent.ContentWrapper -> bodyBytes(content.delegate(), context) is OutgoingContent.NoContent -> null is OutgoingContent.ProtocolUpgrade -> error("Isolated browser WebSockets are unavailable") } } private fun fetchPromise(operation: JsAny): Promise = js("operation.promise") private fun abortFetch(operation: JsAny): Unit = js("operation.controller.abort()") private fun status(result: JsAny): Int = js("result.status") private fun statusText(result: JsAny): String = js("result.statusText") private fun headerJson(result: JsAny): String = js("result.headers") private fun chunkDone(result: JsAny): Boolean = js("result.done") private fun chunkBody(result: JsAny): String = js("result.body") private fun readFetchChunk(operation: JsAny): Promise = js( """(() => { operation.readPromise = (async () => { if (!operation.reader) return { done: true, body: '' }; const chunk = await operation.reader.read(); if (chunk.done) return { done: true, body: '' }; let binary = ''; for (let i = 0; i < chunk.value.length; i += 32768) binary += String.fromCharCode(...chunk.value.subarray(i, i + 32768)); return { done: false, body: btoa(binary) }; })(); return operation.readPromise; })()""", ) private fun finishFetch(operation: JsAny): Promise = js( """(async () => { if (operation.readPromise) await operation.readPromise.catch(() => {}); if (operation.reader) { await operation.reader.cancel().catch(() => {}); operation.reader.releaseLock(); operation.reader = null; } return null; })()""", ) private fun startFetch(url: String, method: String, headersJson: String, body: String?): JsAny = js( """ (() => { const controller = new AbortController(); let bytes; if (body !== null) { const binary = atob(body); bytes = Uint8Array.from(binary, c => c.charCodeAt(0)); } const operation = { controller, reader: null, readPromise: null, promise: null }; operation.promise = (async () => { const response = await fetch(url, { method, headers: JSON.parse(headersJson), body: bytes, credentials: 'omit', cache: 'no-store', signal: controller.signal }); operation.reader = response.body && response.body.getReader(); return { status: response.status, statusText: response.statusText, headers: JSON.stringify(Array.from(response.headers.entries())) }; })(); return operation; })() """, )