Scoop API

scoop:scoop.http.asyncio:0.1.0

src/websocket/operation.scoop

Selected production source · src/websocket/operation.scoop

1package scoop.http.asyncio
3internal fun wsClosed(state: WsState): WebSocketSessionException =
4 WebSocketSessionException(WebSocketFailureKind.Closed, "the session is closing or closed", state.peerClose)
6internal fun wsInterrupted(state: WsState): WebSocketSessionException =
7 WebSocketSessionException(WebSocketFailureKind.InterruptedMessage, "closing interrupted an unfinished message", state.peerClose)
9internal fun wsOpen(state: WsState) {
10 if (state.closing || present(state.shutdown)) throw (state.failure ?: wsClosed(state))
13internal fun wsClean(state: WsState): Boolean =
14 !present(state.failure) && present(state.peerClose) && present(state.sentClose)
16internal suspend fun <P, T> wsOperation(state: WsState, reading: Boolean, prepare: () -> P,
17 block: suspend (P) -> T): T {
18 val job = httpJob(state.loop, true)
19 val prepared = state.lock.withLock {
20 if (if (reading) state.reading else state.writing)
21 throw IllegalStateException(Some("WebSocket direction is busy"))
22 val value = prepare()
23 if (reading) state.reading = true else state.writing = true
24 value
25 }
26 val listener = job.invokeOnCancellation { error ->
27 state.lock.withLock { abortWs(state, Some(error)) }
28 driveWs(state)
29 }
30 var result: T? = None
31 var failed: Throwable? = None
32 try {
33 job.ensureActive()
34 result = Some(block(prepared))
35 } catch (error: Throwable) {
36 failed = Some(error)
37 state.lock.withLock { recordWsOperationFailure(state, error) }
38 } finally {
39 listener.dispose()
40 state.lock.withLock { if (reading) state.reading = false else state.writing = false }
41 driveWs(state)
42 }
43 if (present(failed) || state.lock.withLock { state.closing }) {
44 try { awaitWsClosed(state) } catch (_: Throwable) {}
45 val failure = state.lock.withLock { state.failure }
46 if (present(failure)) throw failure!!
47 if (present(failed)) throw (if (failed!! is CancellationException) wsClosed(state) else failed!!)
48 }
49 return result!!
52internal suspend fun failWsOperation(state: WsState, error: Throwable): Nothing {
53 state.lock.withLock { recordWsOperationFailure(state, error) }
54 driveWs(state)
55 try { awaitWsClosed(state) } catch (_: Throwable) {}
56 throw state.lock.withLock { state.failure ?: error }
59internal suspend fun closeWsLife(state: WsState, life: WsLife) {
60 if (!state.lock.withLock { state.closed }) httpJob(state.loop, false)
61 val actions = ArrayList<() -> Unit>()
62 val incomplete = state.lock.withLock {
63 life.closed = true
64 detachWsLife(life, actions)
65 !life.complete
66 }
67 for (action in actions) action()
68 if (incomplete) closeWs(state)