Skip to main content

moq_transport_iroh/
stream.rs

1//! The streams of a [`Transport`](crate::Transport), as moq-net's poll traits.
2
3use std::{
4    fmt,
5    pin::{Pin, pin},
6    sync::{Arc, Mutex},
7    task::Poll,
8};
9
10use bytes::Bytes;
11use iroh::endpoint::{self, StoppedError, VarInt};
12use kio::Waiter;
13use moq_net::transport::poll::{self, SendOptions};
14
15use crate::{
16    SendGroup, TransportError,
17    group::{self, Membership, SharedStream},
18    transport::{OpSlot, poll_op},
19};
20
21/// The sending half of a stream.
22pub struct SendStream {
23    /// Shared with the stream's send group, which sets its urgency.
24    stream: SharedStream,
25    /// The priority moq-net gave the stream: its order inside its group, or
26    /// its rank among the ungrouped streams.
27    priority: i64,
28    /// The stream's send group, or `None` while it is ungrouped.
29    membership: Option<Membership>,
30    /// Whether the stream has ended.
31    ///
32    /// Set by [`finish`](poll::SendStream::finish) and
33    /// [`reset`](poll::SendStream::reset).
34    ended: bool,
35    /// The peer's acknowledgement of the FIN, or its STOP_SENDING.
36    ///
37    /// iroh's `stopped` future owns what it watches, so it is stored here and
38    /// polled through a shared borrow while writes go on.
39    closed: OpSlot<Result<Option<VarInt>, StoppedError>>,
40}
41
42impl SendStream {
43    /// Wraps `stream`, scheduled by `options`.
44    pub(crate) fn new(stream: endpoint::SendStream, options: SendOptions<'_, SendGroup>) -> Self {
45        let stream = Arc::new(Mutex::new(stream));
46        let membership = options
47            .group
48            .map(|group| group.join(stream.clone(), options.priority));
49        let stream = Self {
50            stream,
51            priority: options.priority,
52            membership,
53            ended: false,
54            closed: OpSlot::default(),
55        };
56        if stream.membership.is_none() {
57            stream.apply_ungrouped();
58        }
59        stream
60    }
61
62    /// Sets the urgency of a stream outside every group.
63    fn apply_ungrouped(&self) {
64        group::lock(&self.stream)
65            .set_priority(group::ungrouped(self.priority))
66            .ok();
67    }
68}
69
70impl fmt::Debug for SendStream {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.debug_struct("SendStream")
73            .field("id", &group::lock(&self.stream).id())
74            .field("priority", &self.priority)
75            .field("grouped", &self.membership.is_some())
76            .field("ended", &self.ended)
77            .finish_non_exhaustive()
78    }
79}
80
81impl poll::SendStream for SendStream {
82    type Error = TransportError;
83    type Group = SendGroup;
84    /// iroh does not report which bytes the peer acknowledged, so
85    /// [`poll_acked`](poll::SendStream::poll_acked) keeps its default, which
86    /// is ready as soon as the stream took the bytes.
87    type Offset = ();
88
89    fn offset(&self) -> Self::Offset {}
90
91    fn poll_write(&mut self, waiter: &Waiter, buf: &[u8]) -> Poll<Result<usize, TransportError>> {
92        if buf.is_empty() {
93            return Poll::Ready(Ok(0));
94        }
95        // iroh's write takes nothing from `buf` until it returns ready, so a
96        // pending write leaves the stream as it was.
97        let mut stream = group::lock(&self.stream);
98        Pin::new(&mut *stream)
99            .poll_write(&mut waiter.context(), buf)
100            .map_err(Into::into)
101    }
102
103    fn set_priority(&mut self, priority: i64) {
104        self.priority = priority;
105        match &self.membership {
106            Some(membership) => membership.set_order(priority),
107            None => self.apply_ungrouped(),
108        }
109    }
110
111    fn set_group(&mut self, group: &SendGroup) {
112        if self
113            .membership
114            .as_ref()
115            .is_some_and(|membership| membership.group().same(group))
116        {
117            return;
118        }
119        // Leaves the old group first, which reranks the streams it leaves.
120        self.membership = None;
121        self.membership = Some(group.join(self.stream.clone(), self.priority));
122    }
123
124    fn finish(&mut self) -> Result<(), TransportError> {
125        self.ended = true;
126        group::lock(&self.stream).finish().map_err(Into::into)
127    }
128
129    fn reset(&mut self, code: u32) {
130        self.ended = true;
131        group::lock(&self.stream).reset(code.into()).ok();
132    }
133
134    /// Resets the stream without delivering anything first.
135    ///
136    /// The offset is `()`, so there is nothing to deliver up to. moq-net asks
137    /// for this only on sessions whose
138    /// [`reliable_reset`](poll::Session::reliable_reset) is true, which iroh's
139    /// is not, so a plain reset is what the caller expects.
140    fn reset_at(&mut self, _offset: &(), code: u32) {
141        self.reset(code);
142    }
143
144    fn poll_closed(&self, waiter: &Waiter) -> Poll<Result<(), TransportError>> {
145        poll_op(&self.closed, waiter, || {
146            Box::pin(group::lock(&self.stream).stopped())
147        })
148        .map(|stopped| match stopped {
149            // Acknowledged after a finish, or freed after a reset.
150            Ok(None) => Ok(()),
151            Ok(Some(code)) => Err(TransportError::Stopped(code)),
152            Err(err) => Err(err.into()),
153        })
154    }
155}
156
157impl Drop for SendStream {
158    /// Leaves the send group, then resets a stream that was neither finished
159    /// nor reset.
160    ///
161    /// iroh finishes a dropped stream, so a writer that went away would read
162    /// as a complete stream to the peer. moq-net asks for a reset instead.
163    fn drop(&mut self) {
164        self.membership = None;
165        if !self.ended {
166            group::lock(&self.stream).reset(VarInt::from_u32(0)).ok();
167        }
168    }
169}
170
171/// The receiving half of a stream.
172///
173/// moq-net reads it through [`poll::Buffered`], since iroh returns flow
174/// control credit as it reads. Dropping it stops the stream with code 0, as
175/// iroh does.
176///
177/// It keeps the default [`poll_reset`](poll::Chunks::poll_reset), which never
178/// completes. iroh's `received_reset` leaves its waker registered with the
179/// stream, which a later read to the end then trips over in iroh's drop check.
180pub struct RecvStream {
181    stream: endpoint::RecvStream,
182}
183
184impl RecvStream {
185    /// Wraps `stream` for moq-net.
186    pub(crate) fn buffered(stream: endpoint::RecvStream) -> poll::Buffered<Self> {
187        poll::Buffered::new(Self { stream })
188    }
189}
190
191impl fmt::Debug for RecvStream {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        f.debug_struct("RecvStream")
194            .field("id", &self.stream.id())
195            .finish_non_exhaustive()
196    }
197}
198
199impl poll::Chunks for RecvStream {
200    type Error = TransportError;
201
202    fn poll_read_chunk(
203        &mut self,
204        waiter: &Waiter,
205        max: usize,
206    ) -> Poll<Result<Option<Bytes>, TransportError>> {
207        if max == 0 {
208            return Poll::Ready(Ok(Some(Bytes::new())));
209        }
210        // A read future that is dropped while pending reads nothing, and the
211        // waker it registered stays with the stream, so a fresh one per poll
212        // is enough.
213        let read = pin!(self.stream.read_chunk(max));
214        read.poll(&mut waiter.context()).map_err(Into::into)
215    }
216
217    fn stop(&mut self, code: u32) {
218        self.stream.stop(code.into()).ok();
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use std::sync::atomic::{AtomicUsize, Ordering};
225
226    use bytes::Bytes;
227    use iroh::endpoint;
228    use moq_net::transport::poll::{
229        self, RecvStream as _, SendGroup as _, SendOptions, SendStream as _, Session as _,
230    };
231
232    use super::{RecvStream, SendStream};
233    use crate::{
234        group,
235        transport::tests::{TIMEOUT, pair, pair_configured},
236    };
237
238    /// Returns the urgency iroh schedules `send` at.
239    fn urgency(send: &SendStream) -> i32 {
240        group::lock(&send.stream).priority().expect("open")
241    }
242
243    /// An ungrouped stream opens at its option's priority, above every group,
244    /// and a priority past the ungrouped range saturates.
245    #[tokio::test]
246    async fn ungrouped_priorities_reach_iroh_and_saturate() {
247        let (client, _server, _endpoints) = pair().await;
248        let options = SendOptions {
249            group: None,
250            priority: 5,
251        };
252        let mut send = client.open_uni(options).await.expect("open");
253        assert_eq!(urgency(&send), group::ungrouped(5));
254        let at_zero = client.open_uni(SendOptions::default()).await.expect("open");
255        assert!(urgency(&send) > urgency(&at_zero));
256        send.set_priority(i64::MAX);
257        assert_eq!(urgency(&send), group::ungrouped(i64::MAX));
258        send.set_priority(i64::MIN);
259        assert_eq!(urgency(&send), group::ungrouped(i64::MIN));
260
261        let top = client.send_group(i64::MAX).expect("a send group");
262        let grouped = client
263            .open_uni(SendOptions {
264                group: Some(&top),
265                priority: i64::MAX,
266            })
267            .await
268            .expect("open");
269        assert!(urgency(&send) > urgency(&grouped), "ungrouped goes first");
270    }
271
272    /// The heads of equal-priority groups tie, a group's older streams rank
273    /// below every head, and a higher group outranks them all.
274    ///
275    /// It reads the urgency stored on each stream, so it checks the group's
276    /// bookkeeping, not noq's scheduling: a raised urgency reaches data
277    /// already queued only at the stream's next turn, which this does not
278    /// exercise.
279    #[tokio::test]
280    async fn groups_rank_their_streams_in_tiers() {
281        let (client, _server, _endpoints) = pair().await;
282        let mut first = client.send_group(7).expect("a send group");
283        let second = client.send_group(7).expect("a send group");
284        let open = |group, priority| {
285            client.open_uni(SendOptions {
286                group: Some(group),
287                priority,
288            })
289        };
290        // Orders as moq-net gives them: group sequences that differ between
291        // the subscriptions.
292        let newest = open(&first, 100).await.expect("open");
293        let older = open(&first, 98).await.expect("open");
294        let mut other = open(&second, 4).await.expect("open");
295        assert_eq!(urgency(&newest), urgency(&other), "heads share");
296        assert!(
297            urgency(&older) < urgency(&other),
298            "a backlog waits for every head"
299        );
300
301        // A newer stream in the second group demotes its head.
302        let newer = open(&second, 6).await.expect("open");
303        assert_eq!(urgency(&newer), urgency(&newest));
304        assert_eq!(urgency(&other), urgency(&older));
305
306        // Leaving promotes the stream behind.
307        drop(newest);
308        assert_eq!(urgency(&older), urgency(&newer));
309
310        // A stream that moves past its group's head becomes the head.
311        other.set_priority(8);
312        assert!(urgency(&other) > urgency(&newer));
313        assert_eq!(urgency(&other), urgency(&older));
314
315        // Raising a group lifts all of its streams above the other's.
316        first.set_priority(8);
317        assert!(urgency(&older) > urgency(&other));
318
319        // Moving a stream to another group reranks both.
320        let mut moved = newer;
321        moved.set_group(&first);
322        assert!(urgency(&moved) > urgency(&other));
323        assert!(
324            urgency(&older) > urgency(&moved),
325            "it ranks behind the head"
326        );
327    }
328
329    /// Two equal-priority groups share the link, whatever their streams' orders.
330    ///
331    /// The first group's stream has the higher order, as a newer group sequence
332    /// would. Ranked by order alone it would drain before the second sent a
333    /// byte, so the second must be well along when the first completes.
334    #[tokio::test]
335    async fn equal_priority_groups_progress_together() {
336        let streams = progress_of_the_lagging_stream(true).await;
337        assert!(
338            streams >= LEN / 4,
339            "the other stream had {streams} of {LEN} bytes when the first finished",
340        );
341    }
342
343    /// The same two streams outside any group, ranked by order alone, do not
344    /// share: the lower one waits for the higher. This keeps the test above
345    /// honest, since a loopback link with small windows would let any two
346    /// streams interleave.
347    #[tokio::test]
348    async fn ungrouped_streams_drain_in_order() {
349        let streams = progress_of_the_lagging_stream(false).await;
350        assert!(
351            streams < LEN / 4,
352            "the other stream had {streams} of {LEN} bytes when the first finished",
353        );
354    }
355
356    /// The bytes each stream sends after its tag.
357    ///
358    /// Kept well under a thousand packets: noq closes the connection once a
359    /// stream buffers more than 1024 separate spans, and every full packet
360    /// that arrives behind a lost one stays its own span until the
361    /// retransmission fills the hole. Loopback does drop packets on some
362    /// hosts, so a stream with megabytes in flight can trip that limit.
363    const LEN: usize = 512 << 10;
364
365    /// Sends [`LEN`] bytes on each of two streams at orders 1000 and 0, in two
366    /// equal-priority groups if `grouped`, and returns how much of one stream
367    /// had arrived when the other finished.
368    ///
369    /// The flow control windows exceed what the streams send, so only the
370    /// sender's scheduler decides which goes first.
371    async fn progress_of_the_lagging_stream(grouped: bool) -> usize {
372        let window = 2 * LEN as u32;
373        let config = endpoint::QuicTransportConfig::builder()
374            .stream_receive_window(endpoint::VarInt::from_u32(window))
375            .receive_window(endpoint::VarInt::from_u32(2 * window))
376            .send_window(2 * window as u64)
377            .build();
378        let (client, server, _endpoints) = pair_configured(config).await;
379        let groups = [7, 7].map(|priority| client.send_group(priority).expect("a send group"));
380        let mut sends = Vec::new();
381        for (tag, (group, order)) in groups.iter().zip([1000, 0]).enumerate() {
382            let options = SendOptions {
383                group: grouped.then_some(group),
384                priority: order,
385            };
386            let mut send = client.open_uni(options).await.expect("open");
387            send.write_chunk(Bytes::from(vec![tag as u8]))
388                .await
389                .expect("write the tag");
390            sends.push(send);
391        }
392        let write = |mut send: SendStream| async move {
393            send.write_chunk(Bytes::from(vec![0; LEN]))
394                .await
395                .expect("write");
396            send.finish().expect("finish");
397            send
398        };
399        // Accepts a stream and reads its tag, the index of its writer.
400        let accept = || async {
401            let mut recv = server.accept_uni().await.expect("accept");
402            let tag = recv.read_chunk(1).await.expect("read").expect("a tag")[0] as usize;
403            (tag, recv)
404        };
405        let received = [AtomicUsize::new(0), AtomicUsize::new(0)];
406        // What the other stream had received when each finished.
407        let other_at_finish = [AtomicUsize::new(0), AtomicUsize::new(0)];
408        let read = async |(tag, mut recv): (usize, poll::Buffered<RecvStream>)| {
409            while let Some(chunk) = recv.read_chunk(usize::MAX).await.expect("read") {
410                received[tag].fetch_add(chunk.len(), Ordering::Relaxed);
411            }
412            other_at_finish[tag]
413                .store(received[1 - tag].load(Ordering::Relaxed), Ordering::Relaxed);
414        };
415        let receive = async {
416            let (one, other) = tokio::join!(accept(), accept());
417            let (first, second) = if one.0 == 0 {
418                (one, other)
419            } else {
420                (other, one)
421            };
422            // The endpoint delivers packets in batches, and one batch can hold
423            // the end of the order-1000 stream along with more of the other.
424            // Reading the order-1000 stream first leaves those later bytes out
425            // of its count, which would otherwise depend on which reader the
426            // runtime happens to poll first.
427            tokio::join!(biased; read(first), read(second));
428        };
429        let [first, second]: [SendStream; 2] = sends.try_into().expect("two streams");
430        tokio::time::timeout(TIMEOUT, async {
431            tokio::join!(write(first), write(second), receive)
432        })
433        .await
434        .expect("both streams arrive in time");
435
436        // The stream that finished second saw all of the first, so the
437        // smaller figure is the first one's view of the second.
438        other_at_finish
439            .iter()
440            .map(|other| other.load(Ordering::Relaxed))
441            .min()
442            .expect("two streams")
443    }
444}