tokio_quiche/http3/driver/
mod.rs

1// Copyright (C) 2025, Cloudflare, Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright notice,
9//       this list of conditions and the following disclaimer.
10//
11//     * Redistributions in binary form must reproduce the above copyright
12//       notice, this list of conditions and the following disclaimer in the
13//       documentation and/or other materials provided with the distribution.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27mod client;
28/// Wrapper for running HTTP/3 connections.
29pub mod connection;
30mod datagram;
31// `DriverHooks` must stay private to prevent users from creating their own
32// H3Drivers.
33mod hooks;
34mod server;
35mod streams;
36
37use std::collections::BTreeMap;
38use std::error::Error;
39use std::fmt;
40use std::marker::PhantomData;
41use std::sync::Arc;
42
43use datagram_socket::StreamClosureKind;
44use foundations::telemetry::log;
45use futures::FutureExt;
46use futures_util::stream::FuturesUnordered;
47use quiche::h3;
48use tokio::select;
49use tokio::sync::mpsc;
50use tokio::sync::mpsc::error::TryRecvError;
51use tokio::sync::mpsc::error::TrySendError;
52use tokio::sync::mpsc::UnboundedReceiver;
53use tokio::sync::mpsc::UnboundedSender;
54use tokio_stream::StreamExt;
55use tokio_util::sync::PollSender;
56
57use self::hooks::DriverHooks;
58use self::hooks::InboundHeaders;
59use self::streams::FlowCtx;
60use self::streams::HaveUpstreamCapacity;
61use self::streams::ReceivedDownstreamData;
62use self::streams::StreamCtx;
63use self::streams::StreamReady;
64use self::streams::WaitForDownstreamData;
65use self::streams::WaitForStream;
66use self::streams::WaitForUpstreamCapacity;
67use crate::buf_factory::BufFactory;
68use crate::buf_factory::PooledBuf;
69use crate::buf_factory::PooledDgram;
70use crate::http3::settings::Http3Settings;
71use crate::http3::H3AuditStats;
72use crate::metrics::Metrics;
73use crate::quic::HandshakeInfo;
74use crate::quic::QuicCommand;
75use crate::quic::QuicheConnection;
76use crate::ApplicationOverQuic;
77use crate::QuicResult;
78
79pub use self::client::ClientEventStream;
80pub use self::client::ClientH3Command;
81pub use self::client::ClientH3Controller;
82pub use self::client::ClientH3Driver;
83pub use self::client::ClientH3Event;
84pub use self::client::ClientRequestSender;
85pub use self::client::NewClientRequest;
86pub use self::server::ServerEventStream;
87pub use self::server::ServerH3Command;
88pub use self::server::ServerH3Controller;
89pub use self::server::ServerH3Driver;
90pub use self::server::ServerH3Event;
91
92// The default priority for HTTP/3 responses if the application didn't provide
93// one.
94const DEFAULT_PRIO: h3::Priority = h3::Priority::new(3, true);
95
96// For a stream use a channel with 16 entries, which works out to 16 * 64KB =
97// 1MB of max buffered data.
98#[cfg(not(any(test, debug_assertions)))]
99const STREAM_CAPACITY: usize = 16;
100#[cfg(any(test, debug_assertions))]
101const STREAM_CAPACITY: usize = 1; // Set to 1 to stress write_pending under test conditions
102
103// For *all* flows use a shared channel with 2048 entries, which works out
104// to 3MB of max buffered data at 1500 bytes per datagram.
105const FLOW_CAPACITY: usize = 2048;
106
107/// Used by a local task to send [`OutboundFrame`]s to a peer on the
108/// stream or flow associated with this channel.
109pub type OutboundFrameSender = PollSender<OutboundFrame>;
110
111/// Used internally to receive [`OutboundFrame`]s which should be sent to a peer
112/// on the stream or flow associated with this channel.
113type OutboundFrameStream = mpsc::Receiver<OutboundFrame>;
114
115/// Used internally to send [`InboundFrame`]s (data) from the peer to a local
116/// task on the stream or flow associated with this channel.
117type InboundFrameSender = PollSender<InboundFrame>;
118
119/// Used by a local task to receive [`InboundFrame`]s (data) on the stream or
120/// flow associated with this channel.
121pub type InboundFrameStream = mpsc::Receiver<InboundFrame>;
122
123/// The error type used internally in [H3Driver].
124///
125/// Note that [`ApplicationOverQuic`] errors are not exposed to users at this
126/// time. The type is public to document the failure modes in [H3Driver].
127#[derive(Debug, PartialEq, Eq)]
128#[non_exhaustive]
129pub enum H3ConnectionError {
130    /// The controller task was shut down and is no longer listening.
131    ControllerWentAway,
132    /// Other error at the connection, but not stream level.
133    H3(h3::Error),
134    /// Received a GOAWAY frame from the peer.
135    GoAway,
136    /// Received data for a stream that was closed or never opened.
137    NonexistentStream,
138    /// The server's post-accept timeout was hit.
139    /// The timeout can be configured in [`Http3Settings`].
140    PostAcceptTimeout,
141}
142
143impl From<h3::Error> for H3ConnectionError {
144    fn from(err: h3::Error) -> Self {
145        H3ConnectionError::H3(err)
146    }
147}
148
149impl From<quiche::Error> for H3ConnectionError {
150    fn from(err: quiche::Error) -> Self {
151        H3ConnectionError::H3(h3::Error::TransportError(err))
152    }
153}
154
155impl Error for H3ConnectionError {}
156
157impl fmt::Display for H3ConnectionError {
158    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
159        let s: &dyn fmt::Display = match self {
160            Self::ControllerWentAway => &"controller went away",
161            Self::H3(e) => e,
162            Self::GoAway => &"goaway",
163            Self::NonexistentStream => &"nonexistent stream",
164            Self::PostAcceptTimeout => &"post accept timeout hit",
165        };
166
167        write!(f, "H3ConnectionError: {s}")
168    }
169}
170
171type H3ConnectionResult<T> = Result<T, H3ConnectionError>;
172
173/// HTTP/3 headers that were received on a stream.
174///
175/// `recv` is used to read the message body, while `send` is used to transmit
176/// data back to the peer.
177#[derive(Debug)]
178pub struct IncomingH3Headers {
179    /// Stream ID of the frame.
180    pub stream_id: u64,
181    /// The actual [`h3::Header`]s which were received.
182    pub headers: Vec<h3::Header>,
183    /// An [`OutboundFrameSender`] for streaming body data to the peer. For
184    /// [ClientH3Driver], note that the request body can also be passed a
185    /// cloned sender via [`NewClientRequest`].
186    pub send: OutboundFrameSender,
187    /// An [`InboundFrameStream`] of body data received from the peer.
188    pub recv: InboundFrameStream,
189    /// Whether there is a body associated with the incoming headers.
190    pub read_fin: bool,
191    /// Handle to the [`H3AuditStats`] for the message's stream.
192    pub h3_audit_stats: Arc<H3AuditStats>,
193}
194
195/// [`H3Event`]s are produced by an [H3Driver] to describe HTTP/3 state updates.
196///
197/// Both [ServerH3Driver] and [ClientH3Driver] may extend this enum with
198/// endpoint-specific variants. The events must be consumed by users of the
199/// drivers, like a higher-level `Server` or `Client` controller.
200#[derive(Debug)]
201pub enum H3Event {
202    /// A SETTINGS frame was received.
203    IncomingSettings {
204        /// Raw HTTP/3 setting pairs, in the order received from the peer.
205        settings: Vec<(u64, u64)>,
206    },
207
208    /// A HEADERS frame was received on the given stream. This is either a
209    /// request or a response depending on the perspective of the [`H3Event`]
210    /// receiver.
211    IncomingHeaders(IncomingH3Headers),
212
213    /// A DATAGRAM flow was created and associated with the given `flow_id`.
214    /// This event is fired before a HEADERS event for CONNECT[-UDP] requests.
215    NewFlow {
216        /// Flow ID of the new flow.
217        flow_id: u64,
218        /// An [`OutboundFrameSender`] for transmitting datagrams to the peer.
219        send: OutboundFrameSender,
220        /// An [`InboundFrameStream`] for receiving datagrams from the peer.
221        recv: InboundFrameStream,
222    },
223    /// A RST_STREAM frame was seen on the given `stream_id`. The user of the
224    /// driver should clean up any state allocated for this stream.
225    ResetStream { stream_id: u64 },
226    /// The connection has irrecoverably errored and is shutting down.
227    ConnectionError(h3::Error),
228    /// The connection has been shutdown, optionally due to an
229    /// [`H3ConnectionError`].
230    ConnectionShutdown(Option<H3ConnectionError>),
231    /// Body data has been received over a stream.
232    BodyBytesReceived {
233        /// Stream ID of the body data.
234        stream_id: u64,
235        /// Number of bytes received.
236        num_bytes: u64,
237        /// Whether the stream is finished and won't yield any more data.
238        fin: bool,
239    },
240    /// The stream has been closed. This is used to signal stream closures that
241    /// don't result from RST_STREAM frames, unlike the
242    /// [`H3Event::ResetStream`] variant.
243    StreamClosed { stream_id: u64 },
244}
245
246impl H3Event {
247    /// Generates an event from an applicable [`H3ConnectionError`].
248    fn from_error(err: &H3ConnectionError) -> Option<Self> {
249        Some(match err {
250            H3ConnectionError::H3(e) => Self::ConnectionError(*e),
251            H3ConnectionError::PostAcceptTimeout => Self::ConnectionShutdown(
252                Some(H3ConnectionError::PostAcceptTimeout),
253            ),
254            _ => return None,
255        })
256    }
257}
258
259/// An [`OutboundFrame`] is a data frame that should be sent from a local task
260/// to a peer over a [`quiche::h3::Connection`].
261///
262/// This is used, for example, to send response body data to a peer, or proxied
263/// UDP datagrams.
264#[derive(Debug)]
265pub enum OutboundFrame {
266    /// Response headers to be sent to the peer, with optional priority.
267    Headers(Vec<h3::Header>, Option<quiche::h3::Priority>),
268    /// Response body/CONNECT downstream data plus FIN flag.
269    #[cfg(feature = "zero-copy")]
270    Body(crate::buf_factory::QuicheBuf, bool),
271    /// Response body/CONNECT downstream data plus FIN flag.
272    #[cfg(not(feature = "zero-copy"))]
273    Body(PooledBuf, bool),
274    /// CONNECT-UDP (DATAGRAM) downstream data plus flow ID.
275    Datagram(PooledDgram, u64),
276    /// An error encountered when serving the request. Stream should be closed.
277    PeerStreamError,
278    /// DATAGRAM flow explicitly closed.
279    FlowShutdown { flow_id: u64, stream_id: u64 },
280}
281
282impl OutboundFrame {
283    /// Creates a body frame with the provided buffer.
284    pub fn body(body: PooledBuf, fin: bool) -> Self {
285        #[cfg(feature = "zero-copy")]
286        let body = crate::buf_factory::QuicheBuf::new(body);
287
288        OutboundFrame::Body(body, fin)
289    }
290}
291
292/// An [`InboundFrame`] is a data frame that was received from the peer over a
293/// [`quiche::h3::Connection`]. This is used by peers to send body or datagrams
294/// to the local task.
295#[derive(Debug)]
296pub enum InboundFrame {
297    /// Request body/CONNECT upstream data plus FIN flag.
298    Body(PooledBuf, bool),
299    /// CONNECT-UDP (DATAGRAM) upstream data.
300    Datagram(PooledDgram),
301}
302
303/// A ready-made [`ApplicationOverQuic`] which can handle HTTP/3 and MASQUE.
304/// Depending on the `DriverHooks` in use, it powers either a client or a
305/// server.
306///
307/// Use the [ClientH3Driver] and [ServerH3Driver] aliases to access the
308/// respective driver types. The driver is passed into an I/O loop and
309/// communicates with the driver's user (e.g., an HTTP client or a server) via
310/// its associated [H3Controller]. The controller allows the application to both
311/// listen for [`H3Event`]s of note and send [`H3Command`]s into the I/O loop.
312pub struct H3Driver<H: DriverHooks> {
313    /// Configuration used to initialize `conn`. Created from [`Http3Settings`]
314    /// in the constructor.
315    h3_config: h3::Config,
316    /// The underlying HTTP/3 connection. Initialized in
317    /// `ApplicationOverQuic::on_conn_established`.
318    conn: Option<h3::Connection>,
319    /// State required by the client/server hooks.
320    hooks: H,
321    /// Sends [`H3Event`]s to the [H3Controller] paired with this driver.
322    h3_event_sender: mpsc::UnboundedSender<H::Event>,
323    /// Receives [`H3Command`]s from the [H3Controller] paired with this driver.
324    cmd_recv: mpsc::UnboundedReceiver<H::Command>,
325
326    /// A map of stream IDs to their [StreamCtx]. This is mainly used to
327    /// retrieve the internal Tokio channels associated with the stream.
328    stream_map: BTreeMap<u64, StreamCtx>,
329    /// A map of flow IDs to their [FlowCtx]. This is mainly used to retrieve
330    /// the internal Tokio channels associated with the flow.
331    flow_map: BTreeMap<u64, FlowCtx>,
332    /// Set of [`WaitForStream`] futures. A stream is added to this set if
333    /// we need to send to it and its channel is at capacity, or if we need
334    /// data from its channel and the channel is empty.
335    waiting_streams: FuturesUnordered<WaitForStream>,
336
337    /// Receives [`OutboundFrame`]s from all datagram flows on the connection.
338    dgram_recv: OutboundFrameStream,
339    /// Keeps the datagram channel open such that datagram flows can be created.
340    dgram_send: OutboundFrameSender,
341
342    /// The buffer used to interact with the underlying IoWorker.
343    pooled_buf: PooledBuf,
344    /// The maximum HTTP/3 stream ID seen on this connection.
345    max_stream_seen: u64,
346
347    /// Tracks whether we have forwarded the HTTP/3 SETTINGS frame
348    /// to the [H3Controller] once.
349    settings_received_and_forwarded: bool,
350}
351
352impl<H: DriverHooks> H3Driver<H> {
353    /// Builds a new [H3Driver] and an associated [H3Controller].
354    ///
355    /// The driver should then be passed to
356    /// [`InitialQuicConnection`](crate::InitialQuicConnection)'s `start`
357    /// method.
358    pub fn new(http3_settings: Http3Settings) -> (Self, H3Controller<H>) {
359        let (dgram_send, dgram_recv) = mpsc::channel(FLOW_CAPACITY);
360        let (cmd_sender, cmd_recv) = mpsc::unbounded_channel();
361        let (h3_event_sender, h3_event_recv) = mpsc::unbounded_channel();
362
363        (
364            H3Driver {
365                h3_config: (&http3_settings).into(),
366                conn: None,
367                hooks: H::new(&http3_settings),
368                h3_event_sender,
369                cmd_recv,
370
371                stream_map: BTreeMap::new(),
372                flow_map: BTreeMap::new(),
373
374                dgram_recv,
375                dgram_send: PollSender::new(dgram_send),
376                pooled_buf: BufFactory::get_max_buf(),
377                max_stream_seen: 0,
378
379                waiting_streams: FuturesUnordered::new(),
380
381                settings_received_and_forwarded: false,
382            },
383            H3Controller {
384                cmd_sender,
385                h3_event_recv: Some(h3_event_recv),
386            },
387        )
388    }
389
390    /// Retrieve the [FlowCtx] associated with the given `flow_id`. If no
391    /// context is found, a new one will be created.
392    fn get_or_insert_flow(
393        &mut self, flow_id: u64,
394    ) -> H3ConnectionResult<&mut FlowCtx> {
395        use std::collections::btree_map::Entry;
396        Ok(match self.flow_map.entry(flow_id) {
397            Entry::Vacant(e) => {
398                // This is a datagram for a new flow we haven't seen before
399                let (flow, recv) = FlowCtx::new(FLOW_CAPACITY);
400                let flow_req = H3Event::NewFlow {
401                    flow_id,
402                    recv,
403                    send: self.dgram_send.clone(),
404                };
405                self.h3_event_sender
406                    .send(flow_req.into())
407                    .map_err(|_| H3ConnectionError::ControllerWentAway)?;
408                e.insert(flow)
409            },
410            Entry::Occupied(e) => e.into_mut(),
411        })
412    }
413
414    /// Adds a [StreamCtx] to the stream map with the given `stream_id`.
415    fn insert_stream(&mut self, stream_id: u64, ctx: StreamCtx) {
416        self.stream_map.insert(stream_id, ctx);
417        self.max_stream_seen = self.max_stream_seen.max(stream_id);
418    }
419
420    /// Fetches body chunks from the [`quiche::h3::Connection`] and forwards
421    /// them to the stream's associated [`InboundFrameStream`].
422    fn process_h3_data(
423        &mut self, qconn: &mut QuicheConnection, stream_id: u64,
424    ) -> H3ConnectionResult<()> {
425        // Split self borrow between conn and stream_map
426        let conn = self.conn.as_mut().ok_or(Self::connection_not_present())?;
427        let ctx = self
428            .stream_map
429            .get_mut(&stream_id)
430            .ok_or(H3ConnectionError::NonexistentStream)?;
431
432        enum StreamStatus {
433            Done { close: bool },
434            Blocked,
435        }
436
437        let status = loop {
438            let Some(sender) = ctx.send.as_ref().and_then(PollSender::get_ref)
439            else {
440                // already waiting for capacity
441                break StreamStatus::Done { close: false };
442            };
443
444            let permit = match sender.try_reserve() {
445                Ok(permit) => permit,
446                Err(TrySendError::Closed(())) => {
447                    break StreamStatus::Done {
448                        close: ctx.fin_sent && ctx.fin_recv,
449                    };
450                },
451                Err(TrySendError::Full(())) => {
452                    if ctx.fin_recv || qconn.stream_readable(stream_id) {
453                        break StreamStatus::Blocked;
454                    }
455                    break StreamStatus::Done { close: false };
456                },
457            };
458
459            if ctx.fin_recv {
460                // Signal end-of-body to upstream
461                permit
462                    .send(InboundFrame::Body(BufFactory::get_empty_buf(), true));
463                break StreamStatus::Done {
464                    close: ctx.fin_sent,
465                };
466            }
467
468            match conn.recv_body(qconn, stream_id, &mut self.pooled_buf) {
469                Ok(n) => {
470                    let mut body = std::mem::replace(
471                        &mut self.pooled_buf,
472                        BufFactory::get_max_buf(),
473                    );
474                    body.truncate(n);
475
476                    ctx.audit_stats.add_downstream_bytes_recvd(n as u64);
477                    let event = H3Event::BodyBytesReceived {
478                        stream_id,
479                        num_bytes: n as u64,
480                        fin: false,
481                    };
482                    let _ = self.h3_event_sender.send(event.into());
483
484                    permit.send(InboundFrame::Body(body, false));
485                },
486                Err(h3::Error::Done) =>
487                    break StreamStatus::Done { close: false },
488                Err(_) => break StreamStatus::Done { close: true },
489            }
490        };
491
492        match status {
493            StreamStatus::Done { close } => {
494                if close {
495                    return self.finish_stream(qconn, stream_id, None, None);
496                }
497
498                // The QUIC stream is finished, manually invoke `process_h3_fin`
499                // in case `h3::poll()` is never called again.
500                //
501                // Note that this case will not conflict with StreamStatus::Done
502                // being returned due to the body channel being
503                // blocked. qconn.stream_finished() will guarantee
504                // that we've fully parsed the body as it only returns true
505                // if we've seen a Fin for the read half of the stream.
506                if !ctx.fin_recv && qconn.stream_finished(stream_id) {
507                    return self.process_h3_fin(qconn, stream_id);
508                }
509            },
510            StreamStatus::Blocked => {
511                self.waiting_streams.push(ctx.wait_for_send(stream_id));
512            },
513        }
514
515        Ok(())
516    }
517
518    /// Processes an end-of-stream event from the [`quiche::h3::Connection`].
519    fn process_h3_fin(
520        &mut self, qconn: &mut QuicheConnection, stream_id: u64,
521    ) -> H3ConnectionResult<()> {
522        let ctx = self.stream_map.get_mut(&stream_id).filter(|c| !c.fin_recv);
523        let Some(ctx) = ctx else {
524            // Stream is already finished, nothing to do
525            return Ok(());
526        };
527
528        ctx.fin_recv = true;
529        ctx.audit_stats
530            .set_recvd_stream_fin(StreamClosureKind::Explicit);
531
532        // It's important to send this H3Event before process_h3_data so that
533        // a server can (potentially) generate the control response before the
534        // corresponding receiver drops.
535        let event = H3Event::BodyBytesReceived {
536            stream_id,
537            num_bytes: 0,
538            fin: true,
539        };
540        let _ = self.h3_event_sender.send(event.into());
541
542        // Communicate fin to upstream. Since `ctx.fin_recv` is true now,
543        // there can't be a recursive loop.
544        self.process_h3_data(qconn, stream_id)
545    }
546
547    /// Processes a single [`quiche::h3::Event`] received from the underlying
548    /// [`quiche::h3::Connection`]. Some events are dispatched to helper
549    /// methods.
550    fn process_read_event(
551        &mut self, qconn: &mut QuicheConnection, stream_id: u64, event: h3::Event,
552    ) -> H3ConnectionResult<()> {
553        self.forward_settings()?;
554
555        match event {
556            // Requests/responses are exclusively handled by hooks.
557            h3::Event::Headers { list, more_frames } =>
558                H::headers_received(self, qconn, InboundHeaders {
559                    stream_id,
560                    headers: list,
561                    has_body: more_frames,
562                }),
563
564            h3::Event::Data => self.process_h3_data(qconn, stream_id),
565            h3::Event::Finished => self.process_h3_fin(qconn, stream_id),
566
567            h3::Event::Reset(code) => {
568                if let Some(ctx) = self.stream_map.get(&stream_id) {
569                    ctx.audit_stats.set_recvd_reset_stream_error_code(code as _);
570                }
571
572                self.h3_event_sender
573                    .send(H3Event::ResetStream { stream_id }.into())
574                    .map_err(|_| H3ConnectionError::ControllerWentAway)?;
575
576                self.finish_stream(qconn, stream_id, None, None)
577            },
578
579            h3::Event::PriorityUpdate => Ok(()),
580            h3::Event::GoAway => Err(H3ConnectionError::GoAway),
581        }
582    }
583
584    /// The SETTINGS frame can be received at any point, so we
585    /// need to check `peer_settings_raw` to decide if we've received it.
586    ///
587    /// Settings should only be sent once, so we generate a single event
588    /// when `peer_settings_raw` transitions from None to Some.
589    fn forward_settings(&mut self) -> H3ConnectionResult<()> {
590        if self.settings_received_and_forwarded {
591            return Ok(());
592        }
593
594        // capture the peer settings and forward it
595        if let Some(settings) = self.conn_mut()?.peer_settings_raw() {
596            let incoming_settings = H3Event::IncomingSettings {
597                settings: settings.to_vec(),
598            };
599
600            self.h3_event_sender
601                .send(incoming_settings.into())
602                .map_err(|_| H3ConnectionError::ControllerWentAway)?;
603
604            self.settings_received_and_forwarded = true;
605        }
606        Ok(())
607    }
608
609    /// Send an individual frame to the underlying [`quiche::h3::Connection`] to
610    /// be flushed at a later time.
611    ///
612    /// `Self::process_writes` will iterate over all writable streams and call
613    /// this method in a loop for each stream to send all writable packets.
614    fn process_write_frame(
615        conn: &mut h3::Connection, qconn: &mut QuicheConnection,
616        ctx: &mut StreamCtx,
617    ) -> h3::Result<()> {
618        let Some(frame) = &mut ctx.queued_frame else {
619            return Ok(());
620        };
621
622        let audit_stats = &ctx.audit_stats;
623        let stream_id = audit_stats.stream_id();
624
625        match frame {
626            OutboundFrame::Headers(headers, priority) => {
627                let prio = priority.as_ref().unwrap_or(&DEFAULT_PRIO);
628
629                if ctx.initial_headers_sent {
630                    // Initial headers were already sent, send additional
631                    // headers now.
632                    conn.send_additional_headers_with_priority(
633                        qconn, stream_id, headers, prio, false, false,
634                    )
635                } else {
636                    // Send initial headers.
637                    conn.send_response_with_priority(
638                        qconn, stream_id, headers, prio, false,
639                    )
640                    .inspect(|_| ctx.initial_headers_sent = true)
641                }
642            },
643
644            OutboundFrame::Body(body, fin) => {
645                let len = body.as_ref().len();
646                if len == 0 && !*fin {
647                    // quiche doesn't allow sending an empty body when the fin
648                    // flag is not set
649                    return Ok(());
650                }
651                if *fin {
652                    // If this is the last body frame, close the receiver in the
653                    // stream map to signal that we shouldn't
654                    // receive any more frames.
655                    ctx.recv.as_mut().expect("channel").close();
656                }
657                #[cfg(feature = "zero-copy")]
658                let n = conn.send_body_zc(qconn, stream_id, body, *fin)?;
659
660                #[cfg(not(feature = "zero-copy"))]
661                let n = conn.send_body(qconn, stream_id, body, *fin)?;
662
663                audit_stats.add_downstream_bytes_sent(n as _);
664                if n != len {
665                    // Couldn't write the entire body, keep what remains for
666                    // future retry.
667                    #[cfg(not(feature = "zero-copy"))]
668                    body.pop_front(n);
669
670                    Err(h3::Error::StreamBlocked)
671                } else {
672                    if *fin {
673                        ctx.fin_sent = true;
674                        audit_stats
675                            .set_sent_stream_fin(StreamClosureKind::Explicit);
676                        if ctx.fin_recv {
677                            // Return a TransportError to trigger stream cleanup
678                            // instead of h3::Error::Done
679                            return Err(h3::Error::TransportError(
680                                quiche::Error::Done,
681                            ));
682                        }
683                    }
684                    Ok(())
685                }
686            },
687
688            OutboundFrame::PeerStreamError => Err(h3::Error::MessageError),
689
690            OutboundFrame::FlowShutdown { .. } => {
691                unreachable!("Only flows send shutdowns")
692            },
693
694            OutboundFrame::Datagram(..) => {
695                unreachable!("Only flows send datagrams")
696            },
697        }
698    }
699
700    /// Resumes reads or writes to the connection when a stream channel becomes
701    /// unblocked.
702    ///
703    /// If we were waiting for more data from a channel, we resume writing to
704    /// the connection. Otherwise, we were blocked on channel capacity and
705    /// continue reading from the connection. `Upstream` in this context is
706    /// the consumer of the stream.
707    fn upstream_ready(
708        &mut self, qconn: &mut QuicheConnection, ready: StreamReady,
709    ) -> H3ConnectionResult<()> {
710        match ready {
711            StreamReady::Downstream(r) => self.upstream_read_ready(qconn, r),
712            StreamReady::Upstream(r) => self.upstream_write_ready(qconn, r),
713        }
714    }
715
716    fn upstream_read_ready(
717        &mut self, qconn: &mut QuicheConnection,
718        read_ready: ReceivedDownstreamData,
719    ) -> H3ConnectionResult<()> {
720        let ReceivedDownstreamData {
721            stream_id,
722            chan,
723            data,
724        } = read_ready;
725
726        match self.stream_map.get_mut(&stream_id) {
727            None => Ok(()),
728            Some(stream) => {
729                stream.recv = Some(chan);
730                stream.queued_frame = data;
731                self.process_writable_stream(qconn, stream_id)
732            },
733        }
734    }
735
736    fn upstream_write_ready(
737        &mut self, qconn: &mut QuicheConnection,
738        write_ready: HaveUpstreamCapacity,
739    ) -> H3ConnectionResult<()> {
740        let HaveUpstreamCapacity {
741            stream_id,
742            mut chan,
743        } = write_ready;
744
745        match self.stream_map.get_mut(&stream_id) {
746            None => Ok(()),
747            Some(stream) => {
748                chan.abort_send(); // Have to do it to release the associated permit
749                stream.send = Some(chan);
750                self.process_h3_data(qconn, stream_id)
751            },
752        }
753    }
754
755    /// Processes all queued outbound datagrams from the `dgram_recv` channel.
756    fn dgram_ready(
757        &mut self, qconn: &mut QuicheConnection, frame: OutboundFrame,
758    ) -> H3ConnectionResult<()> {
759        let mut frame = Ok(frame);
760
761        loop {
762            match frame {
763                Ok(OutboundFrame::Datagram(dgram, flow_id)) => {
764                    // Drop datagrams if there is no capacity
765                    let _ = datagram::send_h3_dgram(qconn, flow_id, dgram);
766                },
767                Ok(OutboundFrame::FlowShutdown { flow_id, stream_id }) => {
768                    self.finish_stream(
769                        qconn,
770                        stream_id,
771                        Some(quiche::h3::WireErrorCode::NoError as u64),
772                        Some(quiche::h3::WireErrorCode::NoError as u64),
773                    )?;
774                    self.flow_map.remove(&flow_id);
775                    break;
776                },
777                Ok(_) => unreachable!("Flows can't send frame of other types"),
778                Err(TryRecvError::Empty) => break,
779                Err(TryRecvError::Disconnected) =>
780                    return Err(H3ConnectionError::ControllerWentAway),
781            }
782
783            frame = self.dgram_recv.try_recv();
784        }
785
786        Ok(())
787    }
788
789    /// Return a mutable reference to the driver's HTTP/3 connection.
790    ///
791    /// If the connection doesn't exist yet, this function returns
792    /// a `Self::connection_not_present()` error.
793    fn conn_mut(&mut self) -> H3ConnectionResult<&mut h3::Connection> {
794        self.conn.as_mut().ok_or(Self::connection_not_present())
795    }
796
797    /// Alias for [`quiche::Error::TlsFail`], which is used in the case where
798    /// this driver doesn't have an established HTTP/3 connection attached
799    /// to it yet.
800    const fn connection_not_present() -> H3ConnectionError {
801        H3ConnectionError::H3(h3::Error::TransportError(quiche::Error::TlsFail))
802    }
803
804    /// Removes a stream from the stream map if it exists. Also optionally sends
805    /// `RESET` or `STOP_SENDING` frames if `write` or `read` is set to an
806    /// error code, respectively.
807    fn finish_stream(
808        &mut self, qconn: &mut QuicheConnection, stream_id: u64,
809        read: Option<u64>, write: Option<u64>,
810    ) -> H3ConnectionResult<()> {
811        let Some(stream_ctx) = self.stream_map.remove(&stream_id) else {
812            return Ok(());
813        };
814
815        let audit_stats = &stream_ctx.audit_stats;
816
817        if let Some(err) = read {
818            audit_stats.set_sent_stop_sending_error_code(err as _);
819            let _ = qconn.stream_shutdown(stream_id, quiche::Shutdown::Read, err);
820        }
821
822        if let Some(err) = write {
823            audit_stats.set_sent_reset_stream_error_code(err as _);
824            let _ =
825                qconn.stream_shutdown(stream_id, quiche::Shutdown::Write, err);
826        }
827
828        // Find if the stream also has any pending futures associated with it
829        for pending in self.waiting_streams.iter_mut() {
830            match pending {
831                WaitForStream::Downstream(WaitForDownstreamData {
832                    stream_id: id,
833                    chan: Some(chan),
834                }) if stream_id == *id => {
835                    chan.close();
836                },
837                WaitForStream::Upstream(WaitForUpstreamCapacity {
838                    stream_id: id,
839                    chan: Some(chan),
840                }) if stream_id == *id => {
841                    chan.close();
842                },
843                _ => {},
844            }
845        }
846
847        // Close any DATAGRAM-proxying channels when we close the stream, if they
848        // exist
849        if let Some(mapped_flow_id) = stream_ctx.associated_dgram_flow_id {
850            self.flow_map.remove(&mapped_flow_id);
851        }
852
853        if qconn.is_server() {
854            // Signal the server to remove the stream from its map
855            let _ = self
856                .h3_event_sender
857                .send(H3Event::StreamClosed { stream_id }.into());
858        }
859
860        Ok(())
861    }
862
863    /// Handles a regular [`H3Command`]. May be called internally by
864    /// [DriverHooks] for non-endpoint-specific [`H3Command`]s.
865    fn handle_core_command(
866        &mut self, qconn: &mut QuicheConnection, cmd: H3Command,
867    ) -> H3ConnectionResult<()> {
868        match cmd {
869            H3Command::QuicCmd(cmd) => cmd.execute(qconn),
870            H3Command::GoAway => {
871                let max_id = self.max_stream_seen;
872                self.conn_mut()
873                    .expect("connection should be established")
874                    .send_goaway(qconn, max_id)?;
875            },
876        }
877        Ok(())
878    }
879}
880
881impl<H: DriverHooks> H3Driver<H> {
882    /// Reads all buffered datagrams out of `qconn` and distributes them to
883    /// their flow channels.
884    fn process_available_dgrams(
885        &mut self, qconn: &mut QuicheConnection,
886    ) -> H3ConnectionResult<()> {
887        loop {
888            match datagram::receive_h3_dgram(qconn) {
889                Ok((flow_id, dgram)) => {
890                    self.get_or_insert_flow(flow_id)?.send_best_effort(dgram);
891                },
892                Err(quiche::Error::Done) => return Ok(()),
893                Err(err) => return Err(H3ConnectionError::from(err)),
894            }
895        }
896    }
897
898    /// Flushes any queued-up frames for `stream_id` into `qconn` until either
899    /// there is no more capacity in `qconn` or no more frames to send.
900    fn process_writable_stream(
901        &mut self, qconn: &mut QuicheConnection, stream_id: u64,
902    ) -> H3ConnectionResult<()> {
903        // Split self borrow between conn and stream_map
904        let conn = self.conn.as_mut().ok_or(Self::connection_not_present())?;
905        let Some(ctx) = self.stream_map.get_mut(&stream_id) else {
906            return Ok(()); // Unknown stream_id
907        };
908
909        loop {
910            // Process each writable frame, queue the next frame for processing
911            // and shut down any errored streams.
912            match Self::process_write_frame(conn, qconn, ctx) {
913                Ok(()) => ctx.queued_frame = None,
914                Err(h3::Error::StreamBlocked | h3::Error::Done) => break,
915                Err(h3::Error::MessageError) => {
916                    return self.finish_stream(
917                        qconn,
918                        stream_id,
919                        Some(quiche::h3::WireErrorCode::MessageError as u64),
920                        Some(quiche::h3::WireErrorCode::MessageError as u64),
921                    );
922                },
923                Err(h3::Error::TransportError(quiche::Error::StreamStopped(
924                    e,
925                ))) => {
926                    ctx.audit_stats.set_recvd_stop_sending_error_code(e as i64);
927                    return self.finish_stream(qconn, stream_id, Some(e), None);
928                },
929                Err(h3::Error::TransportError(
930                    quiche::Error::InvalidStreamState(stream),
931                )) => {
932                    return self.finish_stream(qconn, stream, None, None);
933                },
934                Err(_) => {
935                    return self.finish_stream(qconn, stream_id, None, None);
936                },
937            }
938
939            let Some(recv) = ctx.recv.as_mut() else {
940                return Ok(()); // This stream is already waiting for data
941            };
942
943            // Attempt to queue the next frame for processing. The corresponding
944            // sender is created at the same time as the `StreamCtx`
945            // and ultimately ends up in an `H3Body`. The body then
946            // determines which frames to send to the peer via
947            // this processing loop.
948            match recv.try_recv() {
949                Ok(frame) => ctx.queued_frame = Some(frame),
950                Err(TryRecvError::Disconnected) => break,
951                Err(TryRecvError::Empty) => {
952                    self.waiting_streams.push(ctx.wait_for_recv(stream_id));
953                    break;
954                },
955            }
956        }
957
958        Ok(())
959    }
960
961    /// Tests `qconn` for either a local or peer error and increments
962    /// the associated HTTP/3 or QUIC error counter.
963    fn record_quiche_error(qconn: &mut QuicheConnection, metrics: &impl Metrics) {
964        // split metrics between local/peer and QUIC/HTTP/3 level errors
965        if let Some(err) = qconn.local_error() {
966            if err.is_app {
967                metrics.local_h3_conn_close_error_count(err.error_code.into())
968            } else {
969                metrics.local_quic_conn_close_error_count(err.error_code.into())
970            }
971            .inc();
972        } else if let Some(err) = qconn.peer_error() {
973            if err.is_app {
974                metrics.peer_h3_conn_close_error_count(err.error_code.into())
975            } else {
976                metrics.peer_quic_conn_close_error_count(err.error_code.into())
977            }
978            .inc();
979        }
980    }
981}
982
983impl<H: DriverHooks> ApplicationOverQuic for H3Driver<H> {
984    fn on_conn_established(
985        &mut self, quiche_conn: &mut QuicheConnection,
986        handshake_info: &HandshakeInfo,
987    ) -> QuicResult<()> {
988        let conn = h3::Connection::with_transport(quiche_conn, &self.h3_config)?;
989        self.conn = Some(conn);
990
991        H::conn_established(self, quiche_conn, handshake_info)?;
992        Ok(())
993    }
994
995    #[inline]
996    fn should_act(&self) -> bool {
997        self.conn.is_some()
998    }
999
1000    #[inline]
1001    fn buffer(&mut self) -> &mut [u8] {
1002        &mut self.pooled_buf
1003    }
1004
1005    /// Poll the underlying [`quiche::h3::Connection`] for
1006    /// [`quiche::h3::Event`]s and DATAGRAMs, delegating processing to
1007    /// `Self::process_read_event`.
1008    ///
1009    /// If a DATAGRAM is found, it is sent to the receiver on its channel.
1010    fn process_reads(&mut self, qconn: &mut QuicheConnection) -> QuicResult<()> {
1011        loop {
1012            match self.conn_mut()?.poll(qconn) {
1013                Ok((stream_id, event)) =>
1014                    self.process_read_event(qconn, stream_id, event)?,
1015                Err(h3::Error::Done) => break,
1016                Err(err) => {
1017                    // Don't bubble error up, instead keep the worker loop going
1018                    // until quiche reports the connection is
1019                    // closed.
1020                    log::debug!("connection closed due to h3 protocol error"; "error"=>?err);
1021                    return Ok(());
1022                },
1023            };
1024        }
1025
1026        self.process_available_dgrams(qconn)?;
1027        Ok(())
1028    }
1029
1030    /// Write as much data as possible into the [`quiche::h3::Connection`] from
1031    /// all sources. This will attempt to write any queued frames into their
1032    /// respective streams, if writable.
1033    fn process_writes(&mut self, qconn: &mut QuicheConnection) -> QuicResult<()> {
1034        while let Some(stream_id) = qconn.stream_writable_next() {
1035            self.process_writable_stream(qconn, stream_id)?;
1036        }
1037
1038        // Also optimistically check for any ready streams
1039        while let Some(Some(ready)) = self.waiting_streams.next().now_or_never() {
1040            self.upstream_ready(qconn, ready)?;
1041        }
1042
1043        Ok(())
1044    }
1045
1046    /// Reports connection-level error metrics and forwards
1047    /// IOWorker errors to the associated [H3Controller].
1048    fn on_conn_close<M: Metrics>(
1049        &mut self, quiche_conn: &mut QuicheConnection, metrics: &M,
1050        work_loop_result: &QuicResult<()>,
1051    ) {
1052        let max_stream_seen = self.max_stream_seen;
1053        metrics
1054            .maximum_writable_streams()
1055            .observe(max_stream_seen as f64);
1056
1057        let Err(work_loop_error) = work_loop_result else {
1058            return;
1059        };
1060
1061        Self::record_quiche_error(quiche_conn, metrics);
1062
1063        let Some(h3_err) = work_loop_error.downcast_ref::<H3ConnectionError>()
1064        else {
1065            log::error!("Found non-H3ConnectionError"; "error" => %work_loop_error);
1066            return;
1067        };
1068
1069        if matches!(h3_err, H3ConnectionError::ControllerWentAway) {
1070            // Inform client that we won't (can't) respond anymore
1071            let _ =
1072                quiche_conn.close(true, h3::WireErrorCode::NoError as u64, &[]);
1073            return;
1074        }
1075
1076        if let Some(ev) = H3Event::from_error(h3_err) {
1077            let _ = self.h3_event_sender.send(ev.into());
1078            #[expect(clippy::needless_return)]
1079            return; // avoid accidental fallthrough in the future
1080        }
1081    }
1082
1083    /// Wait for incoming data from the [H3Controller]. The next iteration of
1084    /// the I/O loop commences when one of the `select!`ed futures triggers.
1085    #[inline]
1086    async fn wait_for_data(
1087        &mut self, qconn: &mut QuicheConnection,
1088    ) -> QuicResult<()> {
1089        select! {
1090            biased;
1091            Some(ready) = self.waiting_streams.next() => self.upstream_ready(qconn, ready),
1092            Some(dgram) = self.dgram_recv.recv() => self.dgram_ready(qconn, dgram),
1093            Some(cmd) = self.cmd_recv.recv() => H::conn_command(self, qconn, cmd),
1094            r = self.hooks.wait_for_action(qconn), if H::has_wait_action(self) => r,
1095        }?;
1096
1097        // Make sure controller is not starved, but also not prioritized in the
1098        // biased select. So poll it last, however also perform a try_recv
1099        // each iteration.
1100        if let Ok(cmd) = self.cmd_recv.try_recv() {
1101            H::conn_command(self, qconn, cmd)?;
1102        }
1103
1104        Ok(())
1105    }
1106}
1107
1108impl<H: DriverHooks> Drop for H3Driver<H> {
1109    fn drop(&mut self) {
1110        for stream in self.stream_map.values() {
1111            stream
1112                .audit_stats
1113                .set_recvd_stream_fin(StreamClosureKind::Implicit);
1114        }
1115    }
1116}
1117
1118/// [`H3Command`]s are sent by the [H3Controller] to alter the [H3Driver]'s
1119/// state.
1120///
1121/// Both [ServerH3Driver] and [ClientH3Driver] may extend this enum with
1122/// endpoint-specific variants.
1123#[derive(Debug)]
1124pub enum H3Command {
1125    /// A connection-level command that executes directly on the
1126    /// [`quiche::Connection`].
1127    QuicCmd(QuicCommand),
1128    /// Send a GOAWAY frame to the peer to initiate a graceful connection
1129    /// shutdown.
1130    GoAway,
1131}
1132
1133/// Sends [`H3Command`]s to an [H3Driver]. The sender is typed and internally
1134/// wraps instances of `T` in the appropriate `H3Command` variant.
1135pub struct RequestSender<C, T> {
1136    sender: UnboundedSender<C>,
1137    // Required to work around dangling type parameter
1138    _r: PhantomData<fn() -> T>,
1139}
1140
1141impl<C, T: Into<C>> RequestSender<C, T> {
1142    /// Send a request to the [H3Driver]. This can only fail if the driver is
1143    /// gone.
1144    #[inline(always)]
1145    pub fn send(&self, v: T) -> Result<(), mpsc::error::SendError<C>> {
1146        self.sender.send(v.into())
1147    }
1148}
1149
1150impl<C, T> Clone for RequestSender<C, T> {
1151    fn clone(&self) -> Self {
1152        Self {
1153            sender: self.sender.clone(),
1154            _r: Default::default(),
1155        }
1156    }
1157}
1158
1159/// Interface to communicate with a paired [H3Driver].
1160///
1161/// An [H3Controller] receives [`H3Event`]s from its driver, which must be
1162/// consumed by the application built on top of the driver to react to incoming
1163/// events. The controller also allows the application to send ad-hoc
1164/// [`H3Command`]s to the driver, which will be processed when the driver waits
1165/// for incoming data.
1166pub struct H3Controller<H: DriverHooks> {
1167    /// Sends [`H3Command`]s to the [H3Driver], like [`QuicCommand`]s or
1168    /// outbound HTTP requests.
1169    cmd_sender: UnboundedSender<H::Command>,
1170    /// Receives [`H3Event`]s from the [H3Driver]. Can be extracted and
1171    /// used independently of the [H3Controller].
1172    h3_event_recv: Option<UnboundedReceiver<H::Event>>,
1173}
1174
1175impl<H: DriverHooks> H3Controller<H> {
1176    /// Gets a mut reference to the [`H3Event`] receiver for the paired
1177    /// [H3Driver].
1178    pub fn event_receiver_mut(&mut self) -> &mut UnboundedReceiver<H::Event> {
1179        self.h3_event_recv
1180            .as_mut()
1181            .expect("No event receiver on H3Controller")
1182    }
1183
1184    /// Takes the [`H3Event`] receiver for the paired [H3Driver].
1185    pub fn take_event_receiver(&mut self) -> UnboundedReceiver<H::Event> {
1186        self.h3_event_recv
1187            .take()
1188            .expect("No event receiver on H3Controller")
1189    }
1190
1191    /// Creates a [`QuicCommand`] sender for the paired [H3Driver].
1192    pub fn cmd_sender(&self) -> RequestSender<H::Command, QuicCommand> {
1193        RequestSender {
1194            sender: self.cmd_sender.clone(),
1195            _r: Default::default(),
1196        }
1197    }
1198
1199    /// Sends a GOAWAY frame to initiate a graceful connection shutdown.
1200    pub fn send_goaway(&self) {
1201        let _ = self.cmd_sender.send(H3Command::GoAway.into());
1202    }
1203}