Skip to content
Myr

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

13 files+315 added−7 removed

modified:httpx/concurrency/asyncio.py+14 added
110 unmodified lines
111 if should_raise:112 raise WriteTimeout() from None113114 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)128129 return self.stream_reader.at_eof()130131 async def close(self) -> None:132 self.stream_writer.close()
160 unmodified lines
modified:httpx/concurrency/base.py+7 added
185 unmodified lines
186 exc_value: BaseException = None,187 traceback: TracebackType = None,188 ) -> None:189 raise NotImplementedError() # pragma: no cover190191 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
1import functools2import math3import ssl4import typing5from types import TracebackType67import trio89from ..config import PoolLimits, TimeoutConfig10from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout11from .base import (12 BaseBackgroundManager,13 BaseEvent,14 BasePoolSemaphore,15 BaseQueue,16 BaseTCPStream,17 ConcurrencyBackend,18 TimeoutFlag,19)202122def _or_inf(value: typing.Optional[float]) -> float:23 return value if value is not None else float("inf")242526class 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()3637 def get_http_version(self) -> str:38 if not isinstance(self.stream, trio.SSLStream):39 return "HTTP/1.1"4041 ident = self.stream.selected_alpn_protocol()42 if ident is None:43 return "HTTP/1.1"4445 return "HTTP/2" if ident == "h2" else "HTTP/1.1"4647 async def read(48 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None49 ) -> bytes:50 if timeout is None:51 timeout = self.timeout5253 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)5859 with trio.move_on_after(read_timeout):60 return await self.stream.receive_some(max_bytes=n)6162 if should_raise:63 raise ReadTimeout() from None6465 def is_connection_dropped(self) -> bool:66 # Adapted from: https://github.com/encode/httpx/pull/143#issuecomment-51520298267 stream = self.stream6869 # 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)7374 # 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()7980 def write_no_block(self, data: bytes) -> None:81 self.write_buffer += data8283 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 raise9697 if not data:98 return99100 if timeout is None:101 timeout = self.timeout102103 write_timeout = _or_inf(timeout.write_timeout)104105 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 None116117 async def close(self) -> None:118 await self.stream.aclose()119120121class PoolSemaphore(BasePoolSemaphore):122 def __init__(self, pool_limits: PoolLimits):123 self.pool_limits = pool_limits124125 @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._semaphore136137 async def acquire(self) -> None:138 if self.semaphore is None:139 return140141 timeout = _or_inf(self.pool_limits.pool_timeout)142143 with trio.move_on_after(timeout):144 await self.semaphore.acquire()145 return146147 raise PoolTimeout()148149 def release(self) -> None:150 if self.semaphore is None:151 return152153 self.semaphore.release()154155156class 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)165166 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()171172 if cancel_scope.cancelled_caught:173 raise ConnectTimeout()174175 return TCPStream(stream=stream, timeout=timeout)176177 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 )183184 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 )190191 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:192 return PoolSemaphore(limits)193194 def create_queue(self, max_size: int) -> BaseQueue:195 return Queue(max_size=max_size)196197 def create_event(self) -> BaseEvent:198 return Event()199200 def background_manager(201 self, coroutine: typing.Callable, *args: typing.Any202 ) -> "BackgroundManager":203 return BackgroundManager(coroutine, *args)204205206class Queue(BaseQueue):207 def __init__(self, max_size: int) -> None:208 self.send_channel, self.receive_channel = trio.open_memory_channel(math.inf)209210 async def get(self) -> typing.Any:211 return await self.receive_channel.receive()212213 async def put(self, value: typing.Any) -> None:214 await self.send_channel.send(value)215216217class Event(BaseEvent):218 def __init__(self) -> None:219 self._event = trio.Event()220221 def set(self) -> None:222 self._event.set()223224 def is_set(self) -> bool:225 return self._event.is_set()226227 async def wait(self) -> None:228 await self._event.wait()229230 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()234235236class 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] = None242243 async def __aenter__(self) -> "BackgroundManager":244 self.nursery = await self.nursery_manager.__aenter__()245 self.nursery.start_soon(self.coroutine, *self.args)246 return self247248 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 lines
129130 await response_started_or_failed.wait()131132 if app_exc is not None and self.raise_app_exceptions:133 await background.close(app_exc)134 raise app_exc135136 assert status_code is not None, "application did not return a response."137 assert headers is not None138139 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_exc145146 return AsyncResponse(
49 unmodified lines
modified:httpx/dispatch/http2.py+5 added
4 unmodified lines
5import h2.events67from ..concurrency.base import BaseEvent, BaseTCPStream, ConcurrencyBackend, TimeoutFlag8from ..config import TimeoutConfig, TimeoutTypes9from ..exceptions import ProtocolError10from ..models import AsyncRequest, AsyncResponse11from ..utils import get_logger1213logger = get_logger(__name__)
173 unmodified lines
187 event_stream_id = getattr(event, "stream_id", 0)188 logger.debug(189 f"receive_event stream_id={event_stream_id} event={event!r}"190 )191192 if hasattr(event, "error_code"):193 raise ProtocolError(event)194195 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 lines
modified:httpx/client.py+1 added-1 removed
79 unmodified lines
80 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)8586 self.trust_env = True if trust_env is None else trust_env8788 if dispatch is None:
988 unmodified lines
modified:tests/dispatch/test_connection_pools.py+3 added-1 removed
166 unmodified lines
167 """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()176177 # Close the connection so we're forced to recycle it
4 unmodified lines
modified:tests/concurrency.py+12 added
15 unmodified lines
1617@sleep.register(AsyncioBackend)18async def _sleep_asyncio(backend, seconds: int):19 await asyncio.sleep(seconds)202122try:23 import trio24 from httpx.concurrency.trio import TrioBackend25except ImportError: # pragma: no cover26 pass27else:2829 @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 lines
46 os.environ.clear()47 os.environ.update(original_environ)484950@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])50backend_params = [pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)]5152try:53 from httpx.concurrency.trio import TrioBackend54except ImportError: # pragma: no cover55 pass56else:57 backend_params.append(pytest.param(TrioBackend, marks=pytest.mark.trio))585960@pytest.fixture(params=backend_params)61def backend(request):62 backend_cls = request.param63 return backend_cls()64
230 unmodified lines
modified:tests/test_timeouts.py+1 added-1 removed
36 unmodified lines
37 await client.get("http://10.255.255.1/")383940async 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)4243 async with AsyncClient(pool_limits=pool_limits, backend=backend) as client:44 response = await client.get(server.url, stream=True)45
4 unmodified lines
modified:setup.cfg+1 added-1 removed
9 unmodified lines
10combine_as_imports = True11force_grid_wrap = 012include_trailing_comma = True13known_first_party = httpx,tests14known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,nox,pytest,requests,rfc3986,setuptools,trustme,uvicorn14known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,nox,pytest,requests,rfc3986,setuptools,trio,trustme,uvicorn15line_length = 8816multi_line_output = 31718[tool:pytest]
3 unmodified lines
modified:setup.py+1 added
57 unmodified lines
58 "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 lines
modified:test-requirements.txt+2 added-1 removed
1-e .1-e .[trio]23# Optional4brotlipy==0.7.*5
4 unmodified lines
10isort11mypy12pytest13pytest-asyncio14pytest-trio15pytest-cov16trustme17uvicorn18
2 unmodified lines