Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
26 changes: 23 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,29 @@ When an API call results in a 4xx or 5xx error (e.g. when a chart could not be f

This exception contains a message string describing what went wrong, and also two other properties:

- `Errors`: a list of errors (containing a code and a message) that the server returned. In most cases, this list will contain only one element.
- `RequestId`: the identifier of the request you made. Please mention this to us when you have questions, as it will make debugging easier.
-
- `errors`: a list of errors (containing a code and a message) that the server returned. In most cases, this list will contain only one element.
- `requestId`: the identifier of the request you made. Please mention this to us when you have questions, as it will make debugging easier.

## Idempotency

**NOTE**: Idempotency is currently in a soft launch: it is enabled per company and not yet publicly available. Contact seats.io support to have it enabled for your company.

Every `POST`, `PUT` and `DELETE` request is sent with an `Idempotency-Key` header (a v4 UUID, generated by the client). If idempotency is enabled for your company, the server executes a request with a given key only once, and replays the original response when it receives the same request again. If it isn't enabled, the server ignores the key, and retrying a request can execute it a second time.

If a request fails and you can't tell whether it was processed (e.g. the connection dropped before you received the response), the exception carries the key that was used, so you can retry the operation with the same key:

```python
try:
client.events.create(chart_key)
except SeatsioException as e:
# only retry when the outcome is unknown (a connection error, a timeout or a 5xx); retrying a 4xx can never succeed
client.with_idempotency_key(e.idempotency_key).events.create(chart_key)
```

The retried request must be identical to the original one. All requests made with the client returned by `with_idempotency_key` send the same key, so use it for one operation only. You can also supply your own key (e.g. `str(uuid.uuid4())`); it must be a v4 UUID, otherwise `with_idempotency_key` raises a `ValueError`.

The client reuses the key when it retries a request after a `429`, and also when the server answers `409` because an earlier request with the same key is still being processed.

## Rate limiting - exponential backoff

This library supports [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff).
Expand Down
22 changes: 19 additions & 3 deletions seatsio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,20 @@


class Client:
IDEMPOTENCY_KEY_HEADER = "Idempotency-Key"

def __init__(self, region, secret_key, workspace_key=None, max_retries=5):
base_url = region.url
self.base_url = base_url
self.http_client = HttpClient(base_url, secret_key, workspace_key, max_retries)
self.__init_with_http_client(HttpClient(region.url, secret_key, workspace_key, max_retries))

@classmethod
def _from_http_client(cls, http_client):
client = cls.__new__(cls)
client.__init_with_http_client(http_client)
return client

def __init_with_http_client(self, http_client):
self.http_client = http_client
self.base_url = http_client.base_url
self.charts = ChartsClient(self.http_client)
self.events = EventsClient(self.http_client)
self.seasons = SeasonsClient(self.http_client, self)
Expand All @@ -22,3 +32,9 @@ def __init__(self, region, secret_key, workspace_key=None, max_retries=5):
self.usage_reports = UsageReports(self.http_client)
self.event_log = EventLogClient(self.http_client)
self.ticket_buyers = TicketBuyersClient(self.http_client)

def with_idempotency_key(self, idempotency_key):
return Client._from_http_client(self.http_client.with_idempotency_key(idempotency_key))

def withIdempotencyKey(self, idempotency_key):
return self.with_idempotency_key(idempotency_key)
16 changes: 15 additions & 1 deletion seatsio/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
class SeatsioException(Exception):

def __init__(self, request, response=None, cause=None):
if isinstance(request, str):
self.errors = None
self.requestId = None
self.cause = cause
self.message = request
self.idempotency_key = None
self.idempotencyKey = None
super(SeatsioException, self).__init__(self.message)
return

self.idempotency_key = getattr(request, 'idempotency_key', None)
self.idempotencyKey = self.idempotency_key
if (response is not None) and ("application/json" in response.headers.get("content-type", "")):
body = response.json()
self.errors = body["errors"]
Expand All @@ -12,7 +24,9 @@ def __init__(self, request, response=None, cause=None):
self.errors = None
self.requestId = None
self.cause = cause
self.message = "Error while executing " + request.http_method + " " + request.url
http_method = getattr(request, 'http_method', '')
url = getattr(request, 'url', '')
self.message = f"Error while executing {http_method} {url}".strip()
super(SeatsioException, self).__init__(self.message)

@staticmethod
Expand Down
114 changes: 100 additions & 14 deletions seatsio/httpClient.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import re
import time
import uuid
from urllib.parse import quote, urlencode

import jsonpickle
Expand All @@ -7,32 +9,45 @@
from seatsio.exceptions import SeatsioException, RateLimitExceededException


UUID_V4 = re.compile(r'\A[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\Z', re.IGNORECASE)


def handle_error(request, response):
raise SeatsioException.from_response(request, response)


class HttpClient:
def __init__(self, base_url, secret_key, workspace_key, max_retries, timeout=10):
def __init__(self, base_url, secret_key, workspace_key, max_retries, timeout=10, idempotency_key=None):
self.base_url = base_url
self.secret_key = secret_key
self.workspace_key = workspace_key
self.max_retries = max_retries
self.timeout = timeout
self.idempotency_key = idempotency_key

def with_idempotency_key(self, idempotency_key):
if not isinstance(idempotency_key, str) or not UUID_V4.match(idempotency_key):
raise ValueError("idempotency key %r is not a v4 UUID" % (idempotency_key,))
return HttpClient(self.base_url, self.secret_key, self.workspace_key, self.max_retries, self.timeout, idempotency_key)

def withIdempotencyKey(self, idempotency_key):
return self.with_idempotency_key(idempotency_key)

def url(self, relative_url, query_params=None, **path_params):
if query_params is None:
query_params = {}
return ApiResource(self.max_retries, self.secret_key, self.workspace_key, self.base_url, relative_url,
query_params, self.timeout, **path_params)
query_params, self.timeout, self.idempotency_key, **path_params)


