Scoop API

scoop:scoop.asyncio:0.1.0

src/loop/loop_owner.scoop

Selected production source · src/loop/loop_owner.scoop

1package scoop.asyncio
3import scoop.collections.HashMap
5internal interface LoopWorkers {
6 fun nextOwner(): LoopOwner
7 fun isCurrentWorker(index: Int): Boolean
8}
10internal interface LoopResource {
11 fun closeFromLoop()
14internal class LoopOwner(
15 private val runtime: LoopWorkers? = None,
16 private val worker: Int = -1
17) {
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? = None
26 private val driver: LoopDriver = LoopDriver()
27 private var pointer: Ptr<Unit>? = None
28 private var execution: LoopExecution? = None
29 private val nextId = AtomicLong(1L)
30 private var root: Job? = None
31 private var backendFailed: Boolean = false
32 private val rootEnded = AtomicBoolean(false)
33 private var failure: Throwable? = None
34 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 = false
38 internal var pendingTransfers: ((LoopOwner) -> Unit)? = None
39 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 @Unsafe
45 {
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.pointer
51 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 error
62 }
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().executor
72 fun connectionOwner(): LoopOwner =
73 when (runtime) {
74 case Some(val runtime) -> runtime.nextOwner()
75 case None -> this
76 }
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.executor
95 }
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 job
117 }
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 return
130 }
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 id
145 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 return
156 }
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 = true
166 }
167 operation.begin(pointer!!)
168 }
170 fun flushTransfers() {
171 val flush = pendingTransfers ?: return
172 pendingTransfers = None
173 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 = false
209 }
210 operation.complete(event)
211 }
213 fun forgetOperation(operation: LoopOperation) {
214 if (operation.registered) {
215 operations.remove(operation.id)
216 operation.registered = false
217 }
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 = 0L
228 while (index < resources.size) {
229 if (resources[index] === resource) {
230 resources.removeAt(index);
231 return
232 }
233 index += 1L
234 }
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 -> error
244 }
245 )
246 }
247 }
249 fun startCleanup() {
250 if (cleaning || !rootEnded.load(MemoryOrder.Acquire) || !executor.isTerminated)
251 return
252 cleaning = true
253 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 backendFailed
264 }
265 if (failed)
266 job.cancel()
267 }
269 fun poll(native: Ptr<Unit>, wait: Boolean) {
270 flushTransfers()
271 @Unsafe
272 {
273 val status = nativeLoopPoll(native, wait)
274 if (status.code != 0) {
275 val failed =
276 lock.withLock {
277 if (backendFailed)
278 false
279 else {
280 backendFailed = true;
281 true
282 }
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 = error
297 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 = None
304 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 = localCommands
314 localCommands = empty
315 return batch
316 }
318 fun takeReady(empty: ArrayList<LoopWork>): ArrayList<LoopWork> {
319 val batch = ready
320 ready = empty
321 return batch
322 }
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 != 0L
332 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 0L
346 fun stopIfDrained(native: Ptr<Unit>): Boolean {
347 if (!managedIdle())
348 return false
349 @Unsafe
350 {
351 if (!nativeLoopIdle(native))
352 return false
353 }
354 val state = currentExecution()
355 if (!state.stopPoolIfNeeded())
356 return false
357 if (!managedIdle() || !inbox.closeIfEmpty())
358 return false
359 running.store(false, MemoryOrder.Release)
360 pointer = None
361 return true
362 }
364 fun destroy(native: Ptr<Unit>): Throwable? {
365 @Unsafe
366 {
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 }