-
Notifications
You must be signed in to change notification settings - Fork 516
/
IO.scala
1813 lines (1593 loc) · 60.7 KB
/
IO.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 2020-2022 Typelevel
*
* 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 cats.effect
import cats.{
Align,
Alternative,
Applicative,
Eval,
Functor,
Id,
Monad,
Monoid,
Now,
Parallel,
Semigroup,
SemigroupK,
Show,
StackSafeMonad,
Traverse
}
import cats.data.Ior
import cats.syntax.all._
import cats.effect.instances.spawn
import cats.effect.std.Console
import cats.effect.tracing.{Tracing, TracingEvent}
import scala.annotation.unchecked.uncheckedVariance
import scala.concurrent.{
CancellationException,
ExecutionContext,
Future,
Promise,
TimeoutException
}
import scala.concurrent.duration._
import scala.util.{Failure, Success, Try}
/**
* A pure abstraction representing the intention to perform a side effect, where the result of
* that side effect may be obtained synchronously (via return) or asynchronously (via callback).
*
* `IO` values are pure, immutable values and thus preserve referential transparency, being
* usable in functional programming. An `IO` is a data structure that represents just a
* description of a side effectful computation.
*
* `IO` can describe synchronous or asynchronous computations that:
*
* 1. on evaluation yield exactly one result 2. can end in either success or failure and in
* case of failure `flatMap` chains get short-circuited (`IO` implementing the algebra of
* `MonadError`) 3. can be canceled, but note this capability relies on the user to provide
* cancelation logic
*
* Effects described via this abstraction are not evaluated until the "end of the world", which
* is to say, when one of the "unsafe" methods are used. Effectful results are not memoized,
* meaning that memory overhead is minimal (and no leaks), and also that a single effect may be
* run multiple times in a referentially-transparent manner. For example:
*
* {{{
* val ioa = IO.println("hey!")
*
* val program = for {
* _ <- ioa
* _ <- ioa
* } yield ()
*
* program.unsafeRunSync()
* }}}
*
* The above will print "hey!" twice, as the effect will be re-run each time it is sequenced in
* the monadic chain.
*
* `IO` is trampolined in its `flatMap` evaluation. This means that you can safely call
* `flatMap` in a recursive function of arbitrary depth, without fear of blowing the stack.
*
* {{{
* def fib(n: Int, a: Long = 0, b: Long = 1): IO[Long] =
* IO.pure(a + b) flatMap { b2 =>
* if (n > 0)
* fib(n - 1, b, b2)
* else
* IO.pure(a)
* }
* }}}
*
* @see
* [[IOApp]] for the preferred way of executing whole programs wrapped in `IO`
*/
sealed abstract class IO[+A] private () extends IOPlatform[A] {
private[effect] def tag: Byte
/**
* Like [[*>]], but keeps the result of the source.
*
* For a similar method that also runs the parameter in case of failure or interruption, see
* [[guarantee]].
*/
def <*[B](that: IO[B]): IO[A] =
productL(that)
/**
* Runs the current IO, then runs the parameter, keeping its result. The result of the first
* action is ignored. If the source fails, the other action won't run. Not suitable for use
* when the parameter is a recursive reference to the current expression.
*
* @see
* [[>>]] for the recursion-safe, lazily evaluated alternative
*/
def *>[B](that: IO[B]): IO[B] =
productR(that)
/**
* Runs the current IO, then runs the parameter, keeping its result. The result of the first
* action is ignored. If the source fails, the other action won't run. Evaluation of the
* parameter is done lazily, making this suitable for recursion.
*
* @see
* [*>] for the strictly evaluated alternative
*/
def >>[B](that: => IO[B]): IO[B] =
flatMap(_ => that)
def !>[B](that: IO[B]): IO[B] =
forceR(that)
/**
* Runs this IO and the parameter in parallel.
*
* Failure in either of the IOs will cancel the other one. If the whole computation is
* canceled, both actions are also canceled.
*/
def &>[B](that: IO[B]): IO[B] =
both(that).map { case (_, b) => b }
/**
* Like [[&>]], but keeps the result of the source
*/
def <&[B](that: IO[B]): IO[A] =
both(that).map { case (a, _) => a }
/**
* Replaces the result of this IO with the given value.
*/
def as[B](b: B): IO[B] =
map(_ => b)
/**
* Materializes any sequenced exceptions into value space, where they may be handled.
*
* This is analogous to the `catch` clause in `try`/`catch`, being the inverse of
* `IO.raiseError`. Thus:
*
* {{{
* IO.raiseError(ex).attempt.unsafeRunAsync === Left(ex)
* }}}
*
* @see
* [[IO.raiseError]]
*/
def attempt: IO[Either[Throwable, A]] =
IO.Attempt(this)
/**
* Replaces failures in this IO with an empty Option.
*/
def option: IO[Option[A]] =
redeem(_ => None, Some(_))
/**
* Runs the current and given IO in parallel, producing the pair of the outcomes. Both
* outcomes are produced, regardless of whether they complete successfully.
*
* @see
* [[both]] for the version which embeds the outcomes to produce a pair of the results
* @see
* [[raceOutcome]] for the version which produces the outcome of the winner and cancels the
* loser of the race
*/
def bothOutcome[B](that: IO[B]): IO[(OutcomeIO[A @uncheckedVariance], OutcomeIO[B])] =
IO.uncancelable { poll =>
racePair(that).flatMap {
case Left((oc, f)) => poll(f.join).onCancel(f.cancel).map((oc, _))
case Right((f, oc)) => poll(f.join).onCancel(f.cancel).map((_, oc))
}
}
/**
* Runs the current and given IO in parallel, producing the pair of the results. If either
* fails with an error, the result of the whole will be that error and the other will be
* canceled.
*
* @see
* [[bothOutcome]] for the version which produces the outcome of both effects executed in
* parallel
* @see
* [[race]] for the version which produces the result of the winner and cancels the loser of
* the race
*/
def both[B](that: IO[B]): IO[(A, B)] =
IO.both(this, that)
/**
* Returns an `IO` action that treats the source task as the acquisition of a resource, which
* is then exploited by the `use` function and then `released`.
*
* The `bracket` operation is the equivalent of the `try {} catch {} finally {}` statements
* from mainstream languages.
*
* The `bracket` operation installs the necessary exception handler to release the resource in
* the event of an exception being raised during the computation, or in case of cancelation.
*
* If an exception is raised, then `bracket` will re-raise the exception ''after'' performing
* the `release`. If the resulting task gets canceled, then `bracket` will still perform the
* `release`, but the yielded task will be non-terminating (equivalent with [[IO.never]]).
*
* Example:
*
* {{{
* import java.io._
*
* def readFile(file: File): IO[String] = {
* // Opening a file handle for reading text
* val acquire = IO(new BufferedReader(
* new InputStreamReader(new FileInputStream(file), "utf-8")
* ))
*
* acquire.bracket { in =>
* // Usage part
* IO {
* // Yes, ugly Java, non-FP loop;
* // side-effects are suspended though
* var line: String = null
* val buff = new StringBuilder()
* do {
* line = in.readLine()
* if (line != null) buff.append(line)
* } while (line != null)
* buff.toString()
* }
* } { in =>
* // The release part
* IO(in.close())
* }
* }
* }}}
*
* Note that in case of cancelation the underlying implementation cannot guarantee that the
* computation described by `use` doesn't end up executed concurrently with the computation
* from `release`. In the example above that ugly Java loop might end up reading from a
* `BufferedReader` that is already closed due to the task being canceled, thus triggering an
* error in the background with nowhere to get signaled.
*
* In this particular example, given that we are just reading from a file, it doesn't matter.
* But in other cases it might matter, as concurrency on top of the JVM when dealing with I/O
* might lead to corrupted data.
*
* For those cases you might want to do synchronization (e.g. usage of locks and semaphores)
* and you might want to use [[bracketCase]], the version that allows you to differentiate
* between normal termination and cancelation.
*
* '''NOTE on error handling''': in case both the `release` function and the `use` function
* throws, the error raised by `release` gets signaled.
*
* For example:
*
* {{{
* val foo = new RuntimeException("Foo")
* val bar = new RuntimeException("Bar")
* IO("resource").bracket { _ =>
* // use
* IO.raiseError(foo)
* } { _ =>
* // release
* IO.raiseError(bar)
* }
* }}}
*
* In this case the resulting `IO` will raise error `foo`, while the `bar` error gets reported
* on a side-channel. This is consistent with the behavior of Java's "Try with resources"
* except that no involved exceptions are mutated (i.e., in contrast to Java, `bar` isn't
* added as a suppressed exception to `foo`).
*
* @see
* [[bracketCase]]
*
* @param use
* is a function that evaluates the resource yielded by the source, yielding a result that
* will get generated by the task returned by this `bracket` function
*
* @param release
* is a function that gets called after `use` terminates, either normally or in error, or if
* it gets canceled, receiving as input the resource that needs to be released
*/
def bracket[B](use: A => IO[B])(release: A => IO[Unit]): IO[B] =
bracketCase(use)((a, _) => release(a))
/**
* Returns a new `IO` task that treats the source task as the acquisition of a resource, which
* is then exploited by the `use` function and then `released`, with the possibility of
* distinguishing between normal termination and cancelation, such that an appropriate release
* of resources can be executed.
*
* The `bracketCase` operation is the equivalent of `try {} catch {} finally {}` statements
* from mainstream languages when used for the acquisition and release of resources.
*
* The `bracketCase` operation installs the necessary exception handler to release the
* resource in the event of an exception being raised during the computation, or in case of
* cancelation.
*
* In comparison with the simpler [[bracket]] version, this one allows the caller to
* differentiate between normal termination, termination in error and cancelation via an
* [[Outcome]] parameter.
*
* @see
* [[bracket]]
*
* @param use
* is a function that evaluates the resource yielded by the source, yielding a result that
* will get generated by this function on evaluation
*
* @param release
* is a function that gets called after `use` terminates, either normally or in error, or if
* it gets canceled, receiving as input the resource that needs release, along with the
* result of `use` (cancelation, error or successful result)
*/
def bracketCase[B](use: A => IO[B])(release: (A, OutcomeIO[B]) => IO[Unit]): IO[B] =
IO.bracketFull(_ => this)(use)(release)
/**
* Shifts the execution of the current IO to the specified `ExecutionContext`. All stages of
* the execution will default to the pool in question, and any asynchronous callbacks will
* shift back to the pool upon completion. Any nested use of `evalOn` will override the
* specified pool. Once the execution fully completes, default control will be shifted back to
* the enclosing (inherited) pool.
*
* @see
* [[IO.executionContext]] for obtaining the `ExecutionContext` on which the current `IO` is
* being executed
*/
def evalOn(ec: ExecutionContext): IO[A] = IO.EvalOn(this, ec)
def startOn(ec: ExecutionContext): IO[FiberIO[A @uncheckedVariance]] = start.evalOn(ec)
def backgroundOn(ec: ExecutionContext): ResourceIO[IO[OutcomeIO[A @uncheckedVariance]]] =
Resource.make(startOn(ec))(_.cancel).map(_.join)
def forceR[B](that: IO[B]): IO[B] =
handleError(_ => ()).productR(that)
/**
* Monadic bind on `IO`, used for sequentially composing two `IO` actions, where the value
* produced by the first `IO` is passed as input to a function producing the second `IO`
* action.
*
* Due to this operation's signature, `flatMap` forces a data dependency between two `IO`
* actions, thus ensuring sequencing (e.g. one action to be executed before another one).
*
* Any exceptions thrown within the function will be caught and sequenced into the `IO`,
* because due to the nature of asynchronous processes, without catching and handling
* exceptions, failures would be completely silent and `IO` references would never terminate
* on evaluation.
*/
def flatMap[B](f: A => IO[B]): IO[B] =
IO.FlatMap(this, f, Tracing.calculateTracingEvent(f))
def flatten[B](implicit ev: A <:< IO[B]): IO[B] = flatMap(ev)
def flatTap[B](f: A => IO[B]): IO[A] = flatMap(a => f(a).as(a))
/**
* Executes the given `finalizer` when the source is finished, either in success or in error,
* or if canceled.
*
* This variant of [[guaranteeCase]] evaluates the given `finalizer` regardless of how the
* source gets terminated:
*
* - normal completion
* - completion in error
* - cancelation
*
* This equivalence always holds:
*
* {{{
* io.guarantee(f) <-> IO.unit.bracket(_ => io)(_ => f)
* }}}
*
* @see
* [[guaranteeCase]] for the version that can discriminate between termination conditions
*/
def guarantee(finalizer: IO[Unit]): IO[A] =
// this is a little faster than the default implementation, which helps Resource
IO uncancelable { poll =>
val handled = finalizer handleErrorWith { t =>
IO.executionContext.flatMap(ec => IO(ec.reportFailure(t)))
}
poll(this).onCancel(finalizer).onError(_ => handled).flatTap(_ => finalizer)
}
/**
* Executes the given `finalizer` when the source is finished, either in success or in error,
* or if canceled, allowing for differentiating between exit conditions.
*
* This variant of [[guarantee]] injects an [[Outcome]] in the provided function, allowing one
* to make a difference between:
*
* - normal completion
* - completion in error
* - cancelation
*
* This equivalence always holds:
*
* {{{
* io.guaranteeCase(f) <-> IO.unit.bracketCase(_ => io)((_, e) => f(e))
* }}}
*
* @see
* [[guarantee]] for the simpler version
*/
def guaranteeCase(finalizer: OutcomeIO[A @uncheckedVariance] => IO[Unit]): IO[A] =
IO.uncancelable { poll =>
val finalized = poll(this).onCancel(finalizer(Outcome.canceled))
val handled = finalized.onError { e =>
finalizer(Outcome.errored(e)).handleErrorWith { t =>
IO.executionContext.flatMap(ec => IO(ec.reportFailure(t)))
}
}
handled.flatTap(a => finalizer(Outcome.succeeded(IO.pure(a))))
}
def handleError[B >: A](f: Throwable => B): IO[B] =
handleErrorWith[B](t => IO.pure(f(t)))
/**
* Handle any error, potentially recovering from it, by mapping it to another `IO` value.
*
* Implements `ApplicativeError.handleErrorWith`.
*/
def handleErrorWith[B >: A](f: Throwable => IO[B]): IO[B] =
IO.HandleErrorWith(this, f, Tracing.calculateTracingEvent(f))
def ifM[B](ifTrue: => IO[B], ifFalse: => IO[B])(implicit ev: A <:< Boolean): IO[B] =
flatMap(a => if (ev(a)) ifTrue else ifFalse)
/**
* Functor map on `IO`. Given a mapping function, it transforms the value produced by the
* source, while keeping the `IO` context.
*
* Any exceptions thrown within the function will be caught and sequenced into the `IO`. Due
* to the nature of asynchronous processes, without catching and handling exceptions, failures
* would be completely silent and `IO` references would never terminate on evaluation.
*/
def map[B](f: A => B): IO[B] = IO.Map(this, f, Tracing.calculateTracingEvent(f))
def onCancel(fin: IO[Unit]): IO[A] =
IO.OnCancel(this, fin)
def onError(f: Throwable => IO[Unit]): IO[A] =
handleErrorWith(t => f(t).attempt *> IO.raiseError(t))
def race[B](that: IO[B]): IO[Either[A, B]] =
IO.race(this, that)
def raceOutcome[B](that: IO[B]): IO[Either[OutcomeIO[A @uncheckedVariance], OutcomeIO[B]]] =
IO.uncancelable { _ =>
racePair(that).flatMap {
case Left((oc, f)) => f.cancel.as(Left(oc))
case Right((f, oc)) => f.cancel.as(Right(oc))
}
}
def racePair[B](that: IO[B]): IO[Either[
(OutcomeIO[A @uncheckedVariance], FiberIO[B]),
(FiberIO[A @uncheckedVariance], OutcomeIO[B])]] =
IO.racePair(this, that)
/**
* Returns a new value that transforms the result of the source, given the `recover` or `map`
* functions, which get executed depending on whether the result ends in error or if it is
* successful.
*
* This is an optimization on usage of [[attempt]] and [[map]], this equivalence being true:
*
* {{{
* io.redeem(recover, map) <-> io.attempt.map(_.fold(recover, map))
* }}}
*
* Usage of `redeem` subsumes `handleError` because:
*
* {{{
* io.redeem(fe, id) <-> io.handleError(fe)
* }}}
*
* @param recover
* is a function used for error recover in case the source ends in error
* @param map
* is a function used for mapping the result of the source in case it ends in success
*/
def redeem[B](recover: Throwable => B, map: A => B): IO[B] =
attempt.map(_.fold(recover, map))
/**
* Returns a new value that transforms the result of the source, given the `recover` or `bind`
* functions, which get executed depending on whether the result ends in error or if it is
* successful.
*
* This is an optimization on usage of [[attempt]] and [[flatMap]], this equivalence being
* available:
*
* {{{
* io.redeemWith(recover, bind) <-> io.attempt.flatMap(_.fold(recover, bind))
* }}}
*
* Usage of `redeemWith` subsumes `handleErrorWith` because:
*
* {{{
* io.redeemWith(fe, F.pure) <-> io.handleErrorWith(fe)
* }}}
*
* Usage of `redeemWith` also subsumes [[flatMap]] because:
*
* {{{
* io.redeemWith(F.raiseError, fs) <-> io.flatMap(fs)
* }}}
*
* @param recover
* is the function that gets called to recover the source in case of error
* @param bind
* is the function that gets to transform the source in case of success
*/
def redeemWith[B](recover: Throwable => IO[B], bind: A => IO[B]): IO[B] =
attempt.flatMap(_.fold(recover, bind))
def replicateA(n: Int): IO[List[A]] =
if (n <= 0)
IO.pure(Nil)
else
flatMap(a => replicateA(n - 1).map(a :: _))
// TODO PR to cats
def replicateA_(n: Int): IO[Unit] =
if (n <= 0)
IO.unit
else
flatMap(_ => replicateA_(n - 1))
/**
* Returns an IO that will delay the execution of the source by the given duration.
*/
def delayBy(duration: FiniteDuration): IO[A] =
IO.sleep(duration) *> this
/**
* Returns an IO that either completes with the result of the source within the specified time
* `duration` or otherwise raises a `TimeoutException`.
*
* The source is canceled in the event that it takes longer than the specified time duration
* to complete. Once the source has been successfully canceled (and has completed its
* finalizers), the `TimeoutException` will be raised. If the source is uncancelable, the
* resulting effect will wait for it to complete before raising the exception.
*
* @param duration
* is the time span for which we wait for the source to complete; in the event that the
* specified time has passed without the source completing, a `TimeoutException` is raised
*/
def timeout[A2 >: A](duration: FiniteDuration): IO[A2] =
timeoutTo(duration, IO.defer(IO.raiseError(new TimeoutException(duration.toString))))
/**
* Returns an IO that either completes with the result of the source within the specified time
* `duration` or otherwise evaluates the `fallback`.
*
* The source is canceled in the event that it takes longer than the specified time duration
* to complete. Once the source has been successfully canceled (and has completed its
* finalizers), the fallback will be sequenced. If the source is uncancelable, the resulting
* effect will wait for it to complete before evaluating the fallback.
*
* @param duration
* is the time span for which we wait for the source to complete; in the event that the
* specified time has passed without the source completing, the `fallback` gets evaluated
*
* @param fallback
* is the task evaluated after the duration has passed and the source canceled
*/
def timeoutTo[A2 >: A](duration: FiniteDuration, fallback: IO[A2]): IO[A2] =
race(IO.sleep(duration)).flatMap {
case Right(_) => fallback
case Left(value) => IO.pure(value)
}
/**
* Returns an IO that either completes with the result of the source within the specified time
* `duration` or otherwise raises a `TimeoutException`.
*
* The source is canceled in the event that it takes longer than the specified time duration
* to complete. Unlike [[timeout]], the cancelation of the source will be ''requested'' but
* not awaited, and the exception will be raised immediately upon the completion of the timer.
* This may more closely match intuitions about timeouts, but it also violates backpressure
* guarantees and intentionally leaks fibers.
*
* This combinator should be applied very carefully.
*
* @param duration
* The time span for which we wait for the source to complete; in the event that the
* specified time has passed without the source completing, a `TimeoutException` is raised
* @see
* [[timeout]] for a variant which respects backpressure and does not leak fibers
*/
def timeoutAndForget(duration: FiniteDuration): IO[A] =
Temporal[IO].timeoutAndForget(this, duration)
def timed: IO[(FiniteDuration, A)] =
Clock[IO].timed(this)
def product[B](that: IO[B]): IO[(A, B)] =
flatMap(a => that.map(b => (a, b)))
def productL[B](that: IO[B]): IO[A] =
flatMap(a => that.as(a))
def productR[B](that: IO[B]): IO[B] =
flatMap(_ => that)
/**
* Start execution of the source suspended in the `IO` context.
*
* This can be used for non-deterministic / concurrent execution. The following code is more
* or less equivalent with `parMap2` (minus the behavior on error handling and cancelation):
*
* {{{
* def par2[A, B](ioa: IO[A], iob: IO[B]): IO[(A, B)] =
* for {
* fa <- ioa.start
* fb <- iob.start
* a <- fa.join
* b <- fb.join
* } yield (a, b)
* }}}
*
* Note in such a case usage of `parMapN` (via `cats.Parallel`) is still recommended because
* of behavior on error and cancelation — consider in the example above what would happen if
* the first task finishes in error. In that case the second task doesn't get canceled, which
* creates a potential memory leak.
*
* Also see [[background]] for a safer alternative.
*/
def start: IO[FiberIO[A @uncheckedVariance]] =
IO.Start(this)
/**
* Returns a resource that will start execution of this IO in the background.
*
* In case the resource is closed while this IO is still running (e.g. due to a failure in
* `use`), the background action will be canceled.
*
* @see
* [[cats.effect.kernel.GenSpawn#background]] for the generic version.
*/
def background: ResourceIO[IO[OutcomeIO[A @uncheckedVariance]]] =
Spawn[IO].background(this)
def memoize: IO[IO[A]] =
Concurrent[IO].memoize(this)
/**
* Makes the source `IO` uninterruptible such that a [[cats.effect.kernel.Fiber#cancel]]
* signal is ignored until completion.
*
* @see
* [[IO.uncancelable]] for constructing uncancelable `IO` values with user-configurable
* cancelable regions
*/
def uncancelable: IO[A] =
IO.uncancelable(_ => this)
/**
* Ignores the result of this IO.
*/
def void: IO[Unit] =
map(_ => ())
/**
* Converts the source `IO` into any `F` type that implements the [[LiftIO]] type class.
*/
def to[F[_]](implicit F: LiftIO[F]): F[A @uncheckedVariance] =
F.liftIO(this)
override def toString: String = "IO(...)"
// unsafe stuff
/**
* Passes the result of the encapsulated effects to the given callback by running them as
* impure side effects.
*
* Any exceptions raised within the effect will be passed to the callback in the `Either`. The
* callback will be invoked at most *once*. Note that it is very possible to construct an IO
* which never returns while still never blocking a thread, and attempting to evaluate that IO
* with this method will result in a situation where the callback is *never* invoked.
*
* As the name says, this is an UNSAFE function as it is impure and performs side effects. You
* should ideally only call this function ''once'', at the very end of your program.
*/
def unsafeRunAsync(cb: Either[Throwable, A] => Unit)(
implicit runtime: unsafe.IORuntime): Unit = {
unsafeRunFiber(
cb(Left(new CancellationException("The fiber was canceled"))),
t => cb(Left(t)),
a => cb(Right(a)))
()
}
def unsafeRunAsyncOutcome(cb: Outcome[Id, Throwable, A @uncheckedVariance] => Unit)(
implicit runtime: unsafe.IORuntime): Unit = {
unsafeRunFiber(
cb(Outcome.canceled),
t => cb(Outcome.errored(t)),
a => cb(Outcome.succeeded(a: Id[A])))
()
}
/**
* Triggers the evaluation of the source and any suspended side effects therein, but ignores
* the result.
*
* This operation is similar to [[unsafeRunAsync]], in that the evaluation can happen
* asynchronously, except no callback is required and therefore the result is ignored.
*
* Note that errors still get logged (via IO's internal logger), because errors being thrown
* should never be totally silent.
*/
def unsafeRunAndForget()(implicit runtime: unsafe.IORuntime): Unit =
unsafeRunAsync(_ => ())
/**
* Evaluates the effect and produces the result in a `Future`.
*
* This is similar to `unsafeRunAsync` in that it evaluates the `IO` as a side effect in a
* non-blocking fashion, but uses a `Future` rather than an explicit callback. This function
* should really only be used if interoperating with code which uses Scala futures.
*
* @see
* [[IO.fromFuture]]
*/
def unsafeToFuture()(implicit runtime: unsafe.IORuntime): Future[A] =
unsafeToFutureCancelable()._1
/**
* Evaluates the effect and produces the result in a `Future`, along with a cancelation token
* that can be used to cancel the original effect.
*
* This is similar to `unsafeRunAsync` in that it evaluates the `IO` as a side effect in a
* non-blocking fashion, but uses a `Future` rather than an explicit callback. This function
* should really only be used if interoperating with code which uses Scala futures.
*
* @see
* [[IO.fromFuture]]
*/
def unsafeToFutureCancelable()(
implicit runtime: unsafe.IORuntime): (Future[A], () => Future[Unit]) = {
val p = Promise[A]()
val fiber = unsafeRunFiber(
p.failure(new CancellationException("The fiber was canceled")),
p.failure,
p.success)
(p.future, () => fiber.cancel.unsafeToFuture())
}
/**
* Evaluates the effect, returning a cancelation token that can be used to cancel it.
*
* This is similar to `unsafeRunAsync` in that it evaluates the `IO` as a side effect in a
* non-blocking fashion, but uses a `Future` rather than an explicit callback. This function
* should really only be used if interoperating with code which uses Scala futures.
*
* @see
* [[IO.fromFuture]]
*/
def unsafeRunCancelable()(implicit runtime: unsafe.IORuntime): () => Future[Unit] =
unsafeToFutureCancelable()._2
private[effect] def unsafeRunFiber(
canceled: => Unit,
failure: Throwable => Unit,
success: A => Unit)(implicit runtime: unsafe.IORuntime): IOFiber[A @uncheckedVariance] = {
val fiber = new IOFiber[A](
Map.empty,
oc =>
oc.fold(
{
runtime.fiberErrorCbs.remove(failure)
canceled
},
{ t =>
runtime.fiberErrorCbs.remove(failure)
failure(t)
},
{ ioa =>
runtime.fiberErrorCbs.remove(failure)
success(ioa.asInstanceOf[IO.Pure[A]].value)
}
),
this,
runtime.compute,
runtime
)
runtime.fiberErrorCbs.put(failure)
runtime.compute.execute(fiber)
fiber
}
/**
* Translates this `IO[A]` into a `SyncIO` value which, when evaluated, runs the original `IO`
* to its completion, or until the first asynchronous, boundary, whichever is encountered
* first.
*/
def syncStep: SyncIO[Either[IO[A], A]] = {
def interpret[B](io: IO[B]): SyncIO[Either[IO[B], B]] =
io match {
case IO.Pure(a) => SyncIO.pure(Right(a))
case IO.Error(t) => SyncIO.raiseError(t)
case IO.Delay(thunk, _) => SyncIO.delay(thunk()).map(Right(_))
case IO.RealTime => SyncIO.realTime.map(Right(_))
case IO.Monotonic => SyncIO.monotonic.map(Right(_))
case IO.Map(ioe, f, _) =>
interpret(ioe).map {
case Left(io) => Left(io.map(f))
case Right(a) => Right(f(a))
}
case IO.FlatMap(ioe, f, _) =>
interpret(ioe).flatMap {
case Left(io) => SyncIO.pure(Left(io.flatMap(f)))
case Right(a) => interpret(f(a))
}
case IO.Attempt(ioe) =>
interpret(ioe)
.map {
case Left(io) => Left(io.attempt)
case Right(a) => Right(a.asRight[Throwable])
}
.handleError(t => Right(t.asLeft[IO[B]]))
case IO.HandleErrorWith(ioe, f, _) =>
interpret(ioe)
.map {
case Left(io) => Left(io.handleErrorWith(f))
case Right(a) => Right(a)
}
.handleErrorWith(t => interpret(f(t)))
case IO.Uncancelable(body, _) =>
interpret(body(new Poll[IO] {
def apply[C](ioc: IO[C]): IO[C] = ioc
}))
case IO.OnCancel(ioa, _) => interpret(ioa)
case _ => SyncIO.pure(Left(io))
}
interpret(this)
}
/**
* Evaluates the current `IO` in an infinite loop, terminating only on error or cancelation.
*
* {{{
* IO.println("Hello, World!").foreverM // continues printing forever
* }}}
*/
def foreverM: IO[Nothing] = IO.asyncForIO.foreverM[A, Nothing](this)
def whileM[G[_]: Alternative, B >: A](p: IO[Boolean]): IO[G[B]] =
Monad[IO].whileM[G, B](p)(this)
def whileM_(p: IO[Boolean]): IO[Unit] = Monad[IO].whileM_(p)(this)
def untilM[G[_]: Alternative, B >: A](cond: => IO[Boolean]): IO[G[B]] =
Monad[IO].untilM[G, B](this)(cond)
def untilM_(cond: => IO[Boolean]): IO[Unit] = Monad[IO].untilM_(this)(cond)
def iterateWhile(p: A => Boolean): IO[A] = Monad[IO].iterateWhile(this)(p)
def iterateUntil(p: A => Boolean): IO[A] = Monad[IO].iterateUntil(this)(p)
}
private[effect] trait IOLowPriorityImplicits {
implicit def showForIONoPure[A]: Show[IO[A]] =
Show.show(_ => "IO(...)")
implicit def semigroupForIO[A: Semigroup]: Semigroup[IO[A]] =
new IOSemigroup[A]
protected class IOSemigroup[A](implicit val A: Semigroup[A]) extends Semigroup[IO[A]] {
def combine(left: IO[A], right: IO[A]) =
left.flatMap(l => right.map(r => l |+| r))
}
}
object IO extends IOCompanionPlatform with IOLowPriorityImplicits {
/**
* Newtype encoding for an `IO` datatype that has a `cats.Applicative` capable of doing
* parallel processing in `ap` and `map2`, needed for implementing `cats.Parallel`.
*
* For converting back and forth you can use either the `Parallel[IO]` instance or the methods
* `cats.effect.kernel.Par.ParallelF.apply` for wrapping any `IO` value and
* `cats.effect.kernel.Par.ParallelF.value` for unwrapping it.
*
* The encoding is based on the "newtypes" project by Alexander Konovalov, chosen because it's
* devoid of boxing issues and a good choice until opaque types will land in Scala.
*/
type Par[A] = ParallelF[IO, A]
// constructors
/**
* Suspends a synchronous side effect in `IO`. Use [[IO.apply]] if your side effect is not
* thread-blocking; otherwise you should use [[IO.blocking]] (uncancelable) or
* `IO.interruptible` (cancelable).
*
* Alias for [[IO.delay]].
*/
def apply[A](thunk: => A): IO[A] = delay(thunk)
/**
* Suspends a synchronous side effect in `IO`. Use [[IO.delay]] if your side effect is not
* thread-blocking; otherwise you should use [[IO.blocking]] (uncancelable) or
* `IO.interruptible` (cancelable).
*
* Any exceptions thrown by the effect will be caught and sequenced into the `IO`.
*/
def delay[A](thunk: => A): IO[A] = {
val fn = Thunk.asFunction0(thunk)
Delay(fn, Tracing.calculateTracingEvent(fn))
}
/**
* Suspends a synchronous side effect which produces an `IO` in `IO`.
*
* This is useful for trampolining (i.e. when the side effect is conceptually the allocation
* of a stack frame). Any exceptions thrown by the side effect will be caught and sequenced
* into the `IO`.
*/
def defer[A](thunk: => IO[A]): IO[A] =
delay(thunk).flatten
/**
* Suspends an asynchronous side effect in `IO`.
*
* The given function will be invoked during evaluation of the `IO` to "schedule" the
* asynchronous callback, where the callback of type `Either[Throwable, A] => Unit` is the
* parameter passed to that function. Only the ''first'' invocation of the callback will be
* effective! All subsequent invocations will be silently dropped.
*
* The process of registering the callback itself is suspended in `IO` (the outer `IO` of
* `IO[Option[IO[Unit]]]`).
*
* The effect returns `Option[IO[Unit]]` which is an optional finalizer to be run in the event
* that the fiber running `async(k)` is canceled.
*
* For example, here is a simplified version of `IO.fromCompletableFuture`:
*
* {{{
* def fromCompletableFuture[A](fut: IO[CompletableFuture[A]]): IO[A] = {
* fut.flatMap { cf =>
* IO.async { cb =>
* IO {
* //Invoke the callback with the result of the completable future
* val stage = cf.handle[Unit] {
* case (a, null) => cb(Right(a))
* case (_, e) => cb(Left(e))
* }
*
* //Cancel the completable future if the fiber is canceled
* Some(IO(stage.cancel(false)).void)
* }