/
Task.scala
1582 lines (1409 loc) · 55.5 KB
/
Task.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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2014-2016 by its authors. Some rights reserved.
* 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
import monix.eval.Task._
import monix.execution.Ack.Stop
import monix.execution.cancelables.{CompositeCancelable, SingleAssignmentCancelable, StackedCancelable}
import monix.execution.rstreams.Subscription
import monix.execution.schedulers.ExecutionModel
import monix.execution.{Cancelable, CancelableFuture, Scheduler}
import monix.types.Evaluable
import org.reactivestreams.Subscriber
import monix.execution.atomic.{Atomic, AtomicAny}
import scala.annotation.tailrec
import scala.collection.mutable
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{Future, Promise, TimeoutException}
import scala.util.control.NonFatal
import scala.util.{Failure, Success, Try}
/** `Task` represents a specification for a possibly lazy or
* asynchronous computation, which when executed will produce
* an `A` as a result, along with possible side-effects.
*
* Compared with `Future` from Scala's standard library, `Task` does
* not represent a running computation or a value detached from time,
* as `Task` does not execute anything when working with its builders
* or operators and it does not submit any work into any thread-pool,
* the execution eventually taking place only after `runAsync`
* is called and not before that.
*
* Note that `Task` is conservative in how it spawns logical threads.
* Transformations like `map` and `flatMap` for example will default
* to being executed on the logical thread on which the asynchronous
* computation was started. But one shouldn't make assumptions about
* how things will end up executed, as ultimately it is the
* implementation's job to decide on the best execution model. All
* you are guaranteed is asynchronous execution after executing
* `runAsync`.
*/
sealed abstract class Task[+A] extends Serializable { self =>
/** Triggers the asynchronous execution.
*
* @param cb is a callback that will be invoked upon completion.
* @return a [[monix.execution.Cancelable Cancelable]] that can
* be used to cancel a running task
*/
def runAsync(cb: Callback[A])(implicit s: Scheduler): Cancelable = {
val conn = StackedCancelable()
Task.unsafeStartNow[A](this, s, conn, Callback.safe(cb))
conn
}
/** Triggers the asynchronous execution.
*
* @param f is a callback that will be invoked upon completion.
* @return a [[monix.execution.Cancelable Cancelable]] that can
* be used to cancel a running task
*/
def runAsync(f: Try[A] => Unit)(implicit s: Scheduler): Cancelable =
runAsync(new Callback[A] {
def onSuccess(value: A): Unit = f(Success(value))
def onError(ex: Throwable): Unit = f(Failure(ex))
})
/** Triggers the asynchronous execution.
*
* @return a [[monix.execution.CancelableFuture CancelableFuture]]
* that can be used to extract the result or to cancel
* a running task.
*/
def runAsync(implicit s: Scheduler): CancelableFuture[A] =
Task.runAsCancelableFuture(s, this, Nil)
/** Transforms a [[Task]] into a [[Coeval]] that tries to
* execute the source synchronously, returning either `Right(value)`
* in case a value is available immediately, or `Left(future)` in case
* we have an asynchronous boundary.
*/
def coeval(implicit s: Scheduler): Coeval[Either[CancelableFuture[A], A]] =
Coeval.evalAlways {
val f = this.runAsync(s)
f.value match {
case None => Left(f)
case Some(Success(a)) => Right(a)
case Some(Failure(ex)) => throw ex
}
}
/** Creates a new Task by applying a function to the successful result
* of the source Task, and returns a task equivalent to the result
* of the function.
*/
def flatMap[B](f: A => Task[B]): Task[B] =
self match {
case Now(a) =>
Suspend(() => try f(a) catch { case NonFatal(ex) => Error(ex) })
case eval @ EvalOnce(_) =>
Suspend(() => eval.runAttempt match {
case Now(a) => try f(a) catch { case NonFatal(ex) => Error(ex) }
case error @ Error(_) => error
})
case EvalAlways(thunk) =>
Suspend(() => try f(thunk()) catch {
case NonFatal(ex) => Error(ex)
})
case Suspend(thunk) =>
BindSuspend(thunk, f)
case task @ MemoizeSuspend(_) =>
BindSuspend(() => task, f)
case BindSuspend(thunk, g) =>
Suspend(() => BindSuspend(thunk, g andThen (_ flatMap f)))
case Async(onFinish) =>
BindAsync(onFinish, f)
case BindAsync(listen, g) =>
Suspend(() => BindAsync(listen, g andThen (_ flatMap f)))
case error @ Error(_) =>
error
}
/** Given a source Task that emits another Task, this function
* flattens the result, returning a Task equivalent to the emitted
* Task by the source.
*/
def flatten[B](implicit ev: A <:< Task[B]): Task[B] =
flatMap(a => a)
/** Returns a task that waits for the specified `timespan` before
* executing and mirroring the result of the source.
*/
def delayExecution(timespan: FiniteDuration): Task[A] =
Async { (scheduler, conn, cb) =>
val c = SingleAssignmentCancelable()
conn push c
c := scheduler.scheduleOnce(timespan.length, timespan.unit, new Runnable {
def run(): Unit = {
conn.pop()
Task.resume[A](scheduler, conn, self, cb, Nil)
}
})
}
/** Returns a task that waits for the specified `trigger` to succeed
* before mirroring the result of the source.
*
* If the `trigger` ends in error, then the resulting task will also
* end in error.
*/
def delayExecutionWith(trigger: Task[Any]): Task[A] =
Async { (scheduler, conn, cb) =>
implicit val s = scheduler
Task.unsafeStartNow(trigger, scheduler, conn, new Callback[Any] {
def onSuccess(value: Any): Unit =
// Async boundary forced, prevents stack-overflows
Task.unsafeStartAsync(self, scheduler, conn, cb)
def onError(ex: Throwable): Unit =
cb.onError(ex)
})
}
/** Returns a task that executes the source immediately on `runAsync`,
* but before emitting the `onSuccess` result for the specified
* duration.
*
* Note that if an error happens, then it is streamed immediately
* with no delay.
*/
def delayResult(timespan: FiniteDuration): Task[A] =
Async { (scheduler, conn, cb) =>
implicit val s = scheduler
// Executing source
Task.unsafeStartNow(self, scheduler, conn, new Callback[A] {
def onSuccess(value: A): Unit = {
val task = SingleAssignmentCancelable()
conn push task
// Delaying result
task := scheduler.scheduleOnce(timespan.length, timespan.unit,
new Runnable {
def run(): Unit = {
conn.pop()
cb.onSuccess(value)
}
})
}
def onError(ex: Throwable): Unit =
cb.onError(ex)
})
}
/** Returns a task that executes the source immediately on `runAsync`,
* but before emitting the `onSuccess` result for the specified
* duration.
*
* Note that if an error happens, then it is streamed immediately
* with no delay.
*/
def delayResultBySelector[B](selector: A => Task[B]): Task[A] =
Async { (scheduler, conn, cb) =>
implicit val s = scheduler
// Executing source
Task.unsafeStartNow(self, scheduler, conn, new Callback[A] {
def onSuccess(value: A): Unit = {
var streamErrors = true
try {
val trigger = selector(value)
streamErrors = false
// Delaying result
Task.unsafeStartAsync(trigger, scheduler, conn, new Callback[B] {
def onSuccess(b: B): Unit = cb.onSuccess(value)
def onError(ex: Throwable): Unit = cb.onError(ex)
})
} catch {
case NonFatal(ex) if streamErrors =>
cb.onError(ex)
}
}
def onError(ex: Throwable): Unit =
cb.onError(ex)
})
}
/** Returns a failed projection of this task.
*
* The failed projection is a future holding a value of type
* `Throwable`, emitting a value which is the throwable of the
* original task in case the original task fails, otherwise if the
* source succeeds, then it fails with a `NoSuchElementException`.
*/
def failed: Task[Throwable] =
materializeAttempt.flatMap {
case Error(ex) => Now(ex)
case Now(_) => Error(new NoSuchElementException("failed"))
}
/** Returns a new Task that applies the mapping function to
* the element emitted by the source.
*/
def map[B](f: A => B): Task[B] =
flatMap(a => try Now(f(a)) catch { case NonFatal(ex) => Error(ex) })
/** Returns a new `Task` in which `f` is scheduled to be run on completion.
* This would typically be used to release any resources acquired by this
* `Task`.
*
* The returned `Task` completes when both the source and the
* task returned by `f` complete.
*/
def doOnFinish(f: Option[Throwable] => Task[Unit]): Task[A] =
materializeAttempt.flatMap {
case Task.Now(value) =>
f(None).map(_ => value)
case Task.Error(ex) =>
f(Some(ex)).flatMap(_ => Task.raiseError(ex))
}
/** Creates a new [[Task]] that will expose any triggered error from
* the source.
*/
def materialize: Task[Try[A]] =
materializeAttempt.map(_.asScala)
/** Creates a new [[Task]] that will expose any triggered error from
* the source.
*/
def materializeAttempt: Task[Attempt[A]] = {
self match {
case now @ Now(_) =>
Now(now)
case eval @ EvalOnce(_) =>
Suspend(() => Now(eval.runAttempt))
case EvalAlways(thunk) =>
Suspend(() => Now(Attempt(thunk())))
case Error(ex) =>
Now(Error(ex))
case Suspend(thunk) =>
Suspend(() => try {
thunk().materializeAttempt
} catch { case NonFatal(ex) =>
Now(Error(ex))
})
case task @ MemoizeSuspend(_) =>
Async[Attempt[A]] { (s, conn, cb) =>
Task.unsafeStartNow[A](task, s, conn, new Callback[A] {
def onSuccess(value: A): Unit = cb.onSuccess(Now(value))
def onError(ex: Throwable): Unit = cb.onSuccess(Error(ex))
})
}
case BindSuspend(thunk, g) =>
BindSuspend[Attempt[Any], Attempt[A]](
() => try thunk().materializeAttempt catch {
case NonFatal(ex) => Now(Error(ex))
},
result => result match {
case Now(any) =>
try {
g.asInstanceOf[Any => Task[A]](any)
.materializeAttempt
} catch {
case NonFatal(ex) =>
Now(Error(ex))
}
case Error(ex) =>
Now(Error(ex))
})
case Async(onFinish) =>
Async((s, conn, cb) => onFinish(s, conn, new Callback[A] {
def onSuccess(value: A): Unit = cb.onSuccess(Now(value))
def onError(ex: Throwable): Unit = cb.onSuccess(Error(ex))
}))
case BindAsync(onFinish, g) =>
BindAsync[Attempt[Any], Attempt[A]](
(s, conn, cb) =>
onFinish(s, conn, new Callback[Any] {
def onSuccess(value: Any): Unit = cb.onSuccess(Now(value))
def onError(ex: Throwable): Unit = cb.onSuccess(Error(ex))
}),
result => result match {
case Now(any) =>
try {
g.asInstanceOf[Any => Task[A]](any)
.materializeAttempt
}
catch {
case NonFatal(ex) =>
Now(Error(ex))
}
case Error(ex) =>
Now(Error(ex))
})
}
}
/** Dematerializes the source's result from a `Try`. */
def dematerialize[B](implicit ev: A <:< Try[B]): Task[B] =
self.asInstanceOf[Task[Try[B]]].flatMap(Attempt.fromTry)
/** Dematerializes the source's result from an `Attempt`. */
def dematerializeAttempt[B](implicit ev: A <:< Attempt[B]): Task[B] =
self.asInstanceOf[Task[Attempt[B]]].flatMap(identity)
/** Creates a new task that will try recovering from an error by
* matching it with another task using the given partial function.
*
* See [[onErrorHandleWith]] for the version that takes a total function.
*/
def onErrorRecoverWith[B >: A](pf: PartialFunction[Throwable, Task[B]]): Task[B] =
onErrorHandleWith(ex => pf.applyOrElse(ex, Task.raiseError))
/** Creates a new task that will handle any matching throwable that
* this task might emit by executing another task.
*
* See [[onErrorRecoverWith]] for the version that takes a partial function.
*/
def onErrorHandleWith[B >: A](f: Throwable => Task[B]): Task[B] =
self.materializeAttempt.flatMap {
case now @ Now(_) => now
case Error(ex) => try f(ex) catch { case NonFatal(err) => Error(err) }
}
/** Creates a new task that in case of error will fallback to the
* given backup task.
*/
def onErrorFallbackTo[B >: A](that: Task[B]): Task[B] =
onErrorHandleWith(ex => that)
/** Given a predicate function, keep retrying the
* task until the function returns true.
*/
def restartUntil(p: (A) => Boolean): Task[A] =
self.flatMap(a => if (p(a)) Task.now(a) else self.restartUntil(p))
/** Creates a new task that in case of error will retry executing the
* source again and again, until it succeeds.
*
* In case of continuous failure the total number of executions
* will be `maxRetries + 1`.
*/
def onErrorRestart(maxRetries: Long): Task[A] =
self.onErrorHandleWith(ex =>
if (maxRetries > 0) self.onErrorRestart(maxRetries-1)
else Error(ex))
/** Creates a new task that in case of error will retry executing the
* source again and again, until it succeeds.
*
* In case of continuous failure the total number of executions
* will be `maxRetries + 1`.
*/
def onErrorRestartIf(p: Throwable => Boolean): Task[A] =
self.onErrorHandleWith(ex => if (p(ex)) self.onErrorRestartIf(p) else Error(ex))
/** Creates a new task that will handle any matching throwable that
* this task might emit.
*
* See [[onErrorRecover]] for the version that takes a partial function.
*/
def onErrorHandle[U >: A](f: Throwable => U): Task[U] =
onErrorHandleWith(ex => try Now(f(ex)) catch { case NonFatal(err) => Error(err) })
/** Creates a new task that on error will try to map the error
* to another value using the provided partial function.
*
* See [[onErrorHandle]] for the version that takes a total function.
*/
def onErrorRecover[U >: A](pf: PartialFunction[Throwable, U]): Task[U] =
onErrorRecoverWith(pf.andThen(Task.now))
/** Memoizes the result on the computation and reuses it on subsequent
* invocations of `runAsync`.
*/
def memoize: Task[A] =
self match {
case ref @ Now(_) => ref
case error @ Error(_) => error
case EvalAlways(thunk) => new EvalOnce[A](thunk)
case eval: EvalOnce[_] => self
case Suspend(thunk) =>
val evalOnce = EvalOnce(() => thunk().memoize)
Suspend(evalOnce)
case memoized: MemoizeSuspend[_] => self
case other => new MemoizeSuspend[A](() => other)
}
/** Converts a [[Task]] to an `org.reactivestreams.Publisher` that
* emits a single item on success, or just the error on failure.
*
* See [[http://www.reactive-streams.org/ reactive-streams.org]] for the
* Reactive Streams specification.
*/
def toReactivePublisher[B >: A](implicit s: Scheduler): org.reactivestreams.Publisher[B] =
new org.reactivestreams.Publisher[B] {
def subscribe(out: Subscriber[_ >: B]): Unit = {
out.onSubscribe(new Subscription {
private[this] var isActive = true
private[this] val conn = StackedCancelable()
def request(n: Long): Unit = {
require(n > 0, "n must be strictly positive, according to " +
"the Reactive Streams contract, rule 3.9")
if (isActive) Task.unsafeStartNow[A](self, s, conn, Callback.safe(
new Callback[A] {
def onError(ex: Throwable): Unit =
out.onError(ex)
def onSuccess(value: A): Unit = {
out.onNext(value)
out.onComplete()
}
}))
}
def cancel(): Unit = {
isActive = false
conn.cancel()
}
})
}
}
/** Returns a Task that mirrors the source Task but that triggers a
* `TimeoutException` in case the given duration passes without the
* task emitting any item.
*/
def timeout(after: FiniteDuration): Task[A] =
timeoutTo(after, raiseError(new TimeoutException(s"Task timed-out after $after of inactivity")))
/** Returns a Task that mirrors the source Task but switches to the
* given backup Task in case the given duration passes without the
* source emitting any item.
*/
def timeoutTo[B >: A](after: FiniteDuration, backup: Task[B]): Task[B] =
Task.chooseFirstOf(self, backup.delayExecution(after)).map {
case Left(((a, futureB))) =>
futureB.cancel()
a
case Right((futureA, b)) =>
futureA.cancel()
b
}
/** Zips the values of `this` and `that` task, and creates a new task
* that will emit the tuple of their results.
*/
def zip[B](that: Task[B]): Task[(A, B)] =
Task.mapBoth(this, that)((a,b) => (a,b))
/** Zips the values of `this` and `that` and applies the given
* mapping function on their results.
*/
def zipWith[B,C](that: Task[B])(f: (A,B) => C): Task[C] =
Task.mapBoth(this, that)(f)
}
object Task extends TaskInstances {
/** Returns a new task that, when executed, will emit the result of
* the given function executed asynchronously.
*/
def apply[A](f: => A): Task[A] =
fork(evalAlways(f))
/** Returns a `Task` that on execution is always successful, emitting
* the given strict value.
*/
def now[A](a: A): Task[A] = Now(a)
/** Lifts a value into the task context. Alias for [[now]]. */
def pure[A](a: A): Task[A] = Now(a)
/** Returns a task that on execution is always finishing in error
* emitting the specified exception.
*/
def raiseError[A](ex: Throwable): Task[A] =
Error(ex)
/** Promote a non-strict value representing a Task to a Task of the
* same type.
*/
def defer[A](task: => Task[A]): Task[A] =
Suspend(() => task)
/** Promote a non-strict value to a Task that is memoized on the first
* evaluation, the result being then available on subsequent evaluations.
*/
def evalOnce[A](a: => A): Task[A] =
EvalOnce(a _)
/** Promote a non-strict value to a Task, catching exceptions in the
* process.
*
* Note that since `Task` is not memoized, this will recompute the
* value each time the `Task` is executed.
*/
def evalAlways[A](a: => A): Task[A] =
EvalAlways(a _)
/** A [[Task]] instance that upon evaluation will never complete. */
def never[A]: Task[A] = neverRef
private[this] final val neverRef: Async[Nothing] =
Async((_,_,_) => ())
/** A `Task[Unit]` provided for convenience. */
final val unit: Task[Unit] = Now(())
/** Transforms a [[Coeval]] into a [[Task]]. */
def eval[A](eval: Coeval[A]): Task[A] =
eval.task
/** Mirrors the given source `Task`, but upon execution ensure
* that evaluation forks into a separate (logical) thread.
*/
def fork[A](fa: Task[A]): Task[A] =
fa match {
case async @ Async(_) => async
case async @ BindAsync(_,_) => async
case Suspend(thunk) =>
Suspend(() => fork(thunk()))
case memoize: MemoizeSuspend[_] =>
if (memoize.isStarted)
Async { (s, conn, cb) => Task.unsafeStartNow(memoize, s, conn, cb) }
else
memoize
case other =>
Async { (s, conn, cb) => Task.unsafeStartNow(other, s, conn, cb) }
}
/** Create a `Task` from an asynchronous computation, which takes the
* form of a function with which we can register a callback.
*
* This can be used to translate from a callback-based API to a
* straightforward monadic version. Note that execution of
* the `register` callback always happens asynchronously.
*
* @param register is a function that will be called when this `Task`
* is executed, receiving a callback as a parameter, a
* callback that the user is supposed to call in order to
* signal the desired outcome of this `Task`.
*/
def create[A](register: (Scheduler, Callback[A]) => Cancelable): Task[A] =
Async { (scheduler, conn, cb) =>
try {
val c = SingleAssignmentCancelable()
conn push c
c := register(scheduler, Callback.popBeforeCall(cb, conn))
} catch {
case NonFatal(ex) =>
// We cannot stream the error, because the callback might have
// been called already and we'd be violating its contract,
// hence the only thing possible is to log the error.
scheduler.reportFailure(ex)
}
}
/** Constructs a lazy [[Task]] instance whose result
* will be computed asynchronously.
*
* Unsafe to use directly, only use if you know what you're doing.
* For building `Task` instances safely see [[create]].
*/
def unsafeCreate[A](onFinish: OnFinish[A]): Task[A] =
Async(onFinish)
/** Converts the given Scala `Future` into a `Task`.
*
* NOTE: if you want to defer the creation of the future, use
* in combination with [[defer]].
*/
def fromFuture[A](f: Future[A]): Task[A] = {
if (f.isCompleted) {
// Ready result gets synchronous treatment
Attempt.fromTry(f.value.get)
}
else f match {
// Do we have a CancelableFuture?
case c: Cancelable =>
// Cancelable future, needs canceling
Async { (s, conn, cb) =>
// Already completed future avoids
// forking another thread, as one
// was already forked
if (f.isCompleted) cb(f.value.get) else {
conn.push(c)
f.onComplete {
case Success(a) =>
conn.pop()
cb.onSuccess(a)
case Failure(ex) =>
conn.pop()
cb.onError(ex)
}(s)
}
}
case _ =>
// Simple future, convert directly
Async { (s, conn, cb) =>
if (f.isCompleted) cb(f.value.get) else
f.onComplete(cb)(s)
}
}
}
/** Creates a `Task` that upon execution will execute both given tasks
* (possibly in parallel in case the tasks are asynchronous) and will
* return the result of the task that manages to complete first,
* along with a cancelable future of the other task.
*
* If the first task that completes
*/
def chooseFirstOf[A,B](fa: Task[A], fb: Task[B]): Task[Either[(A, CancelableFuture[B]), (CancelableFuture[A], B)]] =
Async { (scheduler, conn, cb) =>
val pa = Promise[A]()
val pb = Promise[B]()
val isActive = Atomic(true)
val connA = StackedCancelable()
val connB = StackedCancelable()
conn push CompositeCancelable(connA, connB)
// First task: A
Task.unsafeStartNow(fa, scheduler, connA, new Callback[A] {
def onSuccess(valueA: A): Unit =
if (isActive.getAndSet(false)) {
val futureB = CancelableFuture(pb.future, connB)
conn.pop()
cb.onSuccess(Left((valueA, futureB)))
} else {
pa.success(valueA)
}
def onError(ex: Throwable): Unit =
if (isActive.getAndSet(false)) {
conn.pop()
connB.cancel()
cb.onError(ex)
} else {
pa.failure(ex)
}
})
// Second task: B
Task.unsafeStartNow(fb, scheduler, connB, new Callback[B] {
def onSuccess(valueB: B): Unit =
if (isActive.getAndSet(false)) {
val futureA = CancelableFuture(pa.future, connA)
conn.pop()
cb.onSuccess(Right((futureA, valueB)))
} else {
pb.success(valueB)
}
def onError(ex: Throwable): Unit =
if (isActive.getAndSet(false)) {
conn.pop()
connA.cancel()
cb.onError(ex)
} else {
pb.failure(ex)
}
})
}
/** Creates a `Task` that upon execution will return the result of the
* first completed task in the given list and then cancel the rest.
*/
def chooseFirstOfList[A](tasks: TraversableOnce[Task[A]]): Task[A] =
Async { (scheduler, conn, cb) =>
val isActive = Atomic(true)
val composite = CompositeCancelable()
conn.push(composite)
for (task <- tasks; if isActive.get) {
val taskCancelable = StackedCancelable()
composite += taskCancelable
Task.unsafeStartNow(task, scheduler, taskCancelable, new Callback[A] {
def onSuccess(value: A): Unit =
if (isActive.getAndSet(false)) {
composite -= taskCancelable
composite.cancel()
conn.popAndCollapse(taskCancelable)
cb.onSuccess(value)
}
def onError(ex: Throwable): Unit =
if (isActive.getAndSet(false)) {
composite -= taskCancelable
composite.cancel()
conn.popAndCollapse(taskCancelable)
cb.onError(ex)
}
})
}
}
/** Given a sequence of tasks, transforms it to a task signaling a sequence,
* executing the tasks one by one and gathering their results in a list.
*
* This operation will execute the tasks one by one, in order, which means that
* both effects and results will be ordered. See [[gather]] and [[gatherUnordered]]
* for unordered results or effects, and thus potential of running in paralel.
*/
def sequence[A](in: Seq[Task[A]]): Task[List[A]] = {
val init = evalAlways(mutable.ListBuffer.empty[A])
val r = in.foldLeft(init)((acc,elem) => acc.flatMap(lb => elem.map(e => lb += e)))
r.map(_.toList)
}
/** Nondeterministically gather results from the given sequence of tasks,
* returning a task that will signal a sequence of results once all
* tasks are finished.
*
* This function is the nondeterministic analogue of `sequence` and should
* behave identically to `sequence` so long as there is no interaction between
* the effects being gathered. However, unlike `sequence`, which decides on
* a total order of effects, the effects in a `gather` are unordered with
* respect to each other.
*
* Although the effects are unordered, we ensure the order of results
* matches the order of the input sequence. Also see [[gatherUnordered]].
*
* Alias for [[zipList]].
*/
def gather[A](in: Seq[Task[A]]): Task[List[A]] =
zipList(in)
/** Nondeterministically gather results from the given sequence of tasks
* to a sequence, without keeping the original ordering of results.
*
* This function is similar to [[gather]], but neither the effects nor the
* results will be ordered. Useful when you don't need ordering because it
* can be more efficient than `gather`.
*/
def gatherUnordered[A](in: Seq[Task[A]]): Task[Seq[A]] =
Async { (scheduler, conn, finalCallback) =>
val atom = Atomic(Vector.empty[A])
val expected = in.length
val composite = CompositeCancelable()
conn.push(composite)
for (task <- in; if !composite.isCanceled) yield {
val stacked = StackedCancelable()
composite += stacked
Task.unsafeStartNow(task, scheduler, stacked,
new Callback[A] {
@tailrec def onSuccess(value: A): Unit =
atom.get match {
case null => ()
case current =>
val update = current :+ value
if (!atom.compareAndSet(current, update))
onSuccess(value)
else if (update.length == expected) {
conn.pop()
finalCallback.onSuccess(update)
}
}
def onError(ex: Throwable): Unit = {
if (atom.getAndSet(null) != null) {
conn.pop().cancel()
finalCallback.onError(ex)
}
}
})
}
}
/** Obtain results from both `a` and `b`, nondeterministically ordering
* their effects.
*
* The two tasks are both executed asynchronously. In a multi-threading
* environment this means that the tasks will get executed in parallel and
* their results synchronized.
*/
def both[A,B](a: Task[A], b: Task[B]): Task[(A,B)] = mapBoth(a,b)((_,_))
/** Apply a mapping functions to the results of two tasks, nondeterministically
* ordering their effects.
*
* If the two tasks are synchronous, they'll get executed immediately, one
* after the other, with the result being available synchronously.
* If the two tasks are asynchronous, they'll get scheduled for execution
* at the same time and in a multi-threading environment they'll execute
* in parallel and have their results synchronized.
*/
def mapBoth[A1,A2,R](fa1: Task[A1], fa2: Task[A2])(f: (A1,A2) => R): Task[R] = {
/* For signaling the values after the successful completion of both tasks. */
def sendSignal(conn: StackedCancelable, cb: Callback[R], a1: A1, a2: A2): Unit = {
var streamErrors = true
try {
val r = f(a1,a2)
streamErrors = false
conn.pop()
cb.onSuccess(r)
} catch {
case NonFatal(ex) if streamErrors =>
conn.pop()
cb.onError(ex)
}
}
/* For signaling an error. */
@tailrec def sendError(conn: StackedCancelable, state: AtomicAny[AnyRef], s: Scheduler,
cb: Callback[R], ex: Throwable): Unit =
state.get match {
case Stop =>
// We've got nowhere to send the error, so report it
s.reportFailure(ex)
case other =>
if (!state.compareAndSet(other, Stop))
sendError(conn, state, s, cb, ex) // retry
else {
conn.pop().cancel()
cb.onError(ex)
}
}
// The resulting task will be executed asynchronously
Async { (scheduler, conn, cb) =>
// for synchronizing the results
val state = Atomic(null : AnyRef)
val task1 = StackedCancelable()
val task2 = StackedCancelable()
conn push CompositeCancelable(task1, task2)
Task.unsafeStartNow(fa1, scheduler, task1, new Callback[A1] {
@tailrec def onSuccess(a1: A1): Unit =
state.get match {
case null => // null means this is the first task to complete
if (!state.compareAndSet(null, Left(a1))) onSuccess(a1)
case ref @ Right(a2) => // the other task completed, so we can send
sendSignal(conn, cb, a1, a2.asInstanceOf[A2])
case Stop => // the other task triggered an error
() // do nothing
case s @ Left(_) =>
// This task has triggered multiple onSuccess calls
// violating the protocol. Should never happen.
onError(new IllegalStateException(s.toString))
}
def onError(ex: Throwable): Unit =
sendError(conn, state, scheduler, cb, ex)
})
Task.unsafeStartNow(fa2, scheduler, task2, new Callback[A2] {
@tailrec def onSuccess(a2: A2): Unit =
state.get match {
case null => // null means this is the first task to complete
if (!state.compareAndSet(null, Right(a2))) onSuccess(a2)
case ref @ Left(a1) => // the other task completed, so we can send
sendSignal(conn, cb, a1.asInstanceOf[A1], a2)
case Stop => // the other task triggered an error
() // do nothing
case s @ Right(_) =>
// This task has triggered multiple onSuccess calls
// violating the protocol. Should never happen.
onError(new IllegalStateException(s.toString))
}
def onError(ex: Throwable): Unit =
sendError(conn, state, scheduler, cb, ex)
})
}
}
/** Gathers the results from a sequence of tasks into a single list.
* The effects are not ordered, but the results are.
*/
def zipList[A](sources: Seq[Task[A]]): Task[List[A]] = {
val init = evalAlways(mutable.ListBuffer.empty[A])
val r = sources.foldLeft(init)((acc,elem) => Task.mapBoth(acc,elem)(_ += _))
r.map(_.toList)
}
/** Pairs two [[Task]] instances. */
def zip2[A1,A2,R](fa1: Task[A1], fa2: Task[A2]): Task[(A1,A2)] =
Task.mapBoth(fa1, fa2)((_,_))
/** Pairs two [[Task]] instances, creating a new instance that will apply
* the given mapping function to the resulting pair. */
def zipWith2[A1,A2,R](fa1: Task[A1], fa2: Task[A2])(f: (A1,A2) => R): Task[R] =
Task.mapBoth(fa1, fa2)(f)
/** Pairs three [[Task]] instances. */
def zip3[A1,A2,A3](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3]): Task[(A1,A2,A3)] =
zipWith3(fa1,fa2,fa3)((a1,a2,a3) => (a1,a2,a3))
/** Pairs four [[Task]] instances. */
def zip4[A1,A2,A3,A4](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4]): Task[(A1,A2,A3,A4)] =
zipWith4(fa1,fa2,fa3,fa4)((a1,a2,a3,a4) => (a1,a2,a3,a4))
/** Pairs five [[Task]] instances. */
def zip5[A1,A2,A3,A4,A5](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4], fa5: Task[A5]): Task[(A1,A2,A3,A4,A5)] =
zipWith5(fa1,fa2,fa3,fa4,fa5)((a1,a2,a3,a4,a5) => (a1,a2,a3,a4,a5))
/** Pairs six [[Task]] instances. */
def zip6[A1,A2,A3,A4,A5,A6](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4], fa5: Task[A5], fa6: Task[A6]): Task[(A1,A2,A3,A4,A5,A6)] =
zipWith6(fa1,fa2,fa3,fa4,fa5,fa6)((a1,a2,a3,a4,a5,a6) => (a1,a2,a3,a4,a5,a6))
/** Pairs three [[Task]] instances,
* applying the given mapping function to the result.
*/
def zipWith3[A1,A2,A3,R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3])(f: (A1,A2,A3) => R): Task[R] = {
val fa12 = zip2(fa1, fa2)
zipWith2(fa12, fa3) { case ((a1,a2), a3) => f(a1,a2,a3) }
}
/** Pairs four [[Task]] instances,
* applying the given mapping function to the result.
*/
def zipWith4[A1,A2,A3,A4,R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4])(f: (A1,A2,A3,A4) => R): Task[R] = {
val fa123 = zip3(fa1, fa2, fa3)
zipWith2(fa123, fa4) { case ((a1,a2,a3), a4) => f(a1,a2,a3,a4) }
}
/** Pairs five [[Task]] instances,
* applying the given mapping function to the result.
*/
def zipWith5[A1,A2,A3,A4,A5,R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4], fa5: Task[A5])(f: (A1,A2,A3,A4,A5) => R): Task[R] = {
val fa1234 = zip4(fa1, fa2, fa3, fa4)
zipWith2(fa1234, fa5) { case ((a1,a2,a3,a4), a5) => f(a1,a2,a3,a4,a5) }
}
/** Pairs six [[Task]] instances,
* applying the given mapping function to the result.
*/
def zipWith6[A1,A2,A3,A4,A5,A6,R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4], fa5: Task[A5], fa6: Task[A6])(f: (A1,A2,A3,A4,A5,A6) => R): Task[R] = {
val fa12345 = zip5(fa1, fa2, fa3, fa4, fa5)
zipWith2(fa12345, fa6) { case ((a1,a2,a3,a4,a5), a6) => f(a1,a2,a3,a4,a5,a6) }
}
/** Type alias representing callbacks for [[create]] tasks. */
type OnFinish[+A] = (Scheduler, StackedCancelable, Callback[A]) => Unit
/** The `Attempt` represents a strict, already evaluated result
* of a [[Task]] that either resulted in success, wrapped in a
* [[Now]], or in an error, wrapped in a [[Error]].