scoop:scoop.compression:0.1.0
src/asyncio/owner.scoop
Selected production source · src/asyncio/owner.scoop
1
package scoop.compression.asyncio3
import scoop.asyncio.*4
import scoop.compression.*6
private enum CompressionOutcome<T> {7
Value(val value: T), Error(val error: Throwable)8
}10
internal 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
}21
}23
internal class AsyncCompressionOwner(24
val resources: CompressionIoResources,25
val owner: AsyncCloseable?,26
val loop: EventLoop27
) {28
val lock: CompressionAsyncLock = CompressionAsyncLock()29
var running: Boolean = false30
var active: Job? = None31
var closing: Boolean = false32
var closed: Boolean = false33
var cleanupStarted: Boolean = false34
var closeJob: Job? = None35
val closeWaiters: ArrayList<Continuation<Unit>> = ArrayList<Continuation<Unit>>()36
private var operationFailure: Throwable? = None37
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 = true49
}50
var advancing = false51
try {52
validate()53
advancing = true54
val outcome =55
coroutineScope<CompressionOutcome<T>> {56
val scope = this58
val stop =59
this @AsyncCompressionOwner.lock.withLock {60
this @AsyncCompressionOwner.active = Some(scope.job)61
this @AsyncCompressionOwner.closing62
}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 error75
}76
} catch (error: Throwable) {77
if (advancing)78
lock.withLock { operationFailure = Some(error) }79
throw error80
} finally {81
lock.withLock {82
running = false;83
active = None84
}85
startCompressionClose(this)86
}87
}88
}90
internal 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 job100
}