-
Notifications
You must be signed in to change notification settings - Fork 6
/
asynchronous.scala
368 lines (329 loc) · 12.5 KB
/
asynchronous.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
package com.thoughtworks.raii
import com.thoughtworks.raii.covariant.{ResourceT, Releasable}
import com.thoughtworks.tryt.covariant.TryT
import scala.concurrent.ExecutionContext
import scalaz.{-\/, @@, Applicative, ContT, Monad, MonadError, Semigroup, \/, \/-}
import scalaz.concurrent.{Future, Task}
import scala.language.higherKinds
import scala.util.{Failure, Success, Try}
import scalaz.Free.Trampoline
import scalaz.Tags.Parallel
import scalaz.std.`try`
import ResourceT._
import TryT._
import com.thoughtworks.raii.shared._
/** The namespace that contains [[Do]].
*
* @author 杨博 (Yang Bo) <pop.atry@gmail.com>
*/
object asynchronous {
/** @template */
private type RAIIFuture[+Value] = ResourceT[Future, Value]
private[asynchronous] trait OpacityTypes {
type Do[+Value]
private[asynchronous] def fromTryT[Value](run: TryT[ResourceT[Future, `+?`], Value]): Do[Value]
private[asynchronous] def toTryT[Value](doValue: Do[Value]): TryT[RAIIFuture, Value]
//TODO: BindRec
implicit private[asynchronous] def doMonadErrorInstances: MonadError[Do, Throwable]
implicit private[asynchronous] def doParallelApplicative(
implicit throwableSemigroup: Semigroup[Throwable]): Applicative[Lambda[Value => Do[Value] @@ Parallel]]
}
/** The type-level [[http://en.cppreference.com/w/cpp/language/pimpl Pimpl]] in order to prevent the Scala compiler seeing the actual type of [[Do]]
*
* @note For internal usage only.
*/
val opacityTypes: OpacityTypes = new OpacityTypes {
override type Do[+Value] = TryT[RAIIFuture, Value]
override private[asynchronous] def fromTryT[Value](run: TryT[RAIIFuture, Value]): TryT[RAIIFuture, Value] = run
override private[asynchronous] def toTryT[Value](doa: TryT[RAIIFuture, Value]): TryT[RAIIFuture, Value] = doa
override private[asynchronous] def doMonadErrorInstances: MonadError[TryT[RAIIFuture, ?], Throwable] = {
TryT.tryTMonadError[RAIIFuture](ResourceT.resourceTMonad[Future](Future.futureInstance))
}
override private[asynchronous] def doParallelApplicative(implicit throwableSemigroup: Semigroup[Throwable]) = {
TryT.tryTParallelApplicative[RAIIFuture](
ResourceT.resourceTParallelApplicative[Future](Future.futureParallelApplicativeInstance),
throwableSemigroup)
}
}
/** An universal monadic data type that consists of many useful monad transformers.
*
* == Features of `Do` ==
* - [[com.thoughtworks.tryt.covariant.TryT exception handling]]
* - [[com.thoughtworks.raii.covariant.ResourceT automatic resource management]]
* - [[Do$.shared reference counting]]
* - [[scalaz.concurrent.Future asynchronous programming]]
* - [[ParallelDo parallel computing]]
*
* @note This `Do` type is an [[https://www.reddit.com/r/scala/comments/5qbdgq/value_types_without_anyval/dcxze9q/ opacity alias]] to `Future[Releasable[Future, Try[Value]]]`.
* @see [[Do$ Do]] companion object for all type classes and helper functions for this `Do` type.
* @template
*/
type Do[+Value] = opacityTypes.Do[Value]
/** A [[Do]] tagged as [[scalaz.Tags.Parallel Parallel]].
*
* @example `ParallelDo` and [[Do]] can be converted to each other via [[scalaz.Tags.Parallel]].
*
* Given a [[Do]],
*
* {{{
* import com.thoughtworks.raii.asynchronous.{Do, ParallelDo}
* import java.net._
* import java.io._
* val originalDoInput: Do[InputStream] = Do.scoped(new URL("http://thoughtworks.com/").openStream())
* }}}
*
* when converting it to `ParallelDo` and converting it back,
*
* {{{
* import scalaz.Tags.Parallel
* val parallelDoInput: ParallelDo[InputStream] = Parallel(originalDoInput)
* val Parallel(doInput) = parallelDoInput
* }}}
*
* then the [[Do]] should be still the original instance.
*
* {{{
* doInput should be(originalDoInput)
* }}}
*
* @see [[ParallelDo.doParallelApplicative]] for the [[scalaz.Applicative Applicative]] type class for parallel computing.
*
* @template
*/
type ParallelDo[Value] = Do[Value] @@ Parallel
/** The companion object of [[ParallelDo]] */
object ParallelDo {
/** Returns an [[scalaz.Applicative Applicative]] type class for parallel computing.
*
* @note This type class requires a [[scalaz.Semigroup Semigroup]] to combine multiple `Throwable`s into one,
* in the case of multiple tasks report errors in parallel.
*/
implicit def doParallelApplicative(implicit throwableSemigroup: Semigroup[Throwable]): Applicative[ParallelDo] =
opacityTypes.doParallelApplicative
}
/** The companion object of [[Do]]
* @define now Converts a strict value to a `Do` whose [[covariant.Releasable.release release]] operation is no-op.
*
* @define seenow @see [[now]] for strict garbage collected `Do`
*
* @define delay Returns a non-strict `Do` whose [[covariant.Releasable.release release]] operation is no-op.
*
* @define seedelay @see [[delay]] for non-strict garbage collected `Do`
*
* @define scoped Returns a non-strict `Do` whose [[covariant.Releasable.release release]] operation is [[java.lang.AutoCloseable.close]].
*
* @define seescoped @see [[scoped]] for auto-closeable `Do`
*
* @define nonstrict Since the `Do` is non-strict,
* `Value` will be recreated each time it is sequenced into a larger `Do`.
*
* @define garbagecollected [[Value]] must be a garbage-collected type that does not hold native resource.
*/
object Do {
/** @group Type classes */
implicit def doMonadErrorInstances: MonadError[Do, Throwable] = opacityTypes.doMonadErrorInstances
/** @group Converters */
def apply[Value](future: Future[Releasable[Future, Try[Value]]]): Do[Value] = {
opacityTypes.fromTryT(TryT[RAIIFuture, Value](ResourceT(future)))
}
private def unwrap[Value](doValue: Do[Value]): Future[Releasable[Future, Try[Value]]] = {
val ResourceT(future) = TryT.unwrap(opacityTypes.toTryT(doValue))
future
}
/** Returns the underlying [[scalaz.concurrent.Future]] that creates a [[covariant.Releasable]] `Value`.
*
* @group Converters
*/
def unapply[Value](doValue: Do[Value]): Some[Future[Releasable[Future, Try[Value]]]] = {
Some(unwrap(doValue))
}
/** $scoped
* $nonstrict
* $seenow
* $seedelay
*/
def scoped[Value <: AutoCloseable](task: Task[Value]): Do[Value] = {
Do(
task.get.map { either =>
new Releasable[Future, Try[Value]] {
override def value: Try[Value] = `try`.fromDisjunction(either)
override def release(): Future[Unit] = {
either match {
case \/-(closeable) =>
Future.delay(closeable.close())
case -\/(_) =>
Future.now(())
}
}
}
}
)
}
/** $scoped
* $nonstrict
* $seenow
* $seedelay
*/
def scoped[Value <: AutoCloseable](future: Future[Value]): Do[Value] = {
scoped(new Task(future.map(\/-(_))))
}
/** $scoped
* $nonstrict
* $seenow
* $seedelay
*/
def scoped[Value <: AutoCloseable](continuation: ContT[Trampoline, Unit, Value]): Do[Value] = {
scoped(
new Task(
Future.Async { continue: ((Throwable \/ Value) => Trampoline[Unit]) =>
continuation { value: Value =>
continue(\/-(value))
}.run
}
)
)
}
/** $scoped
* $nonstrict
* $seenow
* $seedelay
*/
def scoped[Value <: AutoCloseable](value: => Value): Do[Value] = {
scoped(Task.delay(value))
}
/** $delay
* $nonstrict
* $seenow
* $seescoped
*/
def delay[Value](task: Task[Value]): Do[Value] = {
Do(
task.get.map { either =>
Releasable.now[Future, Try[Value]](`try`.fromDisjunction(either))
}
)
}
/** $delay
* $nonstrict
* $seenow
* $seescoped
*/
def delay[Value](future: Future[Value]): Do[Value] = {
delay(new Task(future.map(\/-(_))))
}
/** $delay
* $nonstrict
* $seenow
* $seescoped
*/
def delay[Value](continuation: ContT[Trampoline, Unit, Value]): Do[Value] = {
delay(
new Task(
Future.Async { continue: ((Throwable \/ Value) => Trampoline[Unit]) =>
continuation { value: Value =>
continue(\/-(value))
}.run
}
)
)
}
/** $delay
* $nonstrict
* $seenow
* $seescoped
*/
def delay[Value](value: => Value): Do[Value] = {
delay(Task.delay(value))
}
/** $now
* $seedelay
* $seescoped
*/
def now[Value](value: Value): Do[Value] = {
delay(Task.now(value))
}
/** Returns a `Do` that runs in `executorContext`
*
* @note This method is usually been used for changing the current thread.
*
* {{{
* import java.util.concurrent._
* import scala.concurrent._
* import scalaz.syntax.all._
* import com.thoughtworks.raii.asynchronous.Do, Do._
*
* implicit def executorContext = ExecutionContext.fromExecutor(Executors.newSingleThreadExecutor())
*
* val mainThread = Thread.currentThread
*
* Do.run {
* for {
* _ <- Do.delay(())
* threadBeforeJump = Thread.currentThread
* _ = threadBeforeJump should be(mainThread)
* _ <- Do.jump()
* threadAfterJump = Thread.currentThread
* } yield {
* threadAfterJump shouldNot be(mainThread)
* }
* }
* }}}
*/
def jump()(implicit executorContext: ExecutionContext): Do[Unit] = {
delay(Future.async { handler: (Unit => Unit) =>
executorContext.execute { () =>
handler(())
}
})
}
/**
* Returns a `Task` of `Value`, which will open `Value` and release all resources during opening `Value`.
*
* @note `Value` itself must not be a [[scoped]] resources,
* though `Value` may depends on some [[scoped]] resources during opening `Value`.
*/
def run[Value](doValue: Do[Value]): Task[Value] = {
val future: Future[Throwable \/ Value] =
ResourceT.run(ResourceT(Do.unwrap(doValue))).map(`try`.toDisjunction)
new Task(future)
}
/** Returns a `Do` of `B` based on a `Do` of `Value` and a function that creates a `Do` of `B`.
*
* @note `releaseFlatMap` is similar to `flatMap` in [[doMonadErrorInstances]],
* except `releaseFlatMap` will release `Value` right after `B` is created.
*/
def releaseFlatMap[Value, B](doValue: Do[Value])(f: Value => Do[B]): Do[B] = {
val resourceA = ResourceT(Do.unwrap(doValue))
val resourceB = ResourceT.releaseFlatMap[Future, Try[Value], Try[B]](resourceA) {
case Failure(e) =>
ResourceT(Future.now(Releasable.now(Failure(e))))
case Success(value) =>
ResourceT(Do.unwrap(f(value)))
}
val ResourceT(future) = resourceB
Do(future)
}
/** Returns a `Do` of `B` based on a `Do` of `Value` and a function that creates `B`.
*
* @note `releaseMap` is similar to `map` in [[doMonadErrorInstances]],
* except `releaseMap` will release `Value` right after `B` is created.
*/
def releaseMap[Value, B](doValue: Do[Value])(f: Value => B): Do[B] = {
val resourceA = ResourceT(Do.unwrap(doValue))
val resourceB = ResourceT.releaseMap(resourceA)(_.map(f))
val ResourceT(future) = resourceB
Do(future)
}
/** Converts `doValue` to a reference counted wrapper `Do`.
*
* When the wrapper `Do` is used by multiple larger `Do` at the same time,
* only one `Value` instance is created.
* The underlying `Value` will be [[covariant.Releasable.release release]]d only once,
* when all users [[covariant.Releasable.release release]] the wrapper `Do`.
*/
def shared[Value](doValue: Do[Value]): Do[Value] = {
val sharedFuture: RAIIFuture[Try[Value]] = TryT.unwrap(opacityTypes.toTryT(doValue)).shared
opacityTypes.fromTryT(TryT(sharedFuture))
}
}
}