Skip to content

Add support for httpx as backend #1085

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

Open
wants to merge 41 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
1eb6888
Replace aiohttp with httpx
jakkdl Feb 1, 2024
d10761c
WIP of full replacement of aiohttp with httpx
jakkdl Feb 9, 2024
3608872
mostly finished WIP of adding httpx support
jakkdl Feb 19, 2024
757819f
fix various test failures
jakkdl Feb 19, 2024
4327b58
fix more parametrization issues
jakkdl Feb 19, 2024
e123adc
fix typo current_http_stack -> current_http_backend
jakkdl Feb 19, 2024
d029aa4
Add pytest flag for specifying backend when running tests.
jakkdl Feb 20, 2024
8f6bd69
add initial retryable exceptions. _validate_connector_args will now g…
jakkdl Feb 20, 2024
bdc680c
yes
jakkdl Feb 20, 2024
48b7310
append coverage when running tests twice
jakkdl Mar 1, 2024
b19bc09
Merge branch 'master' into httpx
jakkdl Mar 1, 2024
3e38c06
fix normalization of key paths in urls, revert test
jakkdl Apr 3, 2024
3e29d0d
shuffle around code wrt retryable exception to be less confusing
jakkdl Apr 3, 2024
af293b0
Merge remote-tracking branch 'origin/master' into httpx
jakkdl Apr 3, 2024
4482464
Merge remote-tracking branch 'origin/master' into httpx
jakkdl Oct 19, 2024
9dff5be
fix failed merge
jakkdl Oct 19, 2024
746d6b1
ruamel/yaml release pulled, so minor commit to retrigger CI
jakkdl Oct 19, 2024
82f2bc8
pre-merge dir rename
jakkdl Feb 27, 2025
550b660
Merge remote-tracking branch 'origin/master' into httpx
jakkdl Feb 27, 2025
2fd7f29
first fixes after reviews
jakkdl Feb 28, 2025
d1c0d12
fix no-httpx ci run
jakkdl Feb 28, 2025
9462503
add HttpxStreamingBody to reduce test changes
jakkdl Feb 28, 2025
c5d4592
blah
jakkdl Feb 28, 2025
6b73fbb
Merge remote-tracking branch 'origin/master' into httpx
jakkdl Mar 3, 2025
4d4cf32
make no_httpx a separate matrix entry
jakkdl Mar 3, 2025
6daaa79
Merge branch 'master' into httpx
jakkdl Apr 7, 2025
03da7e7
Merge remote-tracking branch 'origin/master' into HEAD
jakkdl May 9, 2025
be976f1
error if unknown http backend
jakkdl May 14, 2025
ae6f1d0
Merge remote-tracking branch 'origin/master' into httpx
jakkdl May 14, 2025
041f7f1
add HttpxStreamingChecksumBody to fix tests. But there's probably a n…
jakkdl May 14, 2025
da5e9fa
fix test_output_compliance fails... as it uses global state 🙃
jakkdl May 14, 2025
e8ba517
stop using include in CI for conditional vars
jakkdl May 14, 2025
7f057b2
quote os value
jakkdl May 14, 2025
109a201
remove HttpxAWSResponse, replace with some logic in AioAWSResponse
jakkdl May 14, 2025
fd8e653
small fixes after review
jakkdl May 14, 2025
b977370
move skip_httpx to tests/conftest
jakkdl May 14, 2025
a4ee8c7
improve exception mapping & retryable exceptions
jakkdl May 15, 2025
e257182
convert iterables to async iterables instead of reading data in send
jakkdl May 19, 2025
81d120f
Merge remote-tracking branch 'origin/master' into httpx
jakkdl May 21, 2025
d7e5f4a
use wait_for_close instead of close in StreamingBody
jakkdl May 21, 2025
4149c4f
handle timeouts better, clean up comments
jakkdl May 21, 2025
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
13 changes: 7 additions & 6 deletions .github/workflows/ci-cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,21 @@ jobs:
os:
- ubuntu-24.04
- ubuntu-24.04-arm
no-httpx: [false]
include:
- experimental: false
- upload-coverage: false
- upload-coverage: true
python-version: 3.11
- no-httpx: true
python-version: 3.13
os: ubuntu-24.04
fail-fast: false
uses: ./.github/workflows/reusable-test.yml
with:
python-version: ${{ matrix.python-version }}
os: ${{ matrix.os }}
continue-on-error: ${{ matrix.experimental }}
continue-on-error: false
enable-cache: ${{ github.ref_type == 'tag' && 'false' || 'auto' }}
upload-coverage: ${{ matrix.upload-coverage }}
upload-coverage:
${{ matrix.python-version == 3.11 && matrix.os == 'ubuntu-24.04' }}
no-httpx: ${{ matrix.no-httpx }}
secrets:
# yamllint disable-line rule:line-length
codecov-token: ${{ matrix.upload-coverage && secrets.CODECOV_TOKEN || '' }}
Expand Down
15 changes: 14 additions & 1 deletion .github/workflows/reusable-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ on:
required: true
upload-coverage:
type: boolean
no-httpx:
type: boolean
required: true
secrets:
codecov-token:
required: false
Expand All @@ -28,7 +31,9 @@ env:

