Skip to content
Myr

Use Python 3.8 asyncio.Stream where possible (#369)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Jamie Hewland · committed by Seth Michael Larson · parent 6752f7d · Browse files · 5 files+413 added−300 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+413 added−300 removed

  • tests:+2 added−2 removed
  • other:+411 added−298 removed

5 files+413 added−300 removed

added:httpx/concurrency/asyncio/__init__.py+3 added
1from .backend import AsyncioBackend, BackgroundManager, PoolSemaphore, TCPStream23__all__ = ["AsyncioBackend", "BackgroundManager", "PoolSemaphore", "TCPStream"]
added:httpx/concurrency/asyncio/backend.py+271 added
1import asyncio2import functools3import ssl4import typing5from types import TracebackType67from httpx.config import PoolLimits, TimeoutConfig8from httpx.exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout910from ..base import (11 BaseBackgroundManager,12 BaseEvent,13 BasePoolSemaphore,14 BaseQueue,15 BaseTCPStream,16 ConcurrencyBackend,17 TimeoutFlag,18)19from .compat import Stream, connect_compat2021SSL_MONKEY_PATCH_APPLIED = False222324def ssl_monkey_patch() -> None:25 """26 Monkey-patch for https://bugs.python.org/issue367092728 This prevents console errors when outstanding HTTPS connections29 still exist at the point of exiting.3031 Clients which have been opened using a `with` block, or which have32 had `close()` closed, will not exhibit this issue in the first place.33 """34 MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignore3536 _write = MonkeyPatch.write3738 def _fixed_write(self, data: bytes) -> None: # type: ignore39 if self._loop and not self._loop.is_closed():40 _write(self, data)4142 MonkeyPatch.write = _fixed_write434445class TCPStream(BaseTCPStream):46 def __init__(self, stream: Stream, timeout: TimeoutConfig):47 self.stream = stream48 self.timeout = timeout4950 def get_http_version(self) -> str:51 ssl_object = self.stream.get_extra_info("ssl_object")5253 if ssl_object is None:54 return "HTTP/1.1"5556 ident = ssl_object.selected_alpn_protocol()5758 if ident is None:59 return "HTTP/1.1"6061 return "HTTP/2" if ident == "h2" else "HTTP/1.1"6263 async def read(64 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None65 ) -> bytes:66 if timeout is None:67 timeout = self.timeout6869 while True:70 # Check our flag at the first possible moment, and use a fine71 # grained retry loop if we're not yet in read-timeout mode.72 should_raise = flag is None or flag.raise_on_read_timeout73 read_timeout = timeout.read_timeout if should_raise else 0.0174 try:75 data = await asyncio.wait_for(self.stream.read(n), read_timeout)76 break77 except asyncio.TimeoutError:78 if should_raise:79 raise ReadTimeout() from None80 # FIX(py3.6): yield control back to the event loop to give it a chance81 # to cancel `.read(n)` before we retry.82 # This prevents concurrent `.read()` calls, which asyncio83 # doesn't seem to allow on 3.6.84 # See: https://github.com/encode/httpx/issues/38285 await asyncio.sleep(0)8687 return data8889 def write_no_block(self, data: bytes) -> None:90 self.stream.write(data) # pragma: nocover9192 async def write(93 self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None94 ) -> None:95 if not data:96 return9798 if timeout is None:99 timeout = self.timeout100101 self.stream.write(data)102 while True:103 try:104 await asyncio.wait_for( # type: ignore105 self.stream.drain(), timeout.write_timeout106 )107 break108 except asyncio.TimeoutError:109 # We check our flag at the first possible moment, in order to110 # allow us to suppress write timeouts, if we've since111 # switched over to read-timeout mode.112 should_raise = flag is None or flag.raise_on_write_timeout113 if should_raise:114 raise WriteTimeout() from None115116 def is_connection_dropped(self) -> bool:117 # Counter-intuitively, what we really want to know here is whether the socket is118 # *readable*, i.e. whether it would return immediately with empty bytes if we119 # called `.recv()` on it, indicating that the other end has closed the socket.120 # See: https://github.com/encode/httpx/pull/143#issuecomment-515181778121 #122 # As it turns out, asyncio checks for readability in the background123 # (see: https://github.com/encode/httpx/pull/276#discussion_r322000402),124 # so checking for EOF or readability here would yield the same result.125 #126 # At the cost of rigour, we check for EOF instead of readability because asyncio127 # does not expose any public API to check for readability.128 # (For a solution that uses private asyncio APIs, see:129 # https://github.com/encode/httpx/pull/143#issuecomment-515202982)130131 return self.stream.at_eof()132133 async def close(self) -> None:134 # FIXME: We should await on this call, but need a workaround for this first:135 # https://github.com/aio-libs/aiohttp/issues/3535136 self.stream.close()137138139class PoolSemaphore(BasePoolSemaphore):140 def __init__(self, pool_limits: PoolLimits):141 self.pool_limits = pool_limits142143 @property144 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:145 if not hasattr(self, "_semaphore"):146 max_connections = self.pool_limits.hard_limit147 if max_connections is None:148 self._semaphore = None149 else:150 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)151 return self._semaphore152153 async def acquire(self) -> None:154 if self.semaphore is None:155 return156157 timeout = self.pool_limits.pool_timeout158 try:159 await asyncio.wait_for(self.semaphore.acquire(), timeout)160 except asyncio.TimeoutError:161 raise PoolTimeout()162163 def release(self) -> None:164 if self.semaphore is None:165 return166167 self.semaphore.release()168169170class AsyncioBackend(ConcurrencyBackend):171 def __init__(self) -> None:172 global SSL_MONKEY_PATCH_APPLIED173174 if not SSL_MONKEY_PATCH_APPLIED:175 ssl_monkey_patch()176 SSL_MONKEY_PATCH_APPLIED = True177178 @property179 def loop(self) -> asyncio.AbstractEventLoop:180 if not hasattr(self, "_loop"):181 try:182 self._loop = asyncio.get_event_loop()183 except RuntimeError:184 self._loop = asyncio.new_event_loop()185 return self._loop186187 async def open_tcp_stream(188 self,189 hostname: str,190 port: int,191 ssl_context: typing.Optional[ssl.SSLContext],192 timeout: TimeoutConfig,193 ) -> BaseTCPStream:194 try:195 stream = await asyncio.wait_for( # type: ignore196 connect_compat(hostname, port, ssl=ssl_context), timeout.connect_timeout197 )198 except asyncio.TimeoutError:199 raise ConnectTimeout()200201 return TCPStream(stream=stream, timeout=timeout)202203 async def start_tls(204 self,205 stream: BaseTCPStream,206 hostname: str,207 ssl_context: ssl.SSLContext,208 timeout: TimeoutConfig,209 ) -> BaseTCPStream:210 assert isinstance(stream, TCPStream)211212 await asyncio.wait_for(213 stream.stream.start_tls(ssl_context, server_hostname=hostname),214 timeout=timeout.connect_timeout,215 )216217 return stream218219 async def run_in_threadpool(220 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any221 ) -> typing.Any:222 if kwargs:223 # loop.run_in_executor doesn't accept 'kwargs', so bind them in here224 func = functools.partial(func, **kwargs)225 return await self.loop.run_in_executor(None, func, *args)226227 def run(228 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any229 ) -> typing.Any:230 loop = self.loop231 if loop.is_running():232 self._loop = asyncio.new_event_loop()233 try:234 return self.loop.run_until_complete(coroutine(*args, **kwargs))235 finally:236 self._loop = loop237238 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:239 return PoolSemaphore(limits)240241 def create_queue(self, max_size: int) -> BaseQueue:242 return typing.cast(BaseQueue, asyncio.Queue(maxsize=max_size))243244 def create_event(self) -> BaseEvent:245 return typing.cast(BaseEvent, asyncio.Event())246247 def background_manager(248 self, coroutine: typing.Callable, *args: typing.Any249 ) -> "BackgroundManager":250 return BackgroundManager(coroutine, args)251252253class BackgroundManager(BaseBackgroundManager):254 def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:255 self.coroutine = coroutine256 self.args = args257258 async def __aenter__(self) -> "BackgroundManager":259 loop = asyncio.get_event_loop()260 self.task = loop.create_task(self.coroutine(*self.args))261 return self262263 async def __aexit__(264 self,265 exc_type: typing.Type[BaseException] = None,266 exc_value: BaseException = None,267 traceback: TracebackType = None,268 ) -> None:269 await self.task270 if exc_type is None:271 self.task.result()
added:httpx/concurrency/asyncio/compat.py+137 added
1import asyncio2import ssl3import sys4import typing56if sys.version_info >= (3, 8):7 from typing import Protocol8else:9 from typing_extensions import Protocol101112class Stream(Protocol): # pragma: no cover13 """Protocol defining just the methods we use from asyncio.Stream."""1415 def at_eof(self) -> bool:16 ...1718 def close(self) -> typing.Awaitable[None]:19 ...2021 async def drain(self) -> None:22 ...2324 def get_extra_info(self, name: str, default: typing.Any = None) -> typing.Any:25 ...2627 async def read(self, n: int = -1) -> bytes:28 ...2930 async def start_tls(31 self,32 sslContext: ssl.SSLContext,33 *,34 server_hostname: typing.Optional[str] = None,35 ssl_handshake_timeout: typing.Optional[float] = None,36 ) -> None:37 ...3839 def write(self, data: bytes) -> typing.Awaitable[None]:40 ...414243async def connect_compat(*args: typing.Any, **kwargs: typing.Any) -> Stream:44 if sys.version_info >= (3, 8):45 return await asyncio.connect(*args, **kwargs)46 else:47 reader, writer = await asyncio.open_connection(*args, **kwargs)48 return StreamCompat(reader, writer)495051class StreamCompat:52 """53 Thin wrapper around asyncio.StreamReader/StreamWriter to make them look and54 behave similarly to an asyncio.Stream.55 """5657 def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):58 self.reader = reader59 self.writer = writer6061 def at_eof(self) -> bool:62 return self.reader.at_eof()6364 def close(self) -> typing.Awaitable[None]:65 self.writer.close()66 return _OptionalAwait(self.wait_closed)6768 async def drain(self) -> None:69 await self.writer.drain()7071 def get_extra_info(self, name: str, default: typing.Any = None) -> typing.Any:72 return self.writer.get_extra_info(name, default)7374 async def read(self, n: int = -1) -> bytes:75 return await self.reader.read(n)7677 async def start_tls(78 self,79 sslContext: ssl.SSLContext,80 *,81 server_hostname: typing.Optional[str] = None,82 ssl_handshake_timeout: typing.Optional[float] = None,83 ) -> None:84 if not sys.version_info >= (3, 7): # pragma: no cover85 raise NotImplementedError(86 "asyncio.AbstractEventLoop.start_tls() is only available in Python 3.7+"87 )88 else:89 # This code is in an else branch to appease mypy on Python < 3.79091 reader = asyncio.StreamReader()92 protocol = asyncio.StreamReaderProtocol(reader)93 transport = self.writer.transport9495 loop = asyncio.get_event_loop()96 loop_start_tls = loop.start_tls # type: ignore97 tls_transport = await loop_start_tls(98 transport=transport,99 protocol=protocol,100 sslcontext=sslContext,101 server_hostname=server_hostname,102 ssl_handshake_timeout=ssl_handshake_timeout,103 )104105 reader.set_transport(tls_transport)106 self.reader = reader107 self.writer = asyncio.StreamWriter(108 transport=tls_transport, protocol=protocol, reader=reader, loop=loop109 )110111 def write(self, data: bytes) -> typing.Awaitable[None]:112 self.writer.write(data)113 return _OptionalAwait(self.drain)114115 async def wait_closed(self) -> None:116 if sys.version_info >= (3, 7):117 await self.writer.wait_closed()118 # else not much we can do to wait for the connection to close119120121# This code is copied from cPython 3.8 but with type annotations added:122# https://github.com/python/cpython/blob/v3.8.0b4/Lib/asyncio/streams.py#L1262-L1273123_T = typing.TypeVar("_T")124125126class _OptionalAwait(typing.Generic[_T]):127 # The class doesn't create a coroutine128 # if not awaited129 # It prevents "coroutine is never awaited" message130131 __slots___ = ("_method",)132133 def __init__(self, method: typing.Callable[[], typing.Awaitable[_T]]):134 self._method = method135136 def __await__(self) -> typing.Generator[typing.Any, None, _T]:137 return self._method().__await__()
deleted:httpx/concurrency/asyncio.py-298 removed
1import asyncio2import functools3import ssl4import typing5from types import TracebackType67from ..config import PoolLimits, TimeoutConfig8from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9from .base import (10 BaseBackgroundManager,11 BaseEvent,12 BasePoolSemaphore,13 BaseQueue,14 BaseTCPStream,15 ConcurrencyBackend,16 TimeoutFlag,17)1819SSL_MONKEY_PATCH_APPLIED = False202122def ssl_monkey_patch() -> None:23 """24 Monkey-patch for https://bugs.python.org/issue367092526 This prevents console errors when outstanding HTTPS connections27 still exist at the point of exiting.2829 Clients which have been opened using a `with` block, or which have30 had `close()` closed, will not exhibit this issue in the first place.31 """32 MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignore3334 _write = MonkeyPatch.write3536 def _fixed_write(self, data: bytes) -> None: # type: ignore37 if self._loop and not self._loop.is_closed():38 _write(self, data)3940 MonkeyPatch.write = _fixed_write414243class TCPStream(BaseTCPStream):44 def __init__(45 self,46 stream_reader: asyncio.StreamReader,47 stream_writer: asyncio.StreamWriter,48 timeout: TimeoutConfig,49 ):50 self.stream_reader = stream_reader51 self.stream_writer = stream_writer52 self.timeout = timeout5354 def get_http_version(self) -> str:55 ssl_object = self.stream_writer.get_extra_info("ssl_object")5657 if ssl_object is None:58 return "HTTP/1.1"5960 ident = ssl_object.selected_alpn_protocol()6162 if ident is None:63 return "HTTP/1.1"6465 return "HTTP/2" if ident == "h2" else "HTTP/1.1"6667 async def read(68 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None69 ) -> bytes:70 if timeout is None:71 timeout = self.timeout7273 while True:74 # Check our flag at the first possible moment, and use a fine75 # grained retry loop if we're not yet in read-timeout mode.76 should_raise = flag is None or flag.raise_on_read_timeout77 read_timeout = timeout.read_timeout if should_raise else 0.0178 try:79 data = await asyncio.wait_for(self.stream_reader.read(n), read_timeout)80 break81 except asyncio.TimeoutError:82 if should_raise:83 raise ReadTimeout() from None84 # FIX(py3.6): yield control back to the event loop to give it a chance85 # to cancel `.read(n)` before we retry.86 # This prevents concurrent `.read()` calls, which asyncio87 # doesn't seem to allow on 3.6.88 # See: https://github.com/encode/httpx/issues/38289 await asyncio.sleep(0)9091 return data9293 def write_no_block(self, data: bytes) -> None:94 self.stream_writer.write(data) # pragma: nocover9596 async def write(97 self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None98 ) -> None:99 if not data:100 return101102 if timeout is None:103 timeout = self.timeout104105 self.stream_writer.write(data)106 while True:107 try:108 await asyncio.wait_for( # type: ignore109 self.stream_writer.drain(), timeout.write_timeout110 )111 break112 except asyncio.TimeoutError:113 # We check our flag at the first possible moment, in order to114 # allow us to suppress write timeouts, if we've since115 # switched over to read-timeout mode.116 should_raise = flag is None or flag.raise_on_write_timeout117 if should_raise:118 raise WriteTimeout() from None119120 def is_connection_dropped(self) -> bool:121 # Counter-intuitively, what we really want to know here is whether the socket is122 # *readable*, i.e. whether it would return immediately with empty bytes if we123 # called `.recv()` on it, indicating that the other end has closed the socket.124 # See: https://github.com/encode/httpx/pull/143#issuecomment-515181778125 #126 # As it turns out, asyncio checks for readability in the background127 # (see: https://github.com/encode/httpx/pull/276#discussion_r322000402),128 # so checking for EOF or readability here would yield the same result.129 #130 # At the cost of rigour, we check for EOF instead of readability because asyncio131 # does not expose any public API to check for readability.132 # (For a solution that uses private asyncio APIs, see:133 # https://github.com/encode/httpx/pull/143#issuecomment-515202982)134135 return self.stream_reader.at_eof()136137 async def close(self) -> None:138 self.stream_writer.close()139140141class PoolSemaphore(BasePoolSemaphore):142 def __init__(self, pool_limits: PoolLimits):143 self.pool_limits = pool_limits144145 @property146 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:147 if not hasattr(self, "_semaphore"):148 max_connections = self.pool_limits.hard_limit149 if max_connections is None:150 self._semaphore = None151 else:152 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)153 return self._semaphore154155 async def acquire(self) -> None:156 if self.semaphore is None:157 return158159 timeout = self.pool_limits.pool_timeout160 try:161 await asyncio.wait_for(self.semaphore.acquire(), timeout)162 except asyncio.TimeoutError:163 raise PoolTimeout()164165 def release(self) -> None:166 if self.semaphore is None:167 return168169 self.semaphore.release()170171172class AsyncioBackend(ConcurrencyBackend):173 def __init__(self) -> None:174 global SSL_MONKEY_PATCH_APPLIED175176 if not SSL_MONKEY_PATCH_APPLIED:177 ssl_monkey_patch()178 SSL_MONKEY_PATCH_APPLIED = True179180 @property181 def loop(self) -> asyncio.AbstractEventLoop:182 if not hasattr(self, "_loop"):183 try:184 self._loop = asyncio.get_event_loop()185 except RuntimeError:186 self._loop = asyncio.new_event_loop()187 return self._loop188189 async def open_tcp_stream(190 self,191 hostname: str,192 port: int,193 ssl_context: typing.Optional[ssl.SSLContext],194 timeout: TimeoutConfig,195 ) -> BaseTCPStream:196 try:197 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore198 asyncio.open_connection(hostname, port, ssl=ssl_context),199 timeout.connect_timeout,200 )201 except asyncio.TimeoutError:202 raise ConnectTimeout()203204 return TCPStream(205 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout206 )207208 async def start_tls(209 self,210 stream: BaseTCPStream,211 hostname: str,212 ssl_context: ssl.SSLContext,213 timeout: TimeoutConfig,214 ) -> BaseTCPStream:215216 loop = self.loop217 if not hasattr(loop, "start_tls"): # pragma: no cover218 raise NotImplementedError(219 "asyncio.AbstractEventLoop.start_tls() is only available in Python 3.7+"220 )221222 assert isinstance(stream, TCPStream)223224 stream_reader = asyncio.StreamReader()225 protocol = asyncio.StreamReaderProtocol(stream_reader)226 transport = stream.stream_writer.transport227228 loop_start_tls = loop.start_tls # type: ignore229 transport = await asyncio.wait_for(230 loop_start_tls(231 transport=transport,232 protocol=protocol,233 sslcontext=ssl_context,234 server_hostname=hostname,235 ),236 timeout=timeout.connect_timeout,237 )238239 stream_reader.set_transport(transport)240 stream.stream_reader = stream_reader241 stream.stream_writer = asyncio.StreamWriter(242 transport=transport, protocol=protocol, reader=stream_reader, loop=loop243 )244 return stream245246 async def run_in_threadpool(247 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any248 ) -> typing.Any:249 if kwargs:250 # loop.run_in_executor doesn't accept 'kwargs', so bind them in here251 func = functools.partial(func, **kwargs)252 return await self.loop.run_in_executor(None, func, *args)253254 def run(255 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any256 ) -> typing.Any:257 loop = self.loop258 if loop.is_running():259 self._loop = asyncio.new_event_loop()260 try:261 return self.loop.run_until_complete(coroutine(*args, **kwargs))262 finally:263 self._loop = loop264265 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:266 return PoolSemaphore(limits)267268 def create_queue(self, max_size: int) -> BaseQueue:269 return typing.cast(BaseQueue, asyncio.Queue(maxsize=max_size))270271 def create_event(self) -> BaseEvent:272 return typing.cast(BaseEvent, asyncio.Event())273274 def background_manager(275 self, coroutine: typing.Callable, *args: typing.Any276 ) -> "BackgroundManager":277 return BackgroundManager(coroutine, args)278279280class BackgroundManager(BaseBackgroundManager):281 def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:282 self.coroutine = coroutine283 self.args = args284285 async def __aenter__(self) -> "BackgroundManager":286 loop = asyncio.get_event_loop()287 self.task = loop.create_task(self.coroutine(*self.args))288 return self289290 async def __aexit__(291 self,292 exc_type: typing.Type[BaseException] = None,293 exc_value: BaseException = None,294 traceback: TracebackType = None,295 ) -> None:296 await self.task297 if exc_type is None:298 self.task.result()
modified:tests/test_concurrency.py+2 added-2 removed
23 unmodified lines
24 )2526 try:27 assert stream.is_connection_dropped() is False28 assert stream.stream_writer.get_extra_info("cipher", default=None) is None28 assert stream.stream.get_extra_info("cipher", default=None) is None2930 stream = await backend.start_tls(stream, https_server.url.host, ctx, timeout)31 assert stream.is_connection_dropped() is False32 assert stream.stream_writer.get_extra_info("cipher", default=None) is not None32 assert stream.stream.get_extra_info("cipher", default=None) is not None3334 await stream.write(b"GET / HTTP/1.1\r\n\r\n")35 assert (await stream.read(8192, timeout)).startswith(b"HTTP/1.1 200 OK\r\n")36
2 unmodified lines