Scoop API

scoop:scoop.asyncio:0.1.0

src/loop/loop_mailbox.scoop

Selected production source · src/loop/loop_mailbox.scoop

1package scoop.asyncio
3internal class LoopMailbox(private val owner: LoopOwner) {
4 private val lock: IoLock = IoLock()
5 private var accepting: Boolean = true
6 private var closeRequested: Boolean = false
7 private var closed: Boolean = false
8 private var messages: ArrayList<CoroutineScope.() -> Unit> =
9 ArrayList<CoroutineScope.() -> Unit>()
10 private var waiting: Continuation<Unit>? = None
12 val isClosed: Boolean get() = lock.withLock { closed }
14 fun post(block: CoroutineScope.() -> Unit): Boolean {
15 val accepted =
16 lock.withLock {
17 if (!accepting)
18 false
19 else {
20 messages.add(block);
21 true
22 }
23 }
24 if (accepted)
25 owner.post { signal() }
26 return accepted
27 }
29 fun requestClose() {
30 val first =
31 lock.withLock {
32 if (!accepting)
33 false
34 else {
35 accepting = false
36 closeRequested = true
37 messages = ArrayList<CoroutineScope.() -> Unit>()
38 true
39 }
40 }
41 if (first)
42 owner.post { owner.cancelRoot() }
43 }
45 fun signal() {
46 when (waiting) {
47 case Some(val continuation) -> {
48 waiting = None
49 owner.enqueueReady { continuation.resume(Unit) }
50 }
51 case None -> {}
52 }
53 }
55 suspend fun run(scope: CoroutineScope) {
56 owner.bindRoot(scope.job)
57 val subscription = scope.job.invokeOnCancellation { owner.post { signal() } }
58 try {
59 while (true) {
60 suspendCoroutine<Unit> { continuation -> waiting = Some(continuation) }
61 scope.job.ensureActive()
62 val batch =
63 lock.withLock {
64 val pending = messages
65 messages = ArrayList<CoroutineScope.() -> Unit>()
66 pending
67 }
68 for (block in batch) {
69 if (!lock.withLock { accepting })
70 break
71 scope.job.ensureActive()
72 block(scope)
73 }
74 }
75 } finally {
76 stop()
77 subscription.dispose()
78 }
79 }
81 private fun stop() {
82 lock.withLock {
83 accepting = false
84 messages = ArrayList<CoroutineScope.() -> Unit>()
85 }
86 }
88 fun finish(error: Throwable?) {
89 stop()
90 val requested = lock.withLock { closeRequested }
91 val result =
92 when (error) {
93 case Some(val value) -> if (requested && value is CancellationException)
94 None
95 else
96 error
97 case None -> None
98 }
99 owner.finishRoot(result)
100 }
102 fun didClose() {
103 lock.withLock { closed = true }
104 }
107internal class SessionCompletion(private val mailbox: LoopMailbox): Continuation<Unit> {
108 public override fun resume(value: Unit) {
109 mailbox.finish(None)
110 }
111 public override fun resumeWithException(exception: Throwable) {
112 mailbox.finish(Some(exception))
113 }