jobs:
test:
name: Test Python ${{ inputs.python-version }} on ${{ inputs.os }}
name: Test Python ${{ inputs.python-version }} on ${{ inputs.os }}${{
inputs.no-httpx && ' no-httpx' || '' }}

runs-on: ${{ inputs.os }}
continue-on-error: ${{ inputs.continue-on-error }}
env:
Expand All @@ -51,10 +56,18 @@ jobs:
run: |
uv run make pre-commit
- name: Run unittests
if: ${{ ! matrix.no_httpx }}
env:
COLOR: 'yes'
run: |
uv run make mototest
- name: Run unittests without httpx installed
if: ${{ matrix.no_httpx }}
env:
COLOR: 'yes'
HTTP_BACKEND: 'aiohttp'
run: |
uv run --no-group=httpx make mototest
- name: Upload coverage to Codecov
if: ${{ inputs.upload-coverage }}
# yamllint disable-line rule:line-length
Expand Down
5 changes: 3 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Some simple testing tasks (sorry, UNIX only).

# ?= conditional assign, so users can pass options on the CLI instead of manually editing this file
# ?= is conditional assign, so users can pass options on the CLI instead of manually editing this file
HTTP_BACKEND?='all'
FLAGS?=

pre-commit:
Expand All @@ -17,7 +18,7 @@ cov cover coverage: pre-commit
@echo "open file://`pwd`/htmlcov/index.html"

mototest:
python -Wd -X tracemalloc=5 -X faulthandler -m pytest -vv -m "not localonly" -n auto --cov-report term --cov-report html --cov-report xml --cov=aiobotocore --cov=tests --log-cli-level=DEBUG $(FLAGS) aiobotocore tests
python -Wd -X tracemalloc=5 -X faulthandler -m pytest -vv -m "not localonly" -n auto --cov-report term --cov-report html --cov-report xml --cov=aiobotocore --cov=tests --log-cli-level=DEBUG --http-backend=$(HTTP_BACKEND) $(FLAGS) aiobotocore tests

clean:
rm -rf `find . -name __pycache__`
Expand Down
21 changes: 21 additions & 0 deletions aiobotocore/_endpoint_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
import botocore.retryhandler
import wrapt

try:
import httpx
except ImportError:
httpx = None

# Monkey patching: We need to insert the aiohttp exception equivalents
# The only other way to do this would be to have another config file :(
_aiohttp_retryable_exceptions = [
Expand All @@ -14,10 +19,26 @@
asyncio.TimeoutError,
]


botocore.retryhandler.EXCEPTION_MAP['GENERAL_CONNECTION_ERROR'].extend(
_aiohttp_retryable_exceptions
)

if httpx is not None:
# See https://www.python-httpx.org/exceptions/#the-exception-hierarchy
# All child exceptions of TransportError, except ProxyError,
# UnsupportedProtocol and CloseError.
_httpx_retryable_exceptions = [
httpx.TimeoutException,
httpx.ProtocolError,
httpx.ConnectError,
httpx.ReadError,
httpx.WriteError,
]
botocore.retryhandler.EXCEPTION_MAP['GENERAL_CONNECTION_ERROR'].extend(
_httpx_retryable_exceptions
)


