Skip to content

Commit 59ac76b

Browse files
committed
api: Use Random Exponential Backoff in do_api_query method.
Fixes #537.
1 parent cf83a6f commit 59ac76b

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
@@ -510,13 +510,10 @@ def do_api_query(self, orig_request, url, method="POST",
510510
query_state = {
511511
'had_error_retry': False,
512512
'request': request,
513-
'failures': 0,
514513
} # type: Dict[str, Any]
515514

516515
def error_retry(error_string):
517-
# type: (str) -> bool
518-
if not self.retry_on_errors or query_state["failures"] >= 10:
519-
return False
516+
# type: (str) -> None
520517
if self.verbose:
521518
if not query_state["had_error_retry"]:
522519
sys.stdout.write("zulip API(%s): connection error%s -- retrying." %
@@ -526,9 +523,6 @@ def error_retry(error_string):
526523
sys.stdout.write(".")
527524
sys.stdout.flush()
528525
query_state["request"]["dont_block"] = json.dumps(True)
529-
time.sleep(1)
530-
query_state["failures"] += 1
531-
return True
532526

533527
def end_error_retry(succeeded):
534528
# type: (bool) -> None
@@ -538,7 +532,8 @@ def end_error_retry(succeeded):
538532
else:
539533
print("Failed!")
540534

541-
while True:
535+
backoff = RandomExponentialBackoff(timeout_success_equivalent=300)
536+
while backoff.keep_going():
542537
try:
543538
if method == "GET":
544539
kwarg = "params"
@@ -561,7 +556,9 @@ def end_error_retry(succeeded):
561556

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

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

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

0 commit comments

Comments
 (0)