Skip to content
Myr

HTTP/2 refactoring (#612)

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

* HTTP/2 refactoring * Clean up flow control * Remove extra blank line

authored by Tom Christie · committed by GitHub · parent bc54dd0 · Browse files · 1 file+142 added−151 removed
This commit

State

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

Diff stats

1 file+142 added−151 removed

  • other:+142 added−151 removed

1 file+142 added−151 removed

modified:httpx/dispatch/http2.py+142 added-151 removed
1import functools1import typing23import h2.connection4import h2.events
2 unmodified lines
7from ..concurrency.base import (8 BaseEvent,9 BaseSocketStream,10 ConcurrencyBackend,12 TimeoutFlag,11 lookup_backend,12)13from ..config import Timeout14from ..exceptions import ProtocolError
14 unmodified lines
29 ):30 self.socket = socket31 self.backend = lookup_backend(backend)32 self.on_release = on_release35 self.h2_state = h2.connection.H2Connection()33 self.state = h2.connection.H2Connection()3435 self.streams = {} # type: typing.Dict[int, HTTP2Stream]36 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]37 self.timeout_flags = {} # type: typing.Dict[int, TimeoutFlag]38 self.window_update_received = {} # type: typing.Dict[int, BaseEvent]3738 self.init_started = False3940 @property
10 unmodified lines
51 if not self.init_started:52 # The very first stream is responsible for initiating the connection.53 self.init_started = True54 await self.send_connection_init(timeout)55 stream_id = self.state.get_next_available_stream_id()56 self.init_complete.set()57 else:58 # All other streams need to wait until the connection is established.59 await self.init_complete.wait()60 stream_id = self.state.get_next_available_stream_id()6162 stream_id = await self.send_headers(request, timeout)6362 stream = HTTP2Stream(stream_id=stream_id, connection=self, state=self.state)63 self.streams[stream_id] = stream64 self.events[stream_id] = []65 self.timeout_flags[stream_id] = TimeoutFlag()66 self.window_update_received[stream_id] = self.backend.create_event()65 return await stream.send(request, timeout)6668 status_code: typing.Optional[int] = None69 headers: typing.Optional[list] = None7071 async def receive_response(stream_id: int, timeout: Timeout) -> None:72 nonlocal status_code, headers73 status_code, headers = await self.receive_response(stream_id, timeout)7475 await self.backend.fork(76 self.send_request_data,77 [stream_id, request.stream(), timeout],78 receive_response,79 [stream_id, timeout],80 )8182 assert status_code is not None83 assert headers is not None8485 content = self.body_iter(stream_id, timeout)86 on_close = functools.partial(self.response_closed, stream_id=stream_id)8788 return Response(89 status_code=status_code,90 http_version="HTTP/2",91 headers=headers,92 content=content,93 on_close=on_close,94 request=request,95 )9697 async def close(self) -> None:98 await self.socket.close()9967 async def send_connection_init(self, timeout: Timeout) -> None:68 """69 The HTTP/2 connection requires some initial setup before we can start70 using individual request/response streams on it.71 """7273 # Need to set these manually here instead of manipulating via74 # __setitem__() otherwise the H2Connection will emit SettingsUpdate75 # frames in addition to sending the undesired defaults.104 self.h2_state.local_settings = Settings(76 self.state.local_settings = Settings(77 client=True,78 initial_values={79 # Disable PUSH_PROMISE frames from the server since we don't do anything80 # with them for now. Maybe when we support caching?
6 unmodified lines
8788 # Some websites (*cough* Yahoo *cough*) balk at this setting being89 # present in the initial handshake since it's not defined in the original90 # RFC despite the RFC mandating ignoring settings you don't know about.119 del self.h2_state.local_settings[120 h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL121 ]91 del self.state.local_settings[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL]92123 self.h2_state.initiate_connection()124 data_to_send = self.h2_state.data_to_send()93 self.state.initiate_connection()94 data_to_send = self.state.data_to_send()95 await self.socket.write(data_to_send, timeout)96127 async def send_headers(self, request: Request, timeout: Timeout) -> int:128 stream_id = self.h2_state.get_next_available_stream_id()97 @property98 def is_closed(self) -> bool:99 return False100101 def is_connection_dropped(self) -> bool:102 return self.socket.is_connection_dropped()103104 async def close(self) -> None:105 await self.socket.close()106107 async def wait_for_outgoing_flow(self, stream_id: int, timeout: Timeout) -> int:108 """109 Returns the maximum allowable outgoing flow for a given stream.110111 If the allowable flow is zero, then waits on the network until112 WindowUpdated frames have increased the flow rate.113114 https://tools.ietf.org/html/rfc7540#section-6.9115 """116 local_flow = self.state.local_flow_control_window(stream_id)117 connection_flow = self.state.max_outbound_frame_size118 flow = min(local_flow, connection_flow)119 while flow == 0:120 await self.receive_events(timeout)121 local_flow = self.state.local_flow_control_window(stream_id)122 connection_flow = self.state.max_outbound_frame_size123 flow = min(local_flow, connection_flow)124 return flow125126 async def wait_for_event(self, stream_id: int, timeout: Timeout) -> h2.events.Event:127 """128 Returns the next event for a given stream.129130 If no events are available yet, then waits on the network until131 an event is available.132 """133 while not self.events[stream_id]:134 await self.receive_events(timeout)135 return self.events[stream_id].pop(0)136137 async def receive_events(self, timeout: Timeout) -> None:138 """139 Read some data from the network, and update the H2 state.140 """141 data = await self.socket.read(self.READ_NUM_BYTES, timeout)142 events = self.state.receive_data(data)143 for event in events:144 event_stream_id = getattr(event, "stream_id", 0)145 logger.trace(f"receive_event stream_id={event_stream_id} event={event!r}")146147 if hasattr(event, "error_code"):148 raise ProtocolError(event)149150 if event_stream_id in self.events:151 self.events[event_stream_id].append(event)152153 data_to_send = self.state.data_to_send()154 await self.socket.write(data_to_send, timeout)155156 async def send_outgoing_data(self, timeout: Timeout) -> None:157 data_to_send = self.state.data_to_send()158 if data_to_send:159 await self.socket.write(data_to_send, timeout)160161 async def close_stream(self, stream_id: int) -> None:162 del self.streams[stream_id]163 del self.events[stream_id]164165 if not self.streams and self.on_release is not None:166 await self.on_release()167168169class HTTP2Stream:170 def __init__(171 self,172 stream_id: int,173 connection: HTTP2Connection,174 state: h2.connection.H2Connection,175 ) -> None:176 self.stream_id = stream_id177 self.connection = connection178 self.state = state179180 async def send(self, request: Request, timeout: Timeout) -> Response:181 # Send the request.182 await self.send_headers(request, timeout)183 await self.send_body(request, timeout)184185 # Receive the response.186 status_code, headers = await self.receive_response(timeout)187 content = self.body_iter(timeout)188 return Response(189 status_code=status_code,190 http_version="HTTP/2",191 headers=headers,192 content=content,193 on_close=self.close,194 request=request,195 )196197 async def send_headers(self, request: Request, timeout: Timeout) -> None:198 headers = [199 (b":method", request.method.encode("ascii")),200 (b":authority", request.url.authority.encode("ascii")),201 (b":scheme", request.url.scheme.encode("ascii")),
1 unmodified line
203 ] + [(k, v) for k, v in request.headers.raw if k != b"host"]204205 logger.trace(206 f"send_headers "138 f"stream_id={stream_id} "207 f"stream_id={self.stream_id} "208 f"method={request.method!r} "209 f"target={request.url.full_path!r} "210 f"headers={headers!r}"211 )143 self.h2_state.send_headers(stream_id, headers)144 data_to_send = self.h2_state.data_to_send()145 await self.socket.write(data_to_send, timeout)146 return stream_id212 self.state.send_headers(self.stream_id, headers)213 await self.connection.send_outgoing_data(timeout)214148 async def send_request_data(149 self, stream_id: int, stream: typing.AsyncIterator[bytes], timeout: Timeout,150 ) -> None:151 try:152 async for data in stream:153 await self.send_data(stream_id, data, timeout)154 await self.end_stream(stream_id, timeout)155 finally:156 # Once we've sent the request we should enable read timeouts.157 self.timeout_flags[stream_id].set_read_timeouts()158159 async def send_data(self, stream_id: int, data: bytes, timeout: Timeout) -> None:160 while data:161 # The data will be divided into frames to send based on the flow control162 # window and the maximum frame size. Because the flow control window163 # can decrease in size, even possibly to zero, this will loop until all the164 # data is sent. In http2 specification:165 # https://tools.ietf.org/html/rfc7540#section-6.9166 flow_control = self.h2_state.local_flow_control_window(stream_id)167 chunk_size = min(168 len(data), flow_control, self.h2_state.max_outbound_frame_size169 )170 if chunk_size == 0:171 # this means that the flow control window is 0 (either for the stream172 # or the connection one), and no data can be sent until the flow control173 # window is updated.174 await self.window_update_received[stream_id].wait()175 self.window_update_received[stream_id].clear()176 else:215 async def send_body(self, request: Request, timeout: Timeout) -> None:216 logger.trace(f"send_body stream_id={self.stream_id}")217 async for data in request.stream():218 while data:219 max_flow = await self.connection.wait_for_outgoing_flow(220 self.stream_id, timeout221 )222 chunk_size = min(len(data), max_flow)223 chunk, data = data[:chunk_size], data[chunk_size:]178 self.h2_state.send_data(stream_id, chunk)179 data_to_send = self.h2_state.data_to_send()180 await self.socket.write(data_to_send, timeout)224 self.state.send_data(self.stream_id, chunk)225 await self.connection.send_outgoing_data(timeout)226182 async def end_stream(self, stream_id: int, timeout: Timeout) -> None:183 logger.trace(f"end_stream stream_id={stream_id}")184 self.h2_state.end_stream(stream_id)185 data_to_send = self.h2_state.data_to_send()186 await self.socket.write(data_to_send, timeout)227 self.state.end_stream(self.stream_id)228 await self.connection.send_outgoing_data(timeout)229230 async def receive_response(189 self, stream_id: int, timeout: Timeout231 self, timeout: Timeout232 ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:233 """234 Read the response status and headers from the network.235 """236 while True:195 event = await self.receive_event(stream_id, timeout)196 # As soon as we start seeing response events, we should enable197 # read timeouts, if we haven't already.198 self.timeout_flags[stream_id].set_read_timeouts()237 event = await self.connection.wait_for_event(self.stream_id, timeout)238 if isinstance(event, h2.events.ResponseReceived):239 break240241 status_code = 200
5 unmodified lines
247 headers.append((k, v))248249 return (status_code, headers)250212 async def body_iter(213 self, stream_id: int, timeout: Timeout214 ) -> typing.AsyncIterator[bytes]:251 async def body_iter(self, timeout: Timeout) -> typing.AsyncIterator[bytes]:252 while True:216 event = await self.receive_event(stream_id, timeout)253 event = await self.connection.wait_for_event(self.stream_id, timeout)254 if isinstance(event, h2.events.DataReceived):218 self.h2_state.acknowledge_received_data(219 event.flow_controlled_length, stream_id255 self.state.acknowledge_received_data(256 event.flow_controlled_length, self.stream_id257 )258 await self.connection.send_outgoing_data(timeout)259 yield event.data260 elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):261 break262225 async def receive_event(self, stream_id: int, timeout: Timeout) -> h2.events.Event:226 while not self.events[stream_id]:227 flag = self.timeout_flags[stream_id]228 data = await self.socket.read(self.READ_NUM_BYTES, timeout, flag=flag)229 events = self.h2_state.receive_data(data)230 for event in events:231 event_stream_id = getattr(event, "stream_id", 0)232 logger.trace(233 f"receive_event stream_id={event_stream_id} event={event!r}"234 )235236 if hasattr(event, "error_code"):237 raise ProtocolError(event)238239 if isinstance(event, h2.events.WindowUpdated):240 if event_stream_id == 0:241 for window_update_event in self.window_update_received.values():242 window_update_event.set()243 else:244 try:245 self.window_update_received[event_stream_id].set()246 except KeyError: # pragma: no cover247 # the window_update_received dictionary is only relevant248 # when sending data, which should never raise a KeyError249 # here.250 pass251252 if event_stream_id:253 self.events[event.stream_id].append(event)254255 data_to_send = self.h2_state.data_to_send()256 await self.socket.write(data_to_send, timeout)257258 return self.events[stream_id].pop(0)259260 async def response_closed(self, stream_id: int) -> None:261 del self.events[stream_id]262 del self.timeout_flags[stream_id]263 del self.window_update_received[stream_id]264265 if not self.events and self.on_release is not None:266 await self.on_release()267268 @property269 def is_closed(self) -> bool:270 return False271272 def is_connection_dropped(self) -> bool:273 return self.socket.is_connection_dropped()263 async def close(self) -> None:264 await self.connection.close_stream(self.stream_id)