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 Sep 7, 2021
1 parent bdc139e commit 7a293bf
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions zulip/zulip/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,7 @@ 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]:
Expand All @@ -707,14 +708,27 @@ def call_endpoint(
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"
or "retry-after" not in result
):
break
wait_before_retry_secs: float = result["retry-after"]
logger.warning("Hit API rate limit, waiting for %f seconds...", wait_before_retry_secs)
time.sleep(wait_before_retry_secs)

return result

def call_on_each_event(
self,
Expand Down

0 comments on commit 7a293bf

Please sign in to comment.