Skip to content

Add support for older redis versions #47

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
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
16 changes: 15 additions & 1 deletion asyncio_redis_rate_limit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ async def __aexit__(
) -> None:
"""Do nothing. We need this to ``__aenter__`` to work."""

async def redis_version(self):
version = await self._backend.info(section='SERVER')
return version['redis_version']

# Private API:

async def _acquire(self) -> None:
Expand All @@ -95,7 +99,17 @@ async def _acquire(self) -> None:
pipeline = self._backend.pipeline()

async with self._lock:
current_rate = await self._run_pipeline(cache_key, pipeline)
redis_version = await self.redis_version()
Copy link
Member

Choose a reason for hiding this comment

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

Can we do this earlier? We don't need to query this every time. We only need this once per app.


if int(redis_version.split('.')[0]) < 7:
current_rate, *_ = await pipeline.incr(cache_key).execute()
Copy link
Member

Choose a reason for hiding this comment

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

It feels like you execute a pipeline twice. This might not be safe due to race conditions.

if current_rate == 1:
await pipeline.expire(
cache_key,
self._rate_spec.seconds
).execute()
else:
current_rate = await self._run_pipeline(cache_key, pipeline)
# This looks like a coverage error on 3.10:
if current_rate > self._rate_spec.requests: # pragma: no cover
raise RateLimitError('Rate limit is hit', current_rate)
Expand Down