Skip to content

Commit ef16af5

Browse files
committed
Revert "Refactor RateLimitUtil for improved concurrency (#68)"
This reverts commit d8f6e6d.
1 parent bb035a9 commit ef16af5

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed
Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
package app.util
22

33
import io.javalin.Javalin
4+
import java.util.*
45
import java.util.concurrent.ConcurrentHashMap
5-
import java.util.concurrent.Executors
6-
import java.util.concurrent.TimeUnit
76

87
/**
98
* A very naive IP-based rate-limiting mechanism
@@ -22,28 +21,30 @@ object RateLimitUtil {
2221
fun enableTerribleRateLimiting(app: Javalin) {
2322

2423
app.before { ctx ->
25-
ipReqCount.compute(ctx.ip(), { _, count ->
26-
when (count) {
27-
null -> 1
28-
in 0..25 -> count + 1
29-
else -> throw TerribleRateLimitException()
30-
}
31-
})
24+
if (ipReqCount[ctx.ip()] ?: 0 > 25) {
25+
throw TerribleRateLimitException()
26+
}
27+
ipReqCount[ctx.ip()] = (ipReqCount[ctx.ip()] ?: 0) + 1
3228
}
3329

34-
app.exception(TerribleRateLimitException::class.java) { _, ctx ->
30+
app.exception(TerribleRateLimitException::class.java) { e, ctx ->
3531
ctx.result("You can't spam this much. I'll give you a new request every five seconds.")
3632
}
3733

38-
Executors.newSingleThreadScheduledExecutor()
39-
.scheduleAtFixedRate(decrementAllCounters, 0, 5, TimeUnit.SECONDS)
34+
Timer().scheduleAtFixedRate(decrementAllCounters(), 0, 5000) // every 5s
4035

4136
}
4237

43-
private val decrementAllCounters = Runnable {
44-
ipReqCount.forEachKey(1, { ip ->
45-
ipReqCount.computeIfPresent(ip, { _, count -> if (count > 1) count - 1 else null })
46-
})
38+
private fun decrementAllCounters() = object : TimerTask() {
39+
override fun run() {
40+
ipReqCount.forEach { ip, count ->
41+
if (count > 0) {
42+
ipReqCount[ip] = ipReqCount[ip]!! - 1
43+
} else {
44+
ipReqCount.remove(ip)
45+
}
46+
}
47+
}
4748
}
4849

4950
}

0 commit comments

Comments
 (0)