Handle early connection closes (#103)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Refactoring h11 implementation * More h11 refactoring * Support early connection closes on H11 connections * Tweak comment * Refactor concurrent read/writes * Drop WriteTimeout masking * Linting * Use concurrent read/writes for HTTP2 * Push background sending into ConcurrencyBackend
authored by Tom Christie · committed by GitHub · parent f9e3ad4 · Browse files · 8 files·+190 added−74 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+190 added−74 removed
- tests:+3 added−1 removed
- other:+187 added−73 removed
Provenance
- Commit
b9c8a15- Tree
efa0c43- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
f9e3ad4
8 files changed+190 added−74 removed
modified:http3/dispatch/connection.py+4 added-2 removed
80 unmodified lines81 reader, writer, protocol = await self.backend.connect(82 host, port, ssl_context, timeout83 )84 if protocol == Protocol.HTTP_2:85- self.h2_connection = HTTP2Connection(reader, writer, on_release=on_release)85+ self.h2_connection = HTTP2Connection(86+ reader, writer, self.backend, on_release=on_release87+ )88 else:89 self.h11_connection = HTTP11Connection(88- reader, writer, on_release=on_release90+ reader, writer, self.backend, on_release=on_release91 )92 93 async def close(self) -> None:94 if self.h2_connection is not None:15 unmodified linesmodified:http3/dispatch/http11.py+94 added-45 removed
2 unmodified lines3 import h114 5 from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes6 from ..exceptions import ConnectTimeout, ReadTimeout7-from ..interfaces import BaseReader, BaseWriter7+from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend8 from ..models import AsyncRequest, AsyncResponse9 10 H11Event = typing.Union[11 h11.Request,17 unmodified lines29 def __init__(30 self,31 reader: BaseReader,32 writer: BaseWriter,33+ backend: ConcurrencyBackend,34 on_release: typing.Optional[OnReleaseCallback] = None,35 ):36 self.reader = reader37 self.writer = writer38+ self.backend = backend39 self.on_release = on_release40 self.h11_state = h11.Connection(our_role=h11.CLIENT)41 42 async def send(43 self, request: AsyncRequest, timeout: TimeoutTypes = None44 ) -> AsyncResponse:45 timeout = None if timeout is None else TimeoutConfig(timeout)46 45- # Start sending the request.46- method = request.method.encode("ascii")47- target = request.url.full_path.encode("ascii")48- headers = request.headers.raw49- if "Host" not in request.headers:50- host = request.url.authority.encode("ascii")51- headers = [(b"host", host)] + headers52- event = h11.Request(method=method, target=target, headers=headers)53- await self._send_event(event, timeout)47+ await self._send_request(request, timeout)48+ task, args = self._send_request_data, [request.stream(), timeout]49+ async with self.backend.background_manager(task, args=args):50+ status_code, headers = await self._receive_response(timeout)51+ content = self._receive_response_data(timeout)52 55- # Send the request body.56- async for data in request.stream():57- event = h11.Data(data=data)58- await self._send_event(event, timeout)59-60- # Finalize sending the request.61- event = h11.EndOfMessage()62- await self._send_event(event, timeout)63-64- # Start getting the response.65- event = await self._receive_event(timeout)66- if isinstance(event, h11.InformationalResponse):67- event = await self._receive_event(timeout)68-69- assert isinstance(event, h11.Response)70- status_code = event.status_code71- headers = event.headers72- content = self._body_iter(timeout)73-53 return AsyncResponse(54 status_code=status_code,55 protocol="HTTP/1.1",56 headers=headers,3 unmodified lines60 )61 62 async def close(self) -> None:63 event = h11.ConnectionClosed()64+ try:85- self.h11_state.send(event)65+ self.h11_state.send(event)66+ except h11.LocalProtocolError as exc: # pragma: no cover67+ # Premature client disconnect68+ pass69 await self.writer.close()70 88- async def _body_iter(71+ async def _send_request(72+ self, request: AsyncRequest, timeout: TimeoutConfig = None73+ ) -> None:74+ """75+ Send the request method, URL, and headers to the network.76+ """77+ method = request.method.encode("ascii")78+ target = request.url.full_path.encode("ascii")79+ headers = request.headers.raw80+ if "Host" not in request.headers:81+ host = request.url.authority.encode("ascii")82+ headers = [(b"host", host)] + headers83+ event = h11.Request(method=method, target=target, headers=headers)84+ await self._send_event(event, timeout)85+86+ async def _send_request_data(87+ self, data: typing.AsyncIterator[bytes], timeout: TimeoutConfig = None88+ ) -> None:89+ """90+ Send the request body to the network.91+ """92+ try:93+ # Send the request body.94+ async for chunk in data:95+ event = h11.Data(data=chunk)96+ await self._send_event(event, timeout)97+98+ # Finalize sending the request.99+ event = h11.EndOfMessage()100+ await self._send_event(event, timeout)101+ except OSError: # pragma: nocover102+ # Once we've sent the initial part of the request we don't actually103+ # care about connection errors that occur when sending the body.104+ # Ignore these, and defer to any exceptions on reading the response.105+ self.h11_state.send_failed()106+107+ async def _send_event(self, event: H11Event, timeout: TimeoutConfig = None) -> None:108+ """109+ Send a single `h11` event to the network, waiting for the data to110+ drain before returning.111+ """112+ bytes_to_send = self.h11_state.send(event)113+ await self.writer.write(bytes_to_send, timeout)114+115+ async def _receive_response(116 self, timeout: TimeoutConfig = None117+ ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:118+ """119+ Read the response status and headers from the network.120+ """121+ while True:122+ event = await self._receive_event(timeout)123+ if isinstance(event, h11.InformationalResponse):124+ continue125+ else:126+ assert isinstance(event, h11.Response)127+ break128+ return (event.status_code, event.headers)129+130+ async def _receive_response_data(131+ self, timeout: TimeoutConfig = None132 ) -> typing.AsyncIterator[bytes]:91- event = await self._receive_event(timeout)92- while isinstance(event, h11.Data):93- yield event.data133+ """134+ Read the response data from the network.135+ """136+ while True:137 event = await self._receive_event(timeout)138+ if isinstance(event, h11.Data):139+ yield event.data140+ else:95- assert isinstance(event, h11.EndOfMessage)141+ assert isinstance(event, h11.EndOfMessage)142+ break143 97- async def _send_event(self, event: H11Event, timeout: TimeoutConfig = None) -> None:98- data = self.h11_state.send(event)99- await self.writer.write(data, timeout)100-144 async def _receive_event(self, timeout: TimeoutConfig = None) -> H11Event:102- event = self.h11_state.next_event()103-104- while event is h11.NEED_DATA:105- data = await self.reader.read(self.READ_NUM_BYTES, timeout)106- self.h11_state.receive_data(data)145+ """146+ Read a single `h11` event, reading more data from the network if needed.147+ """148+ while True:149 event = self.h11_state.next_event()108-150+ if event is h11.NEED_DATA:151+ try:152+ data = await self.reader.read(self.READ_NUM_BYTES, timeout)153+ except OSError: # pragma: nocover154+ data = b""155+ self.h11_state.receive_data(data)156+ else:157+ break158 return event159 160 async def response_closed(self) -> None:161 if (13 unmodified linesmodified:http3/dispatch/http2.py+41 added-24 removed
4 unmodified lines5 import h2.events6 7 from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes8 from ..exceptions import ConnectTimeout, ReadTimeout9-from ..interfaces import BaseReader, BaseWriter9+from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend10 from ..models import AsyncRequest, AsyncResponse11 12 13 class HTTP2Connection:14 READ_NUM_BYTES = 409615 16 def __init__(17- self, reader: BaseReader, writer: BaseWriter, on_release: typing.Callable = None17+ self,18+ reader: BaseReader,19+ writer: BaseWriter,20+ backend: ConcurrencyBackend,21+ on_release: typing.Callable = None,22 ):23 self.reader = reader24 self.writer = writer25+ self.backend = backend26 self.on_release = on_release27 self.h2_state = h2.connection.H2Connection()28 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]29 self.initialized = False9 unmodified lines39 40 stream_id = await self.send_headers(request, timeout)41 self.events[stream_id] = []42 38- # Send the request body.39- async for data in request.stream():40- await self.send_data(stream_id, data, timeout)41-42- # Finalize sending the request.43- await self.end_stream(stream_id, timeout)44-45- # Start getting the response.46- while True:47- event = await self.receive_event(stream_id, timeout)48- if isinstance(event, h2.events.ResponseReceived):49- break50-51- status_code = 20052- headers = []53- for k, v in event.headers:54- if k == b":status":55- status_code = int(v.decode("ascii", errors="ignore"))56- elif not k.startswith(b":"):57- headers.append((k, v))58-43+ task, args = self.send_request_data, [stream_id, request.stream(), timeout]44+ async with self.backend.background_manager(task, args=args):45+ status_code, headers = await self.receive_response(stream_id, timeout)46 content = self.body_iter(stream_id, timeout)47 on_close = functools.partial(self.response_closed, stream_id=stream_id)48 49 return AsyncResponse(28 unmodified lines78 data_to_send = self.h2_state.data_to_send()79 await self.writer.write(data_to_send, timeout)80 return stream_id81 82+ async def send_request_data(83+ self,84+ stream_id: int,85+ stream: typing.AsyncIterator[bytes],86+ timeout: TimeoutConfig = None,87+ ) -> None:88+ async for data in stream:89+ await self.send_data(stream_id, data, timeout)90+ await self.end_stream(stream_id, timeout)91+92 async def send_data(93 self, stream_id: int, data: bytes, timeout: TimeoutConfig = None94 ) -> None:95 flow_control = self.h2_state.local_flow_control_window(stream_id)96 chunk_size = min(len(data), flow_control)97 for idx in range(0, len(data), chunk_size):101- chunk = data[idx:idx+chunk_size]98+ chunk = data[idx : idx + chunk_size]99 self.h2_state.send_data(stream_id, chunk)100 data_to_send = self.h2_state.data_to_send()101 await self.writer.write(data_to_send, timeout)102 1 unmodified line104 self.h2_state.end_stream(stream_id)105 data_to_send = self.h2_state.data_to_send()106 await self.writer.write(data_to_send, timeout)107 108+ async def receive_response(109+ self, stream_id: int, timeout: TimeoutConfig = None110+ ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:111+ """112+ Read the response status and headers from the network.113+ """114+ while True:115+ event = await self.receive_event(stream_id, timeout)116+ if isinstance(event, h2.events.ResponseReceived):117+ break118+119+ status_code = 200120+ headers = []121+ for k, v in event.headers:122+ if k == b":status":123+ status_code = int(v.decode("ascii", errors="ignore"))124+ elif not k.startswith(b":"):125+ headers.append((k, v))126+ return (status_code, headers)127+128 async def body_iter(129 self, stream_id: int, timeout: TimeoutConfig = None130 ) -> typing.AsyncIterator[bytes]:131 while True:31 unmodified linesmodified:http3/client.py+1 added-1 removed
79 unmodified lines80 else:81 async_dispatch = dispatch82 83 if base_url is None:84- self.base_url = URL('', allow_relative=True)84+ self.base_url = URL("", allow_relative=True)85 else:86 self.base_url = URL(base_url)87 88 self.auth = auth793 unmodified linesmodified:http3/concurrency.py+29 added-1 removed
10 unmodified lines11 import asyncio12 import functools13 import ssl14 import typing15+from types import TracebackType16 17 from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig18 from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19 from .interfaces import (20+ BaseBackgroundManager,21 BasePoolSemaphore,22 BaseReader,23 BaseWriter,24 ConcurrencyBackend,17 unmodified lines42 43 _write = MonkeyPatch.write44 45 def _fixed_write(self, data: bytes) -> None: # type: ignore44- if not self._loop.is_closed():46+ if self._loop and not self._loop.is_closed():47 _write(self, data)48 49 MonkeyPatch.write = _fixed_write50 143 unmodified lines194 self._loop = loop195 196 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:197 return PoolSemaphore(limits)198+199+ def background_manager(200+ self, coroutine: typing.Callable, args: typing.Any201+ ) -> "BackgroundManager":202+ return BackgroundManager(coroutine, args)203+204+205+class BackgroundManager(BaseBackgroundManager):206+ def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:207+ self.coroutine = coroutine208+ self.args = args209+210+ async def __aenter__(self) -> "BackgroundManager":211+ loop = asyncio.get_event_loop()212+ self.task = loop.create_task(self.coroutine(*self.args))213+ return self214+215+ async def __aexit__(216+ self,217+ exc_type: typing.Type[BaseException] = None,218+ exc_value: BaseException = None,219+ traceback: TracebackType = None,220+ ) -> None:221+ await self.task222+ if exc_type is None:223+ self.task.result()modified:http3/interfaces.py+18 added
205 unmodified lines206 try:207 yield self.run(async_iterator.__anext__)208 except StopAsyncIteration:209 break210+211+ def background_manager(212+ self, coroutine: typing.Callable, args: typing.Any213+ ) -> "BaseBackgroundManager":214+ raise NotImplementedError() # pragma: no cover215+216+217+class BaseBackgroundManager:218+ async def __aenter__(self) -> "BaseBackgroundManager":219+ raise NotImplementedError() # pragma: no cover220+221+ async def __aexit__(222+ self,223+ exc_type: typing.Type[BaseException] = None,224+ exc_value: BaseException = None,225+ traceback: TracebackType = None,226+ ) -> None:227+ raise NotImplementedError() # pragma: no covermodified:tests/client/test_client.py+1 added-1 removed
145 unmodified lines146 @threadpool147 def test_base_url(server):148 base_url = "http://127.0.0.1:8000/"149 with http3.Client(base_url=base_url) as http:150- response = http.get('/')150+ response = http.get("/")151 assert response.status_code == 200152 assert str(response.url) == base_urlmodified:tests/dispatch/utils.py+2 added
1+import asyncio2 import ssl3 import typing4 5 import h2.config39 unmodified lines45 46 # BaseReader interface47 48 async def read(self, n, timeout) -> bytes:49+ await asyncio.sleep(0)50 send, self.buffer = self.buffer[:n], self.buffer[n:]51 return send52 53 # BaseWriter interface64 unmodified lines