def _text(s, encoding='utf-8', errors='strict'):
if isinstance(s, bytes):
Expand Down
11 changes: 10 additions & 1 deletion aiobotocore/awsrequest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import botocore.utils
from botocore.awsrequest import AWSResponse

try:
import httpx
except ImportError:
httpx = None


class AioAWSResponse(AWSResponse):
# Unlike AWSResponse, these return awaitables
Expand All @@ -9,8 +14,12 @@ async def _content_prop(self):
"""Content of the response as bytes."""

if self._content is None:
if httpx is not None and isinstance(self.raw, httpx.Response):
read_func = self.raw.aread
else:
read_func = self.raw.read
# NOTE: this will cache the data in self.raw
self._content = await self.raw.read() or b''
self._content = await read_func() or b''

return self._content

Expand Down
33 changes: 25 additions & 8 deletions aiobotocore/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
from botocore.exceptions import ParamValidationError

from aiobotocore.endpoint import DEFAULT_HTTP_SESSION_CLS
from aiobotocore.httpxsession import HttpxSession

# AWS has a 20 second idle timeout:
# https://web.archive.org/web/20150926192339/https://forums.aws.amazon.com/message.jspa?messageID=215367
# and aiohttp default timeout is 30s so we set it to something
# reasonable here
DEFAULT_KEEPALIVE_TIMEOUT = 12


class AioConfig(botocore.client.Config):
Expand All @@ -15,18 +22,16 @@ def __init__(
):
super().__init__(**kwargs)

self._validate_connector_args(connector_args)
self._validate_connector_args(connector_args, http_session_cls)
self.connector_args = copy.copy(connector_args)
self.http_session_cls = http_session_cls
if not self.connector_args:
self.connector_args = dict()

if 'keepalive_timeout' not in self.connector_args:
# AWS has a 20 second idle timeout:
# https://web.archive.org/web/20150926192339/https://forums.aws.amazon.com/message.jspa?messageID=215367
# and aiohttp default timeout is 30s so we set it to something
# reasonable here
self.connector_args['keepalive_timeout'] = 12
self.connector_args['keepalive_timeout'] = (
DEFAULT_KEEPALIVE_TIMEOUT
)

def merge(self, other_config):
# Adapted from parent class
Expand All @@ -35,13 +40,17 @@ def merge(self, other_config):
return AioConfig(self.connector_args, **config_options)

@staticmethod
def _validate_connector_args(connector_args):
def _validate_connector_args(connector_args, http_session_cls):
if connector_args is None:
return

