Scoop API

scoop:scoop.compression:0.1.0

src/asyncio/close.scoop

Selected production source · src/asyncio/close.scoop

1package scoop.compression.asyncio
3import scoop.asyncio.*
4import scoop.compression.*
6internal suspend fun closeCompression(state: AsyncCompressionOwner) {
7 if (state.lock.withLock { state.closed }) return
8 val job = requireAsyncCompressionJob(state.loop, false)
9 suspendCoroutine<Unit> { continuation ->
10 val result: (Boolean, Job?) = state.lock.withLock {
11 if (state.closed) (true, None)
12 else {
13 state.closeWaiters.add(continuation)
14 if (!state.closing) { state.closing = true; state.closeJob = Some(job) }
15 (false, state.active)
16 }
17 }
18 val (closed, active) = result
19 if (closed) continuation.resume(Unit)
20 else {
21 when (active) { case Some(val value) -> value.cancel(); case None -> {} }
22 startCompressionClose(state)
23 }
24 }
27internal fun startCompressionClose(state: AsyncCompressionOwner) {
28 val start = state.lock.withLock {
29 if (!state.closing || state.running || state.cleanupStarted) false
30 else { state.cleanupStarted = true; true }
31 }
32 if (!start) return
33 val job = state.closeJob!!
34 val loop = state.loop
35 context(job) { context(loop) {
36 startCoroutine<Unit>(suspend {
37 var failure = compressionCleanup(None) { state.resources.close() }
38 when (state.owner) {
39 case Some(val owner) -> {
40 try { owner.close() }
41 catch (error: Throwable) { failure = Some(when (failure) {
42 case Some(val primary) -> ResourceUseException(primary, error)
43 case None -> error
44 }) }
45 }
46 case None -> {}
47 }
48 throwCompressionFailure(failure)
49 }, CompressionCloseCompletion(state))
50 } }
53private class CompressionCloseCompletion(val state: AsyncCompressionOwner) : Continuation<Unit> {
54 public override fun resume(value: Unit) { finish(None) }
55 public override fun resumeWithException(exception: Throwable) { finish(Some(exception)) }
57 private fun finish(error: Throwable?) {
58 val waiters = state.lock.withLock {
59 state.closed = true
60 val result = state.closeWaiters.toArray()
61 state.closeWaiters.clear()
62 result
63 }
64 for (waiter in waiters) {
65 when (error) { case Some(val failure) -> waiter.resumeWithException(failure); case None -> waiter.resume(Unit) }
66 }
67 }