-
Notifications
You must be signed in to change notification settings - Fork 508
/
Concurrent.scala
479 lines (441 loc) · 16.9 KB
/
Concurrent.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
/*
* Copyright (c) 2017-2018 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 simulacrum._
import cats.data.{EitherT, OptionT, StateT, WriterT}
import cats.effect.IO.{Delay, Pure, RaiseError}
import cats.effect.internals.IORunLoop
import cats.syntax.all._
import scala.annotation.implicitNotFound
import scala.util.Either
/**
* Type class for [[Async]] data types that are cancelable and
* can be started concurrently.
*
* Thus this type class allows abstracting over data types that:
*
* 1. implement the [[Async]] algebra, with all its restrictions
* 1. can provide logic for cancelation, to be used in race
* conditions in order to release resources early
* (in its [[Concurrent!.cancelable cancelable]] builder)
*
* Due to these restrictions, this type class also affords to describe
* a [[Concurrent!.start start]] operation that can start async
* processing, suspended in the context of `F[_]` and that can be
* cancelled or joined.
*
* Without cancelation being baked in, we couldn't afford to do it.
* See below.
*
* ==Cancelable builder==
*
* The signature exposed by the [[Concurrent!.cancelable cancelable]]
* builder is this:
*
* {{{
* (Either[Throwable, A] => Unit) => F[Unit]
* }}}
*
* `F[Unit]` is used to represent a cancelation action which will
* send a signal to the producer, that may observe it and cancel the
* asynchronous process.
*
* ==On Cancellation==
*
* Simple asynchronous processes, like Scala's `Future`, can be
* described with this very basic and side-effectful type and you
* should recognize what is more or less the signature of
* `Future#onComplete` or of [[Async.async]] (minus the error
* handling):
*
* {{{
* (A => Unit) => Unit
* }}}
*
* But many times the abstractions built to deal with asynchronous
* tasks can also provide a way to cancel such processes, to be used
* in race conditions in order to cleanup resources early, so a very
* basic and side-effectful definition of asynchronous processes that
* can be cancelled would be:
*
* {{{
* (A => Unit) => Cancelable
* }}}
*
* This is approximately the signature of JavaScript's `setTimeout`,
* which will return a "task ID" that can be used to cancel it. Or of
* Java's `ScheduledExecutorService#schedule`, which will return a
* Java `ScheduledFuture` that has a `.cancel()` operation on it.
*
* Similarly, for `Concurrent` data types, we can provide
* cancelation logic, that can be triggered in race conditions to
* cancel the on-going processing, only that `Concurrent`'s
* cancelable token is an action suspended in an `IO[Unit]`. See
* [[IO.cancelable]].
*
* Suppose you want to describe a "sleep" operation, like that described
* by [[Timer]] to mirror Java's `ScheduledExecutorService.schedule`
* or JavaScript's `setTimeout`:
*
* {{{
* def sleep(d: FiniteDuration): F[Unit]
* }}}
*
* This signature is in fact incomplete for data types that are not
* cancelable, because such equivalent operations always return some
* cancelation token that can be used to trigger a forceful
* interruption of the timer. This is not a normal "dispose" or
* "finally" clause in a try/catch block, because "cancel" in the
* context of an asynchronous process is ''concurrent'' with the
* task's own run-loop.
*
* To understand what this means, consider that in the case of our
* `sleep` as described above, on cancelation we'd need a way to
* signal to the underlying `ScheduledExecutorService` to forcefully
* remove the scheduled `Runnable` from its internal queue of
* scheduled tasks, ''before'' its execution. Therefore, without a
* cancelable data type, a safe signature needs to return a
* cancelation token, so it would look like this:
*
* {{{
* def sleep(d: FiniteDuration): F[(F[Unit], F[Unit])]
* }}}
*
* This function is returning a tuple, with one `F[Unit]` to wait for
* the completion of our sleep and a second `F[Unit]` to cancel the
* scheduled computation in case we need it. This is in fact the shape
* of [[Fiber]]'s API. And this is exactly what the
* [[Concurrent!.start start]] operation returns.
*
* The difference between a [[Concurrent]] data type and one that
* is only [[Async]] is that you can go from any `F[A]` to a
* `F[Fiber[F, A]]`, to participate in race conditions and that can be
* cancelled should the need arise, in order to trigger an early
* release of allocated resources.
*
* Thus a [[Concurrent]] data type can safely participate in race
* conditions, whereas a data type that is only [[Async]] cannot do it
* without exposing and forcing the user to work with cancelation
* tokens. An [[Async]] data type cannot expose for example a `start`
* operation that is safe.
*/
@typeclass
@implicitNotFound("""Cannot find implicit value for Concurrent[${F}].
Building this implicit value might depend on having an implicit
s.c.ExecutionContext in scope, a Scheduler or some equivalent type.""")
trait Concurrent[F[_]] extends Async[F] {
/**
* Creates a cancelable `F[A]` instance that executes an
* asynchronous process on evaluation.
*
* This builder accepts a registration function that is
* being injected with a side-effectful callback, to be called
* when the asynchronous process is complete with a final result.
*
* The registration function is also supposed to return
* an `IO[Unit]` that captures the logic necessary for
* cancelling the asynchronous process, for as long as it
* is still active.
*
* Example:
*
* {{{
* import java.util.concurrent.ScheduledExecutorService
* import scala.concurrent.duration._
*
* def sleep[F[_]](d: FiniteDuration)
* (implicit F: Concurrent[F], ec: ScheduledExecutorService): F[A] = {
*
* F.cancelable { cb =>
* // Note the callback is pure, so we need to trigger evaluation
* val run = new Runnable { def run() = cb(Right(())).unsafeRunSync }
*
* // Schedules task to run after delay
* val future = ec.schedule(run, d.length, d.unit)
*
* // Cancellation logic, suspended in IO
* IO(future.cancel())
* }
* }
* }}}
*/
def cancelable[A](k: (Either[Throwable, A] => Unit) => IO[Unit]): F[A]
/**
* Returns a new `F` that mirrors the source, but that is uninterruptible.
*
* This means that the [[Fiber.cancel cancel]] signal has no effect on the
* result of [[Fiber.join join]] and that the cancelable token returned by
* [[ConcurrentEffect.runCancelable]] on evaluation will have no effect.
*
* This operation is undoing the cancelation mechanism of [[cancelable]],
* with this equivalence:
*
* {{{
* F.uncancelable(F.cancelable { cb => f(cb); io }) <-> F.async(f)
* }}}
*
* Sample:
*
* {{{
* val F = Concurrent[IO]
* val timer = Timer[IO]
*
* // Normally Timer#sleep yields cancelable tasks
* val tick = F.uncancelable(timer.sleep(10.seconds))
*
* // This prints "Tick!" after 10 seconds, even if we are
* // cancelling the Fiber after start:
* for {
* fiber <- F.start(tick)
* _ <- fiber.cancel
* _ <- fiber.join
* } yield {
* println("Tick!")
* }
* }}}
*
* Cancelable effects are great in race conditions, however sometimes
* this operation is necessary to ensure that the bind continuation
* of a task (the following `flatMap` operations) are also evaluated
* no matter what.
*/
def uncancelable[A](fa: F[A]): F[A]
/**
* Returns a new `F` value that mirrors the source for normal
* termination, but that triggers the given error on cancelation.
*
* This `onCancelRaiseError` operator transforms any task into one
* that on cancelation will terminate with the given error, thus
* transforming potentially non-terminating tasks into ones that
* yield a certain error.
*
* {{{
* import scala.concurrent.CancellationException
*
* val F = Concurrent[IO]
* val timer = Timer[IO]
*
* val error = new CancellationException("Boo!")
* val fa = F.onCancelRaiseError(timer.sleep(5.seconds, error))
*
* fa.start.flatMap { fiber =>
* fiber.cancel *> fiber.join
* }
* }}}
*
* Without "onCancelRaiseError" the [[Timer.sleep sleep]] operation
* yields a non-terminating task on cancellation. But by applying
* "onCancelRaiseError", the yielded task above will terminate with
* the indicated "CancellationException" reference, which we can
* then also distinguish from other errors thrown in the `F` context.
*
* Depending on the implementation, tasks that are canceled can
* become non-terminating. This operation ensures that when
* cancelation happens, the resulting task is terminated with an
* error, such that logic can be scheduled to happen after
* cancelation:
*
* {{{
* import scala.concurrent.CancellationException
* val wasCanceled = new CancellationException()
*
* F.onCancelRaiseError(fa, wasCanceled).attempt.flatMap {
* case Right(a) =>
* F.delay(println(s"Success: \$a"))
* case Left(`wasCanceled`) =>
* F.delay(println("Was canceled!"))
* case Left(error) =>
* F.delay(println(s"Terminated in error: \$error"))
* }
* }}}
*
* This technique is how a "bracket" operation can be implemented.
*
* Besides sending the cancelation signal, this operation also cuts
* the connection between the producer and the consumer. Example:
*
* {{{
* val F = Concurrent[IO]
* val timer = Timer[IO]
*
* // This task is uninterruptible ;-)
* val tick = F.uncancelable(
* for {
* _ <- timer.sleep(5.seconds)
* _ <- IO(println("Tick!"))
* } yield ())
*
* // Builds an value that triggers an exception on cancellation
* val loud = F.onCancelRaiseError(tick, new CancellationException)
* }}}
*
* In this example the `loud` reference will be completed with a
* "CancellationException", as indicated via "onCancelRaiseError".
* The logic of the source won't get cancelled, because we've
* embedded it all in [[uncancelable]]. But its bind continuation is
* not allowed to continue after that, its final result not being
* allowed to be signaled.
*
* Therefore this also transforms [[uncancelable]] values into ones
* that can be canceled. The logic of the source, its run-loop
* might not be interruptible, however `cancel` on a value on which
* `onCancelRaiseError` was applied will cut the connection from
* the producer, the consumer receiving the indicated error instead.
*/
def onCancelRaiseError[A](fa: F[A], e: Throwable): F[A]
/**
* Start concurrent execution of the source suspended in
* the `F` context.
*
* Returns a [[Fiber]] that can be used to either join or cancel
* the running computation, being similar in spirit (but not
* in implementation) to starting a thread.
*/
def start[A](fa: F[A]): F[Fiber[F, A]]
/**
* Inherited from [[LiftIO]], defines a conversion from [[IO]]
* in terms of the `Concurrent` type class.
*
* N.B. expressing this conversion in terms of `Concurrent` and
* its capabilities means that the resulting `F` is cancelable in
* case the source `IO` is.
*
* To access this implementation as a standalone function, you can
* use [[Concurrent$.liftIO Concurrent.liftIO]]
* (on the object companion).
*/
override def liftIO[A](ioa: IO[A]): F[A] =
Concurrent.liftIO(ioa)(this)
}
object Concurrent {
/**
* Lifts any `IO` value into any data type implementing [[Concurrent]].
*
* Compared with [[Async.liftIO]], this version preserves the
* interruptibility of the given `IO` value.
*
* This is the default `Concurrent.liftIO` implementation.
*/
def liftIO[F[_], A](ioa: IO[A])(implicit F: Concurrent[F]): F[A] =
ioa match {
case Pure(a) => F.pure(a)
case RaiseError(e) => F.raiseError(e)
case Delay(thunk) => F.delay(thunk())
case _ =>
F.suspend {
IORunLoop.step(ioa) match {
case Pure(a) => F.pure(a)
case RaiseError(e) => F.raiseError(e)
case async =>
F.cancelable(cb => IO.Delay(async.unsafeRunCancelable(cb)))
}
}
}
/**
* [[Concurrent]] instance built for `cats.data.EitherT` values initialized
* with any `F` data type that also implements `Concurrent`.
*/
implicit def catsEitherTConcurrent[F[_]: Concurrent, L]: Concurrent[EitherT[F, L, ?]] =
new EitherTConcurrent[F, L] { def F = Concurrent[F] }
/**
* [[Concurrent]] instance built for `cats.data.OptionT` values initialized
* with any `F` data type that also implements `Concurrent`.
*/
implicit def catsOptionTConcurrent[F[_]: Concurrent]: Concurrent[OptionT[F, ?]] =
new OptionTConcurrent[F] { def F = Concurrent[F] }
/**
* [[Concurrent]] instance built for `cats.data.StateT` values initialized
* with any `F` data type that also implements `Concurrent`.
*/
implicit def catsStateTAsync[F[_]: Concurrent, S]: Concurrent[StateT[F, S, ?]] =
new StateTConcurrent[F, S] { def F = Concurrent[F] }
/**
* [[Concurrent]] instance built for `cats.data.WriterT` values initialized
* with any `F` data type that also implements `Concurrent`.
*/
implicit def catsWriterTAsync[F[_]: Concurrent, L: Monoid]: Concurrent[WriterT[F, L, ?]] =
new WriterTConcurrent[F, L] { def F = Concurrent[F]; def L = Monoid[L] }
private[effect] trait EitherTConcurrent[F[_], L] extends Async.EitherTAsync[F, L]
with Concurrent[EitherT[F, L, ?]] {
override protected implicit def F: Concurrent[F]
override protected def FF = F
def cancelable[A](k: (Either[Throwable, A] => Unit) => IO[Unit]): EitherT[F, L, A] =
EitherT.liftF(F.cancelable(k))(F)
def uncancelable[A](fa: EitherT[F, L, A]): EitherT[F, L, A] =
EitherT(F.uncancelable(fa.value))
def onCancelRaiseError[A](fa: EitherT[F, L, A], e: Throwable): EitherT[F, L, A] =
EitherT(F.onCancelRaiseError(fa.value, e))
def start[A](fa: EitherT[F, L, A]) =
EitherT.liftF(
F.start(fa.value).map { fiber =>
Fiber(
EitherT(fiber.join),
EitherT.liftF(fiber.cancel))
})
}
private[effect] trait OptionTConcurrent[F[_]] extends Async.OptionTAsync[F]
with Concurrent[OptionT[F, ?]] {
override protected implicit def F: Concurrent[F]
override protected def FF = F
def cancelable[A](k: (Either[Throwable, A] => Unit) => IO[Unit]): OptionT[F, A] =
OptionT.liftF(F.cancelable(k))(F)
def uncancelable[A](fa: OptionT[F, A]): OptionT[F, A] =
OptionT(F.uncancelable(fa.value))
def onCancelRaiseError[A](fa: OptionT[F, A], e: Throwable): OptionT[F, A] =
OptionT(F.onCancelRaiseError(fa.value, e))
def start[A](fa: OptionT[F, A]) = {
OptionT.liftF(
F.start(fa.value).map { fiber =>
Fiber(OptionT(fiber.join), OptionT.liftF(fiber.cancel))
})
}
}
private[effect] trait StateTConcurrent[F[_], S] extends Async.StateTAsync[F, S]
with Concurrent[StateT[F, S, ?]] {
override protected implicit def F: Concurrent[F]
override protected def FA = F
def cancelable[A](k: (Either[Throwable, A] => Unit) => IO[Unit]): StateT[F, S, A] =
StateT.liftF(F.cancelable(k))(F)
def uncancelable[A](fa: StateT[F, S, A]): StateT[F, S, A] =
fa.transformF(F.uncancelable)
def onCancelRaiseError[A](fa: StateT[F, S, A], e: Throwable): StateT[F, S, A] =
fa.transformF(F.onCancelRaiseError(_, e))
def start[A](fa: StateT[F, S, A]) =
StateT(s => F.start(fa.run(s)).map { fiber =>
(s, Fiber(
StateT(_ => fiber.join),
StateT.liftF(fiber.cancel)))
})
}
private[effect] trait WriterTConcurrent[F[_], L] extends Async.WriterTAsync[F, L]
with Concurrent[WriterT[F, L, ?]] {
override protected implicit def F: Concurrent[F]
override protected def FA = F
def cancelable[A](k: (Either[Throwable, A] => Unit) => IO[Unit]): WriterT[F, L, A] =
WriterT.liftF(F.cancelable(k))(L, F)
def uncancelable[A](fa: WriterT[F, L, A]): WriterT[F, L, A] =
WriterT(F.uncancelable(fa.run))
def onCancelRaiseError[A](fa: WriterT[F, L, A], e: Throwable): WriterT[F, L, A] =
WriterT(F.onCancelRaiseError(fa.run, e))
def start[A](fa: WriterT[F, L, A]) =
WriterT(F.start(fa.run).map { fiber =>
(L.empty, Fiber(
WriterT(fiber.join),
WriterT.liftF(fiber.cancel)))
})
}
}