Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions zio-cache/shared/src/main/scala/zio/cache/Cache.scala
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,26 @@ abstract class Cache[-Key, +Error, +Value] {
def size(implicit trace: Trace): UIO[Int]
}

object TimeToLive {

/**
* Returns a TTL function that adds randomized jitter to the base time to live.
*
* The `min` and `max` parameters control the bounds within which the base time to live
* is randomly scaled.
*/
def jittered[Value](
timeToLive: Exit[Nothing, Value] => Duration,
min: Double,
max: Double
): Exit[Nothing, Value] => Duration = { (exit: Exit[Nothing, Value]) =>
val d = timeToLive(exit).toNanos
val random = scala.util.Random.nextDouble()
val jittered = d * min * (1 - random) + d * max * random
zio.Duration.fromNanos(jittered.toLong)
}
}

object Cache {

/**
Expand Down
21 changes: 20 additions & 1 deletion zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,26 @@ object CacheSpec extends ZIOSpecDefault {
expected <- ZIO.foreachPar(1 to 100)(hash(salt))
} yield assertTrue(actual == expected)
}
}
},
test("jitter") {
check(Gen.int(20, 100)) { duration =>
for {
ref <- Ref.make(0)
lookup = Lookup((n: Int) => ref.updateAndGet(_ + 1).as(n))
cache <- Cache.makeWith(10, lookup)(TimeToLive.jittered(_ => duration.seconds, 1, 2))
_ <- cache.get(1)
lookupCount1 <- ref.get
_ <- TestClock.adjust((duration / 10).seconds)
_ <- cache.get(1)
lookupCount2 <- ref.get
_ <- TestClock.adjust((duration * 2).seconds)
_ <- cache.get(1)
lookupCount3 <- ref.get
} yield assertTrue(
lookupCount1 == 1 && lookupCount2 == 1 && lookupCount3 == 2
)
}
} @@ TestAspect.samples(10)
),
suite("`refresh` method")(
test("should update the cache with a new value") {
Expand Down