@file:OptIn(io.ktor.utils.io.InternalAPI::class) package eu.friedcutlet.yokan.services.http import eu.friedcutlet.yokan.util.PlatformLock import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.callContext import io.ktor.client.request.HttpRequestData import io.ktor.client.request.HttpResponseData import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /** Ktor call jobs are parented to request execution contexts, not the engine job. Track them explicitly. */ internal class ProfileHttpEngine( private val delegate: HttpClientEngine, private val owner: Job? = null, private val admission: () -> Boolean = { true }, ) : HttpClientEngine { override val coroutineContext get() = delegate.coroutineContext override val dispatcher get() = delegate.dispatcher override val config get() = delegate.config override val supportedCapabilities get() = delegate.supportedCapabilities private val lock = PlatformLock() private val retirementLock = Mutex() private val calls = mutableSetOf() private var retired = false private var released = false fun ensureOpen() { // Admission may consult another owner lock; never invoke it while holding the engine lock. if (!admission()) throw CancellationException("Profile transport admission has ended") lock.withLock { owner?.ensureActive() if (retired) throw CancellationException("Profile transport has ended") } } override suspend fun execute(data: HttpRequestData): HttpResponseData { ensureOpen() val call = requireNotNull(callContext()[Job]) lock.withLock { owner?.ensureActive() if (retired) throw CancellationException("Profile transport has ended") call.ensureActive() calls += call call.invokeOnCompletion { lock.withLock { calls.remove(call) } } } return delegate.execute(data) } private fun retire(): List = lock.withLock { retired = true; calls.toList() } private fun release() = lock.withLock { if (!released) { delegate.close(); released = true } } override fun close() { retire().forEach { it.cancel() }; release() } suspend fun closeAndJoin() = retirementLock.withLock { withContext(NonCancellable) { val active = retire() active.forEach { it.cancel() } active.forEach { it.join() } release() delegate.coroutineContext[Job]?.let { it.cancel(); it.join() } } } }