Repository navigation
Support graceful shutdown after receiving GOAWAY(NO_ERROR) - #1346
benpbolton wants to merge 4 commits into
Conversation
RFC 9113, Section 6.8 lets streams at or below a GOAWAY's last stream ID complete. Servers often shut down in two stages: GOAWAY(NO_ERROR) with a high last stream ID, a PING, then a GOAWAY with the real last stream ID. h2 moved to CLOSED on any GOAWAY, so the PING or the rest of an open response raised "Invalid input ... in state ConnectionState.CLOSED". After a GOAWAY with NO_ERROR, the connection now drains: - The state stays CLOSED, so consumers that check for CLOSED still stop opening streams on the connection. H2ConnectionStateMachine.draining reports the drain. - Frames for open streams are still processed. PING and SETTINGS are still acknowledged. PUSH_PROMISE can still be received. The outbound buffer is kept. - The drain keeps a shadow of the open state, so the client and server rules of the open connection still apply. - New local streams (send_headers on a new stream ID, push_stream, initiate_upgrade_connection) raise ProtocolError before any state change, and the drain continues. - A further graceful GOAWAY continues the drain. A GOAWAY with an error code, an invalid input or close_connection() ends it. A graceful GOAWAY never reopens a connection that is already closed. ConnectionTerminated is still fired for every GOAWAY. h2 does not reset or filter streams above last_stream_id; the application decides. Fixes python-hyper#1199. Fixes the receive side of python-hyper#1181. Builds on python-hyper#1324. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
448f065 to
c25db2b
Compare
Kriechi
left a comment
There was a problem hiding this comment.
Thanks - looks like we are on the right path heading in the right direction.
A few thoughts on naming and everything fits together.
| msg = "Input must be an instance of ConnectionInputs" | ||
| raise ValueError(msg) # noqa: TRY004 | ||
|
|
||
| if self._draining_state is not None: |
There was a problem hiding this comment.
use the new property to improve readability here.
There was a problem hiding this comment.
Updated in 4d98c44 to if self.is_in_graceful_shutdown: (with a narrowing assert on _graceful_shutdown_state for strict mypy).
| # Anything else (a GOAWAY, or an input the open connection would | ||
| # also reject) ends the drain. A further graceful GOAWAY from the | ||
| # peer continues it (see H2Connection._receive_goaway_frame). | ||
| self._draining_state = None |
There was a problem hiding this comment.
Is my reading of this here correct, that it is possible and allowed to "cancel" a draining and re-open an already closed connection in this way?
There was a problem hiding this comment.
Good catch on readability — it cannot re-open a closed connection. Throughout graceful shutdown, self.state is already ConnectionState.CLOSED, and _transitions has no way out of CLOSED (only SEND_GOAWAY and RECV_GOAWAY, both staying CLOSED; any other input raises ProtocolError). Clearing _graceful_shutdown_state does the opposite: it ends graceful shutdown and leaves the connection hard-closed.
In 4d98c44 I added assert self.state is ConnectionState.CLOSED and tightened the comment to make that invariant explicit.
| "Upgrade connection. Current settings: %s", self.local_settings, | ||
| ) | ||
|
|
||
| self._refuse_new_stream_while_draining(1) |
There was a problem hiding this comment.
How could a connection already have a received a GoAway at this point - the HTTP/2 connection is not even established and no frames have been (allowed to) sent yet.
There was a problem hiding this comment.
Fair point — in valid HTTP/2 an h2c upgrade cannot happen after a GOAWAY. We had only added it defensively for API misuse (calling receive_data(GOAWAY(NO_ERROR)) on an idle connection before initiate_upgrade_connection(), which raised ProtocolError on master). Agreed it doesn't belong here — removed along with its test in 4d98c44.
| self.streams[1].upgrade(self.config.client_side) | ||
| return frame_data | ||
|
|
||
| def _refuse_new_stream_while_draining(self, stream_id: int) -> None: |
There was a problem hiding this comment.
I am stumbling over the function and property naming here a few times.
draining is not part of the HTTP/2 RFC, so I would like to avoid introducing new terminology.
How about renaming this function to check_connection_still_open or similar, same for the other uses of draining above. The RFC does use the graceful shutdown phrase a few times - how about adopting that terminology?
H2Connection.is_in_graceful_shutdownbool property_refuse_new_stream_while_drainingbecomes_verify...or_ensure_no_new_streamsor_check_graceful_shutdown
There was a problem hiding this comment.
Agreed — RFC 9113's "graceful shutdown" terminology fits much better. Renamed throughout in 4d98c44 (H2Connection.is_in_graceful_shutdown lifted onto H2Connection, H2ConnectionStateMachine.is_in_graceful_shutdown, _graceful_shutdown_state, _graceful_shutdown_inputs, _start_graceful_shutdown, and _check_graceful_shutdown) and updated the docstrings, changelog, and tests to match. Thanks for the thoughtful review!
| # error, or close_connection()); a later graceful GOAWAY must not | ||
| # revive it (RFC 9113, Section 5.4.1). | ||
| open_state: ConnectionState | None = self.state_machine._draining_state | ||
| if open_state is None and self.state_machine.state is not ConnectionState.CLOSED: |
There was a problem hiding this comment.
Use new property here again for readability.
There was a problem hiding this comment.
Updated in 4d98c44 to branch on self.is_in_graceful_shutdown.
| import h2.events | ||
| import h2.exceptions | ||
|
|
||
| MAX_STREAM_ID = 2**31 - 1 |
There was a problem hiding this comment.
re-use HIGHEST_ALLOWED_STREAM_ID from connections.py
There was a problem hiding this comment.
Done in 4d98c44 — reused h2.connection.H2Connection.HIGHEST_ALLOWED_STREAM_ID.
…erty onto H2Connection
| # must not revive it (RFC 9113, Section 5.4.1). | ||
| open_state: ConnectionState | None | ||
| if self.is_in_graceful_shutdown: | ||
| open_state = self.state_machine._graceful_shutdown_state |
There was a problem hiding this comment.
accessing a private instance attribute (variable name with _ prefix) is not nice here.
There was a problem hiding this comment.
Good catch — thank you. Reading and re-applying private state-machine attributes from H2Connection broke encapsulation. I am refactoring this to handle graceful GOAWAY inside H2ConnectionStateMachine via ConnectionInputs.RECV_GRACEFUL_GOAWAY (mirroring StreamInputs.RECV_INFORMATIONAL_HEADERS), so H2Connection._receive_goaway_frame only calls process_input() and reads the public is_in_graceful_shutdown property.
| # streams that are already open may complete. Keep the outbound | ||
| # buffer, which may hold WINDOW_UPDATE, SETTINGS or PING ACK frames | ||
| # those streams need. | ||
| self.state_machine._start_graceful_shutdown(open_state) |
There was a problem hiding this comment.
accessing a private function (variable name with _ prefix) is not nice here.
There was a problem hiding this comment.
Same catch — thank you. This call goes away with the ConnectionInputs.RECV_GRACEFUL_GOAWAY refactor above; graceful shutdown transitions will live entirely inside H2ConnectionStateMachine.
Fixes #1199. Covers the receive side of #1181 (sending-side graceful shutdown is out of scope). Companion mitmproxy PR: mitmproxy/mitmproxy#8580.
Problem
On
GOAWAY(NO_ERROR),h2transitions toCLOSEDand rejects subsequent frames (e.g., thePINGor in-flight response frames in a standard RFC 9113 §6.8 two-stage shutdown).Design
GOAWAY(NO_ERROR): When an open connection receivesGOAWAY(NO_ERROR),state_machine.stateremainsCLOSED(preserving existing reuse checks likehttpcore's) whileH2Connection.is_in_graceful_shutdownbecomesTrue.PING/SETTINGSare still acknowledged, and normal client/server role rules remain enforced via a shadow of the open state (_graceful_shutdown_state). The peer may still open streams (includingPUSH_PROMISE).send_headers(new stream ID) andpush_streamcall_check_graceful_shutdownand raiseProtocolErrorbefore mutating state, leaving graceful shutdown intact for open streams.GOAWAY, protocol error, orclose_connection()ends graceful shutdown (leavingstatehard-CLOSED). A later gracefulGOAWAYnever reopens a closed connection. Once closed (not in graceful shutdown), leftover non-GOAWAYframes are ignored rather than raisingProtocolError.ConnectionTerminatedstill fires for everyGOAWAY(checkH2Connection.is_in_graceful_shutdownto distinguish graceful shutdown from terminal closure). Handling streams abovelast_stream_idand enforcing non-increasinglast_stream_idremain the application's responsibility.Notes
@adarshx01's commit and authorship preserved; connections in graceful shutdown are excluded from its post-close ignore guard). Thanks also to@zanieb,@dimaqq, and@neoLsHfor the design discussion in Support graceful connection close #1181.pytest(100% line and branch coverage),ruff,mypy --strict-bytes, andsphinx-build.