Skip to main content

weirdnet_net/stream/
mod.rs

1//! Streams (W1) that survive path changes (W15).
2//!
3//! An application accepts streams of its own protocol ids ([`Node::accept_streams`]) and opens
4//! them to a peer ([`Node::open_stream`]). A [`Stream`] is an ordered, reliable byte stream with
5//! no size cap and backpressure (a sender has at most [`Limits::window`] bytes unacknowledged).
6//! It is a logical stream: underneath, a libp2p substream carries it, over a direct connection
7//! when there is one, else through a relay.
8//!
9//! Path switching: when a direct connection to the peer comes up (DCUtR hole punching, or a
10//! dial), the side that opened the stream moves it there; when the connection under a stream
11//! goes away, the opener re-opens it over whatever path is left (the relay, kept warm while
12//! streams are open) and both sides carry on where the other stopped. Nothing is lost or
13//! repeated: every data frame carries its byte offset, each side acknowledges what it has, and
14//! after a move the sender sends again what wasn't acknowledged. A stream fails only when no
15//! path comes back within [`Limits::resume`].
16//!
17//! Wire format, on every substream of the application's protocol: the opener sends `Hello`
18//! (new or resume, the stream id, bytes received so far) and the acceptor answers `Welcome`
19//! (bytes received so far) or `Refuse`; then `Data` (offset, bytes), `Ack` (bytes received),
20//! `Fin` (total bytes) and `Reset` frames, each one a type byte and big-endian fields.
21//! Traffic is end-to-end encrypted by the connection (Noise), relayed or not.
22//!
23//! [`Node::accept_streams`]: crate::Node::accept_streams
24//! [`Node::open_stream`]: crate::Node::open_stream
25pub(crate) mod transport;
26
27use futures::channel::mpsc;
28use futures::io::{ReadHalf, WriteHalf};
29use futures::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, SinkExt, StreamExt};
30use libp2p::swarm::ConnectionId;
31use libp2p::{PeerId, StreamProtocol};
32use std::collections::{HashMap, VecDeque};
33use std::io;
34use std::pin::Pin;
35use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
36use std::sync::{Arc, Mutex};
37use std::task::{Context, Poll};
38use std::time::{Duration, Instant};
39use transport::{Control, OpenError, PathEvent, Warm};
40
41/// How streams of one protocol behave.
42#[derive(Debug, Clone, Copy)]
43pub struct Limits {
44    /// Bytes a sender may have in flight unacknowledged (and a receiver buffers).
45    pub window: usize,
46    /// Largest data frame.
47    pub max_frame: usize,
48    /// Streams of this protocol open at once from others (more are refused). A stream stops
49    /// counting once both sides have ended it (closed or dropped).
50    pub max_streams: usize,
51    /// New inbound streams waiting for [`Incoming::accept`] (more are refused).
52    pub backlog: usize,
53    /// How long a stream waits for a path to come back before it fails.
54    pub resume: Duration,
55    /// Reset a stream after this long with nothing sent or received (`None`: never).
56    pub idle: Option<Duration>,
57}
58
59impl Default for Limits {
60    fn default() -> Self {
61        Limits { window: 1 << 20, max_frame: 64 * 1024, max_streams: 1024, backlog: 64, resume: Duration::from_secs(30), idle: None }
62    }
63}
64
65/// The kind of connection a stream is on.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub enum Path {
68    Direct,
69    Relayed,
70}
71
72const HELLO: u8 = 1;
73const WELCOME: u8 = 2;
74const REFUSE: u8 = 3;
75const DATA: u8 = 16;
76const ACK: u8 = 17;
77const FIN: u8 = 18;
78const RESET: u8 = 19;
79
80const REFUSE_BUSY: u8 = 1;
81const REFUSE_UNKNOWN: u8 = 2;
82const RESET_APP: u8 = 1;
83const RESET_IDLE: u8 = 2;
84
85const HANDSHAKE: Duration = Duration::from_secs(10);
86const LINGER: Duration = Duration::from_secs(2);
87const ACK_EVERY: Duration = Duration::from_millis(50);
88
89#[derive(Debug, PartialEq, Eq)]
90enum Frame {
91    Hello { resume: bool, id: u64, recv: u64 },
92    Welcome { recv: u64 },
93    Refuse(u8),
94    Data { off: u64, bytes: Vec<u8> },
95    Ack(u64),
96    Fin(u64),
97    Reset(u8),
98}
99
100fn bad(m: &str) -> io::Error {
101    io::Error::new(io::ErrorKind::InvalidData, m.to_string())
102}
103
104async fn u64_of<R: AsyncRead + Unpin>(r: &mut R) -> io::Result<u64> {
105    let mut b = [0u8; 8];
106    r.read_exact(&mut b).await?;
107    Ok(u64::from_be_bytes(b))
108}
109
110async fn read_frame<R: AsyncRead + Unpin>(r: &mut R, max_frame: usize) -> io::Result<Frame> {
111    let mut t = [0u8; 1];
112    r.read_exact(&mut t).await?;
113    Ok(match t[0] {
114        HELLO => {
115            let mut f = [0u8; 1];
116            r.read_exact(&mut f).await?;
117            Frame::Hello { resume: f[0] & 1 == 1, id: u64_of(r).await?, recv: u64_of(r).await? }
118        }
119        WELCOME => Frame::Welcome { recv: u64_of(r).await? },
120        REFUSE | RESET => {
121            let mut c = [0u8; 1];
122            r.read_exact(&mut c).await?;
123            if t[0] == REFUSE { Frame::Refuse(c[0]) } else { Frame::Reset(c[0]) }
124        }
125        DATA => {
126            let off = u64_of(r).await?;
127            let mut l = [0u8; 4];
128            r.read_exact(&mut l).await?;
129            let n = u32::from_be_bytes(l) as usize;
130            if n > max_frame {
131                return Err(bad("data frame too large"));
132            }
133            let mut bytes = vec![0u8; n];
134            r.read_exact(&mut bytes).await?;
135            Frame::Data { off, bytes }
136        }
137        ACK => Frame::Ack(u64_of(r).await?),
138        FIN => Frame::Fin(u64_of(r).await?),
139        _ => return Err(bad("unknown frame")),
140    })
141}
142
143fn encode(f: &Frame, out: &mut Vec<u8>) {
144    match f {
145        Frame::Hello { resume, id, recv } => {
146            out.extend([HELLO, *resume as u8]);
147            out.extend(id.to_be_bytes());
148            out.extend(recv.to_be_bytes());
149        }
150        Frame::Welcome { recv } => {
151            out.push(WELCOME);
152            out.extend(recv.to_be_bytes());
153        }
154        Frame::Refuse(c) => out.extend([REFUSE, *c]),
155        Frame::Reset(c) => out.extend([RESET, *c]),
156        Frame::Data { off, bytes } => {
157            out.push(DATA);
158            out.extend(off.to_be_bytes());
159            out.extend((bytes.len() as u32).to_be_bytes());
160            out.extend(bytes);
161        }
162        Frame::Ack(n) => {
163            out.push(ACK);
164            out.extend(n.to_be_bytes());
165        }
166        Frame::Fin(n) => {
167            out.push(FIN);
168            out.extend(n.to_be_bytes());
169        }
170    }
171}
172
173async fn write_frame<W: AsyncWrite + Unpin>(w: &mut W, f: &Frame) -> io::Result<()> {
174    let mut b = Vec::new();
175    encode(f, &mut b);
176    w.write_all(&b).await?;
177    w.flush().await
178}
179
180type Sub = (ReadHalf<libp2p::Stream>, WriteHalf<libp2p::Stream>);
181
182/// What a [`Stream`] reads: bytes, or why the stream failed.
183type Chunk = Result<Vec<u8>, String>;
184
185#[derive(Default)]
186struct Info {
187    relayed: AtomicBool,
188    moves: AtomicU32,
189}
190
191/// A reliable byte stream to a peer that moves between relayed and direct connections without
192/// losing anything. Use it as a `futures` `AsyncRead`/`AsyncWrite`, or with the blocking
193/// `std::io::Read`/`Write` (not from inside an async task). Closing (or dropping) it ends the
194/// sending side; reads return 0 once the peer has closed its side and everything has arrived.
195pub struct Stream {
196    peer: PeerId,
197    protocol: String,
198    tx: Option<mpsc::Sender<Vec<u8>>>,
199    rx: mpsc::Receiver<Chunk>,
200    buf: Vec<u8>,
201    pos: usize,
202    info: Arc<Info>,
203    reset: mpsc::UnboundedSender<()>,
204    max_frame: usize,
205}
206
207impl std::fmt::Debug for Stream {
208    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209        f.debug_struct("Stream").field("peer", &self.peer).field("protocol", &self.protocol).field("path", &self.path()).finish()
210    }
211}
212
213impl Stream {
214    pub fn peer(&self) -> PeerId {
215        self.peer
216    }
217
218    pub fn protocol(&self) -> &str {
219        &self.protocol
220    }
221
222    /// The kind of connection the stream is on now.
223    pub fn path(&self) -> Path {
224        if self.info.relayed.load(Ordering::Relaxed) { Path::Relayed } else { Path::Direct }
225    }
226
227    /// How many times the stream has moved to another connection.
228    pub fn moves(&self) -> u32 {
229        self.info.moves.load(Ordering::Relaxed)
230    }
231
232    /// End the sending side (the peer reads to the end of what was written).
233    pub fn close_write(&mut self) {
234        self.tx = None;
235    }
236
237    /// Abort the stream both ways; the peer's reads fail.
238    pub fn reset(self) {
239        let _ = self.reset.unbounded_send(());
240    }
241}
242
243impl AsyncRead for Stream {
244    fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, out: &mut [u8]) -> Poll<io::Result<usize>> {
245        let this = &mut *self;
246        loop {
247            if this.pos < this.buf.len() {
248                let n = out.len().min(this.buf.len() - this.pos);
249                out[..n].copy_from_slice(&this.buf[this.pos..this.pos + n]);
250                this.pos += n;
251                return Poll::Ready(Ok(n));
252            }
253            match this.rx.poll_next_unpin(cx) {
254                Poll::Ready(Some(Ok(v))) => {
255                    this.buf = v;
256                    this.pos = 0;
257                }
258                Poll::Ready(Some(Err(e))) => return Poll::Ready(Err(io::Error::new(io::ErrorKind::ConnectionReset, e))),
259                Poll::Ready(None) => return Poll::Ready(Ok(0)),
260                Poll::Pending => return Poll::Pending,
261            }
262        }
263    }
264}
265
266impl AsyncWrite for Stream {
267    fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
268        let max = self.max_frame;
269        let Some(tx) = self.tx.as_mut() else { return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())) };
270        if buf.is_empty() {
271            return Poll::Ready(Ok(0));
272        }
273        match tx.poll_ready(cx) {
274            Poll::Ready(Ok(())) => {
275                let n = buf.len().min(max);
276                match tx.start_send(buf[..n].to_vec()) {
277                    Ok(()) => Poll::Ready(Ok(n)),
278                    Err(_) => Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())),
279                }
280            }
281            Poll::Ready(Err(_)) => Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())),
282            Poll::Pending => Poll::Pending,
283        }
284    }
285
286    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
287        Poll::Ready(Ok(()))
288    }
289
290    fn poll_close(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
291        self.tx = None;
292        Poll::Ready(Ok(()))
293    }
294}
295
296impl io::Read for Stream {
297    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
298        futures::executor::block_on(AsyncReadExt::read(self, buf))
299    }
300}
301
302impl io::Write for Stream {
303    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
304        futures::executor::block_on(AsyncWriteExt::write(self, buf))
305    }
306
307    fn flush(&mut self) -> io::Result<()> {
308        Ok(())
309    }
310}
311
312/// Inbound streams of one protocol. Dropping it stops accepting them.
313pub struct Incoming {
314    protocol: String,
315    rx: mpsc::Receiver<Stream>,
316    _task: Abort,
317}
318
319struct Abort(tokio::task::AbortHandle);
320
321impl Drop for Abort {
322    fn drop(&mut self) {
323        self.0.abort();
324    }
325}
326
327impl Incoming {
328    pub fn protocol(&self) -> &str {
329        &self.protocol
330    }
331
332    /// The next stream (blocking; `None` once the node stops).
333    pub fn accept(&mut self) -> Option<Stream> {
334        futures::executor::block_on(self.rx.next())
335    }
336
337    /// The next stream, waiting at most `d`.
338    pub fn accept_timeout(&mut self, d: Duration) -> Option<Stream> {
339        let deadline = Instant::now() + d;
340        loop {
341            match self.rx.try_recv() {
342                Ok(s) => return Some(s),
343                Err(mpsc::TryRecvError::Closed) => return None,
344                Err(mpsc::TryRecvError::Empty) if Instant::now() >= deadline => return None,
345                Err(mpsc::TryRecvError::Empty) => std::thread::sleep(Duration::from_millis(5)),
346            }
347        }
348    }
349
350    /// The next stream (async).
351    pub async fn next(&mut self) -> Option<Stream> {
352        self.rx.next().await
353    }
354}
355
356impl futures::Stream for Incoming {
357    type Item = Stream;
358
359    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Stream>> {
360        self.rx.poll_next_unpin(cx)
361    }
362}
363
364/// A substream that resumes a stream, handed to its driver.
365struct Resume {
366    sub: Sub,
367    relayed: bool,
368    conn: ConnectionId,
369    recv: u64,
370}
371
372/// An accepted stream's route for resumes, and whether it still counts against
373/// [`Limits::max_streams`]: it stops counting once both sides have ended it, while its driver
374/// lingers to answer a late resume.
375struct Route {
376    resume: mpsc::UnboundedSender<Resume>,
377    live: bool,
378}
379
380type Registry = Arc<Mutex<HashMap<(PeerId, u64), Route>>>;
381
382fn stream_err(e: OpenError) -> crate::NetError {
383    crate::NetError::Network(e.to_string())
384}
385
386fn app_side(peer: PeerId, protocol: &StreamProtocol, limits: &Limits, relayed: bool) -> (Stream, AppEnds, Arc<Info>) {
387    let (tx, app_in) = mpsc::channel(4);
388    let (app_out, rx) = mpsc::channel(4);
389    let (reset, reset_rx) = mpsc::unbounded();
390    let info = Arc::new(Info::default());
391    info.relayed.store(relayed, Ordering::Relaxed);
392    let s = Stream {
393        peer,
394        protocol: protocol.to_string(),
395        tx: Some(tx),
396        rx,
397        buf: vec![],
398        pos: 0,
399        info: info.clone(),
400        reset,
401        max_frame: limits.max_frame,
402    };
403    (s, AppEnds { app_in, app_out, reset_rx }, info)
404}
405
406struct AppEnds {
407    app_in: mpsc::Receiver<Vec<u8>>,
408    app_out: mpsc::Sender<Chunk>,
409    reset_rx: mpsc::UnboundedReceiver<()>,
410}
411
412/// Open a stream of `protocol` to `peer` (already connected or dialable by peer id).
413pub(crate) async fn open(control: Control, peer: PeerId, protocol: StreamProtocol, limits: Limits) -> crate::Result<Stream> {
414    let id = u64::from_be_bytes(uuid::Uuid::new_v4().as_bytes()[..8].try_into().unwrap_or_default());
415    let watch = control.watch();
416    let (sub, relayed, conn, _) = handshake(&control, peer, &protocol, id, false, 0, &limits).await?;
417    let (s, ends, info) = app_side(peer, &protocol, &limits, relayed);
418    let d = Driver::new(peer, protocol, id, true, limits, control, ends, info, watch, None);
419    tokio::spawn(d.run(sub, relayed, conn));
420    Ok(s)
421}
422
423/// The opener's handshake on a new substream: `Hello`, then the peer's `Welcome`.
424async fn handshake(
425    control: &Control,
426    peer: PeerId,
427    protocol: &StreamProtocol,
428    id: u64,
429    resume: bool,
430    recv: u64,
431    limits: &Limits,
432) -> crate::Result<(Sub, bool, ConnectionId, u64)> {
433    let opened = tokio::time::timeout(HANDSHAKE, control.open(peer, protocol.clone()))
434        .await
435        .map_err(|_| crate::NetError::Network(format!("no stream to {peer} in time")))?
436        .map_err(stream_err)?;
437    let (s, relayed, conn) = opened;
438    let (mut r, mut w) = s.split();
439    let shake = async {
440        write_frame(&mut w, &Frame::Hello { resume, id, recv }).await?;
441        read_frame(&mut r, limits.max_frame).await
442    };
443    match tokio::time::timeout(HANDSHAKE, shake).await {
444        Ok(Ok(Frame::Welcome { recv })) => Ok(((r, w), relayed, conn, recv)),
445        Ok(Ok(Frame::Refuse(REFUSE_BUSY))) => Err(crate::NetError::Network(format!("{peer} has too many {protocol} streams"))),
446        Ok(Ok(Frame::Refuse(_))) => Err(crate::NetError::Network(format!("{peer} refused the {protocol} stream"))),
447        Ok(Ok(_)) => Err(crate::NetError::Network("unexpected stream frame".into())),
448        Ok(Err(e)) => Err(crate::NetError::Network(format!("stream handshake: {e}"))),
449        Err(_) => Err(crate::NetError::Network("stream handshake timed out".into())),
450    }
451}
452
453/// Accept streams of `protocol`: answer handshakes, hand new streams to the returned
454/// [`Incoming`] and resumes to their drivers.
455pub(crate) fn accept(control: Control, protocol: StreamProtocol, limits: Limits, rt: &tokio::runtime::Handle) -> crate::Result<Incoming> {
456    let Some(mut inbound) = control.accept(protocol.clone(), limits.backlog.max(1)) else {
457        return Err(crate::NetError::Network(format!("{protocol} streams are accepted already")));
458    };
459    // one sender, so the channel holds exactly `backlog` streams (each clone would add a slot)
460    let (tx, rx) = mpsc::channel(limits.backlog.max(1) - 1);
461    let tx = Arc::new(Mutex::new(tx));
462    let registry: Registry = Arc::default();
463    let p = protocol.clone();
464    let task = rt.spawn(async move {
465        while let Some((peer, s, relayed, conn)) = inbound.next().await {
466            let (control, protocol, registry, tx) = (control.clone(), p.clone(), registry.clone(), tx.clone());
467            tokio::spawn(async move {
468                let (mut r, mut w) = s.split();
469                let hello = tokio::time::timeout(HANDSHAKE, read_frame(&mut r, limits.max_frame)).await;
470                let Ok(Ok(Frame::Hello { resume, id, recv })) = hello else { return };
471                if resume {
472                    let to = registry.lock().ok().and_then(|m| m.get(&(peer, id)).map(|r| r.resume.clone()));
473                    match to {
474                        Some(to) => {
475                            let _ = to.unbounded_send(Resume { sub: (r, w), relayed, conn, recv });
476                        }
477                        None => {
478                            let _ = write_frame(&mut w, &Frame::Refuse(REFUSE_UNKNOWN)).await;
479                        }
480                    }
481                    return;
482                }
483                let full = registry
484                    .lock()
485                    .map(|m| m.values().filter(|r| r.live).count() >= limits.max_streams || m.contains_key(&(peer, id)))
486                    .unwrap_or(true);
487                if full {
488                    let _ = write_frame(&mut w, &Frame::Refuse(REFUSE_BUSY)).await;
489                    return;
490                }
491                let (s, ends, info) = app_side(peer, &protocol, &limits, relayed);
492                let queued = tx.lock().map(|mut t| t.try_send(s).is_ok()).unwrap_or(false);
493                if !queued {
494                    let _ = write_frame(&mut w, &Frame::Refuse(REFUSE_BUSY)).await;
495                    return;
496                }
497                if write_frame(&mut w, &Frame::Welcome { recv: 0 }).await.is_err() {
498                    return;
499                }
500                let (rtx, rrx) = mpsc::unbounded();
501                if let Ok(mut m) = registry.lock() {
502                    m.insert((peer, id), Route { resume: rtx, live: true });
503                }
504                let watch = control.watch();
505                let slot = registry.clone();
506                let release = move || {
507                    if let Ok(mut m) = slot.lock()
508                        && let Some(r) = m.get_mut(&(peer, id))
509                    {
510                        r.live = false;
511                    }
512                };
513                let d = Driver::new(peer, protocol, id, false, limits, control, ends, info, watch, Some(rrx)).with_release(release);
514                d.run((r, w), relayed, conn).await;
515                if let Ok(mut m) = registry.lock() {
516                    m.remove(&(peer, id));
517                }
518            });
519        }
520        if let Ok(mut t) = tx.lock() {
521            t.close_channel();
522        }
523    });
524    Ok(Incoming { protocol: protocol.to_string(), rx, _task: Abort(task.abort_handle()) })
525}
526
527/// Carries one logical stream over its current substream, and moves it.
528struct Driver {
529    peer: PeerId,
530    protocol: StreamProtocol,
531    id: u64,
532    opener: bool,
533    limits: Limits,
534    control: Control,
535    _warm: Warm,
536    info: Arc<Info>,
537    watch: mpsc::UnboundedReceiver<PathEvent>,
538    resumes: Option<mpsc::UnboundedReceiver<Resume>>,
539    // the current substream's writer and generation; frames from every reader
540    writer: Option<WriteHalf<libp2p::Stream>>,
541    relayed: bool,
542    conn: Option<ConnectionId>,
543    want_move: bool,
544    generation: u64,
545    frames_tx: mpsc::Sender<(u64, Frame)>,
546    frames: mpsc::Receiver<(u64, Frame)>,
547    // a substream's reader saw it end (apart from frames, which wait while the inbox is full)
548    lost_tx: mpsc::UnboundedSender<u64>,
549    lost: mpsc::UnboundedReceiver<u64>,
550    // sending: bytes from `acked` on, the next offset to write, the total once closed
551    out: VecDeque<u8>,
552    acked: u64,
553    sent: u64,
554    app_in: Option<mpsc::Receiver<Vec<u8>>>,
555    fin: Option<u64>,
556    fin_sent: Option<u64>,
557    // receiving
558    inbox: VecDeque<Vec<u8>>,
559    inbox_bytes: usize,
560    recv: u64,
561    // bytes handed to the application (or dropped for it): what we acknowledge, so a sender's
562    // window bounds what we buffer and frames never have to wait
563    delivered: u64,
564    ack_sent: u64,
565    peer_fin: Option<u64>,
566    app_out: Option<mpsc::Sender<Chunk>>,
567    /// `None` once the application dropped its end (an end, not a reset).
568    reset_rx: Option<mpsc::UnboundedReceiver<()>>,
569    last: Instant,
570    /// Called once both sides have ended the stream (frees its `max_streams` slot).
571    release: Option<Box<dyn FnOnce() + Send>>,
572}
573
574enum Step {
575    Go,
576    Lost,
577    Fail(String),
578    Done,
579}
580
581impl Driver {
582    #[allow(clippy::too_many_arguments)]
583    fn new(
584        peer: PeerId,
585        protocol: StreamProtocol,
586        id: u64,
587        opener: bool,
588        limits: Limits,
589        control: Control,
590        ends: AppEnds,
591        info: Arc<Info>,
592        watch: mpsc::UnboundedReceiver<PathEvent>,
593        resumes: Option<mpsc::UnboundedReceiver<Resume>>,
594    ) -> Self {
595        let (frames_tx, frames) = mpsc::channel(16);
596        let (lost_tx, lost) = mpsc::unbounded();
597        Driver {
598            peer,
599            protocol,
600            id,
601            opener,
602            limits,
603            _warm: control.warm(peer),
604            control,
605            info,
606            watch,
607            resumes,
608            writer: None,
609            relayed: false,
610            conn: None,
611            want_move: false,
612            generation: 0,
613            frames_tx,
614            frames,
615            lost_tx,
616            lost,
617            out: VecDeque::new(),
618            acked: 0,
619            sent: 0,
620            app_in: Some(ends.app_in),
621            fin: None,
622            fin_sent: None,
623            inbox: VecDeque::new(),
624            inbox_bytes: 0,
625            recv: 0,
626            delivered: 0,
627            ack_sent: 0,
628            peer_fin: None,
629            app_out: Some(ends.app_out),
630            reset_rx: Some(ends.reset_rx),
631            last: Instant::now(),
632            release: None,
633        }
634    }
635
636    fn with_release(mut self, release: impl FnOnce() + Send + 'static) -> Self {
637        self.release = Some(Box::new(release));
638        self
639    }
640
641    /// Make `sub` the stream's substream; the peer has `peer_recv` bytes of ours.
642    fn adopt(&mut self, sub: Sub, relayed: bool, conn: ConnectionId, peer_recv: u64) {
643        let (mut r, w) = sub;
644        if let Some(mut old) = self.writer.replace(w) {
645            tokio::spawn(async move {
646                let _ = old.close().await;
647            });
648        }
649        if self.generation > 0 {
650            self.info.moves.fetch_add(1, Ordering::Relaxed);
651        }
652        self.generation += 1;
653        self.relayed = relayed;
654        self.conn = Some(conn);
655        self.info.relayed.store(relayed, Ordering::Relaxed);
656        self.on_ack(peer_recv);
657        self.sent = self.acked;
658        self.fin_sent = None;
659        // what we have counts as acknowledged: the handshake carried it
660        self.ack_sent = self.ack_sent.max(self.recv);
661        let (g, mut tx, lost, max) = (self.generation, self.frames_tx.clone(), self.lost_tx.clone(), self.limits.max_frame);
662        tokio::spawn(async move {
663            loop {
664                match read_frame(&mut r, max).await {
665                    Ok(f) => {
666                        if tx.send((g, f)).await.is_err() {
667                            break;
668                        }
669                    }
670                    Err(_) => {
671                        let _ = lost.unbounded_send(g);
672                        break;
673                    }
674                }
675            }
676        });
677        tracing::debug!(peer = %self.peer, id = self.id, relayed, "network: stream on a new path");
678    }
679
680    fn on_ack(&mut self, n: u64) {
681        if n > self.acked {
682            let k = ((n - self.acked) as usize).min(self.out.len());
683            self.out.drain(..k);
684            self.acked += k as u64;
685        }
686    }
687
688    async fn run(mut self, sub: Sub, relayed: bool, conn: ConnectionId) {
689        self.adopt(sub, relayed, conn, 0);
690        let mut done_at: Option<Instant> = None;
691        let mut tick = tokio::time::interval(ACK_EVERY);
692        loop {
693            if self.want_move {
694                self.want_move = false;
695                self.migrate().await;
696            }
697            let step = if self.writer.is_some() { self.flush().await } else { Step::Lost };
698            let step = match step {
699                Step::Go => self.select(&mut tick, done_at).await,
700                s => s,
701            };
702            match step {
703                Step::Go => {}
704                Step::Done => return,
705                Step::Fail(e) => return self.fail(e).await,
706                Step::Lost => {
707                    if done_at.is_some() {
708                        return;
709                    }
710                    self.writer = None;
711                    self.conn = None;
712                    if let Err(e) = self.recover().await {
713                        return self.fail(e).await;
714                    }
715                }
716            }
717            if done_at.is_none() && self.finished() {
718                done_at = Some(Instant::now());
719                if let Some(release) = self.release.take() {
720                    release();
721                }
722            }
723        }
724    }
725
726    fn finished(&self) -> bool {
727        self.fin.is_some_and(|f| self.acked == f && self.fin_sent.is_some())
728            && self.peer_fin.is_some_and(|f| f == self.recv)
729            && self.inbox.is_empty()
730            && self.app_out.is_none()
731            && self.ack_sent == self.recv
732    }
733
734    async fn fail(mut self, why: String) {
735        tracing::debug!(peer = %self.peer, id = self.id, "network: stream failed: {why}");
736        if let Some(w) = self.writer.as_mut() {
737            let _ = write_frame(w, &Frame::Reset(RESET_APP)).await;
738        }
739        if let Some(mut tx) = self.app_out.take() {
740            let _ = tx.try_send(Err(why));
741        }
742    }
743
744    /// Write what hasn't been written on this substream (data, then the end).
745    async fn flush(&mut self) -> Step {
746        let Some(w) = self.writer.as_mut() else { return Step::Lost };
747        let end = self.acked + self.out.len() as u64;
748        let mut batch = Vec::new();
749        while self.sent < end && batch.len() < 4 * self.limits.max_frame {
750            let from = (self.sent - self.acked) as usize;
751            let n = (self.out.len() - from).min(self.limits.max_frame);
752            let bytes: Vec<u8> = self.out.range(from..from + n).copied().collect();
753            encode(&Frame::Data { off: self.sent, bytes }, &mut batch);
754            self.sent += n as u64;
755        }
756        if let Some(f) = self.fin
757            && self.sent == f
758            && self.fin_sent != Some(self.generation)
759        {
760            encode(&Frame::Fin(f), &mut batch);
761            self.fin_sent = Some(self.generation);
762        }
763        if self.delivered > self.ack_sent && (self.delivered - self.ack_sent >= (self.limits.window / 4) as u64 || self.peer_fin.is_some()) {
764            encode(&Frame::Ack(self.delivered), &mut batch);
765            self.ack_sent = self.delivered;
766        }
767        if batch.is_empty() {
768            return Step::Go;
769        }
770        self.last = Instant::now();
771        // a write can hang on a connection that is closing: its going away ends the wait
772        let (conn, watch, peer, opener, relayed) = (self.conn, &mut self.watch, self.peer, self.opener, self.relayed);
773        let mut want_move = false;
774        let write = async {
775            w.write_all(&batch).await?;
776            w.flush().await
777        };
778        tokio::pin!(write);
779        let step = loop {
780            tokio::select! {
781                r = &mut write => break if r.is_ok() { Step::Go } else { Step::Lost },
782                ev = watch.next() => match ev {
783                    Some(ev) if !ev.up && Some(ev.conn) == conn => break Step::Lost,
784                    Some(ev) if moves_to(&ev, peer, opener, relayed) => want_move = true,
785                    _ => {}
786                },
787            }
788        };
789        self.want_move |= want_move;
790        step
791    }
792
793    async fn select(&mut self, tick: &mut tokio::time::Interval, done_at: Option<Instant>) -> Step {
794        let window = self.limits.window;
795        let can_take = self.app_in.is_some() && self.out.len() < window;
796        let deliver = !self.inbox.is_empty() || (self.peer_fin.is_some_and(|f| f == self.recv) && self.app_out.is_some());
797        let idle = self.limits.idle.map(|d| self.last + d);
798        let linger = done_at.map(|t| t + LINGER);
799        tokio::select! {
800            // a reset comes before the end that dropping the stream also makes
801            biased;
802            r = async { self.reset_rx.as_mut().unwrap().next().await }, if self.reset_rx.is_some() => match r {
803                Some(()) => Step::Fail("reset".into()),
804                // dropped: what was written still goes out, then the end
805                None => {
806                    self.reset_rx = None;
807                    Step::Go
808                }
809            },
810            f = self.frames.next() => match f {
811                Some((g, f)) => self.frame(g, f),
812                None => Step::Go,
813            },
814            g = self.lost.next() => match g {
815                Some(g) if g == self.generation => Step::Lost,
816                _ => Step::Go,
817            },
818            c = async { self.app_in.as_mut().unwrap().next().await }, if can_take => {
819                match c {
820                    Some(v) => self.out.extend(v),
821                    None => {
822                        self.app_in = None;
823                        self.fin = Some(self.acked + self.out.len() as u64);
824                    }
825                }
826                self.last = Instant::now();
827                Step::Go
828            }
829            r = futures::future::poll_fn(|cx| match self.app_out.as_mut() {
830                Some(tx) => tx.poll_ready(cx).map(|r| r.is_ok()),
831                None => Poll::Ready(false),
832            }), if deliver => {
833                self.deliver(r);
834                Step::Go
835            }
836            ev = self.watch.next() => match ev {
837                Some(ev) if !ev.up && Some(ev.conn) == self.conn => Step::Lost,
838                Some(ev) if moves_to(&ev, self.peer, self.opener, self.relayed) => {
839                    self.want_move = true;
840                    Step::Go
841                }
842                _ => Step::Go,
843            },
844            r = async { self.resumes.as_mut().unwrap().next().await }, if self.resumes.is_some() => {
845                if let Some(r) = r {
846                    self.take_resume(r).await;
847                }
848                Step::Go
849            }
850            _ = tick.tick() => {
851                if self.delivered > self.ack_sent && let Some(w) = self.writer.as_mut() {
852                    self.ack_sent = self.delivered;
853                    if write_frame(w, &Frame::Ack(self.delivered)).await.is_err() {
854                        return Step::Lost;
855                    }
856                }
857                Step::Go
858            }
859            _ = async { tokio::time::sleep_until(idle.unwrap().into()).await }, if idle.is_some() && done_at.is_none() => {
860                if let Some(w) = self.writer.as_mut() {
861                    let _ = write_frame(w, &Frame::Reset(RESET_IDLE)).await;
862                }
863                Step::Fail("idle".into())
864            }
865            _ = async { tokio::time::sleep_until(linger.unwrap().into()).await }, if linger.is_some() => Step::Done,
866        }
867    }
868
869    fn frame(&mut self, _g: u64, f: Frame) -> Step {
870        self.last = Instant::now();
871        match f {
872            Frame::Data { off, bytes } => {
873                let end = off + bytes.len() as u64;
874                if off <= self.recv && end > self.recv {
875                    let tail = bytes[(self.recv - off) as usize..].to_vec();
876                    self.recv = end;
877                    if self.app_out.is_some() {
878                        self.inbox_bytes += tail.len();
879                        self.inbox.push_back(tail);
880                    } else {
881                        self.delivered = self.recv;
882                    }
883                }
884                Step::Go
885            }
886            Frame::Ack(n) => {
887                self.on_ack(n);
888                Step::Go
889            }
890            Frame::Fin(n) => {
891                self.peer_fin = Some(n);
892                Step::Go
893            }
894            Frame::Reset(c) => Step::Fail(if c == RESET_IDLE { "the peer reset the idle stream".into() } else { "the peer reset the stream".into() }),
895            _ => Step::Go,
896        }
897    }
898
899    fn deliver(&mut self, ready: bool) {
900        if !ready {
901            // the reader is gone: what arrives is dropped
902            self.app_out = None;
903            self.inbox.clear();
904            self.inbox_bytes = 0;
905            self.delivered = self.recv;
906            return;
907        }
908        let Some(tx) = self.app_out.as_mut() else { return };
909        match self.inbox.pop_front() {
910            Some(v) => {
911                self.inbox_bytes -= v.len();
912                self.delivered += v.len() as u64;
913                if tx.start_send(Ok(v)).is_err() {
914                    self.app_out = None;
915                }
916            }
917            None => self.app_out = None, // the peer's end: reads return 0
918        }
919    }
920
921    /// The opener moves the stream to a new direct connection.
922    async fn migrate(&mut self) {
923        if !self.control.has_direct(self.peer) {
924            return;
925        }
926        match handshake(&self.control, self.peer, &self.protocol, self.id, true, self.recv, &self.limits).await {
927            Ok((sub, false, conn, peer_recv)) => self.adopt(sub, false, conn, peer_recv),
928            Ok(_) => {}
929            Err(e) => tracing::debug!(peer = %self.peer, "network: stream stays relayed: {e}"),
930        }
931    }
932
933    async fn take_resume(&mut self, r: Resume) {
934        let Resume { sub: (rd, mut w), relayed, conn, recv } = r;
935        if write_frame(&mut w, &Frame::Welcome { recv: self.recv }).await.is_ok() {
936            self.adopt((rd, w), relayed, conn, recv);
937        }
938    }
939
940    /// The substream went away: the opener opens another, the acceptor waits for one.
941    async fn recover(&mut self) -> std::result::Result<(), String> {
942        let deadline = tokio::time::Instant::now() + self.limits.resume;
943        let mut wait = Duration::from_millis(100);
944        loop {
945            if tokio::time::Instant::now() >= deadline {
946                return Err("no path to the peer came back".into());
947            }
948            if self.opener {
949                match handshake(&self.control, self.peer, &self.protocol, self.id, true, self.recv, &self.limits).await {
950                    Ok((sub, relayed, conn, peer_recv)) => {
951                        self.adopt(sub, relayed, conn, peer_recv);
952                        return Ok(());
953                    }
954                    Err(e) if e.to_string().contains("refused") => return Err(e.to_string()),
955                    Err(e) => tracing::debug!(peer = %self.peer, "network: stream resume: {e}"),
956                }
957                tokio::time::sleep(wait.min(deadline.saturating_duration_since(tokio::time::Instant::now()))).await;
958                wait = (wait * 2).min(Duration::from_secs(2));
959            } else {
960                let next = async { self.resumes.as_mut().unwrap().next().await };
961                match tokio::time::timeout_at(deadline, next).await {
962                    Ok(Some(r)) => {
963                        self.take_resume(r).await;
964                        if self.writer.is_some() {
965                            return Ok(());
966                        }
967                    }
968                    Ok(None) => return Err("closed".into()),
969                    Err(_) => return Err("the peer did not come back".into()),
970                }
971            }
972        }
973    }
974}
975
976/// The opener moves a relayed stream when a direct connection to its peer comes up.
977fn moves_to(ev: &PathEvent, peer: PeerId, opener: bool, relayed: bool) -> bool {
978    opener && relayed && ev.up && !ev.relayed && ev.peer == peer
979}
980
981#[cfg(test)]
982mod tests {
983    use super::*;
984
985    #[test]
986    fn frames_round_trip() {
987        let frames = [
988            Frame::Hello { resume: true, id: 7, recv: 1 << 40 },
989            Frame::Welcome { recv: 3 },
990            Frame::Refuse(REFUSE_BUSY),
991            Frame::Data { off: 9, bytes: vec![1, 2, 3] },
992            Frame::Ack(12),
993            Frame::Fin(12),
994            Frame::Reset(RESET_APP),
995        ];
996        for f in frames {
997            let mut b = vec![];
998            encode(&f, &mut b);
999            let got = futures::executor::block_on(read_frame(&mut &b[..], 1024)).unwrap();
1000            assert_eq!(got, f);
1001        }
1002        let mut b = vec![];
1003        encode(&Frame::Data { off: 0, bytes: vec![0; 2048] }, &mut b);
1004        assert!(futures::executor::block_on(read_frame(&mut &b[..], 1024)).is_err());
1005        assert!(futures::executor::block_on(read_frame(&mut &[99u8][..], 1024)).is_err());
1006    }
1007}