Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add http 429 error handling #189

Merged
merged 5 commits into from
Apr 18, 2018
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions matrix_client/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,14 @@ class MatrixHttpApi(object):
response = matrix.send_message("!roomid:matrix.org", "Hello!")
"""

def __init__(self, base_url, token=None, identity=None):
def __init__(self, base_url, token=None, identity=None, default_429_wait_ms=5000):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add documentation on this kwarg to the docstring. After that, I can
certainly merge this; hopefully the weird behavior from Synapse will be fixed
upstream soon, and then we can remove at least a bit of this logic.

self.base_url = base_url
self.token = token
self.identity = identity
self.txn_id = 0
self.validate_cert = True
self.session = Session()
self.default_429_wait_ms = default_429_wait_ms

def initial_sync(self, limit=1):
"""
Expand Down Expand Up @@ -663,7 +664,16 @@ def _send(self, method, path, content=None, query_params={}, headers={},
raise MatrixHttpLibError(e, method, endpoint)

if response.status_code == 429:
sleep(response.json()['retry_after_ms'] / 1000)
try:
waittime = response.json()['retry_after_ms'] / 1000
except KeyError:
try:
errordata = json.loads(response.json()['error'])
waittime = errordata['retry_after_ms'] / 1000
except KeyError:
waittime = self.default_429_wait_ms / 1000
finally:
sleep(waittime)
else:
break

Expand Down