Skip to main content

tokio_quiche/quic/io/
worker.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
27use std::net::SocketAddr;
28use std::ops::ControlFlow;
29use std::sync::Arc;
30use std::task::Poll;
31use std::time::Duration;
32use std::time::Instant;
33#[cfg(feature = "perf-quic-listener-metrics")]
34use std::time::SystemTime;
35
36use super::connection_stage::Close;
37use super::connection_stage::ConnectionStage;
38use super::connection_stage::ConnectionStageContext;
39use super::connection_stage::Handshake;
40use super::connection_stage::RunningApplication;
41use super::gso::*;
42use super::utilization_estimator::BandwidthReporter;
43
44use crate::metrics::labels;
45use crate::metrics::Metrics;
46use crate::quic::connection::ApplicationOverQuic;
47use crate::quic::connection::HandshakeError;
48use crate::quic::connection::HandshakeInfo;
49use crate::quic::connection::Incoming;
50use crate::quic::connection::IncomingPacketReceiver;
51use crate::quic::connection::QuicConnectionStats;
52use crate::quic::connection::SharedConnectionIdGenerator;
53use crate::quic::hooks::ConnectionHook;
54use crate::quic::DscpHandle;
55use crate::quic::QuicheConnection;
56use crate::QuicResult;
57
58use boring::ssl::SslRef;
59use datagram_socket::DatagramSocketSend;
60use datagram_socket::DatagramSocketSendExt;
61use datagram_socket::MaybeConnectedSocket;
62use datagram_socket::QuicAuditStats;
63use foundations::telemetry::log;
64use foundations::telemetry::metrics::Gauge;
65use foundations::telemetry::metrics::GaugeGuard;
66use quiche::Error as QuicheError;
67use quiche::SendInfo;
68use tokio::select;
69use tokio::sync::mpsc;
70use tokio::time;
71
72// Number of incoming packets to be buffered in the incoming channel.
73pub(crate) const INCOMING_QUEUE_SIZE: usize = 2048;
74
75// Check if there are any incoming packets while sending data every this number
76// of sent packets
77pub(crate) const CHECK_INCOMING_QUEUE_RATIO: usize = INCOMING_QUEUE_SIZE / 16;
78
79const RELEASE_TIMER_THRESHOLD: Duration = Duration::from_micros(250);
80
81/// Stop queuing GSO packets, if packet size is below this threshold.
82const GSO_THRESHOLD: usize = 1_000;
83
84/// Size of each full egress buffer borrowed for a send burst.
85///
86/// Matches the maximum quiche buffer size so GSO batching is unaffected while
87/// a connection is actively sending. Unlike a persistent per-connection
88/// buffer, this memory is returned to the per-worker [`SEND_BUF_POOL`] before
89/// the worker sleeps. The free list retains it for reuse (rather than truly
90/// freeing it) but no idle connection owns an egress buffer.
91const SEND_BUFFER_SIZE: usize = crate::buf_factory::BufFactory::MAX_BUF_SIZE;
92
93/// Size of a temporary egress buffer when pooling is disabled.
94///
95/// The cold handshake and connection-close paths generate a single datagram at
96/// a time. When pooling is enabled, they borrow a full-size buffer from
97/// [`SEND_BUF_POOL`]; otherwise a one-MTU buffer is enough.
98const TRANSIENT_SEND_BUFFER_SIZE: usize = 1500;
99
100/// Allocates a zero-initialized egress buffer on the heap.
101///
102/// This is the cold path that fills [`SEND_BUF_POOL`] on a miss; steady-state
103/// bursts borrow a recycled buffer via [`PooledSendBuf::acquire`] and never
104/// hit this. The buffer is boxed (never a stack array) so that holding it
105/// across the `.await` in [`IoWorker::flush_buffer_to_socket`] keeps the
106/// worker's futures small and avoids uncontrolled stack growth.
107fn alloc_send_buffer() -> Box<[u8]> {
108    vec![0u8; SEND_BUFFER_SIZE].into_boxed_slice()
109}
110
111thread_local! {
112    /// Per-runtime-worker free-list of egress scratch buffers.
113    ///
114    /// A buffer is borrowed for a single send burst and returned on drop, so
115    /// its pages stay resident across bursts (no per-burst page fault or
116    /// kernel zero-fill) while no idle connection retains a buffer: the pool
117    /// holds at most [`SEND_BUF_POOL_CAP`] buffers per worker thread,
118    /// independent of the connection count.
119    static SEND_BUF_POOL: std::cell::RefCell<Vec<Box<[u8]>>> =
120        const { std::cell::RefCell::new(Vec::new()) };
121}
122
123/// Upper bound on egress buffers parked per worker thread. The natural
124/// high-water mark is the number of connection tasks simultaneously suspended
125/// at a flush `.await` on one runtime thread; returns beyond the cap are freed
126/// so a burst spike cannot pin unbounded memory to a thread.
127///
128/// This is a fixed per-worker-thread reservation, independent of the
129/// connection count: up to `SEND_BUF_POOL_CAP * SEND_BUFFER_SIZE`
130/// (16 * 64 KiB = 1 MiB) per runtime worker thread. The pool is not shrunk
131/// once grown, so after a burst it stays at its high-water mark for the
132/// process lifetime.
133const SEND_BUF_POOL_CAP: usize = 16;
134
135/// Egress scratch buffer borrowed from the per-thread [`SEND_BUF_POOL`] and
136/// returned to it on drop.
137///
138/// Behaves like the `Box<[u8]>` it replaces via `Deref`/`DerefMut`, so idle
139/// connections still retain no egress buffer, but the backing pages are
140/// recycled instead of re-faulted (and re-zeroed by the kernel) every burst.
141struct PooledSendBuf(Box<[u8]>);
142
143impl PooledSendBuf {
144    fn acquire() -> Self {
145        let buf = SEND_BUF_POOL
146            .with(|pool| pool.borrow_mut().pop())
147            .unwrap_or_else(|| {
148                // Pool miss (cold path): allocate a fresh buffer and record it.
149                // Re-using a parked buffer (the hot path) does not touch any
150                // counter.
151                crate::metrics::quic::send_buffer_pool_allocated().inc();
152                alloc_send_buffer()
153            });
154        // No re-zeroing on reuse: quiche writes only the bytes it emits and
155        // the flush path transmits solely `send_buf[..bytes_written]`, so any
156        // stale bytes left by a previous burst are never sent.
157        Self(buf)
158    }
159}
160
161impl Drop for PooledSendBuf {
162    fn drop(&mut self) {
163        // Move the buffer out, leaving an empty (non-allocating) boxed slice
164        // behind, so it can be returned to the pool. Storing a plain
165        // `Box<[u8]>` rather than an `Option` keeps `Deref`/`DerefMut`
166        // panic-free.
167        let buf = std::mem::take(&mut self.0);
168        // Returns to *this* thread's pool. With tokio work-stealing a task may
169        // migrate across the flush `.await`, so a buffer can be acquired on one
170        // worker and returned on another; this is benign, and the per-thread
171        // cap keeps the total bounded by `cap * workers`.
172        SEND_BUF_POOL.with(|pool| {
173            let mut pool = pool.borrow_mut();
174            if pool.len() < SEND_BUF_POOL_CAP {
175                pool.push(buf);
176            } else {
177                // Pool already at capacity (cold path, only under burst
178                // spikes): drop the buffer instead of parking it, and record
179                // the discard. Returning to a non-full pool (the hot path)
180                // does not touch any counter.
181                crate::metrics::quic::send_buffer_pool_discarded().inc();
182            }
183        });
184    }
185}
186
187impl std::ops::Deref for PooledSendBuf {
188    type Target = [u8];
189
190    fn deref(&self) -> &[u8] {
191        &self.0
192    }
193}
194
195impl std::ops::DerefMut for PooledSendBuf {
196    fn deref_mut(&mut self) -> &mut [u8] {
197        &mut self.0
198    }
199}
200
201/// Egress buffer used briefly outside the main write loop.
202///
203/// This preserves the runtime pooling switch for handshake and close paths:
204/// pooling borrows a full-size recycled buffer, while disabling it allocates a
205/// small one-off buffer.
206enum TransientSendBuf {
207    Pooled(PooledSendBuf),
208    Unpooled(Box<[u8]>),
209}
210
211impl TransientSendBuf {
212    fn acquire(pool_send_buffer: bool) -> Self {
213        if pool_send_buffer {
214            Self::Pooled(PooledSendBuf::acquire())
215        } else {
216            Self::Unpooled(
217                vec![0u8; TRANSIENT_SEND_BUFFER_SIZE].into_boxed_slice(),
218            )
219        }
220    }
221}
222
223impl AsRef<[u8]> for TransientSendBuf {
224    fn as_ref(&self) -> &[u8] {
225        match self {
226            Self::Pooled(buf) => &buf[..],
227            Self::Unpooled(buf) => &buf[..],
228        }
229    }
230}
231
232impl AsMut<[u8]> for TransientSendBuf {
233    fn as_mut(&mut self) -> &mut [u8] {
234        match self {
235            Self::Pooled(buf) => &mut buf[..],
236            Self::Unpooled(buf) => &mut buf[..],
237        }
238    }
239}
240
241pub struct WriterConfig {
242    pub peer_addr: SocketAddr,
243    pub local_addr: SocketAddr,
244    pub with_gso: bool,
245    pub pacing_offload: bool,
246    pub with_pktinfo: bool,
247    /// Whether the worker borrows its egress buffer from a per-worker-thread
248    /// pool for each send burst. When `false`, the worker keeps a persistent
249    /// per-connection buffer for its lifetime instead.
250    pub pool_send_buffer: bool,
251}
252
253#[derive(Default)]
254pub(crate) struct WriteState {
255    conn_established: bool,
256    bytes_written: usize,
257    segment_size: usize,
258    num_pkts: usize,
259    tx_time: Option<Instant>,
260    has_pending_data: bool,
261    // If pacer schedules packets too far into the future, we want to pause
262    // sending, until the future arrives
263    next_release_time: Option<Instant>,
264    // The selected source and destination addresses for the current write
265    // cycle.
266    selected_path: Option<(SocketAddr, SocketAddr)>,
267    // Iterator over the network paths that haven't been flushed yet.
268    pending_paths: quiche::SocketAddrIter,
269}
270
271pub(crate) struct IoWorkerParams<Tx, M> {
272    pub(crate) socket: MaybeConnectedSocket<Tx>,
273    pub(crate) shutdown_tx: mpsc::Sender<()>,
274    pub(crate) cfg: WriterConfig,
275    pub(crate) audit_log_stats: Arc<QuicAuditStats>,
276    pub(crate) write_state: WriteState,
277    pub(crate) dscp_handle: Option<DscpHandle>,
278    pub(crate) cid_generator: Option<SharedConnectionIdGenerator>,
279    #[cfg(feature = "perf-quic-listener-metrics")]
280    pub(crate) init_rx_time: Option<SystemTime>,
281    pub(crate) metrics: M,
282    pub(crate) handshake_info: HandshakeInfo,
283    pub(crate) active_conn_guard: GaugeGuard<Gauge>,
284}
285
286fn notify_path_events(
287    connection_hook: Option<&(dyn ConnectionHook + Send + Sync + 'static)>,
288    qconn: &mut QuicheConnection,
289) {
290    while let Some(path_event) = qconn.path_event_next() {
291        if let Some(hook) = connection_hook {
292            hook.on_path_event(qconn, &path_event);
293        }
294    }
295}
296
297pub(crate) struct IoWorker<Tx, M, S> {
298    socket: MaybeConnectedSocket<Tx>,
299    /// A field that signals to the listener task that the connection has gone
300    /// away (nothing is sent here, listener task just detects the sender
301    /// has dropped)
302    shutdown_tx: mpsc::Sender<()>,
303    cfg: WriterConfig,
304    audit_log_stats: Arc<QuicAuditStats>,
305    write_state: WriteState,
306    dscp_handle: Option<DscpHandle>,
307    cid_generator: Option<SharedConnectionIdGenerator>,
308    #[cfg(feature = "perf-quic-listener-metrics")]
309    init_rx_time: Option<SystemTime>,
310    metrics: M,
311    /// The handshake deadline is enforced by the worker until the handshake
312    /// completes, regardless of the connection stage. With 0-RTT early data,
313    /// the application is started before the handshake completes, and a peer
314    /// that never completes it could otherwise keep the connection in early
315    /// data indefinitely.
316    handshake_info: HandshakeInfo,
317    conn_stage: S,
318    bw_estimator: BandwidthReporter,
319    /// Guard to decrement the `connections_in_memory` gauge on drop.
320    active_conn_guard: GaugeGuard<Gauge>,
321}
322
323impl<Tx, M, S> IoWorker<Tx, M, S>
324where
325    Tx: DatagramSocketSend + Send,
326    M: Metrics,
327    S: ConnectionStage,
328{
329    pub(crate) fn new(params: IoWorkerParams<Tx, M>, conn_stage: S) -> Self {
330        let bw_estimator =
331            BandwidthReporter::new(params.metrics.utilized_bandwidth());
332
333        log::trace!("Creating IoWorker with stage: {conn_stage:?}");
334
335        Self {
336            socket: params.socket,
337            shutdown_tx: params.shutdown_tx,
338            cfg: params.cfg,
339            audit_log_stats: params.audit_log_stats,
340            write_state: params.write_state,
341            dscp_handle: params.dscp_handle,
342            cid_generator: params.cid_generator,
343            #[cfg(feature = "perf-quic-listener-metrics")]
344            init_rx_time: params.init_rx_time,
345            metrics: params.metrics,
346            handshake_info: params.handshake_info,
347            conn_stage,
348            bw_estimator,
349            active_conn_guard: params.active_conn_guard,
350        }
351    }
352
353    fn fill_available_scids(
354        &self, qconn: &mut QuicheConnection,
355        incoming_pkt_receiver: &mut IncomingPacketReceiver,
356    ) {
357        if qconn.scids_left() == 0 {
358            return;
359        }
360        let Some(cid_generator) = self.cid_generator.as_deref() else {
361            return;
362        };
363
364        for _ in 0..qconn.scids_left() {
365            // We don't emit stateless resets, so any unguessable value is fine
366            let reset_token = random_u128();
367            let new_cid = cid_generator.new_connection_id();
368
369            if !incoming_pkt_receiver.map_cid(&new_cid) {
370                // Can't do anything if the connection map is gone
371                return;
372            }
373
374            if qconn.new_scid(&new_cid, reset_token, false).is_err() {
375                // This only fails if we have reached the CID limit already
376                return;
377            }
378        }
379    }
380
381    fn refresh_connection_ids(
382        &self, qconn: &mut QuicheConnection,
383        incoming_pkt_receiver: &mut IncomingPacketReceiver,
384    ) {
385        // Top up the connection's active CIDs
386        self.fill_available_scids(qconn, incoming_pkt_receiver);
387
388        // Remove retired CIDs from the ingress router
389        while let Some(retired_cid) = qconn.retired_scid_next() {
390            incoming_pkt_receiver.unmap_cid(&retired_cid);
391        }
392    }
393
394    async fn work_loop<A: ApplicationOverQuic>(
395        &mut self, qconn: &mut QuicheConnection,
396        ctx: &mut ConnectionStageContext<A>,
397    ) -> QuicResult<()> {
398        const DEFAULT_SLEEP: Duration = Duration::from_secs(60);
399        let mut current_deadline: Option<Instant> = None;
400        let sleep = time::sleep(DEFAULT_SLEEP);
401        tokio::pin!(sleep);
402
403        // Without pooling, the IO worker owns one egress buffer for the entire
404        // connection, including idle periods. With pooling, this remains `None`
405        // and each send burst borrows a buffer from the per-worker pool.
406        let mut persistent_send_buf: Option<Box<[u8]>> =
407            (!self.cfg.pool_send_buffer).then(alloc_send_buffer);
408
409        loop {
410            let now = Instant::now();
411
412            self.write_state.has_pending_data = true;
413
414            // Transient egress buffer for this wakeup's send burst when pooling
415            // is enabled. Borrowed from the per-worker pool on demand (see
416            // below) and returned after the burst, before the worker sleeps in
417            // the `select!` further down, so idle connections still hold no
418            // egress buffer. Stays `None` when a persistent buffer is used.
419            let mut pooled_send_buf: Option<PooledSendBuf> = None;
420
421            while self.write_state.has_pending_data {
422                let mut packets_sent = 0;
423
424                // Drain received packets periodically because they contain ACKs
425                // and the bounded receive queue stalls new packets when full.
426                let mut did_recv = false;
427                while let Some(pkt) = ctx
428                    .in_pkt
429                    .take()
430                    .or_else(|| ctx.incoming_pkt_receiver.rx.try_recv().ok())
431                {
432                    self.process_incoming(qconn, pkt)?;
433                    did_recv = true;
434                }
435
436                // Deliver transport-generated events before the application can
437                // consume them.
438                notify_path_events(ctx.connection_hook.as_deref(), qconn);
439
440                self.conn_stage.on_read(did_recv, qconn, ctx)?;
441
442                // Deliver events generated by application reads or writes.
443                notify_path_events(ctx.connection_hook.as_deref(), qconn);
444                self.refresh_connection_ids(
445                    qconn,
446                    &mut ctx.incoming_pkt_receiver,
447                );
448
449                let can_release = match self.write_state.next_release_time {
450                    None => true,
451                    Some(next_release) =>
452                        next_release
453                            .checked_duration_since(now)
454                            .unwrap_or_default() <
455                            RELEASE_TIMER_THRESHOLD,
456                };
457
458                self.write_state.has_pending_data &= can_release;
459
460                while self.write_state.has_pending_data &&
461                    packets_sent < CHECK_INCOMING_QUEUE_RATIO
462                {
463                    // Use the persistent per-connection buffer when pooling is
464                    // disabled. Otherwise borrow a buffer from the per-worker
465                    // pool on the first gather of this send burst and reuse it
466                    // for the remainder of the burst; it is returned at the end
467                    // of the enclosing block (below), before the worker sleeps,
468                    // so idle connections hold no egress buffer.
469                    let send_buf: &mut [u8] =
470                        if let Some(buf) = persistent_send_buf.as_deref_mut() {
471                            buf
472                        } else {
473                            &mut pooled_send_buf
474                                .get_or_insert_with(PooledSendBuf::acquire)[..]
475                        };
476
477                    self.gather_data_from_quiche_conn(qconn, send_buf, false)?;
478
479                    // Break if the connection is closed
480                    if qconn.is_closed() {
481                        return Ok(());
482                    }
483
484                    let mut flush_operation_token =
485                        TrackMidHandshakeFlush::new(self.metrics.clone());
486
487                    self.flush_buffer_to_socket(&send_buf[..]).await;
488
489                    flush_operation_token.mark_complete();
490
491                    packets_sent += self.write_state.num_pkts;
492
493                    if let ControlFlow::Break(reason) =
494                        self.conn_stage.on_flush(qconn, ctx)
495                    {
496                        return reason;
497                    }
498                }
499            }
500
501            // Return the borrowed egress buffer to the per-worker pool before
502            // sleeping so it is not held while the connection is idle. The
503            // persistent buffer (when pooling is disabled) is intentionally
504            // kept across sleeps for the connection's lifetime.
505            drop(pooled_send_buf);
506
507            self.bw_estimator.update(qconn, now);
508
509            self.audit_log_stats
510                .set_max_bandwidth(self.bw_estimator.max_bandwidth);
511            self.audit_log_stats.set_max_loss_pct(
512                (self.bw_estimator.max_loss_pct * 100_f32).round() as u8,
513            );
514
515            let new_deadline = min_of_some(
516                qconn.timeout_instant(),
517                self.write_state.next_release_time,
518            );
519            let new_deadline =
520                min_of_some(new_deadline, self.handshake_deadline(qconn));
521
522            if new_deadline != current_deadline {
523                current_deadline = new_deadline;
524
525                sleep
526                    .as_mut()
527                    .reset(new_deadline.unwrap_or(now + DEFAULT_SLEEP).into());
528            }
529
530            let incoming_recv = &mut ctx.incoming_pkt_receiver.rx;
531            let application = &mut ctx.application;
532
533            select! {
534                biased;
535                () = &mut sleep => {
536                    // It's very important that we keep the timeout arm at the top of this loop so
537                    // that we poll it every time we need to. Since this is a biased `select!`, if
538                    // we put this behind another arm, we could theoretically starve the sleep arm
539                    // and hang connections.
540                    //
541                    // See https://docs.rs/tokio/latest/tokio/macro.select.html#fairness for more
542                    qconn.on_timeout();
543
544                    self.write_state.next_release_time = None;
545                    current_deadline = None;
546                    sleep.as_mut().reset((now + DEFAULT_SLEEP).into());
547                }
548                Some(pkt) = incoming_recv.recv() => ctx.in_pkt = Some(pkt),
549                directive = self.wait_for_data_or_handshake(qconn, application) => {
550                    match directive? {
551                        WaitForDataOrHandshakeDirective::Flush(send_buf) => {
552                            // The handshake data was gathered into this
553                            // on-demand buffer; flush it here (outside the
554                            // select! so the flush cannot be cancelled), then
555                            // return it to the pool or drop it.
556                            self.flush_buffer_to_socket(send_buf.as_ref()).await;
557                        }
558                        WaitForDataOrHandshakeDirective::Noop => {}
559                    }
560                },
561            };
562
563            self.enforce_handshake_deadline(qconn)?;
564        }
565    }
566
567    #[cfg(feature = "perf-quic-listener-metrics")]
568    fn measure_complete_handshake_time(&mut self) {
569        if let Some(init_rx_time) = self.init_rx_time.take() {
570            if let Ok(delta) = init_rx_time.elapsed() {
571                self.metrics
572                    .handshake_time_seconds(
573                        labels::QuicHandshakeStage::HandshakeResponse,
574                    )
575                    .observe(delta.as_nanos() as u64);
576            }
577        }
578    }
579
580    /// Gathers one or more packets from quiche into `send_buf`.
581    ///
582    /// A single-packet gather leaves a full buffer available for the next
583    /// packet instead of generating a short packet in the remaining tail.
584    fn gather_data_from_quiche_conn(
585        &mut self, qconn: &mut QuicheConnection, send_buf: &mut [u8],
586        single_packet: bool,
587    ) -> QuicResult<usize> {
588        let mut segment_size = None;
589        let mut send_info = None;
590
591        self.write_state.num_pkts = 0;
592        self.write_state.bytes_written = 0;
593
594        self.write_state.selected_path = None;
595
596        let now = Instant::now();
597
598        let send_buf = {
599            let trunc = UDP_MAX_GSO_PACKET_SIZE.min(send_buf.len());
600            &mut send_buf[..trunc]
601        };
602
603        #[cfg(feature = "gcongestion")]
604        let gcongestion_enabled = true;
605
606        #[cfg(not(feature = "gcongestion"))]
607        let gcongestion_enabled = qconn.gcongestion_enabled().unwrap_or(false);
608
609        let initial_release_decision = if gcongestion_enabled {
610            let initial_release_decision = qconn
611                .get_next_release_time()
612                .filter(|_| self.pacing_enabled(qconn));
613
614            if let Some(future_release_time) =
615                initial_release_decision.as_ref().and_then(|v| v.time(now))
616            {
617                let max_into_fut = qconn.max_release_into_future();
618
619                if future_release_time.duration_since(now) >= max_into_fut {
620                    self.write_state.next_release_time =
621                        Some(now + max_into_fut.mul_f32(0.8));
622                    self.write_state.has_pending_data = false;
623                    return Ok(0);
624                }
625            }
626
627            initial_release_decision
628        } else {
629            None
630        };
631
632        let buffer_write_outcome = loop {
633            let outcome = self.write_packet_to_buffer(
634                qconn,
635                send_buf,
636                &mut send_info,
637                segment_size,
638            );
639
640            let packet_size = match outcome {
641                Ok(0) => break Ok(0),
642
643                Ok(bytes_written) => bytes_written,
644
645                Err(e) => break Err(e),
646            };
647
648            // Flush after one packet when GSO is disabled or the caller needs
649            // each packet to start with a full buffer.
650            if single_packet || !self.cfg.with_gso {
651                break outcome;
652            }
653
654            #[cfg(not(feature = "gcongestion"))]
655            let max_send_size = if !gcongestion_enabled {
656                // Only call qconn.send_quantum when !gcongestion_enabled.
657                tune_max_send_size(
658                    segment_size,
659                    qconn.send_quantum(),
660                    send_buf.len(),
661                )
662            } else {
663                usize::MAX
664            };
665
666            #[cfg(feature = "gcongestion")]
667            let max_send_size = usize::MAX;
668
669            // If segment_size is known, update the maximum of
670            // GSO sender buffer size to the multiple of
671            // segment_size.
672            let buffer_is_full = self.write_state.num_pkts ==
673                UDP_MAX_SEGMENT_COUNT ||
674                self.write_state.bytes_written >= max_send_size;
675
676            if buffer_is_full {
677                break outcome;
678            }
679
680            // Flush to network when the newly generated packet size is
681            // different from previously written packet, as GSO needs packets
682            // to have the same size, except for the last one in the buffer.
683            // The last packet may be smaller than the previous size.
684            match segment_size {
685                Some(size)
686                    if packet_size != size || packet_size < GSO_THRESHOLD =>
687                    break outcome,
688                None => segment_size = Some(packet_size),
689                _ => (),
690            }
691
692            if gcongestion_enabled {
693                // Start a new batch if the next packet has a different release
694                // time or cannot be part of a burst.
695                if let Some(initial_release_decision) = initial_release_decision {
696                    match qconn.get_next_release_time() {
697                        Some(release)
698                            if release.can_burst() ||
699                                release.time_eq(
700                                    &initial_release_decision,
701                                    now,
702                                ) => {},
703                        _ => break outcome,
704                    }
705                }
706            }
707        };
708
709        let tx_time = if gcongestion_enabled {
710            initial_release_decision
711                .filter(|_| self.pacing_enabled(qconn))
712                // Return the time from the release decision if
713                // release_decision.time > now, else None.
714                .and_then(|v| v.time(now))
715        } else {
716            send_info
717                .filter(|_| self.pacing_enabled(qconn))
718                .map(|v| v.at)
719        };
720
721        self.write_state.conn_established = qconn.is_established();
722        self.write_state.tx_time = tx_time;
723        self.write_state.segment_size =
724            segment_size.unwrap_or(self.write_state.bytes_written);
725
726        if !gcongestion_enabled {
727            if let Some(time) = tx_time {
728                const DEFAULT_MAX_INTO_FUTURE: Duration =
729                    Duration::from_millis(1);
730                if time
731                    .checked_duration_since(now)
732                    .map(|d| d > DEFAULT_MAX_INTO_FUTURE)
733                    .unwrap_or(false)
734                {
735                    self.write_state.next_release_time =
736                        Some(now + DEFAULT_MAX_INTO_FUTURE.mul_f32(0.8));
737                    self.write_state.has_pending_data = false;
738                    return Ok(0);
739                }
740            }
741        }
742
743        buffer_write_outcome
744    }
745
746    /// Selects a network path, if none already selected.
747    ///
748    /// This will return the first path available in the write state's
749    /// `pending_paths` iterator. If that is empty a new iterator will be
750    /// created by querying quiche itself.
751    ///
752    /// Note that the connection's statically configured local address will be
753    /// used to query quiche for available paths, so this can't handle multiple
754    /// local addresses currently.
755    fn select_path(
756        &mut self, qconn: &QuicheConnection,
757    ) -> Option<(SocketAddr, SocketAddr)> {
758        if self.write_state.selected_path.is_some() {
759            return self.write_state.selected_path;
760        }
761
762        let from = self.cfg.local_addr;
763
764        // Initialize paths iterator.
765        if self.write_state.pending_paths.len() == 0 {
766            self.write_state.pending_paths = qconn.paths_iter(from);
767        }
768
769        let to = self.write_state.pending_paths.next()?;
770
771        Some((from, to))
772    }
773
774    #[cfg(not(feature = "gcongestion"))]
775    fn pacing_enabled(&self, qconn: &QuicheConnection) -> bool {
776        self.cfg.pacing_offload && qconn.pacing_enabled()
777    }
778
779    #[cfg(feature = "gcongestion")]
780    fn pacing_enabled(&self, _qconn: &QuicheConnection) -> bool {
781        self.cfg.pacing_offload
782    }
783
784    fn write_packet_to_buffer(
785        &mut self, qconn: &mut QuicheConnection, send_buf: &mut [u8],
786        send_info: &mut Option<SendInfo>, segment_size: Option<usize>,
787    ) -> QuicResult<usize> {
788        let mut send_buf = &mut send_buf[self.write_state.bytes_written..];
789        if send_buf.len() > segment_size.unwrap_or(usize::MAX) {
790            // Never let the buffer be longer than segment size, for GSO to
791            // function properly.
792            send_buf = &mut send_buf[..segment_size.unwrap_or(usize::MAX)];
793        }
794
795        // On the first call to `select_path()` a path will be chosen based on
796        // the local address the connection initially landed on. Once a path is
797        // selected following calls to `select_path()` will return it, until it
798        // is reset at the start of the next write cycle.
799        //
800        // The path is then passed to `send_on_path()` which will only generate
801        // packets meant for that path, this way a single GSO buffer will only
802        // contain packets that belong to the same network path, which is
803        // required because the from/to addresses for each `sendmsg()` call
804        // apply to the whole GSO buffer.
805        let (from, to) = self.select_path(qconn).unzip();
806
807        match qconn.send_on_path(send_buf, from, to) {
808            Ok((packet_size, info)) => {
809                let _ = send_info.get_or_insert(info);
810
811                self.write_state.bytes_written += packet_size;
812                self.write_state.num_pkts += 1;
813
814                let from = send_info.as_ref().map(|info| info.from);
815                let to = send_info.as_ref().map(|info| info.to);
816
817                self.write_state.selected_path = from.zip(to);
818
819                self.write_state.has_pending_data = true;
820
821                Ok(packet_size)
822            },
823
824            Err(QuicheError::Done) => {
825                // Flush the current buffer to network. If no other path needs
826                // to be flushed to the network also yield the work loop task.
827                //
828                // Otherwise the write loop will start again and the next path
829                // will be selected.
830                let has_pending_paths = self.write_state.pending_paths.len() > 0;
831
832                // Keep writing if there are paths left to try.
833                self.write_state.has_pending_data = has_pending_paths;
834
835                Ok(0)
836            },
837
838            Err(e) => {
839                let error_code = if let Some(local_error) = qconn.local_error() {
840                    local_error.error_code
841                } else {
842                    let internal_error_code =
843                        quiche::WireErrorCode::InternalError as u64;
844                    let _ = qconn.close(false, internal_error_code, &[]);
845
846                    internal_error_code
847                };
848
849                self.audit_log_stats
850                    .set_sent_conn_close_transport_error_code(error_code as i64);
851
852                Err(Box::new(e))
853            },
854        }
855    }
856
857    async fn flush_buffer_to_socket(&mut self, send_buf: &[u8]) {
858        if self.write_state.bytes_written > 0 {
859            let current_send_buf = &send_buf[..self.write_state.bytes_written];
860
861            let (from, to) = self.write_state.selected_path.unzip();
862
863            let to = to.unwrap_or(self.cfg.peer_addr);
864            let from = from.filter(|_| self.cfg.with_pktinfo);
865
866            let dscp = self.dscp_handle.as_ref().and_then(DscpHandle::get);
867            // Don't bypass the socket wrapper when DSCP cannot be applied.
868            let needs_dscp_cmsg =
869                cfg!(all(target_os = "linux", not(feature = "fuzzing"))) &&
870                    dscp.is_some();
871
872            let send_res = if let (Some(udp_socket), true) = (
873                self.socket.as_udp_socket(),
874                self.cfg.with_gso || needs_dscp_cmsg,
875            ) {
876                // Only UDP supports GSO and per-packet DSCP control messages.
877                let (segment_size, tx_time) = if self.cfg.with_gso {
878                    (
879                        Some(self.write_state.segment_size),
880                        self.write_state.tx_time,
881                    )
882                } else {
883                    (None, None)
884                };
885                send_to(
886                    udp_socket,
887                    to,
888                    from,
889                    current_send_buf,
890                    segment_size,
891                    tx_time,
892                    dscp,
893                    self.metrics
894                        .write_errors(labels::QuicWriteError::WouldBlock),
895                    self.metrics.send_to_wouldblock_duration_s(),
896                )
897                .await
898            } else {
899                self.socket.send_to(current_send_buf, to).await
900            };
901
902            #[cfg(feature = "perf-quic-listener-metrics")]
903            self.measure_complete_handshake_time();
904
905            match send_res {
906                Ok(n) =>
907                    if n < self.write_state.bytes_written {
908                        self.metrics
909                            .write_errors(labels::QuicWriteError::Partial)
910                            .inc();
911                    },
912
913                Err(_) => {
914                    self.metrics.write_errors(labels::QuicWriteError::Err).inc();
915                },
916            }
917        }
918    }
919
920    /// The deadline before which the handshake must complete, if it hasn't
921    /// completed yet.
922    fn handshake_deadline(&self, qconn: &QuicheConnection) -> Option<Instant> {
923        if qconn.is_established() {
924            return None;
925        }
926
927        self.handshake_info.deadline()
928    }
929
930    /// Closes the connection if the handshake didn't complete before its
931    /// deadline.
932    fn enforce_handshake_deadline(
933        &self, qconn: &mut QuicheConnection,
934    ) -> QuicResult<()> {
935        if !qconn.is_established() && self.handshake_info.is_expired() {
936            let err = quiche::WireErrorCode::ApplicationError as u64;
937            let _ = qconn.close(false, err, &[]);
938            return Err(HandshakeError::Timeout.into());
939        }
940
941        Ok(())
942    }
943
944    /// Process the incoming packet
945    fn process_incoming(
946        &mut self, qconn: &mut QuicheConnection, mut pkt: Incoming,
947    ) -> QuicResult<()> {
948        // Checked for every packet, so that a peer flooding packets can't keep
949        // the worker busy past the handshake deadline.
950        self.enforce_handshake_deadline(qconn)?;
951
952        let recv_info = quiche::RecvInfo {
953            from: pkt.peer_addr,
954            to: pkt.local_addr,
955        };
956
957        if let Some(gro) = pkt.gro {
958            for dgram in pkt.buf.chunks_mut(gro as usize) {
959                qconn.recv(dgram, recv_info)?;
960            }
961        } else {
962            qconn.recv(&mut pkt.buf, recv_info)?;
963        }
964
965        Ok(())
966    }
967
968    // Process application data after establishment. Before then, a BoringSSL
969    // wakeup might require quiche to send handshake packets.
970    //
971    // TODO(erittenhouse): Decouple `wait_for_data` from the application.
972    // `wait_for_quiche` depends on IOW methods, preventing a default
973    // `ConnectionStage` implementation.
974    //
975    // # Cancel safety
976    //
977    // This future is polled as an arm of the `select!` in `Self::work_loop`, so
978    // it must be cancel-safe. Another arm may complete first and drop it at any
979    // `.await`. `ApplicationOverQuic::wait_for_data` is also cancel-safe, and
980    // the handshake branch retains only its local `send_buf` across `.await`.
981    // Cancellation returns or frees that buffer. The next poll gathers its
982    // bytes again. Preserve this property when modifying the function.
983    async fn wait_for_data_or_handshake<A: ApplicationOverQuic>(
984        &mut self, qconn: &mut QuicheConnection, quic_application: &mut A,
985    ) -> QuicResult<WaitForDataOrHandshakeDirective> {
986        if quic_application.should_act() {
987            // Poll the application to make progress.
988            //
989            // Once the connection has been established (i.e. the handshake is
990            // complete), we only poll the application.
991            //
992            // The exception is 0-RTT in TLS 1.3, where the full handshake is
993            // still in progress but we have 0-RTT keys to process early data.
994            // This means TLS callbacks might only be polled on the next timeout
995            // or when a packet is received from the peer.
996            quic_application.wait_for_data(qconn).await?;
997            Ok(WaitForDataOrHandshakeDirective::Noop)
998        } else {
999            // Poll quiche to make progress on handshake callbacks, gathering
1000            // any handshake packets into an on-demand buffer that the caller
1001            // flushes. `wait_for_quiche()` returns it only after generating a
1002            // packet, so pending handshake waits do not retain a buffer.
1003            let send_buf = self.wait_for_quiche(qconn).await?;
1004            Ok(WaitForDataOrHandshakeDirective::Flush(send_buf))
1005        }
1006    }
1007
1008    /// Check if Quiche has any packets to send
1009    ///
1010    /// If yes: fills buffer and updates self.write_state.bytes_written
1011    /// If no: Poll::Pending
1012    ///
1013    /// # Example
1014    ///
1015    /// This function can be used, for example, to drive an asynchronous TLS
1016    /// handshake. Each call to `gather_data_from_quiche_conn` attempts to
1017    /// progress the handshake via a call to `quiche::Connection.send()` -
1018    /// once one of the `gather_data_from_quiche_conn()` calls writes to the
1019    /// send buffer, we signal to the caller which has to take care of flushing
1020    ///
1021    /// # Cancel safety
1022    ///
1023    /// This future is awaited (indirectly) as an arm of the `select!` in
1024    /// [`Self::work_loop`], so it MUST be cancel safe. The `poll_fn` below
1025    /// holds no state across polls other than what lives in `self.write_state`,
1026    /// so dropping the future between polls loses nothing: the next call simply
1027    /// re-gathers. Take care to preserve this property when modifying it.
1028    async fn wait_for_quiche(
1029        &mut self, qconn: &mut QuicheConnection,
1030    ) -> QuicResult<TransientSendBuf> {
1031        let send_buf = std::future::poll_fn(|_| {
1032            // Allocate inside this closure so a pending poll immediately
1033            // returns its buffer to the pool instead of retaining it across
1034            // the select! wait.
1035            let mut send_buf =
1036                TransientSendBuf::acquire(self.cfg.pool_send_buffer);
1037
1038            match self.gather_data_from_quiche_conn(
1039                qconn,
1040                send_buf.as_mut(),
1041                true,
1042            ) {
1043                Ok(bytes_written) => {
1044                    // Do not call `gather()` twice without an intervening
1045                    // `flush()`. Consecutive calls may overwrite data or delay
1046                    // handshake completion.
1047                    if bytes_written == 0 && self.write_state.bytes_written == 0 {
1048                        Poll::Pending
1049                    } else {
1050                        Poll::Ready(Ok(send_buf))
1051                    }
1052                },
1053                _ => Poll::Ready(Err(quiche::Error::TlsFail)),
1054            }
1055        })
1056        .await?;
1057        Ok(send_buf)
1058    }
1059}
1060
1061/// Whether caller of [`wait_for_data_or_handshake`] is required to
1062/// call [`flush_buffer_to_socket`].
1063///
1064/// `Flush` carries the on-demand buffer the handshake data was gathered into so
1065/// the caller can flush it and then return it to the pool or drop it.
1066#[must_use]
1067enum WaitForDataOrHandshakeDirective {
1068    Noop,
1069    Flush(TransientSendBuf),
1070}
1071
1072pub struct Running<Tx, M, A> {
1073    pub(crate) params: IoWorkerParams<Tx, M>,
1074    pub(crate) context: ConnectionStageContext<A>,
1075    /// See [`QuicConnectionParams::quiche_conn`].
1076    pub(crate) qconn: Box<QuicheConnection>,
1077}
1078
1079impl<Tx, M, A> Running<Tx, M, A> {
1080    pub fn ssl(&mut self) -> &mut SslRef {
1081        // Deref to pick `Connection::as_mut` over `Box::as_mut`.
1082        (*self.qconn).as_mut()
1083    }
1084}
1085
1086pub(crate) struct Closing<Tx, M, A> {
1087    pub(crate) params: IoWorkerParams<Tx, M>,
1088    pub(crate) context: ConnectionStageContext<A>,
1089    pub(crate) work_loop_result: QuicResult<()>,
1090    /// See [`QuicConnectionParams::quiche_conn`].
1091    pub(crate) qconn: Box<QuicheConnection>,
1092}
1093
1094pub enum RunningOrClosing<Tx, M, A> {
1095    Running(Running<Tx, M, A>),
1096    Closing(Closing<Tx, M, A>),
1097}
1098
1099impl<Tx, M> IoWorker<Tx, M, Handshake>
1100where
1101    Tx: DatagramSocketSend + Send,
1102    M: Metrics,
1103{
1104    pub(crate) async fn run<A>(
1105        mut self, mut qconn: Box<QuicheConnection>,
1106        mut ctx: ConnectionStageContext<A>,
1107    ) -> RunningOrClosing<Tx, M, A>
1108    where
1109        A: ApplicationOverQuic,
1110    {
1111        // The `ex_data` waker must remain stable for this task. Moving a future
1112        // with an async callback to another task leaves a stale waker that
1113        // wakes the wrong task.
1114        std::future::poll_fn(|cx| {
1115            // Deref to pick `Connection::as_mut` over `Box::as_mut`.
1116            let ssl = (*qconn).as_mut();
1117            ssl.set_task_waker(Some(cx.waker().clone()));
1118
1119            Poll::Ready(())
1120        })
1121        .await;
1122
1123        #[cfg(target_os = "linux")]
1124        if let Some(incoming) = ctx.in_pkt.as_mut() {
1125            self.audit_log_stats
1126                .set_initial_so_mark_data(incoming.so_mark_data.take());
1127        }
1128
1129        let mut work_loop_result = self.work_loop(&mut qconn, &mut ctx).await;
1130        notify_path_events(ctx.connection_hook.as_deref(), &mut qconn);
1131        if work_loop_result.is_ok() && qconn.is_closed() {
1132            work_loop_result = Err(HandshakeError::ConnectionClosed.into());
1133        }
1134
1135        if let Err(err) = &work_loop_result {
1136            self.metrics.failed_handshakes(err.into()).inc();
1137
1138            return RunningOrClosing::Closing(Closing {
1139                params: self.into(),
1140                context: ctx,
1141                work_loop_result,
1142                qconn,
1143            });
1144        };
1145
1146        let on_conn_established_result =
1147            self.on_conn_established(&mut qconn, &mut ctx);
1148        notify_path_events(ctx.connection_hook.as_deref(), &mut qconn);
1149
1150        match on_conn_established_result {
1151            Ok(()) => RunningOrClosing::Running(Running {
1152                params: self.into(),
1153                context: ctx,
1154                qconn,
1155            }),
1156            Err(e) => {
1157                foundations::telemetry::log::warn!(
1158                    "Handshake stage on_connection_established failed"; "error"=>%e
1159                );
1160
1161                RunningOrClosing::Closing(Closing {
1162                    params: self.into(),
1163                    context: ctx,
1164                    work_loop_result,
1165                    qconn,
1166                })
1167            },
1168        }
1169    }
1170
1171    fn on_conn_established<A: ApplicationOverQuic>(
1172        &mut self, qconn: &mut QuicheConnection,
1173        ctx: &mut ConnectionStageContext<A>,
1174    ) -> QuicResult<()> {
1175        // Only calculate the QUIC handshake duration and call the driver's
1176        // on_conn_established hook if this is the first time
1177        // is_established == true.
1178        if self.audit_log_stats.transport_handshake_duration_us() == -1 {
1179            self.handshake_info.set_elapsed();
1180            let handshake_info = &self.handshake_info;
1181
1182            self.audit_log_stats
1183                .set_transport_handshake_duration(handshake_info.elapsed());
1184
1185            ctx.application.on_conn_established(qconn, handshake_info)?;
1186        }
1187
1188        if let Some(cid) = self.conn_stage.pending_cid.take() {
1189            ctx.incoming_pkt_receiver.unmap_cid(&cid);
1190        }
1191
1192        Ok(())
1193    }
1194}
1195
1196impl<Tx, M, S> From<IoWorker<Tx, M, S>> for IoWorkerParams<Tx, M> {
1197    fn from(value: IoWorker<Tx, M, S>) -> Self {
1198        Self {
1199            socket: value.socket,
1200            shutdown_tx: value.shutdown_tx,
1201            cfg: value.cfg,
1202            audit_log_stats: value.audit_log_stats,
1203            write_state: value.write_state,
1204            dscp_handle: value.dscp_handle,
1205            cid_generator: value.cid_generator,
1206            #[cfg(feature = "perf-quic-listener-metrics")]
1207            init_rx_time: value.init_rx_time,
1208            metrics: value.metrics,
1209            handshake_info: value.handshake_info,
1210            active_conn_guard: value.active_conn_guard,
1211        }
1212    }
1213}
1214
1215impl<Tx, M> IoWorker<Tx, M, RunningApplication>
1216where
1217    Tx: DatagramSocketSend + Send,
1218    M: Metrics,
1219{
1220    pub(crate) async fn run<A: ApplicationOverQuic>(
1221        mut self, mut qconn: Box<QuicheConnection>,
1222        mut ctx: ConnectionStageContext<A>,
1223    ) -> Closing<Tx, M, A> {
1224        // With 0-RTT early data, the application may be resumed after the
1225        // handshake deadline, in which case no data must be passed to it.
1226        let mut work_loop_result = self.enforce_handshake_deadline(&mut qconn);
1227
1228        if work_loop_result.is_ok() {
1229            // Perform a single call to process_reads()/process_writes(),
1230            // unconditionally, to ensure that any application data (e.g.
1231            // STREAM frames or datagrams) processed by the Handshake
1232            // stage are properly passed to the application.
1233            work_loop_result =
1234                self.conn_stage.on_read(true, &mut qconn, &mut ctx);
1235            notify_path_events(ctx.connection_hook.as_deref(), &mut qconn);
1236        }
1237
1238        if work_loop_result.is_ok() {
1239            work_loop_result = self.work_loop(&mut qconn, &mut ctx).await;
1240            notify_path_events(ctx.connection_hook.as_deref(), &mut qconn);
1241        }
1242
1243        // Only connections started with 0-RTT early data can get here before
1244        // the handshake completes, in which case this is a failed handshake,
1245        // as in the Handshake stage.
1246        if !qconn.is_established() {
1247            let reason = match &work_loop_result {
1248                Err(err) => err.into(),
1249                Ok(()) => labels::HandshakeError::Disconnect,
1250            };
1251
1252            self.metrics.failed_handshakes(reason).inc();
1253        }
1254
1255        Closing {
1256            params: self.into(),
1257            context: ctx,
1258            work_loop_result,
1259            qconn,
1260        }
1261    }
1262}
1263
1264impl<Tx, M> IoWorker<Tx, M, Close>
1265where
1266    Tx: DatagramSocketSend + Send,
1267    M: Metrics,
1268{
1269    pub(crate) async fn close<A: ApplicationOverQuic>(
1270        mut self, qconn: &mut QuicheConnection,
1271        ctx: &mut ConnectionStageContext<A>,
1272    ) {
1273        if self.conn_stage.work_loop_result.is_ok() &&
1274            self.bw_estimator.max_bandwidth > 0
1275        {
1276            let metrics = &self.metrics;
1277
1278            metrics
1279                .max_bandwidth_mbps()
1280                .observe(self.bw_estimator.max_bandwidth as f64 * 1e-6);
1281
1282            metrics
1283                .max_loss_pct()
1284                .observe(self.bw_estimator.max_loss_pct as f64 * 100.);
1285        }
1286
1287        if ctx.application.should_act() {
1288            ctx.application.on_conn_close(
1289                qconn,
1290                &self.metrics,
1291                &self.conn_stage.work_loop_result,
1292            );
1293            notify_path_events(ctx.connection_hook.as_deref(), qconn);
1294        }
1295
1296        // TODO: this assumes that the tidy_up operation can be completed in one
1297        // send (ignoring flow/congestion control constraints). We should
1298        // guarantee that it gets sent by doublechecking the
1299        // gathered/flushed byte totals and retry if they don't match.
1300        //
1301        // This runs once per connection at close and sends a single
1302        // CONNECTION_CLOSE datagram, so acquire a buffer only for this send.
1303        let mut send_buf = TransientSendBuf::acquire(self.cfg.pool_send_buffer);
1304        let _ =
1305            self.gather_data_from_quiche_conn(qconn, send_buf.as_mut(), false);
1306        self.flush_buffer_to_socket(send_buf.as_ref()).await;
1307
1308        *ctx.stats.lock().unwrap() = QuicConnectionStats::from_conn(qconn);
1309
1310        if let Some(err) = qconn.peer_error() {
1311            if err.is_app {
1312                self.audit_log_stats
1313                    .set_recvd_conn_close_application_error_code(
1314                        err.error_code as _,
1315                    );
1316            } else {
1317                self.audit_log_stats
1318                    .set_recvd_conn_close_transport_error_code(
1319                        err.error_code as _,
1320                    );
1321            }
1322        }
1323
1324        if let Some(err) = qconn.local_error() {
1325            if err.is_app {
1326                self.audit_log_stats
1327                    .set_sent_conn_close_application_error_code(
1328                        err.error_code as _,
1329                    );
1330            } else {
1331                self.audit_log_stats
1332                    .set_sent_conn_close_transport_error_code(
1333                        err.error_code as _,
1334                    );
1335            }
1336        }
1337
1338        self.close_connection(qconn, &mut ctx.incoming_pkt_receiver);
1339
1340        if let Err(work_loop_error) = self.conn_stage.work_loop_result {
1341            self.audit_log_stats
1342                .set_connection_close_reason(work_loop_error);
1343        }
1344    }
1345
1346    fn close_connection(
1347        &mut self, qconn: &mut QuicheConnection,
1348        incoming_pkt_receiver: &mut IncomingPacketReceiver,
1349    ) {
1350        while let Some(retired_cid) = qconn.retired_scid_next() {
1351            incoming_pkt_receiver.unmap_cid(&retired_cid);
1352        }
1353        for cid in qconn.source_ids() {
1354            incoming_pkt_receiver.unmap_cid(cid);
1355        }
1356    }
1357}
1358
1359/// Returns the minimum of `v1` and `v2`, ignoring `None`s.
1360fn min_of_some<T: Ord>(v1: Option<T>, v2: Option<T>) -> Option<T> {
1361    match (v1, v2) {
1362        (Some(a), Some(b)) => Some(a.min(b)),
1363        (Some(v), _) | (_, Some(v)) => Some(v),
1364        (None, None) => None,
1365    }
1366}
1367
1368/// A Token which increment the skipped_mid_handshake_flush_count metric on
1369/// `Drop` unless it is marked complete.
1370struct TrackMidHandshakeFlush<M: Metrics> {
1371    complete: bool,
1372    metrics: M,
1373}
1374
1375impl<M: Metrics> TrackMidHandshakeFlush<M> {
1376    fn new(metrics: M) -> Self {
1377        Self {
1378            complete: false,
1379            metrics,
1380        }
1381    }
1382
1383    fn mark_complete(&mut self) {
1384        self.complete = true;
1385    }
1386}
1387
1388impl<M: Metrics> Drop for TrackMidHandshakeFlush<M> {
1389    fn drop(&mut self) {
1390        if !self.complete {
1391            self.metrics.skipped_mid_handshake_flush_count().inc();
1392        }
1393    }
1394}
1395
1396fn random_u128() -> u128 {
1397    let mut buf = [0; 16];
1398    boring::rand::rand_bytes(&mut buf).expect("boring's RAND_bytes never fails");
1399    u128::from_ne_bytes(buf)
1400}
1401
1402#[cfg(test)]
1403mod pooled_send_buf_tests {
1404    use super::*;
1405
1406    // Each pool test runs on a freshly spawned thread so the thread-local
1407    // `SEND_BUF_POOL` starts empty (const-initialized) and cannot interfere
1408    // with other tests sharing the harness's worker threads.
1409
1410    #[test]
1411    fn caps_retained_buffers() {
1412        std::thread::spawn(|| {
1413            // Acquire more than the cap at once (all misses, so all fresh
1414            // allocations), then drop them. Only `SEND_BUF_POOL_CAP` may be
1415            // parked; the remainder are freed.
1416            let bufs: Vec<PooledSendBuf> = (0..SEND_BUF_POOL_CAP + 4)
1417                .map(|_| PooledSendBuf::acquire())
1418                .collect();
1419            drop(bufs);
1420
1421            let retained = SEND_BUF_POOL.with(|pool| pool.borrow().len());
1422            assert_eq!(retained, SEND_BUF_POOL_CAP);
1423        })
1424        .join()
1425        .unwrap();
1426    }
1427
1428    #[test]
1429    fn reuses_a_returned_buffer() {
1430        std::thread::spawn(|| {
1431            let first_ptr = {
1432                let buf = PooledSendBuf::acquire();
1433                assert_eq!(buf.len(), SEND_BUFFER_SIZE);
1434                buf.as_ptr()
1435            }; // returned to the pool here
1436
1437            let reused = PooledSendBuf::acquire();
1438            assert_eq!(
1439                reused.as_ptr(),
1440                first_ptr,
1441                "acquire should hand back the pooled allocation"
1442            );
1443        })
1444        .join()
1445        .unwrap();
1446    }
1447
1448    #[test]
1449    fn returns_to_the_dropping_thread() {
1450        // Acquire on one thread, drop on another: the buffer lands in the
1451        // dropping thread's pool (work-stealing migration across `.await` is
1452        // benign).
1453        let buf = std::thread::spawn(PooledSendBuf::acquire).join().unwrap();
1454
1455        std::thread::spawn(move || {
1456            assert_eq!(SEND_BUF_POOL.with(|pool| pool.borrow().len()), 0);
1457            drop(buf);
1458            assert_eq!(SEND_BUF_POOL.with(|pool| pool.borrow().len()), 1);
1459        })
1460        .join()
1461        .unwrap();
1462    }
1463}