Add ConcurrencyBackend interface
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 · parent 87cab4c · Browse files · 5 files·+89 added−45 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+89 added−45 removed
- tests:+0 added−1 removed
- other:+89 added−44 removed
Provenance
- Commit
2694c48- Tree
c00a67c- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
87cab4c
5 files changed+89 added−45 removed
modified:httpcore/dispatch/connection_pool.py+7 added-3 removed
1 import collections.abc2 import typing3 4-from ..concurrency import PoolSemaphore4+from ..concurrency import AsyncioBackend5 from ..config import (6 DEFAULT_CA_BUNDLE_PATH,7 DEFAULT_POOL_LIMITS,8 DEFAULT_SSL_CONFIG,3 unmodified lines12 TimeoutConfig,13 )14 from ..decoders import ACCEPT_ENCODING15 from ..exceptions import PoolTimeout16-from ..interfaces import Dispatcher16+from ..interfaces import ConcurrencyBackend, Dispatcher17 from ..models import Origin, Request, Response18 from .connection import HTTPConnection19 20 CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]68 unmodified lines89 *,90 ssl: SSLConfig = DEFAULT_SSL_CONFIG,91 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,92 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,93+ backend: ConcurrencyBackend = None,94 ):95 self.ssl = ssl96 self.timeout = timeout97 self.pool_limits = pool_limits98 self.is_closed = False99 99- self.max_connections = PoolSemaphore(pool_limits)100 self.keepalive_connections = ConnectionStore()101 self.active_connections = ConnectionStore()102 103+ self.backend = AsyncioBackend() if backend is None else backend104+ self.max_connections = self.backend.get_semaphore(pool_limits)105+106 @property107 def num_connections(self) -> int:108 return len(self.keepalive_connections) + len(self.active_connections)109 25 unmodified lines135 connection = HTTPConnection(136 origin,137 ssl=self.ssl,138 timeout=self.timeout,139+ backend=self.backend,140 release_func=self.release_connection,141 )142 143 self.active_connections.add(connection)24 unmodified linesmodified:httpcore/dispatch/connection.py+7 added-3 removed
2 unmodified lines3 4 import h2.connection5 import h116 7-from ..concurrency import connect7+from ..concurrency import AsyncioBackend8 from ..config import (9 DEFAULT_SSL_CONFIG,10 DEFAULT_TIMEOUT_CONFIG,11 SSLConfig,12 TimeoutConfig,13 )14 from ..exceptions import ConnectTimeout15-from ..interfaces import Dispatcher, Protocol15+from ..interfaces import ConcurrencyBackend, Dispatcher, Protocol16 from ..models import Origin, Request, Response17 from .http2 import HTTP2Connection18 from .http11 import HTTP11Connection19 6 unmodified lines26 self,27 origin: typing.Union[str, Origin],28 ssl: SSLConfig = DEFAULT_SSL_CONFIG,29 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,30+ backend: ConcurrencyBackend = None,31 release_func: typing.Optional[ReleaseCallback] = None,32 ):33 self.origin = Origin(origin) if isinstance(origin, str) else origin34 self.ssl = ssl35 self.timeout = timeout36+ self.backend = AsyncioBackend() if backend is None else backend37 self.release_func = release_func38 self.h11_connection = None # type: typing.Optional[HTTP11Connection]39 self.h2_connection = None # type: typing.Optional[HTTP2Connection]40 35 unmodified lines76 on_release = None77 else:78 on_release = functools.partial(self.release_func, self)79 78- reader, writer, protocol = await connect(host, port, ssl_context, timeout)80+ reader, writer, protocol = await self.backend.connect(81+ host, port, ssl_context, timeout82+ )83 if protocol == Protocol.HTTP_2:84 self.h2_connection = HTTP2Connection(reader, writer, on_release=on_release)85 else:86 self.h11_connection = HTTP11Connection(20 unmodified linesmodified:httpcore/concurrency.py+59 added-37 removed
12 unmodified lines13 import typing14 15 from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig16 from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout17-from .interfaces import BasePoolSemaphore, BaseReader, BaseWriter, Protocol17+from .interfaces import (18+ BasePoolSemaphore,19+ BaseReader,20+ BaseWriter,21+ ConcurrencyBackend,22+ Protocol,23+)24 25 OptionalTimeout = typing.Optional[TimeoutConfig]26 27 22-# Monky-patch for https://bugs.python.org/issue3670923-#24-# This prevents console errors when outstanding HTTPS connections25-# still exist at the point of exiting.26-#27-# Clients which have been opened using a `with` block, or which have28-# had `close()` closed, will not exhibit this issue in the first place.28+SSL_MONKEY_PATCH_APPLIED = False29 30 31-_write = asyncio.selector_events._SelectorSocketTransport.write # type: ignore31+def ssl_monkey_patch() -> None:32+ """33+ Monky-patch for https://bugs.python.org/issue3670934 35+ This prevents console errors when outstanding HTTPS connections36+ still exist at the point of exiting.37 34-def _fixed_write(self, data: bytes) -> None: # type: ignore35- if not self._loop.is_closed():36- _write(self, data)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 39-asyncio.selector_events._SelectorSocketTransport.write = _fixed_write # type: ignore45+ def _fixed_write(self, data: bytes) -> None: # type: ignore46+ if not self._loop.is_closed():47+ _write(self, data)48 49+ MonkeyPatch.write = _fixed_write50 51+52 class Reader(BaseReader):53 def __init__(54 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig55 ) -> None:71 unmodified lines127 128 self.semaphore.release()129 130 121-async def connect(122- hostname: str,123- port: int,124- ssl_context: typing.Optional[ssl.SSLContext] = None,125- timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,126-) -> typing.Tuple[Reader, Writer, Protocol]:127- try:128- stream_reader, stream_writer = await asyncio.wait_for( # type: ignore129- asyncio.open_connection(hostname, port, ssl=ssl_context),130- timeout.connect_timeout,131- )132- except asyncio.TimeoutError:133- raise ConnectTimeout()131+class AsyncioBackend(ConcurrencyBackend):132+ def __init__(self) -> None:133+ global SSL_MONKEY_PATCH_APPLIED134 135- ssl_object = stream_writer.get_extra_info("ssl_object")136- if ssl_object is None:137- ident = "http/1.1"138- else:139- ident = ssl_object.selected_alpn_protocol()140- if ident is None:141- ident = ssl_object.selected_npn_protocol()135+ if not SSL_MONKEY_PATCH_APPLIED:136+ ssl_monkey_patch()137+ SSL_MONKEY_PATCH_APPLIED = True138 143- reader = Reader(stream_reader=stream_reader, timeout=timeout)144- writer = Writer(stream_writer=stream_writer, timeout=timeout)145- protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11139+ async def connect(140+ self,141+ hostname: str,142+ port: int,143+ ssl_context: typing.Optional[ssl.SSLContext],144+ timeout: TimeoutConfig,145+ ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:146+ try:147+ stream_reader, stream_writer = await asyncio.wait_for( # type: ignore148+ asyncio.open_connection(hostname, port, ssl=ssl_context),149+ timeout.connect_timeout,150+ )151+ except asyncio.TimeoutError:152+ raise ConnectTimeout()153 154+ ssl_object = stream_writer.get_extra_info("ssl_object")155+ if ssl_object is None:156+ ident = "http/1.1"157+ else:158+ ident = ssl_object.selected_alpn_protocol()159+ if ident is None:160+ ident = ssl_object.selected_npn_protocol()161+162+ reader = Reader(stream_reader=stream_reader, timeout=timeout)163+ writer = Writer(stream_writer=stream_writer, timeout=timeout)164+ protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11165+147- return (reader, writer, protocol)166+ return (reader, writer, protocol)167+168+ def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:169+ return PoolSemaphore(limits)modified:httpcore/interfaces.py+16 added-1 removed
1 import enum2+import ssl3 import typing4 from types import TracebackType5 5-from .config import SSLConfig, TimeoutConfig6+from .config import PoolLimits, SSLConfig, TimeoutConfig7 from .models import (8 URL,9 Headers,10 HeaderTypes,106 unmodified lines117 raise NotImplementedError() # pragma: no cover118 119 def release(self) -> None:120 raise NotImplementedError() # pragma: no cover121+122+123+class ConcurrencyBackend:124+ async def connect(125+ self,126+ hostname: str,127+ port: int,128+ ssl_context: typing.Optional[ssl.SSLContext],129+ timeout: TimeoutConfig,130+ ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:131+ raise NotImplementedError() # pragma: no cover132+133+ def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:134+ raise NotImplementedError() # pragma: no covermodified:tests/conftest.py-1 removed
1 import asyncio2-import os2 3 import pytest4 import trustme5 from uvicorn.config import Config83 unmodified lines