Skip to content
Merged
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
43 changes: 41 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,11 @@ logging.getLogger('checkout').setLevel(logging.INFO)
Checkout SDK uses `requests` library to perform http operations, and you can provide your own custom http client implementing `HttpClientBuilderInterface`

```python
import requests
from requests import Session

import checkout_sdk
from checkout_sdk.checkout_sdk import CheckoutSdk
from checkout_sdk.default_http_client import DefaultTimeoutSession
from checkout_sdk.environment import Environment
from checkout_sdk.oauth_scopes import OAuthScopes
from checkout_sdk.http_client_interface import HttpClientBuilderInterface
Expand All @@ -168,7 +168,7 @@ from checkout_sdk.http_client_interface import HttpClientBuilderInterface
class CustomHttpClientBuilder(HttpClientBuilderInterface):

def get_client(self) -> Session:
session = requests.Session()
session = DefaultTimeoutSession() # keeps the SDK default timeouts, see Timeouts below
session.max_redirects = 5
return session

Expand All @@ -188,6 +188,45 @@ def oauth():
payments_client.refund_payment('payment_id')
```

### Timeouts

The session the SDK creates by default gives every request a timeout of 10 seconds to connect and send the request
(each wait on the socket, so a large upload is not limited as a whole) and 60 seconds between bytes of the response,
not a limit on the whole request (`DEFAULT_CONNECT_TIMEOUT` and `DEFAULT_READ_TIMEOUT` in
`checkout_sdk.default_http_client`). The 10 seconds start once the host name is resolved: the DNS lookup is not
included and keeps the limits of the system resolver. A request that times out raises a `CheckoutException`, or a
`CheckoutAuthorizationException` for the OAuth token request.

A session returned by your own `HttpClientBuilderInterface` is used as is, so the SDK adds no timeout to it. `requests`
waits forever unless a timeout is given, so set your own bounds on the session you provide. To keep the defaults above,
return a `DefaultTimeoutSession`, as in the example above. To use other bounds, mount an adapter that sets them on every
request that passes no timeout of its own:

```python
from requests import Session
from requests.adapters import HTTPAdapter

from checkout_sdk.http_client_interface import HttpClientBuilderInterface


class TimeoutAdapter(HTTPAdapter):

def send(self, request, **kwargs):
if kwargs.get('timeout') is None:
kwargs['timeout'] = (5, 30) # (connect, read) in seconds
return super().send(request, **kwargs)


class TimeoutHttpClientBuilder(HttpClientBuilderInterface):

def get_client(self) -> Session:
session = Session()
session.mount('https://', TimeoutAdapter())
return session
```

Pass it to the builder with `.http_client_builder(TimeoutHttpClientBuilder())`, as in the example above.

## Exception handling

All the API responses that do not fall in the 2** status codes will cause a `CheckoutApiException`. The exception encapsulates
Expand Down
37 changes: 36 additions & 1 deletion checkout_sdk/default_http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,46 @@

from checkout_sdk.http_client_interface import HttpClientBuilderInterface

# Seconds to wait for the connection to the API host to be established.
DEFAULT_CONNECT_TIMEOUT = 10
# Seconds to wait between bytes of the response once the request has been sent.
DEFAULT_READ_TIMEOUT = 60


class DefaultTimeoutSession(requests.Session):
"""
Session created by the SDK when no http_client_builder is provided. requests has no
session-wide timeout and waits forever by default, so every request made through this
session is bounded by DEFAULT_CONNECT_TIMEOUT and DEFAULT_READ_TIMEOUT unless the call
passes its own timeout.
"""

# Index of timeout in the positional arguments of requests.Session.request after method and url
# (params, data, headers, cookies, files, auth, timeout).
_TIMEOUT_POSITION = 6

def request(self, method, url, *args, **kwargs):
"""
Sends the request with the default (connect, read) timeout unless the call passes its own.

Args:
method: the HTTP method.
url: the URL of the request.
*args: the other positional arguments of requests.Session.request.
**kwargs: the other keyword arguments of requests.Session.request.

Returns:
requests.Response: the response.
"""
if len(args) <= self._TIMEOUT_POSITION:
kwargs.setdefault('timeout', (DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT))
return super().request(method, url, *args, **kwargs)


class DefaultHttpClientBuilder(HttpClientBuilderInterface):

def __init__(self):
self.session = requests.Session()
self.session = DefaultTimeoutSession()

def get_client(self):
return self.session
19 changes: 18 additions & 1 deletion checkout_sdk/oauth_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from abc import ABCMeta
from datetime import datetime, timedelta

from requests import HTTPError, Session, ConnectionError
from requests import HTTPError, Session, ConnectionError, Timeout

from checkout_sdk.authorization_type import AuthorizationType
from checkout_sdk.environment import Environment
Expand Down Expand Up @@ -58,6 +58,18 @@ def get_authorization(self, authorization_type: AuthorizationType):
raise CheckoutAuthorizationException.invalid_authorization(authorization_type=authorization_type)

