Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions rs/web-transport-iroh/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,27 @@ pub enum SessionError {
SendDatagramError(#[error(source, from, std_err)] endpoint::SendDatagramError),
}

/// The QUIC code to reset or stop a stream with. Raw QUIC sends the code as is, while
/// HTTP/3 maps it into its own code space.
pub(crate) fn encode_stream_code(code: u32, raw: bool) -> endpoint::VarInt {
if raw {
return code.into();
}
endpoint::VarInt::try_from(web_transport_proto::error_to_http3(code)).unwrap()
}

/// Decode the peer's QUIC code for a stream reset or stop, or None if it is not one.
pub(crate) fn decode_stream_code(code: endpoint::VarInt, raw: bool) -> Option<u32> {
let code = code.into_inner();
// An older raw peer maps its codes into the HTTP/3 range too. No u32 reaches that
// range, so the mapped form cannot be mistaken for a raw code.
match web_transport_proto::error_from_http3(code) {
Some(code) => Some(code),
None if raw => u32::try_from(code).ok(),
None => None,
}
}

/// An error that can occur when reading/writing the WebTransport stream header.
#[stack_error(derive, from_sources)]
#[derive(Clone)]
Expand Down
53 changes: 42 additions & 11 deletions rs/web-transport-iroh/src/recv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,55 +7,86 @@ use std::{
use bytes::Bytes;
use iroh::endpoint;

use crate::{ClosedStream, ReadError, ReadExactError, ReadToEndError, SessionError};
use crate::{
ClosedStream, ReadError, ReadExactError, ReadToEndError, SessionError,
error::{decode_stream_code, encode_stream_code},
};

/// A stream that can be used to receive bytes. See [`iroh::endpoint::RecvStream`].
#[derive(Debug)]
pub struct RecvStream {
inner: endpoint::RecvStream,
// Raw QUIC carries stream codes as is; HTTP/3 maps them into its own code space.
raw: bool,
}

impl RecvStream {
pub(crate) fn new(stream: endpoint::RecvStream) -> Self {
Self { inner: stream }
pub(crate) fn new(stream: endpoint::RecvStream, raw: bool) -> Self {
Self { inner: stream, raw }
}

/// Decode the peer's reset code with the session's code space.
fn map_error(&self, e: endpoint::ReadError) -> ReadError {
match e {
endpoint::ReadError::Reset(code) => match decode_stream_code(code, self.raw) {
Some(code) => ReadError::Reset(code),
None => ReadError::InvalidReset(code),
},
e => e.into(),
}
}

/// Tell the other end to stop sending data with the given error code. See [`iroh::endpoint::RecvStream::stop`].
/// This is a u32 with WebTransport since it shares the error space with HTTP/3.
/// A raw QUIC session sends the code as is.
pub fn stop(&mut self, code: u32) -> Result<(), endpoint::ClosedStream> {
let code = web_transport_proto::error_to_http3(code);
let code = endpoint::VarInt::try_from(code).unwrap();
let code = encode_stream_code(code, self.raw);
self.inner.stop(code)
}

// Unfortunately, we have to wrap ReadError for a bunch of functions.

/// Read some data into the buffer and return the amount read. See [`iroh::endpoint::RecvStream::read`].
pub async fn read(&mut self, buf: &mut [u8]) -> Result<Option<usize>, ReadError> {
self.inner.read(buf).await.map_err(Into::into)
self.inner.read(buf).await.map_err(|e| self.map_error(e))
}

/// Fill the entire buffer with data. See [`iroh::endpoint::RecvStream::read_exact`].
pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), ReadExactError> {
self.inner.read_exact(buf).await.map_err(Into::into)
self.inner.read_exact(buf).await.map_err(|e| match e {
endpoint::ReadExactError::ReadError(e) => self.map_error(e).into(),
e => e.into(),
})
}

/// Read a chunk of data from the stream. See [`iroh::endpoint::RecvStream::read_chunk`].
pub async fn read_chunk(&mut self, max_length: usize) -> Result<Option<Bytes>, ReadError> {
self.inner.read_chunk(max_length).await.map_err(Into::into)
self.inner
.read_chunk(max_length)
.await
.map_err(|e| self.map_error(e))
}

/// Read chunks of data from the stream. See [`iroh::endpoint::RecvStream::read_many_chunks`].
pub async fn read_many_chunks(
&mut self,
bufs: &mut [Bytes],
) -> Result<Option<usize>, ReadError> {
self.inner.read_many_chunks(bufs).await.map_err(Into::into)
self.inner
.read_many_chunks(bufs)
.await
.map_err(|e| self.map_error(e))
}

/// Read until the end of the stream or the limit is hit. See [`iroh::endpoint::RecvStream::read_to_end`].
pub async fn read_to_end(&mut self, size_limit: usize) -> Result<Vec<u8>, ReadToEndError> {
self.inner.read_to_end(size_limit).await.map_err(Into::into)
self.inner
.read_to_end(size_limit)
.await
.map_err(|e| match e {
endpoint::ReadToEndError::Read(e) => self.map_error(e).into(),
e => e.into(),
})
}

/// Block until the stream has been reset and return the error code. See [`iroh::endpoint::RecvStream::received_reset`].
Expand All @@ -64,7 +95,7 @@ impl RecvStream {
pub async fn received_reset(&mut self) -> Result<Option<u32>, SessionError> {
match self.inner.received_reset().await {
Ok(None) => Ok(None),
Ok(Some(code)) => Ok(web_transport_proto::error_from_http3(code.into_inner())),
Ok(Some(code)) => Ok(decode_stream_code(code, self.raw)),
Err(endpoint::ResetError::ConnectionLost(e)) => Err(e.into()),
Err(endpoint::ResetError::ZeroRttRejected) => unreachable!("0-RTT not supported"),
}
Expand Down
47 changes: 36 additions & 11 deletions rs/web-transport-iroh/src/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ use std::{
use bytes::{Buf, Bytes};
use iroh::endpoint;

use crate::{ClosedStream, SessionError, WriteError};
use crate::{
ClosedStream, SessionError, WriteError,
error::{decode_stream_code, encode_stream_code},
};

/// A stream that can be used to send bytes. See [`iroh::endpoint::SendStream`].
///
Expand All @@ -16,18 +19,31 @@ use crate::{ClosedStream, SessionError, WriteError};
#[derive(Debug)]
pub struct SendStream {
stream: endpoint::SendStream,
// Raw QUIC carries stream codes as is; HTTP/3 maps them into its own code space.
raw: bool,
}

impl SendStream {
pub(crate) fn new(stream: endpoint::SendStream) -> Self {
Self { stream }
pub(crate) fn new(stream: endpoint::SendStream, raw: bool) -> Self {
Self { stream, raw }
}

/// Decode the peer's stop code with the session's code space.
fn map_error(&self, e: endpoint::WriteError) -> WriteError {
match e {
endpoint::WriteError::Stopped(code) => match decode_stream_code(code, self.raw) {
Some(code) => WriteError::Stopped(code),
None => WriteError::InvalidStopped(code),
},
e => e.into(),
}
}

/// Abruptly reset the stream with the provided error code. See [`iroh::endpoint::SendStream::reset`].
/// This is a u32 with WebTransport because we share the error space with HTTP/3.
/// A raw QUIC session sends the code as is.
pub fn reset(&mut self, code: u32) -> Result<(), ClosedStream> {
let code = web_transport_proto::error_to_http3(code);
let code = endpoint::VarInt::try_from(code).unwrap();
let code = encode_stream_code(code, self.raw);
self.stream.reset(code).map_err(Into::into)
}

Expand All @@ -37,7 +53,7 @@ impl SendStream {
/// Also unlike Quinn, this returns a SessionError, not a StoppedError, because 0-RTT is not supported.
pub async fn stopped(&mut self) -> Result<Option<u32>, SessionError> {
match self.stream.stopped().await {
Ok(Some(code)) => Ok(web_transport_proto::error_from_http3(code.into_inner())),
Ok(Some(code)) => Ok(decode_stream_code(code, self.raw)),
Ok(None) => Ok(None),
Err(endpoint::StoppedError::ConnectionLost(e)) => Err(e.into()),
Err(endpoint::StoppedError::ZeroRttRejected) => {
Expand All @@ -50,12 +66,15 @@ impl SendStream {

/// Write some data to the stream, returning the size written. See [`iroh::endpoint::SendStream::write`].
pub async fn write(&mut self, buf: &[u8]) -> Result<usize, WriteError> {
self.stream.write(buf).await.map_err(Into::into)
self.stream.write(buf).await.map_err(|e| self.map_error(e))
}

/// Write all of the data to the stream. See [`iroh::endpoint::SendStream::write_all`].
pub async fn write_all(&mut self, buf: &[u8]) -> Result<(), WriteError> {
self.stream.write_all(buf).await.map_err(Into::into)
self.stream
.write_all(buf)
.await
.map_err(|e| self.map_error(e))
}

/// Write chunks of data to the stream, returning the number of bytes written.
Expand All @@ -68,17 +87,23 @@ impl SendStream {
self.stream
.write_many_chunks(bufs)
.await
.map_err(Into::into)
.map_err(|e| self.map_error(e))
}

/// Write a chunk of data to the stream. See [`iroh::endpoint::SendStream::write_chunk`].
pub async fn write_chunk(&mut self, buf: Bytes) -> Result<(), WriteError> {
self.stream.write_chunk(buf).await.map_err(Into::into)
self.stream
.write_chunk(buf)
.await
.map_err(|e| self.map_error(e))
}

/// Write all of the chunks of data to the stream. See [`iroh::endpoint::SendStream::write_all_chunks`].
pub async fn write_all_chunks(&mut self, bufs: &mut [Bytes]) -> Result<(), WriteError> {
self.stream.write_all_chunks(bufs).await.map_err(Into::into)
self.stream
.write_all_chunks(bufs)
.await
.map_err(|e| self.map_error(e))
}

/// Mark the stream as finished, such that no more data can be written. See [`iroh::endpoint::SendStream::finish`].
Expand Down
15 changes: 8 additions & 7 deletions rs/web-transport-iroh/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ impl Session {
self.conn
.accept_uni()
.await
.map(RecvStream::new)
.map(|recv| RecvStream::new(recv, true))
.map_err(Into::into)
}
}
Expand All @@ -136,7 +136,7 @@ impl Session {
self.conn
.accept_bi()
.await
.map(|(send, recv)| (SendStream::new(send), RecvStream::new(recv)))
.map(|(send, recv)| (SendStream::new(send, true), RecvStream::new(recv, true)))
.map_err(Into::into)
}
}
Expand All @@ -149,7 +149,7 @@ impl Session {
write_full_with_max_prio(&mut send, &h3.header_uni).await?;
}

Ok(SendStream::new(send))
Ok(SendStream::new(send, self.h3.is_none()))
}

/// Open a new bidirectional stream. See [`iroh::endpoint::Connection::open_bi`].
Expand All @@ -160,7 +160,8 @@ impl Session {
write_full_with_max_prio(&mut send, &h3.header_bi).await?;
}

Ok((SendStream::new(send), RecvStream::new(recv)))
let raw = self.h3.is_none();
Ok((SendStream::new(send, raw), RecvStream::new(recv, raw)))
}

/// Asynchronously receives an application datagram from the remote peer.
Expand Down Expand Up @@ -545,7 +546,7 @@ impl H3SessionAccept {
// Decide if we keep looping based on the type.
match typ {
StreamUni::WEBTRANSPORT => {
let recv = RecvStream::new(recv);
let recv = RecvStream::new(recv, false);
return Poll::Ready(Ok(recv));
}
StreamUni::QPACK_DECODER => {
Expand Down Expand Up @@ -625,8 +626,8 @@ impl H3SessionAccept {

if let Some((send, recv)) = res {
// Wrap the streams in our own types for correct error codes.
let send = SendStream::new(send);
let recv = RecvStream::new(recv);
let send = SendStream::new(send, false);
let recv = RecvStream::new(recv, false);
return Poll::Ready(Ok((send, recv)));
}

Expand Down
85 changes: 84 additions & 1 deletion rs/web-transport-iroh/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::{

use iroh::{
Endpoint,
endpoint::{ConnectionError, presets},
endpoint::{ConnectionError, ReadError, VarInt, presets},
};
use n0_tracing_test::traced_test;
use tokio::time::timeout;
Expand Down Expand Up @@ -426,3 +426,86 @@ async fn abandoned_accepters_release_their_wakers() -> n0_error::Result<()> {

Ok(())
}

/// A raw QUIC session sends RESET_STREAM and STOP_SENDING codes as is, so a plain QUIC
/// peer agrees on them, and still reads the HTTP/3-mapped codes an older raw peer sends.
#[tokio::test]
#[traced_test]
async fn raw_stream_codes() -> n0_error::Result<()> {
use web_transport_trait::Error as _;

const ALPN: &str = "moql";
const CODE: u32 = 5;

let client = Endpoint::bind(presets::Minimal).await.unwrap();
let client = Client::new(client);
let server = Endpoint::builder(presets::Minimal)
.alpns(vec![ALPN.as_bytes().to_vec()])
.bind()
.await
.unwrap();
let server_addr = server.addr();

let (session, plain) = tokio::join!(
async {
client
.connect_quic(server_addr, ALPN.as_bytes())
.await
.unwrap()
},
async { server.accept().await.unwrap().await.unwrap() },
);
let legacy = VarInt::try_from(web_transport_proto::error_to_http3(CODE)).unwrap();

timeout(Duration::from_secs(10), async {
// Our reset and stop reach the plain peer as is.
let mut send = session.open_uni().await.unwrap();
send.write_all(b"x").await.unwrap();
let mut recv = plain.accept_uni().await.unwrap();
recv.read_exact(&mut [0u8; 1]).await.unwrap();
send.reset(CODE).unwrap();
let err = recv.read(&mut [0u8; 1]).await.unwrap_err();
assert!(
matches!(err, ReadError::Reset(code) if code == CODE.into()),
"{err:?}"
);

let mut send = plain.open_uni().await.unwrap();
send.write_all(b"x").await.unwrap();
let mut recv = session.accept_uni().await.unwrap();
recv.read_exact(&mut [0u8; 1]).await.unwrap();
recv.stop(CODE).unwrap();
assert_eq!(send.stopped().await.unwrap(), Some(CODE.into()));

// The plain peer's codes, and a legacy peer's mapped ones, read back as the code.
for code in [CODE.into(), legacy] {
let mut send = plain.open_uni().await.unwrap();
send.write_all(b"x").await.unwrap();
let mut recv = session.accept_uni().await.unwrap();
recv.read_exact(&mut [0u8; 1]).await.unwrap();
send.reset(code).unwrap();
let err = recv.read(&mut [0u8; 1]).await.unwrap_err();
assert_eq!(err.stream_error(), Some(CODE), "{err}");

let mut send = session.open_uni().await.unwrap();
send.write_all(b"x").await.unwrap();
let mut recv = plain.accept_uni().await.unwrap();
recv.read_exact(&mut [0u8; 1]).await.unwrap();
recv.stop(code).unwrap();
let err = loop {
if let Err(err) = send.write(&[0u8; 1024]).await {
break err;
}
};
assert_eq!(err.stream_error(), Some(CODE), "{err}");
assert_eq!(send.stopped().await.unwrap(), Some(CODE));
}
})
.await
.expect("timed out");

session.close(0, b"");
client.close().await;
server.close().await;
Ok(())
}
Loading
Loading