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
Provenance
- Commit
86a0eb0- Tree
d0b3f99- Author
Josep Cugat <jcugat@gmail.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
b65bce5
5 files changed+296 added−409 removed
deleted:httpx/concurrency/asyncio/__init__.py-3 removed
1-from .backend import AsyncioBackend, BackgroundManager, PoolSemaphore, TCPStream2-3-__all__ = ["AsyncioBackend", "BackgroundManager", "PoolSemaphore", "TCPStream"]deleted:httpx/concurrency/asyncio/backend.py-267 removed
1-import asyncio2-import functools3-import ssl4-import typing5-from types import TracebackType6-7-from httpx.config import PoolLimits, TimeoutConfig8-from httpx.exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9-10-from ..base import (11- BaseBackgroundManager,12- BaseEvent,13- BasePoolSemaphore,14- BaseQueue,15- BaseTCPStream,16- ConcurrencyBackend,17- TimeoutFlag,18-)19-from .compat import Stream, connect_compat20-21-SSL_MONKEY_PATCH_APPLIED = False22-23-24-def ssl_monkey_patch() -> None:25- """26- Monkey-patch for https://bugs.python.org/issue3670927-28- This prevents console errors when outstanding HTTPS connections29- still exist at the point of exiting.30-31- 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: ignore35-36- _write = MonkeyPatch.write37-38- def _fixed_write(self, data: bytes) -> None: # type: ignore39- if self._loop and not self._loop.is_closed():40- _write(self, data)41-42- MonkeyPatch.write = _fixed_write43-44-45-class TCPStream(BaseTCPStream):46- def __init__(self, stream: Stream, timeout: TimeoutConfig):47- self.stream = stream48- self.timeout = timeout49-50- def get_http_version(self) -> str:51- ssl_object = self.stream.get_extra_info("ssl_object")52-53- if ssl_object is None:54- return "HTTP/1.1"55-56- ident = ssl_object.selected_alpn_protocol()57- return "HTTP/2" if ident == "h2" else "HTTP/1.1"58-59- async def read(60- self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None61- ) -> bytes:62- if timeout is None:63- timeout = self.timeout64-65- 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)82-83- return data84-85- def write_no_block(self, data: bytes) -> None:86- self.stream.write(data) # pragma: nocover87-88- async def write(89- self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None90- ) -> None:91- if not data:92- return93-94- if timeout is None:95- timeout = self.timeout96-97- 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 None111-112- 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)126-127- return self.stream.at_eof()128-129- 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()133-134-135-class PoolSemaphore(BasePoolSemaphore):136- def __init__(self, pool_limits: PoolLimits):137- self.pool_limits = pool_limits138-139- @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._semaphore148-149- async def acquire(self) -> None:150- if self.semaphore is None:151- return152-153- timeout = self.pool_limits.pool_timeout154- try:155- await asyncio.wait_for(self.semaphore.acquire(), timeout)156- except asyncio.TimeoutError:157- raise PoolTimeout()158-159- def release(self) -> None:160- if self.semaphore is None:161- return162-163- self.semaphore.release()164-165-166-class AsyncioBackend(ConcurrencyBackend):167- def __init__(self) -> None:168- global SSL_MONKEY_PATCH_APPLIED169-170- if not SSL_MONKEY_PATCH_APPLIED:171- ssl_monkey_patch()172- SSL_MONKEY_PATCH_APPLIED = True173-174- @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._loop182-183- 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()196-197- return TCPStream(stream=stream, timeout=timeout)198-199- 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)207-208- await asyncio.wait_for(209- stream.stream.start_tls(ssl_context, server_hostname=hostname),210- timeout=timeout.connect_timeout,211- )212-213- return stream214-215- 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)222-223- 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 = loop233-234- def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:235- return PoolSemaphore(limits)236-237- def create_queue(self, max_size: int) -> BaseQueue:238- return typing.cast(BaseQueue, asyncio.Queue(maxsize=max_size))239-240- def create_event(self) -> BaseEvent:241- return typing.cast(BaseEvent, asyncio.Event())242-243- def background_manager(244- self, coroutine: typing.Callable, *args: typing.Any245- ) -> "BackgroundManager":246- return BackgroundManager(coroutine, args)247-248-249-class BackgroundManager(BaseBackgroundManager):250- def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:251- self.coroutine = coroutine252- self.args = args253-254- async def __aenter__(self) -> "BackgroundManager":255- loop = asyncio.get_event_loop()256- self.task = loop.create_task(self.coroutine(*self.args))257- return self258-259- 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
1-import asyncio2-import ssl3-import sys4-import typing5-6-if sys.version_info >= (3, 8):7- from typing import Protocol8-else:9- from typing_extensions import Protocol10-11-12-class Stream(Protocol): # pragma: no cover13- """Protocol defining just the methods we use from asyncio.Stream."""14-15- def at_eof(self) -> bool:16- ...17-18- def close(self) -> typing.Awaitable[None]:19- ...20-21- async def drain(self) -> None:22- ...23-24- def get_extra_info(self, name: str, default: typing.Any = None) -> typing.Any:25- ...26-27- async def read(self, n: int = -1) -> bytes:28- ...29-30- 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- ...38-39- def write(self, data: bytes) -> typing.Awaitable[None]:40- ...41-42-43-async 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)49-50-51-class StreamCompat:52- """53- Thin wrapper around asyncio.StreamReader/StreamWriter to make them look and54- behave similarly to an asyncio.Stream.55- """56-57- def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):58- self.reader = reader59- self.writer = writer60-61- def at_eof(self) -> bool:62- return self.reader.at_eof()63-64- def close(self) -> typing.Awaitable[None]:65- self.writer.close()66- return _OptionalAwait(self.wait_closed)67-68- async def drain(self) -> None:69- await self.writer.drain()70-71- def get_extra_info(self, name: str, default: typing.Any = None) -> typing.Any:72- return self.writer.get_extra_info(name, default)73-74- async def read(self, n: int = -1) -> bytes:75- return await self.reader.read(n)76-77- 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.790-91- reader = asyncio.StreamReader()92- protocol = asyncio.StreamReaderProtocol(reader)93- transport = self.writer.transport94-95- 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- )104-105- reader.set_transport(tls_transport)106- self.reader = reader107- self.writer = asyncio.StreamWriter(108- transport=tls_transport, protocol=protocol, reader=reader, loop=loop109- )110-111- def write(self, data: bytes) -> typing.Awaitable[None]:112- self.writer.write(data)113- return _OptionalAwait(self.drain)114-115- 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 close119-120-121-# 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")124-125-126-class _OptionalAwait(typing.Generic[_T]):127- # The class doesn't create a coroutine128- # if not awaited129- # It prevents "coroutine is never awaited" message130-131- __slots___ = ("_method",)132-133- def __init__(self, method: typing.Callable[[], typing.Awaitable[_T]]):134- self._method = method135-136- def __await__(self) -> typing.Generator[typing.Any, None, _T]:137- return self._method().__await__()added:httpx/concurrency/asyncio.py+294 added
1+import asyncio2+import functools3+import ssl4+import typing5+from types import TracebackType6+7+from ..config import PoolLimits, TimeoutConfig8+from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9+from .base import (10+ BaseBackgroundManager,11+ BaseEvent,12+ BasePoolSemaphore,13+ BaseQueue,14+ BaseTCPStream,15+ ConcurrencyBackend,16+ TimeoutFlag,17+)18+19+SSL_MONKEY_PATCH_APPLIED = False20+21+22+def ssl_monkey_patch() -> None:23+ """24+ Monkey-patch for https://bugs.python.org/issue3670925+26+ This prevents console errors when outstanding HTTPS connections27+ still exist at the point of exiting.28+29+ 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: ignore33+34+ _write = MonkeyPatch.write35+36+ def _fixed_write(self, data: bytes) -> None: # type: ignore37+ if self._loop and not self._loop.is_closed():38+ _write(self, data)39+40+ MonkeyPatch.write = _fixed_write41+42+43+class 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 = timeout53+54+ def get_http_version(self) -> str:55+ ssl_object = self.stream_writer.get_extra_info("ssl_object")56+57+ if ssl_object is None:58+ return "HTTP/1.1"59+60+ ident = ssl_object.selected_alpn_protocol()61+ return "HTTP/2" if ident == "h2" else "HTTP/1.1"62+63+ async def read(64+ self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None65+ ) -> bytes:66+ if timeout is None:67+ timeout = self.timeout68+69+ 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)86+87+ return data88+89+ def write_no_block(self, data: bytes) -> None:90+ self.stream_writer.write(data) # pragma: nocover91+92+ async def write(93+ self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None94+ ) -> None:95+ if not data:96+ return97+98+ if timeout is None:99+ timeout = self.timeout100+101+ 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 None115+116+ 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)130+131+ return self.stream_reader.at_eof()132+133+ async def close(self) -> None:134+ self.stream_writer.close()135+136+137+class PoolSemaphore(BasePoolSemaphore):138+ def __init__(self, pool_limits: PoolLimits):139+ self.pool_limits = pool_limits140+141+ @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._semaphore150+151+ async def acquire(self) -> None:152+ if self.semaphore is None:153+ return154+155+ timeout = self.pool_limits.pool_timeout156+ try:157+ await asyncio.wait_for(self.semaphore.acquire(), timeout)158+ except asyncio.TimeoutError:159+ raise PoolTimeout()160+161+ def release(self) -> None:162+ if self.semaphore is None:163+ return164+165+ self.semaphore.release()166+167+168+class AsyncioBackend(ConcurrencyBackend):169+ def __init__(self) -> None:170+ global SSL_MONKEY_PATCH_APPLIED171+172+ if not SSL_MONKEY_PATCH_APPLIED:173+ ssl_monkey_patch()174+ SSL_MONKEY_PATCH_APPLIED = True175+176+ @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._loop184+185+ 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()199+200+ return TCPStream(201+ stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout202+ )203+204+ async def start_tls(205+ self,206+ stream: BaseTCPStream,207+ hostname: str,208+ ssl_context: ssl.SSLContext,209+ timeout: TimeoutConfig,210+ ) -> BaseTCPStream:211+212+ 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+ )217+218+ assert isinstance(stream, TCPStream)219+220+ stream_reader = asyncio.StreamReader()221+ protocol = asyncio.StreamReaderProtocol(stream_reader)222+ transport = stream.stream_writer.transport223+224+ 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+ )234+235+ 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 stream241+242+ 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)249+250+ 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 = loop260+261+ def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:262+ return PoolSemaphore(limits)263+264+ def create_queue(self, max_size: int) -> BaseQueue:265+ return typing.cast(BaseQueue, asyncio.Queue(maxsize=max_size))266+267+ def create_event(self) -> BaseEvent:268+ return typing.cast(BaseEvent, asyncio.Event())269+270+ def background_manager(271+ self, coroutine: typing.Callable, *args: typing.Any272+ ) -> "BackgroundManager":273+ return BackgroundManager(coroutine, args)274+275+276+class BackgroundManager(BaseBackgroundManager):277+ def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:278+ self.coroutine = coroutine279+ self.args = args280+281+ async def __aenter__(self) -> "BackgroundManager":282+ loop = asyncio.get_event_loop()283+ self.task = loop.create_task(self.coroutine(*self.args))284+ return self285+286+ 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 lines24 )25 26 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 None29 30 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 None33 34 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