Skip to main content

h3i/client/
async_client.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
27//! Responsible for creating a [tokio_quiche::quic::QuicheConnection] and
28//! yielding I/O to tokio-quiche.
29
30use log;
31use quiche::PathStats;
32use quiche::Stats;
33use std::future::Future;
34use std::pin::Pin;
35use std::task::Context;
36use std::task::Poll;
37use std::time::Duration;
38use tokio::select;
39use tokio::sync::mpsc;
40use tokio::sync::oneshot;
41use tokio::time::sleep;
42use tokio::time::sleep_until;
43use tokio::time::Instant;
44use tokio_quiche::metrics::Metrics;
45use tokio_quiche::quic::HandshakeInfo;
46use tokio_quiche::quic::QuicheConnection;
47use tokio_quiche::settings::Hooks;
48use tokio_quiche::settings::QuicSettings;
49use tokio_quiche::socket::Socket;
50use tokio_quiche::ApplicationOverQuic;
51use tokio_quiche::ConnectionParams;
52use tokio_quiche::QuicResult;
53
54use crate::actions::h3::Action;
55use crate::actions::h3::WaitType;
56use crate::actions::h3::WaitingFor;
57use crate::client::execute_action;
58use crate::client::parse_args;
59use crate::client::parse_streams;
60use crate::client::ClientError;
61use crate::client::CloseTriggerFrames;
62use crate::client::ConnectionSummary;
63use crate::client::ParsedArgs;
64use crate::client::StreamMap;
65use crate::client::MAX_DATAGRAM_SIZE;
66use crate::config::Config as H3iConfig;
67use crate::frame::H3iFrame;
68use crate::quiche;
69
70use super::Client;
71use super::ConnectionCloseDetails;
72use super::StreamParserMap;
73
74/// Connect to the socket.
75pub async fn connect(
76    args: &H3iConfig, frame_actions: Vec<Action>,
77    close_trigger_frames: Option<CloseTriggerFrames>,
78) -> std::result::Result<BuildingConnectionSummary, ClientError> {
79    let quic_settings = create_config(args);
80    let mut connection_params =
81        ConnectionParams::new_client(quic_settings, None, Hooks::default());
82
83    connection_params.session = args.session.clone();
84
85    let ParsedArgs {
86        connect_url,
87        bind_addr,
88        peer_addr,
89    } = parse_args(args);
90
91    let socket = tokio::net::UdpSocket::bind(bind_addr).await.unwrap();
92    socket.connect(peer_addr).await.unwrap();
93
94    log::info!(
95        "connecting to {:} from {:}",
96        peer_addr,
97        socket.local_addr().unwrap()
98    );
99
100    let (h3i, conn_summary_fut) =
101        H3iDriver::new(frame_actions, close_trigger_frames);
102    match tokio_quiche::quic::connect_with_config(
103        Socket::try_from(socket).unwrap(),
104        connect_url,
105        &connection_params,
106        h3i,
107    )
108    .await
109    {
110        Ok(_) => Ok(conn_summary_fut),
111        Err(_) => Err(ClientError::HandshakeFail),
112    }
113}
114
115fn create_config(args: &H3iConfig) -> QuicSettings {
116    let mut quic_settings = QuicSettings::default();
117
118    quic_settings.verify_peer = args.verify_peer;
119    quic_settings.max_idle_timeout =
120        Some(Duration::from_millis(args.idle_timeout));
121    quic_settings.max_recv_udp_payload_size = MAX_DATAGRAM_SIZE;
122    quic_settings.max_send_udp_payload_size = MAX_DATAGRAM_SIZE;
123    quic_settings.initial_max_data = 10_000_000;
124    quic_settings.initial_max_stream_data_bidi_local =
125        args.max_stream_data_bidi_local;
126    quic_settings.initial_max_stream_data_bidi_remote =
127        args.max_stream_data_bidi_remote;
128    quic_settings.initial_max_stream_data_uni = args.max_stream_data_uni;
129    quic_settings.initial_max_streams_bidi = args.max_streams_bidi;
130    quic_settings.initial_max_streams_uni = args.max_streams_uni;
131    quic_settings.disable_active_migration = true;
132    quic_settings.active_connection_id_limit = 0;
133    quic_settings.max_connection_window = args.max_window;
134    quic_settings.max_stream_window = args.max_stream_window;
135    quic_settings.enable_send_streams_blocked = true;
136    quic_settings.grease = false;
137
138    quic_settings.capture_quiche_logs = true;
139    quic_settings.keylog_file = std::env::var_os("SSLKEYLOGFILE")
140        .and_then(|os_str| os_str.into_string().ok());
141
142    quic_settings.enable_dgram = args.enable_dgram;
143    quic_settings.dgram_recv_max_queue_len = args.dgram_recv_queue_len;
144    quic_settings.dgram_send_max_queue_len = args.dgram_send_queue_len;
145
146    quic_settings
147}
148
149/// The [`Future`] used to build a [`ConnectionSummary`].
150///
151/// At a high level, [`H3iDriver`] will interact with the UDP socket directly,
152/// sending and receiving data as necessary. As new data is received, it will
153/// send [`ConnectionRecord`]s to this struct, which uses these records to
154/// construct the [`ConnectionSummary`].
155#[must_use = "must await to get a ConnectionSummary"]
156pub struct BuildingConnectionSummary {
157    rx: mpsc::UnboundedReceiver<ConnectionRecord>,
158    summary: Option<ConnectionSummary>,
159    seen_all_close_trigger_frames: Option<oneshot::Sender<()>>,
160}
161
162impl BuildingConnectionSummary {
163    fn new(
164        rx: mpsc::UnboundedReceiver<ConnectionRecord>,
165        close_trigger_frames: Option<CloseTriggerFrames>,
166        trigger_frame_tx: oneshot::Sender<()>,
167    ) -> Self {
168        let summary = ConnectionSummary {
169            stream_map: StreamMap::new(close_trigger_frames),
170            ..Default::default()
171        };
172
173        Self {
174            rx,
175            summary: Some(summary),
176            seen_all_close_trigger_frames: Some(trigger_frame_tx),
177        }
178    }
179}
180
181impl Future for BuildingConnectionSummary {
182    type Output = ConnectionSummary;
183
184    fn poll(
185        mut self: Pin<&mut Self>, cx: &mut Context<'_>,
186    ) -> Poll<Self::Output> {
187        while let Poll::Ready(Some(record)) = self.rx.poll_recv(cx) {
188            // Grab all records received from the current event loop iteration and
189            // insert them into the in-progress summary
190            let summary = self.summary.as_mut().expect("summary already taken");
191
192            match record {
193                ConnectionRecord::StreamedFrame { stream_id, frame } => {
194                    let stream_map = &mut summary.stream_map;
195                    stream_map.insert(stream_id, frame);
196
197                    if stream_map.all_close_trigger_frames_seen() {
198                        // Signal the H3iDriver task to close the connection.
199                        if let Some(expected_tx) =
200                            self.seen_all_close_trigger_frames.take()
201                        {
202                            let _ = expected_tx.send(());
203                        }
204                    }
205                },
206                ConnectionRecord::ConnectionStats(s) => summary.stats = Some(s),
207                ConnectionRecord::PathStats(ps) => summary.path_stats = ps,
208                ConnectionRecord::Close(d) => summary.conn_close_details = d,
209            };
210        }
211
212        if self.rx.is_closed() {
213            // The sender drops when the Tokio-Quiche IOW finishes, so the
214            // connection is done and we're safe to yield the summary.
215            let summary = self.summary.take().expect("summary already taken");
216            Poll::Ready(summary)
217        } else {
218            Poll::Pending
219        }
220    }
221}
222
223pub struct H3iDriver {
224    actions: Vec<Action>,
225    actions_executed: usize,
226    next_fire_time: Instant,
227    waiting_for_responses: WaitingFor,
228    record_tx: mpsc::UnboundedSender<ConnectionRecord>,
229    stream_parsers: StreamParserMap,
230    close_trigger_seen_rx: oneshot::Receiver<()>,
231}
232
233impl H3iDriver {
234    fn new(
235        actions: Vec<Action>, close_trigger_frames: Option<CloseTriggerFrames>,
236    ) -> (Self, BuildingConnectionSummary) {
237        let (record_tx, record_rx) = mpsc::unbounded_channel();
238        let (close_trigger_seen_tx, close_trigger_seen_rx) = oneshot::channel();
239        let fut = BuildingConnectionSummary::new(
240            record_rx,
241            close_trigger_frames,
242            close_trigger_seen_tx,
243        );
244
245        (
246            Self {
247                actions,
248                actions_executed: 0,
249                next_fire_time: Instant::now(),
250                waiting_for_responses: WaitingFor::default(),
251                record_tx,
252                stream_parsers: StreamParserMap::default(),
253                close_trigger_seen_rx,
254            },
255            fut,
256        )
257    }
258
259    /// If the next action should fire.
260    fn should_fire(&self) -> bool {
261        Instant::now() >= self.next_fire_time
262    }
263
264    /// Insert all waits into the waiting set.
265    fn register_waits(&mut self) {
266        while self.actions_executed < self.actions.len() {
267            if let Action::Wait { wait_type } =
268                &self.actions[self.actions_executed]
269            {
270                self.actions_executed += 1;
271
272                match wait_type {
273                    WaitType::WaitDuration(duration) => {
274                        self.next_fire_time = Instant::now() + *duration;
275
276                        log::debug!(
277                            "h3i: waiting for responses: {:?}",
278                            self.waiting_for_responses
279                        );
280                    },
281                    WaitType::StreamEvent(event) => {
282                        self.waiting_for_responses.add_wait(event);
283                    },
284                    WaitType::CanOpenNumStreams(required_streams) => {
285                        log::info!(
286                            "h3i: waiting for peer_streams_left_bidi >= {required_streams:?}"
287                        );
288                        self.waiting_for_responses
289                            .set_required_stream_quota(*required_streams);
290                    },
291                }
292            } else {
293                break;
294            }
295        }
296    }
297}
298
299impl Client for H3iDriver {
300    fn stream_parsers_mut(&mut self) -> &mut StreamParserMap {
301        &mut self.stream_parsers
302    }
303
304    fn handle_response_frame(
305        &mut self, stream_id: u64, frame: crate::frame::H3iFrame,
306    ) {
307        self.record_tx
308            .send(ConnectionRecord::StreamedFrame { stream_id, frame })
309            .expect("H3iDriver task dropped")
310    }
311}
312
313impl ApplicationOverQuic for H3iDriver {
314    fn on_conn_established(
315        &mut self, _qconn: &mut QuicheConnection, _handshake_info: &HandshakeInfo,
316    ) -> QuicResult<()> {
317        log::info!("h3i: HTTP/3 connection established");
318        Ok(())
319    }
320
321    fn should_act(&self) -> bool {
322        // Even if the connection wasn't established, we should still send
323        // terminal records to the summary
324        true
325    }
326
327    fn process_reads(&mut self, qconn: &mut QuicheConnection) -> QuicResult<()> {
328        log::trace!("h3i: process_reads");
329
330        // This is executed in process_reads so that work_loop can clear any waits
331        // on the current event loop iteration - if it was in process_writes, we
332        // could potentially miss waits and hang the client.
333        self.register_waits();
334
335        let stream_events = parse_streams(qconn, self);
336        for event in stream_events {
337            self.waiting_for_responses.remove_wait(event);
338        }
339
340        self.waiting_for_responses.check_can_open_num_streams(qconn);
341
342        Ok(())
343    }
344
345    fn process_writes(&mut self, qconn: &mut QuicheConnection) -> QuicResult<()> {
346        log::trace!("h3i: process_writes");
347
348        if !self.waiting_for_responses.is_empty() {
349            log::debug!(
350                "awaiting responses on streams {:?}, skipping further action",
351                self.waiting_for_responses
352            );
353
354            return Ok(());
355        }
356
357        // Re-create the iterator so we can mutably borrow the stream parser map
358        let iter = self.actions.clone().into_iter().skip(self.actions_executed);
359
360        for action in iter {
361            match action {
362                Action::SendFrame { .. } |
363                Action::StreamBytes { .. } |
364                Action::SendDatagram { .. } |
365                Action::ResetStream { .. } |
366                Action::StopSending { .. } |
367                Action::OpenUniStream { .. } |
368                Action::ConnectionClose { .. } |
369                Action::SendHeadersFrame { .. } => {
370                    if self.should_fire() {
371                        // Reset the fire time such that the next action will
372                        // still fire.
373                        self.next_fire_time = Instant::now();
374
375                        execute_action(&action, qconn, self.stream_parsers_mut());
376                        self.actions_executed += 1;
377                    } else {
378                        break;
379                    }
380                },
381                Action::Wait { .. } => {
382                    // Break out of the write phase if we see a wait, since waits
383                    // have to be registered in the read
384                    // phase. The actions_executed pointer will be
385                    // incremented there as well
386                    break;
387                },
388                Action::FlushPackets => {
389                    self.actions_executed += 1;
390                    break;
391                },
392            }
393        }
394
395        Ok(())
396    }
397
398    async fn wait_for_data(
399        &mut self, qconn: &mut QuicheConnection,
400    ) -> QuicResult<()> {
401        log::trace!("h3i: wait_for_data");
402
403        let sleep_fut = if !self.should_fire() {
404            sleep_until(self.next_fire_time)
405        } else {
406            // If we have nothing to send, allow the IOW to resolve wait_for_data
407            // on its own (whether via Quiche timer or incoming data).
408            sleep(Duration::MAX)
409        };
410
411        select! {
412            rx = &mut self.close_trigger_seen_rx, if !self.close_trigger_seen_rx.is_terminated() => {
413                // NOTE: wait_for_data can be called again after all close triggers have been seen,
414                // depending on how long it takes quiche to mark the connection as closed.
415                // Therefore we can't re-poll the receiver or we'd panic.
416                if rx.is_ok() {
417                    // TODO: customizable close trigger frames
418                    let _ = qconn.close(true, quiche::h3::WireErrorCode::NoError as u64, b"saw all expected frames");
419                }
420            }
421            _ = sleep_fut => {}
422        }
423
424        Ok(())
425    }
426
427    fn on_conn_close<M: Metrics>(
428        &mut self, qconn: &mut QuicheConnection, _metrics: &M,
429        _work_loop_result: &QuicResult<()>,
430    ) {
431        let _ = self
432            .record_tx
433            .send(ConnectionRecord::Close(ConnectionCloseDetails::new(qconn)));
434
435        let _ = self
436            .record_tx
437            .send(ConnectionRecord::ConnectionStats(qconn.stats()));
438
439        let conn_path_stats = qconn.path_stats().collect::<Vec<PathStats>>();
440        let _ = self
441            .record_tx
442            .send(ConnectionRecord::PathStats(conn_path_stats));
443    }
444}
445
446pub enum ConnectionRecord {
447    StreamedFrame { stream_id: u64, frame: H3iFrame },
448    Close(ConnectionCloseDetails),
449    PathStats(Vec<PathStats>),
450    ConnectionStats(Stats),
451}