Skip to main content

trillium_http/h2/
transport.rs

1//! Per-stream transport handed to handler tasks.
2//!
3//! [`H2Transport`] is the [`AsyncRead`] + [`AsyncWrite`] view of a single HTTP/2 stream. It is
4//! carried on the emitted [`Conn`][crate::Conn] returned from [`H2Driver::next`], and the
5//! runtime adapter spawns a handler task that consumes it. The transport never touches the
6//! underlying TCP connection directly — all I/O coordinates through shared per-stream state
7//! on the [`H2Connection`] driven by the driver task.
8//!
9//! Two paths reach the impls:
10//!
11//! - **Normal HTTP/2 request/response**: handlers usually don't touch [`H2Transport`] directly
12//!   (same sharp edge h1 and h3 document). [`ReceivedBody`][crate::ReceivedBody] reads request body
13//!   bytes through the transport's `AsyncRead`. Response bytes are handed to the driver as a queue
14//!   of [`OutboundPart`]s via [`H2Connection::submit_send`][submit_send]; the send pump frames them
15//!   without ever touching this `AsyncWrite`.
16//!
17//! - **Extended-CONNECT upgrades** ([RFC 8441] WebSocket-over-h2, plus the in-progress
18//!   `draft-ietf-webtrans-http2` for WebTransport-over-h2): after the handler responds 200 to a
19//!   `CONNECT` request with a `:protocol` pseudo-header, [`Conn::send_h2`][crate::Conn::send_h2]
20//!   routes through [`H2Connection::submit_upgrade`][submit_upgrade], which enqueues HEADERS (and
21//!   an optional prelude body) *without* a terminating [`OutboundPart::Close`], leaving the stream
22//!   open as a bidirectional byte channel. The runtime adapter then dispatches
23//!   [`Handler::upgrade`][trillium::Handler::upgrade], which gets an [`Upgrade`][crate::Upgrade]
24//!   wrapping this transport. `AsyncWrite::poll_write` appends to a per-stream outbound ring
25//!   ([`SendState::outbound`]); the send pump drains it into DATA frames bounded by the per-stream
26//!   and connection send windows. `AsyncWrite::poll_close` enqueues [`OutboundPart::Close`] so the
27//!   driver emits the `END_STREAM` terminator and tears the stream down.
28//!
29//! [`H2Driver::next`]: super::H2Driver::next
30//! [`H2Connection`]: super::H2Connection
31//! [submit_send]: super::H2Connection::submit_send
32//! [submit_upgrade]: super::H2Connection::submit_upgrade
33//! [RFC 8441]: https://www.rfc-editor.org/rfc/rfc8441
34
35use super::{
36    H2Body, H2Connection, H2ErrorCode,
37    role::Role,
38    stream_state::{StreamEvent, StreamLifecycle},
39};
40use crate::{
41    Buffer, Headers, Status,
42    headers::hpack::{FieldSection, PseudoHeaders},
43};
44use atomic_waker::AtomicWaker;
45use futures_lite::io::{AsyncRead, AsyncWrite};
46use std::{
47    collections::VecDeque,
48    fmt, io,
49    pin::Pin,
50    sync::{
51        Arc, Mutex, MutexGuard,
52        atomic::{AtomicBool, AtomicU64, Ordering},
53    },
54    task::{Context, Poll},
55};
56
57/// A single HTTP/2 stream's transport handle.
58///
59/// Carries a backref to the shared [`H2Connection`], the stream id, and the per-stream
60/// `Arc<StreamState>` used by the read and write sides. Normal HTTP/2 operation reads through
61/// [`ReceivedBody`][crate::ReceivedBody] and writes through the driver's send queue; the
62/// `AsyncRead` / `AsyncWrite` impls here are only reached by code that borrows the transport
63/// directly (typically an upgrade handler after extended CONNECT).
64pub struct H2Transport {
65    connection: Arc<H2Connection>,
66    stream_id: u32,
67    state: Arc<StreamState>,
68    role: Role,
69}
70
71impl fmt::Debug for H2Transport {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.debug_struct("H2Transport")
74            .field("stream_id", &self.stream_id)
75            .finish_non_exhaustive()
76    }
77}
78
79impl H2Transport {
80    /// Create a transport for a stream that has just been opened by the driver.
81    pub(super) fn new(
82        connection: Arc<H2Connection>,
83        stream_id: u32,
84        state: Arc<StreamState>,
85        role: Role,
86    ) -> Self {
87        Self {
88            connection,
89            stream_id,
90            state,
91            role,
92        }
93    }
94
95    /// The stream identifier this transport is bound to.
96    pub fn stream_id(&self) -> u32 {
97        self.stream_id
98    }
99
100    /// The shared [`H2Connection`] backing this stream.
101    pub fn connection(&self) -> &Arc<H2Connection> {
102        &self.connection
103    }
104}
105
106impl Drop for H2Transport {
107    /// Application-side release / cancel signal, decided from the stream's protocol state plus
108    /// whether a response has been handed off:
109    ///
110    /// - **Already removed from the shared map** — the driver beat us to cleanup; no-op.
111    /// - **`Closed`** (both halves done on the wire; client-role streams linger in the map for
112    ///   post-EOF trailer/response access) — set `SendState::transport_dropped` so the driver GCs
113    ///   the lingering entry.
114    /// - **Send half still open + a response was submitted** (`submit_resolved`) — a bidirectional
115    ///   upgrade tunnel the handler is dropping; enqueue `OutboundPart::Close` for a graceful
116    ///   `END_STREAM`.
117    /// - **Anything else** (`HalfClosedLocal` awaiting the peer, or send-open with no response ever
118    ///   submitted) — abandoning the stream; enqueue `RST_STREAM(Cancel)`.
119    ///
120    /// A server stream dropped while its handler panics, with the response unfinished, is a server
121    /// failure rather than a cancellation: it gets a bodyless `500` if no response had been staged,
122    /// and otherwise `RST_STREAM(INTERNAL_ERROR)`.
123    fn drop(&mut self) {
124        if !self.connection.streams_lock().contains_key(&self.stream_id) {
125            log::trace!(
126                "h2 stream {}: H2Transport dropped on already-released stream",
127                self.stream_id,
128            );
129            return;
130        }
131
132        let lifecycle = *self.state.lifecycle_lock();
133        // Unwinding drops the panicking handler's conn, and with it this transport.
134        let handler_panicked = self.role == Role::Server && std::thread::panicking();
135        if handler_panicked && !lifecycle.send_closed() {
136            if self.state.send.started.load(Ordering::Acquire) {
137                log::error!(
138                    "h2 stream {}: handler panicked mid-response — RST_STREAM(INTERNAL_ERROR)",
139                    self.stream_id,
140                );
141                self.state.request_reset(H2ErrorCode::InternalError);
142            } else {
143                log::error!(
144                    "h2 stream {}: handler panicked before responding — 500",
145                    self.stream_id,
146                );
147                self.state.stage([
148                    OutboundPart::Headers {
149                        pseudos: PseudoHeaders::default().with_status(Status::InternalServerError),
150                        headers: Arc::new(Headers::new()),
151                    },
152                    OutboundPart::Close,
153                ]);
154            }
155        } else if lifecycle.is_closed() {
156            log::trace!(
157                "h2 stream {}: H2Transport dropped on wire-closed stream — releasing",
158                self.stream_id,
159            );
160            self.state
161                .send
162                .transport_dropped
163                .store(true, Ordering::Release);
164        } else if !lifecycle.send_closed()
165            && self.state.send.submit_resolved.load(Ordering::Acquire)
166        {
167            // Send half open and a response is on the wire: an upgrade tunnel being dropped.
168            // Graceful close.
169            log::trace!(
170                "h2 stream {}: H2Transport dropped (upgrade tunnel) — scheduling graceful close",
171                self.stream_id,
172            );
173            self.state.request_close();
174        } else {
175            // Send half closed awaiting the peer, or never-responded: abandon the stream.
176            log::debug!(
177                "h2 stream {}: H2Transport dropped mid-stream — RST_STREAM(Cancel)",
178                self.stream_id,
179            );
180            self.state.request_reset(H2ErrorCode::Cancel);
181        }
182        self.state.send.outbound_write_waker.wake();
183        self.connection.signal_driver(self.stream_id, &self.state);
184    }
185}
186
187impl AsyncRead for H2Transport {
188    fn poll_read(
189        self: Pin<&mut Self>,
190        cx: &mut Context<'_>,
191        out: &mut [u8],
192    ) -> Poll<io::Result<usize>> {
193        if out.is_empty() {
194            return Poll::Ready(Ok(0));
195        }
196
197        // The first `poll_read` is the handler's declaration of intent to consume the request
198        // body — until this point, we've advertised a zero recv window and the peer has sent
199        // nothing beyond HEADERS. Tell the driver to top up our per-stream window now. Later
200        // calls CAS-fail silently and don't re-signal.
201        let recv_state = &self.state.recv;
202        let connection = &*self.connection;
203        if !recv_state.is_reading.swap(true, Ordering::AcqRel) {
204            connection.signal_driver(self.stream_id, &self.state);
205        }
206
207        let mut recv = recv_state.buf.lock().expect("recv buf mutex poisoned");
208
209        // Copy as many bytes as fit from the front of the ring into `out`, then advance the
210        // ring's virtual read cursor. `Buffer::ignore_front` truncates the underlying `Vec` to
211        // zero when we drain fully, so capacity stays bounded by peak in-flight bytes rather
212        // than cumulative traffic.
213        let take = out.len().min(recv.len());
214        if take > 0 {
215            out[..take].copy_from_slice(&recv[..take]);
216            recv.ignore_front(take);
217            // Counted under the buffer lock, so a driver releasing a removed stream's window sees
218            // each byte exactly once: still buffered, or consumed.
219            recv_state
220                .bytes_consumed
221                .fetch_add(take as u64, Ordering::AcqRel);
222            drop(recv);
223            connection.signal_driver(self.stream_id, &self.state);
224            return Poll::Ready(Ok(take));
225        }
226
227        // Buffer empty. Register the waker *before* releasing the buf lock so a driver push
228        // between this poll and the recv-closed check is guaranteed to wake us:
229        //   1. We take buf lock (driver-push blocked).
230        //   2. We register waker.
231        //   3. We drop buf lock (driver-push may now proceed and fire waker).
232        //   4. We read recv-closed from the lifecycle.
233        //   5. Return Pending or Ready(0); if a push raced through step 3, the waker is registered
234        //      and a fresh poll will see the new bytes.
235        recv_state.waker.register(cx.waker());
236        drop(recv);
237        if self.state.lifecycle_lock().recv_closed() {
238            return Poll::Ready(Ok(0));
239        }
240        Poll::Pending
241    }
242}
243
244impl AsyncWrite for H2Transport {
245    fn poll_write(
246        self: Pin<&mut Self>,
247        cx: &mut Context<'_>,
248        buf: &[u8],
249    ) -> Poll<io::Result<usize>> {
250        // Parity with h1/h3: writing to a stream whose send half is already closed (clean
251        // `END_STREAM`, or reset) is a `BrokenPipe` rather than silently swallowed bytes.
252        // Otherwise we always accept the write — the "don't write at an inappropriate time"
253        // contract is the caller's, same as borrowing the raw transport in h1/h3.
254        if self.state.lifecycle_lock().send_closed() {
255            return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into()));
256        }
257
258        // Append into the per-stream outbound ring. The send pump drains the same ring into DATA
259        // frames bounded by per-stream + connection send windows. Bounded by
260        // `response_buffer_max_len` (the cap h1 and h3 use for their transit buffers): a stalled
261        // peer window means the driver can't drain, the cap is hit, and we return `Pending` so the
262        // handler is throttled. The drain side wakes `outbound_write_waker` after each take.
263        let send = &self.state.send;
264        let cap = self.connection.context.config.response_buffer_max_len;
265        let mut outbound = send.outbound.lock().expect("outbound buf mutex poisoned");
266        if outbound.len() >= cap {
267            // Register first, then re-check under lock to close the race against the drain side
268            // (which takes the same lock to `ignore_front` and then wakes us).
269            send.outbound_write_waker.register(cx.waker());
270            if outbound.len() >= cap {
271                return Poll::Pending;
272            }
273        }
274        let take = (cap - outbound.len()).min(buf.len());
275        log::trace!(
276            "h2 stream {}: H2Transport::poll_write appending {take}/{} bytes to outbound ring",
277            self.stream_id,
278            buf.len(),
279        );
280        outbound.extend_live(&buf[..take]);
281        drop(outbound);
282
283        // Wake the driver (parked on the connection-level waker).
284        self.connection.outbound_waker().wake();
285        Poll::Ready(Ok(take))
286    }
287
288    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
289        // Best-effort: bytes appended via `poll_write` are already visible to the driver and will
290        // be framed on the next tick. There's no application-level "flushed" state below us.
291        Poll::Ready(Ok(()))
292    }
293
294    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
295        // Mark the write half closed by enqueuing the `END_STREAM` terminator. Once the driver
296        // drains the remaining outbound ring bytes it frames the terminator and tears the stream
297        // down. Idempotent — `request_close` is a no-op if a terminator is already queued or the
298        // send half is already closed.
299        log::trace!(
300            "h2 stream {}: H2Transport::poll_close enqueuing Close",
301            self.stream_id,
302        );
303        self.state.request_close();
304        self.state.send.outbound_write_waker.wake();
305        self.connection.signal_driver(self.stream_id, &self.state);
306        Poll::Ready(Ok(()))
307    }
308}
309
310/// A unit of outbound work the conn task hands the driver, framed in order by the send pump.
311///
312/// `Headers` opens the response/request; `Body` is an owned source the driver frames lazily under
313/// flow control (no intermediate buffering); `Trailers` and `Close` are alternative `END_STREAM`
314/// terminators; `Reset` abandons the stream (the conn task clears the rest of the queue when it
315/// pushes one — nothing else is valid to send after `RST_STREAM`).
316///
317/// Streaming bytes a handler writes through [`H2Transport`]'s `AsyncWrite` do *not* go here — they
318/// flow through the reused [`SendState::outbound`] ring, which the pump drains before framing a
319/// terminator.
320#[derive(Debug)]
321pub(super) enum OutboundPart {
322    /// Initial HEADERS block — HPACK-encoded by the driver at frame time so the wire order
323    /// matches the dynamic-table mutation order. Shared, so a submitter that keeps its headers
324    /// readable after sending doesn't have to copy them.
325    Headers {
326        pseudos: PseudoHeaders<'static>,
327        headers: Arc<Headers>,
328    },
329    /// An owned body source, framed directly into DATA frames under flow control. Wrapped as an
330    /// [`H2Body`] from the moment it's staged, so even a queued body that's discarded unsent drops
331    /// with its panics contained.
332    Body(H2Body),
333    /// Trailing HEADERS — carries `END_STREAM`.
334    Trailers(Headers),
335    /// Empty `DATA(END_STREAM)` terminator.
336    Close,
337    /// `RST_STREAM(code)` — conn-task-initiated reset; clears any preceding queued parts.
338    Reset(H2ErrorCode),
339}
340
341impl OutboundPart {
342    /// `true` for the `END_STREAM`/`RST_STREAM` terminators — used by `request_close` to stay
343    /// idempotent and by the send pump to know the ring must be drained first.
344    pub(super) fn is_terminal(&self) -> bool {
345        matches!(self, Self::Trailers(_) | Self::Close | Self::Reset(_))
346    }
347}
348
349/// Shared per-stream state. Owned by an [`Arc`] held jointly by the driver (via the connection's
350/// stream table) and the handler task (via [`H2Transport`]).
351///
352/// The cross-task-visible protocol state machine is the [`StreamLifecycle`] in [`Self::lifecycle`]
353/// — written only by the driver (which feeds it [`StreamEvent`]s as it frames/receives) and read by
354/// both sides. Everything else is data and mailbox plumbing: the recv ring, the outbound parts
355/// queue + streaming ring, and the conn-task → driver signals.
356#[derive(Debug, Default)]
357pub(super) struct StreamState {
358    /// Protocol state (RFC 9113 §5.1). Driver is the sole writer; the handler side reads it for
359    /// recv-EOF (`poll_read`) and send-closed (`poll_write`) decisions. Held under a `Mutex` so
360    /// observe-then-act sequences are atomic.
361    lifecycle: Mutex<StreamLifecycle>,
362
363    /// Recv side: inbound DATA payloads, handler waker, handler-intent signal, trailers.
364    pub(super) recv: RecvState,
365
366    /// Send side: the outbound parts queue, the streaming ring, the driver→conn completion
367    /// channel, and the application-release signal.
368    pub(super) send: SendState,
369
370    /// Whether this stream is already in the connection's queue of signaled streams. Set by
371    /// [`H2Connection::signal_driver`] when it queues the stream, which conn-task code calls
372    /// whenever it produces work for the driver (enqueue a part, raise `is_reading`, increment
373    /// `bytes_consumed`, set `transport_dropped`); cleared by the driver when it takes the stream
374    /// off the queue, *before* it reads the stream's mailbox. So a signal racing the driver
375    /// either lands in what the driver reads or queues the stream again.
376    ///
377    /// Only `signal_driver` may set it: a stream whose flag is set without being queued would
378    /// never be queued again.
379    pub(super) needs_servicing: AtomicBool,
380}
381
382impl StreamState {
383    /// Lock the per-stream protocol lifecycle. Convenience wrapper — every site treats poisoning as
384    /// a programming error.
385    pub(super) fn lifecycle_lock(&self) -> MutexGuard<'_, StreamLifecycle> {
386        self.lifecycle.lock().expect("lifecycle mutex poisoned")
387    }
388
389    /// Apply a [`StreamEvent`] to the lifecycle. Driver-only — the sole writer of protocol state.
390    pub(super) fn apply_event(
391        &self,
392        event: StreamEvent,
393    ) -> Result<(), super::stream_state::StreamProtocolError> {
394        self.lifecycle_lock().on_event(event)
395    }
396
397    /// Stage a full submission of outbound parts atomically, so the send pump sees a complete
398    /// message rather than a partial one (the `SubmitSend` future keys "done" off the queue
399    /// draining to empty). The caller signals the driver.
400    pub(super) fn stage(&self, parts: impl IntoIterator<Item = OutboundPart>) {
401        self.send.started.store(true, Ordering::Release);
402        self.send
403            .queue
404            .lock()
405            .expect("send queue mutex poisoned")
406            .extend(parts);
407    }
408
409    /// Enqueue the `END_STREAM` terminator unless one (or a reset) is already queued or the send
410    /// half is already closed. Idempotent — safe to call from repeated `poll_close` / Drop. The
411    /// caller signals the driver.
412    pub(super) fn request_close(&self) {
413        if self.lifecycle_lock().send_closed() {
414            return;
415        }
416        let mut queue = self.send.queue.lock().expect("send queue mutex poisoned");
417        if queue.back().is_none_or(|p| !p.is_terminal()) {
418            queue.push_back(OutboundPart::Close);
419        }
420    }
421
422    /// Clear any queued parts and request `RST_STREAM(code)`. First-wins: a reset already at the
423    /// back keeps its code. Nothing else is valid to send after a reset, so clearing the queue
424    /// models the §5.1 sequence faithfully. The caller signals the driver.
425    pub(super) fn request_reset(&self, code: H2ErrorCode) {
426        let mut queue = self.send.queue.lock().expect("send queue mutex poisoned");
427        if matches!(queue.back(), Some(OutboundPart::Reset(_))) {
428            return;
429        }
430        queue.clear();
431        queue.push_back(OutboundPart::Reset(code));
432    }
433}
434
435/// Receive-side per-stream state.
436#[derive(Debug, Default)]
437pub(super) struct RecvState {
438    /// Inbound DATA body bytes awaiting handler read. A single persistent ring (append-at-tail,
439    /// `ignore_front`-at-head): the driver appends via `extend_live` when a DATA frame
440    /// arrives; the handler reads from the front and virtually drops consumed bytes. When
441    /// `ignore_front` catches up to the data end the `Buffer` truncates to zero, so the underlying
442    /// `Vec` capacity stays bounded by peak in-flight bytes rather than cumulative traffic — zero
443    /// amortized allocations per DATA frame.
444    pub(super) buf: Mutex<Buffer>,
445
446    /// Handler-task waker, fired by the driver after pushing DATA into `buf` or after the
447    /// lifecycle transitions to recv-closed. Single-waiter: only one task ever polls a given
448    /// `H2Transport`.
449    pub(super) waker: AtomicWaker,
450
451    /// Set by the handler's first [`H2Transport::poll_read`] to declare intent to consume the
452    /// request body. The driver observes the transition and emits a `WINDOW_UPDATE` for this
453    /// stream, topping its recv window up from `SETTINGS_INITIAL_WINDOW_SIZE` (advertised as `0`)
454    /// to the per-stream maximum. Once set, stays set.
455    pub(super) is_reading: AtomicBool,
456
457    /// Bytes the handler has consumed from `buf` since the driver last sampled this counter.
458    /// Incremented by [`H2Transport::poll_read`] using `fetch_add` after each drain; the driver
459    /// reads it via `swap(0)` per tick and emits stream-level + connection-level `WINDOW_UPDATE`
460    /// for the consumed total.
461    pub(super) bytes_consumed: AtomicU64,
462
463    /// Trailers, populated by the driver if a trailing HEADERS frame arrives for this stream.
464    /// Always written *before* the lifecycle transitions to recv-closed, so once the handler
465    /// observes `Ready(0)` on the recv side, any trailers for this request are guaranteed to
466    /// be in place. Boxed, like `response_headers`: every stream carries the slot, but few streams
467    /// fill it, and an inline `Headers` would grow every stream's state for them.
468    pub(super) trailers: Mutex<Option<Box<Headers>>>,
469
470    /// Client-role: response HEADERS field section, populated by the driver on the first non-1xx
471    /// HEADERS frame arrival for a client-initiated stream. Server role doesn't use this slot.
472    /// Single-shot: the conn task takes the `FieldSection` once; subsequent HEADERS arrivals are
473    /// interpreted as trailers. Interim 1xx HEADERS frames are discarded by the driver without
474    /// touching this slot or latching `first_response_headers_seen`. Boxed so that server
475    /// streams, which never fill it, don't carry a `FieldSection`'s worth of empty space.
476    pub(super) response_headers: Mutex<Option<Box<FieldSection<'static>>>>,
477
478    /// Client-role: latching flag for "first HEADERS arrived for this stream." Distinct from
479    /// `response_headers.is_some()` — the conn task drains that slot when it consumes headers, so
480    /// the driver can't use slot occupancy to distinguish "haven't seen HEADERS yet" from "headers
481    /// seen + already taken." Set inside `finalize_response_headers` before that slot is
482    /// populated; checked by `route_headers` on subsequent HEADERS to route them as trailers.
483    /// Never cleared.
484    pub(super) first_response_headers_seen: AtomicBool,
485
486    /// Client-role: waker the conn task registers via
487    /// [`H2Connection::response_headers`][super::H2Connection]; fired by the driver after stashing
488    /// the `FieldSection` *or* on stream removal (so a parked conn task observing the stream gone
489    /// surfaces `NotConnected` instead of hanging).
490    pub(super) response_headers_waker: AtomicWaker,
491}
492
493/// Send-side per-stream state: the conn-task → driver outbound parts queue, the streaming ring for
494/// bidirectional upgrades, the driver → conn-task completion channel, and the application-release
495/// signal.
496///
497/// **Normal response path**: the conn task `stage`s `[Headers, Body?, Close]` once via
498/// [`H2Connection::submit_send`][submit] and waits on `completion_waker` for `submit_resolved` to
499/// flip. The driver drains the queue into its private send cursor, frames the parts, and on the
500/// queue draining to empty stores `completion_result`, sets `submit_resolved = true`, and wakes the
501/// conn task.
502///
503/// **Extended-CONNECT upgrade path** ([RFC 8441]): the conn task `stage`s `[Headers, Body?]` with
504/// *no* `Close`, so the stream stays open after the prelude frames. `submit_resolved` flips when
505/// the queue first drains (i.e. once the prelude is on the wire) — matching h1/h3, not at
506/// `END_HEADERS` — so `submit_upgrade().await` returns and the runtime can dispatch
507/// [`Handler::upgrade`][trillium::Handler::upgrade]. The handler then writes through
508/// [`H2Transport`]'s `AsyncWrite`, which appends to `outbound`; the send pump drains that ring into
509/// DATA. `poll_close` enqueues [`OutboundPart::Close`], the pump drains the ring, frames the
510/// terminator, and tears the stream down.
511///
512/// [submit]: super::H2Connection::submit_send
513/// [RFC 8441]: https://www.rfc-editor.org/rfc/rfc8441
514#[derive(Debug, Default)]
515pub(super) struct SendState {
516    /// Outbound parts the conn task has handed off, drained by the driver into its private send
517    /// cursor when the stream is signaled. Cold: a handful of pushes per stream lifetime.
518    pub(super) queue: Mutex<VecDeque<OutboundPart>>,
519
520    /// Streaming bytes for a bidirectional upgrade: [`H2Transport`]'s `AsyncWrite::poll_write`
521    /// appends here, the send pump drains it into DATA frames before framing a terminator. A
522    /// single reused ring (`ignore_front` at head) — empty for normal responses, which frame an
523    /// owned [`OutboundPart::Body`] directly.
524    pub(super) outbound: Mutex<Buffer>,
525
526    /// Reverse-direction backpressure waker: registered by [`H2Transport::poll_write`] when
527    /// `outbound` hits the cap, fired by the send pump after it drains bytes so a parked writer
528    /// can resume. Without it a slow/unresponsive peer's closed window would let `outbound`
529    /// grow unbounded.
530    pub(super) outbound_write_waker: AtomicWaker,
531
532    /// Set to `true` by the driver once the conn task's [`SubmitSend`][super::SubmitSend] future
533    /// may resolve and its `completion_result` is readable. The future polls this atomic and
534    /// registers on `completion_waker`. Flips when the outbound queue first drains to empty —
535    /// `END_STREAM` for a normal response, the prelude-handoff for an upgrade.
536    pub(super) submit_resolved: AtomicBool,
537
538    /// The driver writes the final result here before flipping `submit_resolved`. The conn task
539    /// takes it once `submit_resolved` is observed true.
540    pub(super) completion_result: Mutex<Option<io::Result<()>>>,
541
542    /// The conn task's waker, registered by `SubmitSend::poll` and fired by the driver after
543    /// `submit_resolved` is set.
544    pub(super) completion_waker: AtomicWaker,
545
546    /// Set by [`H2Transport::Drop`] when the lifecycle is already `Closed` and the application is
547    /// releasing a stream that lingered in the map for post-EOF access (client role). The driver
548    /// picks it up and removes the entry from both maps. Not protocol state — a local
549    /// resource-ownership fact the lifecycle can't represent.
550    pub(super) transport_dropped: AtomicBool,
551
552    /// Set once the conn task stages anything to send, so a stream whose handler panics can tell
553    /// whether a response is already underway.
554    pub(super) started: AtomicBool,
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560    use crate::{Body, HttpContext};
561
562    /// A queued body discarded unsent — here by a reset clearing the queue — drops with its
563    /// panic contained.
564    #[test]
565    fn discarded_queued_body_drop_panic_is_contained() {
566        struct PanicsOnDrop;
567        impl AsyncRead for PanicsOnDrop {
568            fn poll_read(
569                self: Pin<&mut Self>,
570                _cx: &mut Context<'_>,
571                _buf: &mut [u8],
572            ) -> Poll<io::Result<usize>> {
573                Poll::Ready(Ok(0))
574            }
575        }
576        impl Drop for PanicsOnDrop {
577            fn drop(&mut self) {
578                assert!(std::thread::panicking(), "body source panicked in drop");
579            }
580        }
581
582        let state = StreamState::default();
583        *state.lifecycle_lock() = StreamLifecycle::Open;
584        let body = Body::new_streaming(PanicsOnDrop, None).into_h2();
585        state.stage([OutboundPart::Body(body), OutboundPart::Close]);
586        state.request_reset(H2ErrorCode::Cancel);
587    }
588
589    #[test]
590    fn request_close_enqueues_single_close() {
591        let state = StreamState::default();
592        *state.lifecycle_lock() = StreamLifecycle::Open;
593        state.request_close();
594        state.request_close();
595        let queue = state.send.queue.lock().unwrap();
596        assert_eq!(queue.len(), 1, "second request_close is a no-op");
597        assert!(matches!(queue.front(), Some(OutboundPart::Close)));
598    }
599
600    #[test]
601    fn request_close_noop_when_send_closed() {
602        let state = StreamState::default();
603        *state.lifecycle_lock() = StreamLifecycle::HalfClosedLocal;
604        state.request_close();
605        assert!(
606            state.send.queue.lock().unwrap().is_empty(),
607            "no terminator queued once the send half is closed"
608        );
609    }
610
611    #[test]
612    fn request_reset_clears_queue_and_is_first_wins() {
613        let state = StreamState::default();
614        *state.lifecycle_lock() = StreamLifecycle::Open;
615        state.stage([
616            OutboundPart::Body(Body::default().into_h2()),
617            OutboundPart::Close,
618        ]);
619        state.request_reset(H2ErrorCode::Cancel);
620        state.request_reset(H2ErrorCode::InternalError);
621        let queue = state.send.queue.lock().unwrap();
622        assert_eq!(queue.len(), 1, "queue cleared, single reset");
623        assert!(
624            matches!(
625                queue.front(),
626                Some(OutboundPart::Reset(H2ErrorCode::Cancel))
627            ),
628            "first reset code wins",
629        );
630    }
631
632    #[test]
633    fn poll_write_caps_at_response_buffer_max_len() {
634        use futures_lite::AsyncWrite;
635        use std::task::{Context, Poll, Waker};
636        let mut context = HttpContext::new();
637        context.config.response_buffer_max_len = 16;
638        let connection = H2Connection::new(Arc::new(context));
639        let state = Arc::new(StreamState::default());
640        *state.lifecycle_lock() = StreamLifecycle::Open;
641        let mut transport = H2Transport::new(connection, 1, state, Role::Server);
642        let waker = Waker::noop();
643        let mut cx = Context::from_waker(waker);
644        let buf = [0u8; 32];
645        match Pin::new(&mut transport).poll_write(&mut cx, &buf) {
646            Poll::Ready(Ok(n)) => assert_eq!(n, 16, "should accept exactly cap bytes"),
647            other => panic!("expected Ready(Ok(16)), got {other:?}"),
648        }
649    }
650}