KtorHttpServiceLifecycleTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/KtorHttpServiceLifecycleTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, io.ktor.utils.io.InternalAPI::class)23package eu.friedcutlet.yokan.services.http45import io.ktor.client.engine.HttpClientEngine6import io.ktor.client.engine.callContext7import io.ktor.client.request.HttpResponseData8import io.ktor.http.Headers9import io.ktor.http.HttpProtocolVersion10import io.ktor.http.HttpStatusCode11import io.ktor.util.date.GMTDate12import io.ktor.utils.io.ByteChannel13import io.ktor.utils.io.ByteReadChannel14import kotlinx.coroutines.CancellationException15import kotlinx.coroutines.CompletableDeferred16import kotlinx.coroutines.CoroutineScope17import kotlinx.coroutines.Job18import kotlinx.coroutines.NonCancellable19import kotlinx.coroutines.SupervisorJob20import kotlinx.coroutines.awaitCancellation21import kotlinx.coroutines.cancelAndJoin22import kotlinx.coroutines.launch23import kotlinx.coroutines.test.StandardTestDispatcher24import kotlinx.coroutines.test.runTest25import kotlinx.coroutines.withContext26import kotlin.test.Test27import kotlin.test.assertEquals28import kotlin.test.assertFailsWith29import kotlin.test.assertFalse30import kotlin.test.assertTrue3132class KtorHttpServiceLifecycleTest {33 @Test fun standaloneTransportRetainsResponseMappingAndClosesOnlyOnce() = runTest {34 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {35 response(ByteReadChannel(byteArrayOf(0, -1, 1)), Headers.build {36 append("Set-Cookie", "a=1"); append("Set-Cookie", "b=2")37 })38 }39 val service = KtorHttpService(engine)40 val result = service.request(HttpRequest("https://source.test/page", method = "POST", body = "payload"))41 assertTrue(result.bodyBytes.contentEquals(byteArrayOf(0, -1, 1)))42 assertEquals(listOf("a=1", "b=2"), result.setCookies)43 assertEquals("POST", engine.requests.receive().method.value)44 service.closeAndJoin(); service.closeAndJoin(); service.close()45 assertEquals(1, engine.closeCalls)46 assertTrue(engine.coroutineContext[Job]?.isCompleted == true)47 }4849 @Test fun retirementJoinsPendingRequestFinalizersBeforeNativeRelease() = runTest {50 val parent = SupervisorJob()51 val release = CompletableDeferred<Unit>(); var finalized = false52 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {53 try { awaitCancellation() }54 finally { withContext(NonCancellable) { release.await(); finalized = true } }55 }56 val service = KtorHttpService(engine, parent)57 val caller = launch { service.request(HttpRequest("https://source.test/page")) }58 engine.requests.receive()59 val retiring = launch { service.closeAndJoin() }60 testScheduler.runCurrent()61 assertFalse(retiring.isCompleted); assertFalse(finalized); assertEquals(0, engine.closeCalls)62 release.complete(Unit); retiring.join(); caller.join()63 assertTrue(finalized); assertEquals(1, engine.closeCalls); assertTrue(parent.isActive)64 assertTrue(engine.coroutineContext[Job]?.isCompleted == true)65 parent.cancelAndJoin()66 }6768 @Test fun streamRetirementJoinsBodyProducerAfterEngineExecuteReturns() = runTest {69 val producerEntered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()70 var finalized = false71 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {72 val context = callContext()73 CoroutineScope(context).launch {74 try { producerEntered.complete(Unit); awaitCancellation() }75 finally { withContext(NonCancellable) { release.await(); finalized = true } }76 }77 response(ByteChannel(), context = context)78 }79 val service = KtorHttpService(engine)80 val caller = launch { service.stream(HttpRequest("https://source.test/page")) { error("No body was sent") } }81 producerEntered.await(); engine.requests.receive()82 caller.cancel(); testScheduler.runCurrent()83 val retiring = launch { service.closeAndJoin() }84 testScheduler.runCurrent()85 assertFalse(retiring.isCompleted); assertEquals(0, engine.closeCalls)86 release.complete(Unit); retiring.join(); caller.join()87 assertTrue(finalized); assertEquals(1, engine.closeCalls)88 }8990 @Test fun expiredOwnerRejectsRequestsAndStreamsBeforeUrlValidationOrDispatch() = runTest {91 val parent = SupervisorJob()92 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response(ByteReadChannel("ok")) }93 val service = KtorHttpService(engine, parent)94 parent.cancelAndJoin()95 for (url in listOf("https://source.test/page", "http://[")) {96 assertFailsWith<CancellationException> { service.request(HttpRequest(url)) }97 assertFailsWith<CancellationException> { service.stream(HttpRequest(url)) {} }98 }99 assertTrue(engine.requests.tryReceive().isFailure)100 service.closeAndJoin()101 }102103 @Test fun awaitedCloseStillJoinsFinalizersAfterLegacyImmediateClose() = runTest {104 val release = CompletableDeferred<Unit>()105 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {106 try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }107 }108 val service = KtorHttpService(engine)109 val caller = launch { service.request(HttpRequest("https://source.test/page")) }110 engine.requests.receive(); service.close()111 val retiring = launch { service.closeAndJoin() }112 testScheduler.runCurrent(); assertFalse(retiring.isCompleted)113 assertFailsWith<CancellationException> { service.request(HttpRequest("http://[")) }114 release.complete(Unit); retiring.join(); caller.join()115 assertEquals(1, engine.closeCalls)116 }117118 @Test fun failedNativeReleaseCanBeRetriedWithoutAdmittingNewCalls() = runTest {119 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response(ByteReadChannel("ok")) }120 var attempts = 0121 val failingEngine = object : HttpClientEngine by engine {122 override fun close() { attempts++; check(attempts > 1) { "Native release failed" }; engine.close() }123 }124 val service = KtorHttpService(failingEngine)125 assertFailsWith<IllegalStateException> { service.closeAndJoin() }126 assertFailsWith<CancellationException> { service.request(HttpRequest("https://source.test/page")) }127 service.closeAndJoin(); service.closeAndJoin()128 assertEquals(2, attempts); assertEquals(1, engine.closeCalls)129 assertTrue(engine.requests.tryReceive().isFailure)130 }131132 @Test fun platformFactoryRejectsExpiredOwnerBeforeDefaultAllocation() = runTest {133 val parent = SupervisorJob(); parent.cancelAndJoin()134 assertFailsWith<CancellationException> {135 createPlatformHttpService(ownerScope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)))136 }137 }138139 private suspend fun response(body: ByteReadChannel, headers: Headers = Headers.Empty,140 context: kotlin.coroutines.CoroutineContext? = null) =141 HttpResponseData(HttpStatusCode.OK, GMTDate(), headers, HttpProtocolVersion.HTTP_1_1, body, context ?: callContext())142}143