forked from monix/monix
/
TaskConnection.scala
222 lines (197 loc) · 7.09 KB
/
TaskConnection.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
/*
* Copyright (c) 2014-2020 by The Monix Project Developers.
* See the project homepage at: https://monix.io
*
* 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 monix.eval
package internal
import cats.effect.CancelToken
import monix.catnap.CancelableF
import monix.execution.atomic.{Atomic, PaddingStrategy}
import monix.execution.{Cancelable, Scheduler}
import scala.annotation.tailrec
import scala.concurrent.Promise
/**
* INTERNAL API — Represents a composite of functions
* (meant for cancellation) that are stacked.
*
* Implementation notes:
*
* - `cancel()` is idempotent
* - all methods are thread-safe / atomic
*
* Used in the implementation of `cats.effect.Task`. Inspired by the
* implementation of `StackedCancelable` from the Monix library.
*/
private[eval] sealed abstract class TaskConnection extends CancelableF[Task] {
/**
* Cancels the unit of work represented by this reference.
*
* Guaranteed idempotency - calling it multiple times should have the
* same side-effect as calling it only once. Implementations
* of this method should also be thread-safe.
*/
def cancel: CancelToken[Task]
/**
* @return true in case this cancelable hasn't been canceled,
* or false otherwise.
*/
def isCanceled: Boolean
/**
* Pushes a cancelable token on the stack, to be
* popped or canceled later in LIFO order.
*
* The function needs a [[monix.execution.Scheduler Scheduler]]
* to work because in case the connection was already cancelled,
* then the given `token` needs to be cancelled as well.
*/
def push(token: CancelToken[Task])(implicit s: Scheduler): Unit
/**
* Pushes a [[monix.execution.Cancelable]] on the stack, to be
* popped or canceled later in LIFO order.
*
* The function needs a [[monix.execution.Scheduler Scheduler]]
* to work because in case the connection was already cancelled,
* then the given `token` needs to be cancelled as well.
*/
def push(cancelable: Cancelable)(implicit s: Scheduler): Unit
/**
* Pushes a [[monix.catnap.CancelableF]] on the stack, to be
* popped or canceled later in LIFO order.
*
* The function needs a [[monix.execution.Scheduler Scheduler]]
* to work because in case the connection was already cancelled,
* then the given `token` needs to be cancelled as well.
*/
def push(connection: CancelableF[Task])(implicit s: Scheduler): Unit
/**
* Pushes multiple connections on the stack.
*
* The function needs a [[monix.execution.Scheduler Scheduler]]
* to work because in case the connection was already cancelled,
* then the given connections need to be cancelled as well.
*/
def pushConnections(seq: CancelableF[Task]*)(implicit s: Scheduler): Unit
/**
* Removes a cancelable reference from the stack in LIFO order.
*
* @return the cancelable reference that was removed.
*/
def pop(): CancelToken[Task]
/**
* Tries to reset an `TaskConnection`, from a cancelled state,
* back to a pristine state, but only if possible.
*
* Returns `true` on success, or `false` if there was a race
* condition (i.e. the connection wasn't cancelled) or if
* the type of the connection cannot be reactivated.
*/
def tryReactivate(): Boolean
/**
* Transforms this `TaskConnection` into a
* [[monix.execution.Cancelable Cancelable]] reference.
*/
def toCancelable(implicit s: Scheduler): Cancelable
}
private[eval] object TaskConnection {
/** Builder for [[TaskConnection]]. */
def apply(): TaskConnection =
new Impl
/**
* Reusable [[TaskConnection]] reference that cannot
* be canceled.
*/
val uncancelable: TaskConnection =
new Uncancelable
private final class Uncancelable extends TaskConnection {
def cancel = Task.unit
def isCanceled: Boolean = false
def pop(): CancelToken[Task] = Task.unit
def tryReactivate(): Boolean = true
def push(token: CancelToken[Task])(implicit s: Scheduler): Unit = ()
def push(cancelable: Cancelable)(implicit s: Scheduler): Unit = ()
def push(connection: CancelableF[Task])(implicit s: Scheduler): Unit = ()
def pushConnections(seq: CancelableF[Task]*)(implicit s: Scheduler): Unit = ()
def toCancelable(implicit s: Scheduler): Cancelable =
Cancelable.empty
}
private final class Impl extends TaskConnection { self =>
private[this] val state =
Atomic.withPadding(
(List.empty[AnyRef], Promise[Unit]()),
PaddingStrategy.LeftRight128
)
val cancel = Task.suspend {
state.transformAndExtract {
case (Nil, p) =>
(Task[Unit](p.success(())), (null, p))
case (null, p) => (TaskFromFuture.strict(p.future), (null, p))
case (list, p) =>
val task = UnsafeCancelUtils
.cancelAllUnsafe(list)
.redeemWith[Unit](ex => Task(p.success(())).flatMap(_ => Task.raiseError(ex)), _ => Task(p.success(())))
(task, (null, p))
}
}
def isCanceled: Boolean =
state.get._1 eq null
def push(token: CancelToken[Task])(implicit s: Scheduler): Unit =
pushAny(token)
def push(cancelable: Cancelable)(implicit s: Scheduler): Unit =
pushAny(cancelable)
def push(connection: CancelableF[Task])(implicit s: Scheduler): Unit =
pushAny(connection)
@tailrec
private def pushAny(cancelable: AnyRef)(implicit s: Scheduler): Unit = {
state.get() match {
case (null, _) =>
UnsafeCancelUtils.triggerCancel(cancelable)
case current@(list, p) =>
val update = cancelable :: list
if (!state.compareAndSet(current, (update, p))) {
// $COVERAGE-OFF$
pushAny(cancelable)
// $COVERAGE-ON$
}
}
}
def pushConnections(seq: CancelableF[Task]*)(implicit s: Scheduler): Unit =
push(UnsafeCancelUtils.cancelAllUnsafe(seq))
@tailrec def pop(): CancelToken[Task] =
state.get() match {
case (null, _) | (Nil, _) => Task.unit
case current @(x :: xs, p) =>
if (state.compareAndSet(current, (xs, p)))
UnsafeCancelUtils.getToken(x)
else {
// $COVERAGE-OFF$
pop()
// $COVERAGE-ON$
}
}
def tryReactivate(): Boolean = {
state.transformAndExtract {
case (null, _) =>
(true, (Nil, Promise[Unit]()))
case notCanceled =>
(false, notCanceled)
}
}
def toCancelable(implicit s: Scheduler): Cancelable =
new Cancelable {
def cancel(): Unit =
self.cancel.runAsyncAndForget(s)
}
}
}