Skip to content
Myr

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

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

This reverts commit 71cbde8ba4cab32dd96ccb91e9db20216587fae9.

authored by Josep Cugat · committed by Tom Christie · parent b65bce5 · Browse files · 5 files+296 added−409 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+296 added−409 removed

  • tests:+2 added−2 removed
  • other:+294 added−407 removed

5 files+296 added−409 removed

deleted:httpx/concurrency/asyncio/__init__.py-3 removed
1from .backend import AsyncioBackend, BackgroundManager, PoolSemaphore, TCPStream23__all__ = ["AsyncioBackend", "BackgroundManager", "PoolSemaphore", "TCPStream"]
deleted:httpx/concurrency/asyncio/backend.py-267 removed
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()57 return "HTTP/2" if ident == "h2" else "HTTP/1.1"5859 async def read(60 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None61 ) -> bytes:62 if timeout is None:63 timeout = self.timeout6465 while True:66 # Check our flag at the first possible moment, and use a fine67 # grained retry loop if we're not yet in read-timeout mode.68 should_raise = flag is None or flag.raise_on_read_timeout69 read_timeout = timeout.read_timeout if should_raise else 0.0170 try:71 data = await asyncio.wait_for(self.stream.read(n), read_timeout)72 break73 except asyncio.TimeoutError:74 if should_raise:75 raise ReadTimeout() from None76 # FIX(py3.6): yield control back to the event loop to give it a chance77 # to cancel `.read(n)` before we retry.78 # This prevents concurrent `.read()` calls, which asyncio79 # doesn't seem to allow on 3.6.80 # See: https://github.com/encode/httpx/issues/38281 await asyncio.sleep(0)8283 return data8485 def write_no_block(self, data: bytes) -> None:86 self.stream.write(data) # pragma: nocover8788 async def write(89 self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None90 ) -> None:91 if not data:92 return9394 if timeout is None:95 timeout = self.timeout9697 self.stream.write(data)98 while True:99 try:100 await asyncio.wait_for( # type: ignore101 self.stream.drain(), timeout.write_timeout102 )103 break104 except asyncio.TimeoutError:105 # We check our flag at the first possible moment, in order to106 # allow us to suppress write timeouts, if we've since107 # switched over to read-timeout mode.108 should_raise = flag is None or flag.raise_on_write_timeout109 if should_raise:110 raise WriteTimeout() from None111112 def is_connection_dropped(self) -> bool:113 # Counter-intuitively, what we really want to know here is whether the socket is114 # *readable*, i.e. whether it would return immediately with empty bytes if we115 # called `.recv()` on it, indicating that the other end has closed the socket.116 # See: https://github.com/encode/httpx/pull/143#issuecomment-515181778117 #118 # As it turns out, asyncio checks for readability in the background119 # (see: https://github.com/encode/httpx/pull/276#discussion_r322000402),120 # so checking for EOF or readability here would yield the same result.121 #122 # At the cost of rigour, we check for EOF instead of readability because asyncio123 # does not expose any public API to check for readability.124 # (For a solution that uses private asyncio APIs, see:125 # https://github.com/encode/httpx/pull/143#issuecomment-515202982)126127 return self.stream.at_eof()128129 async def close(self) -> None:130 # FIXME: We should await on this call, but need a workaround for this first:131 # https://github.com/aio-libs/aiohttp/issues/3535132 self.stream.close()133134135class PoolSemaphore(BasePoolSemaphore):136 def __init__(self, pool_limits: PoolLimits):137 self.pool_limits = pool_limits138139 @property140 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:141 if not hasattr(self, "_semaphore"):142 max_connections = self.pool_limits.hard_limit143 if max_connections is None:144 self._semaphore = None145 else:146 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)147 return self._semaphore148149 async def acquire(self) -> None:150 if self.semaphore is None:151 return152153 timeout = self.pool_limits.pool_timeout154 try:155 await asyncio.wait_for(self.semaphore.acquire(), timeout)156 except asyncio.TimeoutError:157 raise PoolTimeout()158159 def release(self) -> None:160 if self.semaphore is None:161 return162163 self.semaphore.release()164165166class AsyncioBackend(ConcurrencyBackend):167 def __init__(self) -> None:168 global SSL_MONKEY_PATCH_APPLIED169170 if not SSL_MONKEY_PATCH_APPLIED:171 ssl_monkey_patch()172 SSL_MONKEY_PATCH_APPLIED = True173174 @property175 def loop(self) -> asyncio.AbstractEventLoop:176 if not hasattr(self, "_loop"):177 try:178 self._loop = asyncio.get_event_loop()179 except RuntimeError:180 self._loop = asyncio.new_event_loop()181 return self._loop182183 async def open_tcp_stream(184 self,185 hostname: str,186 port: int,187 ssl_context: typing.Optional[ssl.SSLContext],188 timeout: TimeoutConfig,189 ) -> BaseTCPStream:190 try:191 stream = await asyncio.wait_for( # type: ignore192 connect_compat(hostname, port, ssl=ssl_context), timeout.connect_timeout193 )194 except asyncio.TimeoutError:195 raise ConnectTimeout()196197 return TCPStream(stream=stream, timeout=timeout)198199 async def start_tls(200 self,201 stream: BaseTCPStream,202 hostname: str,203 ssl_context: ssl.SSLContext,204 timeout: TimeoutConfig,205 ) -> BaseTCPStream:206 assert isinstance(stream, TCPStream)207208 await asyncio.wait_for(209 stream.stream.start_tls(ssl_context, server_hostname=hostname),210 timeout=timeout.connect_timeout,211 )212213 return stream214215 async def run_in_threadpool(216 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any217 ) -> typing.Any:218 if kwargs:219 # loop.run_in_executor doesn't accept 'kwargs', so bind them in here220 func = functools.partial(func, **kwargs)221 return await self.loop.run_in_executor(None, func, *args)222223 def run(224 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any225 ) -> typing.Any:226 loop = self.loop227 if loop.is_running():228 self._loop = asyncio.new_event_loop()229 try:230 return self.loop.run_until_complete(coroutine(*args, **kwargs))231 finally:232 self._loop = loop233234 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:235 return PoolSemaphore(limits)236237 def create_queue(self, max_size: int) -> BaseQueue:238 return typing.cast(BaseQueue, asyncio.Queue(maxsize=max_size))239240 def create_event(self) -> BaseEvent:241 return typing.cast(BaseEvent, asyncio.Event())242243 def background_manager(244 self, coroutine: typing.Callable, *args: typing.Any245 ) -> "BackgroundManager":246 return BackgroundManager(coroutine, args)247248249class BackgroundManager(BaseBackgroundManager):250 def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:251 self.coroutine = coroutine252 self.args = args253254 async def __aenter__(self) -> "BackgroundManager":255 loop = asyncio.get_event_loop()256 self.task = loop.create_task(self.coroutine(*self.args))257 return self258259 async def __aexit__(260 self,261 exc_type: typing.Type[BaseException] = None,262 exc_value: BaseException = None,263 traceback: TracebackType = None,264 ) -> None:265 await self.task266 if exc_type is None:267 self.task.result()
deleted:httpx/concurrency/asyncio/compat.py-137 removed
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__()
added:httpx/concurrency/asyncio.py+294 added
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()61 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_reader.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_writer.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_writer.write(data)102 while True:103 try:104 await asyncio.wait_for( # type: ignore105 self.stream_writer.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_reader.at_eof()132133 async def close(self) -> None:134 self.stream_writer.close()135136137class PoolSemaphore(BasePoolSemaphore):138 def __init__(self, pool_limits: PoolLimits):139 self.pool_limits = pool_limits140141 @property142 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:143 if not hasattr(self, "_semaphore"):144 max_connections = self.pool_limits.hard_limit145 if max_connections is None:146 self._semaphore = None147 else:148 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)149 return self._semaphore150151 async def acquire(self) -> None:152 if self.semaphore is None:153 return154155 timeout = self.pool_limits.pool_timeout156 try:157 await asyncio.wait_for(self.semaphore.acquire(), timeout)158 except asyncio.TimeoutError:159 raise PoolTimeout()160161 def release(self) -> None:162 if self.semaphore is None:163 return164165 self.semaphore.release()166167168class AsyncioBackend(ConcurrencyBackend):169 def __init__(self) -> None:170 global SSL_MONKEY_PATCH_APPLIED171172 if not SSL_MONKEY_PATCH_APPLIED:173 ssl_monkey_patch()174 SSL_MONKEY_PATCH_APPLIED = True175176 @property177 def loop(self) -> asyncio.AbstractEventLoop:178 if not hasattr(self, "_loop"):179 try:180 self._loop = asyncio.get_event_loop()181 except RuntimeError:182 self._loop = asyncio.new_event_loop()183 return self._loop184185 async def open_tcp_stream(186 self,187 hostname: str,188 port: int,189 ssl_context: typing.Optional[ssl.SSLContext],190 timeout: TimeoutConfig,191 ) -> BaseTCPStream:192 try:193 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore194 asyncio.open_connection(hostname, port, ssl=ssl_context),195 timeout.connect_timeout,196 )197 except asyncio.TimeoutError:198 raise ConnectTimeout()199200 return TCPStream(201 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout202 )203204 async def start_tls(205 self,206 stream: BaseTCPStream,207 hostname: str,208 ssl_context: ssl.SSLContext,209 timeout: TimeoutConfig,210 ) -> BaseTCPStream:211212 loop = self.loop213 if not hasattr(loop, "start_tls"): # pragma: no cover214 raise NotImplementedError(215 "asyncio.AbstractEventLoop.start_tls() is only available in Python 3.7+"216 )217218 assert isinstance(stream, TCPStream)219220 stream_reader = asyncio.StreamReader()221 protocol = asyncio.StreamReaderProtocol(stream_reader)222 transport = stream.stream_writer.transport223224 loop_start_tls = loop.start_tls # type: ignore225 transport = await asyncio.wait_for(226 loop_start_tls(227 transport=transport,228 protocol=protocol,229 sslcontext=ssl_context,230 server_hostname=hostname,231 ),232 timeout=timeout.connect_timeout,233 )234235 stream_reader.set_transport(transport)236 stream.stream_reader = stream_reader237 stream.stream_writer = asyncio.StreamWriter(238 transport=transport, protocol=protocol, reader=stream_reader, loop=loop239 )240 return stream241242 async def run_in_threadpool(243 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any244 ) -> typing.Any:245 if kwargs:246 # loop.run_in_executor doesn't accept 'kwargs', so bind them in here247 func = functools.partial(func, **kwargs)248 return await self.loop.run_in_executor(None, func, *args)249250 def run(251 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any252 ) -> typing.Any:253 loop = self.loop254 if loop.is_running():255 self._loop = asyncio.new_event_loop()256 try:257 return self.loop.run_until_complete(coroutine(*args, **kwargs))258 finally:259 self._loop = loop260261 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:262 return PoolSemaphore(limits)263264 def create_queue(self, max_size: int) -> BaseQueue:265 return typing.cast(BaseQueue, asyncio.Queue(maxsize=max_size))266267 def create_event(self) -> BaseEvent:268 return typing.cast(BaseEvent, asyncio.Event())269270 def background_manager(271 self, coroutine: typing.Callable, *args: typing.Any272 ) -> "BackgroundManager":273 return BackgroundManager(coroutine, args)274275276class BackgroundManager(BaseBackgroundManager):277 def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:278 self.coroutine = coroutine279 self.args = args280281 async def __aenter__(self) -> "BackgroundManager":282 loop = asyncio.get_event_loop()283 self.task = loop.create_task(self.coroutine(*self.args))284 return self285286 async def __aexit__(287 self,288 exc_type: typing.Type[BaseException] = None,289 exc_value: BaseException = None,290 traceback: TracebackType = None,291 ) -> None:292 await self.task293 if exc_type is None:294 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.get_extra_info("cipher", default=None) is None28 assert stream.stream_writer.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.get_extra_info("cipher", default=None) is not None32 assert stream.stream_writer.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