File tree Expand file tree Collapse file tree 1 file changed +10
-7
lines changed Expand file tree Collapse file tree 1 file changed +10
-7
lines changed Original file line number Diff line number Diff line change @@ -22,25 +22,28 @@ object RateLimitUtil {
22
22
fun enableTerribleRateLimiting (app : Javalin ) {
23
23
24
24
app.before { ctx ->
25
- ipReqCount.compute(ctx.ip()) { _, count ->
25
+ ipReqCount.compute(ctx.ip(), { _, count ->
26
26
when (count) {
27
27
null -> 1
28
28
in 0 .. 25 -> count + 1
29
29
else -> throw TerribleRateLimitException ()
30
30
}
31
- }
31
+ })
32
32
}
33
33
34
34
app.exception(TerribleRateLimitException ::class .java) { _, ctx ->
35
35
ctx.result(" You can't spam this much. I'll give you a new request every five seconds." )
36
36
}
37
37
38
- Executors .newSingleThreadScheduledExecutor().scheduleAtFixedRate({
39
- ipReqCount.forEachKey(1 ) { ip ->
40
- ipReqCount.computeIfPresent(ip) { _, count -> if (count > 1 ) count - 1 else null }
41
- }
42
- }, 0 , 5 , TimeUnit .SECONDS )
38
+ Executors .newSingleThreadScheduledExecutor()
39
+ .scheduleAtFixedRate(decrementAllCounters, 0 , 5 , TimeUnit .SECONDS )
43
40
44
41
}
45
42
43
+ private val decrementAllCounters = Runnable {
44
+ ipReqCount.forEachKey(1 , { ip ->
45
+ ipReqCount.computeIfPresent(ip, { _, count -> if (count > 1 ) count - 1 else null })
46
+ })
47
+ }
48
+
46
49
}
You can’t perform that action at this time.
0 commit comments