-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Retries.scala
44 lines (32 loc) · 1.08 KB
/
Retries.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
package japgolly.webapputil.general
import japgolly.microlibs.stdlib_ext.StdlibExt._
import java.time.Duration
import scala.collection.View
/** Immutable retry policy */
final case class Retries(waitTimes: Iterable[Duration]) {
def apply(attemptsSoFar: Int): Option[Duration] =
waitTimes.drop(attemptsSoFar).headOption
def isEmpty: Boolean =
waitTimes.isEmpty
def take(n: Int): Retries =
Retries(waitTimes.take(n))
def takeWhile(f: Duration => Boolean): Retries =
Retries(waitTimes.takeWhile(f))
def pop: Option[(Duration, Retries)] =
if (isEmpty)
None
else
Some((waitTimes.head, Retries(waitTimes.tail)))
def ++(r: Retries): Retries =
Retries(waitTimes ++ r.waitTimes)
}
object Retries {
private def expStream(d: Duration, factor: Double): LazyList[Duration] =
d #:: expStream((d.toMillis * factor).millis, factor)
def exponentially(d: Duration, factor: Double = 2): Retries =
apply(expStream(d, factor))
def continually(d: Duration): Retries =
apply(View.from(Iterator.continually(d)))
def none: Retries =
Retries(Nil)
}