File tree Expand file tree Collapse file tree 2 files changed +30
-0
lines changed
chapter12/src/main/scala/com/reactivedesignpatterns/chapter12 Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -10,3 +10,4 @@ lazy val chapter04 = project dependsOn (common)
1010
1111lazy val chapter07 = project dependsOn (common)
1212
13+ lazy val chapter12 = project dependsOn (common)
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments