package eu.friedcutlet.yokan.services.http import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.runJoined import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.ensureActive /** Owns the entire call, including settings/cookie access, retries, streaming and finalizers. */ internal class ProfileHttpService( val profileId: ProfileId, private val delegate: HttpService, ownerScope: CoroutineScope, ) : HttpService { private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Profile HTTP requires an owner job" } private val scope = CoroutineScope(ownerScope.coroutineContext + SupervisorJob(ownerJob)) override suspend fun request(request: HttpRequest): HttpResponse = scope.runJoined { delegate.request(request) } override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse = scope.runJoined { callJob -> val guardedRequest = request.onStreamResponse?.let { onResponse -> request.copy(onStreamResponse = { response -> callJob.ensureActive() ownerJob.ensureActive() onResponse(response) }) } ?: request delegate.stream(guardedRequest) { bytes -> // Check the original call even if a transport invokes this from a cleanup context. callJob.ensureActive() ownerJob.ensureActive() onChunk(bytes) } } }