Skip to content

Commit 0929963

Browse files
author
Dmitry Voronov
committed
Extracted blocker method
1 parent ec001ba commit 0929963

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

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

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ class RateLimit(config: RateLimitConfig) extends Directive0 with Json4sSupport {
1919
private implicit val serialization: Serialization = native.Serialization
2020
private implicit val formats: Formats = DefaultFormats + JsonSerializers.RpcErrorJsonSerializer
2121

22-
protected def getCurrentTimeNanos: Long = System.nanoTime()
22+
private[this] lazy val minInterval = config.minRequestInterval.toSeconds
2323

2424
private[this] lazy val lru = {
2525
val nanoDuration = config.minRequestInterval.toNanos
@@ -35,26 +35,30 @@ class RateLimit(config: RateLimitConfig) extends Directive0 with Json4sSupport {
3535
.build[RemoteAddress, NotUsed]()
3636
}
3737

38+
private[this] def isBelowRateLimit(ip: RemoteAddress): Boolean = {
39+
var exists = true
40+
lru.get(
41+
ip,
42+
() => {
43+
exists = false
44+
NotUsed
45+
}
46+
)
47+
exists
48+
}
49+
50+
// Override this to test
51+
protected def getCurrentTimeNanos: Long = System.nanoTime()
52+
3853
// Such algebras prevent if-elseif-else boilerplate in the JsonRPCServer code
3954
// It is also guaranteed that:
4055
// 1) no IP address is extracted unless config.enabled is true
4156
// 2) no LRU is created unless config.enabled is true
4257
// 3) cache is accessed only once (using get)
4358
override def tapply(f: Unit => Route): Route = {
4459
if (config.enabled) {
45-
val minInterval = config.minRequestInterval.toSeconds
4660
extractClientIP { ip =>
47-
var exists = true
48-
// We can avoid using var
49-
// But in this case we access our LRU twice.
50-
lru.get(
51-
ip,
52-
() => {
53-
exists = false
54-
NotUsed
55-
}
56-
)
57-
if (exists) {
61+
if (isBelowRateLimit(ip)) {
5862
val err = JsonRpcError.RateLimitError(minInterval)
5963
complete((StatusCodes.TooManyRequests, err))
6064
} else {

0 commit comments

Comments
 (0)