scoop:scoop.http.asyncio:0.1.0
src/websocket/shutdown.scoop
Selected production source · src/websocket/shutdown.scoop
1
package scoop.http.asyncio3
import scoop.asyncio.*4
import scoop.http.*6
internal fun beginWsShutdown(state: WsState, value: WebSocketClose, waitForPeer: Boolean) {7
if (!present(state.shutdown)) state.shutdown = Some(WsShutdown(value, waitForPeer))8
else if (!waitForPeer) state.shutdown!!.waitForPeer = false9
if (present(state.incoming) && !state.incoming!!.life.complete) {10
val message = state.incoming!!11
message.discarded = true12
message.data = None13
message.offset = 0L14
}15
}17
internal suspend fun shutdownWs(state: WsState, value: WebSocketClose): WebSocketClose {18
checkWsCloseContext(state)19
val job = httpJob(state.loop, true)20
val listener = job.invokeOnCancellation { error ->21
state.lock.withLock { abortWs(state, Some(error)) }22
driveWs(state)23
}24
try {25
job.ensureActive()26
return suspendCoroutine<WebSocketClose> { continuation ->27
val wait = WsWait<WebSocketClose>(continuation)28
val actions = ArrayList<() -> Unit>()29
state.lock.withLock {30
if (state.closed) {31
if (wsClean(state)) succeedWsWait(wait, state.peerClose!!, actions)32
else failWsWait(wait, state.failure ?: wsClosed(state), actions)33
} else {34
state.shutdownWaiters.add(wait)35
if (!state.closing) beginWsShutdown(state, value, true)36
}37
Unit38
}39
for (action in actions) action()40
driveWs(state)41
}42
} finally { listener.dispose() }43
}45
internal fun advanceWsShutdown(state: WsState, actions: ArrayList<() -> Unit>): Boolean {46
if (!present(state.shutdown)) return false47
val shutdown = state.shutdown!!48
if (present(state.sentClose) && (!shutdown.waitForPeer || present(state.peerClose))) {49
abortWs(state, None)50
return true51
}52
if (shutdown.timerStarted) return false53
shutdown.timerStarted = true54
actions.add { startWsTimer(state) }55
return true56
}58
private fun startWsTimer(state: WsState) {59
val scope = state.lock.withLock { if (state.closing) None else state.ownerScope }60
if (!present(scope)) return61
val loop = state.loop62
try {63
context(loop) {64
val timer = scope!!.launch suspend {65
try {66
loop.sleep(state.options.closeTimeout)67
state.lock.withLock {68
if (!state.closing) abortWs(state, Some(WebSocketSessionException(WebSocketFailureKind.CloseTimeout,69
"the Close handshake timed out", state.peerClose)))70
Unit71
}72
driveWs(state)73
} catch (_: CancellationException) {}74
catch (error: Throwable) {75
state.lock.withLock { abortWs(state, Some(error)) }76
driveWs(state)77
}78
}79
val closed = state.lock.withLock { if (state.closing) true else { state.timer = Some(timer); false } }80
if (closed) timer.cancel()81
Unit82
}83
} catch (error: Throwable) {84
state.lock.withLock { abortWs(state, Some(error)) }85
driveWs(state)86
}87
}