Skip to content

Commit

Permalink
Adds global rate limit filter
Browse files Browse the repository at this point in the history
  • Loading branch information
paulbrejla committed Dec 1, 2023
1 parent 61f5db3 commit dd88f47
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
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
}
}
}
2 changes: 2 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ spring:
path: /h2-console
server:
port: ${SERVER_PORT:80}
error:
include-stacktrace: never
loader:
source: ${LOADER_SOURCE}
remoteURL: ${LOADER_REMOTE_URL}
Expand Down

0 comments on commit dd88f47

Please sign in to comment.