Skip to content

Commit

Permalink
zulip.Client.call_endpoint: Add retry_on_rate_limit_error.
Browse files Browse the repository at this point in the history
If the call_endpoint method is called with the
"retry_on_rate_limit_error" parameter set to true, wait and retry
automatically on rate limit errors.
See https://chat.zulip.org/#narrow/stream/378-api-design/topic/
Rate.20limits/near/1217048 for the discussion.
  • Loading branch information
ro-i committed Jul 1, 2021
1 parent 71d488e commit b870097
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions zulip/zulip/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,24 +697,41 @@ def call_endpoint(
method: str = "POST",
request: Optional[Dict[str, Any]] = None,
longpolling: bool = False,
retry_on_rate_limit_error: bool = False,
files: Optional[List[IO[Any]]] = None,
timeout: Optional[float] = None,
) -> Dict[str, Any]:
secs: float

if request is None:
request = dict()
marshalled_request = {}
for (k, v) in request.items():
if v is not None:
marshalled_request[k] = v
versioned_url = API_VERSTRING + (url if url is not None else "")
return self.do_api_query(
marshalled_request,
versioned_url,
method=method,
longpolling=longpolling,
files=files,
timeout=timeout,
)

while True:
result = self.do_api_query(
marshalled_request,
versioned_url,
method=method,
longpolling=longpolling,
files=files,
timeout=timeout,
)
if not retry_on_rate_limit_error or result["result"] == "success":
break
elif "code" in result and result["code"] == "RATE_LIMIT_HIT":
secs = result["retry-after"]
elif "X-RateLimit-Reset" in result:
secs = float(result["X-RateLimit-Reset"])
else:
break
logger.warning("hit API rate limit, waiting for %f seconds...", secs)
time.sleep(secs)

return result

def call_on_each_event(
self,
Expand Down

0 comments on commit b870097

Please sign in to comment.