Scoop API

scoop:scoop.http.asyncio:0.1.0

src/message_io/close.scoop

Selected production source · src/message_io/close.scoop

1package scoop.http.asyncio
3import scoop.asyncio.*
5internal suspend fun <T> closeMessageIo(state: MessageIo<T>) {
6 if (state.lock.withLock { state.closed }) return
7 val job = httpJob(state.loop, false)
8 suspendCoroutine<Unit> { continuation ->
9 val result: (Boolean, Job?) = state.lock.withLock {
10 if (state.closed) (true, None)
11 else {
12 state.closeWaiters.add(continuation)
13 if (!state.closing) { state.closing = true; state.closeJob = Some(job) }
14 (false, state.active)
15 }
16 }
17 val (closed, active) = result
18 if (closed) continuation.resume(Unit)
19 else {
20 when (active) { case Some(val value) -> value.cancel(); case None -> {} }
21 startMessageClose(state)
22 }
23 }
26internal fun <T> startMessageClose(state: MessageIo<T>) {
27 val start = state.lock.withLock {
28 if (!state.closing || state.running || state.cleanupStarted) false
29 else { state.cleanupStarted = true; true }
30 }
31 if (!start) return
32 val job = state.closeJob!!
33 val loop = state.loop
34 context(job) { context(loop) {
35 startCoroutine<Unit>(suspend {
36 var failure = messageCleanup(None) { val cleanup = state.cleanup!!; cleanup() }
37 when (state.owner) {
38 case Some(val owner) -> {
39 try { owner.close() }
40 catch (error: Throwable) { failure = Some(when (failure) {
41 case Some(val primary) -> ResourceUseException(primary, error)
42 case None -> error
43 }) }
44 }
45 case None -> {}
46 }
47 when (failure) { case Some(val error) -> throw error; case None -> {} }
48 }, MessageCloseCompletion(state))
49 } }
52private class MessageCloseCompletion<T>(val state: MessageIo<T>) : Continuation<Unit> {
53 public override fun resume(value: Unit) { finish(None) }
54 public override fun resumeWithException(exception: Throwable) { finish(Some(exception)) }
55 private fun finish(failure: Throwable?) {
56 val waiters = state.lock.withLock {
57 state.closed = true
58 state.endpoint = None
59 state.owner = None
60 state.cleanup = None
61 state.closeJob = None
62 val result = state.closeWaiters.toArray()
63 state.closeWaiters.clear()
64 result
65 }
66 for (waiter in waiters) when (failure) {
67 case Some(val error) -> waiter.resumeWithException(error)
68 case None -> waiter.resume(Unit)
69 }
70 }
73internal fun messageCleanup(primary: Throwable?, block: () -> Unit): Throwable? {
74 try { block(); return primary }
75 catch (error: Throwable) { return Some(when (primary) {
76 case Some(val first) -> ResourceUseException(first, error)
77 case None -> error
78 }) }