Add trio concurrency backend (#276)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Florimond Manca · committed by Seth Michael Larson · parent 1275246 · Browse files · 13 files·+315 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+315 added−7 removed
- tests:+27 added−3 removed
- other:+288 added−4 removed
Provenance
- Commit
08355c6- Tree
85e14de- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
1275246
13 files changed+315 added−7 removed
modified:httpx/concurrency/asyncio.py+14 added
110 unmodified lines111 if should_raise:112 raise WriteTimeout() from None113 114 def is_connection_dropped(self) -> bool:115+ # Counter-intuitively, what we really want to know here is whether the socket is116+ # *readable*, i.e. whether it would return immediately with empty bytes if we117+ # called `.recv()` on it, indicating that the other end has closed the socket.118+ # See: https://github.com/encode/httpx/pull/143#issuecomment-515181778119+ #120+ # As it turns out, asyncio checks for readability in the background121+ # (see: https://github.com/encode/httpx/pull/276#discussion_r322000402),122+ # so checking for EOF or readability here would yield the same result.123+ #124+ # At the cost of rigour, we check for EOF instead of readability because asyncio125+ # does not expose any public API to check for readability.126+ # (For a solution that uses private asyncio APIs, see:127+ # https://github.com/encode/httpx/pull/143#issuecomment-515202982)128+129 return self.stream_reader.at_eof()130 131 async def close(self) -> None:132 self.stream_writer.close()160 unmodified linesmodified:httpx/concurrency/base.py+7 added
185 unmodified lines186 exc_value: BaseException = None,187 traceback: TracebackType = None,188 ) -> None:189 raise NotImplementedError() # pragma: no cover190+191+ async def close(self, exception: BaseException = None) -> None:192+ if exception is None:193+ await self.__aexit__(None, None, None)194+ else:195+ traceback = exception.__traceback__ # type: ignore196+ await self.__aexit__(type(exception), exception, traceback)added:httpx/concurrency/trio.py+255 added
1+import functools2+import math3+import ssl4+import typing5+from types import TracebackType6+7+import trio8+9+from ..config import PoolLimits, TimeoutConfig10+from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout11+from .base import (12+ BaseBackgroundManager,13+ BaseEvent,14+ BasePoolSemaphore,15+ BaseQueue,16+ BaseTCPStream,17+ ConcurrencyBackend,18+ TimeoutFlag,19+)20+21+22+def _or_inf(value: typing.Optional[float]) -> float:23+ return value if value is not None else float("inf")24+25+26+class TCPStream(BaseTCPStream):27+ def __init__(28+ self,29+ stream: typing.Union[trio.SocketStream, trio.SSLStream],30+ timeout: TimeoutConfig,31+ ) -> None:32+ self.stream = stream33+ self.timeout = timeout34+ self.write_buffer = b""35+ self.write_lock = trio.Lock()36+37+ def get_http_version(self) -> str:38+ if not isinstance(self.stream, trio.SSLStream):39+ return "HTTP/1.1"40+41+ ident = self.stream.selected_alpn_protocol()42+ if ident is None:43+ return "HTTP/1.1"44+45+ return "HTTP/2" if ident == "h2" else "HTTP/1.1"46+47+ async def read(48+ self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None49+ ) -> bytes:50+ if timeout is None:51+ timeout = self.timeout52+53+ while True:54+ # Check our flag at the first possible moment, and use a fine55+ # grained retry loop if we're not yet in read-timeout mode.56+ should_raise = flag is None or flag.raise_on_read_timeout57+ read_timeout = _or_inf(timeout.read_timeout if should_raise else 0.01)58+59+ with trio.move_on_after(read_timeout):60+ return await self.stream.receive_some(max_bytes=n)61+62+ if should_raise:63+ raise ReadTimeout() from None64+65+ def is_connection_dropped(self) -> bool:66+ # Adapted from: https://github.com/encode/httpx/pull/143#issuecomment-51520298267+ stream = self.stream68+69+ # Peek through any SSLStream wrappers to get the underlying SocketStream.70+ while hasattr(stream, "transport_stream"):71+ stream = stream.transport_stream72+ assert isinstance(stream, trio.SocketStream)73+74+ # Counter-intuitively, what we really want to know here is whether the socket is75+ # *readable*, i.e. whether it would return immediately with empty bytes if we76+ # called `.recv()` on it, indicating that the other end has closed the socket.77+ # See: https://github.com/encode/httpx/pull/143#issuecomment-51518177878+ return stream.socket.is_readable()79+80+ def write_no_block(self, data: bytes) -> None:81+ self.write_buffer += data82+83+ async def write(84+ self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None85+ ) -> None:86+ if self.write_buffer:87+ previous_data = self.write_buffer88+ # Reset before recursive call, otherwise we'll go through89+ # this branch indefinitely.90+ self.write_buffer = b""91+ try:92+ await self.write(previous_data, timeout=timeout, flag=flag)93+ except WriteTimeout:94+ self.writer_buffer = previous_data95+ raise96+97+ if not data:98+ return99+100+ if timeout is None:101+ timeout = self.timeout102+103+ write_timeout = _or_inf(timeout.write_timeout)104+105+ while True:106+ with trio.move_on_after(write_timeout):107+ async with self.write_lock:108+ await self.stream.send_all(data)109+ break110+ # We check our flag at the first possible moment, in order to111+ # allow us to suppress write timeouts, if we've since112+ # switched over to read-timeout mode.113+ should_raise = flag is None or flag.raise_on_write_timeout114+ if should_raise:115+ raise WriteTimeout() from None116+117+ async def close(self) -> None:118+ await self.stream.aclose()119+120+121+class PoolSemaphore(BasePoolSemaphore):122+ def __init__(self, pool_limits: PoolLimits):123+ self.pool_limits = pool_limits124+125+ @property126+ def semaphore(self) -> typing.Optional[trio.Semaphore]:127+ if not hasattr(self, "_semaphore"):128+ max_connections = self.pool_limits.hard_limit129+ if max_connections is None:130+ self._semaphore = None131+ else:132+ self._semaphore = trio.Semaphore(133+ max_connections, max_value=max_connections134+ )135+ return self._semaphore136+137+ async def acquire(self) -> None:138+ if self.semaphore is None:139+ return140+141+ timeout = _or_inf(self.pool_limits.pool_timeout)142+143+ with trio.move_on_after(timeout):144+ await self.semaphore.acquire()145+ return146+147+ raise PoolTimeout()148+149+ def release(self) -> None:150+ if self.semaphore is None:151+ return152+153+ self.semaphore.release()154+155+156+class TrioBackend(ConcurrencyBackend):157+ async def open_tcp_stream(158+ self,159+ hostname: str,160+ port: int,161+ ssl_context: typing.Optional[ssl.SSLContext],162+ timeout: TimeoutConfig,163+ ) -> TCPStream:164+ connect_timeout = _or_inf(timeout.connect_timeout)165+166+ with trio.move_on_after(connect_timeout) as cancel_scope:167+ stream: trio.SocketStream = await trio.open_tcp_stream(hostname, port)168+ if ssl_context is not None:169+ stream = trio.SSLStream(stream, ssl_context, server_hostname=hostname)170+ await stream.do_handshake()171+172+ if cancel_scope.cancelled_caught:173+ raise ConnectTimeout()174+175+ return TCPStream(stream=stream, timeout=timeout)176+177+ async def run_in_threadpool(178+ self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any179+ ) -> typing.Any:180+ return await trio.to_thread.run_sync(181+ functools.partial(func, **kwargs) if kwargs else func, *args182+ )183+184+ def run(185+ self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any186+ ) -> typing.Any:187+ return trio.run(188+ functools.partial(coroutine, **kwargs) if kwargs else coroutine, *args189+ )190+191+ def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:192+ return PoolSemaphore(limits)193+194+ def create_queue(self, max_size: int) -> BaseQueue:195+ return Queue(max_size=max_size)196+197+ def create_event(self) -> BaseEvent:198+ return Event()199+200+ def background_manager(201+ self, coroutine: typing.Callable, *args: typing.Any202+ ) -> "BackgroundManager":203+ return BackgroundManager(coroutine, *args)204+205+206+class Queue(BaseQueue):207+ def __init__(self, max_size: int) -> None:208+ self.send_channel, self.receive_channel = trio.open_memory_channel(math.inf)209+210+ async def get(self) -> typing.Any:211+ return await self.receive_channel.receive()212+213+ async def put(self, value: typing.Any) -> None:214+ await self.send_channel.send(value)215+216+217+class Event(BaseEvent):218+ def __init__(self) -> None:219+ self._event = trio.Event()220+221+ def set(self) -> None:222+ self._event.set()223+224+ def is_set(self) -> bool:225+ return self._event.is_set()226+227+ async def wait(self) -> None:228+ await self._event.wait()229+230+ def clear(self) -> None:231+ # trio.Event.clear() was deprecated in Trio 0.12.232+ # https://github.com/python-trio/trio/issues/637233+ self._event = trio.Event()234+235+236+class BackgroundManager(BaseBackgroundManager):237+ def __init__(self, coroutine: typing.Callable, *args: typing.Any) -> None:238+ self.coroutine = coroutine239+ self.args = args240+ self.nursery_manager = trio.open_nursery()241+ self.nursery: typing.Optional[trio.Nursery] = None242+243+ async def __aenter__(self) -> "BackgroundManager":244+ self.nursery = await self.nursery_manager.__aenter__()245+ self.nursery.start_soon(self.coroutine, *self.args)246+ return self247+248+ async def __aexit__(249+ self,250+ exc_type: typing.Type[BaseException] = None,251+ exc_value: BaseException = None,252+ traceback: TracebackType = None,253+ ) -> None:254+ assert self.nursery is not None255+ await self.nursery_manager.__aexit__(exc_type, exc_value, traceback)modified:httpx/dispatch/asgi.py+2 added-1 removed
128 unmodified lines129 130 await response_started_or_failed.wait()131 132 if app_exc is not None and self.raise_app_exceptions:133+ await background.close(app_exc)134 raise app_exc135 136 assert status_code is not None, "application did not return a response."137 assert headers is not None138 139 async def on_close() -> None:140 nonlocal response_body141 await response_body.drain()141- await background.__aexit__(None, None, None)142+ await background.close(app_exc)143 if app_exc is not None and self.raise_app_exceptions:144 raise app_exc145 146 return AsyncResponse(49 unmodified linesmodified:httpx/dispatch/http2.py+5 added
4 unmodified lines5 import h2.events6 7 from ..concurrency.base import BaseEvent, BaseTCPStream, ConcurrencyBackend, TimeoutFlag8 from ..config import TimeoutConfig, TimeoutTypes9+from ..exceptions import ProtocolError10 from ..models import AsyncRequest, AsyncResponse11 from ..utils import get_logger12 13 logger = get_logger(__name__)173 unmodified lines187 event_stream_id = getattr(event, "stream_id", 0)188 logger.debug(189 f"receive_event stream_id={event_stream_id} event={event!r}"190 )191+192+ if hasattr(event, "error_code"):193+ raise ProtocolError(event)194+195 if isinstance(event, h2.events.WindowUpdated):196 if event_stream_id == 0:197 for window_update_event in self.window_update_received.values():198 window_update_event.set()31 unmodified linesmodified:httpx/client.py+1 added-1 removed
79 unmodified lines80 assert param_count in (2, 3)81 if param_count == 2:82 dispatch = WSGIDispatch(app=app)83 else:84- dispatch = ASGIDispatch(app=app)84+ dispatch = ASGIDispatch(app=app, backend=backend)85 86 self.trust_env = True if trust_env is None else trust_env87 88 if dispatch is None:988 unmodified linesmodified:tests/dispatch/test_connection_pools.py+3 added-1 removed
166 unmodified lines167 """168 Verify that max_connections semaphore is released169 properly on a disconnected connection.170 """171- async with httpx.ConnectionPool(pool_limits=httpx.PoolLimits(hard_limit=1)) as http:171+ async with httpx.ConnectionPool(172+ pool_limits=httpx.PoolLimits(hard_limit=1), backend=backend173+ ) as http:174 response = await http.request("GET", server.url)175 await response.read()176 177 # Close the connection so we're forced to recycle it4 unmodified linesmodified:tests/concurrency.py+12 added
15 unmodified lines16 17 @sleep.register(AsyncioBackend)18 async def _sleep_asyncio(backend, seconds: int):19 await asyncio.sleep(seconds)20+21+22+try:23+ import trio24+ from httpx.concurrency.trio import TrioBackend25+except ImportError: # pragma: no cover26+ pass27+else:28+29+ @sleep.register(TrioBackend)30+ async def _sleep_trio(backend, seconds: int):31+ await trio.sleep(seconds)modified:tests/conftest.py+11 added-1 removed
45 unmodified lines46 os.environ.clear()47 os.environ.update(original_environ)48 49 50-@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])50+backend_params = [pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)]51+52+try:53+ from httpx.concurrency.trio import TrioBackend54+except ImportError: # pragma: no cover55+ pass56+else:57+ backend_params.append(pytest.param(TrioBackend, marks=pytest.mark.trio))58+59+60+@pytest.fixture(params=backend_params)61 def backend(request):62 backend_cls = request.param63 return backend_cls()64 230 unmodified linesmodified:tests/test_timeouts.py+1 added-1 removed
36 unmodified lines37 await client.get("http://10.255.255.1/")38 39 40 async def test_pool_timeout(server, backend):41- pool_limits = PoolLimits(hard_limit=1, pool_timeout=1e-6)41+ pool_limits = PoolLimits(hard_limit=1, pool_timeout=1e-4)42 43 async with AsyncClient(pool_limits=pool_limits, backend=backend) as client:44 response = await client.get(server.url, stream=True)45 4 unmodified linesmodified:setup.cfg+1 added-1 removed
9 unmodified lines10 combine_as_imports = True11 force_grid_wrap = 012 include_trailing_comma = True13 known_first_party = httpx,tests14-known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,nox,pytest,requests,rfc3986,setuptools,trustme,uvicorn14+known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,nox,pytest,requests,rfc3986,setuptools,trio,trustme,uvicorn15 line_length = 8816 multi_line_output = 317 18 [tool:pytest]3 unmodified linesmodified:setup.py+1 added
57 unmodified lines58 "hstspreload>=2019.8.27",59 "idna==2.*",60 "rfc3986==1.*",61 ],62+ extras_require={"trio": ["trio"]},63 classifiers=[64 "Development Status :: 3 - Alpha",65 "Environment :: Web Environment",66 "Intended Audience :: Developers",9 unmodified linesmodified:test-requirements.txt+2 added-1 removed
1--e .1+-e .[trio]2 3 # Optional4 brotlipy==0.7.*5 4 unmodified lines10 isort11 mypy12 pytest13 pytest-asyncio14+pytest-trio15 pytest-cov16 trustme17 uvicorn18 2 unmodified lines