Skip to content

refactor: rewrite http ratelimiting to be dynamic #947

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 2 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
1 change: 1 addition & 0 deletions changelog/663.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Rewrite HTTP ratelimiting to use the :ddocs:`X-RateLimit-Bucket header <topics/rate-limits#header-format>`.
24 changes: 18 additions & 6 deletions disnake/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,8 @@ def __init__(
self.loop: asyncio.AbstractEventLoop = loop
self.connector = connector
self.__session: aiohttp.ClientSession = MISSING # filled in static_login
self._locks: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()
# (route bucket, discord bucket) -> asyncio lock
self._locks: weakref.WeakValueDictionary[tuple[str, Optional[str]], asyncio.Lock] = weakref.WeakValueDictionary()
self._global_over: asyncio.Event = asyncio.Event()
self._global_over.set()
self.token: Optional[str] = None
Expand Down Expand Up @@ -268,6 +269,16 @@ async def ws_connect(self, url: str, *, compress: int = 0) -> aiohttp.ClientWebS

return await self.__session.ws_connect(url, **kwargs)

def _get_bucket(self, route_bucket: str, discord_bucket: Optional[str]) -> asyncio.Lock:
key = (route_bucket, discord_bucket)
lock = self._locks.get(key)

if lock is None:
lock = asyncio.Lock()
self._locks[key] = lock

return lock

async def request(
self,
route: Route,
Expand All @@ -279,12 +290,9 @@ async def request(
bucket = route.bucket
method = route.method
url = route.url
discord_bucket: Optional[str] = None

lock = self._locks.get(bucket)
if lock is None:
lock = asyncio.Lock()
if bucket is not None:
self._locks[bucket] = lock
lock = self._get_bucket(bucket, discord_bucket)

# header creation
headers: Dict[str, str] = {
Expand Down Expand Up @@ -350,6 +358,10 @@ async def request(
response.status,
)

discord_bucket = response.headers.get("X-RateLimit-Bucket")
lock = self._get_bucket(bucket, discord_bucket)
maybe_lock.lock = lock

# even errors have text involved in them so this is safe to call
data = await json_or_text(response)

Expand Down