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
Provenance
- Commit
ec365c0- Tree
252a5bd- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
8db36ed
11 files changed+78 added−51 removed
modified:httpx/dispatch/connection_pool.py+15 added-26 removed
7 unmodified lines8 PoolLimits,9 TimeoutTypes,10 VerifyTypes,11 )12-from ..exceptions import NotConnected12 from ..interfaces import AsyncDispatcher, ConcurrencyBackend13 from ..models import AsyncRequest, AsyncResponse, Origin14 from .connection import HTTPConnection15 90 unmodified lines106 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 exc119 120 return response121 132- 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)126 127+ if connection is not None and connection.is_connection_dropped():128+ connection = None129+130 if connection is None:131 await self.max_connections.acquire()132 connection = HTTPConnection(133 origin,32 unmodified linesmodified:httpx/dispatch/connection.py+7 added
100 unmodified lines101 return self.h2_connection.is_closed102 else:103 assert self.h11_connection is not None104 return self.h11_connection.is_closed105+106+ 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 lines3 import h114 5 from ..concurrency import TimeoutFlag6 from ..config import TimeoutConfig, TimeoutTypes7-from ..exceptions import NotConnected7 from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend8 from ..models import AsyncRequest, AsyncResponse9 10 H11Event = typing.Union[33 unmodified lines44 self, request: AsyncRequest, timeout: TimeoutTypes = None45 ) -> AsyncResponse:46 timeout = None if timeout is None else TimeoutConfig(timeout)47 49- 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 None49 50 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 lines181 182 @property183 def is_closed(self) -> bool:184 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)185+186+ def is_connection_dropped(self) -> bool:187+ return self.reader.is_connection_dropped()modified:httpx/dispatch/http2.py+4 added-5 removed
4 unmodified lines5 import h2.events6 7 from ..concurrency import TimeoutFlag8 from ..config import TimeoutConfig, TimeoutTypes9-from ..exceptions import NotConnected9 from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend10 from ..models import AsyncRequest, AsyncResponse11 12 24 unmodified lines37 # Start sending the request.38 if not self.initialized:39 self.initiate_connection()40 42- 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 None42 43 self.events[stream_id] = []44 self.timeout_flags[stream_id] = TimeoutFlag()45 125 unmodified lines171 172 @property173 def is_closed(self) -> bool:174 return False175+176+ def is_connection_dropped(self) -> bool:177+ return self.reader.is_connection_dropped()modified:httpx/concurrency.py+3 added
106 unmodified lines107 raise ReadTimeout() from None108 109 return data110 111+ def is_connection_dropped(self) -> bool:112+ return self.stream_reader.at_eof()113 114+115 class Writer(BaseWriter):116 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):117 self.stream_writer = stream_writer118 self.timeout = timeout156 unmodified linesmodified:httpx/exceptions.py-7 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-37 class HttpError(Exception):38 """39 An HTTP error occurred.40 """88 unmodified linesmodified:httpx/interfaces.py+3 added
128 unmodified lines129 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None130 ) -> bytes:131 raise NotImplementedError() # pragma: no cover132 133+ def is_connection_dropped(self) -> bool:134+ raise NotImplementedError() # pragma: no cover135 136+137 class BaseWriter:138 """139 A stream writer. Abstracts away any asyncio-specfic interfaces140 into a more generic base class, that we can use with alternate90 unmodified linesmodified:tests/dispatch/test_connection_pools.py+36 added
129 unmodified lines130 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) == 0134+135+136+@pytest.mark.asyncio137+async 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()144+145+ await server.shutdown() # shutdown the server to close the keep-alive connection146+ await server.startup()147+148+ 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) == 1152+153+154+@pytest.mark.asyncio155+async 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()162+163+ await server.shutdown() # shutdown the server to close the keep-alive connection164+ await server.startup()165+166+ 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) == 1modified:tests/dispatch/test_http2.py+1 added-1 removed
66 unmodified lines67 backend = MockHTTP2Backend(app=app)68 69 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")73 74 assert response_1.status_code == 20075 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}3 unmodified linesmodified:tests/dispatch/utils.py+4 added-4 removed
41 unmodified lines42 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 = 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()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 lines70 71 async def close(self) -> None:72 pass73 74+ def is_connection_dropped(self) -> bool:75+ return self.close_connection76+77 # Server implementation78 79 def request_received(self, headers, stream_id):80 """42 unmodified linesmodified:tests/test_multipart.py+1 added-1 removed
8 unmodified lines9 from httpx import (10 CertTypes,11 Client,12 Dispatcher,13- multipart,13 Request,14 Response,15 TimeoutTypes,16 VerifyTypes,17+ multipart,18 )19 20 21 class MockDispatch(Dispatcher):103 unmodified lines