From 0aef0576bbea11a96f039ab2c29f15e2bf3d050a Mon Sep 17 00:00:00 2001 From: Brandon Phillips Date: Fri, 7 Jun 2019 11:12:03 +0200 Subject: [PATCH] add in failopen option to annotation --- Annotation/RateLimit.php | 21 +++++++++++++++++++ EventListener/RateLimitAnnotationListener.php | 13 ++++++++++-- README.md | 2 +- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/Annotation/RateLimit.php b/Annotation/RateLimit.php index 022c04d..fb62835 100644 --- a/Annotation/RateLimit.php +++ b/Annotation/RateLimit.php @@ -31,6 +31,11 @@ class RateLimit extends ConfigurationAnnotation */ protected $payload; + /** + * @var bool allow the ratelimiter to fail open on any request where an exception is thrown + */ + protected $failOpen = false; + /** * Returns the alias name for an annotated configuration. * @@ -115,4 +120,20 @@ public function setPayload($payload) $this->payload = $payload; } + /** + * @return bool + */ + public function getFailOpen() + { + return $this->failOpen; + } + + /** + * @param bool $failOpen + */ + public function setFailOpen($failOpen) + { + $this->failOpen = $failOpen; + } + } diff --git a/EventListener/RateLimitAnnotationListener.php b/EventListener/RateLimitAnnotationListener.php index 00fc499..1d45109 100644 --- a/EventListener/RateLimitAnnotationListener.php +++ b/EventListener/RateLimitAnnotationListener.php @@ -78,8 +78,17 @@ public function onKernelController(FilterControllerEvent $event) $key = $this->getKey($event, $rateLimit, $annotations); - // Ratelimit the call - $rateLimitInfo = $this->rateLimitService->limitRate($key); + $rateLimitInfo = null; + // rate limit fails for any reason we can allow the endpoint to respond normally + try { + // Ratelimit the call + $rateLimitInfo = $this->rateLimitService->limitRate($key); + } catch (\Exception $exception) { + if ($rateLimit->getFailOpen()) { + return; + } + } + if (! $rateLimitInfo) { // Create new rate limit entry for this call $rateLimitInfo = $this->rateLimitService->createRate($key, $rateLimit->getLimit(), $rateLimit->getPeriod()); diff --git a/README.md b/README.md index 0933fc6..ce5fcc6 100644 --- a/README.md +++ b/README.md @@ -181,7 +181,7 @@ use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; /** * @Route(...) * - * @RateLimit(limit=1000, period=3600) + * @RateLimit(limit=1000, period=3600, failOpen=true) */ public function someApiAction() {