scoop:scoop.http.client:0.1.0
src/sse/reconnect.scoop
Selected production source · src/sse/reconnect.scoop
1
package scoop.http.client3
import scoop.http.*4
import scoop.time.Duration5
import scoop.tls.TlsException6
import scoop.tls.TlsFailureKind8
internal suspend fun receiveClientSse(state: ClientSseState): SseEvent? {9
while (true) {10
state.requireActive()11
if (state.client.lock.withLock { state.finished }) return None12
var failure: Throwable? = None13
try {14
val event = state.reader!!.next()15
updateClientSseCursor(state)16
if (clientPresent(event)) return event17
} catch (error: Throwable) {18
if (!canReconnectClientSse(state, error)) throw error19
failure = Some(error)20
}21
closeClientSseResponse(state)22
if (!reconnectClientSse(state, failure)) { finishClientSse(state); return None }23
}24
}26
private fun canReconnectClientSse(state: ClientSseState, error: Throwable): Boolean {27
if (error is ResourceUseException || error is CancellationException || !clientPresent(state.options.reconnect)) return false28
if (state.client.lock.withLock { state.closing || clientPresent(state.failure) || state.client.closing }) return false29
val recorded = state.sequence.lastTransportFailure30
if (!clientPresent(recorded) || recorded!! !== error) return false31
val http2 = when (state.lastCall) {32
case Some(val call) -> clientPresent(call.http2StreamId)33
case None -> false34
}35
return clientPresent(clientRetryReason(error, http2)) || (error is HttpException && error.isUnexpectedEof) ||36
(error is TlsException && error.kind == TlsFailureKind.Truncated)37
}39
private suspend fun reconnectClientSse(state: ClientSseState, initialFailure: Throwable?): Boolean {40
var failure = initialFailure41
while (true) {42
state.requireActive()43
val policy = state.options.reconnect44
if (!clientPresent(policy) || (clientPresent(policy!!.maxReconnects) && state.reconnects >= policy!!.maxReconnects!!)) {45
if (clientPresent(failure)) throw failure!!46
return false47
}48
val cause = failure49
val event = state.client.lock.withLock {50
state.reconnects += 1L51
HttpSseReconnect(state.reconnects, state.delay, state.info!!.url, state.lastEventId, cause)52
}53
policy!!.onReconnect(event)54
state.requireActive()55
if (event.delay > Duration.ZERO) state.client.loop.sleep(event.delay)56
state.requireActive()57
try { openClientSseResponse(state); return true }58
catch (error: Throwable) {59
if (!canReconnectClientSse(state, error)) throw error60
failure = Some(error)61
closeClientSseResponse(state)62
}63
}64
}