Check for connection aliveness on pool re-acquiry (#111)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Check for connection aliveness on pool re-acquiry * Test for connection re-acquiry with HTTP/2 * nocover on HTTP/1.1 ConnectionResetError, since we're testing the equivelent on HTTP/2 * Fix setup.py to read version from __version__
authored by Tom Christie · committed by GitHub · parent fe1f9ed · Browse files · 7 files·+76 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+76 added−21 removed
- tests:+26 added−2 removed
- other:+50 added−19 removed
Provenance
- Commit
025240c- Tree
0426d4f- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
fe1f9ed
7 files changed+76 added−21 removed
modified:http3/dispatch/connection_pool.py+27 added-13 removed
9 unmodified lines10 TimeoutTypes,11 VerifyTypes,12 )13 from ..decoders import ACCEPT_ENCODING14-from ..exceptions import PoolTimeout14+from ..exceptions import NotConnected, PoolTimeout15 from ..interfaces import AsyncDispatcher, ConcurrencyBackend16 from ..models import AsyncRequest, AsyncResponse, Origin17 from .connection import HTTPConnection18 90 unmodified lines109 verify: VerifyTypes = None,110 cert: CertTypes = None,111 timeout: TimeoutTypes = None,112 ) -> AsyncResponse:113- connection = await self.acquire_connection(request.url.origin)114- try:115- response = await connection.send(116- request, verify=verify, cert=cert, timeout=timeout113+ allow_connection_reuse = True114+ connection = None115+ while connection is None:116+ connection = await self.acquire_connection(117+ origin=request.url.origin, allow_connection_reuse=allow_connection_reuse118 )119+ try:120+ response = await connection.send(121+ request, verify=verify, cert=cert, timeout=timeout122+ )118- except BaseException as exc:119- self.active_connections.remove(connection)120- self.max_connections.release()121- raise exc123+ except BaseException as exc:124+ self.active_connections.remove(connection)125+ self.max_connections.release()126+ if isinstance(exc, NotConnected) and allow_connection_reuse:127+ connection = None128+ allow_connection_reuse = False129+ else:130+ raise exc131+132 return response133 134+ async def acquire_connection(135+ self, origin: Origin, allow_connection_reuse: bool = True136+ ) -> HTTPConnection:137+ connection = None124- async def acquire_connection(self, origin: Origin) -> HTTPConnection:125- connection = self.active_connections.pop_by_origin(origin, http2_only=True)126- if connection is None:127- connection = self.keepalive_connections.pop_by_origin(origin)138+ if allow_connection_reuse:139+ connection = self.active_connections.pop_by_origin(origin, http2_only=True)140+ if connection is None:141+ connection = self.keepalive_connections.pop_by_origin(origin)142 143 if connection is None:144 await self.max_connections.acquire()145 connection = HTTPConnection(33 unmodified linesmodified:http3/dispatch/http11.py+8 added-2 removed
2 unmodified lines3 import h114 5 from ..concurrency import TimeoutFlag6 from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes7-from ..exceptions import ConnectTimeout, ReadTimeout7+from ..exceptions import ConnectTimeout, NotConnected, ReadTimeout8 from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend9 from ..models import AsyncRequest, AsyncResponse10 11 H11Event = typing.Union[33 unmodified lines45 self, request: AsyncRequest, timeout: TimeoutTypes = None46 ) -> AsyncResponse:47 timeout = None if timeout is None else TimeoutConfig(timeout)48 49+ try:49- await self._send_request(request, timeout)50+ await self._send_request(request, timeout)51+ except ConnectionResetError: # pragma: nocover52+ # We're currently testing this case in HTTP/2.53+ # Really we should test it here too, but this'll do in the meantime.54+ raise NotConnected() from None55+56 task, args = self._send_request_data, [request.stream(), timeout]57 async with self.backend.background_manager(task, args=args):58 http_version, status_code, headers = await self._receive_response(timeout)59 content = self._receive_response_data(timeout)131 unmodified linesmodified:http3/dispatch/http2.py+6 added-2 removed
4 unmodified lines5 import h2.events6 7 from ..concurrency import TimeoutFlag8 from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes9-from ..exceptions import ConnectTimeout, ReadTimeout9+from ..exceptions import ConnectTimeout, NotConnected, ReadTimeout10 from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend11 from ..models import AsyncRequest, AsyncResponse12 13 24 unmodified lines38 # Start sending the request.39 if not self.initialized:40 self.initiate_connection()41 42+ try:42- stream_id = await self.send_headers(request, timeout)43+ stream_id = await self.send_headers(request, timeout)44+ except ConnectionResetError:45+ raise NotConnected() from None46+47 self.events[stream_id] = []48 self.timeout_flags[stream_id] = TimeoutFlag()49 50 task, args = self.send_request_data, [stream_id, request.stream(), timeout]128 unmodified linesmodified:http3/exceptions.py+8 added-1 removed
32 unmodified lines33 34 # HTTP exceptions...35 36 37+class NotConnected(Exception):38+ """39+ A connection was lost at the point of starting a request,40+ prior to any writes succeeding.41+ """42+43+44 class HttpError(Exception):45 """39- An Http error occurred.46+ An HTTP error occurred.47 """48 49 50 class ProtocolError(Exception):85 unmodified linesmodified:tests/dispatch/test_http2.py+19 added
57 unmodified lines58 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}59 60 assert response_3.status_code == 20061 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}62+63+64+def test_http2_reconnect():65+ """66+ If a connection has been dropped between requests, then we should67+ be seemlessly reconnected.68+ """69+ backend = MockHTTP2Backend(app=app)70+71+ with Client(backend=backend) as client:72+ response_1 = client.get("http://example.org/1")73+ backend.server.raise_disconnect = True74+ response_2 = client.get("http://example.org/2")75+76+ assert response_1.status_code == 20077+ assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}78+79+ assert response_2.status_code == 20080+ assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}modified:tests/dispatch/utils.py+7 added-2 removed
17 unmodified lines18 19 class MockHTTP2Backend(AsyncioBackend):20 def __init__(self, app):21 self.app = app22+ self.server = None23 24 async def connect(25 self,26 hostname: str,27 port: int,28 ssl_context: typing.Optional[ssl.SSLContext],29 timeout: TimeoutConfig,30 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:30- server = MockHTTP2Server(self.app)31- return (server, server, Protocol.HTTP_2)31+ self.server = MockHTTP2Server(self.app)32+ return (self.server, self.server, Protocol.HTTP_2)33 34 35 class MockHTTP2Server(BaseReader, BaseWriter):36 """5 unmodified lines42 self.conn = h2.connection.H2Connection(config=config)43 self.app = app44 self.buffer = b""45 self.requests = {}46+ self.raise_disconnect = False47 48 # BaseReader interface49 50 async def read(self, n, timeout, flag=None) -> bytes:3 unmodified lines54 55 # BaseWriter interface56 57 def write_no_block(self, data: bytes) -> None:58+ if self.raise_disconnect:59+ self.raise_disconnect = False60+ raise ConnectionResetError()61 events = self.conn.receive_data(data)62 self.buffer += self.conn.data_to_send()63 for event in events:64 if isinstance(event, h2.events.RequestReceived):58 unmodified linesmodified:setup.py+1 added-1 removed
9 unmodified lines10 def get_version(package):11 """12 Return package version as listed in `__version__` in `init.py`.13 """14- with open(os.path.join(package, "__init__.py")) as f:14+ with open(os.path.join(package, "__version__.py")) as f:15 return re.search("__version__ = ['\"]([^'\"]+)['\"]", f.read()).group(1)16 17 18 def get_long_description():52 unmodified lines