Scoop API

scoop:scoop.asyncio:0.1.0

src/byte_transfer.scoop

Selected production source · src/byte_transfer.scoop

1package scoop.asyncio
3import scoop.platform.memory.NativeByteBuffer
4import scoop.platform.memory.NativeByteBorrow
5import scoop.platform.io.WriteZeroException
7private const val TRANSFER_IDLE: Long = 0L
9private const val TRANSFER_PENDING: Long = 1L
11private const val TRANSFER_PUBLISHING: Long = 2L
13private const val TRANSFER_STOPPED: Long = 3L
15private const val TRANSFER_COMPLETED: Long = 4L
17private const val TRANSFER_MASK: Long = 7L
19// The resource owns this slot; its direction gate serializes successive uses.
20internal abstract class ByteTransfer(loop: LoopOwner, protected val writing: Boolean):
21LoopOperation(loop, loop.nextOperation(), true), SuspendRegistration<Long> {
22 private val state = AtomicLong(TRANSFER_IDLE)
23 private val binding = AtomicLong(0L)
24 private var job: Job? = None
25 private var subscription: Disposable? = None
26 private var borrow: NativeByteBorrow? = None
27 private var continuation: Continuation<Long>? = None
28 private var selectedError: Throwable? = None
29 private var transferred: Long = 0L
30 private var completionError: Throwable? = None
31 // Only the owner touches the native phase, independently of result selection.
32 private var nativeActive: Boolean = false
33 private var delivering: Boolean = false
35 protected val borrowed: NativeByteBorrow get() = borrow!!
36 protected abstract fun acquire()
37 protected abstract fun release()
38 protected abstract fun closing(): Boolean
39 protected abstract fun start(pointer: Ptr<Unit>): IoStart
40 protected abstract fun cancelRequest(pointer: Ptr<Unit>)
41 protected abstract fun failure(result: IoResult, selected: Throwable?): Throwable?
43 fun prepare(buffer: NativeByteBuffer, count: Long, current: Job): ByteTransfer {
44 acquire()
45 try {
46 val previous = state.load(MemoryOrder.Acquire)
47 if (previous > Long.MAX_VALUE - 8L)
48 throw ArithmeticException()
49 borrow = Some(borrowTransfer(buffer, count, writing))
50 bind(current)
51 state.store(previous + 8L + TRANSFER_PENDING, MemoryOrder.Release)
52 // A cached listener can already have fired while this slot was idle.
53 if (current.isCancelled)
54 selectFailure(CancellationException())
55 return this
56 } catch (error: Throwable) {
57 val value = borrow
58 borrow = None
59 try {
60 when (value) {
61 case Some(val value) -> @Unsafe
62 {
63 value.complete(0L)
64 }
65 case None -> {}
66 }
67 } finally {
68 release()
69 }
70 throw error
71 }
72 }
74 private fun bind(current: Job) {
75 when (job) {
76 case Some(val previous) -> if (previous === current)
77 return
78 case None -> {}
79 }
80 val version = binding.load(MemoryOrder.Relaxed) + 1L
81 binding.store(version, MemoryOrder.Release)
82 subscription?.dispose()
83 subscription = None
84 job = None
85 val listener =
86 current.invokeOnCancellation {
87 error ->
88 val ticket = selectStop(error, version)
89 if (ticket != 0L)
90 queueCancellation(ticket)
91 }
92 subscription = Some(listener)
93 job = Some(current)
94 }
96 public final override fun register(continuation: Continuation<Long>) {
97 this.continuation = Some(continuation)
98 loop.submit(this)
99 }
101 private fun selectStop(error: Throwable, version: Long = 0L): Long {
102 val previous = state.load(MemoryOrder.Acquire)
103 if ((previous and TRANSFER_MASK) != TRANSFER_PENDING)
104 return 0L
105 if (version != 0L && binding.load(MemoryOrder.Acquire) != version)
106 return 0L
107 val ticket = previous - TRANSFER_PENDING
108 if (
109 !state.compareAndSet(
110 previous,
111 ticket + TRANSFER_PUBLISHING,
112 MemoryOrder.AcqRel,
113 MemoryOrder.Acquire
114 )
115 )
116 return 0L
117 selectedError = Some(error)
118 state.store(ticket + TRANSFER_STOPPED, MemoryOrder.Release)
119 return ticket
120 }
122 public final override fun selectFailure(error: Throwable): Boolean = selectStop(error) != 0L
124 public final override fun requestFailure(error: Throwable) {
125 val ticket = selectStop(error)
126 if (ticket != 0L)
127 queueCancellation(ticket)
128 }
130 private fun queueCancellation(ticket: Long) {
131 loop.post {
132 // The prior transfer may have retired and this slot may already be reused.
133 if (state.load(MemoryOrder.Acquire) == ticket + TRANSFER_STOPPED)
134 loop.cancel(id)
135 }
136 }
138 public final override fun run() {
139 if (delivering)
140 finish()
141 else
142 loop.beginOperation(this)
143 }
145 public final override fun begin(pointer: Ptr<Unit>) {
146 if (closing())
147 selectFailure(IoClosedException())
148 if (
149 (state.load(MemoryOrder.Acquire) and TRANSFER_MASK) !=
150 TRANSFER_PENDING ||
151 borrowed.length ==
152 0L
153 ) {
154 loop.complete(NativeEvent(id, IoResult.Bytes(0L)))
155 return
156 }
157 val result =
158 try {
159 start(pointer)
160 } catch (error: Throwable) {
161 selectFailure(error)
162 IoStart.Finished(NativeEvent(id, IoResult.Done))
163 }
164 when (result) {
165 case Pending -> nativeActive = true
166 case Finished(val event) -> loop.complete(event)
167 }
168 }
170 public final override fun cancelNative(pointer: Ptr<Unit>) {
171 if (nativeActive)
172 cancelRequest(pointer)
173 }
175 public final override fun complete(event: NativeEvent) {
176 nativeActive = false
177 var previous = state.load(MemoryOrder.Acquire)
178 while (true) {
179 val choice = previous and TRANSFER_MASK
180 if (choice == TRANSFER_PUBLISHING) {
181 previous = state.load(MemoryOrder.Acquire)
182 continue
183 }
184 if (choice != TRANSFER_PENDING && choice != TRANSFER_STOPPED)
185 throw IllegalStateException(Some("transfer completed without an active request"))
186 if (
187 state.compareAndSet(
188 previous,
189 (previous and TRANSFER_MASK.inv()) + TRANSFER_COMPLETED,
190 MemoryOrder.AcqRel,
191 MemoryOrder.Acquire
192 )
193 )
194 break
195 previous = state.load(MemoryOrder.Acquire)
196 }
197 val selected = selectedError
198 selectedError = None
199 transferred = resultProgress(event.result)
200 completionError =
201 try {
202 failure(event.result, selected)
203 } catch (error: Throwable) {
204 Some(error)
205 }
206 delivering = true
207 loop.enqueueReady(this)
208 }
210 private fun finish() {
211 val target = continuation!!
212 val value = borrowed
213 val count = transferred
214 val error = completionError
215 continuation = None
216 borrow = None
217 completionError = None
218 delivering = false
219 state.store(state.load(MemoryOrder.Relaxed) and TRANSFER_MASK.inv(), MemoryOrder.Release)
220 val result =
221 try {
222 try {
223 when (error) {
224 case Some(val error) -> throw error
225 case None -> {}
226 }
227 if (writing && count == 0L && value.length != 0L)
228 throw WriteZeroException()
229 count
230 } finally {
231 try {
232 @Unsafe
233 {
234 value.complete(count)
235 }
236 } finally {
237 release()
238 }
239 }
240 } catch (error: Throwable) {
241 target.resumeWithException(error)
242 return
243 }
244 // A direct continuation can immediately reuse the slot after release().
245 target.resume(result)
246 }
248 fun closeSlot() {
249 loop.forgetOperation(this)
250 subscription?.dispose()
251 subscription = None
252 job = None
253 }
256internal fun borrowTransfer(
257 buffer: NativeByteBuffer,
258 count: Long,
259 writing: Boolean
260): NativeByteBorrow {
261 @Unsafe
262 {
263 return if (writing)
264 buffer.borrowReadable(count)
265 else
266 buffer.borrowWritable(count)
267 }