scoop:scoop.asyncio:0.1.0
src/loop/loop_owner.scoop
Selected production source · src/loop/loop_owner.scoop
1
package scoop.asyncio3
import scoop.collections.HashMap5
internal interface LoopWorkers {6
fun nextOwner(): LoopOwner7
fun isCurrentWorker(index: Int): Boolean8
}10
internal interface LoopResource {11
fun closeFromLoop()12
}14
internal class LoopOwner(15
private val runtime: LoopWorkers? = None,16
private val worker: Int = -117
) {18
// Root results use this lock; I/O publication has its own parking mutex.19
private val lock: IoLock = IoLock()20
private val inbox = LoopInbox()21
private var localCommands = ArrayList<LoopWork>()22
private val published = AtomicBoolean(false)23
private val running = AtomicBoolean(false)24
// Initialized before publication and retained unchanged through shutdown.25
private var binding: EventLoop? = None26
private val driver: LoopDriver = LoopDriver()27
private var pointer: Ptr<Unit>? = None28
private var execution: LoopExecution? = None29
private val nextId = AtomicLong(1L)30
private var root: Job? = None31
private var backendFailed: Boolean = false32
private val rootEnded = AtomicBoolean(false)33
private var failure: Throwable? = None34
private val operations: HashMap<Long, LoopOperation> = HashMap<Long, LoopOperation>()35
private val resources: ArrayList<LoopResource> = ArrayList<LoopResource>()36
private val timers = LoopTimers(this)37
private var cleaning: Boolean = false38
internal var pendingTransfers: ((LoopOwner) -> Unit)? = None39
private var ready: ArrayList<LoopWork> = ArrayList<LoopWork>()41
fun open(loop: EventLoop, config: LoopBlockingConfig): Ptr<Unit> {42
val state = prepareLoopExecution(this, config)43
try {44
@Unsafe45
{46
val created = nativeLoopCreate()47
if (created.status.code != 0)48
throw backendFailure("create event loop", created.status)49
binding = Some(loop)50
pointer = created.pointer51
execution = Some(state)52
inbox.open(created.pointer!!)53
published.store(true, MemoryOrder.Release)54
running.store(true, MemoryOrder.Release)55
state.observeTermination()56
return created.pointer!!57
}58
} catch (error: Throwable) {59
if (state.owned)60
state.pool.use { _ -> throw error }61
throw error62
}63
}65
private fun currentExecution(): LoopExecution {66
if (!published.load(MemoryOrder.Acquire))67
throw IllegalStateException(Some("event loop is not running"))68
return execution!!69
}71
val executor: LoopExecutor get() = currentExecution().executor72
fun connectionOwner(): LoopOwner =73
when (runtime) {74
case Some(val runtime) -> runtime.nextOwner()75
case None -> this76
}78
fun nativePointer(): Ptr<Unit> {79
if (!running.load(MemoryOrder.Acquire))80
throw IllegalStateException(Some("event loop is not running"))81
return pointer!!82
}84
fun dispatchBlocking(native: Ptr<Unit>) {85
dispatchNativeWork(native, currentExecution().pool)86
}88
fun activeExecutor(): CoroutineExecutor {89
if (!running.load(MemoryOrder.Acquire))90
throw IllegalStateException(Some("event loop is not running"))91
val state = currentExecution()92
if (state.executor.isTerminated)93
throw IllegalStateException(Some("event loop executor has terminated"))94
return state.executor95
}97
fun wakeExecution() {98
inbox.wake()99
}101
fun enqueueExecution(command: () -> Unit) {102
inbox.post(LoopWork.Callback(command), true)103
}105
fun requireJob(cancellable: Boolean = true): Job {106
if (!running.load(MemoryOrder.Acquire))107
throw IllegalStateException(Some("event loop is not running"))108
val expected = binding!!109
if (!hasEventLoop() || currentEventLoop() !== expected)110
throw IllegalStateException(Some("wrong event loop"))111
val job = currentJobOrNone() ?: throw IllegalStateException(Some("I/O requires a Job"))112
if (job.isCompleted)113
throw IllegalStateException(Some("I/O requires an active Job"))114
if (cancellable)115
job.ensureActive()116
return job117
}119
fun post(command: () -> Unit) {120
postWork(LoopWork.Callback(command))121
}123
private fun postWork(command: LoopWork) {124
when (runtime) {125
case Some(val runtime) -> if (126
runtime.isCurrentWorker(worker) && running.load(MemoryOrder.Acquire)127
) {128
localCommands.add(command)129
return130
}131
case None -> {}132
}133
inbox.post(command)134
}136
fun nextOperation(): Long {137
if (!running.load(MemoryOrder.Acquire))138
throw IllegalStateException(Some("event loop is not running"))139
var id = nextId.load(MemoryOrder.Relaxed)140
while (true) {141
if (id == Long.MAX_VALUE)142
throw ArithmeticException()143
if (nextId.compareAndSet(id, id + 1L, MemoryOrder.Relaxed, MemoryOrder.Relaxed))144
return id145
id = nextId.load(MemoryOrder.Relaxed)146
}147
}149
fun submit(operation: LoopOperation) {150
when (runtime) {151
case Some(val runtime) -> if (152
runtime.isCurrentWorker(worker) && running.load(MemoryOrder.Acquire)153
) {154
beginOperation(operation)155
return156
}157
case None -> {}158
}159
inbox.post(LoopWork.Operation(operation))160
}162
fun beginOperation(operation: LoopOperation) {163
if (!operation.registered) {164
operations.put(operation.id, operation)165
operation.registered = true166
}167
operation.begin(pointer!!)168
}170
fun flushTransfers() {171
val flush = pendingTransfers ?: return172
pendingTransfers = None173
flush(this)174
}176
fun enqueueReady(action: () -> Unit) {177
ready.add(LoopWork.Callback(action))178
}180
fun enqueueReady(operation: LoopOperation) {181
ready.add(LoopWork.Operation(operation))182
}184
fun scheduleTimer(timer: LoopTimer) {185
post { timers.add(timer) }186
}188
fun cancelTimer(timer: LoopTimer) {189
post { timers.cancel(timer) }190
}192
fun advanceTimers() {193
timers.advance()194
}196
fun cancel(id: Long) {197
flushTransfers()198
when (operations[id]) {199
case Some(val operation) -> operation.cancelNative(pointer!!)200
case None -> {}201
}202
}204
fun complete(event: NativeEvent) {205
val operation = operations[event.id]!!206
if (!operation.retained) {207
operations.remove(event.id)208
operation.registered = false209
}210
operation.complete(event)211
}213
fun forgetOperation(operation: LoopOperation) {214
if (operation.registered) {215
operations.remove(operation.id)216
operation.registered = false217
}218
}220
fun retain(resource: LoopResource) {221
resources.add(resource)222
if (cleaning)223
resource.closeFromLoop()224
}226
fun forget(resource: LoopResource) {227
var index = 0L228
while (index < resources.size) {229
if (resources[index] === resource) {230
resources.removeAt(index);231
return232
}233
index += 1L234
}235
}237
fun cleanupFailed(error: Throwable) {238
lock.withLock {239
failure =240
Some(241
when (failure) {242
case Some(val primary) -> ResourceUseException(primary, error)243
case None -> error244
}245
)246
}247
}249
fun startCleanup() {250
if (cleaning || !rootEnded.load(MemoryOrder.Acquire) || !executor.isTerminated)251
return252
cleaning = true253
timers.close()254
val owned = Array<LoopResource>(resources.size) { index -> resources[index] }255
for (resource in owned)256
resource.closeFromLoop()257
}259
fun bindRoot(job: Job) {260
val failed =261
lock.withLock {262
root = Some(job)263
backendFailed264
}265
if (failed)266
job.cancel()267
}269
fun poll(native: Ptr<Unit>, wait: Boolean) {270
flushTransfers()271
@Unsafe272
{273
val status = nativeLoopPoll(native, wait)274
if (status.code != 0) {275
val failed =276
lock.withLock {277
if (backendFailed)278
false279
else {280
backendFailed = true;281
true282
}283
}284
if (failed) {285
cleanupFailed(backendFailure("drive event loop", status))286
val job = lock.withLock { root }287
job?.cancel()288
}289
}290
}291
}293
fun finishRoot(error: Throwable?) {294
lock.withLock {295
when (failure) {296
case None -> failure = error297
case Some(val primary) -> when (error) {298
case Some(val next) -> if (!(next is CancellationException))299
failure = Some(ResourceUseException(primary, next))300
case None -> {}301
}302
}303
root = None304
rootEnded.store(true, MemoryOrder.Release)305
}306
currentExecution().finishRoot()307
inbox.wake()308
}310
fun takeCommands(empty: ArrayList<LoopWork>): ArrayList<LoopWork> = inbox.take(empty)312
fun takeLocalCommands(empty: ArrayList<LoopWork>): ArrayList<LoopWork> {313
val batch = localCommands314
localCommands = empty315
return batch316
}318
fun takeReady(empty: ArrayList<LoopWork>): ArrayList<LoopWork> {319
val batch = ready320
ready = empty321
return batch322
}324
fun cancelRoot() {325
val job = lock.withLock { root }326
job?.cancel()327
}329
fun hasQueuedWork(): Boolean =330
localCommands.size != 0L || inbox.hasCommands() || ready.size != 0L332
private fun managedIdle(): Boolean =333
rootEnded.load(MemoryOrder.Acquire) &&334
executor.isTerminated &&335
localCommands.size ==336
0L &&337
!inbox.hasCommands() &&338
ready.size ==339
0L &&340
operations.size ==341
0L &&342
timers.isEmpty &&343
resources.size ==344
0L346
fun stopIfDrained(native: Ptr<Unit>): Boolean {347
if (!managedIdle())348
return false349
@Unsafe350
{351
if (!nativeLoopIdle(native))352
return false353
}354
val state = currentExecution()355
if (!state.stopPoolIfNeeded())356
return false357
if (!managedIdle() || !inbox.closeIfEmpty())358
return false359
running.store(false, MemoryOrder.Release)360
pointer = None361
return true362
}364
fun destroy(native: Ptr<Unit>): Throwable? {365
@Unsafe366
{367
val status = nativeLoopDestroy(native)368
if (status.code != 0)369
cleanupFailed(backendFailure("close event loop", status))370
}371
val state = currentExecution()372
try {373
state.joinOwnedPool()374
}375
catch (error: Throwable) {376
cleanupFailed(error)377
}378
return lock.withLock { failure }379
}381
fun pump(native: Ptr<Unit>): Boolean = driver.pump(this, native)382
fun drive(native: Ptr<Unit>) {383
driver.drive(this, native)384
}385
}