1#![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
83pub 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 #[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
151fn map_error_code(code: u64) -> application::Error {
159 const FALLBACK: u32 = 0x102;
162
163 application::Error::new(code).unwrap_or_else(|_| application::Error::from(FALLBACK))
164}
165
166fn 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
185fn 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
198fn 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
210fn 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#[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
330pub 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#[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 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
465pub struct SendStream<B: Buf> {
467 stream: s2n_quic::stream::SendStream,
468 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 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 if let Some(mut data) = self.buf.take() {
529 loop {
530 let len = data.chunk().len();
531 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 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 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 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 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}