Skip to content

Commit f0472da

Browse files
committed
add chapter 12 and RateLimiter
1 parent d976c5f commit f0472da

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

build.sbt

+1
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ lazy val chapter04 = project dependsOn (common)
1010

1111
lazy val chapter07 = project dependsOn (common)
1212

13+
lazy val chapter12 = project dependsOn (common)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.reactivedesignpatterns.chapter12
2+
3+
import scala.concurrent.duration.FiniteDuration
4+
import scala.concurrent.duration.Deadline
5+
import scala.concurrent.Future
6+
7+
case object RateLimitExceeded extends RuntimeException
8+
9+
class RateLimiter(requests: Int, period: FiniteDuration) {
10+
private val startTimes = {
11+
val onePeriodAgo = Deadline.now - period
12+
Array.fill(requests)(onePeriodAgo)
13+
}
14+
private var position = 0
15+
private def lastTime = startTimes(position)
16+
private def enqueue(time: Deadline) = {
17+
startTimes(position) = time
18+
position += 1
19+
if (position == requests) position = 0
20+
}
21+
def call[T](block: => Future[T]): Future[T] = {
22+
val now = Deadline.now
23+
if ((now - lastTime) < period) Future.failed(RateLimitExceeded)
24+
else {
25+
enqueue(now)
26+
block
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)