Repository navigation
Add support for HTTP/2 #13039
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Add support for HTTP/2 #13039
Changes from all commits
4badcd8
8d6ffe2
1b21c5b
982ad3a
2ecae5a
73bfa16
9bd6ff9
91b46d8
0b361d3
9ab172f
38b9d3d
538164e
2ce9b41
fdb10b7
e312859
93aef89
23997c4
d78d47a
35eb119
742899f
44de092
0f9f4d8
979bb4a
51a5ee2
1d10b19
519c830
44811d3
d242ad7
5f57683
d14a1c7
314a6e5
38c11ff
899742e
2c0493a
088eb38
d40dc83
1028739
bc9eb29
d2941d2
d8dc63a
8fdf2e4
af86d82
e70d672
5f1dc50
1f1b8db
9f9d127
a5124c0
7e8daa3
bce855d
b76be6c
263ea5a
aa3d6f7
d8cb468
1b7f7c1
3ae99c9
4eace7e
e7a205a
ff6f1f5
00e8aaa
c014585
8b52301
8c1316e
d92b6d9
8bc087f
e6c0104
6a237a3
86ae832
111eb99
5d05621
a63237d
8e849f0
285b1d3
83e975b
312ba64
2f47164
7e19d7c
366c442
4d1182e
8f82fe7
79f86f0
2c3a5ec
16e1ada
07d933b
0d12d1e
9e737c3
8418f19
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Added experimental support for ``HTTP/2``. It can be enabled via the ``http2_enabled`` parameter of the :class:`~aiohttp.ClientSession` -- by :user:`Moist-Cat`. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -282,25 +282,42 @@ class _SessionOptions(TypedDict, total=False): | |
| async def _connect_and_send_request(req: ClientRequest) -> ClientResponse: | ||
| connector = req._session._connector | ||
| assert connector is not None | ||
| key = req.connection_key | ||
|
|
||
| if (tracker := req._upload_tracker) is not None: | ||
| req._upload_gen = tracker._attempt_started() | ||
|
|
||
| try: | ||
| conn = await connector.connect(req, traces=req._traces, timeout=req._timeout) | ||
| if connector.http2_enabled: | ||
| await connector.semaphore.acquire(key) | ||
| # only the first connection to a host blocks | ||
| # the rest connect concurrently | ||
| try: | ||
| conn = await connector.connect( | ||
| req, traces=req._traces, timeout=req._timeout | ||
| ) | ||
| finally: | ||
| if connector.http2_enabled: | ||
| connector.semaphore.release(key) | ||
| except TimeoutError as exc: | ||
| raise ConnectionTimeoutError(f"Connection timeout to host {req.url}") from exc | ||
|
|
||
| assert conn.protocol is not None | ||
| conn.protocol.set_response_params(**req._response_params) | ||
| assert conn.protocol.transport is not None | ||
|
|
||
| resp = None | ||
| started = False | ||
|
|
||
| try: | ||
| resp = await req._send(conn) | ||
| try: | ||
| await resp.start(conn) | ||
| except BaseException: | ||
| resp = await conn.send_request(req) | ||
| await resp.start(conn) | ||
| started = True | ||
| finally: | ||
| if resp is not None and not started: | ||
| resp.close() | ||
| raise | ||
| except BaseException: | ||
| conn.close() | ||
| raise | ||
| conn.close() | ||
| if resp is None: | ||
| conn.close() | ||
| return resp | ||
|
|
||
|
|
||
|
|
@@ -372,6 +389,7 @@ def __init__( | |
| fallback_charset_resolver: _CharsetResolver = lambda r, b: "utf-8", | ||
| middlewares: Sequence[ClientMiddlewareType] = (), | ||
| ssl_shutdown_timeout: _SENTINEL | None | float = sentinel, | ||
| http2_enabled: bool = False, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Adding the public Context Used: AGENTS.md (source) Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time! |
||
| ) -> None: | ||
| # We initialise _connector to None immediately, as it's referenced in __del__() | ||
| # and could cause issues if an exception occurs during initialisation. | ||
|
|
@@ -411,7 +429,9 @@ def __init__( | |
| ) | ||
|
|
||
| if connector is None: | ||
| connector = TCPConnector(ssl_shutdown_timeout=ssl_shutdown_timeout) | ||
| connector = TCPConnector( | ||
| ssl_shutdown_timeout=ssl_shutdown_timeout, http2_enabled=http2_enabled | ||
| ) | ||
| # Initialize these three attrs before raising any exception, | ||
| # they are used in __del__ | ||
| self._connector = connector | ||
|
|
@@ -1673,7 +1693,9 @@ def request( | |
| connector_owner = False | ||
| if connector is None: | ||
| connector_owner = True | ||
| connector = TCPConnector(force_close=True) | ||
| # _request doesn't accept http2_enabled | ||
| http2_enabled = kwargs.pop("http2_enabled", False) | ||
| connector = TCPConnector(force_close=True, http2_enabled=http2_enabled) | ||
|
|
||
| session = ClientSession( | ||
| cookies=kwargs.pop("cookies", None), | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -61,6 +61,7 @@ | |
| HttpVersion11, | ||
| StreamWriter, | ||
| ) | ||
| from .http2.adapter import Http2StreamWriter | ||
| from .streams import EMPTY_PAYLOAD, StreamReader | ||
| from .typedefs import DEFAULT_JSON_DECODER, JSONDecoder, RawHeaders | ||
|
|
||
|
|
@@ -711,7 +712,12 @@ async def start(self, connection: "Connection") -> "ClientResponse": | |
| # read response | ||
| try: | ||
| 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: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Better ensure that all protocols have |
||
| message, payload = await connection.read_response() | ||
| else: | ||
| # backwards compatibility | ||
| message, payload = await protocol.read() | ||
| except HttpProcessingError as exc: | ||
| raise ClientResponseError( | ||
| self.request_info, | ||
|
|
@@ -1113,8 +1119,10 @@ def _create_response( | |
| stream_writer=stream_writer, | ||
| ) | ||
|
|
||
| def _create_writer(self, protocol: BaseProtocol) -> StreamWriter: | ||
| return StreamWriter(protocol, self.loop) | ||
| def _create_writer( | ||
| self, connection: "Connection" | ||
| ) -> StreamWriter | Http2StreamWriter: | ||
| return connection.create_writer() | ||
|
|
||
| def _should_write(self, protocol: BaseProtocol) -> bool: | ||
| return protocol.writing_paused | ||
|
|
@@ -1133,9 +1141,7 @@ async def _send(self, conn: "Connection") -> ClientResponse: | |
| else: | ||
| path = self.url.raw_path_qs | ||
|
|
||
| protocol = conn.protocol | ||
| assert protocol is not None | ||
| writer = self._create_writer(protocol) | ||
| writer = self._create_writer(conn) | ||
|
|
||
| # set default content-type | ||
| if ( | ||
|
|
@@ -1163,6 +1169,8 @@ async def _send(self, conn: "Connection") -> ClientResponse: | |
| await writer.write_headers(status_line, self.headers) | ||
|
|
||
| task: asyncio.Task[None] | None | ||
| assert conn.protocol is not None | ||
| protocol = conn.protocol | ||
| if self._should_write(protocol): | ||
| coro = self._write_bytes(writer, conn, self._get_content_length()) | ||
| if sys.version_info >= (3, 14): | ||
|
|
@@ -1613,10 +1621,10 @@ def _create_response( | |
| stream_writer=stream_writer, | ||
| ) | ||
|
|
||
| def _create_writer(self, protocol: BaseProtocol) -> StreamWriter: | ||
| writer = StreamWriter( | ||
| protocol, | ||
| self.loop, | ||
| def _create_writer( | ||
| self, connection: "Connection" | ||
| ) -> StreamWriter | Http2StreamWriter: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Return type looks cumbersome. Could you declare that an abstract writer is returned without using a union type? |
||
| writer = connection.create_writer( | ||
| on_chunk_sent=( | ||
| functools.partial(self._on_chunk_request_sent, self.method, self.url) | ||
| if self._traces | ||
|
|
@@ -1634,6 +1642,17 @@ def _create_writer(self, protocol: BaseProtocol) -> StreamWriter: | |
|
|
||
| if self.chunked is not None: | ||
| writer.enable_chunking() | ||
|
|
||
| # patch for http/2 | ||
| if ( | ||
| hasattr(connection.protocol, "version") | ||
| and connection.protocol is not None | ||
| and connection.protocol.version.major == 2 | ||
| ): | ||
| # we can get this from the status line | ||
| # but it's less convenient | ||
| writer.url = self.url # type: ignore[union-attr] | ||
| writer.method = self.method # type: ignore[union-attr] | ||
| return writer | ||
|
|
||
| def _should_write(self, protocol: BaseProtocol) -> bool: | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is it for
HttpVersion? Move the class to some helper file if needed, but please avoidAny.