Skip to main content

dynamo_runtime/pipeline/network/
quic_response.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Fixed-lane QUIC transport for streaming worker responses.
5//!
6//! A worker keeps a fixed connection bundle to a frontend and distributes a
7//! fixed set of long-lived bidirectional streams (lanes) across it. Logical
8//! response frames are request-hashed to a lane once, queued in a bounded
9//! Tokio channel, and written in batches by the lane's sole writer task.
10
11use std::{
12    collections::{HashMap, VecDeque},
13    fmt,
14    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket},
15    sync::{
16        Arc, OnceLock,
17        atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
18    },
19    time::Duration,
20};
21
22use anyhow::{Context as _, Result, anyhow, bail};
23use arc_swap::ArcSwapOption;
24use bytes::{BufMut, Bytes, BytesMut};
25use crossbeam_queue::SegQueue;
26use dashmap::DashMap;
27use parking_lot::Mutex;
28use prometheus::IntCounter;
29use quinn::crypto::rustls::{QuicClientConfig, QuicServerConfig};
30use rustls::{
31    DigitallySignedStruct, SignatureScheme,
32    client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
33    pki_types::{CertificateDer, PrivatePkcs8KeyDer, ServerName, UnixTime},
34};
35use serde::{Deserialize, Serialize};
36use sha2::{Digest, Sha256};
37use socket2::{Domain, Protocol, Socket, Type};
38use tokio::{
39    io::{AsyncRead, AsyncReadExt, BufReader},
40    sync::{Notify, Semaphore, mpsc, oneshot},
41    time::{Instant, sleep_until},
42};
43use tokio_util::sync::CancellationToken;
44use uuid::Uuid;
45use xxhash_rust::xxh3::xxh3_64;
46
47use super::{
48    ConnectionInfo, RegisteredStream, ResponseStreamPrologue, StreamPrologueError, StreamReceiver,
49    tombstones::InstanceTombstones,
50};
51use crate::{
52    config::environment_names::quic_response, discovery::EndpointInstanceId,
53    engine::AsyncEngineContext, pipeline::PipelineError,
54};
55
56pub const TRANSPORT_NAME: &str = "quic-response";
57const PROTOCOL_VERSION: u8 = 3;
58const ALPN: &[u8] = b"dynamo-response-v2";
59const BULK_CONNECTIONS: usize = 8;
60const BULK_LANES: usize = 8;
61const PRIORITY_CONNECTIONS: usize = 1;
62const LANE_QUEUE_CAPACITY: usize = 512;
63// Bulk writers can spend tens of milliseconds waiting for Quinn to accept a
64// large batch. Keep enough bounded slack to absorb those stalls without
65// parking every response task on the lane semaphore. Priority traffic stays
66// on the smaller queue because it never carries the long token stream.
67const BULK_LANE_QUEUE_CAPACITY: usize = 4_096;
68const MAX_BATCH_FRAMES: usize = 512;
69const DEFAULT_BATCH_INTERVAL_US: u64 = 5_000;
70const MAX_BATCH_INTERVAL_US: u64 = 100_000;
71const FRAME_HEADER_LEN: usize = 1 + 16 + 4;
72// A writer batch can contain hundreds of small response frames. Buffer reads
73// at the receiver so parsing those frames does not poll Quinn once per header
74// and payload and exhaust Tokio's cooperative task budget.
75const RECEIVE_BUFFER_CAPACITY: usize = 256 * 1024;
76const READ_BUDGET_FRAMES: usize = 16;
77const READ_BUDGET_BYTES: usize = 4 * 1024;
78// A single frontend UDP socket is limited by the host receive-buffer ceiling.
79// Reuse-port endpoints preserve one advertised address while spreading QUIC
80// connections and receive queues across several sockets.
81#[cfg(target_os = "linux")]
82const SERVER_ENDPOINTS: usize = 32;
83#[cfg(not(target_os = "linux"))]
84const SERVER_ENDPOINTS: usize = 1;
85const MAX_FRAME_PAYLOAD: usize = 32 * 1024 * 1024;
86const RESPONSE_BUFFER_CAPACITY: usize = 16_384;
87const MAX_RESPONSE_BUFFER_CAPACITY: usize = 65_536;
88const MAX_DEFERRED_RESPONSE_FRAMES: usize = 1_024;
89const MAX_DEFERRED_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
90const CLOSE_CODE_INVARIANT: quinn::VarInt = quinn::VarInt::from_u32(1);
91// Pool keys include the Tokio runtime ID, so entries of stopped runtimes and
92// failed connects are pruned at least this often while the pool is in use.
93const CLIENT_POOL_PRUNE_INTERVAL: Duration = Duration::from_secs(1);
94
95#[derive(Debug, Clone, Copy)]
96pub struct QuicResponseConfig {
97    pub batch_interval: Duration,
98    pub response_buffer_capacity: usize,
99}
100
101impl QuicResponseConfig {
102    pub fn from_env() -> Result<Self, PipelineError> {
103        let interval_us = parse_env_range(
104            quic_response::DYN_QUIC_RESPONSE_BATCH_INTERVAL_US,
105            DEFAULT_BATCH_INTERVAL_US,
106            0,
107            MAX_BATCH_INTERVAL_US,
108        )?;
109        let response_buffer_capacity = parse_env_range(
110            quic_response::DYN_QUIC_RESPONSE_BUFFER_CAPACITY,
111            RESPONSE_BUFFER_CAPACITY,
112            1,
113            MAX_RESPONSE_BUFFER_CAPACITY,
114        )?;
115        Ok(Self {
116            batch_interval: Duration::from_micros(interval_us),
117            response_buffer_capacity,
118        })
119    }
120}
121
122fn parse_env_range<T>(name: &str, default: T, min: T, max: T) -> Result<T, PipelineError>
123where
124    T: Copy + std::str::FromStr + PartialOrd + fmt::Display,
125{
126    let Some(raw) = std::env::var(name).ok().filter(|value| !value.is_empty()) else {
127        return Ok(default);
128    };
129    let value = raw
130        .parse::<T>()
131        .map_err(|_| PipelineError::Generic(format!("invalid {name}: '{raw}' is not a number")))?;
132    if value < min || value > max {
133        return Err(PipelineError::Generic(format!(
134            "invalid {name}: {value} is outside {min}..={max}"
135        )));
136    }
137    Ok(value)
138}
139
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct QuicResponseConnectionInfo {
142    version: u8,
143    address: String,
144    frontend_id: String,
145    registration_id: Uuid,
146    request_id: String,
147    certificate_sha256: String,
148}
149
150impl From<QuicResponseConnectionInfo> for ConnectionInfo {
151    fn from(value: QuicResponseConnectionInfo) -> Self {
152        Self {
153            transport: TRANSPORT_NAME.to_string(),
154            info: serde_json::to_string(&value).expect("QUIC connection info must serialize"),
155        }
156    }
157}
158
159impl TryFrom<ConnectionInfo> for QuicResponseConnectionInfo {
160    type Error = anyhow::Error;
161
162    fn try_from(value: ConnectionInfo) -> Result<Self> {
163        if value.transport != TRANSPORT_NAME {
164            bail!(
165                "expected {TRANSPORT_NAME} connection info, got {}",
166                value.transport
167            );
168        }
169        let info: Self = serde_json::from_str(&value.info)?;
170        if info.version != PROTOCOL_VERSION {
171            bail!(
172                "unsupported QUIC response protocol version {} (expected {})",
173                info.version,
174                PROTOCOL_VERSION
175            );
176        }
177        Ok(info)
178    }
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182#[repr(u8)]
183enum FrameKind {
184    Prologue = 1,
185    Data = 2,
186    /// Terminal pre-stream failure. Payload layout is [`QUIC_TYPED_ERROR_KIND`].
187    Error = 3,
188    End = 4,
189    Stop = 5,
190    Kill = 6,
191    Reset = 7,
192    FirstData = 8,
193    PriorityEnd = 9,
194    Bundle = 10,
195    Register = 11,
196    Registered = 12,
197}
198
199impl TryFrom<u8> for FrameKind {
200    type Error = anyhow::Error;
201
202    fn try_from(value: u8) -> Result<Self> {
203        match value {
204            1 => Ok(Self::Prologue),
205            2 => Ok(Self::Data),
206            3 => Ok(Self::Error),
207            4 => Ok(Self::End),
208            5 => Ok(Self::Stop),
209            6 => Ok(Self::Kill),
210            7 => Ok(Self::Reset),
211            8 => Ok(Self::FirstData),
212            9 => Ok(Self::PriorityEnd),
213            10 => Ok(Self::Bundle),
214            11 => Ok(Self::Register),
215            12 => Ok(Self::Registered),
216            _ => bail!("unknown QUIC response frame kind {value}"),
217        }
218    }
219}
220
221#[derive(Debug)]
222struct Frame {
223    kind: FrameKind,
224    registration_id: Uuid,
225    payload: Bytes,
226}
227
228impl Frame {
229    fn new(kind: FrameKind, registration_id: Uuid, payload: Bytes) -> Self {
230        Self {
231            kind,
232            registration_id,
233            payload,
234        }
235    }
236
237    fn header(&self) -> Bytes {
238        let mut header = BytesMut::with_capacity(FRAME_HEADER_LEN);
239        header.put_u8(self.kind as u8);
240        header.extend_from_slice(self.registration_id.as_bytes());
241        header.put_u32(self.payload.len() as u32);
242        header.freeze()
243    }
244}
245
246/// Typed [`FrameKind::Error`] payloads are JSON tagged with this `kind`.
247///
248/// Untyped errors stay raw UTF-8 so a mixed-version frontend still sees the
249/// worker's text. A current frontend accepts only this discriminant and
250/// recovers [`ResponseStreamPrologue`]. An older frontend reads the payload as
251/// UTF-8 and treats the object as the message. Untagged JSON, including a
252/// decoy `{"error","code"}` object, stays that message. The protocol version
253/// stays 3 because those bytes are already valid UTF-8 for an old decoder.
254const QUIC_TYPED_ERROR_KIND: &str = "dynamo.quic.typed_error";
255
256/// JSON object carrying [`QUIC_TYPED_ERROR_KIND`] and a [`ResponseStreamPrologue`].
257#[derive(Serialize, Deserialize)]
258struct QuicTypedErrorWire {
259    kind: String,
260    #[serde(flatten)]
261    prologue: ResponseStreamPrologue,
262}
263
264/// Encode a pre-stream error for [`FrameKind::Error`].
265fn encode_error_payload(error: StreamPrologueError) -> Bytes {
266    let Some(typed_error) = error.typed_error else {
267        return Bytes::from(error.message);
268    };
269    let wire = QuicTypedErrorWire {
270        kind: QUIC_TYPED_ERROR_KIND.to_string(),
271        prologue: ResponseStreamPrologue {
272            error: Some(error.message),
273            typed_error: Some(typed_error),
274        },
275    };
276    match serde_json::to_vec(&wire) {
277        Ok(bytes) => Bytes::from(bytes),
278        Err(err) => {
279            tracing::error!(
280                error = %err,
281                "QUIC error prologue did not serialize; sending untyped text"
282            );
283            Bytes::from(wire.prologue.error.unwrap_or_default())
284        }
285    }
286}
287
288/// Decode a [`FrameKind::Error`] payload.
289fn decode_error_payload(payload: &[u8]) -> Result<StreamPrologueError> {
290    if payload.first() == Some(&b'{')
291        && let Ok(wire) = serde_json::from_slice::<QuicTypedErrorWire>(payload)
292        && wire.kind == QUIC_TYPED_ERROR_KIND
293        && let Some(message) = wire.prologue.error
294    {
295        return Ok(StreamPrologueError {
296            message,
297            typed_error: wire.prologue.typed_error,
298        });
299    }
300    let message = String::from_utf8(payload.to_vec())
301        .context("QUIC response terminal error was not UTF-8")?;
302    Ok(StreamPrologueError::from_message(message))
303}
304
305async fn read_frame<R>(recv: &mut R) -> Result<Frame>
306where
307    R: AsyncRead + Unpin,
308{
309    let mut header = [0_u8; FRAME_HEADER_LEN];
310    recv.read_exact(&mut header).await?;
311    let kind = FrameKind::try_from(header[0])?;
312    let registration_id = Uuid::from_slice(&header[1..17])?;
313    let payload_len = u32::from_be_bytes(header[17..21].try_into().unwrap()) as usize;
314    if payload_len > MAX_FRAME_PAYLOAD {
315        bail!("QUIC response frame payload {payload_len} exceeds {MAX_FRAME_PAYLOAD}");
316    }
317    let mut payload = BytesMut::zeroed(payload_len);
318    recv.read_exact(&mut payload).await?;
319    Ok(Frame {
320        kind,
321        registration_id,
322        payload: payload.freeze(),
323    })
324}
325
326struct LaneSender(Arc<LaneQueue>);
327
328struct LaneReceiver(Arc<LaneQueue>);
329
330struct LaneQueue {
331    frames: SegQueue<Frame>,
332    slots: Semaphore,
333    ready: Notify,
334    scheduled: AtomicBool,
335    closed: AtomicBool,
336    senders: AtomicUsize,
337    #[cfg(test)]
338    notifications: AtomicUsize,
339}
340
341#[derive(Debug)]
342enum LaneTrySendError {
343    Closed(Frame),
344    Full(Frame),
345}
346
347impl LaneQueue {
348    fn new(capacity: usize) -> Arc<Self> {
349        Arc::new(Self {
350            frames: SegQueue::new(),
351            slots: Semaphore::new(capacity),
352            ready: Notify::new(),
353            scheduled: AtomicBool::new(false),
354            closed: AtomicBool::new(false),
355            senders: AtomicUsize::new(1),
356            #[cfg(test)]
357            notifications: AtomicUsize::new(0),
358        })
359    }
360
361    fn push_with_permit(
362        &self,
363        frame: Frame,
364        permit: tokio::sync::SemaphorePermit<'_>,
365    ) -> std::result::Result<(), Frame> {
366        if self.closed.load(Ordering::Acquire) {
367            return Err(frame);
368        }
369        self.frames.push(frame);
370        permit.forget();
371        if !self.scheduled.swap(true, Ordering::AcqRel) {
372            #[cfg(test)]
373            self.notifications.fetch_add(1, Ordering::Relaxed);
374            self.ready.notify_one();
375        }
376        Ok(())
377    }
378
379    fn try_send(&self, frame: Frame) -> std::result::Result<(), LaneTrySendError> {
380        let permit = match self.slots.try_acquire() {
381            Ok(permit) => permit,
382            Err(tokio::sync::TryAcquireError::Closed) => {
383                return Err(LaneTrySendError::Closed(frame));
384            }
385            Err(tokio::sync::TryAcquireError::NoPermits) => {
386                return Err(LaneTrySendError::Full(frame));
387            }
388        };
389        self.push_with_permit(frame, permit)
390            .map_err(LaneTrySendError::Closed)
391    }
392
393    async fn send(&self, frame: Frame) -> Result<()> {
394        let permit = self
395            .slots
396            .acquire()
397            .await
398            .map_err(|_| anyhow!("QUIC response lane closed"))?;
399        self.push_with_permit(frame, permit)
400            .map_err(|_| anyhow!("QUIC response lane closed"))
401    }
402
403    fn drain(&self, batch: &mut Vec<Frame>, limit: usize) -> usize {
404        let initial_len = batch.len();
405        while batch.len() - initial_len < limit {
406            let Some(frame) = self.frames.pop() else {
407                break;
408            };
409            batch.push(frame);
410        }
411        let count = batch.len() - initial_len;
412        if count != 0 {
413            self.slots.add_permits(count);
414        }
415        count
416    }
417
418    async fn recv_many(&self, batch: &mut Vec<Frame>, limit: usize) -> usize {
419        loop {
420            let mut notified = Box::pin(self.ready.notified());
421            notified.as_mut().enable();
422            let count = self.drain(batch, limit);
423            if count != 0 {
424                return count;
425            }
426            if self.closed.load(Ordering::Acquire) {
427                return 0;
428            }
429            // Producers suppress notifications while the writer is active. Mark
430            // it idle after observing an empty queue, then recheck to close the
431            // producer/consumer race without a lock.
432            self.scheduled.store(false, Ordering::Release);
433            if !self.frames.is_empty() {
434                self.scheduled.store(true, Ordering::Release);
435                continue;
436            }
437            notified.await;
438        }
439    }
440
441    fn close_sender(&self) {
442        self.closed.store(true, Ordering::Release);
443        self.slots.close();
444        self.ready.notify_waiters();
445    }
446
447    fn close_receiver(&self) {
448        self.closed.store(true, Ordering::Release);
449        let mut discarded = 0;
450        while self.frames.pop().is_some() {
451            discarded += 1;
452        }
453        if discarded != 0 {
454            self.slots.add_permits(discarded);
455        }
456        self.slots.close();
457        self.ready.notify_waiters();
458    }
459}
460
461impl Drop for LaneReceiver {
462    fn drop(&mut self) {
463        self.0.close_receiver();
464    }
465}
466
467impl Clone for LaneSender {
468    fn clone(&self) -> Self {
469        self.0.senders.fetch_add(1, Ordering::Relaxed);
470        Self(self.0.clone())
471    }
472}
473
474impl Drop for LaneSender {
475    fn drop(&mut self) {
476        if self.0.senders.fetch_sub(1, Ordering::AcqRel) == 1 {
477            self.0.close_sender();
478        }
479    }
480}
481
482impl LaneReceiver {
483    async fn recv_many(&mut self, batch: &mut Vec<Frame>, limit: usize) -> usize {
484        self.0.recv_many(batch, limit).await
485    }
486
487    #[cfg(test)]
488    async fn recv(&mut self) -> Option<Frame> {
489        let mut batch = Vec::with_capacity(1);
490        (self.recv_many(&mut batch, 1).await == 1).then(|| batch.pop().unwrap())
491    }
492}
493
494impl LaneSender {
495    fn try_send(&self, frame: Frame) -> std::result::Result<(), LaneTrySendError> {
496        self.0.try_send(frame)
497    }
498
499    async fn send(&self, frame: Frame) -> Result<()> {
500        self.0.send(frame).await
501    }
502}
503
504fn lane_queue(capacity: usize) -> (LaneSender, LaneReceiver) {
505    let queue = LaneQueue::new(capacity);
506    (LaneSender(queue.clone()), LaneReceiver(queue))
507}
508
509/// Fill `batch` with up to `max_batch_frames` frames. The first `recv_many`
510/// waits while idle;
511/// subsequent cancellation-safe `recv_many` calls race the single batch
512/// deadline. A zero interval therefore drains an already-ready burst but does
513/// not intentionally wait for more work.
514async fn receive_batch(
515    receiver: &mut LaneReceiver,
516    batch: &mut Vec<Frame>,
517    interval: Duration,
518    max_batch_frames: usize,
519) -> bool {
520    batch.clear();
521    if receiver.recv_many(batch, max_batch_frames).await == 0 {
522        return false;
523    }
524
525    if interval.is_zero() {
526        return true;
527    }
528    let deadline = Instant::now() + interval;
529    let sleep = sleep_until(deadline);
530    tokio::pin!(sleep);
531    while batch.len() < max_batch_frames {
532        tokio::select! {
533            biased;
534            _ = &mut sleep => break,
535            count = receiver.recv_many(batch, max_batch_frames - batch.len()) => {
536                if count == 0 {
537                    break;
538                }
539            }
540        }
541    }
542    true
543}
544
545const SERVER_STATE_SHARDS: usize = 64;
546
547#[derive(Default)]
548struct RegistrationShard {
549    pending: HashMap<Uuid, PendingResponse>,
550    active: HashMap<Uuid, ActiveResponse>,
551}
552
553#[derive(Default)]
554struct ServerIndexes {
555    registration_instance: HashMap<Uuid, EndpointInstanceId>,
556    instance_registrations: HashMap<EndpointInstanceId, Vec<Uuid>>,
557    removed_instances: InstanceTombstones,
558    connection_bundles: HashMap<usize, Uuid>,
559    bundle_connections: HashMap<Uuid, HashMap<usize, quinn::Connection>>,
560}
561
562struct ServerState {
563    registrations: [Mutex<RegistrationShard>; SERVER_STATE_SHARDS],
564    indexes: Mutex<ServerIndexes>,
565}
566
567impl Default for ServerState {
568    fn default() -> Self {
569        Self {
570            registrations: std::array::from_fn(|_| Mutex::new(RegistrationShard::default())),
571            indexes: Mutex::new(ServerIndexes::default()),
572        }
573    }
574}
575
576impl ServerState {
577    fn registration(&self, registration_id: Uuid) -> &Mutex<RegistrationShard> {
578        &self.registrations[registration_id.as_u128() as usize % SERVER_STATE_SHARDS]
579    }
580}
581
582#[derive(Default)]
583struct DeferredResponse {
584    data: VecDeque<Bytes>,
585    bytes: usize,
586    end: bool,
587}
588
589impl DeferredResponse {
590    fn push(&mut self, payload: Bytes) -> Result<(), Bytes> {
591        let Some(bytes) = self.bytes.checked_add(payload.len()) else {
592            return Err(payload);
593        };
594        if self.data.len() >= MAX_DEFERRED_RESPONSE_FRAMES || bytes > MAX_DEFERRED_RESPONSE_BYTES {
595            return Err(payload);
596        }
597        self.bytes = bytes;
598        self.data.push_back(payload);
599        Ok(())
600    }
601
602    fn take_data(&mut self) -> VecDeque<Bytes> {
603        self.bytes = 0;
604        std::mem::take(&mut self.data)
605    }
606}
607
608struct PendingResponse {
609    context: Arc<dyn AsyncEngineContext>,
610    connection: oneshot::Sender<Result<StreamReceiver, StreamPrologueError>>,
611    bundle_id: Option<Uuid>,
612    deferred: DeferredResponse,
613    monitor_cancel: CancellationToken,
614    monitor_response: Option<oneshot::Sender<mpsc::Sender<Bytes>>>,
615}
616
617struct ActiveResponse {
618    sender: mpsc::Sender<Bytes>,
619    monitor_cancel: CancellationToken,
620    bundle_id: Uuid,
621    priority_ready: bool,
622    priority_draining: bool,
623    deferred: DeferredResponse,
624}
625
626pub struct QuicResponseServer {
627    endpoints: Arc<[quinn::Endpoint]>,
628    advertised_address: SocketAddr,
629    frontend_id: String,
630    certificate_sha256: String,
631    state: Arc<ServerState>,
632    response_buffer_capacity: usize,
633    shutdown: CancellationToken,
634}
635
636impl fmt::Debug for QuicResponseServer {
637    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
638        f.debug_struct("QuicResponseServer")
639            .field("address", &self.advertised_address)
640            .field("frontend_id", &self.frontend_id)
641            .finish_non_exhaustive()
642    }
643}
644
645impl QuicResponseServer {
646    pub fn new(
647        bind_address: SocketAddr,
648        advertised_address: SocketAddr,
649        shutdown: CancellationToken,
650    ) -> Result<Arc<Self>, PipelineError> {
651        Self::new_with_stream_window(bind_address, advertised_address, shutdown, None)
652    }
653
654    fn new_with_stream_window(
655        bind_address: SocketAddr,
656        advertised_address: SocketAddr,
657        shutdown: CancellationToken,
658        stream_receive_window: Option<u32>,
659    ) -> Result<Arc<Self>, PipelineError> {
660        let response_config = QuicResponseConfig::from_env()?;
661        Self::new_with_config(
662            bind_address,
663            advertised_address,
664            shutdown,
665            stream_receive_window,
666            response_config,
667        )
668    }
669
670    fn new_with_config(
671        bind_address: SocketAddr,
672        advertised_address: SocketAddr,
673        shutdown: CancellationToken,
674        stream_receive_window: Option<u32>,
675        response_config: QuicResponseConfig,
676    ) -> Result<Arc<Self>, PipelineError> {
677        let certified =
678            rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).map_err(|error| {
679                PipelineError::Generic(format!("failed generating QUIC certificate: {error}"))
680            })?;
681        let cert_der = CertificateDer::from(certified.cert);
682        let fingerprint = Sha256::digest(cert_der.as_ref());
683        let certificate_sha256 = encode_hex(&fingerprint);
684        let key = PrivatePkcs8KeyDer::from(certified.key_pair.serialize_der());
685
686        let provider = Arc::new(rustls::crypto::ring::default_provider());
687        let mut crypto = rustls::ServerConfig::builder_with_provider(provider)
688            .with_safe_default_protocol_versions()
689            .map_err(|error| {
690                PipelineError::Generic(format!("failed configuring QUIC TLS: {error}"))
691            })?
692            .with_no_client_auth()
693            .with_single_cert(vec![cert_der], key.into())
694            .map_err(|error| {
695                PipelineError::Generic(format!("failed configuring QUIC certificate: {error}"))
696            })?;
697        crypto.alpn_protocols = vec![ALPN.to_vec()];
698
699        let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(
700            QuicServerConfig::try_from(crypto).map_err(|error| {
701                PipelineError::Generic(format!("failed configuring QUIC server: {error}"))
702            })?,
703        ));
704        let transport = Arc::get_mut(&mut server_config.transport)
705            .expect("new QUIC server config has one transport owner");
706        transport.max_concurrent_bidi_streams((BULK_LANES as u32).into());
707        transport.max_concurrent_uni_streams(0_u8.into());
708        transport.keep_alive_interval(Some(Duration::from_secs(5)));
709        if let Some(window) = stream_receive_window {
710            transport.stream_receive_window(quinn::VarInt::from_u32(window));
711        }
712
713        let socket = bind_server_udp(bind_address, false).map_err(|error| {
714            PipelineError::Generic(format!(
715                "failed binding QUIC response server socket on {bind_address}: {error}"
716            ))
717        })?;
718        let bound_address = socket.local_addr().map_err(|error| {
719            PipelineError::Generic(format!(
720                "failed reading QUIC response server socket address: {error}"
721            ))
722        })?;
723        let mut first_socket = Some(socket);
724        let mut endpoints = Vec::with_capacity(SERVER_ENDPOINTS);
725        for index in 0..SERVER_ENDPOINTS {
726            let socket = if index == 0 {
727                first_socket
728                    .take()
729                    .expect("first QUIC response socket exists")
730            } else {
731                bind_server_udp(bound_address, true).map_err(|error| {
732                    PipelineError::Generic(format!(
733                        "failed binding QUIC response reuse-port socket {index} on {bound_address}: {error}"
734                    ))
735                })?
736            };
737            let endpoint = quinn::Endpoint::new(
738                quinn::EndpointConfig::default(),
739                Some(server_config.clone()),
740                socket,
741                Arc::new(quinn::TokioRuntime),
742            )
743            .map_err(|error| {
744                PipelineError::Generic(format!(
745                    "failed creating QUIC response endpoint {index} on {bound_address}: {error}"
746                ))
747            })?;
748            endpoints.push(endpoint);
749        }
750        let endpoints: Arc<[quinn::Endpoint]> = endpoints.into();
751        let advertised_address = if advertised_address.port() == 0 {
752            bound_address
753        } else {
754            advertised_address
755        };
756        let server = Arc::new(Self {
757            endpoints,
758            advertised_address,
759            frontend_id: Uuid::new_v4().to_string(),
760            certificate_sha256,
761            state: Arc::new(ServerState::default()),
762            response_buffer_capacity: response_config.response_buffer_capacity,
763            shutdown: shutdown.child_token(),
764        });
765        Self::spawn_accept_loop(&server);
766        Ok(server)
767    }
768
769    fn spawn_accept_loop(server: &Arc<Self>) {
770        for endpoint in server.endpoints.iter() {
771            let endpoint = endpoint.clone();
772            let state = server.state.clone();
773            let response_buffer_capacity = server.response_buffer_capacity;
774            let shutdown = server.shutdown.clone();
775            tokio::spawn(async move {
776                loop {
777                    tokio::select! {
778                        _ = shutdown.cancelled() => {
779                            endpoint.close(quinn::VarInt::from_u32(0), b"runtime shutdown");
780                            break;
781                        }
782                        incoming = endpoint.accept() => {
783                            let Some(incoming) = incoming else { break };
784                            let state = state.clone();
785                            tokio::spawn(async move {
786                                match incoming.await {
787                                    Ok(connection) => run_server_connection(
788                                        connection,
789                                        state,
790                                        response_buffer_capacity,
791                                    ).await,
792                                    Err(error) => tracing::warn!(%error, "QUIC response handshake failed"),
793                                }
794                            });
795                        }
796                    }
797                }
798            });
799        }
800    }
801
802    pub fn register_response(
803        &self,
804        context: Arc<dyn AsyncEngineContext>,
805    ) -> RegisteredStream<StreamReceiver> {
806        let registration_id = Uuid::new_v4();
807        let request_id = context.id().to_string();
808        let (pending_tx, pending_rx) = oneshot::channel();
809        self.state
810            .registration(registration_id)
811            .lock()
812            .pending
813            .insert(
814                registration_id,
815                PendingResponse {
816                    context,
817                    connection: pending_tx,
818                    bundle_id: None,
819                    deferred: DeferredResponse::default(),
820                    monitor_cancel: CancellationToken::new(),
821                    monitor_response: None,
822                },
823            );
824
825        let connection_info = QuicResponseConnectionInfo {
826            version: PROTOCOL_VERSION,
827            address: self.advertised_address.to_string(),
828            frontend_id: self.frontend_id.clone(),
829            registration_id,
830            request_id,
831            certificate_sha256: self.certificate_sha256.clone(),
832        }
833        .into();
834
835        let state = self.state.clone();
836        RegisteredStream::new(connection_info, pending_rx)
837            .with_registration_id(registration_id)
838            .with_cleanup(move || {
839                remove_registration(&state, registration_id);
840            })
841    }
842
843    pub async fn associate_instance(&self, registration_id: Uuid, id: &EndpointInstanceId) -> bool {
844        let mut indexes = self.state.indexes.lock();
845        if indexes.removed_instances.contains(id) {
846            drop(indexes);
847            remove_registration(&self.state, registration_id);
848            return false;
849        }
850        indexes
851            .registration_instance
852            .insert(registration_id, id.clone());
853        indexes
854            .instance_registrations
855            .entry(id.clone())
856            .or_default()
857            .push(registration_id);
858        true
859    }
860
861    pub async fn cancel_response(&self, registration_id: Uuid) {
862        remove_registration(&self.state, registration_id);
863    }
864
865    pub async fn cancel_instance_streams(&self, id: &EndpointInstanceId) -> usize {
866        let registrations = {
867            let mut indexes = self.state.indexes.lock();
868            indexes.removed_instances.insert(id);
869            let registrations = indexes
870                .instance_registrations
871                .remove(id)
872                .unwrap_or_default();
873            for registration_id in &registrations {
874                indexes.registration_instance.remove(registration_id);
875            }
876            registrations
877        };
878        let count = registrations.len();
879        for registration_id in registrations {
880            remove_registration_data(&self.state, registration_id);
881        }
882        count
883    }
884
885    pub async fn clear_instance_tombstone(&self, id: &EndpointInstanceId) {
886        self.state.indexes.lock().removed_instances.remove(id);
887    }
888}
889
890#[async_trait::async_trait]
891impl super::RegisteredResponsePlane for QuicResponseServer {
892    fn register_stream(
893        self: Arc<Self>,
894        context: Arc<dyn AsyncEngineContext>,
895        _defer_cancellation_until_prologue: bool,
896    ) -> anyhow::Result<RegisteredStream<StreamReceiver>> {
897        Ok(QuicResponseServer::register_response(&self, context))
898    }
899
900    async fn associate_instance(&self, registration_id: Uuid, id: &EndpointInstanceId) -> bool {
901        QuicResponseServer::associate_instance(self, registration_id, id).await
902    }
903
904    async fn cancel_response(&self, registration_id: Uuid) {
905        QuicResponseServer::cancel_response(self, registration_id).await;
906    }
907
908    async fn cancel_instance_streams(&self, id: &EndpointInstanceId) -> usize {
909        QuicResponseServer::cancel_instance_streams(self, id).await
910    }
911
912    async fn clear_instance_tombstone(&self, id: &EndpointInstanceId) {
913        QuicResponseServer::clear_instance_tombstone(self, id).await;
914    }
915}
916
917impl Drop for QuicResponseServer {
918    fn drop(&mut self) {
919        self.shutdown.cancel();
920        for endpoint in self.endpoints.iter() {
921            endpoint.close(quinn::VarInt::from_u32(0), b"response server dropped");
922        }
923    }
924}
925
926fn bind_server_udp(address: SocketAddr, join_reuseport: bool) -> std::io::Result<UdpSocket> {
927    let socket = Socket::new(
928        Domain::for_address(address),
929        Type::DGRAM,
930        Some(Protocol::UDP),
931    )?;
932    #[cfg(target_os = "linux")]
933    if join_reuseport {
934        socket.set_reuse_address(true)?;
935        socket.set_reuse_port(true)?;
936    }
937    socket.set_nonblocking(true)?;
938    socket.bind(&address.into())?;
939    // Bind the first endpoint exclusively so an ephemeral port cannot join an
940    // unrelated server's reuse-port group. Linux permits enabling reuse-port
941    // after that first bind, and the remaining endpoints can then join.
942    #[cfg(target_os = "linux")]
943    if !join_reuseport {
944        socket.set_reuse_address(true)?;
945        socket.set_reuse_port(true)?;
946    }
947    Ok(socket.into())
948}
949
950fn remove_registration_data(state: &ServerState, registration_id: Uuid) {
951    let mut registration = state.registration(registration_id).lock();
952    if let Some(pending) = registration.pending.remove(&registration_id) {
953        pending.monitor_cancel.cancel();
954    }
955    if let Some(active) = registration.active.remove(&registration_id) {
956        active.monitor_cancel.cancel();
957    }
958}
959
960fn remove_registration(state: &ServerState, registration_id: Uuid) {
961    let mut indexes = state.indexes.lock();
962    if let Some(instance) = indexes.registration_instance.remove(&registration_id)
963        && let Some(registrations) = indexes.instance_registrations.get_mut(&instance)
964    {
965        registrations.retain(|candidate| *candidate != registration_id);
966        if registrations.is_empty() {
967            indexes.instance_registrations.remove(&instance);
968        }
969    }
970    drop(indexes);
971    remove_registration_data(state, registration_id);
972}
973
974fn fail_registration(state: &ServerState, registration_id: Uuid, reason: &str) {
975    let mut indexes = state.indexes.lock();
976    if let Some(instance) = indexes.registration_instance.remove(&registration_id)
977        && let Some(registrations) = indexes.instance_registrations.get_mut(&instance)
978    {
979        registrations.retain(|candidate| *candidate != registration_id);
980        if registrations.is_empty() {
981            indexes.instance_registrations.remove(&instance);
982        }
983    }
984    drop(indexes);
985
986    let mut registration = state.registration(registration_id).lock();
987    if let Some(pending) = registration.pending.remove(&registration_id) {
988        pending.monitor_cancel.cancel();
989        let _ = pending.connection.send(Err(reason.into()));
990    }
991    if let Some(active) = registration.active.remove(&registration_id) {
992        active.monitor_cancel.cancel();
993    }
994}
995
996async fn run_server_connection(
997    connection: quinn::Connection,
998    state: Arc<ServerState>,
999    response_buffer_capacity: usize,
1000) {
1001    let connection_id = connection.stable_id();
1002    crate::metrics::quic_response::track_connection(connection.clone());
1003    tracing::debug!(connection_id, remote = %connection.remote_address(), "QUIC response connection established");
1004    loop {
1005        match connection.accept_bi().await {
1006            Ok((send, recv)) => {
1007                let lane_connection = connection.clone();
1008                let lane_state = state.clone();
1009                tokio::spawn(async move {
1010                    let result = run_server_lane(
1011                        send,
1012                        recv,
1013                        lane_connection.clone(),
1014                        lane_state.clone(),
1015                        response_buffer_capacity,
1016                    )
1017                    .await;
1018                    if let Err(error) = result {
1019                        tracing::warn!(connection_id, error = format!("{error:#}"), close_reason = ?lane_connection.close_reason(), "QUIC response lane failed; closing connection");
1020                        fail_server_connection(&lane_state, connection_id);
1021                        // Close explicitly if the lane failed before bundle registration.
1022                        lane_connection
1023                            .close(CLOSE_CODE_INVARIANT, b"response lane invariant failure");
1024                    }
1025                });
1026            }
1027            Err(error) => {
1028                if connection.close_reason().is_none() {
1029                    tracing::warn!(connection_id, %error, "QUIC response connection failed while accepting lane");
1030                }
1031                fail_server_connection(&state, connection_id);
1032                break;
1033            }
1034        }
1035    }
1036}
1037
1038fn register_server_connection_bundle(
1039    state: &ServerState,
1040    connection: quinn::Connection,
1041    bundle_id: Uuid,
1042) -> Result<()> {
1043    let connection_id = connection.stable_id();
1044    let mut indexes = state.indexes.lock();
1045    if let Some(existing) = indexes.connection_bundles.get(&connection_id)
1046        && *existing != bundle_id
1047    {
1048        bail!(
1049            "QUIC response connection {connection_id} changed bundle id from {existing} to {bundle_id}"
1050        );
1051    }
1052    indexes.connection_bundles.insert(connection_id, bundle_id);
1053    indexes
1054        .bundle_connections
1055        .entry(bundle_id)
1056        .or_default()
1057        .insert(connection_id, connection);
1058    Ok(())
1059}
1060
1061fn fail_server_connection(state: &ServerState, connection_id: usize) {
1062    let (bundle_id, connections) = {
1063        let mut indexes = state.indexes.lock();
1064        let Some(bundle_id) = indexes.connection_bundles.remove(&connection_id) else {
1065            return;
1066        };
1067        indexes
1068            .connection_bundles
1069            .retain(|_, candidate| *candidate != bundle_id);
1070        let connections = indexes
1071            .bundle_connections
1072            .remove(&bundle_id)
1073            .unwrap_or_default()
1074            .into_values()
1075            .collect::<Vec<_>>();
1076        (bundle_id, connections)
1077    };
1078    crate::metrics::quic_response::record_bundle_failure("frontend");
1079
1080    for connection in connections {
1081        connection.close(
1082            CLOSE_CODE_INVARIANT,
1083            b"response connection bundle invariant failure",
1084        );
1085    }
1086
1087    let doomed = state
1088        .registrations
1089        .iter()
1090        .flat_map(|shard| {
1091            let shard = shard.lock();
1092            shard
1093                .pending
1094                .iter()
1095                .filter_map(|(registration_id, pending)| {
1096                    (pending.bundle_id == Some(bundle_id)).then_some(*registration_id)
1097                })
1098                .chain(shard.active.iter().filter_map(|(registration_id, active)| {
1099                    (active.bundle_id == bundle_id).then_some(*registration_id)
1100                }))
1101                .collect::<Vec<_>>()
1102        })
1103        .collect::<Vec<_>>();
1104    for registration_id in doomed {
1105        fail_registration(
1106            state,
1107            registration_id,
1108            "QUIC response connection bundle failed before stream establishment",
1109        );
1110    }
1111}
1112
1113async fn run_server_lane(
1114    mut send: quinn::SendStream,
1115    recv: quinn::RecvStream,
1116    connection: quinn::Connection,
1117    state: Arc<ServerState>,
1118    response_buffer_capacity: usize,
1119) -> Result<()> {
1120    let mut recv = BufReader::with_capacity(RECEIVE_BUFFER_CAPACITY, recv);
1121    let bundle = read_frame(&mut recv).await?;
1122    if bundle.kind != FrameKind::Bundle || !bundle.payload.is_empty() {
1123        bail!("QUIC response lane did not start with a bundle frame");
1124    }
1125    let bundle_id = bundle.registration_id;
1126    register_server_connection_bundle(&state, connection, bundle_id)?;
1127
1128    let (control_tx, mut control_rx) = mpsc::channel::<Frame>(RESPONSE_BUFFER_CAPACITY);
1129    let writer = async move {
1130        while let Some(frame) = control_rx.recv().await {
1131            let mut chunks = [frame.header(), frame.payload];
1132            send.write_all_chunks(&mut chunks).await?;
1133        }
1134        Ok::<(), quinn::WriteError>(())
1135    };
1136
1137    let reader = async {
1138        let mut frames = READ_BUDGET_FRAMES;
1139        let mut bytes = READ_BUDGET_BYTES;
1140        loop {
1141            // Charge a bounded batch of small frames to the task budget.
1142            // Charging every token frame can leave already-received responses
1143            // queued behind repeated scheduler waits. Keep both bounds so
1144            // large frames still yield and the reverse-control writer runs.
1145            if frames >= READ_BUDGET_FRAMES || bytes >= READ_BUDGET_BYTES {
1146                tokio::task::consume_budget().await;
1147                frames = 0;
1148                bytes = 0;
1149            }
1150            let frame = read_frame(&mut recv).await?;
1151            frames += 1;
1152            bytes += FRAME_HEADER_LEN + frame.payload.len();
1153            process_server_frame(
1154                frame,
1155                bundle_id,
1156                &state,
1157                &control_tx,
1158                response_buffer_capacity,
1159            )
1160            .await?;
1161        }
1162        #[allow(unreachable_code)]
1163        Ok::<(), anyhow::Error>(())
1164    };
1165    // Keep both futures pinned across polls. This avoids a separate task wake
1166    // for registration acknowledgements without cancelling partial reads.
1167    tokio::pin!(reader, writer);
1168    tokio::select! {
1169        result = &mut reader => result,
1170        result = &mut writer => match result {
1171            Ok(()) => bail!("QUIC reverse-control writer exited unexpectedly"),
1172            Err(error) => Err(error.into()),
1173        },
1174    }
1175}
1176
1177async fn process_server_frame(
1178    frame: Frame,
1179    bundle_id: Uuid,
1180    state: &Arc<ServerState>,
1181    control_tx: &mpsc::Sender<Frame>,
1182    response_buffer_capacity: usize,
1183) -> Result<()> {
1184    match frame.kind {
1185        FrameKind::Register => {
1186            if !frame.payload.is_empty() {
1187                bail!("QUIC response Register frame carried a payload");
1188            }
1189            let monitor = {
1190                let mut registration = state.registration(frame.registration_id).lock();
1191                let Some(pending) = registration.pending.get_mut(&frame.registration_id) else {
1192                    send_control(control_tx, FrameKind::Reset, frame.registration_id)?;
1193                    return Ok(());
1194                };
1195                match pending.bundle_id {
1196                    Some(existing) if existing != bundle_id => {
1197                        bail!(
1198                            "QUIC response registration {} changed bundle id from {} to {}",
1199                            frame.registration_id,
1200                            existing,
1201                            bundle_id
1202                        );
1203                    }
1204                    Some(_) => {}
1205                    None => pending.bundle_id = Some(bundle_id),
1206                }
1207                if pending.monitor_response.is_none() {
1208                    let (response_tx, response_rx) = oneshot::channel();
1209                    pending.monitor_response = Some(response_tx);
1210                    Some((
1211                        pending.context.clone(),
1212                        response_rx,
1213                        pending.monitor_cancel.clone(),
1214                    ))
1215                } else {
1216                    None
1217                }
1218            };
1219            // Bundle ownership is visible before the worker is allowed to call
1220            // generate(), so a pre-prologue bundle failure can resolve the
1221            // pending provider with an error.
1222            send_control(control_tx, FrameKind::Registered, frame.registration_id)?;
1223            if let Some((context, response_rx, monitor_cancel)) = monitor {
1224                spawn_response_monitor(
1225                    context,
1226                    response_rx,
1227                    frame.registration_id,
1228                    control_tx.clone(),
1229                    monitor_cancel,
1230                );
1231            }
1232        }
1233        FrameKind::Prologue => {
1234            if !frame.payload.is_empty() {
1235                bail!("QUIC response Prologue frame carried a payload");
1236            }
1237            let (response_tx, response_rx) = mpsc::channel(response_buffer_capacity);
1238            let (pending_connection, monitor_response) = {
1239                let mut registration = state.registration(frame.registration_id).lock();
1240                let Some(pending) = registration.pending.remove(&frame.registration_id) else {
1241                    send_control(control_tx, FrameKind::Reset, frame.registration_id)?;
1242                    return Ok(());
1243                };
1244                let PendingResponse {
1245                    context: _,
1246                    connection,
1247                    bundle_id: pending_bundle,
1248                    deferred,
1249                    monitor_cancel,
1250                    monitor_response,
1251                } = pending;
1252                if pending_bundle != Some(bundle_id) {
1253                    bail!(
1254                        "QUIC response registration {} was not registered to bundle {}",
1255                        frame.registration_id,
1256                        bundle_id
1257                    );
1258                }
1259                registration.active.insert(
1260                    frame.registration_id,
1261                    ActiveResponse {
1262                        sender: response_tx.clone(),
1263                        monitor_cancel: monitor_cancel.clone(),
1264                        bundle_id,
1265                        priority_ready: false,
1266                        priority_draining: false,
1267                        deferred,
1268                    },
1269                );
1270                (connection, monitor_response)
1271            };
1272            let Some(monitor_response) = monitor_response else {
1273                bail!(
1274                    "QUIC response registration {} had no cancellation monitor",
1275                    frame.registration_id
1276                );
1277            };
1278            let _ = monitor_response.send(response_tx.clone());
1279            if pending_connection
1280                .send(Ok(StreamReceiver {
1281                    rx: response_rx.into(),
1282                }))
1283                .is_err()
1284            {
1285                remove_registration(state, frame.registration_id);
1286                send_control(control_tx, FrameKind::Reset, frame.registration_id)?;
1287                return Ok(());
1288            }
1289        }
1290        FrameKind::Error => {
1291            let error = decode_error_payload(&frame.payload)?;
1292            let pending = state
1293                .registration(frame.registration_id)
1294                .lock()
1295                .pending
1296                .remove(&frame.registration_id);
1297            if let Some(pending) = pending {
1298                if let Some(pending_bundle) = pending.bundle_id
1299                    && pending_bundle != bundle_id
1300                {
1301                    bail!(
1302                        "QUIC response registration {} changed bundle id from {} to {}",
1303                        frame.registration_id,
1304                        pending_bundle,
1305                        bundle_id
1306                    );
1307                }
1308                let _ = pending.connection.send(Err(error));
1309                remove_registration(state, frame.registration_id);
1310            } else {
1311                send_control(control_tx, FrameKind::Reset, frame.registration_id)?;
1312            }
1313        }
1314        FrameKind::FirstData | FrameKind::PriorityEnd => {
1315            let first_payload = (frame.kind == FrameKind::FirstData).then_some(frame.payload);
1316            let active = {
1317                let mut registration = state.registration(frame.registration_id).lock();
1318                match registration.active.get_mut(&frame.registration_id) {
1319                    Some(active) if active.bundle_id != bundle_id => {
1320                        bail!(
1321                            "QUIC response registration {} changed bundle id from {} to {}",
1322                            frame.registration_id,
1323                            active.bundle_id,
1324                            bundle_id
1325                        );
1326                    }
1327                    Some(active) if active.priority_ready || active.priority_draining => None,
1328                    Some(active) => {
1329                        active.priority_draining = true;
1330                        Some(active.sender.clone())
1331                    }
1332                    None => None,
1333                }
1334            };
1335            let Some(sender) = active else {
1336                send_control(control_tx, FrameKind::Reset, frame.registration_id)?;
1337                return Ok(());
1338            };
1339
1340            if let Some(payload) = first_payload {
1341                let delivery = deliver_server_payload(&sender, payload);
1342                if let Delivery::Reset(reason) = delivery {
1343                    reset_registration(state, control_tx, frame.registration_id, reason)?;
1344                    return Ok(());
1345                }
1346            }
1347
1348            drain_deferred_response(state, frame.registration_id, &sender, control_tx).await?;
1349        }
1350        FrameKind::Data => {
1351            enum Disposition {
1352                Deferred,
1353                Deliver(mpsc::Sender<Bytes>, Bytes),
1354                Reset,
1355                Overflow,
1356            }
1357
1358            let disposition = {
1359                let mut registration = state.registration(frame.registration_id).lock();
1360                match registration.active.get_mut(&frame.registration_id) {
1361                    Some(active) if active.bundle_id != bundle_id => {
1362                        bail!(
1363                            "QUIC response registration {} changed bundle id from {} to {}",
1364                            frame.registration_id,
1365                            active.bundle_id,
1366                            bundle_id
1367                        );
1368                    }
1369                    Some(active) if !active.priority_ready => {
1370                        match active.deferred.push(frame.payload) {
1371                            Ok(()) => Disposition::Deferred,
1372                            Err(_) => Disposition::Overflow,
1373                        }
1374                    }
1375                    Some(active) => Disposition::Deliver(active.sender.clone(), frame.payload),
1376                    None => {
1377                        if let Some(pending) = registration.pending.get_mut(&frame.registration_id)
1378                        {
1379                            if let Some(pending_bundle) = pending.bundle_id
1380                                && pending_bundle != bundle_id
1381                            {
1382                                bail!(
1383                                    "QUIC response registration {} changed bundle id from {} to {}",
1384                                    frame.registration_id,
1385                                    pending_bundle,
1386                                    bundle_id
1387                                );
1388                            }
1389                            pending.bundle_id = Some(bundle_id);
1390                            match pending.deferred.push(frame.payload) {
1391                                Ok(()) => Disposition::Deferred,
1392                                Err(_) => Disposition::Overflow,
1393                            }
1394                        } else {
1395                            Disposition::Reset
1396                        }
1397                    }
1398                }
1399            };
1400            match disposition {
1401                Disposition::Deferred => {}
1402                Disposition::Deliver(sender, payload) => {
1403                    if let Delivery::Reset(reason) = deliver_server_payload(&sender, payload) {
1404                        reset_registration(state, control_tx, frame.registration_id, reason)?;
1405                    }
1406                }
1407                Disposition::Reset => {
1408                    send_control(control_tx, FrameKind::Reset, frame.registration_id)?;
1409                }
1410                Disposition::Overflow => {
1411                    tracing::warn!(
1412                        registration_id = %frame.registration_id,
1413                        "QUIC response deferred-data bound exceeded"
1414                    );
1415                    remove_registration(state, frame.registration_id);
1416                    send_control(control_tx, FrameKind::Reset, frame.registration_id)?;
1417                }
1418            }
1419        }
1420        FrameKind::End => {
1421            if !frame.payload.is_empty() {
1422                bail!("QUIC response End frame carried a payload");
1423            }
1424            let disposition = {
1425                let mut registration = state.registration(frame.registration_id).lock();
1426                match registration.active.get_mut(&frame.registration_id) {
1427                    Some(active) if active.bundle_id != bundle_id => {
1428                        bail!(
1429                            "QUIC response registration {} changed bundle id from {} to {}",
1430                            frame.registration_id,
1431                            active.bundle_id,
1432                            bundle_id
1433                        );
1434                    }
1435                    Some(active) if !active.priority_ready => {
1436                        active.deferred.end = true;
1437                        0
1438                    }
1439                    Some(_) => 1,
1440                    None => {
1441                        if let Some(pending) = registration.pending.get_mut(&frame.registration_id)
1442                        {
1443                            if let Some(pending_bundle) = pending.bundle_id
1444                                && pending_bundle != bundle_id
1445                            {
1446                                bail!(
1447                                    "QUIC response registration {} changed bundle id from {} to {}",
1448                                    frame.registration_id,
1449                                    pending_bundle,
1450                                    bundle_id
1451                                );
1452                            }
1453                            pending.bundle_id = Some(bundle_id);
1454                            pending.deferred.end = true;
1455                            0
1456                        } else {
1457                            2
1458                        }
1459                    }
1460                }
1461            };
1462            match disposition {
1463                0 => {}
1464                1 => remove_registration(state, frame.registration_id),
1465                2 => {
1466                    send_control(control_tx, FrameKind::Reset, frame.registration_id)?;
1467                }
1468                _ => unreachable!(),
1469            }
1470        }
1471        FrameKind::Reset => {
1472            if !frame.payload.is_empty() {
1473                bail!("QUIC response Reset frame carried a payload");
1474            }
1475            let registration = state.registration(frame.registration_id).lock();
1476            let registered_bundle = registration
1477                .pending
1478                .get(&frame.registration_id)
1479                .and_then(|pending| pending.bundle_id)
1480                .or_else(|| {
1481                    registration
1482                        .active
1483                        .get(&frame.registration_id)
1484                        .map(|active| active.bundle_id)
1485                });
1486            if registered_bundle != Some(bundle_id) {
1487                bail!(
1488                    "QUIC response registration {} was not registered to bundle {}",
1489                    frame.registration_id,
1490                    bundle_id
1491                );
1492            }
1493            drop(registration);
1494            remove_registration(state, frame.registration_id);
1495        }
1496        FrameKind::Stop | FrameKind::Kill | FrameKind::Registered | FrameKind::Bundle => {
1497            bail!("worker sent reverse-only control frame {:?}", frame.kind)
1498        }
1499    }
1500    Ok(())
1501}
1502
1503enum Delivery {
1504    Delivered,
1505    Reset(&'static str),
1506}
1507
1508fn deliver_server_payload(sender: &mpsc::Sender<Bytes>, payload: Bytes) -> Delivery {
1509    match sender.try_send(payload) {
1510        Ok(()) => Delivery::Delivered,
1511        Err(mpsc::error::TrySendError::Full(_)) => Delivery::Reset("full"),
1512        Err(mpsc::error::TrySendError::Closed(_)) => Delivery::Reset("closed"),
1513    }
1514}
1515
1516fn reset_registration(
1517    state: &ServerState,
1518    control_tx: &mpsc::Sender<Frame>,
1519    registration_id: Uuid,
1520    reason: &'static str,
1521) -> Result<()> {
1522    crate::metrics::quic_response::SERVER_MAILBOX_RESETS_TOTAL
1523        .with_label_values(&[reason])
1524        .inc();
1525    remove_registration(state, registration_id);
1526    send_control(control_tx, FrameKind::Reset, registration_id)
1527}
1528
1529async fn drain_deferred_response(
1530    state: &Arc<ServerState>,
1531    registration_id: Uuid,
1532    sender: &mpsc::Sender<Bytes>,
1533    control_tx: &mpsc::Sender<Frame>,
1534) -> Result<()> {
1535    loop {
1536        let (deferred, remove_after_drain) = {
1537            let mut registration = state.registration(registration_id).lock();
1538            let Some(active) = registration.active.get_mut(&registration_id) else {
1539                return Ok(());
1540            };
1541            if active.deferred.data.is_empty() {
1542                active.priority_ready = true;
1543                active.priority_draining = false;
1544                (VecDeque::new(), active.deferred.end)
1545            } else {
1546                (active.deferred.take_data(), false)
1547            }
1548        };
1549
1550        if deferred.is_empty() {
1551            if remove_after_drain {
1552                remove_registration(state, registration_id);
1553            }
1554            return Ok(());
1555        }
1556
1557        for payload in deferred {
1558            if let Delivery::Reset(reason) = deliver_server_payload(sender, payload) {
1559                reset_registration(state, control_tx, registration_id, reason)?;
1560                return Ok(());
1561            }
1562        }
1563    }
1564}
1565
1566fn spawn_response_monitor(
1567    context: Arc<dyn AsyncEngineContext>,
1568    response_rx: oneshot::Receiver<mpsc::Sender<Bytes>>,
1569    registration_id: Uuid,
1570    control_tx: mpsc::Sender<Frame>,
1571    cancel: CancellationToken,
1572) {
1573    tokio::spawn(async move {
1574        let killed = context.killed();
1575        let stopped = context.stopped();
1576        tokio::pin!(killed, stopped, response_rx);
1577        let mut stop_sent = false;
1578        let response_tx = loop {
1579            let kind = tokio::select! {
1580                _ = cancel.cancelled() => return,
1581                _ = &mut killed => Some(FrameKind::Kill),
1582                _ = &mut stopped, if !stop_sent => Some(FrameKind::Stop),
1583                response = &mut response_rx => match response {
1584                    Ok(response_tx) => break response_tx,
1585                    Err(_) => return,
1586                },
1587            };
1588            let Some(kind) = kind else { unreachable!() };
1589            if send_control(&control_tx, kind, registration_id).is_err() {
1590                return;
1591            }
1592            tracing::debug!(control_msg = ?kind, "issued control message");
1593            if kind == FrameKind::Stop {
1594                stop_sent = true;
1595            } else {
1596                return;
1597            }
1598        };
1599
1600        let closed = response_tx.closed();
1601        tokio::pin!(closed);
1602        loop {
1603            let kind = tokio::select! {
1604                _ = cancel.cancelled() => return,
1605                _ = &mut killed => FrameKind::Kill,
1606                _ = &mut stopped, if !stop_sent => FrameKind::Stop,
1607                _ = &mut closed => FrameKind::Reset,
1608            };
1609            if send_control(&control_tx, kind, registration_id).is_err() {
1610                return;
1611            }
1612            tracing::debug!(control_msg = ?kind, "issued control message");
1613            if kind == FrameKind::Stop {
1614                stop_sent = true;
1615            } else {
1616                return;
1617            }
1618        }
1619    });
1620}
1621
1622fn send_control(
1623    control_tx: &mpsc::Sender<Frame>,
1624    kind: FrameKind,
1625    registration_id: Uuid,
1626) -> Result<()> {
1627    control_tx
1628        .try_send(Frame::new(kind, registration_id, Bytes::new()))
1629        .map_err(|error| anyhow!("QUIC response reverse-control enqueue failed: {error}"))
1630}
1631
1632struct Lane {
1633    index: usize,
1634    sender: LaneSender,
1635}
1636
1637struct ResponseLanes {
1638    ordered: Arc<Lane>,
1639    priority: Arc<Lane>,
1640}
1641
1642struct ClientConnectionBundle {
1643    _endpoints: Arc<[quinn::Endpoint]>,
1644    connections: Arc<[quinn::Connection]>,
1645    lanes: Arc<[ResponseLanes]>,
1646    contexts: Arc<Mutex<HashMap<Uuid, Arc<ClientResponseContext>>>>,
1647    healthy: Arc<AtomicBool>,
1648}
1649
1650impl ClientConnectionBundle {
1651    fn is_healthy(&self) -> bool {
1652        self.healthy.load(Ordering::Acquire)
1653    }
1654}
1655
1656/// True when only the pool map holds `entry` and it has no healthy bundle.
1657/// Callers clone an entry out of the map before using or reconnecting it, and
1658/// the map's shard lock, held while this runs, stops new clones, so no caller
1659/// can still reconnect through a removed entry.
1660fn is_idle_entry(entry: &Arc<ClientPoolEntry>) -> bool {
1661    Arc::strong_count(entry) == 1
1662        && entry
1663            .current
1664            .load()
1665            .as_ref()
1666            .is_none_or(|bundle| !bundle.is_healthy())
1667}
1668
1669/// A bundle's endpoint drivers and lane tasks run on the Tokio runtime that
1670/// connected it and stop with that runtime, so only callers on the same Tokio
1671/// runtime may share it.
1672#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1673struct ConnectionKey {
1674    address: String,
1675    frontend_id: String,
1676    certificate_sha256: String,
1677    runtime: tokio::runtime::Id,
1678}
1679
1680struct ClientPoolEntry {
1681    current: ArcSwapOption<ClientConnectionBundle>,
1682    reconnect: tokio::sync::Mutex<()>,
1683}
1684
1685impl ClientPoolEntry {
1686    fn new() -> Self {
1687        Self {
1688            current: ArcSwapOption::empty(),
1689            reconnect: tokio::sync::Mutex::new(()),
1690        }
1691    }
1692}
1693
1694pub struct QuicResponseClientPool {
1695    config: QuicResponseConfig,
1696    connections: DashMap<ConnectionKey, Arc<ClientPoolEntry>>,
1697    created: Instant,
1698    // Milliseconds after `created` when the next prune is due.
1699    next_prune_ms: AtomicU64,
1700}
1701
1702static PROCESS_CLIENT_POOL: OnceLock<Arc<QuicResponseClientPool>> = OnceLock::new();
1703
1704pub fn process_client_pool_from_env() -> Result<Arc<QuicResponseClientPool>, PipelineError> {
1705    if let Some(pool) = PROCESS_CLIENT_POOL.get() {
1706        return Ok(pool.clone());
1707    }
1708    let pool = QuicResponseClientPool::from_env()?;
1709    Ok(PROCESS_CLIENT_POOL.get_or_init(|| pool).clone())
1710}
1711
1712impl fmt::Debug for QuicResponseClientPool {
1713    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1714        f.debug_struct("QuicResponseClientPool")
1715            .field("config", &self.config)
1716            .finish_non_exhaustive()
1717    }
1718}
1719
1720impl QuicResponseClientPool {
1721    pub fn from_env() -> Result<Arc<Self>, PipelineError> {
1722        Ok(Arc::new(Self {
1723            config: QuicResponseConfig::from_env()?,
1724            connections: DashMap::new(),
1725            created: Instant::now(),
1726            next_prune_ms: AtomicU64::new(0),
1727        }))
1728    }
1729
1730    pub async fn sender(
1731        &self,
1732        context: Arc<dyn AsyncEngineContext>,
1733        connection_info: ConnectionInfo,
1734    ) -> Result<QuicResponseSender> {
1735        self.sender_with_cancellation_metric(context, connection_info, None)
1736            .await
1737    }
1738
1739    pub async fn sender_with_cancellation_metric(
1740        &self,
1741        context: Arc<dyn AsyncEngineContext>,
1742        connection_info: ConnectionInfo,
1743        cancellation_counter: Option<IntCounter>,
1744    ) -> Result<QuicResponseSender> {
1745        let info = QuicResponseConnectionInfo::try_from(connection_info)?;
1746        if info.request_id != context.id() {
1747            bail!(
1748                "QUIC response request id mismatch: connection has {}, context has {}",
1749                info.request_id,
1750                context.id()
1751            );
1752        }
1753
1754        let key = ConnectionKey {
1755            address: info.address.clone(),
1756            frontend_id: info.frontend_id.clone(),
1757            certificate_sha256: info.certificate_sha256.clone(),
1758            // connect() is awaited inline below, so its tasks start on this runtime.
1759            runtime: tokio::runtime::Handle::current().id(),
1760        };
1761        let connection = self.connection(key).await?;
1762        let lane_index = xxh3_64(info.request_id.as_bytes()) as usize % connection.lanes.len();
1763        let lanes = &connection.lanes[lane_index];
1764        let (registered_tx, registered_rx) = oneshot::channel();
1765        let response_context = Arc::new(ClientResponseContext {
1766            context: context.clone(),
1767            cancellation_counter,
1768            cancellation_recorded: AtomicBool::new(false),
1769            registered: Mutex::new(Some(registered_tx)),
1770        });
1771        connection
1772            .contexts
1773            .lock()
1774            .insert(info.registration_id, response_context.clone());
1775        let mut sender = QuicResponseSender {
1776            lane: lanes.ordered.clone(),
1777            priority_lane: lanes.priority.clone(),
1778            contexts: connection.contexts.clone(),
1779            response_context,
1780            registration_id: info.registration_id,
1781            prologue_sent: false,
1782            terminated: false,
1783            first_data_sent: AtomicBool::new(false),
1784        };
1785
1786        if let Err(error) = sender
1787            .enqueue_on(
1788                &sender.priority_lane,
1789                Frame::new(FrameKind::Register, info.registration_id, Bytes::new()),
1790            )
1791            .await
1792        {
1793            connection.contexts.lock().remove(&info.registration_id);
1794            return Err(error);
1795        }
1796
1797        // Register ownership before generate(), even if cancellation raced the
1798        // handshake. The registered response monitor then propagates that
1799        // cancellation, and generate() keeps its established cancellation
1800        // semantics instead of being skipped by transport setup.
1801        let registered = registered_rx
1802            .await
1803            .map_err(|_| anyhow!("QUIC response registration acknowledgement was dropped"))?;
1804        if let Err(error) = registered {
1805            if context.is_stopped() && !context.is_killed() {
1806                let _ = sender.abort().await;
1807            } else {
1808                connection.contexts.lock().remove(&info.registration_id);
1809                let _ = sender.priority_lane.sender.try_send(Frame::new(
1810                    FrameKind::Error,
1811                    info.registration_id,
1812                    Bytes::from(error.clone()),
1813                ));
1814            }
1815            bail!(error);
1816        }
1817        Ok(sender)
1818    }
1819
1820    async fn connection(&self, key: ConnectionKey) -> Result<Arc<ClientConnectionBundle>> {
1821        let (entry, inserted) = match self.connections.entry(key.clone()) {
1822            dashmap::mapref::entry::Entry::Occupied(entry) => (entry.get().clone(), false),
1823            dashmap::mapref::entry::Entry::Vacant(entry) => {
1824                (entry.insert(Arc::new(ClientPoolEntry::new())).clone(), true)
1825            }
1826        };
1827        if inserted || self.prune_due() {
1828            self.prune_idle_entries();
1829        }
1830        if let Some(connection) = entry.current.load_full()
1831            && connection.is_healthy()
1832        {
1833            return Ok(connection);
1834        }
1835
1836        let reconnect = entry.reconnect.lock().await;
1837        if let Some(connection) = entry.current.load_full()
1838            && connection.is_healthy()
1839        {
1840            return Ok(connection);
1841        }
1842        match self.connect(&key).await {
1843            Ok(connection) => {
1844                entry.current.store(Some(connection.clone()));
1845                Ok(connection)
1846            }
1847            Err(error) => {
1848                drop(reconnect);
1849                drop(entry);
1850                self.connections
1851                    .remove_if(&key, |_, entry| is_idle_entry(entry));
1852                Err(error)
1853            }
1854        }
1855    }
1856
1857    fn prune_due(&self) -> bool {
1858        let now = self.created.elapsed().as_millis() as u64;
1859        let due = self.next_prune_ms.load(Ordering::Relaxed);
1860        now >= due
1861            && self
1862                .next_prune_ms
1863                .compare_exchange(
1864                    due,
1865                    now + CLIENT_POOL_PRUNE_INTERVAL.as_millis() as u64,
1866                    Ordering::Relaxed,
1867                    Ordering::Relaxed,
1868                )
1869                .is_ok()
1870    }
1871
1872    /// Removes entries with no healthy bundle that no caller holds, such as
1873    /// those of stopped runtimes, so their sockets close and keys do not
1874    /// accumulate.
1875    fn prune_idle_entries(&self) {
1876        self.connections.retain(|_, entry| !is_idle_entry(entry));
1877    }
1878
1879    async fn connect(&self, key: &ConnectionKey) -> Result<Arc<ClientConnectionBundle>> {
1880        let address: SocketAddr = key
1881            .address
1882            .parse()
1883            .with_context(|| format!("invalid QUIC response address {}", key.address))?;
1884        let expected_fingerprint = decode_fingerprint(&key.certificate_sha256)?;
1885        let client_config = pinned_client_config(expected_fingerprint)?;
1886        let priority_connection_index = BULK_CONNECTIONS;
1887        let total_connections = BULK_CONNECTIONS + PRIORITY_CONNECTIONS;
1888        let endpoints = self.client_endpoints(key, total_connections)?;
1889        let mut connections = Vec::with_capacity(total_connections);
1890        for endpoint in &endpoints {
1891            let connection = endpoint
1892                .connect_with(client_config.clone(), address, "localhost")?
1893                .await
1894                .with_context(|| {
1895                    format!("failed connecting QUIC response transport to {address}")
1896                })?;
1897            crate::metrics::quic_response::track_connection(connection.clone());
1898            connections.push(connection);
1899        }
1900        let connections: Arc<[quinn::Connection]> = connections.into();
1901
1902        let bundle_id = Uuid::new_v4();
1903        let contexts = Arc::new(Mutex::new(HashMap::new()));
1904        let healthy = Arc::new(AtomicBool::new(true));
1905        let mut lanes = Vec::with_capacity(BULK_LANES);
1906        for index in 0..BULK_LANES {
1907            let connection = connections[index % BULK_CONNECTIONS].clone();
1908            let (send, recv) = connection.open_bi().await?;
1909            let (lane_tx, lane_rx) = lane_queue(BULK_LANE_QUEUE_CAPACITY);
1910            let ordered = Arc::new(Lane {
1911                index,
1912                sender: lane_tx,
1913            });
1914            spawn_client_lane(
1915                send,
1916                recv,
1917                lane_rx,
1918                self.config.batch_interval,
1919                MAX_BATCH_FRAMES,
1920                bundle_id,
1921                connections.clone(),
1922                contexts.clone(),
1923                healthy.clone(),
1924            );
1925            let priority_connection = connections[priority_connection_index].clone();
1926            let (priority_send, priority_recv) = priority_connection.open_bi().await?;
1927            let (priority_tx, priority_rx) = lane_queue(LANE_QUEUE_CAPACITY);
1928            let priority = Arc::new(Lane {
1929                index,
1930                sender: priority_tx,
1931            });
1932            spawn_client_lane(
1933                priority_send,
1934                priority_recv,
1935                priority_rx,
1936                Duration::ZERO,
1937                1,
1938                bundle_id,
1939                connections.clone(),
1940                contexts.clone(),
1941                healthy.clone(),
1942            );
1943            lanes.push(ResponseLanes { ordered, priority });
1944        }
1945
1946        tracing::debug!(
1947            remote = %address,
1948            bulk_connections = BULK_CONNECTIONS,
1949            priority_connections = PRIORITY_CONNECTIONS,
1950            total_lanes = BULK_LANES,
1951            "QUIC response connection bundle and lanes ready"
1952        );
1953        Ok(Arc::new(ClientConnectionBundle {
1954            _endpoints: endpoints.into(),
1955            connections,
1956            lanes: lanes.into(),
1957            contexts,
1958            healthy,
1959        }))
1960    }
1961
1962    fn client_endpoints(&self, key: &ConnectionKey, count: usize) -> Result<Vec<quinn::Endpoint>> {
1963        let ipv6 = key.address.parse::<SocketAddr>()?.is_ipv6();
1964        let mut endpoints = Vec::with_capacity(count);
1965        for _ in 0..count {
1966            let bind = if ipv6 {
1967                SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0)
1968            } else {
1969                SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)
1970            };
1971            endpoints.push(quinn::Endpoint::client(bind)?);
1972        }
1973        Ok(endpoints)
1974    }
1975}
1976
1977#[allow(clippy::too_many_arguments)]
1978fn spawn_client_lane(
1979    send: quinn::SendStream,
1980    recv: quinn::RecvStream,
1981    receiver: LaneReceiver,
1982    interval: Duration,
1983    max_batch_frames: usize,
1984    bundle_id: Uuid,
1985    connections: Arc<[quinn::Connection]>,
1986    contexts: Arc<Mutex<HashMap<Uuid, Arc<ClientResponseContext>>>>,
1987    healthy: Arc<AtomicBool>,
1988) {
1989    let writer_connections = connections.clone();
1990    let writer_contexts = contexts.clone();
1991    let writer_healthy = healthy.clone();
1992    // Each guard is built before its spawn, so a task dropped before its first
1993    // poll still marks the bundle unhealthy.
1994    let writer_unhealthy_on_exit = MarkUnhealthyOnDrop(healthy.clone());
1995    tokio::spawn(async move {
1996        let _unhealthy_on_exit = writer_unhealthy_on_exit;
1997        if let Err(error) = run_client_writer(
1998            send,
1999            receiver,
2000            interval,
2001            max_batch_frames,
2002            bundle_id,
2003            writer_contexts.clone(),
2004        )
2005        .await
2006        {
2007            fail_client_connection_bundle(
2008                &writer_connections,
2009                &writer_contexts,
2010                &writer_healthy,
2011                bundle_id,
2012                "writer",
2013                &format!("{error:#}"),
2014            );
2015        }
2016    });
2017
2018    let reader_unhealthy_on_exit = MarkUnhealthyOnDrop(healthy.clone());
2019    tokio::spawn(async move {
2020        let _unhealthy_on_exit = reader_unhealthy_on_exit;
2021        if let Err(error) = run_client_control_reader(recv, contexts.clone()).await {
2022            fail_client_connection_bundle(
2023                &connections,
2024                &contexts,
2025                &healthy,
2026                bundle_id,
2027                "control_reader",
2028                &format!("{error:#}"),
2029            );
2030        }
2031    });
2032}
2033
2034/// Lane tasks only end on failure. Runtime shutdown drops them without running
2035/// `fail_client_connection_bundle`, so this marks the bundle unhealthy and the
2036/// pool reconnects instead of reusing it. It drops after the failure path, which
2037/// still sees the bundle healthy and does the full cleanup.
2038struct MarkUnhealthyOnDrop(Arc<AtomicBool>);
2039
2040impl Drop for MarkUnhealthyOnDrop {
2041    fn drop(&mut self) {
2042        self.0.store(false, Ordering::Release);
2043    }
2044}
2045
2046async fn run_client_writer(
2047    mut send: quinn::SendStream,
2048    mut receiver: LaneReceiver,
2049    interval: Duration,
2050    max_batch_frames: usize,
2051    bundle_id: Uuid,
2052    contexts: Arc<Mutex<HashMap<Uuid, Arc<ClientResponseContext>>>>,
2053) -> Result<()> {
2054    let bundle = Frame::new(FrameKind::Bundle, bundle_id, Bytes::new());
2055    let mut bundle_chunks = [bundle.header()];
2056    send.write_all_chunks(&mut bundle_chunks).await?;
2057
2058    let mut batch = Vec::with_capacity(max_batch_frames);
2059    let mut chunks = Vec::with_capacity(max_batch_frames * 2);
2060    while receive_batch(&mut receiver, &mut batch, interval, max_batch_frames).await {
2061        chunks.clear();
2062        for frame in &batch {
2063            chunks.push(frame.header());
2064            if !frame.payload.is_empty() {
2065                chunks.push(frame.payload.clone());
2066            }
2067        }
2068        send.write_all_chunks(&mut chunks).await?;
2069        if batch.iter().any(|frame| {
2070            matches!(
2071                frame.kind,
2072                FrameKind::Error | FrameKind::End | FrameKind::Reset
2073            )
2074        }) {
2075            let mut contexts = contexts.lock();
2076            for frame in &batch {
2077                if matches!(
2078                    frame.kind,
2079                    FrameKind::Error | FrameKind::End | FrameKind::Reset
2080                ) {
2081                    contexts.remove(&frame.registration_id);
2082                }
2083            }
2084        }
2085        batch.clear();
2086    }
2087    bail!("QUIC response lane queue closed unexpectedly")
2088}
2089
2090async fn run_client_control_reader(
2091    recv: quinn::RecvStream,
2092    contexts: Arc<Mutex<HashMap<Uuid, Arc<ClientResponseContext>>>>,
2093) -> Result<()> {
2094    let mut recv = BufReader::with_capacity(RECEIVE_BUFFER_CAPACITY, recv);
2095    loop {
2096        let frame = read_frame(&mut recv).await?;
2097        if !frame.payload.is_empty() {
2098            bail!("QUIC response reverse control carried a payload");
2099        }
2100        let entry = contexts.lock().get(&frame.registration_id).cloned();
2101        match frame.kind {
2102            FrameKind::Registered => {
2103                if let Some(entry) = entry
2104                    && let Some(registered) = entry.registered.lock().take()
2105                {
2106                    let _ = registered.send(Ok(()));
2107                }
2108            }
2109            FrameKind::Stop => {
2110                if let Some(entry) = entry {
2111                    entry.fail_registration("QUIC response registration was stopped");
2112                    entry.record_cancellation();
2113                    entry.context.stop();
2114                }
2115            }
2116            FrameKind::Kill | FrameKind::Reset => {
2117                if let Some(entry) = entry {
2118                    entry.fail_registration("QUIC response registration was reset");
2119                    entry.record_cancellation();
2120                    entry.context.kill();
2121                }
2122            }
2123            _ => bail!("frontend sent forward-only frame {:?}", frame.kind),
2124        }
2125    }
2126}
2127
2128fn fail_client_connection_bundle(
2129    connections: &[quinn::Connection],
2130    contexts: &Mutex<HashMap<Uuid, Arc<ClientResponseContext>>>,
2131    healthy: &AtomicBool,
2132    bundle_id: Uuid,
2133    failure_path: &'static str,
2134    reason: &str,
2135) {
2136    if !healthy.swap(false, Ordering::AcqRel) {
2137        return;
2138    }
2139    crate::metrics::quic_response::record_bundle_failure("worker");
2140    let remote = connections.first().map(quinn::Connection::remote_address);
2141    tracing::warn!(
2142        %bundle_id,
2143        failure_path,
2144        ?remote,
2145        reason,
2146        "QUIC response connection bundle invariant failed"
2147    );
2148    for (_, entry) in contexts.lock().drain() {
2149        entry.fail_registration(reason);
2150        entry.record_cancellation();
2151        entry.context.kill();
2152    }
2153    for connection in connections {
2154        connection.close(
2155            CLOSE_CODE_INVARIANT,
2156            b"response connection bundle invariant failure",
2157        );
2158    }
2159}
2160
2161pub struct QuicResponseSender {
2162    lane: Arc<Lane>,
2163    priority_lane: Arc<Lane>,
2164    contexts: Arc<Mutex<HashMap<Uuid, Arc<ClientResponseContext>>>>,
2165    response_context: Arc<ClientResponseContext>,
2166    registration_id: Uuid,
2167    prologue_sent: bool,
2168    terminated: bool,
2169    first_data_sent: AtomicBool,
2170}
2171
2172struct ClientResponseContext {
2173    context: Arc<dyn AsyncEngineContext>,
2174    cancellation_counter: Option<IntCounter>,
2175    cancellation_recorded: AtomicBool,
2176    registered: Mutex<Option<oneshot::Sender<std::result::Result<(), String>>>>,
2177}
2178
2179impl ClientResponseContext {
2180    fn fail_registration(&self, reason: &str) {
2181        if let Some(registered) = self.registered.lock().take() {
2182            let _ = registered.send(Err(reason.to_string()));
2183        }
2184    }
2185
2186    fn record_cancellation(&self) {
2187        if !self.cancellation_recorded.swap(true, Ordering::AcqRel)
2188            && let Some(counter) = &self.cancellation_counter
2189        {
2190            counter.inc();
2191        }
2192    }
2193}
2194
2195impl QuicResponseSender {
2196    #[cfg(test)]
2197    fn lane_index(&self) -> usize {
2198        self.lane.index
2199    }
2200
2201    pub async fn send_prologue(&mut self, error: Option<String>) -> Result<(), String> {
2202        self.send_prologue_typed(error.map(StreamPrologueError::from_message))
2203            .await
2204    }
2205
2206    pub async fn send_prologue_typed(
2207        &mut self,
2208        error: Option<StreamPrologueError>,
2209    ) -> Result<(), String> {
2210        if self.prologue_sent {
2211            return Err("QUIC response prologue already sent".to_string());
2212        }
2213        let (kind, payload, terminal) = match error {
2214            Some(error) => (FrameKind::Error, encode_error_payload(error), true),
2215            None => (FrameKind::Prologue, Bytes::new(), false),
2216        };
2217        self.enqueue_on(
2218            &self.priority_lane,
2219            Frame::new(kind, self.registration_id, payload),
2220        )
2221        .await
2222        .map_err(|error| error.to_string())?;
2223        self.prologue_sent = true;
2224        if terminal {
2225            self.terminated = true;
2226        }
2227        Ok(())
2228    }
2229
2230    pub async fn send(&self, payload: Bytes) -> Result<()> {
2231        if !self.prologue_sent || self.terminated {
2232            bail!("QUIC response sender is not open for data");
2233        }
2234        let first_data = !self.first_data_sent.swap(true, Ordering::AcqRel);
2235        if first_data
2236            && self.response_context.context.is_stopped()
2237            && !self.response_context.context.is_killed()
2238        {
2239            bail!("QUIC response context stopped before its first response");
2240        }
2241        let frame = if first_data {
2242            Frame::new(FrameKind::FirstData, self.registration_id, payload)
2243        } else {
2244            Frame::new(FrameKind::Data, self.registration_id, payload)
2245        };
2246        if first_data {
2247            self.enqueue_on(&self.priority_lane, frame).await
2248        } else {
2249            self.enqueue_on(&self.lane, frame).await
2250        }
2251    }
2252
2253    pub async fn finish(&mut self) -> Result<()> {
2254        if !self.prologue_sent || self.terminated {
2255            return Ok(());
2256        }
2257        if !self.first_data_sent.load(Ordering::Acquire) {
2258            self.enqueue_on(
2259                &self.priority_lane,
2260                Frame::new(FrameKind::PriorityEnd, self.registration_id, Bytes::new()),
2261            )
2262            .await?;
2263        }
2264        self.enqueue_on(
2265            &self.lane,
2266            Frame::new(FrameKind::End, self.registration_id, Bytes::new()),
2267        )
2268        .await?;
2269        self.terminated = true;
2270        Ok(())
2271    }
2272
2273    /// Close one cancelled logical response without ending its shared lane.
2274    pub async fn abort(&mut self) -> Result<()> {
2275        if self.terminated {
2276            return Ok(());
2277        }
2278        if !self.prologue_sent {
2279            self.enqueue_on(
2280                &self.priority_lane,
2281                Frame::new(FrameKind::Prologue, self.registration_id, Bytes::new()),
2282            )
2283            .await?;
2284            self.prologue_sent = true;
2285        }
2286        self.response_context.record_cancellation();
2287        self.enqueue_on(
2288            &self.priority_lane,
2289            Frame::new(FrameKind::Reset, self.registration_id, Bytes::new()),
2290        )
2291        .await?;
2292        self.terminated = true;
2293        Ok(())
2294    }
2295
2296    async fn enqueue_on(&self, lane: &Lane, frame: Frame) -> Result<()> {
2297        if frame.payload.len() > MAX_FRAME_PAYLOAD {
2298            bail!(
2299                "QUIC response frame payload {} exceeds {}",
2300                frame.payload.len(),
2301                MAX_FRAME_PAYLOAD
2302            );
2303        }
2304        match lane.sender.try_send(frame) {
2305            Ok(()) => Ok(()),
2306            Err(LaneTrySendError::Closed(_)) => {
2307                bail!("QUIC response lane closed")
2308            }
2309            Err(LaneTrySendError::Full(frame)) => lane.sender.send(frame).await,
2310        }
2311    }
2312}
2313
2314impl Drop for QuicResponseSender {
2315    fn drop(&mut self) {
2316        if !self.prologue_sent {
2317            self.contexts.lock().remove(&self.registration_id);
2318            return;
2319        }
2320        if self.terminated {
2321            return;
2322        }
2323        let sender = self.lane.sender.clone();
2324        let priority_sender = (!self.first_data_sent.load(Ordering::Acquire))
2325            .then(|| self.priority_lane.sender.clone());
2326        let registration_id = self.registration_id;
2327        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
2328            runtime.spawn(async move {
2329                if let Some(priority_sender) = priority_sender {
2330                    let _ = priority_sender
2331                        .send(Frame::new(
2332                            FrameKind::PriorityEnd,
2333                            registration_id,
2334                            Bytes::new(),
2335                        ))
2336                        .await;
2337                }
2338                let _ = sender
2339                    .send(Frame::new(FrameKind::End, registration_id, Bytes::new()))
2340                    .await;
2341            });
2342        }
2343    }
2344}
2345
2346#[derive(Debug)]
2347struct PinnedCertificateVerifier {
2348    expected: [u8; 32],
2349    provider: Arc<rustls::crypto::CryptoProvider>,
2350}
2351
2352impl ServerCertVerifier for PinnedCertificateVerifier {
2353    fn verify_server_cert(
2354        &self,
2355        end_entity: &CertificateDer<'_>,
2356        _intermediates: &[CertificateDer<'_>],
2357        _server_name: &ServerName<'_>,
2358        _ocsp_response: &[u8],
2359        _now: UnixTime,
2360    ) -> std::result::Result<ServerCertVerified, rustls::Error> {
2361        let actual: [u8; 32] = Sha256::digest(end_entity.as_ref()).into();
2362        if actual != self.expected {
2363            return Err(rustls::Error::General(
2364                "QUIC response certificate fingerprint mismatch".to_string(),
2365            ));
2366        }
2367        Ok(ServerCertVerified::assertion())
2368    }
2369
2370    fn verify_tls12_signature(
2371        &self,
2372        message: &[u8],
2373        cert: &CertificateDer<'_>,
2374        dss: &DigitallySignedStruct,
2375    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
2376        rustls::crypto::verify_tls12_signature(
2377            message,
2378            cert,
2379            dss,
2380            &self.provider.signature_verification_algorithms,
2381        )
2382    }
2383
2384    fn verify_tls13_signature(
2385        &self,
2386        message: &[u8],
2387        cert: &CertificateDer<'_>,
2388        dss: &DigitallySignedStruct,
2389    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
2390        rustls::crypto::verify_tls13_signature(
2391            message,
2392            cert,
2393            dss,
2394            &self.provider.signature_verification_algorithms,
2395        )
2396    }
2397
2398    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
2399        self.provider
2400            .signature_verification_algorithms
2401            .supported_schemes()
2402    }
2403}
2404
2405fn pinned_client_config(expected: [u8; 32]) -> Result<quinn::ClientConfig> {
2406    let provider = Arc::new(rustls::crypto::ring::default_provider());
2407    let verifier = Arc::new(PinnedCertificateVerifier {
2408        expected,
2409        provider: provider.clone(),
2410    });
2411    let mut crypto = rustls::ClientConfig::builder_with_provider(provider)
2412        .with_safe_default_protocol_versions()?
2413        .dangerous()
2414        .with_custom_certificate_verifier(verifier)
2415        .with_no_client_auth();
2416    crypto.alpn_protocols = vec![ALPN.to_vec()];
2417    let crypto = QuicClientConfig::try_from(crypto)?;
2418    Ok(quinn::ClientConfig::new(Arc::new(crypto)))
2419}
2420
2421fn encode_hex(bytes: &[u8]) -> String {
2422    use std::fmt::Write as _;
2423    let mut encoded = String::with_capacity(bytes.len() * 2);
2424    for byte in bytes {
2425        write!(&mut encoded, "{byte:02x}").expect("writing to String cannot fail");
2426    }
2427    encoded
2428}
2429
2430fn decode_fingerprint(encoded: &str) -> Result<[u8; 32]> {
2431    let bytes = encoded.as_bytes();
2432    if bytes.len() != 64 || !bytes.is_ascii() {
2433        bail!("invalid ASCII SHA-256 fingerprint length {}", bytes.len());
2434    }
2435    let mut decoded = [0_u8; 32];
2436    for (pair, output) in bytes.chunks_exact(2).zip(&mut decoded) {
2437        let high = decode_hex_digit(pair[0])?;
2438        let low = decode_hex_digit(pair[1])?;
2439        *output = (high << 4) | low;
2440    }
2441    Ok(decoded)
2442}
2443
2444fn decode_hex_digit(value: u8) -> Result<u8> {
2445    match value {
2446        b'0'..=b'9' => Ok(value - b'0'),
2447        b'a'..=b'f' => Ok(value - b'a' + 10),
2448        b'A'..=b'F' => Ok(value - b'A' + 10),
2449        _ => bail!("invalid SHA-256 fingerprint hex digit"),
2450    }
2451}
2452
2453#[cfg(test)]
2454mod tests {
2455    use super::*;
2456    use crate::{
2457        engine::AsyncEngineContextProvider,
2458        error::{BackendError, DynamoError, ErrorType},
2459        pipeline::Context as PipelineContext,
2460    };
2461
2462    fn frame(index: usize) -> Frame {
2463        Frame::new(FrameKind::Data, Uuid::nil(), Bytes::from(index.to_string()))
2464    }
2465
2466    fn test_pool() -> QuicResponseClientPool {
2467        QuicResponseClientPool {
2468            config: QuicResponseConfig {
2469                batch_interval: Duration::ZERO,
2470                response_buffer_capacity: RESPONSE_BUFFER_CAPACITY,
2471            },
2472            connections: DashMap::new(),
2473            created: Instant::now(),
2474            next_prune_ms: AtomicU64::new(0),
2475        }
2476    }
2477
2478    fn test_server(
2479        response_buffer_capacity: usize,
2480    ) -> (CancellationToken, Arc<QuicResponseServer>) {
2481        let shutdown = CancellationToken::new();
2482        let address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
2483        let server = QuicResponseServer::new_with_config(
2484            address,
2485            address,
2486            shutdown.clone(),
2487            None,
2488            QuicResponseConfig {
2489                batch_interval: Duration::ZERO,
2490                response_buffer_capacity,
2491            },
2492        )
2493        .unwrap();
2494        (shutdown, server)
2495    }
2496
2497    fn only_bundle(pool: &QuicResponseClientPool) -> Arc<ClientConnectionBundle> {
2498        assert_eq!(pool.connections.len(), 1);
2499        pool.connections
2500            .iter()
2501            .next()
2502            .unwrap()
2503            .current
2504            .load_full()
2505            .unwrap()
2506    }
2507
2508    #[tokio::test]
2509    async fn fixed_batch_cap_drains_512_frames() {
2510        let (tx, mut rx) = lane_queue(MAX_BATCH_FRAMES + 1);
2511        for index in 0..=MAX_BATCH_FRAMES {
2512            tx.send(frame(index)).await.unwrap();
2513        }
2514        let mut batch = Vec::with_capacity(MAX_BATCH_FRAMES);
2515        assert!(receive_batch(&mut rx, &mut batch, Duration::ZERO, MAX_BATCH_FRAMES).await);
2516        assert_eq!(batch.len(), MAX_BATCH_FRAMES);
2517        assert_eq!(batch[0].payload, Bytes::from_static(b"0"));
2518        assert_eq!(
2519            batch[MAX_BATCH_FRAMES - 1].payload,
2520            Bytes::from_static(b"511")
2521        );
2522    }
2523
2524    #[tokio::test]
2525    async fn lane_queue_preserves_capacity_order_and_close() {
2526        let (tx, mut rx) = lane_queue(LANE_QUEUE_CAPACITY);
2527        let queue = tx.0.clone();
2528        for index in 0..LANE_QUEUE_CAPACITY {
2529            tx.try_send(frame(index)).unwrap();
2530        }
2531        assert_eq!(queue.notifications.load(Ordering::Relaxed), 1);
2532        assert!(matches!(
2533            tx.try_send(frame(LANE_QUEUE_CAPACITY)),
2534            Err(LaneTrySendError::Full(_))
2535        ));
2536        let blocked = tokio::spawn({
2537            let tx = tx.clone();
2538            async move { tx.send(frame(LANE_QUEUE_CAPACITY)).await }
2539        });
2540        tokio::task::yield_now().await;
2541        assert!(!blocked.is_finished());
2542
2543        let mut batch = Vec::with_capacity(256);
2544        assert!(receive_batch(&mut rx, &mut batch, Duration::ZERO, 256).await);
2545        for (expected, actual) in (0..256).zip(&batch) {
2546            assert_eq!(actual.payload, Bytes::from(expected.to_string()));
2547        }
2548
2549        blocked.await.unwrap().unwrap();
2550        assert_eq!(queue.notifications.load(Ordering::Relaxed), 1);
2551        assert!(receive_batch(&mut rx, &mut batch, Duration::ZERO, LANE_QUEUE_CAPACITY).await);
2552        for (expected, actual) in (256..=LANE_QUEUE_CAPACITY).zip(&batch) {
2553            assert_eq!(actual.payload, Bytes::from(expected.to_string()));
2554        }
2555
2556        tx.try_send(frame(LANE_QUEUE_CAPACITY + 1)).unwrap();
2557        assert_eq!(queue.notifications.load(Ordering::Relaxed), 1);
2558        drop(tx);
2559        assert!(receive_batch(&mut rx, &mut batch, Duration::ZERO, LANE_QUEUE_CAPACITY).await);
2560        assert_eq!(batch.len(), 1);
2561        assert_eq!(
2562            batch[0].payload,
2563            Bytes::from((LANE_QUEUE_CAPACITY + 1).to_string())
2564        );
2565        assert!(!receive_batch(&mut rx, &mut batch, Duration::ZERO, LANE_QUEUE_CAPACITY).await);
2566    }
2567
2568    #[tokio::test]
2569    async fn lane_queue_close_has_no_lost_wakeup() {
2570        let (tx, mut rx) = lane_queue(1);
2571        let waiting = tokio::spawn(async move {
2572            let mut batch = Vec::new();
2573            rx.recv_many(&mut batch, 1).await
2574        });
2575        tokio::task::yield_now().await;
2576        drop(tx);
2577        assert_eq!(
2578            tokio::time::timeout(Duration::from_secs(1), waiting)
2579                .await
2580                .expect("closed queue must wake its receiver")
2581                .unwrap(),
2582            0
2583        );
2584    }
2585
2586    #[tokio::test(start_paused = true)]
2587    async fn frames_arriving_before_deadline_join_the_same_batch() {
2588        let (tx, mut rx) = lane_queue(128);
2589        tx.send(frame(0)).await.unwrap();
2590        let task = tokio::spawn(async move {
2591            let mut batch = Vec::with_capacity(MAX_BATCH_FRAMES);
2592            let wait = receive_batch(
2593                &mut rx,
2594                &mut batch,
2595                Duration::from_millis(1),
2596                MAX_BATCH_FRAMES,
2597            )
2598            .await;
2599            (wait, batch.len())
2600        });
2601        tokio::task::yield_now().await;
2602        tokio::time::advance(Duration::from_micros(500)).await;
2603        for index in 1..64 {
2604            tx.send(frame(index)).await.unwrap();
2605        }
2606        tokio::task::yield_now().await;
2607        let (wait, len) = task.await.unwrap();
2608        assert!(wait);
2609        assert_eq!(len, 64);
2610    }
2611
2612    #[tokio::test(start_paused = true)]
2613    async fn deadline_wins_when_a_frame_arrives_at_the_boundary() {
2614        let (tx, mut rx) = lane_queue(128);
2615        tx.send(frame(0)).await.unwrap();
2616        let task = tokio::spawn(async move {
2617            let mut batch = Vec::with_capacity(MAX_BATCH_FRAMES);
2618            let wait = receive_batch(
2619                &mut rx,
2620                &mut batch,
2621                Duration::from_millis(1),
2622                MAX_BATCH_FRAMES,
2623            )
2624            .await;
2625            (wait, batch, rx)
2626        });
2627        tokio::task::yield_now().await;
2628        tokio::time::advance(Duration::from_millis(1)).await;
2629        tx.send(frame(1)).await.unwrap();
2630        tokio::task::yield_now().await;
2631
2632        let (wait, batch, mut rx) = task.await.unwrap();
2633        assert!(wait);
2634        assert_eq!(batch.len(), 1);
2635        assert_eq!(rx.recv().await.unwrap().payload, Bytes::from_static(b"1"));
2636    }
2637
2638    #[tokio::test]
2639    async fn eight_connections_eight_lanes_carry_1000_ordered_responses() {
2640        let (shutdown, server) = test_server(RESPONSE_BUFFER_CAPACITY);
2641        let pool = test_pool();
2642
2643        let mut lane_by_request = HashMap::new();
2644        for index in 0..1_000 {
2645            let context = PipelineContext::new(());
2646            let request_id = context.id().to_string();
2647            let registered = server.register_response(context.context());
2648            let (connection_info, provider) = registered.into_parts();
2649            let mut sender = pool
2650                .sender(context.context(), connection_info)
2651                .await
2652                .unwrap();
2653            let expected_lane = xxh3_64(request_id.as_bytes()) as usize % 8;
2654            assert_eq!(sender.lane_index(), expected_lane);
2655            lane_by_request.insert(request_id, sender.lane_index());
2656            sender.send_prologue(None).await.unwrap();
2657            sender
2658                .send(Bytes::from(format!("{index}:first")))
2659                .await
2660                .unwrap();
2661            sender
2662                .send(Bytes::from(format!("{index}:second")))
2663                .await
2664                .unwrap();
2665            sender.finish().await.unwrap();
2666
2667            let mut receiver = provider.await.unwrap().unwrap();
2668            assert_eq!(
2669                receiver.rx.recv().await.unwrap(),
2670                Bytes::from(format!("{index}:first"))
2671            );
2672            assert_eq!(
2673                receiver.rx.recv().await.unwrap(),
2674                Bytes::from(format!("{index}:second"))
2675            );
2676            assert!(receiver.rx.recv().await.is_none());
2677        }
2678
2679        assert_eq!(lane_by_request.len(), 1_000);
2680        let bundle = only_bundle(&pool);
2681        assert_eq!(bundle.connections.len(), 9); // Eight bulk and one priority.
2682        assert_eq!(bundle.lanes.len(), 8);
2683        shutdown.cancel();
2684    }
2685
2686    #[tokio::test]
2687    async fn registration_ack_does_not_resolve_response_stream() {
2688        let (shutdown, server) = test_server(4);
2689        let context = PipelineContext::new(());
2690        let registered = server.register_response(context.context());
2691        let registration_id = registered.registration_id().unwrap();
2692        let (_, mut provider) = registered.into_parts();
2693        let bundle_id = Uuid::new_v4();
2694        let (control_tx, mut control_rx) = mpsc::channel(4);
2695
2696        process_server_frame(
2697            Frame::new(FrameKind::Register, registration_id, Bytes::new()),
2698            bundle_id,
2699            &server.state,
2700            &control_tx,
2701            4,
2702        )
2703        .await
2704        .unwrap();
2705        assert_eq!(control_rx.recv().await.unwrap().kind, FrameKind::Registered);
2706        assert!(matches!(
2707            provider.try_recv(),
2708            Err(oneshot::error::TryRecvError::Empty)
2709        ));
2710
2711        process_server_frame(
2712            Frame::new(FrameKind::Prologue, registration_id, Bytes::new()),
2713            bundle_id,
2714            &server.state,
2715            &control_tx,
2716            4,
2717        )
2718        .await
2719        .unwrap();
2720        assert!(provider.await.unwrap().is_ok());
2721        shutdown.cancel();
2722    }
2723
2724    #[tokio::test]
2725    async fn prologue_activation_is_atomic_with_concurrent_bulk_data() {
2726        let (shutdown, server) = test_server(4);
2727        let context = PipelineContext::new(());
2728        let registered = server.register_response(context.context());
2729        let registration_id = registered.registration_id().unwrap();
2730        let (_, provider) = registered.into_parts();
2731        let bundle_id = Uuid::new_v4();
2732        let (control_tx, mut control_rx) = mpsc::channel(8);
2733
2734        process_server_frame(
2735            Frame::new(FrameKind::Register, registration_id, Bytes::new()),
2736            bundle_id,
2737            &server.state,
2738            &control_tx,
2739            4,
2740        )
2741        .await
2742        .unwrap();
2743        assert_eq!(control_rx.recv().await.unwrap().kind, FrameKind::Registered);
2744
2745        let (prologue, bulk) = tokio::join!(
2746            process_server_frame(
2747                Frame::new(FrameKind::Prologue, registration_id, Bytes::new()),
2748                bundle_id,
2749                &server.state,
2750                &control_tx,
2751                4,
2752            ),
2753            process_server_frame(
2754                Frame::new(
2755                    FrameKind::Data,
2756                    registration_id,
2757                    Bytes::from_static(b"bulk"),
2758                ),
2759                bundle_id,
2760                &server.state,
2761                &control_tx,
2762                4,
2763            )
2764        );
2765        prologue.unwrap();
2766        bulk.unwrap();
2767
2768        process_server_frame(
2769            Frame::new(
2770                FrameKind::FirstData,
2771                registration_id,
2772                Bytes::from_static(b"first"),
2773            ),
2774            bundle_id,
2775            &server.state,
2776            &control_tx,
2777            4,
2778        )
2779        .await
2780        .unwrap();
2781
2782        let mut receiver = provider.await.unwrap().unwrap();
2783        assert_eq!(
2784            receiver.rx.recv().await.unwrap(),
2785            Bytes::from_static(b"first")
2786        );
2787        assert_eq!(
2788            receiver.rx.recv().await.unwrap(),
2789            Bytes::from_static(b"bulk")
2790        );
2791        shutdown.cancel();
2792    }
2793
2794    #[tokio::test]
2795    async fn priority_path_preserves_response_order() {
2796        let (shutdown, server) = test_server(RESPONSE_BUFFER_CAPACITY);
2797        let pool = test_pool();
2798
2799        let context = PipelineContext::new(());
2800        let registered = server.register_response(context.context());
2801        let (connection_info, provider) = registered.into_parts();
2802        let mut sender = pool
2803            .sender(context.context(), connection_info)
2804            .await
2805            .unwrap();
2806        sender.send_prologue(None).await.unwrap();
2807        sender.send(Bytes::from_static(b"first")).await.unwrap();
2808        sender.send(Bytes::from_static(b"second")).await.unwrap();
2809        sender.finish().await.unwrap();
2810
2811        let mut receiver = provider.await.unwrap().unwrap();
2812        assert_eq!(
2813            receiver.rx.recv().await.unwrap(),
2814            Bytes::from_static(b"first")
2815        );
2816        assert_eq!(
2817            receiver.rx.recv().await.unwrap(),
2818            Bytes::from_static(b"second")
2819        );
2820        assert!(receiver.rx.recv().await.is_none());
2821        shutdown.cancel();
2822    }
2823
2824    #[tokio::test]
2825    async fn receiver_drop_sends_logical_reset_without_resetting_lane() {
2826        let (shutdown, server) = test_server(RESPONSE_BUFFER_CAPACITY);
2827        let pool = test_pool();
2828        let context = PipelineContext::new(());
2829        let registered = server.register_response(context.context());
2830        let (info, provider) = registered.into_parts();
2831        let mut sender = pool.sender(context.context(), info).await.unwrap();
2832        sender.send_prologue(None).await.unwrap();
2833        let receiver = provider.await.unwrap().unwrap();
2834        drop(receiver);
2835
2836        let worker_context = context.context();
2837        tokio::time::timeout(Duration::from_secs(1), worker_context.killed())
2838            .await
2839            .expect("logical reset should kill the matching worker context");
2840        assert!(only_bundle(&pool).is_healthy());
2841
2842        // A sibling response still uses the same healthy connection.
2843        let sibling = PipelineContext::new(());
2844        let registered = server.register_response(sibling.context());
2845        let (info, provider) = registered.into_parts();
2846        let mut sibling_sender = pool.sender(sibling.context(), info).await.unwrap();
2847        sibling_sender.send_prologue(None).await.unwrap();
2848        sibling_sender.finish().await.unwrap();
2849        let mut receiver = provider.await.unwrap().unwrap();
2850        assert!(receiver.rx.recv().await.is_none());
2851        shutdown.cancel();
2852    }
2853
2854    #[tokio::test]
2855    async fn priority_barrier_reorders_early_bulk_frames() {
2856        let registration_id = Uuid::new_v4();
2857        let bundle_id = Uuid::new_v4();
2858        let (response_tx, mut response_rx) = mpsc::channel(4);
2859        let state = Arc::new(ServerState::default());
2860        state.registration(registration_id).lock().active.insert(
2861            registration_id,
2862            ActiveResponse {
2863                sender: response_tx,
2864                monitor_cancel: CancellationToken::new(),
2865                bundle_id,
2866                priority_ready: false,
2867                priority_draining: false,
2868                deferred: DeferredResponse::default(),
2869            },
2870        );
2871        let (control_tx, mut control_rx) = mpsc::channel(4);
2872
2873        process_server_frame(
2874            Frame::new(
2875                FrameKind::Data,
2876                registration_id,
2877                Bytes::from_static(b"second"),
2878            ),
2879            bundle_id,
2880            &state,
2881            &control_tx,
2882            4,
2883        )
2884        .await
2885        .unwrap();
2886        process_server_frame(
2887            Frame::new(FrameKind::End, registration_id, Bytes::new()),
2888            bundle_id,
2889            &state,
2890            &control_tx,
2891            4,
2892        )
2893        .await
2894        .unwrap();
2895        assert!(matches!(
2896            response_rx.try_recv(),
2897            Err(mpsc::error::TryRecvError::Empty)
2898        ));
2899
2900        process_server_frame(
2901            Frame::new(
2902                FrameKind::FirstData,
2903                registration_id,
2904                Bytes::from_static(b"first"),
2905            ),
2906            bundle_id,
2907            &state,
2908            &control_tx,
2909            4,
2910        )
2911        .await
2912        .unwrap();
2913
2914        assert_eq!(
2915            response_rx.recv().await.unwrap(),
2916            Bytes::from_static(b"first")
2917        );
2918        assert_eq!(
2919            response_rx.recv().await.unwrap(),
2920            Bytes::from_static(b"second")
2921        );
2922        assert!(response_rx.recv().await.is_none());
2923        assert!(matches!(
2924            control_rx.try_recv(),
2925            Err(mpsc::error::TryRecvError::Empty)
2926        ));
2927    }
2928
2929    #[test]
2930    fn deferred_response_enforces_frame_and_byte_bounds() {
2931        let mut frame_bounded = DeferredResponse::default();
2932        for _ in 0..MAX_DEFERRED_RESPONSE_FRAMES {
2933            frame_bounded.push(Bytes::new()).unwrap();
2934        }
2935        assert!(frame_bounded.push(Bytes::from_static(b"overflow")).is_err());
2936
2937        let mut byte_bounded = DeferredResponse::default();
2938        byte_bounded
2939            .push(Bytes::from(vec![0; MAX_DEFERRED_RESPONSE_BYTES]))
2940            .unwrap();
2941        assert!(byte_bounded.push(Bytes::from_static(b"overflow")).is_err());
2942    }
2943
2944    #[tokio::test]
2945    async fn terminal_generate_error_uses_ordered_lane_frame() {
2946        let (shutdown, server) = test_server(RESPONSE_BUFFER_CAPACITY);
2947        let pool = test_pool();
2948        let context = PipelineContext::new(());
2949        let registered = server.register_response(context.context());
2950        let (info, provider) = registered.into_parts();
2951        let mut sender = pool.sender(context.context(), info).await.unwrap();
2952        sender
2953            .send_prologue(Some("generate failed".to_string()))
2954            .await
2955            .unwrap();
2956        match provider.await.unwrap() {
2957            Err(error) => assert_eq!(&*error, "generate failed"),
2958            Ok(_) => panic!("terminal error unexpectedly opened a response stream"),
2959        }
2960        shutdown.cancel();
2961    }
2962
2963    #[test]
2964    fn error_payload_legacy_utf8_stays_untyped() {
2965        let decoded = decode_error_payload(b"generate failed").unwrap();
2966        assert_eq!(&*decoded, "generate failed");
2967        assert!(decoded.typed_error.is_none());
2968    }
2969
2970    #[test]
2971    fn error_payload_round_trips_typed_refusal() {
2972        let original = StreamPrologueError::new(
2973            "Generate Error: multimodal input is not supported by this backend",
2974            DynamoError::builder()
2975                .error_type(ErrorType::Backend(BackendError::InvalidArgument))
2976                .message("multimodal input is not supported by this backend")
2977                .build(),
2978        );
2979        let payload = encode_error_payload(original.clone());
2980        assert_eq!(payload.first(), Some(&b'{'));
2981        let encoded = std::str::from_utf8(&payload).expect("typed payload is JSON UTF-8");
2982        assert!(
2983            encoded.contains(QUIC_TYPED_ERROR_KIND),
2984            "typed payload must carry the wire discriminant; got {encoded}"
2985        );
2986
2987        let decoded = decode_error_payload(&payload).unwrap();
2988        assert_eq!(decoded, original);
2989        assert_eq!(
2990            decoded.typed_error.map(|e| e.error_type()),
2991            Some(ErrorType::Backend(BackendError::InvalidArgument))
2992        );
2993    }
2994
2995    #[test]
2996    fn error_payload_python_envelope_is_not_a_prologue() {
2997        let envelope = br#"{"message":"unsupported media type","code":415}"#;
2998        let decoded = decode_error_payload(envelope).unwrap();
2999        assert_eq!(decoded.message.as_bytes(), envelope);
3000        assert!(
3001            decoded.typed_error.is_none(),
3002            "a Python HTTP envelope must stay the untyped message, not a prologue"
3003        );
3004    }
3005
3006    #[test]
3007    fn error_payload_legacy_json_with_decoy_error_field_is_preserved() {
3008        let envelope = br#"{"error":"failed","code":500}"#;
3009        let decoded = decode_error_payload(envelope).unwrap();
3010        assert_eq!(
3011            decoded.message.as_bytes(),
3012            envelope,
3013            "untagged legacy JSON must be preserved byte-for-byte"
3014        );
3015        assert!(
3016            decoded.typed_error.is_none(),
3017            "a decoy error field must not be classified as a typed prologue"
3018        );
3019    }
3020
3021    #[tokio::test]
3022    async fn typed_generate_error_survives_the_quic_error_frame() {
3023        let (shutdown, server) = test_server(RESPONSE_BUFFER_CAPACITY);
3024        let pool = test_pool();
3025        let context = PipelineContext::new(());
3026        let registered = server.register_response(context.context());
3027        let (info, provider) = registered.into_parts();
3028        let mut sender = pool.sender(context.context(), info).await.unwrap();
3029        sender
3030            .send_prologue_typed(Some(StreamPrologueError::new(
3031                "Generate Error: multimodal input is not supported by this backend",
3032                DynamoError::builder()
3033                    .error_type(ErrorType::Backend(BackendError::InvalidArgument))
3034                    .message("multimodal input is not supported by this backend")
3035                    .build(),
3036            )))
3037            .await
3038            .unwrap();
3039        match provider.await.unwrap() {
3040            Err(error) => {
3041                assert!(error.contains("multimodal input is not supported"));
3042                assert_eq!(
3043                    error.typed_error.as_ref().map(|e| e.error_type()),
3044                    Some(ErrorType::Backend(BackendError::InvalidArgument)),
3045                    "the worker's error type must survive the QUIC error frame"
3046                );
3047            }
3048            Ok(_) => panic!("terminal error unexpectedly opened a response stream"),
3049        }
3050        shutdown.cancel();
3051    }
3052
3053    #[tokio::test]
3054    async fn cancelled_sender_closes_only_its_logical_response() {
3055        let (shutdown, server) = test_server(RESPONSE_BUFFER_CAPACITY);
3056        let pool = test_pool();
3057
3058        let cancelled = PipelineContext::new(());
3059        let registered = server.register_response(cancelled.context());
3060        let (info, provider) = registered.into_parts();
3061        let mut sender = pool.sender(cancelled.context(), info).await.unwrap();
3062        sender.abort().await.unwrap();
3063        let mut receiver = provider.await.unwrap().unwrap();
3064        assert!(receiver.rx.recv().await.is_none());
3065
3066        let sibling = PipelineContext::new(());
3067        let registered = server.register_response(sibling.context());
3068        let (info, provider) = registered.into_parts();
3069        let mut sibling_sender = pool.sender(sibling.context(), info).await.unwrap();
3070        sibling_sender.send_prologue(None).await.unwrap();
3071        sibling_sender.finish().await.unwrap();
3072        let mut receiver = provider.await.unwrap().unwrap();
3073        assert!(receiver.rx.recv().await.is_none());
3074        assert!(only_bundle(&pool).is_healthy());
3075        shutdown.cancel();
3076    }
3077
3078    #[tokio::test]
3079    async fn physical_connection_failure_kills_all_and_reconnects_once() {
3080        let (shutdown, server) = test_server(RESPONSE_BUFFER_CAPACITY);
3081        let pool = Arc::new(test_pool());
3082
3083        let first_context = PipelineContext::new(());
3084        let first = server.register_response(first_context.context());
3085        let first_info = first.connection_info.clone();
3086        let mut first_sender = pool
3087            .sender(first_context.context(), first_info.clone())
3088            .await
3089            .unwrap();
3090        first_sender.send_prologue(None).await.unwrap();
3091        let old_connections = only_bundle(&pool)
3092            .connections
3093            .iter()
3094            .cloned()
3095            .collect::<Vec<_>>();
3096        let old_ids = old_connections
3097            .iter()
3098            .map(quinn::Connection::stable_id)
3099            .collect::<Vec<_>>();
3100        old_connections[0].close(CLOSE_CODE_INVARIANT, b"test lane failure");
3101        let first_engine_context = first_context.context();
3102        tokio::time::timeout(Duration::from_secs(1), first_engine_context.killed())
3103            .await
3104            .expect("connection failure should kill every active context");
3105        tokio::time::timeout(Duration::from_secs(1), async {
3106            while old_connections
3107                .iter()
3108                .any(|connection| connection.close_reason().is_none())
3109            {
3110                tokio::task::yield_now().await;
3111            }
3112        })
3113        .await
3114        .expect("one physical failure must close the complete client bundle");
3115        let mut registrations = Vec::new();
3116        let mut providers = Vec::new();
3117        for _ in 0..16 {
3118            let context = PipelineContext::new(());
3119            let registered = server.register_response(context.context());
3120            let (connection_info, provider) = registered.into_parts();
3121            registrations.push((context, connection_info));
3122            providers.push(provider);
3123        }
3124        let senders =
3125            futures::future::join_all(registrations.into_iter().map(|(context, info)| {
3126                let pool = pool.clone();
3127                async move { pool.sender(context.context(), info).await }
3128            }))
3129            .await;
3130        let errors = senders
3131            .iter()
3132            .filter_map(|result| result.as_ref().err().map(ToString::to_string))
3133            .collect::<Vec<_>>();
3134        assert!(errors.is_empty(), "replacement sender errors: {errors:?}");
3135        let replacement = only_bundle(&pool);
3136        assert_eq!(
3137            replacement.connections.len(),
3138            BULK_CONNECTIONS + PRIORITY_CONNECTIONS
3139        );
3140        assert!(
3141            replacement
3142                .connections
3143                .iter()
3144                .all(|connection| !old_ids.contains(&connection.stable_id()))
3145        );
3146        assert_eq!(replacement.lanes.len(), 8);
3147        drop(providers);
3148        shutdown.cancel();
3149    }
3150
3151    fn worker_runtime() -> tokio::runtime::Runtime {
3152        tokio::runtime::Builder::new_multi_thread()
3153            .worker_threads(1)
3154            .enable_all()
3155            .build()
3156            .unwrap()
3157    }
3158
3159    fn cached_bundles(pool: &QuicResponseClientPool) -> Vec<Arc<ClientConnectionBundle>> {
3160        pool.connections
3161            .iter()
3162            .filter_map(|entry| entry.current.load_full())
3163            .collect()
3164    }
3165
3166    /// Registers a response on the frontend and opens its worker sender on
3167    /// `runtime`, so the pool connects from that runtime.
3168    fn sender_on(
3169        runtime: &tokio::runtime::Runtime,
3170        pool: &QuicResponseClientPool,
3171        server: &QuicResponseServer,
3172    ) -> (
3173        PipelineContext<()>,
3174        QuicResponseSender,
3175        super::super::StreamProvider<StreamReceiver>,
3176    ) {
3177        runtime.block_on(async {
3178            let context = PipelineContext::new(());
3179            let registered = server.register_response(context.context());
3180            let (info, provider) = registered.into_parts();
3181            let sender =
3182                tokio::time::timeout(Duration::from_secs(5), pool.sender(context.context(), info))
3183                    .await
3184                    .expect("opening a QUIC response sender timed out")
3185                    .unwrap();
3186            (context, sender, provider)
3187        })
3188    }
3189
3190    /// Two worker runtimes serve one frontend through one pool, as two
3191    /// external runtimes in one process do. Stopping the first leaves the
3192    /// second runtime's bundle serving, and traffic on the second runtime
3193    /// alone removes the stopped runtime's entry.
3194    #[test]
3195    fn stopped_runtime_leaves_other_runtime_bundle_serving() {
3196        let frontend = worker_runtime();
3197        let (shutdown, server) = frontend.block_on(async { test_server(RESPONSE_BUFFER_CAPACITY) });
3198        let pool = Arc::new(test_pool());
3199        let first_runtime = worker_runtime();
3200        let second_runtime = worker_runtime();
3201
3202        let first = sender_on(&first_runtime, &pool, &server);
3203        let first_bundle = only_bundle(&pool);
3204        let second = sender_on(&second_runtime, &pool, &server);
3205        let bundles = cached_bundles(&pool);
3206        assert_eq!(bundles.len(), 2, "each Tokio runtime needs its own bundle");
3207        let second_bundle = bundles
3208            .into_iter()
3209            .find(|bundle| !Arc::ptr_eq(bundle, &first_bundle))
3210            .unwrap();
3211
3212        drop((first, second));
3213        first_runtime.shutdown_timeout(Duration::from_secs(5));
3214        assert!(second_bundle.is_healthy());
3215
3216        pool.next_prune_ms.store(0, Ordering::Relaxed);
3217        second_runtime.block_on(async {
3218            tokio::time::timeout(Duration::from_secs(30), async {
3219                let context = PipelineContext::new(());
3220                let registered = server.register_response(context.context());
3221                let (info, provider) = registered.into_parts();
3222                let mut sender = pool.sender(context.context(), info).await.unwrap();
3223                sender.send_prologue(None).await.unwrap();
3224                sender.send(Bytes::from_static(b"alive")).await.unwrap();
3225                sender.finish().await.unwrap();
3226                let mut receiver = provider.await.unwrap().unwrap();
3227                assert_eq!(
3228                    receiver.rx.recv().await.unwrap(),
3229                    Bytes::from_static(b"alive")
3230                );
3231                assert!(receiver.rx.recv().await.is_none());
3232            })
3233            .await
3234            .expect("a response on the surviving runtime timed out");
3235        });
3236        assert!(Arc::ptr_eq(&only_bundle(&pool), &second_bundle));
3237        frontend.block_on(async { shutdown.cancel() });
3238    }
3239
3240    #[tokio::test]
3241    async fn failed_connect_leaves_no_pool_entry() {
3242        let pool = test_pool();
3243        let key = ConnectionKey {
3244            address: "not-a-socket-address".to_string(),
3245            frontend_id: "unreachable".to_string(),
3246            certificate_sha256: "00".repeat(32),
3247            runtime: tokio::runtime::Handle::current().id(),
3248        };
3249        assert!(pool.connection(key).await.is_err());
3250        assert!(pool.connections.is_empty());
3251    }
3252
3253    #[tokio::test]
3254    async fn different_connection_keys_initialize_in_parallel() {
3255        let (shutdown, server) = test_server(RESPONSE_BUFFER_CAPACITY);
3256        let pool = test_pool();
3257
3258        let blocked_key = ConnectionKey {
3259            address: "127.0.0.1:1".to_string(),
3260            frontend_id: "blocked".to_string(),
3261            certificate_sha256: "00".repeat(32),
3262            runtime: tokio::runtime::Handle::current().id(),
3263        };
3264        let blocked_entry = pool
3265            .connections
3266            .entry(blocked_key)
3267            .or_insert_with(|| Arc::new(ClientPoolEntry::new()))
3268            .clone();
3269        let blocked_reconnect = blocked_entry.reconnect.lock().await;
3270
3271        let context = PipelineContext::new(());
3272        let registered = server.register_response(context.context());
3273        let (info, provider) = registered.into_parts();
3274        let sender =
3275            tokio::time::timeout(Duration::from_secs(1), pool.sender(context.context(), info))
3276                .await
3277                .expect("one frontend key must not wait for another key's reconnect mutex")
3278                .unwrap();
3279
3280        drop(sender);
3281        drop(provider);
3282        drop(blocked_reconnect);
3283        shutdown.cancel();
3284    }
3285
3286    #[tokio::test]
3287    async fn bundle_failure_before_prologue_resolves_pending_provider() {
3288        let (shutdown, server) = test_server(RESPONSE_BUFFER_CAPACITY);
3289        let pool = test_pool();
3290        let context = PipelineContext::new(());
3291        let registered = server.register_response(context.context());
3292        let (info, provider) = registered.into_parts();
3293        let _sender = pool.sender(context.context(), info).await.unwrap();
3294        let bundle = only_bundle(&pool);
3295        bundle.connections[0].close(CLOSE_CODE_INVARIANT, b"test pre-prologue failure");
3296
3297        let result = tokio::time::timeout(Duration::from_secs(2), provider)
3298            .await
3299            .expect("pending provider must resolve after bundle failure")
3300            .unwrap();
3301        let error = match result {
3302            Err(error) => error,
3303            Ok(_) => panic!("pre-prologue bundle failure unexpectedly opened a stream"),
3304        };
3305        assert!(error.contains("bundle failed"));
3306        tokio::time::timeout(Duration::from_secs(2), context.context().killed())
3307            .await
3308            .expect("bundle failure must kill the worker request context");
3309        shutdown.cancel();
3310    }
3311
3312    #[tokio::test]
3313    async fn full_mailbox_resets_only_its_registration() {
3314        let state = Arc::new(ServerState::default());
3315        let bundle_id = Uuid::new_v4();
3316        let full_id = Uuid::new_v4();
3317        let sibling_id = Uuid::new_v4();
3318        let (full_tx, mut full_rx) = mpsc::channel(1);
3319        full_tx.try_send(Bytes::from_static(b"occupied")).unwrap();
3320        let (sibling_tx, mut sibling_rx) = mpsc::channel(1);
3321        for (registration_id, sender) in [(full_id, full_tx), (sibling_id, sibling_tx)] {
3322            state.registration(registration_id).lock().active.insert(
3323                registration_id,
3324                ActiveResponse {
3325                    sender,
3326                    monitor_cancel: CancellationToken::new(),
3327                    bundle_id,
3328                    priority_ready: true,
3329                    priority_draining: false,
3330                    deferred: DeferredResponse::default(),
3331                },
3332            );
3333        }
3334        let instance = EndpointInstanceId {
3335            namespace: "n".to_string(),
3336            component: "c".to_string(),
3337            endpoint: "e".to_string(),
3338            instance_id: 1,
3339        };
3340        {
3341            let mut indexes = state.indexes.lock();
3342            indexes
3343                .registration_instance
3344                .insert(full_id, instance.clone());
3345            indexes
3346                .instance_registrations
3347                .insert(instance.clone(), vec![full_id]);
3348        }
3349        let (control_tx, mut control_rx) = mpsc::channel(4);
3350
3351        process_server_frame(
3352            Frame::new(FrameKind::Data, full_id, Bytes::from_static(b"reset")),
3353            bundle_id,
3354            &state,
3355            &control_tx,
3356            1,
3357        )
3358        .await
3359        .unwrap();
3360        assert_eq!(control_rx.recv().await.unwrap().kind, FrameKind::Reset);
3361        assert!(
3362            !state
3363                .registration(full_id)
3364                .lock()
3365                .active
3366                .contains_key(&full_id)
3367        );
3368        assert!(
3369            !state
3370                .indexes
3371                .lock()
3372                .registration_instance
3373                .contains_key(&full_id)
3374        );
3375        assert_eq!(
3376            full_rx.recv().await.unwrap(),
3377            Bytes::from_static(b"occupied")
3378        );
3379
3380        process_server_frame(
3381            Frame::new(FrameKind::Data, sibling_id, Bytes::from_static(b"sibling")),
3382            bundle_id,
3383            &state,
3384            &control_tx,
3385            1,
3386        )
3387        .await
3388        .unwrap();
3389        assert_eq!(
3390            sibling_rx.recv().await.unwrap(),
3391            Bytes::from_static(b"sibling")
3392        );
3393    }
3394
3395    #[tokio::test]
3396    async fn priority_delivery_failures_remove_all_registration_indexes() {
3397        for deferred_failure in [false, true] {
3398            let state = Arc::new(ServerState::default());
3399            let bundle_id = Uuid::new_v4();
3400            let registration_id = Uuid::new_v4();
3401            let (response_tx, _response_rx) = mpsc::channel(1);
3402            let mut deferred = DeferredResponse::default();
3403            if deferred_failure {
3404                deferred.push(Bytes::from_static(b"bulk")).unwrap();
3405            } else {
3406                response_tx
3407                    .try_send(Bytes::from_static(b"occupied"))
3408                    .unwrap();
3409            }
3410            state.registration(registration_id).lock().active.insert(
3411                registration_id,
3412                ActiveResponse {
3413                    sender: response_tx,
3414                    monitor_cancel: CancellationToken::new(),
3415                    bundle_id,
3416                    priority_ready: false,
3417                    priority_draining: false,
3418                    deferred,
3419                },
3420            );
3421            let instance = EndpointInstanceId {
3422                namespace: "n".to_string(),
3423                component: "c".to_string(),
3424                endpoint: "e".to_string(),
3425                instance_id: registration_id.as_u128() as u64,
3426            };
3427            {
3428                let mut indexes = state.indexes.lock();
3429                indexes
3430                    .registration_instance
3431                    .insert(registration_id, instance.clone());
3432                indexes
3433                    .instance_registrations
3434                    .insert(instance.clone(), vec![registration_id]);
3435            }
3436            let (control_tx, mut control_rx) = mpsc::channel(4);
3437
3438            process_server_frame(
3439                Frame::new(
3440                    FrameKind::FirstData,
3441                    registration_id,
3442                    Bytes::from_static(b"first"),
3443                ),
3444                bundle_id,
3445                &state,
3446                &control_tx,
3447                1,
3448            )
3449            .await
3450            .unwrap();
3451
3452            assert_eq!(control_rx.recv().await.unwrap().kind, FrameKind::Reset);
3453            assert!(
3454                !state
3455                    .registration(registration_id)
3456                    .lock()
3457                    .active
3458                    .contains_key(&registration_id)
3459            );
3460            let indexes = state.indexes.lock();
3461            assert!(!indexes.registration_instance.contains_key(&registration_id));
3462            assert!(!indexes.instance_registrations.contains_key(&instance));
3463        }
3464    }
3465
3466    #[test]
3467    fn fingerprint_round_trip() {
3468        let fingerprint = [0x5a; 32];
3469        assert_eq!(
3470            decode_fingerprint(&encode_hex(&fingerprint)).unwrap(),
3471            fingerprint
3472        );
3473        assert!(decode_fingerprint(&"é".repeat(32)).is_err());
3474    }
3475
3476    #[tokio::test]
3477    async fn server_drop_cancels_accept_loops_and_closes_endpoints() {
3478        let (shutdown, server) = test_server(1);
3479        assert_eq!(server.endpoints.len(), SERVER_ENDPOINTS);
3480        let accept_shutdown = server.shutdown.clone();
3481        drop(server);
3482        assert!(accept_shutdown.is_cancelled());
3483        assert!(!shutdown.is_cancelled());
3484    }
3485
3486    #[cfg(target_os = "linux")]
3487    #[test]
3488    fn primary_udp_bind_is_exclusive_before_reuseport_siblings_join() {
3489        let ephemeral = "127.0.0.1:0".parse().unwrap();
3490        let primary = bind_server_udp(ephemeral, false).unwrap();
3491        let bound = primary.local_addr().unwrap();
3492        let sibling = bind_server_udp(bound, true).unwrap();
3493        assert_eq!(sibling.local_addr().unwrap(), bound);
3494
3495        let other_primary = bind_server_udp(ephemeral, false).unwrap();
3496        assert_ne!(other_primary.local_addr().unwrap(), bound);
3497    }
3498}