def get_access_token(self):
"""
Returns the cached access token while it is valid, otherwise requests a new one.

Returns:
OAuthAccessToken: the access token.

Raises:
CheckoutAuthorizationException: if the token endpoint answers with an error status, the connection
cannot be established, or the request times out while waiting for the response. A response body
that stops arriving is reported by requests as a connection error, so it raises the "Unable to
establish connection" message even though the connection was made.
"""
if self.__access_token is not None and self.__access_token.is_valid():
return self.__access_token

Expand All @@ -82,8 +94,13 @@ def get_access_token(self):
err.response.status_code)
raise CheckoutAuthorizationException(message) from err
except ConnectionError as err:
# A connect timeout is a ConnectionError too and keeps this message, and so is a read timeout while
# requests reads the response body (it raises ConnectionError there), even though the connection was made.
raise CheckoutAuthorizationException(
'Unable to establish connection to host: ({})'.format(self.__authorization_uri)) from err
except Timeout as err:
# A read timeout: a fixed message, like the other token errors.
raise CheckoutAuthorizationException('OAuth token request timed out') from err

response_json = response.json()
self.__access_token = OAuthAccessToken(token=response_json['access_token'],
Expand Down
31 changes: 31 additions & 0 deletions tests/api_client_timeout_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import time

import pytest
from requests.exceptions import Timeout

from checkout_sdk import default_http_client
from checkout_sdk.api_client import ApiClient
from checkout_sdk.checkout_configuration import CheckoutConfiguration
from checkout_sdk.default_http_client import DefaultHttpClientBuilder
from checkout_sdk.environment import Environment
from checkout_sdk.exception import CheckoutException
from checkout_sdk.platform_type import PlatformType
from checkout_sdk.sdk_authorization import SdkAuthorization
from tests.checkout_test_utils import unresponsive_server


def test_should_raise_a_checkout_exception_when_the_api_does_not_answer_in_time(monkeypatch):
# The real default session against a server that never answers, with a short read bound.
monkeypatch.setattr(default_http_client, 'DEFAULT_READ_TIMEOUT', 0.5)
configuration = CheckoutConfiguration(None, Environment.sandbox(), DefaultHttpClientBuilder().get_client())

with unresponsive_server() as base_uri:
api_client = ApiClient(configuration, base_uri + '/')
started = time.monotonic()
with pytest.raises(CheckoutException) as excinfo:
api_client.get('payments/pay_123', SdkAuthorization(PlatformType.DEFAULT, 'sk_test'))
elapsed = time.monotonic() - started

assert type(excinfo.value) is CheckoutException
assert isinstance(excinfo.value.__cause__, Timeout)
assert elapsed < 5
41 changes: 41 additions & 0 deletions tests/checkout_test_utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
from __future__ import absolute_import

import logging
import socket
import threading
import time
import uuid
from contextlib import contextmanager
from pathlib import Path

from checkout_sdk.common.common import Address, Phone, CustomerRequest, AccountHolder
Expand Down Expand Up @@ -142,3 +145,41 @@ def get_payment_recipient():
recipient.zip = '12345'
recipient.country = Country.ES
return recipient


@contextmanager
def unresponsive_server(close_after=5):
"""
Local server that accepts connections and never answers. Yields its base URL. Each connection is closed
close_after seconds after it is accepted, so a client with no timeout fails instead of hanging the test.
"""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 0))
server.listen(5)
server.settimeout(0.1)
connections = []
stopped = threading.Event()

def accept():
while not stopped.is_set():
try:
connection = server.accept()[0]
connections.append(connection)
closer = threading.Timer(close_after, connection.close)
closer.daemon = True
closer.start()
except socket.timeout:
continue
except OSError:
return

acceptor = threading.Thread(target=accept, daemon=True)
acceptor.start()
try:
yield 'http://127.0.0.1:{}'.format(server.getsockname()[1])
finally:
stopped.set()
acceptor.join() # no accept can happen after this, so the loop below closes every connection
server.close()
for connection in connections:
connection.close()
96 changes: 96 additions & 0 deletions tests/default_http_client_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import json

from requests import Response, Session
from requests.adapters import HTTPAdapter

from checkout_sdk.checkout_sdk import CheckoutSdk
from checkout_sdk.default_http_client import DefaultHttpClientBuilder, DefaultTimeoutSession, \
DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT
from checkout_sdk.http_client_interface import HttpClientBuilderInterface


def ok_response(request):
response = Response()
response.status_code = 200
response.request = request
response.url = request.url
response.headers['Content-Type'] = 'application/json'
response._content = json.dumps({'id': 'pay_123'}).encode('utf-8')
return response


def stub_transport(mocker):
# Only the transport is stubbed: the session merges its settings into the request, so the
# test sees the timeout the socket would get.
return mocker.patch.object(HTTPAdapter, 'send', autospec=True,
side_effect=lambda adapter, request, **kwargs: ok_response(request))


