ProfileHttpService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/ProfileHttpService.kt
1package eu.friedcutlet.yokan.services.http23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.services.runJoined5import kotlinx.coroutines.CoroutineScope6import kotlinx.coroutines.Job7import kotlinx.coroutines.SupervisorJob8import kotlinx.coroutines.ensureActive910/** Owns the entire call, including settings/cookie access, retries, streaming and finalizers. */11internal class ProfileHttpService(12 val profileId: ProfileId,13 private val delegate: HttpService,14 ownerScope: CoroutineScope,15) : HttpService {16 private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Profile HTTP requires an owner job" }17 private val scope = CoroutineScope(ownerScope.coroutineContext + SupervisorJob(ownerJob))1819 override suspend fun request(request: HttpRequest): HttpResponse = scope.runJoined { delegate.request(request) }2021 override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse =22 scope.runJoined { callJob ->23 val guardedRequest = request.onStreamResponse?.let { onResponse ->24 request.copy(onStreamResponse = { response ->25 callJob.ensureActive()26 ownerJob.ensureActive()27 onResponse(response)28 })29 } ?: request30 delegate.stream(guardedRequest) { bytes ->31 // Check the original call even if a transport invokes this from a cleanup context.32 callJob.ensureActive()33 ownerJob.ensureActive()34 onChunk(bytes)35 }36 }37}38