/
ConcurrentLaws.scala
287 lines (251 loc) · 8.55 KB
/
ConcurrentLaws.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
/*
* Copyright (c) 2017-2019 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.effect
package laws
import cats.effect.concurrent.{Deferred, MVar, Semaphore}
import cats.laws._
import cats.syntax.all._
import scala.Predef.{identity => id}
import scala.concurrent.Promise
trait ConcurrentLaws[F[_]] extends AsyncLaws[F] {
implicit def F: Concurrent[F]
implicit val contextShift: ContextShift[F]
def cancelOnBracketReleases[A, B](a: A, f: (A, A) => B) = {
val received = for {
// A deferred that waits for `use` to get executed
startLatch <- Deferred[F, A]
// A deferred that waits for `release` to be executed
exitLatch <- Deferred[F, A]
// What we're actually testing
bracketed = F.bracketCase(F.pure(a))(a => startLatch.complete(a) *> F.never[A]) {
case (r, ExitCase.Canceled) => exitLatch.complete(r)
case (_, _) => F.unit
}
// Forked execution, allowing us to cancel it later
fiber <- F.start(bracketed)
// Waits for the `use` action to execute
waitStart <- startLatch.get
// Triggers cancellation
_ <- F.start(fiber.cancel)
// Observes cancellation via bracket's `release`
waitExit <- exitLatch.get
} yield f(waitStart, waitExit)
received <-> F.pure(f(a, a))
}
def asyncCancelableCoherence[A](r: Either[Throwable, A]) = {
F.async[A](cb => cb(r)) <-> F.cancelable[A] { cb => cb(r); F.unit }
}
def asyncCancelableReceivesCancelSignal[A](a: A) = {
val lh = for {
release <- Deferred.uncancelable[F, A]
latch = Promise[Unit]()
async = F.cancelable[Unit] { _ => latch.success(()); release.complete(a) }
fiber <- F.start(async)
_ <- F.liftIO(IO.fromFuture(IO.pure(latch.future)))
_ <- F.start(fiber.cancel)
result <- release.get
} yield result
lh <-> F.pure(a)
}
def asyncFRegisterCanBeCancelled[A](a: A) = {
val lh = for {
release <- Deferred[F, A]
acquire <- Deferred[F, Unit]
task = F.asyncF[Unit] { _ =>
F.bracket(acquire.complete(()))(_ => F.never[Unit])(_ => release.complete(a))
}
fiber <- F.start(task)
_ <- acquire.get
_ <- F.start(fiber.cancel)
a <- release.get
} yield a
lh <-> F.pure(a)
}
def startJoinIsIdentity[A](fa: F[A]) =
F.start(fa).flatMap(_.join) <-> fa
def joinIsIdempotent[A](a: A) = {
val lh = Deferred[F, A].flatMap { p =>
// N.B. doing effect.complete twice triggers error
F.start(p.complete(a)).flatMap(t => t.join *> t.join) *> p.get
}
lh <-> F.pure(a)
}
def startCancelIsUnit[A](fa: F[A]) = {
F.start(fa).flatMap(_.cancel) <-> F.unit
}
def uncancelableMirrorsSource[A](fa: F[A]) = {
F.uncancelable(fa) <-> fa
}
def uncancelablePreventsCancelation[A](a: A) = {
val lh = Deferred.uncancelable[F, A].flatMap { p =>
val async = F.cancelable[Unit](_ => p.complete(a))
F.start(F.uncancelable(async)).flatMap(_.cancel) *> p.get
}
// Non-terminating
lh <-> F.never
}
def acquireIsNotCancelable[A](a1: A, a2: A) = {
val lh =
for {
mVar <- MVar[F].of(a1)
latch <- Deferred.uncancelable[F, Unit]
task = F.bracket(latch.complete(()) *> mVar.put(a2))(_ => F.never[A])(_ => F.unit)
fiber <- F.start(task)
_ <- latch.get
_ <- F.start(fiber.cancel)
_ <- contextShift.shift
_ <- mVar.take
out <- mVar.take
} yield out
lh <-> F.pure(a2)
}
def releaseIsNotCancelable[A](a1: A, a2: A) = {
val lh =
for {
mVar <- MVar[F].of(a1)
latch <- Deferred.uncancelable[F, Unit]
task = F.bracket(latch.complete(()))(_ => F.never[A])(_ => mVar.put(a2))
fiber <- F.start(task)
_ <- latch.get
_ <- F.start(fiber.cancel)
_ <- contextShift.shift
_ <- mVar.take
out <- mVar.take
} yield out
lh <-> F.pure(a2)
}
def raceMirrorsLeftWinner[A](fa: F[A], default: A) = {
F.race(fa, F.never[A]).map(_.left.getOrElse(default)) <-> fa
}
def raceMirrorsRightWinner[A](fa: F[A], default: A) = {
F.race(F.never[A], fa).map(_.right.getOrElse(default)) <-> fa
}
def raceCancelsLoser[A, B](r: Either[Throwable, A], leftWinner: Boolean, b: B) = {
val received = for {
s <- Semaphore[F](0L)
effect <- Deferred.uncancelable[F, B]
winner = s.acquire *> F.async[A](_(r))
loser = F.bracket(s.release)(_ => F.never[A])(_ => effect.complete(b))
race =
if (leftWinner) F.race(winner, loser)
else F.race(loser, winner)
b <- F.attempt(race) *> effect.get
} yield b
received <-> F.pure(b)
}
def raceCancelsBoth[A, B, C](a: A, b: B, f: (A, B) => C) = {
val fc = for {
s <- Semaphore[F](0L)
pa <- Deferred.uncancelable[F, A]
loserA = F.bracket(s.release)(_ => F.never[A])(_ => pa.complete(a))
pb <- Deferred.uncancelable[F, B]
loserB = F.bracket(s.release)(_ => F.never[B])(_ => pb.complete(b))
race <- F.start(F.race(loserA, loserB))
_ <- s.acquireN(2L) *> F.start(race.cancel)
a <- pa.get
b <- pb.get
} yield f(a, b)
fc <-> F.pure(f(a, b))
}
def racePairMirrorsLeftWinner[A](fa: F[A]) = {
val never = F.never[A]
val received =
F.racePair(fa, never).flatMap {
case Left((a, fiberB)) =>
fiberB.cancel.map(_ => a)
case Right(_) =>
F.raiseError[A](new IllegalStateException("right"))
}
received <-> F.race(fa, never).map(_.fold(id, id))
}
def racePairMirrorsRightWinner[B](fb: F[B]) = {
val never = F.never[B]
val received =
F.racePair(never, fb).flatMap {
case Right((fiberA, b)) =>
fiberA.cancel.map(_ => b)
case Left(_) =>
F.raiseError[B](new IllegalStateException("left"))
}
received <-> F.race(never, fb).map(_.fold(id, id))
}
def racePairCancelsLoser[A, B](r: Either[Throwable, A], leftWinner: Boolean, b: B) = {
val received: F[B] = for {
s <- Semaphore[F](0L)
effect <- Deferred.uncancelable[F, B]
winner = s.acquire *> F.async[A](_(r))
loser = F.bracket(s.release)(_ => F.never[A])(_ => effect.complete(b))
race =
if (leftWinner) F.racePair(winner, loser)
else F.racePair(loser, winner)
b <- F.attempt(race).flatMap {
case Right(Left((_, fiber))) =>
F.start(fiber.cancel) *> effect.get
case Right(Right((fiber, _))) =>
F.start(fiber.cancel) *> effect.get
case Left(_) =>
effect.get
}
} yield b
received <-> F.pure(b)
}
def racePairCanJoinLeft[A](a: A) = {
val lh = Deferred[F, A].flatMap { fa =>
F.racePair(fa.get, F.unit).flatMap {
case Left((l, _)) => F.pure(l)
case Right((fiberL, _)) =>
fa.complete(a) *> fiberL.join
}
}
lh <-> F.pure(a)
}
def racePairCanJoinRight[A](a: A) = {
val lh = Deferred[F, A].flatMap { fa =>
F.racePair(F.unit, fa.get).flatMap {
case Left((_, fiberR)) =>
fa.complete(a) *> fiberR.join
case Right((_, r)) =>
F.pure(r)
}
}
lh <-> F.pure(a)
}
def racePairCancelsBoth[A, B, C](a: A, b: B, f: (A, B) => C) = {
val fc = for {
s <- Semaphore[F](0L)
pa <- Deferred.uncancelable[F, A]
loserA = F.bracket(s.release)(_ => F.never[A])(_ => pa.complete(a))
pb <- Deferred.uncancelable[F, B]
loserB = F.bracket(s.release)(_ => F.never[B])(_ => pb.complete(b))
race <- F.start(F.racePair(loserA, loserB))
_ <- s.acquireN(2L) *> race.cancel
a <- pa.get
b <- pb.get
} yield f(a, b)
fc <-> F.pure(f(a, b))
}
def actionConcurrentWithPureValueIsJustAction[A](fa: F[A], a: A) = (for {
fiber <- F.start(a.pure)
x <- fa
_ <- fiber.join
} yield x) <-> fa
}
object ConcurrentLaws {
def apply[F[_]](implicit F0: Concurrent[F], contextShift0: ContextShift[F]): ConcurrentLaws[F] = new ConcurrentLaws[F] {
val F = F0
val contextShift = contextShift0
}
}