class CustomHttpClientBuilder(HttpClientBuilderInterface):

def __init__(self):
self.session = Session()

def get_client(self) -> Session:
return self.session


def sdk_builder():
return CheckoutSdk.builder() \
.secret_key('sk_sbox_m73dzbpy7cf3gfd46xr4yj5xo4e') \
.environment_subdomain('123domain')


def test_default_timeouts_are_10_seconds_to_connect_and_60_seconds_to_read():
assert DEFAULT_CONNECT_TIMEOUT == 10
assert DEFAULT_READ_TIMEOUT == 60


def test_should_apply_the_default_timeouts_to_every_request_of_the_default_session(mocker):
send = stub_transport(mocker)
session = DefaultHttpClientBuilder().get_client()

session.request(method='POST', url='https://api.sandbox.checkout.com/payments')
session.get('https://api.sandbox.checkout.com/payments/pay_123')

assert isinstance(session, DefaultTimeoutSession)
assert [call.kwargs['timeout'] for call in send.call_args_list] == [
(DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT), (DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT)]


def test_should_keep_a_timeout_passed_to_the_request_of_the_default_session(mocker):
send = stub_transport(mocker)

DefaultHttpClientBuilder().get_client().request(method='GET', url='https://api.sandbox.checkout.com/',
timeout=5)

assert send.call_args.kwargs['timeout'] == 5


def test_should_keep_a_timeout_passed_by_position_to_the_request_of_the_default_session(mocker):
send = stub_transport(mocker)

DefaultTimeoutSession().request('GET', 'https://example.com/', None, None, None, None, None, None, 7)

assert send.call_args.kwargs['timeout'] == 7


def test_should_send_sdk_requests_with_the_default_timeouts_when_no_http_client_builder_is_set(mocker):
send = stub_transport(mocker)

sdk_builder().build().payments.get_payment_details('pay_123')

assert send.call_count == 1
assert send.call_args.kwargs['timeout'] == (DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT)


def test_should_leave_the_session_of_a_custom_http_client_builder_untouched(mocker):
send = stub_transport(mocker)
http_client_builder = CustomHttpClientBuilder()

sdk = sdk_builder().http_client_builder(http_client_builder).build()
sdk.payments.get_payment_details('pay_123')

assert type(http_client_builder.session) is Session
assert send.call_count == 1
assert send.call_args.kwargs['timeout'] is None
38 changes: 38 additions & 0 deletions tests/oauth_credentials_test.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import json
import time

import pytest
from requests import Response, Session
from requests.adapters import HTTPAdapter
from requests.exceptions import ConnectTimeout, Timeout

from checkout_sdk import default_http_client
from checkout_sdk.default_http_client import DefaultHttpClientBuilder
from checkout_sdk.environment import Environment
from checkout_sdk.exception import CheckoutAuthorizationException
from checkout_sdk.oauth_credentials import OAuthSdkCredentials
from tests.checkout_test_utils import unresponsive_server


def token_response(request):
Expand Down Expand Up @@ -56,3 +62,35 @@ def test_should_use_the_ca_bundle_configured_on_the_http_client(self, mocker):
send = self.request_token(mocker, http_client)

assert send.call_args.kwargs['verify'] == '/path/to/ca-bundle.pem'

def test_should_raise_a_checkout_authorization_exception_when_the_token_request_times_out(self, monkeypatch):
# The real default session against a server that never answers, with a short read bound.
monkeypatch.setattr(default_http_client, 'DEFAULT_READ_TIMEOUT', 0.5)

with unresponsive_server() as base_uri:
authorization_uri = base_uri + '/connect/token'
credentials = OAuthSdkCredentials(DefaultHttpClientBuilder().get_client(), Environment.sandbox(),
'client_id', 'client_secret', authorization_uri, ['vault'])
started = time.monotonic()
with pytest.raises(CheckoutAuthorizationException) as excinfo:
credentials.get_access_token()
elapsed = time.monotonic() - started

assert str(excinfo.value) == 'OAuth token request timed out'
assert 'client_secret' not in str(excinfo.value)
assert 'Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=' not in str(excinfo.value) # base64 of the basic auth value
assert isinstance(excinfo.value.__cause__, Timeout)
assert elapsed < 5

def test_should_keep_the_connection_message_when_the_token_request_cannot_connect_in_time(self, mocker):
http_client = Session()
mocker.patch.object(http_client, 'request', side_effect=ConnectTimeout('connect timed out'))
credentials = OAuthSdkCredentials(http_client, Environment.sandbox(), 'client_id', 'client_secret',
'https://access.sandbox.checkout.com/connect/token', ['vault'])

with pytest.raises(CheckoutAuthorizationException) as excinfo:
credentials.get_access_token()

assert str(excinfo.value) == \
'Unable to establish connection to host: (https://access.sandbox.checkout.com/connect/token)'
assert isinstance(excinfo.value.__cause__, ConnectTimeout)
Loading