trillium_http/h2/acceptor.rs
1//! HTTP/2 driver loop ([`H2Driver`]) — owns the per-connection TCP transport and runs the
2//! poll-based state machine that demuxes frames, dispatches stream-opens to handler tasks, and
3//! pumps responses back out.
4//!
5//! Created by [`H2Connection::run`]. The runtime adapter calls [`H2Driver::next`] in a
6//! loop (or drives via the [`Stream`] impl, which has the same semantics); each yield either
7//! returns the next opened request stream (a [`Conn`] for the runtime to spawn a handler
8//! task against) or `None` when the connection is closed.
9//!
10//! The driver is a poll-based state machine, not an async fn. A single `drive` call is the
11//! unit of forward progress: it picks up conn-task signals, advances any in-flight response
12//! sends, drains pending outbound bytes, and advances the read cursor — parking with
13//! cancel-safe partial state when no further progress can be made.
14//!
15//! # Module layout
16//!
17//! Driver impl is split across this file and child modules to keep each focused:
18//!
19//! - **`acceptor.rs`** (this file): struct definition, the [`Self::drive`] orchestration loop, the
20//! frame read primitive (`poll_fill_to`), and the supporting enums ([`DriverState`],
21//! [`ReadPhase`], [`CloseOutcome`], [`Action`], [`StreamEntry`]).
22//! - **`acceptor::close`**: the closing lifecycle — entering `Closing` (`begin_close`), the drain
23//! on `Drained` (`poll_drain_peer`), the teardown when the driver finishes
24//! (`finish_with_current_outcome`), and [`H2Driver::close`], the transport close that follows.
25//! - **`acceptor::closed_streams`**: bounded ledger of recently-closed streams + reasons, consulted
26//! to pick the right §5.1 error category for stale peer frames.
27//! - **`acceptor::handler_signals`**: conn-task → driver work-pickup boundary. Owns the
28//! `needs_servicing` mailbox protocol — `service_handler_signals`, `pick_up_new_client_streams`,
29//! `has_pending_handler_signals`.
30//! - **`acceptor::outbound`**: outbound write/flush plumbing and `queue_*` frame helpers.
31//! - **`acceptor::recv`**: receive side — frame reader, dispatch, HEADERS+CONTINUATION
32//! accumulation, malformed-request `RST_STREAM`, DATA routing into per-stream recv rings.
33//! - **`acceptor::send`**: send pump — picks up [`SendCursor`][send::SendCursor]s from the
34//! conn-task signal pickup, frames HEADERS / DATA / trailing-HEADERS, signals completion.
35//!
36//! [`H2Connection::run`]: super::H2Connection::run
37//! [`Stream`]: futures_lite::stream::Stream
38
39mod close;
40mod closed_streams;
41mod constants;
42mod handler_signals;
43mod inflow;
44mod outbound;
45mod recv;
46mod send;
47#[cfg(test)]
48mod tests;
49mod types;
50
51use super::{H2Error, connection::H2Connection, role::Role, transport::H2Transport};
52use crate::{
53 Conn, Priority,
54 headers::hpack::{HpackDecoder, HpackEncoder},
55};
56use closed_streams::{ClosedReason, ClosedStream, ClosedStreams};
57use constants::{
58 INITIAL_CONNECTION_RECV_WINDOW, MAX_BUFFER_SIZE, MAX_DATA_CHUNK_SIZE, MAX_FLOW_CONTROL_WINDOW,
59 READ_WINDOW,
60};
61use futures_lite::io::{AsyncRead, AsyncWrite};
62use hashbrown::HashMap;
63use inflow::Inflow;
64use recv::PendingHeaders;
65use send::ScheduleEntry;
66use std::{
67 collections::BTreeMap,
68 future::Future,
69 io,
70 pin::Pin,
71 sync::Arc,
72 task::{Context, Poll, ready},
73 time::Instant,
74};
75use swansong::ShuttingDown;
76use types::{
77 AcceptorConfig, Action, CloseOutcome, DriverState, Next, ReadPhase, StreamEntry, frame_slice,
78};
79
80/// Owns the per-connection TCP transport and drives the HTTP/2 demux loop.
81///
82/// See the module docs for the high-level driver shape and how its impl is split across the
83/// `recv` and `send` child modules.
84#[derive(Debug)]
85pub struct H2Driver<T> {
86 connection: Arc<H2Connection>,
87 transport: T,
88
89 /// Role this driver runs in — see [`Role`]. Consulted at role-asymmetric branch points
90 /// (preface direction, HEADERS-on-unknown-id, HEADERS-on-known-id).
91 role: Role,
92
93 /// Overall lifecycle position of the driver.
94 state: DriverState,
95
96 /// Future that resolves when the shared `Swansong` begins shutdown. Polled each
97 /// `drive` tick while the driver is running; on resolution the driver queues a
98 /// GOAWAY and transitions to `Closing`, after which the top-of-loop guard returns
99 /// early and we never poll this again on the same acceptor.
100 shutting_down: ShuttingDown,
101
102 /// Inbound bytes, read ahead of the frame being processed. `read_buf[read_start..read_filled]`
103 /// holds everything received but not yet consumed: the current frame (which begins at
104 /// `read_start`), possibly followed by later frames. Survives a return to `Poll::Pending`,
105 /// so a partially received frame keeps its bytes.
106 read_buf: Vec<u8>,
107 read_start: usize,
108 read_filled: usize,
109 read_phase: ReadPhase,
110
111 /// Outbound byte cursor. The driver encodes control frames into `write_buf` and drains
112 /// to the transport via `poll_flush_outbound`. `write_cursor` is the offset of the
113 /// first byte not yet accepted by `poll_write`. After the buffer fully drains, both
114 /// fields are reset and a flush is issued.
115 write_buf: Vec<u8>,
116 write_cursor: usize,
117 write_flush_pending: bool,
118
119 /// HPACK decoder state, shared across all header blocks on this connection.
120 hpack: HpackDecoder,
121
122 /// HPACK encoder state. The driver is the sole owner — handlers / conn tasks
123 /// no longer touch it, so this is a plain field with no synchronization.
124 hpack_encoder: HpackEncoder,
125
126 /// Per-stream state, keyed by stream id. Driver-only — handler tasks hold their own
127 /// `Arc<StreamState>` via [`H2Transport`] and don't consult this table. The entry
128 /// bundles the shared state with driver-private bookkeeping (e.g. "have we already
129 /// advertised the recv window after seeing `is_reading`?").
130 streams: BTreeMap<u32, StreamEntry>,
131
132 /// Highest peer-initiated stream id seen so far. Peer-initiated (client) stream ids
133 /// must be odd and strictly increasing.
134 last_peer_stream_id: u32,
135
136 /// Highest client request id whose opening HEADERS have been framed. Allocation alone
137 /// does not open a stream; canceled submissions can disappear before reaching the wire.
138 last_local_stream_id: u32,
139
140 /// Last-stream id of the GOAWAY we sent, if any. A later GOAWAY may lower it, never raise it.
141 goaway_last_stream_id: Option<u32>,
142
143 /// Latest RFC 9218 priority signaled per stream via `PRIORITY_UPDATE`, keyed by stream
144 /// id. Holds entries for streams not yet opened too (an update can precede its HEADERS),
145 /// so it is bounded by [`recv::MAX_TRACKED_PRIORITIES`] as a `DoS` guard. Latest signal
146 /// wins; the request's own `priority` header (on the [`StreamEntry`]) is the fallback when
147 /// no entry is present. See [`Self::effective_priority`].
148 ///
149 /// Lookups are by stream id and nothing iterates this in order, so it's a hash map.
150 stream_priorities: HashMap<u32, Priority>,
151
152 /// Reused scratch for the send pump's priority schedule ([`ScheduleEntry`] per sending
153 /// stream), rebuilt and sorted each pump tick. Kept on the driver (rather than allocated per
154 /// tick) so the per-tick cost on this hot path is a clear + extend, not a fresh allocation.
155 /// See [`Self::advance_outbound_sends`].
156 send_schedule: Vec<ScheduleEntry>,
157
158 /// Ids of the streams holding a send cursor, which are the only streams the send pump has
159 /// work for. Scheduling from this rather than from every open stream keeps a pump tick
160 /// proportional to the responses in flight: with many concurrent streams, most are waiting
161 /// on their handlers. Pushed when a cursor is installed; ids whose cursor has since been
162 /// dropped are pruned after each pump tick.
163 sending_streams: Vec<u32>,
164
165 /// Reused buffer for the stream ids taken off the connection's signal queue each tick. Empty
166 /// between ticks.
167 signaled_scratch: Vec<u32>,
168
169 /// Accumulator for an in-progress HEADERS block that is waiting on further CONTINUATION
170 /// frames. `None` outside a HEADERS block. The spec forbids any frame on any stream
171 /// from interleaving while this is `Some`.
172 pending_headers: Option<PendingHeaders>,
173
174 /// Set once the driver decides to close: graceful (peer GOAWAY / server swansong / peer
175 /// EOF) or erroring (protocol violation → GOAWAY with code, or I/O failure → no
176 /// GOAWAY). `drive` completes (returns `None` or a final `Some(Err(...))`) once
177 /// outbound drains to empty.
178 close_outcome: Option<CloseOutcome>,
179
180 /// Set after `drive` yields its terminal result. Subsequent calls return `None` without
181 /// touching the transport.
182 finished: bool,
183
184 /// Reusable scratch the send pump reads body chunks into before framing as DATA.
185 /// Sized at [`MAX_DATA_CHUNK_SIZE`] — even if the peer permits larger frames we cap our
186 /// DATA emissions here to bound per-connection memory.
187 body_scratch: Vec<u8>,
188
189 /// Reusable scratch the HPACK encoder writes a HEADERS block into before it is copied
190 /// into `write_buf` as HEADERS/CONTINUATION fragments. Retained across responses so the
191 /// steady-state header encode allocates nothing.
192 headers_scratch: Vec<u8>,
193
194 /// Connection-level send flow-control window. Tracked as [`i64`] for symmetry with the
195 /// per-stream windows, which a mid-connection `INITIAL_WINDOW_SIZE` reduction can drive
196 /// temporarily negative; the connection window itself is *not* affected by
197 /// `SETTINGS_INITIAL_WINDOW_SIZE`. Decremented as we emit DATA; incremented by peer
198 /// `WINDOW_UPDATE(stream_id=0, inc)`. Overflow past [`MAX_FLOW_CONTROL_WINDOW`] is a
199 /// connection-level `FLOW_CONTROL_ERROR`.
200 connection_send_window: i64,
201
202 /// Connection-level receive flow-control window. Starts at the spec's 65535-octet baseline
203 /// (the spec forbids SETTINGS from altering it) and is promoted to the configured
204 /// `h2_initial_connection_window_size` via an initial `WINDOW_UPDATE(0)` right after SETTINGS,
205 /// then topped up as handlers drain across all streams. See [`Inflow`]. A peer that sends past
206 /// the granted window earns a connection-level `FLOW_CONTROL_ERROR`.
207 connection_inflow: Inflow,
208
209 /// Bounded ledger of recently-closed streams and why they closed. Consulted by
210 /// [`recv::H2Driver::classify_header_block`] when a HEADERS frame arrives on an id ≤
211 /// `last_peer_stream_id` that's not in the active map, to distinguish `RST_STREAM`-
212 /// closed (stream-level `STREAM_CLOSED`) from `END_STREAM`-closed or never-opened
213 /// (connection-level). See [`ClosedStreams`] for the eviction policy.
214 closed_streams: ClosedStreams,
215
216 /// Snapshot of the h2-relevant fields of [`HttpConfig`][crate::HttpConfig] taken at
217 /// acceptor construction. Copied in because `HttpConfig` is per-server but an acceptor
218 /// is per-connection — the config is effectively immutable over a connection's
219 /// lifetime, and a local copy avoids reaching through [`H2Connection::context`] on
220 /// every policy check.
221 ///
222 /// [`H2Connection::context`]: super::H2Connection::context
223 pub(super) config: AcceptorConfig,
224
225 /// The start time shared by streams opened from the latest transport read: read from the
226 /// clock when the first of them opens, and reset by every read. A burst of new streams reads
227 /// the clock once, and no stream's start time predates the read that completed its HEADERS.
228 burst_start: Option<Instant>,
229
230 /// Rounds of `drive` work since it last returned `Pending`. Carried across calls because
231 /// emitting a stream ends a call with `Ready`: without it, a burst of new streams would never
232 /// reach the cooperative-yield bound, and every stream in the burst would be built before any
233 /// of their handlers ran, by which time the first streams' state has gone cold.
234 rounds_since_pending: usize,
235}
236
237impl<T> H2Driver<T>
238where
239 T: AsyncRead + AsyncWrite + Unpin + Send,
240{
241 pub(super) fn new(connection: Arc<H2Connection>, transport: T, role: Role) -> Self {
242 let shutting_down = connection.swansong().shutting_down();
243 let context = connection.context();
244 let config = AcceptorConfig::from_http_config(context.config());
245 let hpack_encoder = HpackEncoder::new(
246 context.observer.clone(),
247 context.config.dynamic_table_capacity(),
248 context.config.recent_pairs_size(),
249 context.config.recent_pairs_auto(),
250 );
251 Self {
252 connection,
253 transport,
254 role,
255 state: DriverState::AwaitingPreface,
256 shutting_down,
257 read_buf: Vec::new(),
258 read_start: 0,
259 read_filled: 0,
260 read_phase: ReadPhase::NeedHeader,
261 write_buf: Vec::new(),
262 write_cursor: 0,
263 write_flush_pending: false,
264 hpack: HpackDecoder::new(config.hpack_table_capacity()),
265 hpack_encoder,
266 streams: BTreeMap::new(),
267 last_peer_stream_id: 0,
268 last_local_stream_id: 0,
269 goaway_last_stream_id: None,
270 stream_priorities: HashMap::new(),
271 send_schedule: Vec::new(),
272 sending_streams: Vec::new(),
273 signaled_scratch: Vec::new(),
274 pending_headers: None,
275 close_outcome: None,
276 finished: false,
277 body_scratch: vec![0u8; MAX_DATA_CHUNK_SIZE as usize],
278 headers_scratch: Vec::new(),
279 connection_send_window: INITIAL_CONNECTION_RECV_WINDOW,
280 connection_inflow: Inflow::new(INITIAL_CONNECTION_RECV_WINDOW),
281 closed_streams: ClosedStreams::default(),
282 config,
283 burst_start: None,
284 rounds_since_pending: 0,
285 }
286 }
287
288 /// The shared [`H2Connection`] this acceptor was created from.
289 pub fn connection(&self) -> &Arc<H2Connection> {
290 &self.connection
291 }
292
293 /// Drive the connection until the next request stream opens, the connection ends, or a
294 /// fatal protocol or I/O error occurs.
295 ///
296 /// Returns `Ok(Some(conn))` for each new request stream — the runtime adapter is
297 /// expected to spawn a handler task that consumes the [`Conn`]. Malformed requests are
298 /// handled internally with a stream-level `RST_STREAM` and never surfaced. Returns
299 /// `Ok(None)` when the connection has been shut down cleanly (peer GOAWAY, our own
300 /// swansong shutdown, peer EOF at a frame boundary).
301 ///
302 /// # Errors
303 ///
304 /// The returned future resolves to an [`H2Error`] for any *connection-level* protocol
305 /// violation detected while decoding peer frames or for an unrecoverable transport I/O
306 /// error. A final GOAWAY is sent before a protocol error is returned (best-effort; I/O
307 /// errors skip it).
308 // Mirrors `StreamExt::next` (a `&mut self -> impl Future<Output = Option<T>>` adapter),
309 // not `Iterator::next`. The driver is also `Stream`, so callers can use either.
310 #[allow(clippy::should_implement_trait)]
311 pub fn next(&mut self) -> Next<'_, T> {
312 Next { driver: self }
313 }
314
315 /// Poll-based driver core. Shared by [`Next`]'s `Future` impl, the [`Stream`] impl on
316 /// [`H2Driver`], and [`H2Initiator`][super::H2Initiator]'s client-side Future impl.
317 ///
318 /// [`Stream`]: futures_lite::stream::Stream
319 pub(super) fn drive(
320 &mut self,
321 cx: &mut Context<'_>,
322 ) -> Poll<Option<Result<Conn<H2Transport>, H2Error>>> {
323 let poll = self.drive_rounds(cx);
324 if poll.is_pending() {
325 self.rounds_since_pending = 0;
326 }
327 poll
328 }
329
330 #[allow(
331 clippy::too_many_lines,
332 reason = "state-machine orchestration; splitting muddies the read-as-a-recipe shape"
333 )]
334 fn drive_rounds(
335 &mut self,
336 cx: &mut Context<'_>,
337 ) -> Poll<Option<Result<Conn<H2Transport>, H2Error>>> {
338 if self.finished {
339 return Poll::Ready(None);
340 }
341
342 while self.rounds_since_pending < self.config.copy_loops_per_yield() {
343 self.rounds_since_pending += 1;
344 log::trace!("h2 drive loop number: {}", self.rounds_since_pending);
345 // 1. Conn-task signals. Picks up window-update intent (`is_reading`) and new
346 // `submit_send` submissions, moving them into driver-private state.
347 self.service_handler_signals();
348
349 // 2. Send pump. Turns picked-up SendCursors into HEADERS / DATA / trailing- HEADERS
350 // frame bytes in `write_buf`. Body reads that return Pending leave the cursor in
351 // place — the body's source will wake the driver task.
352 self.advance_outbound_sends(cx);
353
354 // 3. Flush any pending outbound — never re-poll reads when we still owe bytes to the
355 // peer, and never signal closure to the caller before the wire is clean.
356 match self.poll_flush_outbound(cx) {
357 Poll::Ready(Ok(())) => {}
358 Poll::Ready(Err(e)) => {
359 // Flush failure while closing: just take whatever outcome we had and
360 // shelve the fresh I/O error. While running, record and finish.
361 if self.close_outcome.is_none() {
362 self.close_outcome = Some(CloseOutcome::Io(e));
363 }
364 return Poll::Ready(self.finish_with_current_outcome());
365 }
366 Poll::Pending => return Poll::Pending,
367 }
368
369 // 4. If we were closing, outbound is now drained. For graceful shutdowns, transition to
370 // `Drained`, which reads whatever the peer has already sent before finishing. A
371 // connection error goes to `Drained` at once: its GOAWAY is out, in-flight streams
372 // are reset at finish, and no further peer frames are processed. For I/O-error
373 // shutdowns the transport is already untrustworthy, so skip the drain. Defer the
374 // graceful transition while in-flight streams still have outbound (an active
375 // SendCursor or queued parts), an open send half (a handler that hasn't submitted
376 // its response yet — half-closed-remote is *not* drained), OR inbound (recv half not
377 // yet closed) work. Without this, a handler that submits trailers *after* the
378 // cancellation race resolves gets stranded with bytes parked in mailboxes; a handler
379 // that hasn't responded yet when shutdown begins has its response `SubmitSend`
380 // orphaned by a driver that finished out from under it; and a client receiving
381 // GOAWAY mid-stream stops decoding incoming frames before the server's trailing
382 // HEADERS arrive. Falls through to step 6 so the recv pump (also gated on
383 // Running|Closing now) keeps running and parks on the transport read waker rather
384 // than the outbound-only `park` here.
385 if self.state == DriverState::Closing {
386 match self.close_outcome {
387 Some(CloseOutcome::Io(_)) => {
388 return Poll::Ready(self.finish_with_current_outcome());
389 }
390 Some(CloseOutcome::Protocol(_)) => {
391 self.set_state(DriverState::Drained, "connection error, GOAWAY flushed");
392 }
393 _ if self.has_active_send_cursors()
394 || self.has_open_send_half()
395 || self.has_pending_recv() =>
396 {
397 self.log_closing_blockers();
398 }
399 _ => self.set_state(
400 DriverState::Drained,
401 "outbound drained, no in-flight streams",
402 ),
403 }
404 }
405
406 // 5. Server-initiated shutdown check. Only relevant while we're running — once we're
407 // past the Closing/Drained transition we've already committed to a close and
408 // re-observing the swansong here would re-enter begin_close in a loop. Post-shutdown
409 // re-polls of `ShuttingDown` are harmless themselves (event_listener-backed, not
410 // single-shot) but the re-entry isn't.
411 if self.state == DriverState::Running
412 && Pin::new(&mut self.shutting_down).poll(cx).is_ready()
413 {
414 self.begin_close(CloseOutcome::Graceful);
415 continue;
416 }
417
418 // 6. State-specific step.
419 match self.state {
420 DriverState::AwaitingPreface => {
421 // Role-asymmetric: server reads the 24-byte preface off the wire; client
422 // writes it to `write_buf` (the next drain tick flushes it, then our
423 // SETTINGS, then the peer's SETTINGS arrives as the first frame in Running).
424 let poll = match self.role {
425 Role::Server => self.poll_read_preface(cx),
426 Role::Client => {
427 self.queue_client_preface();
428 Poll::Ready(Ok(()))
429 }
430 };
431 match poll {
432 Poll::Ready(Ok(())) => {
433 self.set_state(DriverState::NeedsServerSettings, "preface complete");
434 }
435 Poll::Ready(Err(e)) => {
436 self.close_outcome = Some(e);
437 return Poll::Ready(self.finish_with_current_outcome());
438 }
439 Poll::Pending => {
440 if self.park(cx) {
441 return Poll::Pending;
442 }
443 }
444 }
445 }
446
447 DriverState::NeedsServerSettings => {
448 self.queue_settings();
449 // The spec forbids SETTINGS from altering the connection-level
450 // flow-control window — it stays at the 65535 baseline unless we raise
451 // it via `WINDOW_UPDATE(0)`. Do that immediately after SETTINGS so peer
452 // bulk uploads aren't capped at ~5 Mbit/s × RTT.
453 let raise = self
454 .connection_inflow
455 .raise_target(i64::from(self.config.initial_connection_window_size()));
456 if raise > 0 {
457 self.queue_window_update(0, u32::try_from(raise).unwrap_or(u32::MAX));
458 }
459 self.set_state(DriverState::Running, "initial SETTINGS queued");
460 }
461
462 // Read pump runs in both Running and Closing so a Closing-side driver
463 // (we sent or received GOAWAY) keeps decoding inbound frames for streams
464 // that haven't reached recv-closed yet — e.g. trailing HEADERS for an
465 // in-flight server-stream the peer is about to send. New `Action::Emit`
466 // streams are ignored in Closing: post-GOAWAY the peer shouldn't be
467 // opening new ones (and we wouldn't want to dispatch handlers for them
468 // even if it did).
469 DriverState::Running | DriverState::Closing => match self.poll_advance_read(cx) {
470 Poll::Ready(Ok(Action::Continue)) => {}
471 Poll::Ready(Ok(Action::Emit(conn))) => {
472 if self.state == DriverState::Running {
473 return Poll::Ready(Some(Ok(conn)));
474 }
475 // Closing — drop the conn; outer loop continues processing
476 // remaining in-flight streams until drained.
477 }
478 Poll::Ready(Ok(Action::Close(outcome))) => {
479 self.begin_close(outcome);
480 }
481 // Protocol errors need a GOAWAY on the wire before we terminate;
482 // `begin_close` queues that — escalating a graceful close already in
483 // progress — so the next outer-loop iteration flushes it. Io errors
484 // short-circuit: if we're already Closing, the transport is gone, so finish
485 // without looping forever waiting for in-flight streams (`has_pending_recv`
486 // can't decide on its own that the peer is never sending again).
487 Poll::Ready(Err(e)) => {
488 if self.state == DriverState::Closing && matches!(e, CloseOutcome::Io(_)) {
489 self.close_outcome.get_or_insert(e);
490 return Poll::Ready(self.finish_with_current_outcome());
491 }
492 self.begin_close(e);
493 }
494 Poll::Pending => {
495 if self.park(cx) {
496 return Poll::Pending;
497 }
498 }
499 },
500
501 DriverState::Drained => match self.poll_drain_peer(cx) {
502 Poll::Ready(()) => {
503 return Poll::Ready(self.finish_with_current_outcome());
504 }
505 Poll::Pending => return Poll::Pending,
506 },
507 }
508 }
509
510 // Cooperative yield: we made `copy_loops_per_yield` rounds of progress without
511 // hitting an internal Pending, counting rounds that ended a call by emitting a stream.
512 // Re-arm immediately and let the runtime pick up anything else it has waiting —
513 // notably the handler tasks for the streams just emitted — before we resume.
514 cx.waker().wake_by_ref();
515 Poll::Pending
516 }
517
518 /// Register the driver's waker with the shared `outbound_waker` (so handler tasks can
519 /// wake the driver) and tell the caller whether it's safe to park. Returns `true` if
520 /// the driver should return `Poll::Pending`, or `false` if a handler produced work
521 /// between our last check and the registration — in which case the caller should loop
522 /// around to pick it up.
523 fn park(&mut self, cx: &mut Context<'_>) -> bool {
524 self.connection.outbound_waker().register(cx.waker());
525 !self.has_pending_handler_signals() && !self.has_pending_outbound_progress()
526 }
527
528 /// The sole mutator of `self.state`. Logs every transition so a trace log reads as
529 /// a sequence of named lifecycle events.
530 fn set_state(&mut self, new: DriverState, reason: &'static str) {
531 if self.state == new {
532 return;
533 }
534 log::trace!(
535 "h2 driver: state {old:?} → {new:?} ({reason})",
536 old = self.state,
537 );
538 self.state = new;
539 }
540
541 /// Make the first `target` bytes of the current frame available at `read_buf[read_start..]`,
542 /// reading from the transport as needed. Each read takes whatever the transport has, up to
543 /// the free space, so it can also pick up frames that follow. Cancel-safe: if the caller
544 /// drops the Future, bytes already read stay buffered.
545 ///
546 /// A 0-byte read is surfaced as `UnexpectedEof`. The caller maps this to a terminal
547 /// I/O error; we don't emit a GOAWAY on peer-initiated close.
548 fn poll_fill_to(&mut self, target: usize, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
549 while self.read_filled - self.read_start < target {
550 if self.read_start > 0 {
551 // Slide the partial frame to the front so the read gets all the free space.
552 self.read_buf
553 .copy_within(self.read_start..self.read_filled, 0);
554 self.read_filled -= self.read_start;
555 self.read_start = 0;
556 }
557 let len = target.max(READ_WINDOW);
558 if self.read_buf.len() < len {
559 self.read_buf.resize(len, 0);
560 }
561 let n = ready!(
562 Pin::new(&mut self.transport).poll_read(cx, &mut self.read_buf[self.read_filled..])
563 )?;
564 if n == 0 {
565 return Poll::Ready(Err(io::Error::from(io::ErrorKind::UnexpectedEof)));
566 }
567 self.read_filled += n;
568 self.burst_start = None;
569 }
570 Poll::Ready(Ok(()))
571 }
572
573 /// Consume `len` bytes from the front of the buffered input: a dispatched frame, or the
574 /// connection preface.
575 fn consume_read(&mut self, len: usize) {
576 self.read_start += len;
577 self.read_phase = ReadPhase::NeedHeader;
578 if self.read_start == self.read_filled {
579 self.read_start = 0;
580 self.read_filled = 0;
581 // Release a buffer that ballooned for a big frame.
582 if self.read_buf.capacity() > MAX_BUFFER_SIZE / 16 {
583 self.read_buf = Vec::new();
584 }
585 }
586 }
587
588 /// Look up how a stream closed. `None` means either never-opened or evicted from the
589 /// bounded ledger.
590 pub(super) fn closed_stream(&self, stream_id: u32) -> Option<ClosedStream> {
591 self.closed_streams.get(stream_id)
592 }
593
594 /// Whether `stream_id` is still idle: never opened by the endpoint that initiates it.
595 /// Unlike [`Self::closed_stream`], this is exact for every id; it is derived from
596 /// stream-id watermarks rather than the bounded ledger.
597 pub(super) fn stream_is_idle(&self, stream_id: u32) -> bool {
598 // Push is disabled, so even-numbered streams have no opening history in either role.
599 let last_opened = if stream_id.is_multiple_of(2) {
600 0
601 } else if self.role == Role::Client {
602 self.last_local_stream_id
603 } else {
604 self.last_peer_stream_id
605 };
606 stream_id > last_opened
607 }
608}