Skip to content
Open
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
151 changes: 148 additions & 3 deletions httpx/_transports/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from __future__ import annotations

import contextlib
import threading
import typing
from types import TracebackType

Expand Down Expand Up @@ -132,6 +133,139 @@ def close(self) -> None:
self._httpcore_stream.close()


class _SingleRequestStream(typing.Iterable[bytes]):
"""
Wrap a pooled connection's response stream, invoking `on_release`
exactly once when the stream is exhausted or closed.
"""

def __init__(
self,
stream: typing.Iterable[bytes],
on_release: typing.Callable[[], None],
) -> None:
self._stream = stream
self._on_release = on_release
self._released = False

def __iter__(self) -> typing.Iterator[bytes]:
try:
yield from self._stream
finally:
self._release()

def close(self) -> None:
try:
if hasattr(self._stream, "close"):
self._stream.close()
finally:
self._release()

def _release(self) -> None:
if not self._released:
self._released = True
self._on_release()


class _SingleRequestConnection:
"""
Wrap an httpcore connection so that it serves at most one request
at a time, from `handle_request` until the response stream closes.

The HTTP/2 implementation in httpcore multiplexes concurrent requests
onto a single connection, but its connection state is not thread-safe:
when a synchronous client is shared between threads, two threads can
encode headers concurrently and corrupt the shared HPACK state,
raising errors such as `RuntimeError: deque mutated during iteration`
(see #3633). HTTP/1.1 connections already refuse concurrent requests
with `ConnectionNotAvailable`, which makes the pool assign the request
to another connection. This wrapper restores the same guarantee for
every connection created by a synchronous HTTP/2 transport, at the
cost of using separate connections for concurrent requests, bounded
by the configured connection limits.
"""

def __init__(self, connection: typing.Any) -> None:
self._connection = connection
self._in_flight = threading.Lock()

def handle_request(self, request: typing.Any) -> typing.Any:
import httpcore

if not self._in_flight.acquire(blocking=False):
raise httpcore.ConnectionNotAvailable()
try:
response = self._connection.handle_request(request)
except BaseException:
self._in_flight.release()
raise
return httpcore.Response(
status=response.status,
headers=response.headers,
content=_SingleRequestStream(response.stream, self._release),
extensions=response.extensions,
)

def _release(self) -> None:
if self._in_flight.locked():
self._in_flight.release()

def can_handle_request(self, origin: typing.Any) -> bool:
return bool(self._connection.can_handle_request(origin))

def is_available(self) -> bool:
if self._in_flight.locked():
return False
return bool(self._connection.is_available())

def is_idle(self) -> bool:
return bool(self._connection.is_idle())

def is_closed(self) -> bool:
return bool(self._connection.is_closed())

def has_expired(self) -> bool:
return bool(self._connection.has_expired())

def close(self) -> None:
self._connection.close()

def info(self) -> str:
return str(self._connection.info())

def __repr__(self) -> str:
return repr(self._connection)


class _SingleRequestPoolMixin:
"""
Pool behaviour override: wrap every connection the pool creates in
`_SingleRequestConnection`. Used with each of the synchronous httpcore
pool classes when HTTP/2 is enabled.
"""

def create_connection(self, origin: typing.Any) -> typing.Any:
return _SingleRequestConnection(super().create_connection(origin)) # type: ignore[misc]


_single_request_pool_classes: dict[type, type] = {}


def _single_request_pool_class(pool_cls: type) -> type:
"""
Return a subclass of an httpcore sync pool class that creates
`_SingleRequestConnection` instances, building it on first use so
that httpcore is only imported once a transport is instantiated.
"""
if pool_cls not in _single_request_pool_classes:
_single_request_pool_classes[pool_cls] = type(
f"SingleRequest{pool_cls.__name__}",
(_SingleRequestPoolMixin, pool_cls),
{},
)
return _single_request_pool_classes[pool_cls]


class HTTPTransport(BaseTransport):
def __init__(
self,
Expand All @@ -152,8 +286,19 @@ def __init__(
proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy
ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)

# With HTTP/2 enabled, guard pooled connections so that a single
# connection is only ever used by one thread at a time. See
# `_SingleRequestConnection` and #3633.
pool_cls: type = httpcore.ConnectionPool
proxy_pool_cls: type = httpcore.HTTPProxy
socks_pool_cls: type = httpcore.SOCKSProxy
if http2:
pool_cls = _single_request_pool_class(pool_cls)
proxy_pool_cls = _single_request_pool_class(proxy_pool_cls)
socks_pool_cls = _single_request_pool_class(socks_pool_cls)

if proxy is None:
self._pool = httpcore.ConnectionPool(
self._pool = pool_cls(
ssl_context=ssl_context,
max_connections=limits.max_connections,
max_keepalive_connections=limits.max_keepalive_connections,
Expand All @@ -166,7 +311,7 @@ def __init__(
socket_options=socket_options,
)
elif proxy.url.scheme in ("http", "https"):
self._pool = httpcore.HTTPProxy(
self._pool = proxy_pool_cls(
proxy_url=httpcore.URL(
scheme=proxy.url.raw_scheme,
host=proxy.url.raw_host,
Expand All @@ -193,7 +338,7 @@ def __init__(
"Make sure to install httpx using `pip install httpx[socks]`."
) from None

self._pool = httpcore.SOCKSProxy(
self._pool = socks_pool_cls(
proxy_url=httpcore.URL(
scheme=proxy.url.raw_scheme,
host=proxy.url.raw_host,
Expand Down
Loading