package eu.friedcutlet.yokan.services.http import io.ktor.client.HttpClient import io.ktor.client.engine.HttpClientEngine import io.ktor.client.plugins.HttpRequestRetry import io.ktor.client.plugins.retry import io.ktor.client.plugins.HttpTimeout import io.ktor.client.plugins.HttpTimeoutConfig import io.ktor.client.plugins.timeout import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.headers import io.ktor.client.request.prepareRequest import io.ktor.client.request.request import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse as KtorHttpResponse import io.ktor.client.statement.bodyAsChannel import io.ktor.client.statement.bodyAsBytes import io.ktor.http.HttpMethod import io.ktor.http.URLBuilder import io.ktor.http.Url import io.ktor.utils.io.readAvailable import eu.friedcutlet.yokan.services.catchingNonCancellation import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /** * Ktor 3-based [HttpService] used by every platform. Construction takes a pre-configured * engine (typically the platform's preferred transport: OkHttp on JVM targets, * Darwin on iOS). Shared code owns timeouts, retries, request mapping and awaited retirement. * * Maintains parity with the old `HttpURLConnection`-based service: 15s connect / 30s read * timeouts, redirects followed, no caching, error responses still surface as `HttpResponse` (no * exception thrown for 4xx/5xx). Adds Ktor's `HttpRequestRetry` plugin (3 retries, exponential * backoff capped at 4s) for transient 5xx / connection errors that the old service did not handle. * [stream] reads a 2xx body as it arrives (non-2xx bodies are buffered up to [STREAM_ERROR_BODY_LIMIT] * instead), drops the 60s total cap (the 30s socket timeout still catches a dead connection) and skips * the retry plugin: its caller, the download service, owns the retry policy so the two layers never multiply. */ class KtorHttpService(engine: HttpClientEngine, ownerJob: Job? = null) : HttpService { private val engine = ProfileHttpEngine(engine, ownerJob) private val retirementLock = Mutex() private val client: HttpClient = HttpClient(this.engine) { expectSuccess = false followRedirects = true install(HttpTimeout) { connectTimeoutMillis = 15_000L requestTimeoutMillis = 60_000L socketTimeoutMillis = 30_000L } install(HttpRequestRetry) { retryOnExceptionOrServerErrors(maxRetries = 3) exponentialDelay(base = 2.0, maxDelayMs = 4_000L) } } override suspend fun request(request: HttpRequest): HttpResponse { ensureOpen() val url = request.parsedUrl() ?: return HttpResponse(statusCode = 0, body = "Invalid URL: ${request.url}") val response = client.request(url) { configure(request) } val bytes = catchingNonCancellation { response.bodyAsBytes() }.getOrElse { ByteArray(0) } val headerMap = response.headerMap() return HttpResponse( statusCode = response.status.value, headers = headerMap, bodyBytes = bytes, setCookies = response.headers.getAll("Set-Cookie").orEmpty(), ) } override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse { ensureOpen() val url = request.parsedUrl() ?: return HttpStreamResponse(statusCode = 0) // client.request would buffer the whole body before returning; execute {} hands over the live channel. return client.prepareRequest(url) { configure(request) timeout { requestTimeoutMillis = HttpTimeoutConfig.INFINITE_TIMEOUT_MS } retry { noRetry() } }.execute { response -> request.onStreamResponse?.invoke(HttpStreamResponse(response.status.value, response.headerMap(), response.headers.getAll("Set-Cookie").orEmpty())) val channel = response.bodyAsChannel() val success = response.status.value in 200..299 val buffer = ByteArray(if (success) STREAM_CHUNK_SIZE else STREAM_ERROR_BODY_LIMIT) var buffered = 0 while (success || buffered < buffer.size) { val read = channel.readAvailable(buffer, buffered, buffer.size - buffered) if (read < 0) break // Error bodies (challenge pages) are kept for the caller to inspect, never streamed. if (!success) buffered += read else if (read > 0) onChunk(buffer.copyOf(read)) } HttpStreamResponse( statusCode = response.status.value, headers = response.headerMap(), setCookies = response.headers.getAll("Set-Cookie").orEmpty(), body = buffer.copyOf(buffered), ) } } private fun HttpRequest.parsedUrl(): Url? = runCatching { URLBuilder(url).build() }.getOrNull() private fun HttpRequestBuilder.configure(request: HttpRequest) { method = HttpMethod.parse(request.method.uppercase()) headers { request.headers.forEach { (key, value) -> append(key, value) } } val bodyBytes = request.bodyBytes val body = request.body if (bodyBytes != null || body != null) { val hasContentType = request.headers.keys.any { it.equals("Content-Type", ignoreCase = true) } if (!hasContentType) { headers { append("Content-Type", "application/json") } } setBody(bodyBytes ?: body.orEmpty()) } } private fun KtorHttpResponse.headerMap(): Map = headers.entries().associate { (key, values) -> key to values.joinToString(",") } /** Closes the client and the engine; Ktor does not close an engine it was handed. */ fun close() { client.close() engine.close() } /** Join request/body finalizers even when Ktor has already detached them from their callers. */ suspend fun closeAndJoin() = retirementLock.withLock { withContext(NonCancellable) { val clientJob = client.coroutineContext[Job] clientJob?.cancel() engine.closeAndJoin() clientJob?.join() client.close() } } private suspend fun ensureOpen() { currentCoroutineContext().ensureActive() client.coroutineContext[Job]?.ensureActive() engine.ensureOpen() } private companion object { const val STREAM_CHUNK_SIZE = 64 * 1024 } }