Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Ignore Rate Limit for Whitelisted Clients #27

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions redis_rate_limit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,23 @@ class RateLimit(object):
This class offers an abstraction of a Rate Limit algorithm implemented on
top of Redis >= 2.6.0.
"""
def __init__(self, resource, client, max_requests, expire=None, redis_pool=REDIS_POOL):
def __init__(self, resource, client, max_requests, whitelisted_clients=[], expire=None, redis_pool=REDIS_POOL):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should think about a better name here since there's a movement to avoid some terms in software development. Maybe ignore_clients or bypass_clients.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rename to ignored_clients=None

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

"""
Class initialization method checks if the Rate Limit algorithm is
actually supported by the installed Redis version and sets some
useful properties.

If Rate Limit is not supported, it raises an Exception.

:param resource: resource identifier string (i.e. ‘user_pictures’)
:param client: client identifier string (i.e. ‘192.168.0.10’)
:param max_requests: integer (i.e. ‘10’)
:param whitelisted_clients: list of ip addresses (i.e. ['127.0.0.1'])
:param expire: seconds to wait before resetting counters (i.e. ‘60’)
:param redis_pool: instance of redis.ConnectionPool.
Default: ConnectionPool(host='127.0.0.1', port=6379, db=0)
"""
self.client = client
self.whitelisted_clients = whitelisted_clients

self._redis = Redis(connection_pool=redis_pool)
if not self._is_rate_limit_supported():
raise RedisVersionNotSupported()
Expand Down Expand Up @@ -88,7 +90,6 @@ def get_usage(self):
"""
Returns actual resource usage by client. Note that it could be greater
than the maximum number of requests set.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You've removed a bunch of blank lines from docstrings. Could you revert it, please?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changes reverted.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blank line is still removed, could you revert it?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you pushed those updates?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry forgot to push changes. Updated.

:return: integer: current usage
"""
return int(self._redis.get(self._rate_limit_key) or 0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the check should be done here.

Suggested change
return int(self._redis.get(self._rate_limit_key) or 0)
if self.ignored_clients and self.client in self.ignored_clients:
return 0
return int(self._redis.get(self._rate_limit_key) or 0)

There are two reasons for it:

  • adding a client to the list has always an instant bypass effect
  • removing a client from the list automatically enforces the limits again

The reason is to avoid edge cases like this:

  • client reaches max requests limit
  • client is added to the ignored clients list
  • client will still need to wait for expire time before being allowed to make requests again

Or this other one:

  • client is added to ignored list by mistake and overflows max number of requests
  • client is removed from the list
  • there's no back-off

What do you think, @italorossi?

Expand All @@ -97,7 +98,6 @@ def get_wait_time(self):
"""
Returns estimated optimal wait time for subsequent requests.
If limit has already been reached, return wait time until it gets reset.

:return: float: wait time in seconds
"""
expire = self._redis.pttl(self._rate_limit_key)
Expand All @@ -111,22 +111,18 @@ def get_wait_time(self):
def has_been_reached(self):
"""
Checks if Rate Limit has been reached.

:return: bool: True if limit has been reached or False otherwise
"""
return self.get_usage() >= self._max_requests

def increment_usage(self, increment_by=1):
"""
Calls a LUA script that should increment the resource usage by client.

If the resource limit overflows the maximum number of requests, this
method raises an Exception.

:param increment_by: The count to increment the rate limiter by.
This is by default 1, but higher values are provided for more flexible
rate-limiting schemes.

:return: integer: current usage
"""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the first line here could be:

if self.client in self.bypass_clients:
    return 0

The same could be done to other methods since they don't even need to query Redis if the client is supposed to be bypassed.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

if increment_by > self._max_requests:
Expand All @@ -140,8 +136,11 @@ def increment_usage(self, increment_by=1):
.format(increment_by=increment_by))

try:
current_usage = self._redis.evalsha(
INCREMENT_SCRIPT_HASH, 1, self._rate_limit_key, self._expire, increment_by)
if self.client not in self.whitelisted_clients:
current_usage = self._redis.evalsha(
INCREMENT_SCRIPT_HASH, 1, self._rate_limit_key, self._expire, increment_by)
else:
current_usage = 0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't touch this code.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my last comment and add this check at the top like if self.ignored_clients and self.client in self.ignored_clients: return 0

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes done as requested.

except NoScriptError:
current_usage = self._redis.eval(
INCREMENT_SCRIPT, 1, self._rate_limit_key, self._expire, increment_by)
Expand All @@ -155,7 +154,6 @@ def _is_rate_limit_supported(self):
"""
Checks if Rate Limit is supported which can basically be found by
looking at Redis database version that should be 2.6.0 or greater.

:return: bool
"""
redis_version = self._redis.info()['redis_version']
Expand All @@ -172,17 +170,19 @@ def _reset(self):


class RateLimiter(object):
def __init__(self, resource, max_requests, expire=None, redis_pool=REDIS_POOL):
def __init__(self, resource, max_requests, whitelisted_clients=[], expire=None, redis_pool=REDIS_POOL):
"""
Rate limit factory. Checks if RateLimit is supported when limit is called.
:param resource: resource identifier string (i.e. ‘user_pictures’)
:param max_requests: integer (i.e. ‘10’)
:param whitelisted_clients: list of ip addresses (i.e. ['127.0.0.1'])
:param expire: seconds to wait before resetting counters (i.e. ‘60’)
:param redis_pool: instance of redis.ConnectionPool.
Default: ConnectionPool(host='127.0.0.1', port=6379, db=0)
"""
self.resource = resource
self.max_requests = max_requests
self.whitelisted_clients = whitelisted_clients
self.expire = expire
self.redis_pool = redis_pool

Expand All @@ -194,6 +194,7 @@ def limit(self, client):
resource=self.resource,
client=client,
max_requests=self.max_requests,
whitelisted_clients=self.whitelisted_clients,
expire=self.expire,
redis_pool=self.redis_pool,
)
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Revert this change.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, revert this change leaving a blank line at the end of the file.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

13 changes: 13 additions & 0 deletions tests/rate_limit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,19 @@ def test_limit_10_max_request(self):
self.assertEqual(self.rate_limit.get_usage(), 11)
self.assertEqual(self.rate_limit.has_been_reached(), True)

def test_whitelisted_clients(self):
jay-parikh marked this conversation as resolved.
Show resolved Hide resolved
"""
Should not increment counter if client is part of whitelisted_clients list.
"""
self.rate_limit = RateLimit(resource='test', client='localhost', whitelisted_clients=['localhost'],
max_requests=10, expire=2)
self.assertEqual(self.rate_limit.get_usage(), 0)
self.assertEqual(self.rate_limit.has_been_reached(), False)

self._make_10_requests()
self.assertEqual(self.rate_limit.get_usage(), 0)
self.assertEqual(self.rate_limit.has_been_reached(), False)

def test_expire(self):
"""
Should not raise TooManyRequests Exception when trying to increment for
Expand Down