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;
41use std::{
42 collections::{HashMap, VecDeque},
43 future::Future,
44 io,
45 sync::{
46 Arc, Mutex, MutexGuard,
47 atomic::{AtomicBool, Ordering},
48 },
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 #[cfg(feature = "unstable")]
101 pub(super) next_client_stream_id: std::sync::atomic::AtomicU32,
102 /// Outstanding active PINGs awaiting ACKs, keyed by opaque payload. Completed by the
103 /// driver when a `PING { ack: true }` arrives whose payload matches an entry. Drained
104 /// on connection close so awaiting `send_ping` futures don't leak.
105 pub(super) pending_pings: Mutex<HashMap<[u8; 8], PendingPing>>,
106 /// Opaque payloads queued for outbound `PING { ack: false }` emission. Decoupled from
107 /// `pending_pings` so registration and queuing can happen without holding two locks.
108 pub(super) pending_ping_outbound: Mutex<VecDeque<[u8; 8]>>,
109}
110
111impl H2Connection {
112 /// Construct a new `H2Connection` to manage HTTP/2 for a single peer.
113 pub fn new(context: Arc<HttpContext>) -> Arc<Self> {
114 let swansong = context.swansong().child();
115 Arc::new(Self {
116 context,
117 swansong,
118 outbound_waker: AtomicWaker::new(),
119 streams: Mutex::new(HashMap::new()),
120 peer_settings: Mutex::new(H2Settings::default()),
121 peer_settings_received: AtomicBool::new(false),
122 peer_settings_event: Event::new(),
123 #[cfg(feature = "unstable")]
124 next_client_stream_id: std::sync::atomic::AtomicU32::new(1),
125 pending_pings: Mutex::new(HashMap::new()),
126 pending_ping_outbound: Mutex::new(VecDeque::new()),
127 })
128 }
129
130 /// The [`HttpContext`] this connection was constructed with.
131 pub fn context(&self) -> Arc<HttpContext> {
132 self.context.clone()
133 }
134
135 /// The connection-scoped [`Swansong`]. Shuts down on peer GOAWAY or when the server-
136 /// level swansong shuts down.
137 pub fn swansong(&self) -> &Swansong {
138 &self.swansong
139 }
140
141 /// Attempt graceful shutdown of this HTTP/2 connection.
142 pub fn shut_down(&self) -> ShutdownCompletion {
143 self.swansong.shut_down()
144 }
145
146 /// Whether a fresh stream could be opened on this connection right now.
147 ///
148 /// `true` requires: the connection is running (no GOAWAY received, swansong not asked
149 /// to shut down), inflight streams are below the peer's advertised
150 /// `MAX_CONCURRENT_STREAMS`, and the client stream-id space is not exhausted (capped
151 /// at `2^31 - 1`).
152 ///
153 /// `false` doesn't mean the connection is dead — it might just be saturated and free
154 /// up momentarily. Callers should keep saturated connections in their pool rather than
155 /// evicting; pair this with a separate aliveness check to decide eviction.
156 ///
157 /// Stream-id exhaustion is the one "false" case that *is* permanent: the connection
158 /// will never accept another `open_stream` call, though in-flight streams will still
159 /// complete.
160 ///
161 /// # Panics
162 ///
163 /// Panics if any per-connection mutex is poisoned.
164 #[cfg(feature = "unstable")]
165 pub fn can_open_stream(&self) -> bool {
166 if !self.swansong.state().is_running() {
167 return false;
168 }
169 // Stream-id exhaustion check guards against an exhausted connection passing the
170 // inflight-vs-MAX_CONCURRENT_STREAMS check (no streams in flight → counts as 0)
171 // and the pool selecting it as Available, only for `open_stream` to fail at the
172 // call site with a misleading "shutting down" error.
173 if self.next_client_stream_id.load(Ordering::Relaxed) >= (1u32 << 31) {
174 return false;
175 }
176 // Count wire-active streams only — entries the application is still holding after
177 // a clean wire-close stay in the map but don't count against the peer's
178 // MAX_CONCURRENT_STREAMS.
179 let inflight: u32 = self
180 .streams_lock()
181 .values()
182 .filter(|s| {
183 !(s.send.completed.load(Ordering::Acquire) && s.lifecycle_lock().recv_eof())
184 })
185 .count()
186 .try_into()
187 .unwrap_or(u32::MAX);
188 let cap = self
189 .current_peer_settings()
190 .effective_max_concurrent_streams();
191 inflight < cap
192 }
193
194 /// Driver-side wake primitive. Fire after producing work the driver should service.
195 pub(super) fn outbound_waker(&self) -> &AtomicWaker {
196 &self.outbound_waker
197 }
198
199 /// Lock the per-stream `StreamState` map.
200 pub(super) fn streams_lock(&self) -> MutexGuard<'_, HashMap<u32, Arc<StreamState>>> {
201 self.streams
202 .lock()
203 .expect("connection streams mutex poisoned")
204 }
205
206 /// Lock the peer's SETTINGS. Cheap; held only as long as the returned guard lives.
207 /// Use the `effective_*` helpers on [`H2Settings`] to get a value with RFC defaults
208 /// applied for fields the peer hasn't set; typical callers copy out via `*guard` and
209 /// release immediately.
210 pub(super) fn current_peer_settings(&self) -> MutexGuard<'_, H2Settings> {
211 self.peer_settings
212 .lock()
213 .expect("peer_settings mutex poisoned")
214 }
215
216 // `release_stream` (previously a conn-level helper called from `H2Transport::Drop`)
217 // is no longer needed — the Drop impl transitions the lifecycle to `AwaitingRelease`
218 // directly. The transition has the same observable effects (wake driver, raise
219 // `needs_servicing`, mark variant) and removes one indirection.
220
221 /// Request that the driver emit `RST_STREAM` on this stream with the given error code
222 /// and clean up. Transitions the lifecycle to
223 /// [`StreamLifecycle::ResetRequested`][super::lifecycle::StreamLifecycle::ResetRequested]
224 /// and wakes the driver.
225 ///
226 /// First-wins idempotent: a stream already in `ResetRequested` or terminal `Reset`
227 /// state does not have its code overwritten. No-op if the stream is already gone from
228 /// the shared map.
229 pub(crate) fn stream_error(&self, stream_id: u32, code: super::H2ErrorCode) {
230 let Some(stream) = self.streams_lock().get(&stream_id).cloned() else {
231 return;
232 };
233 let mut lifecycle = stream.lifecycle_lock();
234 if matches!(
235 &*lifecycle,
236 super::lifecycle::StreamLifecycle::ResetRequested(_)
237 | super::lifecycle::StreamLifecycle::Reset(_)
238 ) {
239 return;
240 }
241 *lifecycle = super::lifecycle::StreamLifecycle::ResetRequested(code);
242 drop(lifecycle);
243 stream.needs_servicing.store(true, Ordering::Release);
244 self.outbound_waker.wake();
245 }
246
247 /// Bind this `H2Connection` to a TCP transport and return an [`H2Driver`] that drives
248 /// the connection.
249 ///
250 /// The driver must be polled to completion via repeated calls to
251 /// [`H2Driver::next`] (or its [`Stream`][futures_lite::stream::Stream] impl); each returned
252 /// [`Conn`] should be spawned on its own task.
253 pub fn run<T>(self: Arc<Self>, transport: T) -> H2Driver<T>
254 where
255 T: AsyncRead + AsyncWrite + Unpin + Send,
256 {
257 H2Driver::new(self, transport, Role::Server)
258 }
259
260 /// Bind this `H2Connection` to an outbound transport and return an [`H2Initiator`] —
261 /// the background-task future a client spawns to drive the connection.
262 ///
263 /// On first poll the driver writes the 24-byte client preface and its initial
264 /// SETTINGS; thereafter it demuxes inbound frames (peer SETTINGS, response HEADERS /
265 /// DATA on our streams, etc.) and pumps outbound bytes (new stream opens, DATA,
266 /// `WINDOW_UPDATEs`) until the connection closes or errors out.
267 ///
268 /// Awaiting the returned future resolves with `Ok(())` on graceful close or
269 /// `Err(H2Error)` on protocol / I/O failure. Streams are not opened via the future
270 /// itself — client code calls stream-open primitives on `H2Connection`; this future
271 /// just runs the framing loop.
272 #[cfg(feature = "unstable")]
273 pub fn run_client<T>(self: Arc<Self>, transport: T) -> H2Initiator<T>
274 where
275 T: AsyncRead + AsyncWrite + Unpin + Send,
276 {
277 H2Initiator::new(H2Driver::new(self, transport, Role::Client))
278 }
279
280 /// Per-stream entry point — call from the runtime adapter's spawned task for each
281 /// [`Conn`] returned by [`H2Driver::next`]. Runs `handler` to produce the response,
282 /// then `send_h2` to hand the framed response to the driver.
283 ///
284 /// # Errors
285 ///
286 /// Returns the [`io::Error`] from `send_h2` if the body's `poll_read` errors or the
287 /// underlying transport fails partway through the response.
288 pub async fn process_inbound<Transport, Handler, Fut>(
289 conn: Conn<Transport>,
290 handler: Handler,
291 ) -> io::Result<Conn<Transport>>
292 where
293 Transport: AsyncRead + AsyncWrite + Unpin + Send + Sync + 'static,
294 Handler: FnOnce(Conn<Transport>) -> Fut,
295 Fut: Future<Output = Conn<Transport>>,
296 {
297 let _guard = conn.context().swansong().guard();
298 handler(conn).await.send_h2().await
299 }
300}