Skip to content
Myr

Check disconnections on connection reacquiry (#145)

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

* Detect EOF signaling remote server closed connection Raise ConnectionClosedByRemote and handle on `send` * Fix linting * Use existing NotConnected exception * Add `Reader.is_connection_dropped` method * Check connection before sending h11 events as well * Add test covering connection lost before reading response content * Check for connection closed on acquiring it from the pool * Clean up ConnectionPool logic around reaquiry of connections

authored by Tom Christie · committed by GitHub · parent 8db36ed · Browse files · 11 files+78 added−51 removed
This commit

State

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

Diff stats

11 files+78 added−51 removed

  • tests:+42 added−6 removed
  • other:+36 added−45 removed

11 files+78 added−51 removed

modified:httpx/dispatch/connection_pool.py+15 added-26 removed
7 unmodified lines
8 PoolLimits,9 TimeoutTypes,10 VerifyTypes,11)12from ..exceptions import NotConnected12from ..interfaces import AsyncDispatcher, ConcurrencyBackend13from ..models import AsyncRequest, AsyncResponse, Origin14from .connection import HTTPConnection15
90 unmodified lines
106 verify: VerifyTypes = None,107 cert: CertTypes = None,108 timeout: TimeoutTypes = None,109 ) -> AsyncResponse:111 allow_connection_reuse = True112 connection = None113 while connection is None:114 connection = await self.acquire_connection(115 origin=request.url.origin, allow_connection_reuse=allow_connection_reuse110 connection = await self.acquire_connection(origin=request.url.origin)111 try:112 response = await connection.send(113 request, verify=verify, cert=cert, timeout=timeout114 )117 try:118 response = await connection.send(119 request, verify=verify, cert=cert, timeout=timeout120 )121 except BaseException as exc:122 self.active_connections.remove(connection)123 self.max_connections.release()124 if isinstance(exc, NotConnected) and allow_connection_reuse:115 except BaseException as exc:116 self.active_connections.remove(connection)117 self.max_connections.release()118 raise exc125 connection = None126 allow_connection_reuse = False127 else:128 raise exc119120 return response121132 async def acquire_connection(133 self, origin: Origin, allow_connection_reuse: bool = True134 ) -> HTTPConnection:135 connection = None136 if allow_connection_reuse:137 connection = self.active_connections.pop_by_origin(origin, http2_only=True)138 if connection is None:139 connection = self.keepalive_connections.pop_by_origin(origin)122 async def acquire_connection(self, origin: Origin) -> HTTPConnection:123 connection = self.active_connections.pop_by_origin(origin, http2_only=True)124 if connection is None:125 connection = self.keepalive_connections.pop_by_origin(origin)126127 if connection is not None and connection.is_connection_dropped():128 connection = None129130 if connection is None:131 await self.max_connections.acquire()132 connection = HTTPConnection(133 origin,
32 unmodified lines
modified:httpx/dispatch/connection.py+7 added
100 unmodified lines
101 return self.h2_connection.is_closed102 else:103 assert self.h11_connection is not None104 return self.h11_connection.is_closed105106 def is_connection_dropped(self) -> bool:107 if self.h2_connection is not None:108 return self.h2_connection.is_connection_dropped()109 else:110 assert self.h11_connection is not None111 return self.h11_connection.is_connection_dropped()
modified:httpx/dispatch/http11.py+4 added-7 removed
2 unmodified lines
3import h1145from ..concurrency import TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes7from ..exceptions import NotConnected7from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend8from ..models import AsyncRequest, AsyncResponse910H11Event = typing.Union[
33 unmodified lines
44 self, request: AsyncRequest, timeout: TimeoutTypes = None45 ) -> AsyncResponse:46 timeout = None if timeout is None else TimeoutConfig(timeout)4749 try:50 await self._send_request(request, timeout)48 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 None4950 task, args = self._send_request_data, [request.stream(), timeout]51 async with self.backend.background_manager(task, args=args):52 http_version, status_code, headers = await self._receive_response(timeout)
128 unmodified lines
181182 @property183 def is_closed(self) -> bool:184 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)185186 def is_connection_dropped(self) -> bool:187 return self.reader.is_connection_dropped()
modified:httpx/dispatch/http2.py+4 added-5 removed
4 unmodified lines
5import h2.events67from ..concurrency import TimeoutFlag8from ..config import TimeoutConfig, TimeoutTypes9from ..exceptions import NotConnected9from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend10from ..models import AsyncRequest, AsyncResponse1112
24 unmodified lines
37 #  Start sending the request.38 if not self.initialized:39 self.initiate_connection()4042 try:43 stream_id = await self.send_headers(request, timeout)41 stream_id = await self.send_headers(request, timeout)44 except ConnectionResetError:45 raise NotConnected() from None4243 self.events[stream_id] = []44 self.timeout_flags[stream_id] = TimeoutFlag()45
125 unmodified lines
171172 @property173 def is_closed(self) -> bool:174 return False175176 def is_connection_dropped(self) -> bool:177 return self.reader.is_connection_dropped()
modified:httpx/concurrency.py+3 added
106 unmodified lines
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 = timeout
156 unmodified lines
modified:httpx/exceptions.py-7 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 """424337class HttpError(Exception):38 """39 An HTTP error occurred.40 """
88 unmodified lines
modified:httpx/interfaces.py+3 added
128 unmodified lines
129 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None130 ) -> bytes:131 raise NotImplementedError() # pragma: no cover132133 def is_connection_dropped(self) -> bool:134 raise NotImplementedError() # pragma: no cover135136137class BaseWriter:138 """139 A stream writer. Abstracts away any asyncio-specfic interfaces140 into a more generic base class, that we can use with alternate
90 unmodified lines
modified:tests/dispatch/test_connection_pools.py+36 added
129 unmodified lines
130 response = await http.request("GET", "http://127.0.0.1:8000/")131 await response.close()132 assert len(http.active_connections) == 0133 assert len(http.keepalive_connections) == 0134135136@pytest.mark.asyncio137async def test_keepalive_connection_closed_by_server_is_reestablished(server):138 """139 Upon keep-alive connection closed by remote a new connection should be reestablished.140 """141 async with httpx.ConnectionPool() as http:142 response = await http.request("GET", "http://127.0.0.1:8000/")143 await response.read()144145 await server.shutdown() # shutdown the server to close the keep-alive connection146 await server.startup()147148 response = await http.request("GET", "http://127.0.0.1:8000/")149 await response.read()150 assert len(http.active_connections) == 0151 assert len(http.keepalive_connections) == 1152153154@pytest.mark.asyncio155async def test_keepalive_http2_connection_closed_by_server_is_reestablished(server):156 """157 Upon keep-alive connection closed by remote a new connection should be reestablished.158 """159 async with httpx.ConnectionPool() as http:160 response = await http.request("GET", "http://127.0.0.1:8000/")161 await response.read()162163 await server.shutdown() # shutdown the server to close the keep-alive connection164 await server.startup()165166 response = await http.request("GET", "http://127.0.0.1:8000/")167 await response.read()168 assert len(http.active_connections) == 0169 assert len(http.keepalive_connections) == 1
modified:tests/dispatch/test_http2.py+1 added-1 removed
66 unmodified lines
67 backend = MockHTTP2Backend(app=app)6869 with Client(backend=backend) as client:70 response_1 = client.get("http://example.org/1")71 backend.server.raise_disconnect = True71 backend.server.close_connection = True72 response_2 = client.get("http://example.org/2")7374 assert response_1.status_code == 20075 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}
3 unmodified lines
modified:tests/dispatch/utils.py+4 added-4 removed
41 unmodified lines
42 self.conn = h2.connection.H2Connection(config=config)43 self.app = app44 self.buffer = b""45 self.requests = {}46 self.raise_disconnect = False46 self.close_connection = 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()58 events = self.conn.receive_data(data)59 self.buffer += self.conn.data_to_send()60 for event in events:61 if isinstance(event, h2.events.RequestReceived):
8 unmodified lines
7071 async def close(self) -> None:72 pass7374 def is_connection_dropped(self) -> bool:75 return self.close_connection7677 # Server implementation7879 def request_received(self, headers, stream_id):80 """
42 unmodified lines
modified:tests/test_multipart.py+1 added-1 removed
8 unmodified lines
9from httpx import (10 CertTypes,11 Client,12 Dispatcher,13 multipart,13 Request,14 Response,15 TimeoutTypes,16 VerifyTypes,17 multipart,18)192021class MockDispatch(Dispatcher):
103 unmodified lines