-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
paulbrejla
committed
Dec 1, 2023
1 parent
61f5db3
commit dd88f47
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
src/main/kotlin/de/paulbrejla/holidays/rest/impl/RateLimitFilter.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package de.paulbrejla.holidays.rest.impl | ||
|
||
import de.paulbrejla.holidays.application.api.RateLimitService | ||
import org.springframework.beans.factory.annotation.Value | ||
import org.springframework.http.HttpStatus | ||
import org.springframework.stereotype.Component | ||
import org.springframework.web.server.ResponseStatusException | ||
import javax.servlet.Filter | ||
import javax.servlet.FilterChain | ||
import javax.servlet.ServletException | ||
import javax.servlet.ServletRequest | ||
import javax.servlet.ServletResponse | ||
import javax.servlet.http.HttpServletResponse | ||
|
||
@Component | ||
class RateLimitFilter(val rateLimitService: RateLimitService) : Filter { | ||
@Value("\${rateLimit.globalBucket.id}") | ||
var globalBucketId: String = "" | ||
|
||
@Value("\${rateLimit.globalBucket.capacity}") | ||
var globalBucketCapacity: Long = 0 | ||
|
||
|
||
override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) { | ||
if (!this.shouldFulfillRequestWithinRateLimit(globalBucketId)) { // Maybe add additional x-rate-limit headers later. | ||
(response as HttpServletResponse).apply { | ||
this.status = HttpStatus.TOO_MANY_REQUESTS.value() | ||
this.addHeader("X-RateLimit-Limit", globalBucketCapacity.toString()) | ||
this.addHeader("X-RateLimit-Remaining", "0") | ||
} | ||
} else { | ||
chain!!.doFilter(request, response) | ||
} | ||
} | ||
|
||
private fun shouldFulfillRequestWithinRateLimit(bucketId: String): Boolean { | ||
return rateLimitService.resolveBucket(bucketId) | ||
.tryConsumeAndReturnRemaining(1).run { | ||
if (this.isConsumed) | ||
true | ||
else | ||
false | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters