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
Provenance
- Commit
71cbde8- Tree
b272ebe- Author
Jamie Hewland <jhewland@gmail.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
6752f7d
5 files changed+413 added−300 removed
added:httpx/concurrency/asyncio/__init__.py+3 added
1+from .backend import AsyncioBackend, BackgroundManager, PoolSemaphore, TCPStream2+3+__all__ = ["AsyncioBackend", "BackgroundManager", "PoolSemaphore", "TCPStream"]added:httpx/concurrency/asyncio/backend.py+271 added
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+58+ if ident is None:59+ return "HTTP/1.1"60+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.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.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.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 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.at_eof()132+133+ 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()137+138+139+class PoolSemaphore(BasePoolSemaphore):140+ def __init__(self, pool_limits: PoolLimits):141+ self.pool_limits = pool_limits142+143+ @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._semaphore152+153+ async def acquire(self) -> None:154+ if self.semaphore is None:155+ return156+157+ timeout = self.pool_limits.pool_timeout158+ try:159+ await asyncio.wait_for(self.semaphore.acquire(), timeout)160+ except asyncio.TimeoutError:161+ raise PoolTimeout()162+163+ def release(self) -> None:164+ if self.semaphore is None:165+ return166+167+ self.semaphore.release()168+169+170+class AsyncioBackend(ConcurrencyBackend):171+ def __init__(self) -> None:172+ global SSL_MONKEY_PATCH_APPLIED173+174+ if not SSL_MONKEY_PATCH_APPLIED:175+ ssl_monkey_patch()176+ SSL_MONKEY_PATCH_APPLIED = True177+178+ @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._loop186+187+ 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()200+201+ return TCPStream(stream=stream, timeout=timeout)202+203+ 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)211+212+ await asyncio.wait_for(213+ stream.stream.start_tls(ssl_context, server_hostname=hostname),214+ timeout=timeout.connect_timeout,215+ )216+217+ return stream218+219+ 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)226+227+ 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 = loop237+238+ def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:239+ return PoolSemaphore(limits)240+241+ def create_queue(self, max_size: int) -> BaseQueue:242+ return typing.cast(BaseQueue, asyncio.Queue(maxsize=max_size))243+244+ def create_event(self) -> BaseEvent:245+ return typing.cast(BaseEvent, asyncio.Event())246+247+ def background_manager(248+ self, coroutine: typing.Callable, *args: typing.Any249+ ) -> "BackgroundManager":250+ return BackgroundManager(coroutine, args)251+252+253+class BackgroundManager(BaseBackgroundManager):254+ def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:255+ self.coroutine = coroutine256+ self.args = args257+258+ async def __aenter__(self) -> "BackgroundManager":259+ loop = asyncio.get_event_loop()260+ self.task = loop.create_task(self.coroutine(*self.args))261+ return self262+263+ 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
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__()deleted:httpx/concurrency/asyncio.py-298 removed
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-62- if ident is None:63- return "HTTP/1.1"64-65- return "HTTP/2" if ident == "h2" else "HTTP/1.1"66-67- async def read(68- self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None69- ) -> bytes:70- if timeout is None:71- timeout = self.timeout72-73- 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)90-91- return data92-93- def write_no_block(self, data: bytes) -> None:94- self.stream_writer.write(data) # pragma: nocover95-96- async def write(97- self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None98- ) -> None:99- if not data:100- return101-102- if timeout is None:103- timeout = self.timeout104-105- 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 None119-120- 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)134-135- return self.stream_reader.at_eof()136-137- async def close(self) -> None:138- self.stream_writer.close()139-140-141-class PoolSemaphore(BasePoolSemaphore):142- def __init__(self, pool_limits: PoolLimits):143- self.pool_limits = pool_limits144-145- @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._semaphore154-155- async def acquire(self) -> None:156- if self.semaphore is None:157- return158-159- timeout = self.pool_limits.pool_timeout160- try:161- await asyncio.wait_for(self.semaphore.acquire(), timeout)162- except asyncio.TimeoutError:163- raise PoolTimeout()164-165- def release(self) -> None:166- if self.semaphore is None:167- return168-169- self.semaphore.release()170-171-172-class AsyncioBackend(ConcurrencyBackend):173- def __init__(self) -> None:174- global SSL_MONKEY_PATCH_APPLIED175-176- if not SSL_MONKEY_PATCH_APPLIED:177- ssl_monkey_patch()178- SSL_MONKEY_PATCH_APPLIED = True179-180- @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._loop188-189- 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()203-204- return TCPStream(205- stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout206- )207-208- async def start_tls(209- self,210- stream: BaseTCPStream,211- hostname: str,212- ssl_context: ssl.SSLContext,213- timeout: TimeoutConfig,214- ) -> BaseTCPStream:215-216- 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- )221-222- assert isinstance(stream, TCPStream)223-224- stream_reader = asyncio.StreamReader()225- protocol = asyncio.StreamReaderProtocol(stream_reader)226- transport = stream.stream_writer.transport227-228- 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- )238-239- 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 stream245-246- 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)253-254- 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 = loop264-265- def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:266- return PoolSemaphore(limits)267-268- def create_queue(self, max_size: int) -> BaseQueue:269- return typing.cast(BaseQueue, asyncio.Queue(maxsize=max_size))270-271- def create_event(self) -> BaseEvent:272- return typing.cast(BaseEvent, asyncio.Event())273-274- def background_manager(275- self, coroutine: typing.Callable, *args: typing.Any276- ) -> "BackgroundManager":277- return BackgroundManager(coroutine, args)278-279-280-class BackgroundManager(BaseBackgroundManager):281- def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:282- self.coroutine = coroutine283- self.args = args284-285- async def __aenter__(self) -> "BackgroundManager":286- loop = asyncio.get_event_loop()287- self.task = loop.create_task(self.coroutine(*self.args))288- return self289-290- 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 lines24 )25 26 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 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_writer.get_extra_info("cipher", default=None) is not None32+ assert stream.stream.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