/
Retrying.scala
230 lines (206 loc) · 8.92 KB
/
Retrying.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
/*
* Copyright 2001-2013 Artima, Inc.
*
* 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 org.scalatest.enablers
import java.util.concurrent.{Executors, ScheduledExecutorService, ThreadFactory, TimeUnit}
import org.scalactic.source
import org.scalatest.Suite.anExceptionThatShouldCauseAnAbort
import org.scalatest.Resources
import org.scalatest.exceptions.{StackDepthException, TestFailedDueToTimeoutException, TestPendingException}
import org.scalatest.time.{Nanosecond, Nanoseconds, Span}
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.{Failure, Success}
import scala.annotation.tailrec
import scala.language.higherKinds
/**
* Supertrait for <code>Retrying</code> typeclasses, which are used to implement and determine the behavior
* of <a href="../Eventually.html"><code>Eventually</code></a> methods.
*
* <p>
* Currently, implementations for anything type <code>T</code> and <code>Future[T]</code> is provided.
* </p>
*/
trait Retrying[T] {
/**
* Retry the passed in function until the given timeout is reached, with the given interval between attempts.
*
* @param timeout the timespan to try before giving up
* @param interval interval between call attempts
* @param pos the position of the call site
* @param fun function to be called
* @return the value returned from the passed in <code>fun</code>.
*/
def retry(timeout: Span, interval: Span, pos: source.Position)(fun: => T): T
}
/**
* Companion object that provides <code>Retrying</code> implementations for <code>T</code> and <code>Future[T]</code>.
*/
object Retrying {
private def createScheduler(): ScheduledExecutorService = {
val threadFactory = new ThreadFactory {
val inner = Executors.defaultThreadFactory()
def newThread(runnable: Runnable) = {
val thread = inner.newThread(runnable)
thread.setName("ScalaTest-retrying")
thread.setDaemon(true)
thread
}
}
Executors.newSingleThreadScheduledExecutor(threadFactory)
}
/**
* Provides implicit <code>Retrying</code> implementation for <code>Future[T]</code>.
*/
implicit def retryingNatureOfFutureT[T](implicit execCtx: ExecutionContext): Retrying[Future[T]] =
new Retrying[Future[T]] {
def retry(timeout: Span, interval: Span, pos: source.Position)(fun: => Future[T]): Future[T] = {
val startNanos = System.nanoTime
val initialInterval = Span(interval.totalNanos * 0.1, Nanoseconds)
// Can't make this tail recursive. TODO: Document that fact.
def tryTryAgain(attempt: Int): Future[T] = {
try {
fun recoverWith {
case tpe: TestPendingException => Future.failed(tpe)
case e: Throwable if !anExceptionThatShouldCauseAnAbort(e) =>
// Here I want to try again after the duration. So first calculate the duration to
// wait before retrying. This is front loaded with a simple backoff algo.
val duration = System.nanoTime - startNanos
if (duration < timeout.totalNanos) {
val chillTime =
if (duration < interval.totalNanos) // For first interval, we wake up every 1/10 of the interval. This is mainly for optimization purpose.
initialInterval.millisPart
else
interval.millisPart
// Create a Promise
val promise = Promise[T]
val task =
new Runnable {
override def run(): Unit = {
val newFut = tryTryAgain(attempt + 1)
newFut onComplete {
case Success(res) => promise.success(res)
case Failure(ex) => promise.failure(ex)
}
}
}
val scheduler = createScheduler()
scheduler.schedule(task, chillTime, TimeUnit.MILLISECONDS)
scheduler.shutdown()
promise.future
}
else { // Timed out so return a failed Future
val durationSpan = Span(1, Nanosecond).scaledBy(duration) // Use scaledBy to get pretty units
Future.failed(
new TestFailedDueToTimeoutException(
(_: StackDepthException) =>
Some(
if (e.getMessage == null)
Resources.didNotUltimatelySucceed(attempt.toString, durationSpan.prettyString)
else
Resources.didNotUltimatelySucceedBecause(attempt.toString, durationSpan.prettyString, e.getMessage)
),
Some(e),
Left(pos),
None,
timeout
)
)
}
}
}
catch {
case tpe: TestPendingException => throw tpe
case e: Throwable if !anExceptionThatShouldCauseAnAbort(e) =>
val duration = System.nanoTime - startNanos
if (duration < timeout.totalNanos) {
if (duration < interval.totalNanos) // For first interval, we wake up every 1/10 of the interval. This is mainly for optimization purpose.
Thread.sleep(initialInterval.millisPart, initialInterval.nanosPart)
else
Thread.sleep(interval.millisPart, interval.nanosPart)
}
else {
val durationSpan = Span(1, Nanosecond).scaledBy(duration) // Use scaledBy to get pretty units
throw new TestFailedDueToTimeoutException(
(_: StackDepthException) =>
Some(
if (e.getMessage == null)
Resources.didNotEventuallySucceed(attempt.toString, durationSpan.prettyString)
else
Resources.didNotEventuallySucceedBecause(attempt.toString, durationSpan.prettyString, e.getMessage)
),
Some(e),
Left(pos),
None,
timeout
)
}
tryTryAgain(attempt + 1)
}
}
tryTryAgain(1)
}
}
/**
* Provides implicit <code>Retrying</code> implementation for <code>T</code>.
*/
implicit def retryingNatureOfT[T]: Retrying[T] =
new Retrying[T] {
def retry(timeout: Span, interval: Span, pos: source.Position)(fun: => T): T = {
val startNanos = System.nanoTime
def makeAValiantAttempt(): Either[Throwable, T] = {
try {
Right(fun)
}
catch {
case tpe: TestPendingException => throw tpe
case e: Throwable if !anExceptionThatShouldCauseAnAbort(e) => Left(e)
}
}
val initialInterval = Span(interval.totalNanos * 0.1, Nanoseconds)
@tailrec
def tryTryAgain(attempt: Int): T = {
makeAValiantAttempt() match {
case Right(result) => result
case Left(e) =>
val duration = System.nanoTime - startNanos
if (duration < timeout.totalNanos) {
if (duration < interval.totalNanos) // For first interval, we wake up every 1/10 of the interval. This is mainly for optimization purpose.
Thread.sleep(initialInterval.millisPart, initialInterval.nanosPart)
else
Thread.sleep(interval.millisPart, interval.nanosPart)
}
else {
val durationSpan = Span(1, Nanosecond).scaledBy(duration) // Use scaledBy to get pretty units
throw new TestFailedDueToTimeoutException(
(_: StackDepthException) =>
Some(
if (e.getMessage == null)
Resources.didNotEventuallySucceed(attempt.toString, durationSpan.prettyString)
else
Resources.didNotEventuallySucceedBecause(attempt.toString, durationSpan.prettyString, e.getMessage)
),
Some(e),
Left(pos),
None,
timeout
)
}
tryTryAgain(attempt + 1)
}
}
tryTryAgain(1)
}
}
}