Skip to content
Myr

Turn concurrency.py into its own sub-package (#244)

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

authored by Florimond Manca · committed by Seth Michael Larson · parent a0aff8d · 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

9 files+280 added−280 removed

added:httpx/concurrency/__init__.py
added:httpx/concurrency/asyncio.py+274 added
1"""2The `Reader` and `Writer` classes here provide a lightweight layer over3`asyncio.StreamReader` and `asyncio.StreamWriter`.45Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.67These classes help encapsulate the timeout logic, make it easier to unit-test8protocols, and help keep the rest of the package more `async`/`await`9based, and less strictly `asyncio`-specific.10"""11import asyncio12import functools13import ssl14import typing15from types import TracebackType1617from ..config import PoolLimits, TimeoutConfig18from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19from ..interfaces import (20 BaseBackgroundManager,21 BasePoolSemaphore,22 BaseReader,23 BaseWriter,24 ConcurrencyBackend,25 Protocol,26)2728SSL_MONKEY_PATCH_APPLIED = False293031def ssl_monkey_patch() -> None:32 """33 Monkey-patch for https://bugs.python.org/issue367093435 This prevents console errors when outstanding HTTPS connections36 still exist at the point of exiting.3738 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: ignore4243 _write = MonkeyPatch.write4445 def _fixed_write(self, data: bytes) -> None: # type: ignore46 if self._loop and not self._loop.is_closed():47 _write(self, data)4849 MonkeyPatch.write = _fixed_write505152class TimeoutFlag:53 """54 A timeout flag holds a state of either read-timeout or write-timeout mode.5556 We use this so that we can attempt both reads and writes concurrently, while57 only enforcing timeouts in one direction.5859 During a request/response cycle we start in write-timeout mode.6061 Once we've sent a request fully, or once we start seeing a response,62 then we switch to read-timeout mode instead.63 """6465 def __init__(self) -> None:66 self.raise_on_read_timeout = False67 self.raise_on_write_timeout = True6869 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 = False7576 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 = True828384class Reader(BaseReader):85 def __init__(86 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig87 ) -> None:88 self.stream_reader = stream_reader89 self.timeout = timeout9091 async def read(92 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None93 ) -> bytes:94 if timeout is None:95 timeout = self.timeout9697 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 None108109 return data110111 def is_connection_dropped(self) -> bool:112 return self.stream_reader.at_eof()113114115class Writer(BaseWriter):116 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):117 self.stream_writer = stream_writer118 self.timeout = timeout119120 def write_no_block(self, data: bytes) -> None:121 self.stream_writer.write(data) # pragma: nocover122123 async def write(124 self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None125 ) -> None:126 if not data:127 return128129 if timeout is None:130 timeout = self.timeout131132 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 None146147 async def close(self) -> None:148 self.stream_writer.close()149150151class PoolSemaphore(BasePoolSemaphore):152 def __init__(self, pool_limits: PoolLimits):153 self.pool_limits = pool_limits154155 @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._semaphore164165 async def acquire(self) -> None:166 if self.semaphore is None:167 return168169 timeout = self.pool_limits.pool_timeout170 try:171 await asyncio.wait_for(self.semaphore.acquire(), timeout)172 except asyncio.TimeoutError:173 raise PoolTimeout()174175 def release(self) -> None:176 if self.semaphore is None:177 return178179 self.semaphore.release()180181182class AsyncioBackend(ConcurrencyBackend):183 def __init__(self) -> None:184 global SSL_MONKEY_PATCH_APPLIED185186 if not SSL_MONKEY_PATCH_APPLIED:187 ssl_monkey_patch()188 SSL_MONKEY_PATCH_APPLIED = True189190 @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._loop198199 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()213214 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()221222 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_11225226 return reader, writer, protocol227228 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)235236 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 = loop246247 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:248 return PoolSemaphore(limits)249250 def background_manager(251 self, coroutine: typing.Callable, args: typing.Any252 ) -> "BackgroundManager":253 return BackgroundManager(coroutine, args)254255256class BackgroundManager(BaseBackgroundManager):257 def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:258 self.coroutine = coroutine259 self.args = args260261 async def __aenter__(self) -> "BackgroundManager":262 loop = asyncio.get_event_loop()263 self.task = loop.create_task(self.coroutine(*self.args))264 return self265266 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
1import typing23from ..concurrency import AsyncioBackend3from ..concurrency.asyncio import AsyncioBackend4from ..config import (5 DEFAULT_POOL_LIMITS,6 DEFAULT_TIMEOUT_CONFIG,7 CertTypes,
157 unmodified lines
modified:httpx/dispatch/connection.py+1 added-1 removed
1import functools2import typing34from ..concurrency import AsyncioBackend4from ..concurrency.asyncio import AsyncioBackend5from ..config import (6 DEFAULT_TIMEOUT_CONFIG,7 CertTypes,8 SSLConfig,
108 unmodified lines
modified:httpx/dispatch/http11.py+1 added-1 removed
1import typing23import h1145from ..concurrency import TimeoutFlag5from ..concurrency.asyncio import TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes7from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend8from ..models import AsyncRequest, AsyncResponse9
179 unmodified lines
modified:httpx/dispatch/http2.py+1 added-1 removed
2 unmodified lines
34import h2.connection5import h2.events67from ..concurrency import TimeoutFlag7from ..concurrency.asyncio import TimeoutFlag8from ..config import TimeoutConfig, TimeoutTypes9from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend10from ..models import AsyncRequest, AsyncResponse11
166 unmodified lines
modified:httpx/__init__.py+1 added-1 removed
1from .__version__ import __description__, __title__, __version__2from .api import delete, get, head, options, patch, post, put, request3from .client import AsyncClient, Client4from .concurrency import AsyncioBackend4from .concurrency.asyncio import AsyncioBackend5from .config import (6 USER_AGENT,7 CertTypes,8 PoolLimits,
127 unmodified lines
modified:httpx/client.py+1 added-1 removed
3 unmodified lines
45import hstspreload67from .auth import HTTPBasicAuth8from .concurrency import AsyncioBackend8from .concurrency.asyncio import AsyncioBackend9from .config import (10 DEFAULT_MAX_REDIRECTS,11 DEFAULT_POOL_LIMITS,12 DEFAULT_TIMEOUT_CONFIG,
971 unmodified lines
deleted:httpx/concurrency.py-274 removed
1"""2The `Reader` and `Writer` classes here provide a lightweight layer over3`asyncio.StreamReader` and `asyncio.StreamWriter`.45Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.67These classes help encapsulate the timeout logic, make it easier to unit-test8protocols, and help keep the rest of the package more `async`/`await`9based, and less strictly `asyncio`-specific.10"""11import asyncio12import functools13import ssl14import typing15from types import TracebackType1617from .config import PoolLimits, TimeoutConfig18from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19from .interfaces import (20 BaseBackgroundManager,21 BasePoolSemaphore,22 BaseReader,23 BaseWriter,24 ConcurrencyBackend,25 Protocol,26)2728SSL_MONKEY_PATCH_APPLIED = False293031def ssl_monkey_patch() -> None:32 """33 Monkey-patch for https://bugs.python.org/issue367093435 This prevents console errors when outstanding HTTPS connections36 still exist at the point of exiting.3738 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: ignore4243 _write = MonkeyPatch.write4445 def _fixed_write(self, data: bytes) -> None: # type: ignore46 if self._loop and not self._loop.is_closed():47 _write(self, data)4849 MonkeyPatch.write = _fixed_write505152class TimeoutFlag:53 """54 A timeout flag holds a state of either read-timeout or write-timeout mode.5556 We use this so that we can attempt both reads and writes concurrently, while57 only enforcing timeouts in one direction.5859 During a request/response cycle we start in write-timeout mode.6061 Once we've sent a request fully, or once we start seeing a response,62 then we switch to read-timeout mode instead.63 """6465 def __init__(self) -> None:66 self.raise_on_read_timeout = False67 self.raise_on_write_timeout = True6869 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 = False7576 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 = True828384class Reader(BaseReader):85 def __init__(86 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig87 ) -> None:88 self.stream_reader = stream_reader89 self.timeout = timeout9091 async def read(92 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None93 ) -> bytes:94 if timeout is None:95 timeout = self.timeout9697 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 None108109 return data110111 def is_connection_dropped(self) -> bool:112 return self.stream_reader.at_eof()113114115class Writer(BaseWriter):116 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):117 self.stream_writer = stream_writer118 self.timeout = timeout119120 def write_no_block(self, data: bytes) -> None:121 self.stream_writer.write(data) # pragma: nocover122123 async def write(124 self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None125 ) -> None:126 if not data:127 return128129 if timeout is None:130 timeout = self.timeout131132 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 None146147 async def close(self) -> None:148 self.stream_writer.close()149150151class PoolSemaphore(BasePoolSemaphore):152 def __init__(self, pool_limits: PoolLimits):153 self.pool_limits = pool_limits154155 @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._semaphore164165 async def acquire(self) -> None:166 if self.semaphore is None:167 return168169 timeout = self.pool_limits.pool_timeout170 try:171 await asyncio.wait_for(self.semaphore.acquire(), timeout)172 except asyncio.TimeoutError:173 raise PoolTimeout()174175 def release(self) -> None:176 if self.semaphore is None:177 return178179 self.semaphore.release()180181182class AsyncioBackend(ConcurrencyBackend):183 def __init__(self) -> None:184 global SSL_MONKEY_PATCH_APPLIED185186 if not SSL_MONKEY_PATCH_APPLIED:187 ssl_monkey_patch()188 SSL_MONKEY_PATCH_APPLIED = True189190 @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._loop198199 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()213214 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()221222 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_11225226 return reader, writer, protocol227228 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)235236 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 = loop246247 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:248 return PoolSemaphore(limits)249250 def background_manager(251 self, coroutine: typing.Callable, args: typing.Any252 ) -> "BackgroundManager":253 return BackgroundManager(coroutine, args)254255256class BackgroundManager(BaseBackgroundManager):257 def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:258 self.coroutine = coroutine259 self.args = args260261 async def __aenter__(self) -> "BackgroundManager":262 loop = asyncio.get_event_loop()263 self.task = loop.create_task(self.coroutine(*self.args))264 return self265266 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()