scoop:scoop.http.client:0.1.0
src/sse/operation.scoop
Selected production source · src/sse/operation.scoop
1
package scoop.http.client3
import scoop.asyncio.IoClosedException4
import scoop.http.SseEvent6
internal suspend fun openClientSse(7
client: ClientState,8
request: HttpRequest,9
options: HttpSseOptions10
): HttpEventSource {11
clientJob(client.loop, true)12
val state = ClientSseState(client, request, options, validateClientSseRequest(request, options))13
client.lock.withLock {14
if (client.closing)15
throw HttpClientClosedException()16
state.registered = true17
client.eventSources.add(state)18
}19
try {20
runClientSseOperation<Unit>(state) suspend {21
startClientSseTimer(state)22
openClientSseResponse(state)23
}24
} catch (error: Throwable) {25
recordClientSseFailure(state, error)26
startClientSseClose(state)27
awaitClientSseClose(state)28
throw client.lock.withLock { clientSseFailure(state)!! }29
}30
return HttpEventSource(state, state.info!!)31
}33
internal suspend fun readClientSse(state: ClientSseState): SseEvent? {34
val finished =35
state.client.lock.withLock {36
if (state.running)37
throw IllegalStateException(Some("an SSE operation is already active"))38
val failure = clientSseFailure(state)39
if (clientPresent(failure))40
throw failure!!41
state.finished42
}43
if (finished)44
return None45
return runClientSseOperation<SseEvent?>(state) suspend { receiveClientSse(state) }46
}48
private suspend fun <T> runClientSseOperation(state: ClientSseState, block: suspend () -> T): T {49
clientJob(state.client.loop, false)50
state.client.lock.withLock {51
if (state.running)52
throw IllegalStateException(Some("an SSE operation is already active"))53
val failure = clientSseFailure(state)54
if (clientPresent(failure))55
throw failure!!56
if (state.closing || state.closed)57
throw IoClosedException()58
state.running = true59
}60
var result: T? = None61
try {62
result =63
Some(64
context(state) {65
coroutineScope<T> {66
val scope = this68
state.client.lock.withLock { state.active = Some(scope.job) }69
val listener =70
scope.job.invokeOnCancellation {71
reason -> stopClientSse(state, reason)72
}73
try {74
state.requireActive();75
block()76
}77
catch (error: Throwable) {78
recordClientSseFailure(state, error);79
throw error80
}81
finally {82
listener.dispose()83
}84
}85
}86
)87
state.requireActive()88
} catch (error: Throwable) {89
recordClientSseFailure(state, error)90
}91
finally {92
state.client.lock.withLock {93
state.active = None;94
state.running = false95
}96
startClientSseClose(state)97
}98
if (state.client.lock.withLock { state.closing })99
awaitClientSseClose(state)100
val failure = state.client.lock.withLock { clientSseFailure(state) }101
if (clientPresent(failure))102
throw failure!!103
return result!!104
}106
internal fun finishClientSse(state: ClientSseState) {107
state.client.lock.withLock {108
state.finished = true;109
state.closing = true110
}111
}