Skip to content
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