Skip to main content

moq_transport_iroh/
transport.rs

1//! moq-net's poll transport over an iroh connection.
2
3use std::{
4    fmt,
5    future::Future,
6    pin::Pin,
7    task::{Poll, ready},
8    time::Duration,
9};
10
11use bytes::Bytes;
12use iroh::{
13    Endpoint, EndpointAddr,
14    endpoint::{self, Connection, ConnectionError, ConnectionStats, PathStats},
15};
16use kio::{Bridge, Waiter};
17use moq_net::transport::{
18    Address, Wire,
19    poll::{self, BiStreams, SendOptions},
20};
21use n0_error::e;
22use tracing::{debug, warn};
23
24use crate::{ALPN, Error, RecvStream, SendGroup, SendStream, TransportError};
25
26/// moq-net's poll transport over one iroh connection.
27///
28/// Implements [`moq_net::transport::poll::Session`] on iroh's QUIC connection
29/// and streams directly. The request path and token travel in the MoQ SETUP,
30/// since raw QUIC has no request URI.
31///
32/// What it can and cannot back:
33///
34/// - [`send_group`](poll::Session::send_group) returns a [`SendGroup`]. iroh
35///   schedules streams by an urgency alone, so a group's priority and each
36///   stream's order in it are packed into the urgency; see [`SendGroup`] for
37///   the mapping and where it departs from kuic's.
38/// - [`wire`](poll::Session::wire) holds the UDP byte counts and the bytes
39///   declared lost, refreshed from the connection statistics whenever moq-net
40///   reads [`metrics`](poll::Session::metrics). iroh reports neither the time
41///   sends waited on congestion control nor flow-control stalls, so those
42///   counters stay zero.
43/// - [`probe`](poll::Session::probe) is `None`: iroh's congestion controller
44///   takes no probe target.
45/// - [`receive_window`](poll::Session::receive_window) is `None`: iroh does not
46///   report the receive windows in force. moq-net then never pauses a stream.
47pub struct Transport {
48    connection: Connection,
49    // One slot per operation that may wait. iroh's futures for them borrow
50    // the connection, so each slot stores one built from a clone of it, which
51    // every task polling the operation shares.
52    accept_uni: OpSlot<Result<endpoint::RecvStream, ConnectionError>>,
53    accept_bi: OpSlot<Result<IrohBi, ConnectionError>>,
54    open_uni: OpSlot<Result<endpoint::SendStream, ConnectionError>>,
55    open_bi: OpSlot<Result<IrohBi, ConnectionError>>,
56    recv_datagram: OpSlot<Result<Bytes, ConnectionError>>,
57    closed: OpSlot<ConnectionError>,
58    wire: Wire,
59}
60
61/// The halves of a bidirectional stream as iroh hands them out.
62type IrohBi = (endpoint::SendStream, endpoint::RecvStream);
63
64impl Transport {
65    /// Wraps an incoming or outgoing `connection` that negotiated a MoQ ALPN.
66    ///
67    /// Hand the transport to [`moq_net::Server::handshake`] for an
68    /// accepted connection, or to [`moq_net::Client::connect`] for a dialed
69    /// one. To dial with iroh's connect options, such as another QUIC
70    /// transport config for this one connection while the endpoint keeps its
71    /// own for every other, connect through iroh and wrap the result:
72    ///
73    /// ```no_run
74    /// # async fn run(endpoint: iroh::Endpoint, peer: iroh::EndpointId, config: iroh::endpoint::QuicTransportConfig) -> Result<(), Box<dyn std::error::Error>> {
75    /// use iroh::endpoint::ConnectOptions;
76    /// use moq_transport_iroh::{ALPN, Transport};
77    ///
78    /// let options = ConnectOptions::new().with_transport_config(config);
79    /// let connection = endpoint.connect_with_opts(peer, ALPN, options).await?.await?;
80    /// let transport = Transport::new(connection)?;
81    /// # drop(transport);
82    /// # Ok(())
83    /// # }
84    /// ```
85    ///
86    /// # Errors
87    ///
88    /// Fails with [`Error::UnsupportedAlpn`] if the connection negotiated an
89    /// ALPN this build does not speak, which happens when a handler is mounted
90    /// under an ALPN outside [`alpns`](crate::alpns).
91    pub fn new(connection: Connection) -> Result<Self, Error> {
92        let alpn = String::from_utf8_lossy(connection.alpn()).into_owned();
93        let peer = connection.remote_id().fmt_short();
94        if !moq_net::ALPNS.contains(&alpn.as_str()) {
95            // Only a handler mounted under a wrong ALPN gets here.
96            warn!(%alpn, %peer, "unsupported ALPN");
97            return Err(e!(Error::UnsupportedAlpn { alpn }));
98        }
99        debug!(%alpn, %peer, side = ?connection.side(), "MoQ transport opened");
100        Ok(Self {
101            connection,
102            accept_uni: OpSlot::default(),
103            accept_bi: OpSlot::default(),
104            open_uni: OpSlot::default(),
105            open_bi: OpSlot::default(),
106            recv_datagram: OpSlot::default(),
107            closed: OpSlot::default(),
108            wire: Wire::new(),
109        })
110    }
111
112    /// Dials `peer` and returns the MoQ transport over the connection.
113    ///
114    /// Offers only [`ALPN`], the newest MoQ version. iroh's
115    /// [`Router`](iroh::protocol::Router) sorts the ALPNs it accepts, and TLS
116    /// picks the first of the server's that the client offers, so offering
117    /// older versions too would settle every dial on the oldest moq-lite. Hand
118    /// the transport to [`moq_net::Client::connect`].
119    ///
120    /// Dropping the future abandons the dial.
121    ///
122    /// ```no_run
123    /// # async fn run(endpoint: iroh::Endpoint, peer: iroh::EndpointId) -> Result<(), moq_transport_iroh::Error> {
124    /// use moq_transport_iroh::Transport;
125    ///
126    /// let transport = Transport::connect(&endpoint, peer).await?;
127    /// # drop(transport);
128    /// # Ok(())
129    /// # }
130    /// ```
131    ///
132    /// # Errors
133    ///
134    /// Fails with [`Error::Connect`] if the dial fails, or with
135    /// [`Error::UnsupportedAlpn`] if the peer negotiates an ALPN this build
136    /// does not speak.
137    pub async fn connect(
138        endpoint: &Endpoint,
139        peer: impl Into<EndpointAddr>,
140    ) -> Result<Self, Error> {
141        let connection = endpoint.connect(peer, ALPN).await.map_err(Error::connect)?;
142        Self::new(connection)
143    }
144
145    /// Returns the iroh connection the transport runs over.
146    #[must_use]
147    pub fn connection(&self) -> &Connection {
148        &self.connection
149    }
150
151    /// Starts an operation on a clone of the connection.
152    fn start<T, F>(&self, op: fn(Connection) -> F) -> impl FnOnce() -> OpFuture<T> + '_
153    where
154        F: Future<Output = T> + Send + 'static,
155    {
156        move || Box::pin(op(self.connection.clone()))
157    }
158}
159
160impl fmt::Debug for Transport {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        f.debug_struct("Transport")
163            .field("peer", &self.connection.remote_id().fmt_short().to_string())
164            .field("alpn", &String::from_utf8_lossy(self.connection.alpn()))
165            .finish_non_exhaustive()
166    }
167}
168
169impl poll::Session for Transport {
170    type SendStream = SendStream;
171    type RecvStream = poll::Buffered<RecvStream>;
172    type Error = TransportError;
173
174    fn poll_accept_uni(&self, waiter: &Waiter) -> Poll<Result<Self::RecvStream, TransportError>> {
175        let start = self.start(|conn| async move { conn.accept_uni().await });
176        poll_op(&self.accept_uni, waiter, start)
177            .map_ok(RecvStream::buffered)
178            .map_err(Into::into)
179    }
180
181    fn poll_accept_bi(&self, waiter: &Waiter) -> Poll<Result<BiStreams<Self>, TransportError>> {
182        let start = self.start(|conn| async move { conn.accept_bi().await });
183        poll_op(&self.accept_bi, waiter, start)
184            .map_ok(|(send, recv)| {
185                (
186                    SendStream::new(send, SendOptions::default()),
187                    RecvStream::buffered(recv),
188                )
189            })
190            .map_err(Into::into)
191    }
192
193    fn poll_open_uni(
194        &self,
195        waiter: &Waiter,
196        options: SendOptions<'_, SendGroup>,
197    ) -> Poll<Result<SendStream, TransportError>> {
198        let start = self.start(|conn| async move { conn.open_uni().await });
199        poll_op(&self.open_uni, waiter, start)
200            .map_ok(|send| SendStream::new(send, options))
201            .map_err(Into::into)
202    }
203
204    fn poll_open_bi(
205        &self,
206        waiter: &Waiter,
207        options: SendOptions<'_, SendGroup>,
208    ) -> Poll<Result<BiStreams<Self>, TransportError>> {
209        let start = self.start(|conn| async move { conn.open_bi().await });
210        poll_op(&self.open_bi, waiter, start)
211            .map_ok(|(send, recv)| (SendStream::new(send, options), RecvStream::buffered(recv)))
212            .map_err(Into::into)
213    }
214
215    fn send_group(&self, priority: i64) -> Option<SendGroup> {
216        Some(SendGroup::new(priority))
217    }
218
219    /// Sends `payload`, ignoring `options`: iroh queues datagrams apart from
220    /// streams and cannot rank one against the other.
221    fn send_datagram(
222        &self,
223        payload: Bytes,
224        _options: SendOptions<'_, SendGroup>,
225    ) -> Result<(), TransportError> {
226        self.connection.send_datagram(payload).map_err(Into::into)
227    }
228
229    fn poll_recv_datagram(&self, waiter: &Waiter) -> Poll<Result<Bytes, TransportError>> {
230        let start = self.start(|conn| async move { conn.read_datagram().await });
231        poll_op(&self.recv_datagram, waiter, start).map_err(Into::into)
232    }
233
234    fn max_datagram_size(&self) -> usize {
235        self.connection.max_datagram_size().unwrap_or(0)
236    }
237
238    fn protocol(&self) -> Option<&str> {
239        std::str::from_utf8(self.connection.alpn()).ok()
240    }
241
242    fn address(&self) -> Address {
243        Address::Setup
244    }
245
246    fn close(&self, code: u32, reason: &str) {
247        debug!(
248            peer = %self.connection.remote_id().fmt_short(),
249            code,
250            reason,
251            "closing the connection"
252        );
253        self.connection.close(code.into(), reason.as_bytes());
254    }
255
256    fn poll_closed(&self, waiter: &Waiter) -> Poll<TransportError> {
257        let start = self.start(|conn| async move { conn.closed().await });
258        poll_op(&self.closed, waiter, start).map(Into::into)
259    }
260
261    fn metrics(&self) -> impl moq_net::transport::Metrics {
262        let stats = self.connection.stats();
263        // moq-net reads the wire right after the metrics.
264        self.wire.set_sent_bytes(stats.udp_tx.bytes);
265        self.wire.set_received_bytes(stats.udp_rx.bytes);
266        self.wire.set_lost_bytes(stats.lost_bytes);
267        let path = self
268            .connection
269            .paths()
270            .iter()
271            .find(|path| path.is_selected())
272            .map(|path| path.stats());
273        Metrics { stats, path }
274    }
275
276    fn wire(&self) -> Option<Wire> {
277        Some(self.wire.clone())
278    }
279}
280
281/// A connection's statistics, and its selected path's.
282struct Metrics {
283    stats: ConnectionStats,
284    path: Option<PathStats>,
285}
286
287impl moq_net::transport::Metrics for Metrics {
288    fn bytes_lost(&self) -> Option<u64> {
289        Some(self.stats.lost_bytes)
290    }
291
292    fn packets_sent(&self) -> Option<u64> {
293        Some(self.stats.udp_tx.datagrams)
294    }
295
296    fn packets_received(&self) -> Option<u64> {
297        Some(self.stats.udp_rx.datagrams)
298    }
299
300    fn packets_lost(&self) -> Option<u64> {
301        Some(self.stats.lost_packets)
302    }
303
304    fn rtt(&self) -> Option<Duration> {
305        self.path.map(|path| path.rtt)
306    }
307
308    /// Returns the congestion window over the round trip of the selected path.
309    fn estimated_send_rate(&self) -> Option<u64> {
310        let path = self.path?;
311        let rtt = path.rtt.as_secs_f64();
312        (path.cwnd > 0 && rtt > 0.0).then(|| (path.cwnd as f64 * 8.0 / rtt) as u64)
313    }
314}
315
316/// A stored operation future.
317pub(crate) type OpFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
318
319/// An operation in flight, or `None` when idle, which every task polling it shares.
320pub(crate) type OpSlot<T> = Bridge<Option<OpFuture<T>>>;
321
322/// Polls the operation in `slot`, starting it first if the slot is idle.
323///
324/// Clears the slot once the operation resolves. The caller whose poll sees it
325/// resolve takes the output, so a stream it yields is never lost, and the next
326/// caller starts a new operation.
327pub(crate) fn poll_op<T>(
328    slot: &OpSlot<T>,
329    waiter: &Waiter,
330    start: impl FnOnce() -> OpFuture<T>,
331) -> Poll<T> {
332    slot.poll(waiter, |slot, cx| {
333        let op = slot.get_or_insert_with(start);
334        let output = ready!(op.as_mut().poll(cx));
335        *slot = None;
336        Poll::Ready(output)
337    })
338}
339
340#[cfg(test)]
341pub(crate) mod tests {
342    use std::sync::{Arc, LazyLock};
343
344    use iroh::endpoint::{Builder, presets};
345    use moq_net::transport::{
346        CloseKind, Error as _,
347        poll::{RecvStream as _, SendStream as _, Session as _},
348    };
349
350    use super::*;
351
352    pub(crate) const TIMEOUT: Duration = Duration::from_secs(10);
353
354    /// Returns an endpoint builder on rind, the crypto provider moq compiles in.
355    ///
356    /// iroh's own presets exist only with one of its `tls-*` features, which
357    /// this workspace leaves to the application.
358    fn builder() -> Builder {
359        static PROVIDER: LazyLock<Arc<rustls::crypto::CryptoProvider>> =
360            LazyLock::new(|| Arc::new(rind_rustls::default_provider()));
361        Endpoint::builder(presets::Empty).crypto_provider(PROVIDER.clone())
362    }
363
364    /// Returns a dialed and an accepted transport, and the endpoints that drive them.
365    ///
366    /// The accepting endpoint speaks only `server_alpns`. With `client_alpn`
367    /// the client connects with that ALPN instead of through [`Transport::connect`].
368    /// With `config` both endpoints use that QUIC transport config.
369    async fn pair_with(
370        client_alpn: Option<&[u8]>,
371        server_alpns: Vec<&[u8]>,
372        config: Option<endpoint::QuicTransportConfig>,
373    ) -> (Transport, Transport, [Endpoint; 2]) {
374        let builder = || {
375            let builder = builder();
376            match &config {
377                Some(config) => builder.transport_config(config.clone()),
378                None => builder,
379            }
380        };
381        let client = builder().bind().await.expect("bind client");
382        let server = builder()
383            .alpns(server_alpns.into_iter().map(<[u8]>::to_vec).collect())
384            .bind()
385            .await
386            .expect("bind server");
387        let incoming = async {
388            let connection = server
389                .accept()
390                .await
391                .expect("an incoming connection")
392                .await
393                .expect("handshake");
394            Transport::new(connection).expect("a MoQ ALPN")
395        };
396        let outgoing = async {
397            match client_alpn {
398                Some(alpn) => Transport::new(
399                    client
400                        .connect(server.addr(), alpn)
401                        .await
402                        .map_err(Error::connect)?,
403                ),
404                None => Transport::connect(&client, server.addr()).await,
405            }
406        };
407        let (dialed, accepted) =
408            tokio::time::timeout(TIMEOUT, async { tokio::join!(outgoing, incoming) })
409                .await
410                .expect("connect in time");
411        (dialed.expect("dial"), accepted, [client, server])
412    }
413
414    /// Returns a dialed and an accepted transport, the server speaking every MoQ ALPN.
415    ///
416    /// The server's ALPNs are sorted, as iroh's `Router` sorts them.
417    pub(crate) async fn pair() -> (Transport, Transport, [Endpoint; 2]) {
418        let mut alpns = crate::alpns();
419        alpns.sort();
420        pair_with(None, alpns, None).await
421    }
422
423    /// Returns a pair like [`pair`] whose endpoints use `config`.
424    pub(crate) async fn pair_configured(
425        config: endpoint::QuicTransportConfig,
426    ) -> (Transport, Transport, [Endpoint; 2]) {
427        let mut alpns = crate::alpns();
428        alpns.sort();
429        pair_with(None, alpns, Some(config)).await
430    }
431
432    /// Runs `fut` to completion, failing the test after [`TIMEOUT`].
433    async fn timely<F: Future>(what: &str, fut: F) -> F::Output {
434        tokio::time::timeout(TIMEOUT, fut)
435            .await
436            .unwrap_or_else(|_| panic!("{what} timed out"))
437    }
438
439    /// Reads `recv` to its end.
440    async fn read_to_end(recv: &mut poll::Buffered<RecvStream>) -> Result<Vec<u8>, TransportError> {
441        let mut bytes = Vec::new();
442        while let Some(chunk) = recv.read_chunk(usize::MAX).await? {
443            bytes.extend_from_slice(&chunk);
444        }
445        Ok(bytes)
446    }
447
448    /// Opens a unidirectional stream and sends `payload` on it, so the peer can accept it.
449    async fn open_with(transport: &Transport, payload: &'static [u8]) -> SendStream {
450        let mut send = transport
451            .open_uni(SendOptions::default())
452            .await
453            .expect("open uni");
454        send.write_chunk(Bytes::from_static(payload))
455            .await
456            .expect("write");
457        send
458    }
459
460    #[tokio::test]
461    async fn dial_negotiates_the_newest_alpn() {
462        let (client, server, _endpoints) = pair().await;
463        assert_eq!(client.protocol(), std::str::from_utf8(ALPN).ok());
464        assert_eq!(server.protocol(), client.protocol());
465        assert_eq!(client.address(), Address::Setup);
466    }
467
468    #[tokio::test]
469    async fn accept_refuses_a_foreign_alpn() {
470        let client = builder().bind().await.expect("bind");
471        let server = builder()
472            .alpns(vec![b"other".to_vec()])
473            .bind()
474            .await
475            .expect("bind");
476        let incoming = async {
477            server
478                .accept()
479                .await
480                .expect("incoming")
481                .await
482                .expect("handshake")
483        };
484        let (dialed, accepted) = timely("connect", async {
485            tokio::join!(client.connect(server.addr(), b"other"), incoming)
486        })
487        .await;
488        let _client = dialed.expect("connect");
489        assert!(matches!(
490            Transport::new(accepted),
491            Err(Error::UnsupportedAlpn { alpn, .. }) if alpn == "other"
492        ));
493    }
494
495    #[tokio::test]
496    async fn uni_stream_carries_bytes_and_fin() {
497        let (client, server, _endpoints) = pair().await;
498        let mut send = open_with(&client, b"hello ").await;
499        send.write_chunk(Bytes::from_static(b"world"))
500            .await
501            .expect("write");
502        send.finish().expect("finish");
503        let mut recv = timely("accept", server.accept_uni()).await.expect("accept");
504        let bytes = timely("read", read_to_end(&mut recv)).await.expect("read");
505        assert_eq!(bytes, b"hello world");
506        timely("acknowledgement", send.closed())
507            .await
508            .expect("acknowledged");
509    }
510
511    #[tokio::test]
512    async fn bi_stream_carries_both_directions() {
513        let (client, server, _endpoints) = pair().await;
514        let (mut send, mut recv) = client
515            .open_bi(SendOptions::default())
516            .await
517            .expect("open bi");
518        send.write_chunk(Bytes::from_static(b"ping"))
519            .await
520            .expect("write");
521        send.finish().expect("finish");
522        let (mut reply, mut request) = timely("accept", server.accept_bi()).await.expect("accept");
523        assert_eq!(
524            timely("read", read_to_end(&mut request))
525                .await
526                .expect("read"),
527            b"ping"
528        );
529        reply
530            .write_chunk(Bytes::from_static(b"pong"))
531            .await
532            .expect("write");
533        reply.finish().expect("finish");
534        assert_eq!(
535            timely("read", read_to_end(&mut recv)).await.expect("read"),
536            b"pong"
537        );
538    }
539
540    #[tokio::test]
541    async fn open_bi_waits_for_credit_and_opens() {
542        let (client, _server, _endpoints) = pair().await;
543        let opened = kio::wait(|waiter| client.poll_open_bi(waiter, SendOptions::default()));
544        timely("open", opened).await.expect("open");
545    }
546
547    #[tokio::test]
548    async fn a_datagram_arrives() {
549        let (client, server, _endpoints) = pair().await;
550        assert!(client.max_datagram_size() > 0);
551        client
552            .send_datagram(Bytes::from_static(b"tick"), SendOptions::default())
553            .expect("send");
554        let datagram = timely("datagram", server.recv_datagram())
555            .await
556            .expect("receive");
557        assert_eq!(datagram, Bytes::from_static(b"tick"));
558    }
559
560    #[tokio::test]
561    async fn a_close_code_reaches_the_peer() {
562        let (client, server, _endpoints) = pair().await;
563        client.close(42, "bye");
564        let remote = timely("remote close", server.closed()).await;
565        assert_eq!(remote.session_error(), Some((42, "bye".to_owned())));
566        let local = timely("local close", client.closed()).await;
567        assert_eq!(local.close_kind(), CloseKind::Closed);
568        assert_eq!(local.session_error(), None);
569    }
570
571    #[tokio::test]
572    async fn a_stop_code_reaches_the_writer() {
573        let (client, server, _endpoints) = pair().await;
574        let send = open_with(&client, b"unwanted").await;
575        let mut recv = timely("accept", server.accept_uni()).await.expect("accept");
576        recv.stop(7);
577        let err = timely("stop", send.closed()).await.expect_err("stopped");
578        assert_eq!(err.stream_error(), Some(7));
579    }
580
581    #[tokio::test]
582    async fn a_reset_code_reaches_the_reader() {
583        let (client, server, _endpoints) = pair().await;
584        let mut send = open_with(&client, b"partial").await;
585        let mut recv = timely("accept", server.accept_uni()).await.expect("accept");
586        send.reset(9);
587        let err = timely("read", read_to_end(&mut recv))
588            .await
589            .expect_err("reset");
590        assert_eq!(err.stream_error(), Some(9));
591    }
592
593    /// A writer that goes away mid-stream resets it, so the peer never reads it as complete.
594    #[tokio::test]
595    async fn dropping_an_unfinished_stream_resets_it() {
596        let (client, server, _endpoints) = pair().await;
597        let send = open_with(&client, b"cut off").await;
598        let mut recv = timely("accept", server.accept_uni()).await.expect("accept");
599        drop(send);
600        let err = timely("read", read_to_end(&mut recv))
601            .await
602            .expect_err("reset");
603        assert_eq!(err.stream_error(), Some(0));
604    }
605
606    #[tokio::test]
607    async fn metrics_fill_the_wire_counters() {
608        let (client, server, _endpoints) = pair().await;
609        let mut send = open_with(&client, &[7; 4096]).await;
610        send.finish().expect("finish");
611        let mut recv = timely("accept", server.accept_uni()).await.expect("accept");
612        timely("read", read_to_end(&mut recv)).await.expect("read");
613        let metrics = client.metrics();
614        let wire = client.wire().expect("a wire");
615        assert!(wire.sent_bytes() >= 4096, "{}", wire.sent_bytes());
616        assert!(wire.received_bytes() > 0);
617        assert!(moq_net::transport::Metrics::packets_sent(&metrics).is_some_and(|sent| sent > 0));
618        assert!(moq_net::transport::Metrics::rtt(&metrics).is_some());
619        assert!(client.probe().is_none());
620        assert!(client.receive_window().is_none());
621    }
622
623    /// Completes a MoQ handshake: the client over `client`, the server over `server`.
624    ///
625    /// Returns the handshake the server saw before admitting the session.
626    async fn handshake(
627        client: Transport,
628        server: Transport,
629        builder: moq_net::Client,
630    ) -> (moq_net::Session, moq_net::server::Handshake) {
631        let now = moq_net::time::Instant::now();
632        // The client's driver writes the SETUP the server waits for, so it runs
633        // alongside the accept.
634        let connect = async {
635            let (session, driver) = builder.connect(now, client).await.expect("connect");
636            tokio::spawn(moq_net::time::run(driver));
637            session
638        };
639        let accept = async {
640            moq_net::Server::new()
641                .handshake(now, server)
642                .await
643                .expect("accept request")
644        };
645        timely("handshake", async { tokio::join!(connect, accept) }).await
646    }
647
648    /// The request path travels in the SETUP, since raw QUIC has no request URI.
649    #[tokio::test]
650    async fn the_setup_carries_the_request_path() {
651        let (client, server, _endpoints) = pair().await;
652        let url = url::Url::parse("moqt://iroh/room?jwt=abc").expect("url");
653        let (_session, request) =
654            handshake(client, server, moq_net::Client::new().with_url(url)).await;
655        assert_eq!(request.path(), "/room?jwt=abc");
656        let (_session, _driver) = timely("admit", request.ok()).await.expect("admit");
657    }
658
659    /// A version that carries a SETUP token hands the client's token to the server.
660    #[tokio::test]
661    async fn the_setup_carries_the_token() {
662        let (client, server, _endpoints) =
663            pair_with(Some(b"moqt-22"), vec![b"moqt-22"], None).await;
664        assert_eq!(client.protocol(), Some("moqt-22"));
665        let token = moq_net::setup::Token {
666            kind: moq_net::setup::Token::OUT_OF_BAND,
667            value: b"letmein".to_vec(),
668        };
669        let builder = moq_net::Client::new().with_token(token.clone());
670        let (_session, request) = handshake(client, server, builder).await;
671        assert_eq!(request.token(), Some(&token));
672    }
673}