ProfileHttpEngine.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/ProfileHttpEngine.kt
1@file:OptIn(io.ktor.utils.io.InternalAPI::class)23package eu.friedcutlet.yokan.services.http45import eu.friedcutlet.yokan.util.PlatformLock6import io.ktor.client.engine.HttpClientEngine7import io.ktor.client.engine.callContext8import io.ktor.client.request.HttpRequestData9import io.ktor.client.request.HttpResponseData10import kotlinx.coroutines.CancellationException11import kotlinx.coroutines.Job12import kotlinx.coroutines.NonCancellable13import kotlinx.coroutines.ensureActive14import kotlinx.coroutines.sync.Mutex15import kotlinx.coroutines.sync.withLock16import kotlinx.coroutines.withContext1718/** Ktor call jobs are parented to request execution contexts, not the engine job. Track them explicitly. */19internal class ProfileHttpEngine(20 private val delegate: HttpClientEngine,21 private val owner: Job? = null,22 private val admission: () -> Boolean = { true },23) : HttpClientEngine {24 override val coroutineContext get() = delegate.coroutineContext25 override val dispatcher get() = delegate.dispatcher26 override val config get() = delegate.config27 override val supportedCapabilities get() = delegate.supportedCapabilities28 private val lock = PlatformLock()29 private val retirementLock = Mutex()30 private val calls = mutableSetOf<Job>()31 private var retired = false32 private var released = false3334 fun ensureOpen() {35 // Admission may consult another owner lock; never invoke it while holding the engine lock.36 if (!admission()) throw CancellationException("Profile transport admission has ended")37 lock.withLock {38 owner?.ensureActive()39 if (retired) throw CancellationException("Profile transport has ended")40 }41 }4243 override suspend fun execute(data: HttpRequestData): HttpResponseData {44 ensureOpen()45 val call = requireNotNull(callContext()[Job])46 lock.withLock {47 owner?.ensureActive()48 if (retired) throw CancellationException("Profile transport has ended")49 call.ensureActive()50 calls += call51 call.invokeOnCompletion { lock.withLock { calls.remove(call) } }52 }53 return delegate.execute(data)54 }5556 private fun retire(): List<Job> = lock.withLock { retired = true; calls.toList() }57 private fun release() = lock.withLock {58 if (!released) { delegate.close(); released = true }59 }6061 override fun close() { retire().forEach { it.cancel() }; release() }6263 suspend fun closeAndJoin() = retirementLock.withLock {64 withContext(NonCancellable) {65 val active = retire()66 active.forEach { it.cancel() }67 active.forEach { it.join() }68 release()69 delegate.coroutineContext[Job]?.let { it.cancel(); it.join() }70 }71 }72}73