forked from monix/monix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TaskRunLoop.scala
621 lines (548 loc) · 21.1 KB
/
TaskRunLoop.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/*
* Copyright (c) 2014-2017 by The Monix Project Developers.
* See the project homepage at: https://monix.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monix.eval.internal
import monix.eval.Task.{Async, Context, Error, Eval, FlatMap, FrameIndex, MemoizeSuspend, Now, Suspend, fromTry}
import monix.eval.{Callback, Task}
import monix.execution.atomic.AtomicAny
import monix.execution.cancelables.StackedCancelable
import monix.execution.internal.collection.ArrayStack
import monix.execution.misc.{Local, NonFatal}
import monix.execution.schedulers.TrampolinedRunnable
import monix.execution.{Cancelable, CancelableFuture, ExecutionModel, Scheduler}
import scala.annotation.tailrec
import scala.concurrent.Promise
import scala.util.{Failure, Success, Try}
private[eval] object TaskRunLoop {
private type Current = Task[Any]
private type Bind = Any => Task[Any]
private type CallStack = ArrayStack[Bind]
// We always start from 1
final def frameStart(em: ExecutionModel): FrameIndex =
em.nextFrameIndex(0)
/** Creates a new [[CallStack]] */
private def createCallStack(): CallStack =
ArrayStack(8)
/** Internal utility, for forcing an asynchronous boundary in the
* trampoline loop.
*/
def restartAsync[A](
source: Task[A],
context: Context,
cb: Callback[A],
bindCurrent: Bind,
bindRest: CallStack): Unit = {
val savedLocals =
if (context.options.localContextPropagation) Local.getContext()
else null
if (!context.shouldCancel) {
context.scheduler.executeAsync { () =>
// Resetting the frameRef, as a real asynchronous boundary happened
context.frameRef.reset()
// Transporting the current context if localContextPropagation == true.
Local.bind(savedLocals) {
startWithCallback(source, context, cb, bindCurrent, bindRest, 1)
}
}
}
}
/** Logic for finding the next `Transformation` reference,
* meant for handling errors in the run-loop.
*/
private def findErrorHandler(bFirst: Bind, bRest: CallStack): Transformation[Any, Task[Any]] = {
var result: Transformation[Any, Task[Any]] = null
var cursor = bFirst
var continue = true
while (continue) {
if (cursor != null && cursor.isInstanceOf[Transformation[_, _]]) {
result = cursor.asInstanceOf[Transformation[Any, Task[Any]]]
continue = false
} else {
cursor = if (bRest ne null) bRest.pop() else null
continue = cursor != null
}
}
result
}
private def popNextBind(bFirst: Bind, bRest: CallStack): Bind = {
if ((bFirst ne null) && !bFirst.isInstanceOf[Transformation.OnError[_]])
bFirst
else if (bRest ne null) {
var cursor: Bind = null
do { cursor = bRest.pop() }
while (cursor != null && cursor.isInstanceOf[Transformation.OnError[_]])
cursor
} else {
null
}
}
/** Internal utility, starts or resumes evaluation of
* the run-loop from where it left off.
*
* The `frameIndex=1` default value ensures that the
* first cycle of the trampoline gets executed regardless of
* the `ExecutionModel`.
*/
def startWithCallback[A](
source: Task[A],
context: Context,
cb: Callback[A],
bindCurrent: Bind,
bindRest: CallStack,
frameIndex: FrameIndex): Unit = {
final class RestartCallback(context: Context, callback: Callback[Any]) extends Callback[Any] {
private[this] var canCall = false
private[this] var bFirst: Bind = _
private[this] var bRest: CallStack = _
private[this] val runLoopIndex = context.frameRef
private[this] val withLocal = context.options.localContextPropagation
private[this] var savedLocals: Local.Context = _
def prepare(bindCurrent: Bind, bindRest: CallStack): Unit = {
canCall = true
this.bFirst = bindCurrent
this.bRest = bindRest
if (withLocal)
savedLocals = Local.getContext()
}
def onSuccess(value: Any): Unit =
if (canCall) {
canCall = false
Local.bind(savedLocals) {
loop(Now(value), context.executionModel, callback, this, bFirst, bRest, runLoopIndex())
}
}
def onError(ex: Throwable): Unit =
if (canCall) {
canCall = false
Local.bind(savedLocals) {
loop(Error(ex), context.executionModel, callback, this, bFirst, bRest, runLoopIndex())
}
} else {
context.scheduler.reportFailure(ex)
}
override def toString(): String =
s"RestartCallback($context, $callback)@${hashCode()}"
}
def executeOnFinish(
em: ExecutionModel,
cb: Callback[Any],
rcb: RestartCallback,
bFirst: Bind,
bRest: CallStack,
register: (Context, Callback[Any]) => Unit,
nextFrame: FrameIndex): Unit = {
if (!context.shouldCancel) {
// We are going to resume the frame index from where we left,
// but only if no real asynchronous execution happened. So in order
// to detect asynchronous execution, we are reading a thread-local
// variable that's going to be reset in case of a thread jump.
// Obviously this doesn't work for Javascript or for single-threaded
// thread-pools, but that's OK, as it only means that in such instances
// we can experience more async boundaries and everything is fine for
// as long as the implementation of `Async` tasks are triggering
// a `frameRef.reset` on async boundaries.
context.frameRef := nextFrame
// rcb reference might be null, so initializing
val restartCallback = if (rcb != null) rcb else new RestartCallback(context, cb)
restartCallback.prepare(bFirst, bRest)
register(context, restartCallback)
}
}
@tailrec def loop(
source: Current,
em: ExecutionModel,
cb: Callback[Any],
rcb: RestartCallback,
bFirst: Bind,
bRest: CallStack,
frameIndex: FrameIndex): Unit = {
if (frameIndex != 0) source match {
case ref @ FlatMap(fa, _, _) =>
var callStack: CallStack = bRest
val bindNext = ref.bind()
if (bFirst ne null) {
if (callStack eq null) callStack = createCallStack()
callStack.push(bFirst)
}
// Next iteration please
loop(fa, em, cb, rcb, bindNext, callStack, frameIndex)
case Now(value) =>
popNextBind(bFirst, bRest) match {
case null => cb.onSuccess(value)
case bind =>
val fa = try bind(value) catch { case NonFatal(ex) => Error(ex) }
// Given a flatMap evaluation just happened, must increment the index
val nextFrame = em.nextFrameIndex(frameIndex)
// Next iteration please
loop(fa, em, cb, rcb, null, bRest, nextFrame)
}
case Eval(thunk) =>
var streamErrors = true
var nextState: Current = null
try {
val value = thunk()
streamErrors = false
popNextBind(bFirst, bRest) match {
case null => cb.onSuccess(value)
case bind =>
nextState = try bind(value) catch { case NonFatal(ex) => Error(ex) }
}
} catch {
case NonFatal(ex) if streamErrors =>
nextState = Error(ex)
}
if (nextState ne null) {
// Given a flatMap evaluation just happened, must increment the index
val nextFrame = em.nextFrameIndex(frameIndex)
// Next iteration please
val nextBFirst = if (streamErrors) bFirst else null
loop(nextState, em, cb, rcb, nextBFirst, bRest, nextFrame)
}
case Suspend(thunk) =>
// Next iteration please
val fa = try thunk() catch { case NonFatal(ex) => Error(ex) }
loop(fa, em, cb, rcb, bFirst, bRest, frameIndex)
case Error(ex) =>
findErrorHandler(bFirst, bRest) match {
case null => cb.onError(ex)
case bind =>
val fa = try bind.error(ex) catch { case NonFatal(e) => Error(e) }
// Given a flatMap evaluation just happened, must increment the index
val nextFrame = em.nextFrameIndex(frameIndex)
// Next cycle please
loop(fa, em, cb, rcb, null, bRest, nextFrame)
}
case Async(onFinish) =>
executeOnFinish(em, cb, rcb, bFirst, bRest, onFinish, frameIndex)
case ref: MemoizeSuspend[_] =>
// Already processed?
ref.value match {
case Some(materialized) =>
// Next iteration please
loop(fromTry(materialized), em, cb, rcb, bFirst, bRest, frameIndex)
case None =>
val anyRef = ref.asInstanceOf[MemoizeSuspend[Any]]
val isSuccess = startMemoization(anyRef, context, cb, bFirst, bRest, frameIndex)
// Next iteration please
if (!isSuccess) loop(ref, em, cb, rcb, bFirst, bRest, frameIndex)
}
}
else {
// Force async boundary
restartAsync(source, context, cb, bFirst, bRest)
}
}
// Can happen to receive a `RestartCallback` (e.g. from Task.fork),
// in which case we should unwrap it
val callback = cb.asInstanceOf[Callback[Any]]
loop(source, context.executionModel, callback, null, bindCurrent, bindRest, frameIndex)
}
def startLightWithCallback[A](
source: Task[A],
scheduler: Scheduler,
cb: Callback[A],
opts: Task.Options): Cancelable = {
/* Called when we hit the first async boundary. */
def goAsync(
source: Current,
bindCurrent: Bind,
bindRest: CallStack,
nextFrame: FrameIndex,
forceAsync: Boolean): Cancelable = {
val context = Context(scheduler, opts)
val cba = cb.asInstanceOf[Callback[Any]]
if (forceAsync)
restartAsync(source, context, cba, bindCurrent, bindRest)
else
startWithCallback(source, context, cba, bindCurrent, bindRest, nextFrame)
context.connection
}
/* Loop that evaluates a Task until the first async boundary is hit,
* or until the evaluation is finished, whichever comes first.
*/
@tailrec def loop(
source: Current,
em: ExecutionModel,
cb: Callback[Any],
bFirst: Bind,
bRest: CallStack,
frameIndex: Int): Cancelable = {
if (frameIndex != 0) source match {
case ref @ FlatMap(fa, _, _) =>
var callStack: CallStack = bRest
val bind = ref.bind()
if (bFirst ne null) {
if (callStack eq null) callStack = createCallStack()
callStack.push(bFirst)
}
// Next iteration please
loop(fa, em, cb, bind, callStack, frameIndex)
case Now(value) =>
popNextBind(bFirst, bRest) match {
case null =>
cb.onSuccess(value)
Cancelable.empty
case bind =>
val fa = try bind(value) catch { case NonFatal(ex) => Error(ex) }
// Given a flatMap evaluation just happened, must increment the index
val nextFrame = em.nextFrameIndex(frameIndex)
loop(fa, em, cb, null, bRest, nextFrame)
}
case Eval(thunk) =>
var streamErrors = true
var nextState: Current = null
try {
val value = thunk()
streamErrors = false
popNextBind(bFirst, bRest) match {
case null => cb.onSuccess(value)
case bind =>
nextState = try bind(value) catch { case NonFatal(ex) => Error(ex) }
}
} catch {
case NonFatal(ex) if streamErrors =>
nextState = Error(ex)
}
if (nextState eq null) Cancelable.empty else {
// Given a flatMap evaluation just happened, must increment the index
val nextFrame = em.nextFrameIndex(frameIndex)
// Next iteration please
val nextBFirst = if (streamErrors) bFirst else null
loop(nextState, em, cb, nextBFirst, bRest, nextFrame)
}
case Suspend(thunk) =>
val fa = try thunk() catch { case NonFatal(ex) => Error(ex) }
loop(fa, em, cb, bFirst, bRest, frameIndex)
case Error(ex) =>
findErrorHandler(bFirst, bRest) match {
case null =>
cb.onError(ex)
Cancelable.empty
case bind =>
val fa = try bind.error(ex) catch { case NonFatal(e) => Error(e) }
// Given a flatMap evaluation just happened, must increment the index
val nextFrame = em.nextFrameIndex(frameIndex)
// Next cycle please
loop(fa, em, cb, null, bRest, nextFrame)
}
case ref: MemoizeSuspend[_] =>
ref.asInstanceOf[MemoizeSuspend[A]].value match {
case Some(materialized) =>
loop(fromTry(materialized), em, cb, bFirst, bRest, frameIndex)
case None =>
goAsync(source, bFirst, bRest, frameIndex, forceAsync = false)
}
case async @ Async(_) =>
goAsync(async, bFirst, bRest, frameIndex, forceAsync = false)
}
else {
// Asynchronous boundary is forced
goAsync(source, bFirst, bRest, frameIndex, forceAsync = true)
}
}
val em = scheduler.executionModel
loop(source, em, cb.asInstanceOf[Callback[Any]], null, null, frameStart(em))
}
/** A run-loop that attempts to complete a
* [[monix.execution.CancelableFuture CancelableFuture]]
* synchronously falling back to [[startWithCallback]]
* and actual asynchronous execution in case of an
* asynchronous boundary.
*/
def startAsFuture[A](source: Task[A], scheduler: Scheduler, opts: Task.Options): CancelableFuture[A] = {
/* Called when we hit the first async boundary. */
def goAsync(
source: Current,
bindCurrent: Bind,
bindRest: CallStack,
nextFrame: FrameIndex,
forceAsync: Boolean): CancelableFuture[Any] = {
val p = Promise[Any]()
val cb: Callback[Any] = new Callback[Any] {
def onSuccess(value: Any): Unit =
p.trySuccess(value)
def onError(ex: Throwable): Unit =
p.tryFailure(ex)
}
val context = Context(scheduler, opts)
if (forceAsync)
restartAsync(source, context, cb, bindCurrent, bindRest)
else
startWithCallback(source, context, cb, bindCurrent, bindRest, nextFrame)
CancelableFuture(p.future, context.connection)
}
/* Loop that evaluates a Task until the first async boundary is hit,
* or until the evaluation is finished, whichever comes first.
*/
@tailrec def loop(
source: Current,
em: ExecutionModel,
bFirst: Bind,
bRest: CallStack,
frameIndex: Int): CancelableFuture[Any] = {
if (frameIndex != 0) source match {
case ref @ FlatMap(fa, _, _) =>
var callStack: CallStack = bRest
val bind = ref.bind()
if (bFirst ne null) {
if (callStack eq null) callStack = createCallStack()
callStack.push(bFirst)
}
// Next iteration please
loop(fa, em, bind, callStack, frameIndex)
case Now(value) =>
popNextBind(bFirst, bRest) match {
case null =>
CancelableFuture.successful(value)
case bind =>
val fa = try bind(value) catch { case NonFatal(ex) => Error(ex) }
// Given a flatMap evaluation just happened, must increment the index
val nextFrame = em.nextFrameIndex(frameIndex)
loop(fa, em, null, bRest, nextFrame)
}
case Eval(thunk) =>
var nextBFirst = bFirst
var result: CancelableFuture[Any] = null
var nextState: Current = null
try {
val value = thunk()
popNextBind(bFirst, bRest) match {
case null =>
result = CancelableFuture.successful(value)
case bind =>
nextBFirst = null
nextState = bind(value)
}
} catch {
case NonFatal(e) =>
nextState = Error(e)
}
if (result ne null) result else {
// Given a flatMap evaluation just happened, must increment the index
val nextFrame = em.nextFrameIndex(frameIndex)
// Next iteration please
loop(nextState, em, nextBFirst, bRest, nextFrame)
}
case Suspend(thunk) =>
val fa = try thunk() catch { case NonFatal(ex) => Error(ex) }
loop(fa, em, bFirst, bRest, frameIndex)
case Error(ex) =>
findErrorHandler(bFirst, bRest) match {
case null => CancelableFuture.failed(ex)
case bind =>
val fa = try bind.error(ex) catch { case NonFatal(e) => Error(e) }
// Given a flatMap evaluation just happened, must increment the index
val nextFrame = em.nextFrameIndex(frameIndex)
// Next cycle please
loop(fa, em, null, bRest, nextFrame)
}
case async @ Async(_) =>
goAsync(async, bFirst, bRest, frameIndex, forceAsync = false)
case ref: MemoizeSuspend[_] =>
ref.asInstanceOf[MemoizeSuspend[A]].value match {
case Some(materialized) =>
loop(fromTry(materialized), em, bFirst, bRest, frameIndex)
case None =>
goAsync(source, bFirst, bRest, frameIndex, forceAsync = false)
}
}
else {
// Asynchronous boundary is forced
goAsync(source, bFirst, bRest, frameIndex, forceAsync = true)
}
}
val em = scheduler.executionModel
loop(source, em, null, null, frameStart(em))
.asInstanceOf[CancelableFuture[A]]
}
/** Starts the execution and memoization of a `Task.MemoizeSuspend` state. */
def startMemoization[A](
self: MemoizeSuspend[A],
context: Context,
cb: Callback[A],
bindCurrent: Bind,
bindRest: CallStack,
nextFrame: FrameIndex): Boolean = {
// Internal function that stores
def cacheValue(state: AtomicAny[AnyRef], value: Try[A]): Unit = {
// Should we cache everything, error results as well,
// or only successful results?
if (self.cacheErrors || value.isSuccess) {
state.getAndSet(value) match {
case (p: Promise[_], _) =>
p.asInstanceOf[Promise[A]].complete(value)
case _ =>
() // do nothing
}
// GC purposes
self.thunk = null
} else {
// Error happened and we are not caching errors!
val current = state.get
// Resetting the state to `null` will trigger the
// execution again on next `runAsync`
if (state.compareAndSet(current, null))
current match {
case (p: Promise[_], _) =>
p.asInstanceOf[Promise[A]].complete(value)
case _ =>
() // do nothing
}
else
cacheValue(state, value) // retry
}
}
implicit val s = context.scheduler
self.state.get match {
case null =>
val p = Promise[A]()
if (!self.state.compareAndSet(null, (p, context.connection)))
startMemoization(self, context, cb, bindCurrent, bindRest, nextFrame) // retry
else {
val underlying = try self.thunk() catch { case NonFatal(ex) => Error(ex) }
val callback = new Callback[A] {
def onError(ex: Throwable): Unit = {
cacheValue(self.state, Failure(ex))
restartAsync(Error(ex), context, cb, bindCurrent, bindRest)
}
def onSuccess(value: A): Unit = {
cacheValue(self.state, Success(value))
restartAsync(Now(value), context, cb, bindCurrent, bindRest)
}
}
// Asynchronous boundary to prevent stack-overflows!
s.execute(new TrampolinedRunnable {
def run(): Unit = {
startWithCallback(underlying, context, callback, null, null, nextFrame)
}
})
true
}
case (p: Promise[_], mainCancelable: StackedCancelable) =>
// execution is pending completion
context.connection push mainCancelable
p.asInstanceOf[Promise[A]].future.onComplete { r =>
context.connection.pop()
context.frameRef.reset()
startWithCallback(fromTry(r), context, cb, bindCurrent, bindRest, 1)
}
true
case _: Try[_] =>
// Race condition happened
false
}
}
}