Merge branch 'master' into protocol-support
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parents 4bfe54d, b2397ff · Browse files · 9 files·+280 added−280 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+280 added−280 removed
- other:+280 added−280 removed
Provenance
- Commit
193196b- Tree
b1d9569- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent 1
4bfe54d- Parent 2
b2397ff
9 files changed+280 added−280 removed
added:httpx/concurrency/__init__.py
added:httpx/concurrency/asyncio.py+274 added
1+"""2+The `Reader` and `Writer` classes here provide a lightweight layer over3+`asyncio.StreamReader` and `asyncio.StreamWriter`.4+5+Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.6+7+These classes help encapsulate the timeout logic, make it easier to unit-test8+protocols, and help keep the rest of the package more `async`/`await`9+based, and less strictly `asyncio`-specific.10+"""11+import asyncio12+import functools13+import ssl14+import typing15+from types import TracebackType16+17+from ..config import PoolLimits, HTTPVersionConfig, TimeoutConfig18+from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19+from ..interfaces import (20+ BaseBackgroundManager,21+ BasePoolSemaphore,22+ BaseReader,23+ BaseWriter,24+ ConcurrencyBackend,25+ Protocol,26+)27+28+SSL_MONKEY_PATCH_APPLIED = False29+30+31+def ssl_monkey_patch() -> None:32+ """33+ Monkey-patch for https://bugs.python.org/issue3670934+35+ This prevents console errors when outstanding HTTPS connections36+ still exist at the point of exiting.37+38+ Clients which have been opened using a `with` block, or which have39+ had `close()` closed, will not exhibit this issue in the first place.40+ """41+ MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignore42+43+ _write = MonkeyPatch.write44+45+ def _fixed_write(self, data: bytes) -> None: # type: ignore46+ if self._loop and not self._loop.is_closed():47+ _write(self, data)48+49+ MonkeyPatch.write = _fixed_write50+51+52+class TimeoutFlag:53+ """54+ A timeout flag holds a state of either read-timeout or write-timeout mode.55+56+ We use this so that we can attempt both reads and writes concurrently, while57+ only enforcing timeouts in one direction.58+59+ During a request/response cycle we start in write-timeout mode.60+61+ Once we've sent a request fully, or once we start seeing a response,62+ then we switch to read-timeout mode instead.63+ """64+65+ def __init__(self) -> None:66+ self.raise_on_read_timeout = False67+ self.raise_on_write_timeout = True68+69+ def set_read_timeouts(self) -> None:70+ """71+ Set the flag to read-timeout mode.72+ """73+ self.raise_on_read_timeout = True74+ self.raise_on_write_timeout = False75+76+ def set_write_timeouts(self) -> None:77+ """78+ Set the flag to write-timeout mode.79+ """80+ self.raise_on_read_timeout = False81+ self.raise_on_write_timeout = True82+83+84+class Reader(BaseReader):85+ def __init__(86+ self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig87+ ) -> None:88+ self.stream_reader = stream_reader89+ self.timeout = timeout90+91+ async def read(92+ self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None93+ ) -> bytes:94+ if timeout is None:95+ timeout = self.timeout96+97+ while True:98+ # Check our flag at the first possible moment, and use a fine99+ # grained retry loop if we're not yet in read-timeout mode.100+ should_raise = flag is None or flag.raise_on_read_timeout101+ read_timeout = timeout.read_timeout if should_raise else 0.01102+ try:103+ data = await asyncio.wait_for(self.stream_reader.read(n), read_timeout)104+ break105+ except asyncio.TimeoutError:106+ if should_raise:107+ raise ReadTimeout() from None108+109+ return data110+111+ def is_connection_dropped(self) -> bool:112+ return self.stream_reader.at_eof()113+114+115+class Writer(BaseWriter):116+ def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):117+ self.stream_writer = stream_writer118+ self.timeout = timeout119+120+ def write_no_block(self, data: bytes) -> None:121+ self.stream_writer.write(data) # pragma: nocover122+123+ async def write(124+ self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None125+ ) -> None:126+ if not data:127+ return128+129+ if timeout is None:130+ timeout = self.timeout131+132+ self.stream_writer.write(data)133+ while True:134+ try:135+ await asyncio.wait_for( # type: ignore136+ self.stream_writer.drain(), timeout.write_timeout137+ )138+ break139+ except asyncio.TimeoutError:140+ # We check our flag at the possible moment, in order to141+ # allow us to suppress write timeouts, if we've since142+ # switched over to read-timeout mode.143+ should_raise = flag is None or flag.raise_on_write_timeout144+ if should_raise:145+ raise WriteTimeout() from None146+147+ async def close(self) -> None:148+ self.stream_writer.close()149+150+151+class PoolSemaphore(BasePoolSemaphore):152+ def __init__(self, pool_limits: PoolLimits):153+ self.pool_limits = pool_limits154+155+ @property156+ def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:157+ if not hasattr(self, "_semaphore"):158+ max_connections = self.pool_limits.hard_limit159+ if max_connections is None:160+ self._semaphore = None161+ else:162+ self._semaphore = asyncio.BoundedSemaphore(value=max_connections)163+ return self._semaphore164+165+ async def acquire(self) -> None:166+ if self.semaphore is None:167+ return168+169+ timeout = self.pool_limits.pool_timeout170+ try:171+ await asyncio.wait_for(self.semaphore.acquire(), timeout)172+ except asyncio.TimeoutError:173+ raise PoolTimeout()174+175+ def release(self) -> None:176+ if self.semaphore is None:177+ return178+179+ self.semaphore.release()180+181+182+class AsyncioBackend(ConcurrencyBackend):183+ def __init__(self) -> None:184+ global SSL_MONKEY_PATCH_APPLIED185+186+ if not SSL_MONKEY_PATCH_APPLIED:187+ ssl_monkey_patch()188+ SSL_MONKEY_PATCH_APPLIED = True189+190+ @property191+ def loop(self) -> asyncio.AbstractEventLoop:192+ if not hasattr(self, "_loop"):193+ try:194+ self._loop = asyncio.get_event_loop()195+ except RuntimeError:196+ self._loop = asyncio.new_event_loop()197+ return self._loop198+199+ async def connect(200+ self,201+ hostname: str,202+ port: int,203+ ssl_context: typing.Optional[ssl.SSLContext],204+ timeout: TimeoutConfig,205+ ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:206+ try:207+ stream_reader, stream_writer = await asyncio.wait_for( # type: ignore208+ asyncio.open_connection(hostname, port, ssl=ssl_context),209+ timeout.connect_timeout,210+ )211+ except asyncio.TimeoutError:212+ raise ConnectTimeout()213+214+ ssl_object = stream_writer.get_extra_info("ssl_object")215+ if ssl_object is None:216+ ident = "http/1.1"217+ else:218+ ident = ssl_object.selected_alpn_protocol()219+ if ident is None:220+ ident = ssl_object.selected_npn_protocol()221+222+ reader = Reader(stream_reader=stream_reader, timeout=timeout)223+ writer = Writer(stream_writer=stream_writer, timeout=timeout)224+ protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11225+226+ return reader, writer, protocol227+228+ async def run_in_threadpool(229+ self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any230+ ) -> typing.Any:231+ if kwargs:232+ # loop.run_in_executor doesn't accept 'kwargs', so bind them in here233+ func = functools.partial(func, **kwargs)234+ return await self.loop.run_in_executor(None, func, *args)235+236+ def run(237+ self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any238+ ) -> typing.Any:239+ loop = self.loop240+ if loop.is_running():241+ self._loop = asyncio.new_event_loop()242+ try:243+ return self.loop.run_until_complete(coroutine(*args, **kwargs))244+ finally:245+ self._loop = loop246+247+ def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:248+ return PoolSemaphore(limits)249+250+ def background_manager(251+ self, coroutine: typing.Callable, args: typing.Any252+ ) -> "BackgroundManager":253+ return BackgroundManager(coroutine, args)254+255+256+class BackgroundManager(BaseBackgroundManager):257+ def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:258+ self.coroutine = coroutine259+ self.args = args260+261+ async def __aenter__(self) -> "BackgroundManager":262+ loop = asyncio.get_event_loop()263+ self.task = loop.create_task(self.coroutine(*self.args))264+ return self265+266+ async def __aexit__(267+ self,268+ exc_type: typing.Type[BaseException] = None,269+ exc_value: BaseException = None,270+ traceback: TracebackType = None,271+ ) -> None:272+ await self.task273+ if exc_type is None:274+ self.task.result()modified:httpx/dispatch/connection_pool.py+1 added-1 removed
1 import typing2 3-from ..concurrency import AsyncioBackend3+from ..concurrency.asyncio import AsyncioBackend4 from ..config import (5 DEFAULT_POOL_LIMITS,6 DEFAULT_TIMEOUT_CONFIG,7 CertTypes,166 unmodified linesmodified:httpx/dispatch/connection.py+1 added-1 removed
1 import functools2 import typing3 import ssl4 5-from ..concurrency import AsyncioBackend5+from ..concurrency.asyncio import AsyncioBackend6 from ..config import (7 DEFAULT_TIMEOUT_CONFIG,8 CertTypes,9 HTTPVersionTypes,125 unmodified linesmodified:httpx/dispatch/http11.py+1 added-1 removed
1 import typing2 3 import h114 5-from ..concurrency import TimeoutFlag5+from ..concurrency.asyncio import TimeoutFlag6 from ..config import TimeoutConfig, TimeoutTypes7 from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend8 from ..models import AsyncRequest, AsyncResponse9 179 unmodified linesmodified:httpx/dispatch/http2.py+1 added-1 removed
2 unmodified lines3 4 import h2.connection5 import h2.events6 7-from ..concurrency import TimeoutFlag7+from ..concurrency.asyncio import TimeoutFlag8 from ..config import TimeoutConfig, TimeoutTypes9 from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend10 from ..models import AsyncRequest, AsyncResponse11 166 unmodified linesmodified:httpx/__init__.py+1 added-1 removed
1 from .__version__ import __description__, __title__, __version__2 from .api import delete, get, head, options, patch, post, put, request3 from .client import AsyncClient, Client4-from .concurrency import AsyncioBackend4+from .concurrency.asyncio import AsyncioBackend5 from .config import (6 USER_AGENT,7 CertTypes,8 PoolLimits,129 unmodified linesmodified:httpx/client.py+1 added-1 removed
3 unmodified lines4 5 import hstspreload6 7 from .auth import HTTPBasicAuth8-from .concurrency import AsyncioBackend8+from .concurrency.asyncio import AsyncioBackend9 from .config import (10 DEFAULT_MAX_REDIRECTS,11 DEFAULT_POOL_LIMITS,12 DEFAULT_TIMEOUT_CONFIG,971 unmodified linesdeleted:httpx/concurrency.py-274 removed
1-"""2-The `Reader` and `Writer` classes here provide a lightweight layer over3-`asyncio.StreamReader` and `asyncio.StreamWriter`.4-5-Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.6-7-These classes help encapsulate the timeout logic, make it easier to unit-test8-protocols, and help keep the rest of the package more `async`/`await`9-based, and less strictly `asyncio`-specific.10-"""11-import asyncio12-import functools13-import ssl14-import typing15-from types import TracebackType16-17-from .config import PoolLimits, HTTPVersionConfig, TimeoutConfig18-from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19-from .interfaces import (20- BaseBackgroundManager,21- BasePoolSemaphore,22- BaseReader,23- BaseWriter,24- ConcurrencyBackend,25- Protocol,26-)27-28-SSL_MONKEY_PATCH_APPLIED = False29-30-31-def ssl_monkey_patch() -> None:32- """33- Monkey-patch for https://bugs.python.org/issue3670934-35- This prevents console errors when outstanding HTTPS connections36- still exist at the point of exiting.37-38- Clients which have been opened using a `with` block, or which have39- had `close()` closed, will not exhibit this issue in the first place.40- """41- MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignore42-43- _write = MonkeyPatch.write44-45- def _fixed_write(self, data: bytes) -> None: # type: ignore46- if self._loop and not self._loop.is_closed():47- _write(self, data)48-49- MonkeyPatch.write = _fixed_write50-51-52-class TimeoutFlag:53- """54- A timeout flag holds a state of either read-timeout or write-timeout mode.55-56- We use this so that we can attempt both reads and writes concurrently, while57- only enforcing timeouts in one direction.58-59- During a request/response cycle we start in write-timeout mode.60-61- Once we've sent a request fully, or once we start seeing a response,62- then we switch to read-timeout mode instead.63- """64-65- def __init__(self) -> None:66- self.raise_on_read_timeout = False67- self.raise_on_write_timeout = True68-69- def set_read_timeouts(self) -> None:70- """71- Set the flag to read-timeout mode.72- """73- self.raise_on_read_timeout = True74- self.raise_on_write_timeout = False75-76- def set_write_timeouts(self) -> None:77- """78- Set the flag to write-timeout mode.79- """80- self.raise_on_read_timeout = False81- self.raise_on_write_timeout = True82-83-84-class Reader(BaseReader):85- def __init__(86- self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig87- ) -> None:88- self.stream_reader = stream_reader89- self.timeout = timeout90-91- async def read(92- self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None93- ) -> bytes:94- if timeout is None:95- timeout = self.timeout96-97- while True:98- # Check our flag at the first possible moment, and use a fine99- # grained retry loop if we're not yet in read-timeout mode.100- should_raise = flag is None or flag.raise_on_read_timeout101- read_timeout = timeout.read_timeout if should_raise else 0.01102- try:103- data = await asyncio.wait_for(self.stream_reader.read(n), read_timeout)104- break105- except asyncio.TimeoutError:106- if should_raise:107- raise ReadTimeout() from None108-109- return data110-111- def is_connection_dropped(self) -> bool:112- return self.stream_reader.at_eof()113-114-115-class Writer(BaseWriter):116- def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):117- self.stream_writer = stream_writer118- self.timeout = timeout119-120- def write_no_block(self, data: bytes) -> None:121- self.stream_writer.write(data) # pragma: nocover122-123- async def write(124- self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None125- ) -> None:126- if not data:127- return128-129- if timeout is None:130- timeout = self.timeout131-132- self.stream_writer.write(data)133- while True:134- try:135- await asyncio.wait_for( # type: ignore136- self.stream_writer.drain(), timeout.write_timeout137- )138- break139- except asyncio.TimeoutError:140- # We check our flag at the possible moment, in order to141- # allow us to suppress write timeouts, if we've since142- # switched over to read-timeout mode.143- should_raise = flag is None or flag.raise_on_write_timeout144- if should_raise:145- raise WriteTimeout() from None146-147- async def close(self) -> None:148- self.stream_writer.close()149-150-151-class PoolSemaphore(BasePoolSemaphore):152- def __init__(self, pool_limits: PoolLimits):153- self.pool_limits = pool_limits154-155- @property156- def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:157- if not hasattr(self, "_semaphore"):158- max_connections = self.pool_limits.hard_limit159- if max_connections is None:160- self._semaphore = None161- else:162- self._semaphore = asyncio.BoundedSemaphore(value=max_connections)163- return self._semaphore164-165- async def acquire(self) -> None:166- if self.semaphore is None:167- return168-169- timeout = self.pool_limits.pool_timeout170- try:171- await asyncio.wait_for(self.semaphore.acquire(), timeout)172- except asyncio.TimeoutError:173- raise PoolTimeout()174-175- def release(self) -> None:176- if self.semaphore is None:177- return178-179- self.semaphore.release()180-181-182-class AsyncioBackend(ConcurrencyBackend):183- def __init__(self) -> None:184- global SSL_MONKEY_PATCH_APPLIED185-186- if not SSL_MONKEY_PATCH_APPLIED:187- ssl_monkey_patch()188- SSL_MONKEY_PATCH_APPLIED = True189-190- @property191- def loop(self) -> asyncio.AbstractEventLoop:192- if not hasattr(self, "_loop"):193- try:194- self._loop = asyncio.get_event_loop()195- except RuntimeError:196- self._loop = asyncio.new_event_loop()197- return self._loop198-199- async def connect(200- self,201- hostname: str,202- port: int,203- ssl_context: typing.Optional[ssl.SSLContext],204- timeout: TimeoutConfig,205- ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:206- try:207- stream_reader, stream_writer = await asyncio.wait_for( # type: ignore208- asyncio.open_connection(hostname, port, ssl=ssl_context),209- timeout.connect_timeout,210- )211- except asyncio.TimeoutError:212- raise ConnectTimeout()213-214- ssl_object = stream_writer.get_extra_info("ssl_object")215- if ssl_object is None:216- ident = "http/1.1"217- else:218- ident = ssl_object.selected_alpn_protocol()219- if ident is None:220- ident = ssl_object.selected_npn_protocol()221-222- reader = Reader(stream_reader=stream_reader, timeout=timeout)223- writer = Writer(stream_writer=stream_writer, timeout=timeout)224- protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11225-226- return reader, writer, protocol227-228- async def run_in_threadpool(229- self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any230- ) -> typing.Any:231- if kwargs:232- # loop.run_in_executor doesn't accept 'kwargs', so bind them in here233- func = functools.partial(func, **kwargs)234- return await self.loop.run_in_executor(None, func, *args)235-236- def run(237- self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any238- ) -> typing.Any:239- loop = self.loop240- if loop.is_running():241- self._loop = asyncio.new_event_loop()242- try:243- return self.loop.run_until_complete(coroutine(*args, **kwargs))244- finally:245- self._loop = loop246-247- def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:248- return PoolSemaphore(limits)249-250- def background_manager(251- self, coroutine: typing.Callable, args: typing.Any252- ) -> "BackgroundManager":253- return BackgroundManager(coroutine, args)254-255-256-class BackgroundManager(BaseBackgroundManager):257- def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:258- self.coroutine = coroutine259- self.args = args260-261- async def __aenter__(self) -> "BackgroundManager":262- loop = asyncio.get_event_loop()263- self.task = loop.create_task(self.coroutine(*self.args))264- return self265-266- async def __aexit__(267- self,268- exc_type: typing.Type[BaseException] = None,269- exc_value: BaseException = None,270- traceback: TracebackType = None,271- ) -> None:272- await self.task273- if exc_type is None:274- self.task.result()