hi, we have got error with apache5 as httpClient a...
# ktor
t
hi, we have got error with apache5 as httpClient and use it as Ktor DI. So when the server restart, we will get this error.
Copy code
java.nio.channels.CancelledKeyException: null at java.base/sun.nio.ch.SelectionKeyImpl.ensureValid(Unknown Source) at java.base/sun.nio.ch.SelectionKeyImpl.interestOps(Unknown Source) at org.apache.hc.core5.reactor.IOSessionImpl.setEvent(IOSessionImpl.java:172) at org.apache.hc.core5.reactor.IOSessionImpl.enqueue(IOSessionImpl.java:115) at org.apache.hc.core5.reactor.ssl.SSLIOSession.enqueue(SSLIOSession.java:775) at org.apache.hc.core5.reactor.InternalDataChannel.enqueue(InternalDataChannel.java:286) at org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder.lambda$build$2(HttpAsyncClientBuilder.java:1077) at org.apache.hc.core5.reactor.SingleCoreIOReactor.initiateSessionShutdown(SingleCoreIOReactor.java:155) at org.apache.hc.core5.reactor.SingleCoreIOReactor.doExecute(SingleCoreIOReactor.java:115) at org.apache.hc.core5.reactor.AbstractSingleCoreIOReactor.execute(AbstractSingleCoreIOReactor.java:92) at org.apache.hc.core5.reactor.IOReactorWorker.run(IOReactorWorker.java:44) at java.base/java.lang.Thread.run(Unknown Source)
is it anyway to close the apache5 with Ktor DI?
a
Have you tried releasing the client resources by closing the client with the
cleanup
(https://ktor.io/docs/server-dependency-injection.html?topic=rx#custom-cleanup-logic) ?
👍 1
t
We tried using
cleanup
, but we still encountered the same error when redeploying the application on the cloud. We have another application that also uses
Apache 5
as the
HttpClient
without Ktor DI, and that application does not produce the CancelledKeyException error.
a
Can you please share the steps to reproduce the exception?
t
Copy code
fun createHttpClient(): HttpClient =
    HttpClient(Apache5) {
        expectSuccess = true

        engine {
            customizeClient {
                setRoutePlanner(SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                setKeepAliveStrategy { _, _ -> TimeValue.ofSeconds(300) }
            }
        }

        install(ContentNegotiation) {
            json(
                Json {
                    prettyPrint = true
                    ignoreUnknownKeys = true
                    encodeDefaults = true
                    explicitNulls = false
                },
            )
        }

        install(HttpRequestRetry) {
            retryOnExceptionOrServerErrors(5)
            modifyRequest { request ->
                logger.warn { "$retryCount retry feilet mot: ${request.url}" }
            }
            exponentialDelay()
        }
    }
and then in the Application.kt
Copy code
dependencies {
        provide { createHttpClient() } cleanup { client ->
            client.close()
        }
}
so every we redeploy the application, it will through the exeception.
a
Unfortunately, I cannot reproduce the exception with the following code. Can you share the steps to reproduce the problem?
t
this code will reproduce the error:
Copy code
import java.net.ProxySelector

import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking

import io.ktor.client.HttpClient
import io.ktor.client.engine.apache5.Apache5
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.server.application.ApplicationStarted
import io.ktor.server.engine.EmbeddedServer
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.plugins.di.dependencies
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import org.apache.hc.client5.http.impl.routing.SystemDefaultRoutePlanner
import org.apache.hc.core5.util.TimeValue

fun createTestHttpClient(): HttpClient =
    HttpClient(Apache5) {
        expectSuccess = true

        engine {
            customizeClient {
                setRoutePlanner(SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                setKeepAliveStrategy { _, _ -> TimeValue.ofSeconds(300) }
            }
        }
    }

fun createTestServer(): EmbeddedServer*, * =
    embeddedServer(Netty, port = 3333) {
        dependencies {
            provideHttpClient { createTestHttpClient() } cleanup { client ->
                client.close()
            }
        }

        routing {
            val client: HttpClient by dependencies
            get("/test") {
                call.respondText(client.get("https://example.com").bodyAsText(), ContentType.Text.Plain)
            }
        }
    }

suspend fun reproduceError() =
    coroutineScope {
        val client = HttpClient(io.ktor.client.engine.cio.CIO)
        repeat(5) {
            val server = createTestServer()
            val serverStarted = CompletableDeferredAny?(null)
            server.monitor.subscribe(ApplicationStarted) {
                serverStarted.complete(Unit)
            }

            server.start(wait = false)

            serverStarted.await()
            val response = client.get("http://localhost:3333/test")
            println("Response length: ${response.bodyAsText().length}")

            server.stop(500, 5000)
        }
        client.close()
    }

fun main() =
    runBlocking {
        reproduceError()
    }
a
Unfortunately, I cannot reproduce the exception with the above code snippet. Which version of Ktor, Kotlin, and JDK do you use?
t
JDK 21.0.8, Koltin 2.2.21 Ktor 3.3.3 I think I can not reproduce the error. first time I ran the code, 1 of the loop through the CancelledKeyException, but after that I can not get the same error
a
I've slightly modified the code snippet and managed to reproduce the exception (KTOR-9192).
🙇‍♂️ 1