scoop:scoop.tls.asyncio:0.1.0
src/close.scoop
Selected production source · src/close.scoop
1
package scoop.tls.asyncio3
import scoop.asyncio.IoClosedException5
internal suspend fun closeConnection(state: TlsConnection) {6
if (state.lock.withLock { state.closed }) return7
val job = requireJob(state.loop, false)8
suspendCoroutine<Unit> { continuation ->9
val closed = state.lock.withLock {10
if (state.closed) true11
else {12
state.closeWaiters.add(continuation)13
if (!state.closing) state.closeJob = job14
terminate(state, None, IoClosedException())15
false16
}17
}18
if (closed) continuation.resume(Unit)19
else drive(state)20
}21
}23
internal fun advanceClose(state: TlsConnection, actions: ArrayList<() -> Unit>): Boolean {24
if (!state.transportClosing) {25
state.transportClosing = true26
actions.add { startClose(state) }27
return true28
}29
if (!state.transportClosed || state.inputBusy || state.outputBusy || state.verificationBusy) return false30
try { state.engine.close() }31
catch (error: Throwable) { addCloseFailure(state, error) }32
val pending = requests(state)33
for (entry in pending) {34
try { finishBorrow(entry) }35
catch (error: Throwable) { addCloseFailure(state, error) }36
}37
try { state.input.close() }38
catch (error: Throwable) { addCloseFailure(state, error) }39
try { state.output.close() }40
catch (error: Throwable) { addCloseFailure(state, error) }41
state.closed = true42
for (entry in pending) {43
if (present(state.closeFailure)) entry.failure = Some(when (entry.failure) {44
case Some(val primary) -> ResourceUseException(primary, state.closeFailure!!)45
case None -> state.closeFailure!!46
})47
releaseRequest(state, entry, actions)48
}49
val failure = state.closeFailure50
for (waiter in state.closeWaiters) {51
actions.add {52
when (failure) {53
case Some(val error) -> waiter.resumeWithException(error)54
case None -> waiter.resume(Unit)55
}56
}57
}58
state.closeWaiters.clear()59
return true60
}62
private fun startClose(state: TlsConnection) {63
val job = state.closeJob64
val loop = state.loop65
context(job) { context(loop) {66
startCoroutine<Unit>(suspend { state.owner.close() }, CloseCompletion(state))67
} }68
}70
private class CloseCompletion(val state: TlsConnection) : Continuation<Unit> {71
public override fun resume(value: Unit) { finish(None) }72
public override fun resumeWithException(exception: Throwable) { finish(Some(exception)) }73
private fun finish(failure: Throwable?) {74
state.lock.withLock {75
state.transportClosed = true76
if (present(failure)) addCloseFailure(state, failure!!)77
Unit78
}79
drive(state)80
}81
}83
private fun addCloseFailure(state: TlsConnection, error: Throwable) {84
state.closeFailure = Some(when (state.closeFailure) {85
case Some(val primary) -> ResourceUseException(primary, error)86
case None -> error87
})88
}90
internal fun releaseUnadopted(state: TlsConnection) {91
try { state.engine.close() }92
finally { try { state.input.close() } finally { state.output.close() } }93
}