Skip to main content

tachyon_quic/
lib.rs

1//! An implementation of the `h3::quic` traits for `s2n-quic`.
2//!
3//! This crate provides the binding between `s2n-quic` and `h3` (HTTP/3 implementation).
4//! Wrap an accepted or connected [`s2n_quic::Connection`] in [`Connection`] and hand
5//! it to `h3`; everything else is `h3`'s own API.
6//!
7//! # Example
8//!
9//! ```no_run
10//! use bytes::Bytes;
11//! use tachyon_quic::{s2n_quic::Server, Connection};
12//!
13//! # async fn run(cert: &str, key: &str) -> Result<(), Box<dyn std::error::Error>> {
14//! let mut quic_server = Server::builder()
15//!     .with_tls((cert, key))?
16//!     .with_io("127.0.0.1:443")?
17//!     .start()?;
18//!
19//! while let Some(conn) = quic_server.accept().await {
20//!     tokio::spawn(async move {
21//!         // `h3` needs to know which buffer type response bodies are sent as;
22//!         // it cannot be inferred from the connection alone.
23//!         let mut h3_conn =
24//!             tachyon_quic::h3::server::Connection::<_, Bytes>::new(Connection::new(conn)).await?;
25//!
26//!         while let Some(resolver) = h3_conn.accept().await? {
27//!             let (_req, mut stream) = resolver.resolve_request().await?;
28//!             // ... handle the request ...
29//!         }
30//!
31//!         Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
32//!     });
33//! }
34//! # Ok(())
35//! # }
36//! ```
37//!
38//! # Features
39//!
40//! - `fips` — builds `s2n-quic` against the FIPS-validated `aws-lc` module.
41//! - `tracing` — emits `tracing` spans at `TRACE` level around each trait method.
42//!
43//! Neither is enabled by default.
44//!
45//! # Limitations
46//!
47//! [`h3::quic::SendStreamUnframed`] is not implemented, so the parts of `h3`
48//! that require unframed writes — its [`AsyncWrite`] adapters and
49//! `h3-webtransport` — cannot be used with this backend. Everything reachable
50//! through `h3::client` and `h3::server` works. The gap surfaces as an
51//! unsatisfied trait bound at compile time, not as a runtime failure.
52//!
53//! `s2n-quic` cannot carry the HTTP/3 reason phrase in `CONNECTION_CLOSE`, so
54//! [`quic::OpenStreams::close`] sends the error code and drops the reason.
55//!
56//! [`AsyncWrite`]: https://docs.rs/tokio/latest/tokio/io/trait.AsyncWrite.html
57
58#![forbid(unsafe_code, elided_lifetimes_in_paths)]
59#![allow(clippy::multiple_crate_versions)]
60
61#[cfg(doctest)]
62#[doc = include_str!("../README.md")]
63struct ReadmeDoctests;
64
65pub use h3;
66pub use s2n_quic;
67
68use bytes::{Buf, Bytes};
69use core::task::ready;
70use h3::quic::{self, ConnectionErrorIncoming, StreamErrorIncoming, StreamId, WriteBuf};
71use s2n_quic::{
72    application,
73    stream::{BidirectionalStream, ReceiveStream},
74};
75use std::{
76    sync::Arc,
77    task::{self, Poll},
78};
79
80#[cfg(feature = "tracing")]
81use tracing::instrument;
82
83/// A QUIC connection wrapper that implements `h3::quic::Connection`.
84pub struct Connection {
85    conn: s2n_quic::connection::Handle,
86    bidi_acceptor: s2n_quic::connection::BidirectionalStreamAcceptor,
87    recv_acceptor: s2n_quic::connection::ReceiveStreamAcceptor,
88}
89
90impl std::fmt::Debug for Connection {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        f.debug_struct("Connection")
93            .field("conn", &self.conn)
94            .finish_non_exhaustive()
95    }
96}
97
98impl Connection {
99    /// Creates a new `Connection` wrapper.
100    #[must_use]
101    pub fn new(new_conn: s2n_quic::Connection) -> Self {
102        let (handle, acceptor) = new_conn.split();
103        let (bidi, recv) = acceptor.split();
104
105        Self {
106            conn: handle,
107            bidi_acceptor: bidi,
108            recv_acceptor: recv,
109        }
110    }
111}
112
113fn map_conn_err(e: s2n_quic::connection::Error) -> ConnectionErrorIncoming {
114    match e {
115        s2n_quic::connection::Error::IdleTimerExpired { .. } => ConnectionErrorIncoming::Timeout,
116        s2n_quic::connection::Error::Application { error, .. } => {
117            ConnectionErrorIncoming::ApplicationClose {
118                error_code: error.into(),
119            }
120        }
121        s2n_quic::connection::Error::Closed { .. } => ConnectionErrorIncoming::ApplicationClose {
122            error_code: h3::error::Code::H3_NO_ERROR.value(),
123        },
124        _ => ConnectionErrorIncoming::Undefined(Arc::new(e)),
125    }
126}
127
128fn map_stream_err(e: s2n_quic::stream::Error) -> StreamErrorIncoming {
129    match e {
130        s2n_quic::stream::Error::StreamReset { error, .. } => {
131            StreamErrorIncoming::StreamTerminated {
132                error_code: error.into(),
133            }
134        }
135        s2n_quic::stream::Error::ConnectionError { error, .. } => {
136            let conn_err = map_conn_err(error);
137            StreamErrorIncoming::ConnectionErrorIncoming {
138                connection_error: conn_err,
139            }
140        }
141        _ => StreamErrorIncoming::Unknown(Box::new(e)),
142    }
143}
144
145fn map_open_err(e: s2n_quic::connection::Error) -> StreamErrorIncoming {
146    StreamErrorIncoming::ConnectionErrorIncoming {
147        connection_error: map_conn_err(e),
148    }
149}
150
151/// Converts an HTTP/3 error code into a QUIC application error code.
152///
153/// Every code HTTP/3 defines fits in a QUIC `VarInt`, so the fallback is
154/// unreachable for codes originating inside `h3`. It exists because
155/// `quic::SendStream::reset` and `quic::RecvStream::stop_sending` take an
156/// arbitrary `u64`. `H3_INTERNAL_ERROR` is used rather than
157/// `application::Error::UNKNOWN`, which is `0` and not a valid HTTP/3 code.
158fn map_error_code(code: u64) -> application::Error {
159    /// `h3::error::Code::H3_INTERNAL_ERROR`, which is not available as a
160    /// `const` in a form `application::Error` can be built from.
161    const FALLBACK: u32 = 0x102;
162
163    application::Error::new(code).unwrap_or_else(|_| application::Error::from(FALLBACK))
164}
165
166/// Converts an `s2n-quic` stream ID into an `h3` [`StreamId`].
167///
168/// `s2n-quic` only ever produces IDs below 2^62, the QUIC `VarInt` ceiling,
169/// which is exactly the range `StreamId` accepts, so the fallback is
170/// unreachable in practice. It exists because `StreamId` has no infallible
171/// constructor reachable from here — `From<VarInt>` would serve, but `h3`
172/// gates `VarInt` behind a feature this crate does not enable.
173///
174/// Falling back to 0 rather than panicking trades a misattributed stream for a
175/// live connection. That is the better failure for a case that cannot happen,
176/// but note that 0 is a valid ID belonging to some *other* stream, not a
177/// neutral sentinel: `h3` correlates requests by this value.
178fn map_stream_id(id: u64) -> StreamId {
179    StreamId::try_from(id).unwrap_or_else(|_| {
180        #[allow(clippy::unwrap_used)]
181        StreamId::try_from(0u64).unwrap()
182    })
183}
184
185/// Shared body of `quic::OpenStreams::poll_open_bidi`, which `Connection` and
186/// `OpenStreams` both implement against the same underlying handle.
187fn poll_open_bidi_on<B>(
188    handle: &mut s2n_quic::connection::Handle,
189    cx: &mut task::Context<'_>,
190) -> Poll<Result<BidiStream<B>, StreamErrorIncoming>>
191where
192    B: Buf,
193{
194    let stream = ready!(handle.poll_open_bidirectional_stream(cx)).map_err(map_open_err)?;
195    Poll::Ready(Ok(stream.into()))
196}
197
198/// Shared body of `quic::OpenStreams::poll_open_send`.
199fn poll_open_send_on<B>(
200    handle: &mut s2n_quic::connection::Handle,
201    cx: &mut task::Context<'_>,
202) -> Poll<Result<SendStream<B>, StreamErrorIncoming>>
203where
204    B: Buf,
205{
206    let stream = ready!(handle.poll_open_send_stream(cx)).map_err(map_open_err)?;
207    Poll::Ready(Ok(stream.into()))
208}
209
210/// Shared body of `quic::OpenStreams::close`.
211///
212/// `s2n-quic` has no way to carry the HTTP/3 reason phrase in `CONNECTION_CLOSE`,
213/// so the reason is dropped and only the error code reaches the peer.
214fn close_conn(handle: &s2n_quic::connection::Handle, code: h3::error::Code) {
215    handle.close(map_error_code(code.value()));
216}
217
218impl<B> quic::Connection<B> for Connection
219where
220    B: Buf,
221{
222    type RecvStream = RecvStream;
223    type OpenStreams = OpenStreams;
224
225    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
226    fn poll_accept_recv(
227        &mut self,
228        cx: &mut task::Context<'_>,
229    ) -> Poll<Result<Self::RecvStream, ConnectionErrorIncoming>> {
230        let Some(recv) =
231            ready!(self.recv_acceptor.poll_accept_receive_stream(cx)).map_err(map_conn_err)?
232        else {
233            return Poll::Ready(Err(ConnectionErrorIncoming::ApplicationClose {
234                error_code: h3::error::Code::H3_NO_ERROR.value(),
235            }));
236        };
237        Poll::Ready(Ok(Self::RecvStream::new(recv)))
238    }
239
240    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
241    fn poll_accept_bidi(
242        &mut self,
243        cx: &mut task::Context<'_>,
244    ) -> Poll<Result<Self::BidiStream, ConnectionErrorIncoming>> {
245        let Some(bidi_stream) = ready!(self.bidi_acceptor.poll_accept_bidirectional_stream(cx))
246            .map_err(map_conn_err)?
247        else {
248            return Poll::Ready(Err(ConnectionErrorIncoming::ApplicationClose {
249                error_code: h3::error::Code::H3_NO_ERROR.value(),
250            }));
251        };
252        let (recv, send) = bidi_stream.split();
253        Poll::Ready(Ok(Self::BidiStream {
254            send: Self::SendStream::new(send),
255            recv: Self::RecvStream::new(recv),
256        }))
257    }
258
259    fn opener(&self) -> Self::OpenStreams {
260        OpenStreams {
261            conn: self.conn.clone(),
262        }
263    }
264}
265
266impl<B> quic::OpenStreams<B> for Connection
267where
268    B: Buf,
269{
270    type BidiStream = BidiStream<B>;
271    type SendStream = SendStream<B>;
272
273    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
274    fn poll_open_bidi(
275        &mut self,
276        cx: &mut task::Context<'_>,
277    ) -> Poll<Result<Self::BidiStream, StreamErrorIncoming>> {
278        poll_open_bidi_on(&mut self.conn, cx)
279    }
280
281    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
282    fn poll_open_send(
283        &mut self,
284        cx: &mut task::Context<'_>,
285    ) -> Poll<Result<Self::SendStream, StreamErrorIncoming>> {
286        poll_open_send_on(&mut self.conn, cx)
287    }
288
289    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
290    fn close(&mut self, code: h3::error::Code, _reason: &[u8]) {
291        close_conn(&self.conn, code);
292    }
293}
294
295/// A handle to open streams on a connection.
296#[derive(Clone, Debug)]
297pub struct OpenStreams {
298    conn: s2n_quic::connection::Handle,
299}
300
301impl<B> quic::OpenStreams<B> for OpenStreams
302where
303    B: Buf,
304{
305    type BidiStream = BidiStream<B>;
306    type SendStream = SendStream<B>;
307
308    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
309    fn poll_open_bidi(
310        &mut self,
311        cx: &mut task::Context<'_>,
312    ) -> Poll<Result<Self::BidiStream, StreamErrorIncoming>> {
313        poll_open_bidi_on(&mut self.conn, cx)
314    }
315
316    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
317    fn poll_open_send(
318        &mut self,
319        cx: &mut task::Context<'_>,
320    ) -> Poll<Result<Self::SendStream, StreamErrorIncoming>> {
321        poll_open_send_on(&mut self.conn, cx)
322    }
323
324    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
325    fn close(&mut self, code: h3::error::Code, _reason: &[u8]) {
326        close_conn(&self.conn, code);
327    }
328}
329
330/// A bidirectional QUIC stream.
331pub struct BidiStream<B>
332where
333    B: Buf,
334{
335    send: SendStream<B>,
336    recv: RecvStream,
337}
338
339impl<B> std::fmt::Debug for BidiStream<B>
340where
341    B: Buf,
342{
343    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344        f.debug_struct("BidiStream")
345            .field("send", &self.send)
346            .field("recv", &self.recv)
347            .finish()
348    }
349}
350
351impl<B> quic::BidiStream<B> for BidiStream<B>
352where
353    B: Buf,
354{
355    type SendStream = SendStream<B>;
356    type RecvStream = RecvStream;
357
358    fn split(self) -> (Self::SendStream, Self::RecvStream) {
359        (self.send, self.recv)
360    }
361}
362
363impl<B> quic::RecvStream for BidiStream<B>
364where
365    B: Buf,
366{
367    type Buf = Bytes;
368
369    fn poll_data(
370        &mut self,
371        cx: &mut task::Context<'_>,
372    ) -> Poll<Result<Option<Self::Buf>, StreamErrorIncoming>> {
373        self.recv.poll_data(cx)
374    }
375
376    fn stop_sending(&mut self, error_code: u64) {
377        self.recv.stop_sending(error_code);
378    }
379
380    fn recv_id(&self) -> StreamId {
381        self.recv.recv_id()
382    }
383}
384
385impl<B> quic::SendStream<B> for BidiStream<B>
386where
387    B: Buf,
388{
389    fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), StreamErrorIncoming>> {
390        self.send.poll_ready(cx)
391    }
392
393    fn poll_finish(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), StreamErrorIncoming>> {
394        self.send.poll_finish(cx)
395    }
396
397    fn reset(&mut self, reset_code: u64) {
398        self.send.reset(reset_code);
399    }
400
401    fn send_data<D: Into<WriteBuf<B>>>(&mut self, data: D) -> Result<(), StreamErrorIncoming> {
402        self.send.send_data(data)
403    }
404
405    fn send_id(&self) -> StreamId {
406        self.send.send_id()
407    }
408}
409
410impl<B> From<BidirectionalStream> for BidiStream<B>
411where
412    B: Buf,
413{
414    fn from(bidi: BidirectionalStream) -> Self {
415        let (recv, send) = bidi.split();
416        Self {
417            send: send.into(),
418            recv: recv.into(),
419        }
420    }
421}
422
423/// A receive QUIC stream.
424#[derive(Debug)]
425pub struct RecvStream {
426    stream: ReceiveStream,
427}
428
429impl RecvStream {
430    const fn new(stream: ReceiveStream) -> Self {
431        Self { stream }
432    }
433}
434
435impl quic::RecvStream for RecvStream {
436    type Buf = Bytes;
437
438    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
439    fn poll_data(
440        &mut self,
441        cx: &mut task::Context<'_>,
442    ) -> Poll<Result<Option<Self::Buf>, StreamErrorIncoming>> {
443        let buf = ready!(self.stream.poll_receive(cx)).map_err(map_stream_err)?;
444        Ok(buf).into()
445    }
446
447    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
448    fn stop_sending(&mut self, error_code: u64) {
449        // Fails only if the stream is already closed, which is not actionable.
450        let _ = self.stream.stop_sending(map_error_code(error_code));
451    }
452
453    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
454    fn recv_id(&self) -> StreamId {
455        map_stream_id(self.stream.id())
456    }
457}
458
459impl From<ReceiveStream> for RecvStream {
460    fn from(recv: ReceiveStream) -> Self {
461        Self::new(recv)
462    }
463}
464
465/// A send QUIC stream.
466pub struct SendStream<B: Buf> {
467    stream: s2n_quic::stream::SendStream,
468    /// Chunks flattened out of `buf`, waiting to be handed to `s2n-quic`.
469    ///
470    /// Empty exactly when there is nothing left to flush; the elements before
471    /// `sent` have already been accepted by the stream. The allocation is
472    /// reused across sends.
473    chunks: Vec<Bytes>,
474    sent: usize,
475    buf: Option<WriteBuf<B>>,
476}
477
478impl<B> std::fmt::Debug for SendStream<B>
479where
480    B: Buf,
481{
482    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
483        f.debug_struct("SendStream")
484            .field("stream", &self.stream)
485            .field(
486                "pending_chunks",
487                &self.chunks.len().saturating_sub(self.sent),
488            )
489            .field("buf", &self.buf.as_ref().map(|_| "WriteBuf"))
490            .finish()
491    }
492}
493
494impl<B> SendStream<B>
495where
496    B: Buf,
497{
498    const fn new(stream: s2n_quic::stream::SendStream) -> Self {
499        Self {
500            stream,
501            chunks: Vec::new(),
502            sent: 0,
503            buf: None,
504        }
505    }
506
507    /// Returns `true` while data handed to `send_data` has not been fully
508    /// accepted by the underlying stream.
509    const fn is_flushing(&self) -> bool {
510        self.buf.is_some() || !self.chunks.is_empty()
511    }
512}
513
514impl<B> quic::SendStream<B> for SendStream<B>
515where
516    B: Buf,
517{
518    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
519    fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), StreamErrorIncoming>> {
520        // Flatten the pending `WriteBuf` — typically a frame header followed by
521        // the payload — so the whole frame goes out in one vectored write
522        // instead of one `poll_send` per contiguous chunk.
523        //
524        // `WriteBuf` does not override `Buf::copy_to_bytes`, so each chunk is
525        // allocated and copied here even when `B` is already `Bytes`. That copy
526        // cannot be avoided without access to `WriteBuf`'s inner buffer, which
527        // `h3` does not expose.
528        if let Some(mut data) = self.buf.take() {
529            loop {
530                let len = data.chunk().len();
531                // `Buf` guarantees a non-empty chunk while data remains, but
532                // don't spin forever if some `B` breaks that contract.
533                if len == 0 {
534                    break;
535                }
536                self.chunks.push(data.copy_to_bytes(len));
537            }
538        }
539
540        if self.sent < self.chunks.len() {
541            let pending = self.chunks.get_mut(self.sent..).unwrap_or_default();
542            let sent =
543                ready!(self.stream.poll_send_vectored(pending, cx)).map_err(map_stream_err)?;
544            self.sent = self.sent.saturating_add(sent);
545
546            if self.sent < self.chunks.len() {
547                // Defensive: `s2n-quic` documents that a vectored write may
548                // accept only some of the chunks, registering the waker for the
549                // rest. In practice it either takes all of them or returns
550                // `Pending` above, so this branch is rarely taken.
551                return Poll::Pending;
552            }
553        }
554
555        debug_assert!(self.chunks.iter().all(Bytes::is_empty));
556        self.chunks.clear();
557        self.sent = 0;
558
559        Poll::Ready(Ok(()))
560    }
561
562    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
563    fn send_data<D: Into<WriteBuf<B>>>(&mut self, data: D) -> Result<(), StreamErrorIncoming> {
564        if self.is_flushing() {
565            // `h3` documents `InternalError` as the variant for a fault inside a
566            // `quic` trait implementation, and handles `Unknown` exactly like a
567            // peer stream reset. Reporting this as `Unknown` would quietly
568            // degrade a caller-contract violation into a routine stream
569            // termination instead of surfacing it.
570            return Err(StreamErrorIncoming::ConnectionErrorIncoming {
571                connection_error: ConnectionErrorIncoming::InternalError(
572                    "send_data called before poll_ready completed".to_string(),
573                ),
574            });
575        }
576        self.buf = Some(data.into());
577        Ok(())
578    }
579
580    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
581    fn poll_finish(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), StreamErrorIncoming>> {
582        ready!(self.poll_ready(cx))?;
583        self.stream.finish().map_err(map_stream_err)?;
584        Ok(()).into()
585    }
586
587    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
588    fn reset(&mut self, reset_code: u64) {
589        // Fails only if the stream is already closed, which is not actionable.
590        let _ = self.stream.reset(map_error_code(reset_code));
591    }
592
593    #[cfg_attr(feature = "tracing", instrument(skip_all, level = "trace"))]
594    fn send_id(&self) -> StreamId {
595        map_stream_id(self.stream.id())
596    }
597}
598
599impl<B> From<s2n_quic::stream::SendStream> for SendStream<B>
600where
601    B: Buf,
602{
603    fn from(send: s2n_quic::stream::SendStream) -> Self {
604        Self::new(send)
605    }
606}
607
608#[cfg(test)]
609mod tests {
610    use super::map_error_code;
611
612    #[test]
613    fn error_code_fallback_is_h3_internal_error() {
614        // `map_error_code` hardcodes H3_INTERNAL_ERROR because `h3` does not
615        // expose it in a form `application::Error` can be built from in const
616        // context. Keep the two in sync.
617        let fallback = map_error_code(u64::MAX);
618        assert_eq!(
619            *fallback,
620            h3::error::Code::H3_INTERNAL_ERROR.value(),
621            "the out-of-range fallback must stay equal to H3_INTERNAL_ERROR"
622        );
623    }
624
625    #[test]
626    fn h3_error_codes_round_trip() {
627        for code in [
628            h3::error::Code::H3_NO_ERROR,
629            h3::error::Code::H3_INTERNAL_ERROR,
630            h3::error::Code::H3_REQUEST_CANCELLED,
631            h3::error::Code::H3_EXCESSIVE_LOAD,
632        ] {
633            assert_eq!(
634                *map_error_code(code.value()),
635                code.value(),
636                "{code} must survive the conversion to a QUIC application error"
637            );
638        }
639    }
640}