Repository navigation
Add support for HTTP/2 - #13039
Add support for HTTP/2#13039Moist-Cat wants to merge 86 commits into
Conversation
This implementation is backwards compatible, functional, but still incomplete.
for more information, see https://pre-commit.ci
| self._handler: Optional[asyncio.Protocol] = None | ||
|
|
||
| # ---- Transport callbacks forwarded to the real handler ---- | ||
| def connection_made(self, transport: asyncio.BaseTransport) -> None: |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #13039 +/- ##
==========================================
- Coverage 99.13% 98.88% -0.26%
==========================================
Files 135 148 +13
Lines 54630 57014 +2384
Branches 2808 2985 +177
==========================================
+ Hits 54158 56378 +2220
- Misses 357 469 +112
- Partials 115 167 +52
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
Merging this PR will degrade performance by 8.14%2 warnings
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing Footnotes
|
|
|
||
| try: | ||
| import sphinxcontrib.spelling # noqa | ||
| import sphinxcontrib.spelling |
It was necessary to add a semaphore to ensure the requests connect sequentially to the hosts and reuse connections when necessary. HTTP/2 uses a single connection per host.
for more information, see https://pre-commit.ci
|
I ran tests against remote servers (httpbin.org) to verify HTTP/2 indeed reduces latency. HTTP/2 Performance Test ResultsSystem Specs:
Test Configuration:
Batch Mean Latency (seconds)
Individual Request Latency Distribution
Statistical Analysis
A simple bar chart with the means (results vary because they are from a second test): We lose efficiency in CPU bound tasks (see #13039 (comment)) but I/O bound tasks are significantly faster. This is specially true for batch requests that require multiple TCP connections to the same host. |
|
I would like to know if the trade-offs (I/O vs CPU) are acceptable before writing the docs. |
HTTP/1.1 regression not inherent to h2. Caused by global |
Bigger blocker than the CPU/IO trade-off. h2 path returns |
|
|
|
Either inheriting from or using Regarding the To deal with |
for more information, see https://pre-commit.ci
| host_id, req, task = pending.pop(cid) | ||
| try: | ||
| connection = task.result() | ||
| except BaseException as e: |
| try: | ||
| connection = task.result() | ||
| live[cid] = LiveConn(cid, host_id, connection, req) | ||
| except BaseException: |
| try: | ||
| connection = task.result() | ||
| live[cid] = LiveConn(cid, host_id, connection, req) | ||
| except BaseException: |
|
ref #14386 |
|
I isolated all the remaining protocol-specific logic inside I'm going to fix a few bugs and verify that there are no major issues left. |
for more information, see https://pre-commit.ci
|
@aiolibsbot review |
|
❌ Permission denied. Only users with write access can trigger bot commands. |
| self, | ||
| flags: int, | ||
| stream_id: int, | ||
| payload: bytes, |
There was a problem hiding this comment.
Server can exhaust client memory
A malicious HTTP/2 server can exhaust the client's memory with never-ending CONTINUATION frames.
_handle_continuation_frame extends _pending_headers with every incoming CONTINUATION payload and only decodes (and checks) the block after END_HEADERS arrives. There is no limit on how many bytes can accumulate, and HEADERS/CONTINUATION frames are exempt from HTTP/2 flow control, so nothing else caps them either. While the block is pending, every other frame is rejected as a protocol error, so the whole connection stalls too.
Example: the client (with http2_enabled=True) sends a request; the server replies with a HEADERS frame without END_HEADERS, then streams CONTINUATION frames of ~16 KB each forever. The client keeps appending to _pending_headers and is OOM-killed long before the default 5-minute total timeout fires. At localhost speed that is many GB.
The HPACK safety net is also a no-op: DEFAULT_SETTINGS sets MAX_HEADER_LIST_SIZE to 2**32 - 1 (settings.py:68) and that value is passed to Decoder(max_header_list_size=...), despite the comment saying the limit is there to prevent bombs. So even after END_HEADERS, the decoded header list has no size cap. Cap the accumulated block size (e.g. at a few times MAX_FRAME_SIZE) and advertise a real MAX_HEADER_LIST_SIZE, and treat exceeding either as a connection error.
| self.inbound_window -= max(len(data), payload_len) | ||
| # --- stream-level flow control refill --- | ||
| self.maybe_reset_window() | ||
|
|
There was a problem hiding this comment.
Server can buffer endless response data
HTTP/2 flow control no longer bounds how much response data the client buffers, so a malicious server can OOM the client with one response.
Stream.receive_data calls maybe_reset_window the moment data arrives, sending a full WINDOW_UPDATE before the app has consumed anything, and Http2Protocol.pause_reading is a no-op, so there is no transport-level backpressure either. The only remaining cap is the 64 KB connection window, which is refilled every time the app drains any stream's StreamReader below its low-water mark (resume_reading -> maybe_reset_window).
Example: the app reads response B chunk by chunk while response A on the same connection sits unread. Every read of B refills the connection window, and A's stream window refills on arrival, so the server can push an arbitrarily large body into A's body_reader, which buffers all of it in memory until the app gets to it. Reading a single stream slower than the server sends grows the buffer without bound too. HTTP/1.1 is safe here because the transport is paused while the buffer is full; this change removes that protection.
The window should only be refilled as the app consumes data - that is the entire point of HTTP/2 flow control.
|
|
||
| self._read_timeout = read_timeout | ||
| self._auto_decompress = auto_decompress | ||
|
|
There was a problem hiding this comment.
HTTP/2 response reads lose timeouts
Per-request timeout settings are silently dropped or shared connection-wide for HTTP/2 responses, so reads can hang forever.
Http2Protocol.set_response_params accepts timer but never stores it, and Stream creates its body StreamReader without a timer. On the HTTP/1.1 path the timer is passed into the reader, which is what enforces ClientTimeout.total while the app consumes the body. So once headers arrive, a malicious or stuck server can leave resp.read() hanging indefinitely even though the app set total=300.
On top of that, this method writes read_timeout and auto_decompress onto the shared protocol, once per request (H2Connection.send_request calls it for every request). The last request wins for the whole connection: one request with sock_read=None erases the read timeout of every other in-flight stream (the check fails open), and when _on_read_timeout does fire it calls _cancel_streams(0, ...), killing all streams on the connection instead of just the one that timed out.
Example: request A sets sock_read=10, request B on the same connection sets sock_read=None; the server stalls both. B's params overwrite A's, so A never times out and its task hangs until the app gives up.
asvetlov
left a comment
There was a problem hiding this comment.
Thanks for picking the problem up.
Please address my initial review.
| self.transport: asyncio.Transport | None = None | ||
| # proto version | ||
| # we can't set the default due to a circular import | ||
| self.version: Any = None |
There was a problem hiding this comment.
Is it for HttpVersion? Move the class to some helper file if needed, but please avoid Any.
| protocol = self._protocol | ||
| message, payload = await protocol.read() # type: ignore[union-attr] | ||
| assert protocol is not None | ||
| if hasattr(protocol, "version") and protocol.version.major == 2: |
There was a problem hiding this comment.
Better ensure that all protocols have version attribute.
| self.loop, | ||
| def _create_writer( | ||
| self, connection: "Connection" | ||
| ) -> StreamWriter | Http2StreamWriter: |
There was a problem hiding this comment.
Return type looks cumbersome. Could you declare that an abstract writer is returned without using a union type?
| from .http2.connection import Http2Protocol | ||
|
|
||
|
|
||
| class HttpDispatcherProtocol(asyncio.Protocol): |
There was a problem hiding this comment.
I don't like such a hackish solution.
If you need a protocol that redirects everything to its _handler (a bad name BTW) please write it explicitly without redirecting attrs setters/getters. The used approach makes debugging very complex.
| # all incoming data and callbacks. | ||
| self._handler.connection_made(transport) | ||
|
|
||
| def __getattribute__(self, name: str) -> Any: |
There was a problem hiding this comment.
Breaks uvloop even with HTTP/2 off: uvloop caches protocol.data_received before connection_made(), when _handler is still None, so all response data is dropped and requests hang (plain http://, UnixConnector). At least call transport.set_protocol(self._handler) in connection_made().
| else: | ||
| return None | ||
|
|
||
| conns = target[key].copy() |
There was a problem hiding this comment.
Race: the live deque still holds proto during await trace.send_connection_reuseconn(), so a concurrent _get() can take the same HTTP/1.1 connection, and the write-back of conns drops connections released meanwhile. Please mutate the live deque before any await, as before.
| self.hpack_encoder = Encoder() | ||
| # set limits to prevent zip bombs | ||
| self.hpack_decoder = Decoder( | ||
| max_header_list_size=self.local_settings[Setting.MAX_HEADER_LIST_SIZE], |
There was a problem hiding this comment.
Not a zip-bomb limit: MAX_HEADER_LIST_SIZE is 2**32 - 1, overriding hpack's 64 KiB default, and CONTINUATION accumulation is unbounded. A hostile server can OOM the client. Please bound both from the session header limits; THREAT_MODEL.md needs an update too.
|
Thank you for taking the time to review this, @asvetlov . |

What do these changes do?
Add HTTP/2 client support.
Why
Faster I/O bound operations (e.g., many requests to the same host) via multiplexing (handling several streams/requests inside a single connection).
How
Use the environment variableVia theAIOHTTP_ENABLE_EXPERIMENTAL_PROTOCOLS=1to allowh2negotiation via ALPN during the TLS handshake.http2_enabledflag insideClientSession.ResponseHandlerwas substituted by a wrapper that conditionally switches protocols depending on the negotiated protocol.Semaphoreto avoid race conditions.This means opening many HTTP/1.1 connections in parallel is now slower because it's done sequentially. That said, to know if connections can be pooled or not it's only necessary to wait until the first connection is done. Once it's known whether the host supports HTTP/2 or not, the rest of the requests can be done in parallel so it's possible to mitigate this performance hit substantially.Solved!Backward compatibility
Opt-in via
http2_enabled.Testing
%95 coverage, benchmarks (%50 latency reduction for 99 requests, see below), and integration tests against real servers (~100).
Dependencies
hpack
Is it a substantial burden for the maintainers to support this?
Yes.
Related issue number
refs #5999
The implementation is self-contained, the changes to the current codebase are minimal and backwards compatible.
Missing features (to the date):
ProxiesResponse streamingEnsure all the high-level configuration/parameters work (or make sense for) with HTTP/2 as well(obsolete)expect100Request streamingWINDOW_UPDATEframes.Things that should be implemented/changed:
Support reusable connections
This means changing the way we handle all connections so the implementation should be done in a separate PR to avoid regressions.Make HTTP/1.1 a particular case of HTTP/2
HTTP/1.1 connections can be seen as HTTP/2 connections that only allow a single stream. When we try to fit HTTP/2 connections inside routines that were built for HTTP/1.1 like we did here, the implementation ends up looking a bit awkward. (with "awkward" I mean that we have to add 1-2 additional if statements per class to pass thestream_idto the HTTP/2 connector).