Skip to main content

trillium_http/h2/
connection.rs

1//! Shared per-connection HTTP/2 state ([`H2Connection`]).
2//!
3//! [`H2Connection`] is `Arc`-shared between the driver task ([`H2Driver`]) and every conn
4//! task that holds an open stream's [`Conn`]. It owns the per-stream `StreamState` map,
5//! the cross-task wake primitive ([`AtomicWaker`]), and the [`HttpContext`] / [`Swansong`]
6//! the broader server stack reaches in through.
7//!
8//! The driver loop itself lives in [`super::acceptor`] — see that module for the
9//! per-connection state machine and how send / receive concerns are split.
10//!
11//! # Module layout
12//!
13//! Conn-task-side primitives are split across child modules so each subsystem reads
14//! independently:
15//!
16//! - [`ping`]: `PING` / `PING ACK` round-trip tracking and the [`SendPing`] future.
17//! - [`peer_settings_wait`]: the [`PeerSettings`] sync primitive that parks until the peer's first
18//!   SETTINGS frame is applied.
19//! - [`submit`]: send-staging API ([`submit_send`][H2Connection::submit_send],
20//!   [`submit_upgrade`][H2Connection::submit_upgrade]) and client-side stream-open primitives
21//!   ([`open_stream`][H2Connection::open_stream] /
22//!   [`open_connect_stream`][H2Connection::open_connect_stream]) + the [`SubmitSend`] future.
23//! - [`response`]: client-role recv-side primitives — [`ResponseHeaders`] and
24//!   [`take_trailers`][H2Connection::take_trailers].
25//!
26//! [`H2Driver`]: super::H2Driver
27
28mod peer_settings_wait;
29mod ping;
30mod response;
31mod submit;
32
33#[cfg(feature = "unstable")]
34use super::H2Initiator;
35use super::{H2Driver, H2Settings, role::Role, transport::StreamState};
36use crate::{Conn, HttpContext};
37use atomic_waker::AtomicWaker;
38use event_listener::Event;
39use futures_lite::io::{AsyncRead, AsyncWrite};
40use ping::PendingPing;
41#[cfg(feature = "unstable")]
42use std::sync::atomic::Ordering;
43use std::{
44    collections::{HashMap, VecDeque},
45    future::Future,
46    io,
47    sync::{Arc, Mutex, MutexGuard, atomic::AtomicBool},
48    task::{Context, Poll},
49};
50use swansong::{ShutdownCompletion, Swansong};
51#[cfg(feature = "unstable")]
52#[allow(unused_imports)]
53// re-exports for h2.rs's `pub use connection::{ResponseHeaders, SubmitSend}`
54pub use {response::ResponseHeaders, submit::SubmitSend};
55
56/// Shared per-connection state for HTTP/2.
57///
58/// Wrapped in an [`Arc`] and held by both the [`H2Driver`] driver and every conn task
59/// that holds an open stream's [`Conn`]. Per-stream `StreamState`, HPACK encoder state, and
60/// connection-level send flow control lives here.
61#[derive(Debug)]
62pub struct H2Connection {
63    pub(super) context: Arc<HttpContext>,
64    pub(super) swansong: Swansong,
65    /// Driver-side waker that conn tasks fire whenever they produce work the driver should
66    /// act on — the is-reading signal on first `H2Transport::poll_read`, and the
67    /// `submit_send` arrival. Single-consumer (the driver); N producers (conn tasks). The
68    /// driver registers its current `drive` waker here each iteration it parks.
69    pub(super) outbound_waker: AtomicWaker,
70    /// Per-stream shared state, keyed by stream id. The driver inserts on stream open and
71    /// removes on close. Conn-task code looks up via private accessors on `H2Connection`
72    /// rather than touching the map directly — `StreamState` stays module-private.
73    pub(super) streams: Mutex<HashMap<u32, Arc<StreamState>>>,
74    /// The peer's most recently announced SETTINGS values. The driver writes on every
75    /// inbound SETTINGS frame and is the only reader, so a plain `Mutex` suffices.
76    /// `H2Settings` is `Copy`, so readers take the guard, copy out, and release.
77    ///
78    /// Default-constructed (all fields `None`) means "peer has not yet sent SETTINGS";
79    /// readers should use [`H2Settings::effective_*`][H2Settings::effective_max_frame_size]
80    /// helpers that apply the RFC defaults to absent fields.
81    pub(super) peer_settings: Mutex<H2Settings>,
82    /// Latch flipped to `true` the first (and every subsequent) time the driver applies
83    /// a peer SETTINGS frame. Distinct from `peer_settings` because an absent field is
84    /// ambiguous between "peer hasn't sent SETTINGS yet" and "peer sent SETTINGS without
85    /// that field" — the latch disambiguates, gating operations that require having seen
86    /// the peer's first SETTINGS (e.g. extended CONNECT).
87    pub(super) peer_settings_received: AtomicBool,
88    /// Multi-listener wake source for [`PeerSettings`]. The driver fires `notify(usize::MAX)`
89    /// after applying peer SETTINGS and again on connection close, so any number of
90    /// concurrently-parked `PeerSettings` futures all unblock together. [`Event`] (rather
91    /// than a single [`AtomicWaker`]) is required because multiple application tasks can
92    /// park on `peer_settings` concurrently — e.g. a fan-out of WebSocket-over-h2 upgrades
93    /// on one pooled connection — and `AtomicWaker`'s last-writer-wins semantics would
94    /// strand all but one.
95    pub(super) peer_settings_event: Event,
96    /// Next stream id to allocate for client-role outbound streams. Starts at 1 and
97    /// `+= 2` per allocation. Capped at `2^31` — once exhausted, `fetch_update`'s closure
98    /// refuses to advance, and `open_stream` returns `None` (the caller is expected to
99    /// fail over to a fresh connection).
100    ///
101    /// Allocation happens **while holding `streams_lock`** (see `open_stream`), so id order
102    /// matches shared-map insertion order — the invariant the BTreeMap-ordered send pump
103    /// relies on to frame opening HEADERS in monotonic order (RFC 9113 §5.1.1). The lock,
104    /// not the atomic, is what orders allocations; the `AtomicU32` is just the interior
105    /// mutability this `Arc`-shared field needs, so `Relaxed` suffices. The one out-of-band
106    /// reader (`can_open_stream`'s exhaustion check) takes `streams_lock` immediately after,
107    /// so its `load` is an advisory fast-path, not a separately-synchronized access.
108    #[cfg(feature = "unstable")]
109    pub(super) next_client_stream_id: std::sync::atomic::AtomicU32,
110    /// Outstanding active PINGs awaiting ACKs, keyed by opaque payload. Completed by the
111    /// driver when a `PING { ack: true }` arrives whose payload matches an entry. Drained
112    /// on connection close so awaiting `send_ping` futures don't leak.
113    pub(super) pending_pings: Mutex<HashMap<[u8; 8], PendingPing>>,
114    /// Opaque payloads queued for outbound `PING { ack: false }` emission. Decoupled from
115    /// `pending_pings` so registration and queuing can happen without holding two locks.
116    pub(super) pending_ping_outbound: Mutex<VecDeque<[u8; 8]>>,
117}
118
119impl H2Connection {
120    /// Construct a new `H2Connection` to manage HTTP/2 for a single peer.
121    pub fn new(context: Arc<HttpContext>) -> Arc<Self> {
122        let swansong = context.swansong().child();
123        Arc::new(Self {
124            context,
125            swansong,
126            outbound_waker: AtomicWaker::new(),
127            streams: Mutex::new(HashMap::new()),
128            peer_settings: Mutex::new(H2Settings::default()),
129            peer_settings_received: AtomicBool::new(false),
130            peer_settings_event: Event::new(),
131            #[cfg(feature = "unstable")]
132            next_client_stream_id: std::sync::atomic::AtomicU32::new(1),
133            pending_pings: Mutex::new(HashMap::new()),
134            pending_ping_outbound: Mutex::new(VecDeque::new()),
135        })
136    }
137
138    /// The [`HttpContext`] this connection was constructed with.
139    pub fn context(&self) -> Arc<HttpContext> {
140        self.context.clone()
141    }
142
143    /// The connection-scoped [`Swansong`]. Shuts down on peer GOAWAY, when the server-
144    /// level swansong shuts down, or when the connection ends for any other reason
145    /// (peer disconnect, transport error) — once it leaves the running state, the
146    /// connection will never carry another stream.
147    pub fn swansong(&self) -> &Swansong {
148        &self.swansong
149    }
150
151    /// Attempt graceful shutdown of this HTTP/2 connection.
152    pub fn shut_down(&self) -> ShutdownCompletion {
153        self.swansong.shut_down()
154    }
155
156    /// Whether a fresh stream could be opened on this connection right now.
157    ///
158    /// `true` requires: the connection is running (no GOAWAY received, swansong not asked
159    /// to shut down), inflight streams are below the peer's advertised
160    /// `MAX_CONCURRENT_STREAMS`, and the client stream-id space is not exhausted (capped
161    /// at `2^31 - 1`).
162    ///
163    /// `false` doesn't mean the connection is dead — it might just be saturated and free
164    /// up momentarily. Callers should keep saturated connections in their pool rather than
165    /// evicting; pair this with a separate aliveness check to decide eviction.
166    ///
167    /// Stream-id exhaustion is the one "false" case that *is* permanent: the connection
168    /// will never accept another `open_stream` call, though in-flight streams will still
169    /// complete.
170    ///
171    /// # Panics
172    ///
173    /// Panics if any per-connection mutex is poisoned.
174    #[cfg(feature = "unstable")]
175    pub fn can_open_stream(&self) -> bool {
176        if !self.swansong.state().is_running() {
177            return false;
178        }
179        // Stream-id exhaustion check guards against an exhausted connection passing the
180        // inflight-vs-MAX_CONCURRENT_STREAMS check (no streams in flight → counts as 0)
181        // and the pool selecting it as Available, only for `open_stream` to fail at the
182        // call site with a misleading "shutting down" error.
183        if self.next_client_stream_id.load(Ordering::Relaxed) >= (1u32 << 31) {
184            return false;
185        }
186        // Count wire-active streams only — entries the application is still holding after
187        // a clean wire-close stay in the map but don't count against the peer's
188        // MAX_CONCURRENT_STREAMS.
189        let inflight: u32 = self
190            .streams_lock()
191            .values()
192            .filter(|s| !s.lifecycle_lock().is_closed())
193            .count()
194            .try_into()
195            .unwrap_or(u32::MAX);
196        let cap = self
197            .current_peer_settings()
198            .effective_max_concurrent_streams();
199        inflight < cap
200    }
201
202    /// Driver-side wake primitive. Fire after producing work the driver should service.
203    pub(super) fn outbound_waker(&self) -> &AtomicWaker {
204        &self.outbound_waker
205    }
206
207    /// Lock the per-stream `StreamState` map.
208    pub(super) fn streams_lock(&self) -> MutexGuard<'_, HashMap<u32, Arc<StreamState>>> {
209        self.streams
210            .lock()
211            .expect("connection streams mutex poisoned")
212    }
213
214    /// Lock the peer's SETTINGS. Cheap; held only as long as the returned guard lives.
215    /// Use the `effective_*` helpers on [`H2Settings`] to get a value with RFC defaults
216    /// applied for fields the peer hasn't set; typical callers copy out via `*guard` and
217    /// release immediately.
218    pub(super) fn current_peer_settings(&self) -> MutexGuard<'_, H2Settings> {
219        self.peer_settings
220            .lock()
221            .expect("peer_settings mutex poisoned")
222    }
223
224    /// Request that the driver emit `RST_STREAM` on this stream with the given error code and clean
225    /// up. Clears any queued outbound parts and enqueues an [`OutboundPart::Reset`][reset] —
226    /// nothing else is valid to send after a reset — then wakes the driver, which frames the
227    /// `RST_STREAM` and tears the stream down.
228    ///
229    /// First-wins idempotent: a stream already reset-requested keeps its original code. No-op if
230    /// the stream is already gone from the shared map.
231    ///
232    /// [reset]: super::transport::OutboundPart::Reset
233    pub(crate) fn stream_error(&self, stream_id: u32, code: super::H2ErrorCode) {
234        let Some(stream) = self.streams_lock().get(&stream_id).cloned() else {
235            return;
236        };
237        stream.request_reset(code);
238        self.outbound_waker.wake();
239    }
240
241    /// Resolves once the stream is fully closed — reset by either side, both halves
242    /// complete, or already gone from the stream map (including connection teardown).
243    /// Registers on the stream's recv-side waker, which the driver fires on every close
244    /// event.
245    pub(crate) fn poll_stream_closed(&self, stream_id: u32, cx: &mut Context<'_>) -> Poll<()> {
246        let Some(stream) = self.streams_lock().get(&stream_id).cloned() else {
247            return Poll::Ready(());
248        };
249        // Register before checking, so a close that lands between the check and the
250        // driver's wake still finds this waker.
251        stream.recv.waker.register(cx.waker());
252        if stream.lifecycle_lock().is_closed() {
253            Poll::Ready(())
254        } else {
255            Poll::Pending
256        }
257    }
258
259    /// Bind this `H2Connection` to a TCP transport and return an [`H2Driver`] that drives
260    /// the connection.
261    ///
262    /// The driver must be polled to completion via repeated calls to
263    /// [`H2Driver::next`] (or its [`Stream`][futures_lite::stream::Stream] impl); each returned
264    /// [`Conn`] should be spawned on its own task.
265    pub fn run<T>(self: Arc<Self>, transport: T) -> H2Driver<T>
266    where
267        T: AsyncRead + AsyncWrite + Unpin + Send,
268    {
269        H2Driver::new(self, transport, Role::Server)
270    }
271
272    /// Bind this `H2Connection` to an outbound transport and return an [`H2Initiator`] —
273    /// the background-task future a client spawns to drive the connection.
274    ///
275    /// On first poll the driver writes the 24-byte client preface and its initial
276    /// SETTINGS; thereafter it demuxes inbound frames (peer SETTINGS, response HEADERS /
277    /// DATA on our streams, etc.) and pumps outbound bytes (new stream opens, DATA,
278    /// `WINDOW_UPDATEs`) until the connection closes or errors out.
279    ///
280    /// Awaiting the returned future resolves with `Ok(())` on graceful close or
281    /// `Err(H2Error)` on protocol / I/O failure. Streams are not opened via the future
282    /// itself — client code calls stream-open primitives on `H2Connection`; this future
283    /// just runs the framing loop.
284    #[cfg(feature = "unstable")]
285    pub fn run_client<T>(self: Arc<Self>, transport: T) -> H2Initiator<T>
286    where
287        T: AsyncRead + AsyncWrite + Unpin + Send,
288    {
289        H2Initiator::new(H2Driver::new(self, transport, Role::Client))
290    }
291
292    /// Per-stream entry point — call from the runtime adapter's spawned task for each
293    /// [`Conn`] returned by [`H2Driver::next`]. Runs `handler` to produce the response,
294    /// then `send_h2` to hand the framed response to the driver.
295    ///
296    /// # Errors
297    ///
298    /// Returns the [`io::Error`] from `send_h2` if the body's `poll_read` errors or the
299    /// underlying transport fails partway through the response.
300    pub async fn process_inbound<Transport, Handler, Fut>(
301        conn: Conn<Transport>,
302        handler: Handler,
303    ) -> io::Result<Conn<Transport>>
304    where
305        Transport: AsyncRead + AsyncWrite + Unpin + Send + Sync + 'static,
306        Handler: FnOnce(Conn<Transport>) -> Fut,
307        Fut: Future<Output = Conn<Transport>>,
308    {
309        let _guard = conn.context().swansong().guard();
310        handler(conn).await.send_h2().await
311    }
312}