Skip to content
Myr

Fix bug in calculating maximum frame size (#153)

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

authored by IsaacBenghiat · committed by Seth Michael Larson · parent 3065dd6 · Browse files · 4 files+118 added−15 removed
This commit

State

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

Diff stats

4 files+118 added−15 removed

  • tests:+73 added−1 removed
  • other:+45 added−14 removed

4 files+118 added−15 removed

modified:httpx/concurrency/base.py+3 added
86 unmodified lines
8788 def is_set(self) -> bool:89 raise NotImplementedError() # pragma: no cover9091 def clear(self) -> None:92 raise NotImplementedError() # pragma: no cover9394 async def wait(self) -> None:95 raise NotImplementedError() # pragma: no cover9697
92 unmodified lines
modified:httpx/dispatch/http2.py+42 added-14 removed
2 unmodified lines
34import h2.connection5import h2.events67from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag7from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag, BaseEvent8from ..config import TimeoutConfig, TimeoutTypes9from ..models import AsyncRequest, AsyncResponse10from ..utils import get_logger11
15 unmodified lines
27 self.h2_state = h2.connection.H2Connection()28 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]29 self.timeout_flags = {} # type: typing.Dict[int, TimeoutFlag]30 self.initialized = False31 self.window_update_received = {} # type: typing.Dict[int, BaseEvent]3233 async def send(34 self, request: AsyncRequest, timeout: TimeoutTypes = None35 ) -> AsyncResponse:
6 unmodified lines
42 stream_id = await self.send_headers(request, timeout)4344 self.events[stream_id] = []45 self.timeout_flags[stream_id] = TimeoutFlag()46 self.window_update_received[stream_id] = self.backend.create_event()4748 task, args = self.send_request_data, [stream_id, request.stream(), timeout]49 async with self.backend.background_manager(task, *args):50 status_code, headers = await self.receive_response(stream_id, timeout)
58 unmodified lines
109110 async def send_data(111 self, stream_id: int, data: bytes, timeout: TimeoutConfig = None112 ) -> None:111 flow_control = self.h2_state.local_flow_control_window(stream_id)112 chunk_size = min(len(data), flow_control)113 for idx in range(0, len(data), chunk_size):114 chunk = data[idx : idx + chunk_size]115116 logger.debug(117 f"send_data stream_id={stream_id} data=Data(<{len(chunk)} bytes>)"113 while data:114 # The data will be divided into frames to send based on the flow control115 # window and the maximum frame size. Because the flow control window116 # can decrease in size, even possibly to zero, this will loop until all the117 # data is sent. In http2 specification:118 # https://tools.ietf.org/html/rfc7540#section-6.9119 flow_control = self.h2_state.local_flow_control_window(stream_id)120 chunk_size = min(121 len(data), flow_control, self.h2_state.max_outbound_frame_size122 )123 if chunk_size == 0:124 # this means that the flow control window is 0 (either for the stream125 # or the connection one), and no data can be sent until the flow control126 # window is updated.127 await self.window_update_received[stream_id].wait()128 self.window_update_received[stream_id].clear()129 else:130 chunk, data = data[:chunk_size], data[chunk_size:]131 self.h2_state.send_data(stream_id, chunk)132 data_to_send = self.h2_state.data_to_send()133 await self.stream.write(data_to_send, timeout)134120 self.h2_state.send_data(stream_id, chunk)121 data_to_send = self.h2_state.data_to_send()122 await self.stream.write(data_to_send, timeout)123135 async def end_stream(self, stream_id: int, timeout: TimeoutConfig = None) -> None:136 logger.debug(f"end_stream stream_id={stream_id}")137 self.h2_state.end_stream(stream_id)138 data_to_send = self.h2_state.data_to_send()
19 unmodified lines
158 if k == b":status":159 status_code = int(v.decode("ascii", errors="ignore"))160 elif not k.startswith(b":"):161 headers.append((k, v))151 return status_code, headers162163 return (status_code, headers)164165 async def body_iter(166 self, stream_id: int, timeout: TimeoutConfig = None167 ) -> typing.AsyncIterator[bytes]:168 while True:169 event = await self.receive_event(stream_id, timeout)170 if isinstance(event, h2.events.DataReceived):159 self.h2_state.acknowledge_received_data(len(event.data), stream_id)171 self.h2_state.acknowledge_received_data(172 event.flow_controlled_length, stream_id173 )174 yield event.data175 elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):176 break177
8 unmodified lines
186 event_stream_id = getattr(event, "stream_id", 0)187 logger.debug(188 f"receive_event stream_id={event_stream_id} event={event!r}"189 )190 if isinstance(event, h2.events.WindowUpdated):191 if event_stream_id == 0:192 for window_update_event in self.window_update_received.values():193 window_update_event.set()194 else:195 try:196 self.window_update_received[event_stream_id].set()197 except KeyError:198 # the window_update_received dictionary is only relevant199 # when sending data, which should never raise a KeyError200 # here.201 pass202203 if event_stream_id:204 self.events[event.stream_id].append(event)205206 data_to_send = self.h2_state.data_to_send()
3 unmodified lines
210211 async def response_closed(self, stream_id: int) -> None:212 del self.events[stream_id]213 del self.timeout_flags[stream_id]214 del self.window_update_received[stream_id]215216 if not self.events and self.on_release is not None:217 await self.on_release()218
6 unmodified lines
modified:tests/dispatch/test_http2.py+28 added
63 unmodified lines
64 "body": "<data>",65 }666768def test_http2_large_post_request():69 backend = MockHTTP2Backend(app=app)7071 data = b"a" * 10000072 with Client(backend=backend) as client:73 response = client.post("http://example.org", data=data)74 assert response.status_code == 20075 assert json.loads(response.content) == {76 "method": "POST",77 "path": "/",78 "body": data.decode(),79 }808182async def test_async_http2_large_post_request(backend):83 backend = MockHTTP2Backend(app=app, backend=backend)8485 data = b"a" * 10000086 async with AsyncClient(backend=backend) as client:87 response = await client.post("http://example.org", data=data)88 assert response.status_code == 20089 assert json.loads(response.content) == {90 "method": "POST",91 "path": "/",92 "body": data.decode(),93 }949596def test_http2_multiple_requests():97 backend = MockHTTP2Backend(app=app)9899 with Client(backend=backend) as client:
68 unmodified lines
modified:tests/dispatch/utils.py+45 added-1 removed
37 unmodified lines
38 self.backend = backend39 self.buffer = b""40 self.requests = {}41 self.close_connection = False42 self.return_data = {}43 self.returning = {}4445 # Stream interface4647 def get_http_version(self) -> str:
11 unmodified lines
59 if isinstance(event, h2.events.RequestReceived):60 self.request_received(event.headers, event.stream_id)61 elif isinstance(event, h2.events.DataReceived):62 self.receive_data(event.data, event.stream_id)63 # This should send an UPDATE_WINDOW for both the stream and the64 # connection increasing it by the amount65 # consumed keeping the flow control window constant66 flow_control_consumed = event.flow_controlled_length67 if flow_control_consumed > 0:68 self.conn.increment_flow_control_window(flow_control_consumed)69 self.buffer += self.conn.data_to_send()70 self.conn.increment_flow_control_window(71 flow_control_consumed, event.stream_id72 )73 self.buffer += self.conn.data_to_send()74 elif isinstance(event, h2.events.StreamEnded):75 self.stream_complete(event.stream_id)76 elif isinstance(event, h2.events.WindowUpdated):77 if event.stream_id == 0:78 for key, value in self.returning.items():79 if value:80 self.send_return_data(key)81 # This will throw an error if the event is for a not-yet created stream82 elif self.returning[event.stream_id]:83 self.send_return_data(event.stream_id)8485 async def write(self, data: bytes, timeout) -> None:86 self.write_no_block(data)87
46 unmodified lines
134 status_code_bytes = str(response.status_code).encode("ascii")135 response_headers = [(b":status", status_code_bytes)] + response.headers.raw136137 self.conn.send_headers(stream_id, response_headers)117 self.conn.send_data(stream_id, response.content, end_stream=True)138 self.buffer += self.conn.data_to_send()139 self.return_data[stream_id] = response.content140 self.returning[stream_id] = True141 self.send_return_data(stream_id)142143 def send_return_data(self, stream_id):144 while self.return_data[stream_id]:145 flow_control = self.conn.local_flow_control_window(stream_id)146 chunk_size = min(147 len(self.return_data[stream_id]),148 flow_control,149 self.conn.max_outbound_frame_size,150 )151 if chunk_size == 0:152 return153 else:154 chunk, self.return_data[stream_id] = (155 self.return_data[stream_id][:chunk_size],156 self.return_data[stream_id][chunk_size:],157 )158 self.conn.send_data(stream_id, chunk)159 self.buffer += self.conn.data_to_send()160 self.returning[stream_id] = False161 self.conn.end_stream(stream_id)162 self.buffer += self.conn.data_to_send()