@@ -21,13 +21,12 @@ class RateLimit(config: RateLimitConfig) extends Directive0 with Json4sSupport {
21
21
22
22
protected def getCurrentTimeNanos : Long = System .nanoTime()
23
23
24
- private [this ] val ticker : Ticker = new Ticker {
25
- override def read (): Long = getCurrentTimeNanos
26
- }
27
-
28
24
private [this ] lazy val lru = {
29
25
val nanoDuration = config.minRequestInterval.toNanos
30
26
val javaDuration = Duration .ofNanos(nanoDuration)
27
+ val ticker : Ticker = new Ticker {
28
+ override def read (): Long = getCurrentTimeNanos
29
+ }
31
30
CacheBuilder
32
31
.newBuilder()
33
32
.weakKeys()
@@ -38,16 +37,16 @@ class RateLimit(config: RateLimitConfig) extends Directive0 with Json4sSupport {
38
37
39
38
// Such algebras prevent if-elseif-else boilerplate in the JsonRPCServer code
40
39
// It is also guaranteed that:
41
- // 1) config.enabled is checked only once - on route init
42
- // 2) no IP address is extracted unless config.enabled is true
43
- // 3) no LRU is created unless config.enabled is true
44
- // 4) cache is accessed only once (using get)
45
- val rateLimitAlgebra : (Unit => Route ) => Route = {
40
+ // 1) no IP address is extracted unless config.enabled is true
41
+ // 2) no LRU is created unless config.enabled is true
42
+ // 3) cache is accessed only once (using get)
43
+ override def tapply (f : Unit => Route ): Route = {
46
44
if (config.enabled) {
47
45
val minInterval = config.minRequestInterval.toSeconds
48
- f => {
49
46
extractClientIP { ip =>
50
47
var exists = true
48
+ // We can avoid using var
49
+ // But in this case we access our LRU twice.
51
50
lru.get(
52
51
ip,
53
52
() => {
@@ -62,10 +61,7 @@ class RateLimit(config: RateLimitConfig) extends Directive0 with Json4sSupport {
62
61
f.apply(())
63
62
}
64
63
}
65
- }
66
- } else _.apply(())
64
+ } else f.apply(())
67
65
}
68
66
69
- override def tapply (f : Unit => Route ): Route = rateLimitAlgebra(f)
70
-
71
67
}
0 commit comments