Scoop API

scoop:scoop.http.asyncio:0.1.0

src/websocket/shutdown.scoop

Selected production source · src/websocket/shutdown.scoop

1package scoop.http.asyncio
3import scoop.asyncio.*
4import scoop.http.*
6internal 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 = false
9 if (present(state.incoming) && !state.incoming!!.life.complete) {
10 val message = state.incoming!!
11 message.discarded = true
12 message.data = None
13 message.offset = 0L
14 }
17internal 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 Unit
38 }
39 for (action in actions) action()
40 driveWs(state)
41 }
42 } finally { listener.dispose() }
45internal fun advanceWsShutdown(state: WsState, actions: ArrayList<() -> Unit>): Boolean {
46 if (!present(state.shutdown)) return false
47 val shutdown = state.shutdown!!
48 if (present(state.sentClose) && (!shutdown.waitForPeer || present(state.peerClose))) {
49 abortWs(state, None)
50 return true
51 }
52 if (shutdown.timerStarted) return false
53 shutdown.timerStarted = true
54 actions.add { startWsTimer(state) }
55 return true
58private fun startWsTimer(state: WsState) {
59 val scope = state.lock.withLock { if (state.closing) None else state.ownerScope }
60 if (!present(scope)) return
61 val loop = state.loop
62 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 Unit
71 }
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 Unit
82 }
83 } catch (error: Throwable) {
84 state.lock.withLock { abortWs(state, Some(error)) }
85 driveWs(state)
86 }