class ApiResource:
def __init__(self, max_retries, secret_key, workspace_key, base_url, relative_url, query_params, timeout, **path_params):
def __init__(self, max_retries, secret_key, workspace_key, base_url, relative_url, query_params, timeout, idempotency_key=None, **path_params):
self.max_retries = max_retries
self.url = self.__create_full_url(base_url, relative_url, query_params, **path_params)
self.secret_key = secret_key
self.workspace_key = workspace_key
self.timeout = timeout
self.idempotency_key = idempotency_key

def __create_full_url(self, base_url, relative_url, query_params, **path_params):
for key in path_params:
Expand All @@ -53,18 +68,24 @@ def get_as(self, cls):

def post(self, body=None):
if body is None:
return POST(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout).execute()
return POST(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).execute()
else:
return POST(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout).body(body).execute()
return POST(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).body(body).execute()

def post_empty_and_return(self, cls):
return cls(self.post().json())

def delete(self, body=None):
if body is None:
return DELETE(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout).execute()
return DELETE(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).execute()
else:
return DELETE(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout).body(body).execute()
return DELETE(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).body(body).execute()

def put(self, body=None):
if body is None:
return PUT(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).execute()
else:
return PUT(self.max_retries, self.url, self.secret_key, self.workspace_key, self.timeout, self.idempotency_key).body(body).execute()


class GET:
Expand All @@ -76,6 +97,7 @@ def __init__(self, max_retries, url, secret_key, workspace_key, timeout):
self.secret_key = secret_key
self.workspace_key = workspace_key
self.timeout = timeout
self.idempotency_key = None

def execute(self):
response = retry(self.try_execute, self.max_retries)
Expand All @@ -100,14 +122,15 @@ def try_execute(self):

class POST:

def __init__(self, max_retries, url, secret_key, workspace_key, timeout):
def __init__(self, max_retries, url, secret_key, workspace_key, timeout, idempotency_key=None):
self.http_method = "POST"
self.max_retries = max_retries
self.url = url
self.secret_key = secret_key
self.workspace_key = workspace_key
self.timeout = timeout
self.body_object = None
self.idempotency_key = idempotency_key if idempotency_key is not None else str(uuid.uuid4())

def body(self, body):
self.body_object = body
Expand All @@ -126,7 +149,7 @@ def try_execute(self):
return requests.post(
url=self.url,
auth=(self.secret_key, ''),
headers=(common_headers(self.workspace_key)),
headers=(common_headers(self.workspace_key, self.idempotency_key)),
data=json,
timeout=self.timeout
)
Expand All @@ -136,14 +159,15 @@ def try_execute(self):

class DELETE:

def __init__(self, max_retries, url, secret_key, workspace_key, timeout):
def __init__(self, max_retries, url, secret_key, workspace_key, timeout, idempotency_key=None):
self.http_method = "DELETE"
self.max_retries = max_retries
self.url = url
self.secret_key = secret_key
self.workspace_key = workspace_key
self.timeout = timeout
self.body_object = None
self.idempotency_key = idempotency_key if idempotency_key is not None else str(uuid.uuid4())

def body(self, body):
self.body_object = body
Expand All @@ -162,28 +186,90 @@ def try_execute(self):
return requests.delete(
self.url,
auth=(self.secret_key, ''),
headers=(common_headers(self.workspace_key)),
headers=(common_headers(self.workspace_key, self.idempotency_key)),
data=json,
timeout=self.timeout
)
except Exception as cause:
raise SeatsioException(self, cause=cause)


class PUT:

def __init__(self, max_retries, url, secret_key, workspace_key, timeout, idempotency_key=None):
self.http_method = "PUT"
self.max_retries = max_retries
self.url = url
self.secret_key = secret_key
self.workspace_key = workspace_key
self.timeout = timeout
self.body_object = None
self.idempotency_key = idempotency_key if idempotency_key is not None else str(uuid.uuid4())

def body(self, body):
self.body_object = body
return self

def execute(self):
response = retry(self.try_execute, self.max_retries)
if response.status_code >= 400:
handle_error(self, response)
else:
return response

def try_execute(self):
try:
json = jsonpickle.encode(self.body_object, unpicklable=False)
return requests.put(
self.url,
auth=(self.secret_key, ''),
headers=(common_headers(self.workspace_key, self.idempotency_key)),
data=json,
timeout=self.timeout
)
except Exception as cause:
raise SeatsioException(self, cause=cause)


def common_headers(workspace_key):
return {
def common_headers(workspace_key, idempotency_key=None):
headers = {
'X-Workspace-Key': str(workspace_key) if workspace_key else None,
'X-Client-Lib': 'python'
}
if idempotency_key:
headers['Idempotency-Key'] = idempotency_key
return headers


def retry(fn, max_retries):
retry_count = 0
while True:
response = fn()
if response.status_code != 429 or retry_count >= max_retries:
if not is_retryable(response) or retry_count >= max_retries:
return response
else:
wait_time = (2 ** (retry_count + 2)) / 10.0
time.sleep(wait_time)
retry_count += 1


def is_retryable(response):
if response.status_code == 429:
return True
if response.status_code == 409:
codes = api_error_codes(response)
return len(codes) > 0 and codes[0] == 'IDEMPOTENCY_KEY_IN_USE'
return False


def api_error_codes(response):
if "application/json" not in response.headers.get("content-type", ""):
return []
try:
body = response.json()
except ValueError:
return []
errors = body.get("errors") if isinstance(body, dict) else None
if not isinstance(errors, list):
return []
return [error["code"] for error in errors if isinstance(error, dict) and "code" in error]
8 changes: 8 additions & 0 deletions tests/httpbin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import os

DEFAULT_URL = "https://httpbingo.org"


def httpbin_url(path=""):
base = os.environ.get("HTTPBIN_URL", DEFAULT_URL)
return base + path
Loading
Loading