for k, v in connector_args.items():
# verify_ssl is handled by verify parameter to create_client
if k == 'use_dns_cache':
if http_session_cls is HttpxSession:
raise ParamValidationError(
report='Httpx does not support dns caching. https://github.com/encode/httpx/discussions/2211'
)
if not isinstance(v, bool):
raise ParamValidationError(
report=f'{k} value must be a boolean'
Expand All @@ -51,12 +60,16 @@ def _validate_connector_args(connector_args):
raise ParamValidationError(
report=f'{k} value must be an int or None'
)
elif k == 'keepalive_timeout':
elif k in ('keepalive_timeout', 'write_timeout', 'pool_timeout'):
if v is not None and not isinstance(v, (float, int)):
raise ParamValidationError(
report=f'{k} value must be a float/int or None'
)
elif k == 'force_close':
if http_session_cls is HttpxSession:
raise ParamValidationError(
report=f'Httpx backend does not currently support {k}.'
)
if not isinstance(v, bool):
raise ParamValidationError(
report=f'{k} value must be a boolean'
Expand All @@ -72,6 +85,10 @@ def _validate_connector_args(connector_args):
elif k == "resolver":
from aiohttp.abc import AbstractResolver

if http_session_cls is HttpxSession:
raise ParamValidationError(
report=f'Httpx backend does not support {k}.'
)
if not isinstance(v, AbstractResolver):
raise ParamValidationError(
report=f'{k} must be an instance of a AbstractResolver'
Expand Down
14 changes: 11 additions & 3 deletions aiobotocore/endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
from aiobotocore.httpchecksum import handle_checksum_body
from aiobotocore.httpsession import AIOHTTPSession
from aiobotocore.parsers import AioResponseParserFactory
from aiobotocore.response import StreamingBody
from aiobotocore.response import HttpxStreamingBody, StreamingBody

try:
import httpx
except ImportError:
httpx = None

DEFAULT_HTTP_SESSION_CLS = AIOHTTPSession

Expand Down Expand Up @@ -50,8 +55,11 @@ async def convert_to_response_dict(http_response, operation_model):
elif operation_model.has_event_stream_output:
response_dict['body'] = http_response.raw
elif operation_model.has_streaming_output:
length = response_dict['headers'].get('content-length')
response_dict['body'] = StreamingBody(http_response.raw, length)
if httpx and isinstance(http_response.raw, httpx.Response):
response_dict['body'] = HttpxStreamingBody(http_response.raw)
else:
length = response_dict['headers'].get('content-length')
response_dict['body'] = StreamingBody(http_response.raw, length)
else:
response_dict['body'] = await http_response.content
return response_dict
Expand Down
38 changes: 36 additions & 2 deletions aiobotocore/httpchecksum.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@
)

from aiobotocore._helpers import resolve_awaitable
from aiobotocore.response import StreamingBody
from aiobotocore.response import HttpxStreamingBody, StreamingBody

try:
import httpx
except ImportError:
httpx = None


class AioAwsChunkedWrapper(AwsChunkedWrapper):
Expand Down Expand Up @@ -93,6 +98,31 @@ def _validate_checksum(self):
raise FlexibleChecksumError(error_msg=error_msg)


# TODO: fix inheritance? read & _validate_checksum are the exact same as above
# only diff is super class and how to call __init__
class HttpxStreamingChecksumBody(HttpxStreamingBody):
def __init__(self, raw_stream, content_length, checksum, expected):
# HttpxStreamingbody doesn't use content_length
super().__init__(raw_stream)
self._checksum = checksum
self._expected = expected

async def read(self, amt=None):
chunk = await super().read(amt=amt)
self._checksum.update(chunk)
if amt is None or (not chunk and amt > 0):
self._validate_checksum()
return chunk

def _validate_checksum(self):
if self._checksum.digest() != base64.b64decode(self._expected):
error_msg = (
f"Expected checksum {self._expected} did not match calculated "
f"checksum: {self._checksum.b64digest()}"
)
raise FlexibleChecksumError(error_msg=error_msg)


async def handle_checksum_body(
http_response, response, context, operation_model
):
Expand Down Expand Up @@ -139,7 +169,11 @@ async def handle_checksum_body(
def _handle_streaming_response(http_response, response, algorithm):
checksum_cls = _CHECKSUM_CLS.get(algorithm)
header_name = f"x-amz-checksum-{algorithm}"
return StreamingChecksumBody(
if httpx is not None and isinstance(http_response.raw, httpx.Response):
streaming_cls = HttpxStreamingChecksumBody
else:
streaming_cls = StreamingChecksumBody
return streaming_cls(
http_response.raw,
response["headers"].get("content-length"),
checksum_cls(),
Expand Down
8 changes: 4 additions & 4 deletions aiobotocore/httpsession.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
from multidict import CIMultiDict

import aiobotocore.awsrequest
import aiobotocore.config # avoid circular import
from aiobotocore._endpoint_helpers import _IOBaseWrapper, _text


Expand Down Expand Up @@ -83,10 +84,9 @@ def __init__(
self._timeout = timeout
self._connector_args = connector_args
if self._connector_args is None:
# AWS has a 20 second idle timeout:
# https://web.archive.org/web/20150926192339/https://forums.aws.amazon.com/message.jspa?messageID=215367
# aiohttp default timeout is 30s so set something reasonable here
self._connector_args = dict(keepalive_timeout=12)
self._connector_args = dict(
keepalive_timeout=aiobotocore.config.DEFAULT_KEEPALIVE_TIMEOUT
)

self._max_pool_connections = max_pool_connections
self._socket_options = socket_options
Expand Down
Loading