Skip to content

Commit

Permalink
Added retry logic to Client
Browse files Browse the repository at this point in the history
retry on transport errors
  • Loading branch information
ekampf committed Jun 30, 2016
1 parent b30c393 commit 818f8e6
Showing 1 changed file with 35 additions and 3 deletions.
38 changes: 35 additions & 3 deletions gql/client.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
import logging

from graphql import parse, introspection_query, build_ast_schema, build_client_schema
from graphql.validation import validate

from .transport.local_schema import LocalSchemaTransport


class Client(object):
class RetryError(Exception):
"""Custom exception thrown when retry logic fails"""
def __init__(self, retries_count, last_exception):
message = "Failed %s retries: %s" % (retries_count, last_exception)
super(RetryError, self).__init__(message)
self.last_exception = last_exception


class Client(object):
def __init__(self, schema=None, introspection=None, type_def=None, transport=None,
fetch_schema_from_transport=False):
fetch_schema_from_transport=False, retries=0):
assert not(type_def and introspection), 'Cant provide introspection type definition at the same time'
if transport and fetch_schema_from_transport:
assert not schema, 'Cant fetch the schema from transport if is already provided'
Expand All @@ -25,6 +34,7 @@ def __init__(self, schema=None, introspection=None, type_def=None, transport=Non
self.schema = schema
self.introspection = introspection
self.transport = transport
self.retries = retries

def validate(self, document):
if not self.schema:
Expand All @@ -36,7 +46,29 @@ def validate(self, document):
def execute(self, document, *args, **kwargs):
if self.schema:
self.validate(document)
result = self.transport.execute(document, *args, **kwargs)

result = self._get_result(document, *args, **kwargs)
if result.errors:
raise result.errors[0]

return result.data

def _get_result(self, document, *args, **kwargs):
if not self.retries:
return self.transport.execute(document, *args, **kwargs)

last_exception = None
retries_count = 0
while retries_count < self.retries:
try:
result = self.transport.execute(document, *args, **kwargs)
return result
except Exception as e:
last_exception = e
logging.warn("Request failed with exception %s. Retrying for the %s time...", retries_count + 1, exc_info=True)
finally:
retries_count += 1

raise RetryError(retries_count, last_exception)


0 comments on commit 818f8e6

Please sign in to comment.