Support graceful shutdown after receiving GOAWAY(NO_ERROR)

BE
8d ago
+709-11

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), h2 transitions to CLOSED and rejects subsequent frames (e.g., the PING or in-flight response frames in a standard RFC 9113 §6.8 two-stage shutdown).

Design

  • Graceful shutdown on GOAWAY(NO_ERROR): When an open connection receives GOAWAY(NO_ERROR), state_machine.state remains CLOSED (preserving existing reuse checks like httpcore's) while H2Connection.is_in_graceful_shutdown becomes True.
  • Keep open streams alive: Frames for existing streams keep flowing, the outbound buffer is preserved, PING/SETTINGS are 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 (including PUSH_PROMISE).
  • Block new local streams: send_headers (new stream ID) and push_stream call _check_graceful_shutdown and raise ProtocolError before mutating state, leaving graceful shutdown intact for open streams.
  • Terminal closure: An error GOAWAY, protocol error, or close_connection() ends graceful shutdown (leaving state hard-CLOSED). A later graceful GOAWAY never reopens a closed connection. Once closed (not in graceful shutdown), leftover non-GOAWAY frames are ignored rather than raising ProtocolError.
  • Application boundary: ConnectionTerminated still fires for every GOAWAY (check H2Connection.is_in_graceful_shutdown to distinguish graceful shutdown from terminal closure). Handling streams above last_stream_id and enforcing non-increasing last_stream_id remain the application's responsibility.

Notes

  • Builds on #1324 (@adarshx01's commit and authorship preserved; connections in graceful shutdown are excluded from its post-close ignore guard). Thanks also to @zanieb, @dimaqq, and @neoLsH for the design discussion in #1181.
  • Passes pytest (100% line and branch coverage), ruff, mypy --strict-bytes, and sphinx-build.