Skip to content

Commit 405a76a

Browse files
author
Dmitry Voronov
committed
Gave up on returning function value in RL algebra
1 parent c61ec05 commit 405a76a

File tree

1 file changed

+10
-14
lines changed

1 file changed

+10
-14
lines changed

src/main/scala/io/iohk/ethereum/jsonrpc/server/http/RateLimit.scala

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,12 @@ class RateLimit(config: RateLimitConfig) extends Directive0 with Json4sSupport {
2121

2222
protected def getCurrentTimeNanos: Long = System.nanoTime()
2323

24-
private[this] val ticker: Ticker = new Ticker {
25-
override def read(): Long = getCurrentTimeNanos
26-
}
27-
2824
private[this] lazy val lru = {
2925
val nanoDuration = config.minRequestInterval.toNanos
3026
val javaDuration = Duration.ofNanos(nanoDuration)
27+
val ticker: Ticker = new Ticker {
28+
override def read(): Long = getCurrentTimeNanos
29+
}
3130
CacheBuilder
3231
.newBuilder()
3332
.weakKeys()
@@ -38,16 +37,16 @@ class RateLimit(config: RateLimitConfig) extends Directive0 with Json4sSupport {
3837

3938
// Such algebras prevent if-elseif-else boilerplate in the JsonRPCServer code
4039
// 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 = {
4644
if (config.enabled) {
4745
val minInterval = config.minRequestInterval.toSeconds
48-
f => {
4946
extractClientIP { ip =>
5047
var exists = true
48+
// We can avoid using var
49+
// But in this case we access our LRU twice.
5150
lru.get(
5251
ip,
5352
() => {
@@ -62,10 +61,7 @@ class RateLimit(config: RateLimitConfig) extends Directive0 with Json4sSupport {
6261
f.apply(())
6362
}
6463
}
65-
}
66-
} else _.apply(())
64+
} else f.apply(())
6765
}
6866

69-
override def tapply(f: Unit => Route): Route = rateLimitAlgebra(f)
70-
7167
}

0 commit comments

Comments
 (0)