Skip to content

Commit ee74fc9

Browse files
committed
api: Use Random Exponential Backoff in do_api_query method.
Fixes #537.
1 parent 6bf3d3b commit ee74fc9

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

zulip/zulip/__init__.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -509,13 +509,10 @@ def do_api_query(self, orig_request, url, method="POST",
509509
query_state = {
510510
'had_error_retry': False,
511511
'request': request,
512-
'failures': 0,
513512
} # type: Dict[str, Any]
514513

515514
def error_retry(error_string):
516-
# type: (str) -> bool
517-
if not self.retry_on_errors or query_state["failures"] >= 10:
518-
return False
515+
# type: (str) -> None
519516
if self.verbose:
520517
if not query_state["had_error_retry"]:
521518
sys.stdout.write("zulip API(%s): connection error%s -- retrying." %
@@ -525,9 +522,6 @@ def error_retry(error_string):
525522
sys.stdout.write(".")
526523
sys.stdout.flush()
527524
query_state["request"]["dont_block"] = json.dumps(True)
528-
time.sleep(1)
529-
query_state["failures"] += 1
530-
return True
531525

532526
def end_error_retry(succeeded):
533527
# type: (bool) -> None
@@ -537,7 +531,8 @@ def end_error_retry(succeeded):
537531
else:
538532
print("Failed!")
539533

540-
while True:
534+
backoff = RandomExponentialBackoff(timeout_success_equivalent=300)
535+
while backoff.keep_going():
541536
try:
542537
if method == "GET":
543538
kwarg = "params"
@@ -560,7 +555,9 @@ def end_error_retry(succeeded):
560555

561556
# On 50x errors, try again after a short sleep
562557
if str(res.status_code).startswith('5'):
563-
if error_retry(" (server %s)" % (res.status_code,)):
558+
error_retry(" (server %s)" % (res.status_code,))
559+
backoff.fail()
560+
if backoff.keep_going():
564561
continue
565562
# Otherwise fall through and process the python-requests error normally
566563
except (requests.exceptions.Timeout, requests.exceptions.SSLError) as e:
@@ -586,7 +583,9 @@ def end_error_retry(succeeded):
586583
# in an invalid site.
587584
raise UnrecoverableNetworkError('cannot connect to server ' + self.base_url)
588585

589-
if error_retry(""):
586+
error_retry("")
587+
backoff.fail()
588+
if backoff.keep_going():
590589
continue
591590
end_error_retry(False)
592591
return {'msg': "Connection error:\n%s" % traceback.format_exc(),
@@ -610,6 +609,7 @@ def end_error_retry(succeeded):
610609
end_error_retry(False)
611610
return {'msg': "Unexpected error from the server", "result": "http-error",
612611
"status_code": res.status_code}
612+
return {'msg': "Unexpected error from the server", "result": "unexpected-error"}
613613

614614
def call_endpoint(self, url=None, method="POST", request=None,
615615
longpolling=False, files=None, timeout=None):

0 commit comments

Comments
 (0)