Yokan / rebuild
Course 1 8624561

KtorHttpService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/KtorHttpService.kt

implementation152 lines
1package eu.friedcutlet.yokan.services.http23import io.ktor.client.HttpClient4import io.ktor.client.engine.HttpClientEngine5import io.ktor.client.plugins.HttpRequestRetry6import io.ktor.client.plugins.retry7import io.ktor.client.plugins.HttpTimeout8import io.ktor.client.plugins.HttpTimeoutConfig9import io.ktor.client.plugins.timeout10import io.ktor.client.request.HttpRequestBuilder11import io.ktor.client.request.headers12import io.ktor.client.request.prepareRequest13import io.ktor.client.request.request14import io.ktor.client.request.setBody15import io.ktor.client.statement.HttpResponse as KtorHttpResponse16import io.ktor.client.statement.bodyAsChannel17import io.ktor.client.statement.bodyAsBytes18import io.ktor.http.HttpMethod19import io.ktor.http.URLBuilder20import io.ktor.http.Url21import io.ktor.utils.io.readAvailable22import eu.friedcutlet.yokan.services.catchingNonCancellation23import kotlinx.coroutines.Job24import kotlinx.coroutines.NonCancellable25import kotlinx.coroutines.currentCoroutineContext26import kotlinx.coroutines.ensureActive27import kotlinx.coroutines.sync.Mutex28import kotlinx.coroutines.sync.withLock29import kotlinx.coroutines.withContext3031/**32 * Ktor 3-based [HttpService] used by every platform. Construction takes a pre-configured33 * engine (typically the platform's preferred transport: OkHttp on JVM targets,34 * Darwin on iOS). Shared code owns timeouts, retries, request mapping and awaited retirement.35 *36 * Maintains parity with the old `HttpURLConnection`-based service: 15s connect / 30s read37 * timeouts, redirects followed, no caching, error responses still surface as `HttpResponse` (no38 * exception thrown for 4xx/5xx). Adds Ktor's `HttpRequestRetry` plugin (3 retries, exponential39 * backoff capped at 4s) for transient 5xx / connection errors that the old service did not handle.40 * [stream] reads a 2xx body as it arrives (non-2xx bodies are buffered up to [STREAM_ERROR_BODY_LIMIT]41 * instead), drops the 60s total cap (the 30s socket timeout still catches a dead connection) and skips42 * the retry plugin: its caller, the download service, owns the retry policy so the two layers never multiply.43 */44class KtorHttpService(engine: HttpClientEngine, ownerJob: Job? = null) : HttpService {45    private val engine = ProfileHttpEngine(engine, ownerJob)46    private val retirementLock = Mutex()47    private val client: HttpClient = HttpClient(this.engine) {48        expectSuccess = false49        followRedirects = true50        install(HttpTimeout) {51            connectTimeoutMillis = 15_000L52            requestTimeoutMillis = 60_000L53            socketTimeoutMillis = 30_000L54        }55        install(HttpRequestRetry) {56            retryOnExceptionOrServerErrors(maxRetries = 3)57            exponentialDelay(base = 2.0, maxDelayMs = 4_000L)58        }59    }6061    override suspend fun request(request: HttpRequest): HttpResponse {62        ensureOpen()63        val url = request.parsedUrl()64            ?: return HttpResponse(statusCode = 0, body = "Invalid URL: ${request.url}")65        val response = client.request(url) { configure(request) }66        val bytes = catchingNonCancellation { response.bodyAsBytes() }.getOrElse { ByteArray(0) }67        val headerMap = response.headerMap()68        return HttpResponse(69            statusCode = response.status.value,70            headers = headerMap,71            bodyBytes = bytes,72            setCookies = response.headers.getAll("Set-Cookie").orEmpty(),73        )74    }7576    override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {77        ensureOpen()78        val url = request.parsedUrl() ?: return HttpStreamResponse(statusCode = 0)79        // client.request would buffer the whole body before returning; execute {} hands over the live channel.80        return client.prepareRequest(url) {81            configure(request)82            timeout { requestTimeoutMillis = HttpTimeoutConfig.INFINITE_TIMEOUT_MS }83            retry { noRetry() }84        }.execute { response ->85            request.onStreamResponse?.invoke(HttpStreamResponse(response.status.value, response.headerMap(), response.headers.getAll("Set-Cookie").orEmpty()))86            val channel = response.bodyAsChannel()87            val success = response.status.value in 200..29988            val buffer = ByteArray(if (success) STREAM_CHUNK_SIZE else STREAM_ERROR_BODY_LIMIT)89            var buffered = 090            while (success || buffered < buffer.size) {91                val read = channel.readAvailable(buffer, buffered, buffer.size - buffered)92                if (read < 0) break93                // Error bodies (challenge pages) are kept for the caller to inspect, never streamed.94                if (!success) buffered += read else if (read > 0) onChunk(buffer.copyOf(read))95            }96            HttpStreamResponse(97                statusCode = response.status.value,98                headers = response.headerMap(),99                setCookies = response.headers.getAll("Set-Cookie").orEmpty(),100                body = buffer.copyOf(buffered),101            )102        }103    }104105    private fun HttpRequest.parsedUrl(): Url? = runCatching { URLBuilder(url).build() }.getOrNull()106107    private fun HttpRequestBuilder.configure(request: HttpRequest) {108        method = HttpMethod.parse(request.method.uppercase())109        headers {110            request.headers.forEach { (key, value) -> append(key, value) }111        }112        val bodyBytes = request.bodyBytes113        val body = request.body114        if (bodyBytes != null || body != null) {115            val hasContentType = request.headers.keys.any { it.equals("Content-Type", ignoreCase = true) }116            if (!hasContentType) {117                headers { append("Content-Type", "application/json") }118            }119            setBody(bodyBytes ?: body.orEmpty())120        }121    }122123    private fun KtorHttpResponse.headerMap(): Map<String, String> =124        headers.entries().associate { (key, values) -> key to values.joinToString(",") }125126    /** Closes the client and the engine; Ktor does not close an engine it was handed. */127    fun close() {128        client.close()129        engine.close()130    }131132    /** Join request/body finalizers even when Ktor has already detached them from their callers. */133    suspend fun closeAndJoin() = retirementLock.withLock {134        withContext(NonCancellable) {135            val clientJob = client.coroutineContext[Job]136            clientJob?.cancel()137            engine.closeAndJoin()138            clientJob?.join()139            client.close()140        }141    }142143    private suspend fun ensureOpen() {144        currentCoroutineContext().ensureActive()145        client.coroutineContext[Job]?.ensureActive()146        engine.ensureOpen()147    }148149    private companion object {150        const val STREAM_CHUNK_SIZE = 64 * 1024151    }152}153

Search chapters, reference and source filenames.