Skip to content
Myr

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

7 files+76 added−21 removed

modified:http3/dispatch/connection_pool.py+27 added-13 removed
9 unmodified lines
10 TimeoutTypes,11 VerifyTypes,12)13from ..decoders import ACCEPT_ENCODING14from ..exceptions import PoolTimeout14from ..exceptions import NotConnected, PoolTimeout15from ..interfaces import AsyncDispatcher, ConcurrencyBackend16from ..models import AsyncRequest, AsyncResponse, Origin17from .connection import HTTPConnection18
90 unmodified lines
109 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 exc131132 return response133134 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)142143 if connection is None:144 await self.max_connections.acquire()145 connection = HTTPConnection(
33 unmodified lines
modified:http3/dispatch/http11.py+8 added-2 removed
2 unmodified lines
3import h1145from ..concurrency import TimeoutFlag6from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes7from ..exceptions import ConnectTimeout, ReadTimeout7from ..exceptions import ConnectTimeout, NotConnected, ReadTimeout8from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend9from ..models import AsyncRequest, AsyncResponse1011H11Event = typing.Union[
33 unmodified lines
45 self, request: AsyncRequest, timeout: TimeoutTypes = None46 ) -> AsyncResponse:47 timeout = None if timeout is None else TimeoutConfig(timeout)4849 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 None5556 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 lines
modified:http3/dispatch/http2.py+6 added-2 removed
4 unmodified lines
5import h2.events67from ..concurrency import TimeoutFlag8from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes9from ..exceptions import ConnectTimeout, ReadTimeout9from ..exceptions import ConnectTimeout, NotConnected, ReadTimeout10from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend11from ..models import AsyncRequest, AsyncResponse1213
24 unmodified lines
38 #  Start sending the request.39 if not self.initialized:40 self.initiate_connection()4142 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 None4647 self.events[stream_id] = []48 self.timeout_flags[stream_id] = TimeoutFlag()4950 task, args = self.send_request_data, [stream_id, request.stream(), timeout]
128 unmodified lines
modified:http3/exceptions.py+8 added-1 removed
32 unmodified lines
3334# HTTP exceptions...353637class NotConnected(Exception):38 """39 A connection was lost at the point of starting a request,40 prior to any writes succeeding.41 """424344class HttpError(Exception):45 """39 An Http error occurred.46 An HTTP error occurred.47 """484950class ProtocolError(Exception):
85 unmodified lines
modified:tests/dispatch/test_http2.py+19 added
57 unmodified lines
58 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}5960 assert response_3.status_code == 20061 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}626364def 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)7071 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")7576 assert response_1.status_code == 20077 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}7879 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 lines
1819class MockHTTP2Backend(AsyncioBackend):20 def __init__(self, app):21 self.app = app22 self.server = None2324 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)333435class MockHTTP2Server(BaseReader, BaseWriter):36 """
5 unmodified lines
42 self.conn = h2.connection.H2Connection(config=config)43 self.app = app44 self.buffer = b""45 self.requests = {}46 self.raise_disconnect = False4748 # BaseReader interface4950 async def read(self, n, timeout, flag=None) -> bytes:
3 unmodified lines
5455 # BaseWriter interface5657 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 lines
modified:setup.py+1 added-1 removed
9 unmodified lines
10def 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)161718def get_long_description():
52 unmodified lines