Skip to content

Commit 4fc8183

Browse files
committed
api: Use Random Exponential Backoff in do_api_query method.
Fixes #537.
1 parent 77dc23e commit 4fc8183

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
@@ -508,13 +508,10 @@ def do_api_query(self, orig_request, url, method="POST",
508508
query_state = {
509509
'had_error_retry': False,
510510
'request': request,
511-
'failures': 0,
512511
} # type: Dict[str, Any]
513512

514513
def error_retry(error_string):
515-
# type: (str) -> bool
516-
if not self.retry_on_errors or query_state["failures"] >= 10:
517-
return False
514+
# type: (str) -> None
518515
if self.verbose:
519516
if not query_state["had_error_retry"]:
520517
sys.stdout.write("zulip API(%s): connection error%s -- retrying." %
@@ -524,9 +521,6 @@ def error_retry(error_string):
524521
sys.stdout.write(".")
525522
sys.stdout.flush()
526523
query_state["request"]["dont_block"] = json.dumps(True)
527-
time.sleep(1)
528-
query_state["failures"] += 1
529-
return True
530524

531525
def end_error_retry(succeeded):
532526
# type: (bool) -> None
@@ -536,7 +530,8 @@ def end_error_retry(succeeded):
536530
else:
537531
print("Failed!")
538532

539-
while True:
533+
backoff = RandomExponentialBackoff(timeout_success_equivalent=300)
534+
while backoff.keep_going():
540535
try:
541536
if method == "GET":
542537
kwarg = "params"
@@ -559,7 +554,9 @@ def end_error_retry(succeeded):
559554

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

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

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

0 commit comments

Comments
 (0)