Scoop API

scoop:scoop.compression:0.1.0

src/asyncio/owner.scoop

Selected production source · src/asyncio/owner.scoop

1package scoop.compression.asyncio
3import scoop.asyncio.*
4import scoop.compression.*
6private enum CompressionOutcome<T> {
7 Value(val value: T), Error(val error: Throwable)
8}
10internal class CompressionAsyncLock {
11 private val held: AtomicBoolean = AtomicBoolean(false)
12 fun <T> withLock(block: () -> T): T {
13 while (!held.compareAndSet(false, true, MemoryOrder.Acquire, MemoryOrder.Relaxed)) {}
14 try {
15 return block()
16 }
17 finally {
18 held.store(false, MemoryOrder.Release)
19 }
20 }
23internal class AsyncCompressionOwner(
24 val resources: CompressionIoResources,
25 val owner: AsyncCloseable?,
26 val loop: EventLoop
27) {
28 val lock: CompressionAsyncLock = CompressionAsyncLock()
29 var running: Boolean = false
30 var active: Job? = None
31 var closing: Boolean = false
32 var closed: Boolean = false
33 var cleanupStarted: Boolean = false
34 var closeJob: Job? = None
35 val closeWaiters: ArrayList<Continuation<Unit>> = ArrayList<Continuation<Unit>>()
36 private var operationFailure: Throwable? = None
37 val failure: Throwable? get() = lock.withLock { operationFailure }
39 suspend fun <T> operation(validate: () -> Unit, block: suspend () -> T): T {
40 requireAsyncCompressionJob(loop, true)
41 lock.withLock {
42 if (closing || closed)
43 throw IoClosedException()
44 if (compressionPresent(operationFailure))
45 throw IllegalStateException(Some("compression stream has failed"))
46 if (running)
47 throw IllegalStateException(Some("compression stream is already in use"))
48 running = true
49 }
50 var advancing = false
51 try {
52 validate()
53 advancing = true
54 val outcome =
55 coroutineScope<CompressionOutcome<T>> {
56 val scope = this
58 val stop =
59 this @AsyncCompressionOwner.lock.withLock {
60 this @AsyncCompressionOwner.active = Some(scope.job)
61 this @AsyncCompressionOwner.closing
62 }
63 if (stop)
64 scope.job.cancel()
65 try {
66 ensureActive()
67 CompressionOutcome.Value(block())
68 } catch (error: Throwable) {
69 CompressionOutcome.Error(error)
70 }
71 }
72 return when (outcome) {
73 case Value(val value) -> value;
74 case Error(val error) -> throw error
75 }
76 } catch (error: Throwable) {
77 if (advancing)
78 lock.withLock { operationFailure = Some(error) }
79 throw error
80 } finally {
81 lock.withLock {
82 running = false;
83 active = None
84 }
85 startCompressionClose(this)
86 }
87 }
90internal fun requireAsyncCompressionJob(loop: EventLoop, cancellable: Boolean): Job {
91 if (currentEventLoop() !== loop)
92 throw IllegalStateException(Some("compression stream belongs to another event loop"))
93 val job =
94 currentJobOrNone() ?: throw IllegalStateException(Some("compression I/O requires a Job"))
95 if (job.isCompleted)
96 throw IllegalStateException(Some("compression I/O requires an active Job"))
97 if (cancellable)
98 job.ensureActive()
99 return job