package eu.friedcutlet.yokan.services.http fun interface HttpService { suspend fun request(request: HttpRequest): HttpResponse /** * Only a 2xx body reaches [onChunk]; any other body comes back buffered in [HttpStreamResponse.body], * capped at [STREAM_ERROR_BODY_LIMIT], so callers can inspect it (Cloudflare challenge pages) without * the error page ever landing in the caller's file. */ suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse { val response = request(request) val success = response.statusCode in 200..299 request.onStreamResponse?.invoke(HttpStreamResponse(response.statusCode, response.headers, response.setCookies)) if (success && response.bodyBytes.isNotEmpty()) onChunk(response.bodyBytes) return HttpStreamResponse( statusCode = response.statusCode, headers = response.headers, setCookies = response.setCookies, body = if (success) ByteArray(0) else response.bodyBytes.copyOf(minOf(response.bodyBytes.size, STREAM_ERROR_BODY_LIMIT)), ) } } /** Enough for a challenge page's markers; error bodies past this are dropped, never streamed. */ const val STREAM_ERROR_BODY_LIMIT = 64 * 1024 data class HttpRequest( val url: String, val method: String = "GET", val headers: Map = emptyMap(), val body: String? = null, val bodyBytes: ByteArray? = null, /** Streaming consumers validate headers before any bytes are written, including on failed transfers. */ val onStreamResponse: (suspend (HttpStreamResponse) -> Unit)? = null, ) class HttpResponse( val statusCode: Int, body: String? = null, val headers: Map = emptyMap(), val bodyBytes: ByteArray = body?.encodeToByteArray() ?: ByteArray(0), /** * Raw `Set-Cookie` response headers, one entry per cookie. Kept separate * from [headers] because Ktor's joined-map view loses the boundaries * between cookies whose attributes contain commas (`Expires=Mon, …`). */ val setCookies: List = emptyList(), ) { private val suppliedBody = body /** Decode only for text consumers; binary callers retain one representation. */ val body: String by lazy(LazyThreadSafetyMode.NONE) { suppliedBody ?: bodyBytes.decodeToString() } } data class HttpStreamResponse( val statusCode: Int, val headers: Map = emptyMap(), val setCookies: List = emptyList(), /** The non-2xx body (see [HttpService.stream]); empty for 2xx, whose bytes went to `onChunk`. */ val body: ByteArray = ByteArray(0), ) /** Case-insensitive header value, trimmed; null when absent or blank. */ fun Map.header(name: String): String? = entries.firstOrNull { it.key.equals(name, ignoreCase = true) }?.value?.trim()?.takeIf(String::isNotEmpty)