-
Notifications
You must be signed in to change notification settings - Fork 510
/
SyncIO.scala
478 lines (436 loc) · 17 KB
/
SyncIO.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
/*
* Copyright (c) 2017-2021 The Typelevel Cats-effect Project Developers
*
* 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
package effect
import scala.annotation.unchecked.uncheckedVariance
import cats.data.Ior
/**
* A pure abstraction representing the intention to perform a
* side effect, where the result of that side effect is obtained
* synchronously.
*
* `SyncIO` is similar to [[IO]], but does not support asynchronous
* computations. Consequently, a `SyncIO` can be run synchronously
* to obtain a result via `unsafeRunSync`. This is unlike
* `IO#unsafeRunSync`, which cannot be safely called in general --
* doing so on the JVM blocks the calling thread while the
* async part of the computation is run and doing so on Scala.js
* throws an exception upon encountering an async boundary.
*/
final class SyncIO[+A] private (private val io: IO[A]) {
def toIO: IO[A] =
IO(io.unsafeRunSync())
/**
* Produces the result by running the encapsulated effects as impure
* side effects.
*
* Any exceptions raised within the effect will be re-thrown during
* evaluation.
*
* As the name says, this is an UNSAFE function as it is impure and
* performs side effects and throws exceptions. You should ideally
* only call this function *once*, at the very end of your program.
*/
def unsafeRunSync(): A = io.unsafeRunSync()
/**
* Functor map on `SyncIO`. Given a mapping function, it transforms the
* value produced by the source, while keeping the `SyncIO` context.
*
* Any exceptions thrown within the function will be caught and
* sequenced in to the result `SyncIO[B]`.
*/
def map[B](f: A => B): SyncIO[B] = new SyncIO(io.map(f))
/**
* Monadic bind on `SyncIO`, used for sequentially composing two `SyncIO`
* actions, where the value produced by the first `SyncIO` is passed as
* input to a function producing the second `SyncIO` action.
*
* Due to this operation's signature, `flatMap` forces a data
* dependency between two `SyncIO` 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 in to the result `SyncIO[B]`.
*/
def flatMap[B](f: A => SyncIO[B]): SyncIO[B] = new SyncIO(io.flatMap(a => f(a).io))
/**
* 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 `SyncIO.raiseError`. Thus:
*
* {{{
* SyncIO.raiseError(ex).attempt.unsafeRunSync === Left(ex)
* }}}
*
* @see [[SyncIO.raiseError]]
*/
def attempt: SyncIO[Either[Throwable, A]] = new SyncIO(io.attempt)
/**
* 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(io)
/**
* Returns a `SyncIO` 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.
*
* If an exception is raised, then `bracket` will re-raise the
* exception ''after'' performing the `release`.
*
* '''NOTE on error handling''': one big difference versus
* `try/finally` statements is that, in case both the `release`
* function and the `use` function throws, the error raised by `use`
* gets signaled.
*
* For example:
*
* {{{
* SyncIO("resource").bracket { _ =>
* // use
* SyncIO.raiseError(new RuntimeException("Foo"))
* } { _ =>
* // release
* SyncIO.raiseError(new RuntimeException("Bar"))
* }
* }}}
*
* In this case the error signaled downstream is `"Foo"`, while the
* `"Bar"` error gets reported. This is consistent with the behavior
* of Haskell's `bracket` operation and NOT with `try {} finally {}`
* from Scala, Java or JavaScript.
*
* @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 => SyncIO[B])(release: A => SyncIO[Unit]): SyncIO[B] =
bracketCase(use)((a, _) => release(a))
/**
* Returns a new `SyncIO` 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 failure, 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.
*
* In comparison with the simpler [[bracket]] version, this one
* allows the caller to differentiate between normal termination and
* termination in error. Note `SyncIO` does not support cancelation
* so that exit case should be ignored.
*
* @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, receiving
* as input the resource that needs that needs release,
* along with the result of `use` (error or successful result)
*/
def bracketCase[B](use: A => SyncIO[B])(release: (A, ExitCase[Throwable]) => SyncIO[Unit]): SyncIO[B] =
flatMap { a =>
use(a).redeemWith(
t => release(a, ExitCase.Error(t)).flatMap(_ => SyncIO.raiseError(t)),
b => release(a, ExitCase.Completed).map(_ => b)
)
}
/**
* Executes the given `finalizer` when the source is finished,
* either in success or in error.
*
* This variant of [[guaranteeCase]] evaluates the given `finalizer`
* regardless of how the source gets terminated:
*
* - normal completion
* - completion in error
*
* This equivalence always holds:
*
* {{{
* io.guarantee(f) <-> IO.unit.bracket(_ => io)(_ => f)
* }}}
*
* As best practice, it's not a good idea to release resources
* via `guaranteeCase` in polymorphic code. Prefer [[bracket]]
* for the acquisition and release of resources.
*
* @see [[guaranteeCase]] for the version that can discriminate
* between termination conditions
*
* @see [[bracket]] for the more general operation
*/
def guarantee(finalizer: SyncIO[Unit]): SyncIO[A] =
guaranteeCase(_ => finalizer)
/**
* Executes the given `finalizer` when the source is finished,
* either in success or in error, allowing
* for differentiating between exit conditions.
*
* This variant of [[guarantee]] injects an [[ExitCase]] in
* the provided function, allowing one to make a difference
* between:
*
* - normal completion
* - completion in error
*
* This equivalence always holds:
*
* {{{
* io.guaranteeCase(f) <-> IO.unit.bracketCase(_ => io)((_, e) => f(e))
* }}}
*
* As best practice, it's not a good idea to release resources
* via `guaranteeCase` in polymorphic code. Prefer [[bracketCase]]
* for the acquisition and release of resources.
*
* @see [[guarantee]] for the simpler version
*
* @see [[bracketCase]] for the more general operation
*/
def guaranteeCase(finalizer: ExitCase[Throwable] => SyncIO[Unit]): SyncIO[A] =
redeemWith(
t => finalizer(ExitCase.Error(t)).flatMap(_ => SyncIO.raiseError(t)),
a => finalizer(ExitCase.Completed).map(_ => a)
)
/**
* Handle any error, potentially recovering from it, by mapping it to another
* `SyncIO` value.
*
* Implements `ApplicativeError.handleErrorWith`.
*/
def handleErrorWith[AA >: A](f: Throwable => SyncIO[AA]): SyncIO[AA] =
new SyncIO(io.handleErrorWith(t => f(t).io))
/**
* 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): SyncIO[B] =
new SyncIO(io.redeem(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 => SyncIO[B], bind: A => SyncIO[B]): SyncIO[B] =
new SyncIO(io.redeemWith(t => recover(t).io, a => bind(a).io))
override def toString: String = io match {
case IO.Pure(a) => s"SyncIO($a)"
case IO.RaiseError(e) => s"SyncIO(throw $e)"
case _ => "SyncIO$" + System.identityHashCode(this)
}
}
object SyncIO extends SyncIOInstances {
/**
* Suspends a synchronous side effect in `SyncIO`.
*
* Any exceptions thrown by the effect will be caught and sequenced
* into the `SyncIO`.
*/
def apply[A](thunk: => A): SyncIO[A] = new SyncIO(IO(thunk))
/**
* Suspends a synchronous side effect which produces a `SyncIO` in `SyncIO`.
*
* 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
* `SyncIO`.
*/
def defer[A](thunk: => SyncIO[A]): SyncIO[A] = new SyncIO(IO.defer(thunk.toIO))
/**
* Suspends a synchronous side effect which produces a `SyncIO` in `SyncIO`.
*
* 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
* `SyncIO`.
*/
@deprecated("use defer", "2.5.3")
def suspend[A](thunk: => SyncIO[A]): SyncIO[A] = defer(thunk)
/**
* Suspends a pure value in `SyncIO`.
*
* This should ''only'' be used if the value in question has
* "already" been computed! In other words, something like
* `SyncIO.pure(readLine)` is most definitely not the right thing to do!
* However, `SyncIO.pure(42)` is correct and will be more efficient
* (when evaluated) than `SyncIO(42)`, due to avoiding the allocation of
* extra thunks.
*/
def pure[A](a: A): SyncIO[A] = new SyncIO(IO.pure(a))
/** Alias for `SyncIO.pure(())`. */
val unit: SyncIO[Unit] = pure(())
/**
* Lifts an `Eval` into `SyncIO`.
*
* This function will preserve the evaluation semantics of any
* actions that are lifted into the pure `SyncIO`. Eager `Eval`
* instances will be converted into thunk-less `SyncIO` (i.e. eager
* `SyncIO`), while lazy eval and memoized will be executed as such.
*/
def eval[A](fa: Eval[A]): SyncIO[A] = fa match {
case Now(a) => pure(a)
case notNow => apply(notNow.value)
}
/**
* Constructs a `SyncIO` which sequences the specified exception.
*
* If this `SyncIO` is run using `unsafeRunSync` the exception will
* be thrown. This exception can be "caught" (or rather, materialized
* into value-space) using the `attempt` method.
*
* @see [[SyncIO#attempt]]
*/
def raiseError[A](e: Throwable): SyncIO[A] = new SyncIO(IO.raiseError(e))
/**
* Lifts an `Either[Throwable, A]` into the `SyncIO[A]` context, raising
* the throwable if it exists.
*/
def fromEither[A](e: Either[Throwable, A]): SyncIO[A] = new SyncIO(IO.fromEither(e))
}
abstract private[effect] class SyncIOInstances extends SyncIOLowPriorityInstances {
implicit val syncIOsyncEffect: SyncEffect[SyncIO] = new SyncIOSync with SyncEffect[SyncIO] {
final override def runSync[G[_], A](fa: SyncIO[A])(implicit G: Sync[G]): G[A] =
G.delay(fa.unsafeRunSync())
}
implicit val syncIOalign: Align[SyncIO] = new Align[SyncIO] {
def align[A, B](fa: SyncIO[A], fb: SyncIO[B]): SyncIO[Ior[A, B]] =
alignWith(fa, fb)(identity)
override def alignWith[A, B, C](fa: SyncIO[A], fb: SyncIO[B])(f: Ior[A, B] => C): SyncIO[C] =
fa.redeemWith(
t => fb.redeemWith(_ => SyncIO.raiseError(t), b => SyncIO.pure(f(Ior.right(b)))),
a => fb.redeem(_ => f(Ior.left(a)), b => f(Ior.both(a, b)))
)
def functor: Functor[SyncIO] = Functor[SyncIO]
}
@deprecated("Signature changed to return SyncEffect", "2.1.0")
val syncIoSync: Sync[SyncIO] = new SyncIOSync {}
implicit def syncIoMonoid[A: Monoid]: Monoid[SyncIO[A]] = new SyncIOSemigroup[A] with Monoid[SyncIO[A]] {
def empty: SyncIO[A] = SyncIO.pure(Monoid[A].empty)
}
implicit val syncIoSemigroupK: SemigroupK[SyncIO] = new SemigroupK[SyncIO] {
final override def combineK[A](a: SyncIO[A], b: SyncIO[A]): SyncIO[A] =
a.handleErrorWith(_ => b)
}
}
abstract private[effect] class SyncIOLowPriorityInstances {
private[effect] class SyncIOSemigroup[A: Semigroup] extends Semigroup[SyncIO[A]] {
def combine(sioa1: SyncIO[A], sioa2: SyncIO[A]): SyncIO[A] =
sioa1.flatMap(a1 => sioa2.map(a2 => Semigroup[A].combine(a1, a2)))
}
implicit def syncIoSemigroup[A: Semigroup]: Semigroup[SyncIO[A]] = new SyncIOSemigroup[A]
}
abstract private[effect] class SyncIOSync extends Sync[SyncIO] with StackSafeMonad[SyncIO] {
final override def pure[A](a: A): SyncIO[A] =
SyncIO.pure(a)
final override def unit: SyncIO[Unit] =
SyncIO.unit
final override def map[A, B](fa: SyncIO[A])(f: A => B): SyncIO[B] =
fa.map(f)
final override def flatMap[A, B](ioa: SyncIO[A])(f: A => SyncIO[B]): SyncIO[B] =
ioa.flatMap(f)
final override def attempt[A](ioa: SyncIO[A]): SyncIO[Either[Throwable, A]] =
ioa.attempt
final override def handleErrorWith[A](ioa: SyncIO[A])(f: Throwable => SyncIO[A]): SyncIO[A] =
ioa.handleErrorWith(f)
final override def raiseError[A](e: Throwable): SyncIO[A] =
SyncIO.raiseError(e)
final override def bracket[A, B](acquire: SyncIO[A])(use: A => SyncIO[B])(release: A => SyncIO[Unit]): SyncIO[B] =
acquire.bracket(use)(release)
final override def uncancelable[A](task: SyncIO[A]): SyncIO[A] =
task
final override def bracketCase[A, B](
acquire: SyncIO[A]
)(use: A => SyncIO[B])(release: (A, ExitCase[Throwable]) => SyncIO[Unit]): SyncIO[B] =
acquire.bracketCase(use)(release)
final override def guarantee[A](fa: SyncIO[A])(finalizer: SyncIO[Unit]): SyncIO[A] =
fa.guarantee(finalizer)
final override def guaranteeCase[A](fa: SyncIO[A])(finalizer: ExitCase[Throwable] => SyncIO[Unit]): SyncIO[A] =
fa.guaranteeCase(finalizer)
final override def delay[A](thunk: => A): SyncIO[A] =
SyncIO(thunk)
final override def suspend[A](thunk: => SyncIO[A]): SyncIO[A] =
SyncIO.defer(thunk)
}