scoop:scoop.http.client:0.1.0
src/sse/response.scoop
Selected production source · src/sse/response.scoop
1
package scoop.http.client3
import scoop.http.*4
import scoop.http.asyncio.SseSource5
import scoop.time.Duration7
internal suspend fun openClientSseResponse(state: ClientSseState) {8
state.requireActive()9
val request = clientSseRequest(state)10
val previous = state.sequence11
val last = state.lastCall12
val sequence = if (clientPresent(last) && last!!.sequence === previous)13
continueClientSequence(state.client, request, previous, last!!)14
else {15
val next = ClientRequestSequence(state.client.config, request, previous.started)16
next.requestBodyBytes = previous.requestBodyBytes17
next.encodedResponseBodyBytes = previous.encodedResponseBodyBytes18
next.responseBodyBytes = previous.responseBodyBytes19
next20
}21
state.client.lock.withLock { state.sequence = sequence }22
val response = executeClientSequence(state.client, request, sequence)23
state.client.lock.withLock {24
state.response = Some(response)25
state.lastCall = Some(response.call)26
when (state.info) {27
case Some(val info) -> { info.url = response.url; info.head = response.head }28
case None -> state.info = Some(ClientSseInfo(response.url, response.head))29
}30
}31
state.requireActive()32
if (response.status == 204U) {33
response.body.bytes(0L)34
finishClientSse(state)35
return36
}37
response.requireSuccess()38
if (response.status != 200U) throw HttpSseException(HttpSseFailureReason.UnexpectedStatus, response.url, Some(response.head))39
val mediaType = HttpMediaType.parseFields(response.fields)40
if (!clientPresent(mediaType) || mediaType!!.type != "text" || mediaType!!.subtype != "event-stream")41
throw HttpSseException(HttpSseFailureReason.UnsupportedContentType, response.url, Some(response.head))42
val reader = SseSource(response.body, state.options.limits, state.lastEventId, state.options.bufferSize)43
state.client.lock.withLock { state.reader = Some(reader) }44
}46
internal fun updateClientSseCursor(state: ClientSseState) {47
val reader = state.reader ?: return48
val id = reader.lastEventId49
val retry = reader.retryMilliseconds50
state.client.lock.withLock {51
state.lastEventId = id52
val policy = state.options.reconnect53
if (clientPresent(retry) && clientPresent(policy)) {54
val maximum = policy!!.maxDelay55
val requested = Duration.milliseconds(retry!!)56
state.delay = if (requested > maximum) maximum else requested57
}58
Unit59
}60
}62
internal suspend fun closeClientSseResponse(state: ClientSseState) {63
updateClientSseCursor(state)64
val (reader, response) = state.client.lock.withLock {65
val saved = (state.reader, state.response)66
state.reader = None; state.response = None67
saved68
}69
var failure: Throwable? = None70
try { reader?.close() } catch (error: Throwable) { failure = Some(error) }71
try { response?.close() } catch (error: Throwable) { failure = appendClientCleanup(failure, error) }72
if (clientPresent(failure)) throw failure!!73
}