git clone https://garage44.eu/jeroen/pinnacle.git.. /p2p/src/stream.rs
//! Reliable, ordered streams between two contacts, over a session's
//! datagrams, which may be lost, doubled or reordered: a remote terminal,
//! a file. A stream belongs to the contact, not to a session, so a new
//! session (keys renewed, the contact moved, found again in the DHT)
//! carries on with whatever is not yet acknowledged.
//!
//! FRAME: stream id (4) ‖ flags (1) ‖ seq (4) ‖ ack (4) ‖ sack (8) ‖ data
//!
//! - Frames flagged DATA are numbered by `seq` from 0, each way. The opener
//! flags each OPEN until one is acknowledged; FIN is on a side's last (empty) frame.
//! - `ack` is the next frame expected from the other side; bit k of `sack`
//! says frame ack + 1 + k came too, so one loss resends one frame.
//! - At most [`WINDOW`] frames are unacknowledged; a frame is resent after
//! the retransmission timeout, doubled at each try.
use alloc::collections::VecDeque;
use alloc::vec::Vec;
pub const HEADER: usize = 21;
/// Data bytes per frame: with the headers well under a path's usual MTU.
pub const FRAME: usize = 1100;
pub const WINDOW: u32 = 64;
/// A stream whose oldest frame has gone unacknowledged this long ends.
pub const GIVE_UP_MS: u64 = 300_000;
/// How long a finished stream still answers the other side's resends.
pub const LINGER_MS: u64 = 30_000;
const INITIAL_RTO: u64 = 1000;
const MIN_RTO: u64 = 200;
const MAX_RTO: u64 = 16_000;
pub const DATA: u8 = 1;
pub const OPEN: u8 = 2;
pub const FIN: u8 = 4;
pub const RESET: u8 = 8;
pub struct Header {
pub id: u32,
pub flags: u8,
pub seq: u32,
pub ack: u32,
pub sack: u64,
}
impl Header {
pub fn parse(b: &[u8]) -> Option<(Header, &[u8])> {
if b.len() < HEADER {
return None;
}
let u32_at = |at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap());
Some((
Header {
id: u32_at(0),
flags: b[4],
seq: u32_at(5),
ack: u32_at(9),
sack: u64::from_le_bytes(b[13..21].try_into().unwrap()),
},
&b[HEADER..],
))
}
pub fn frame(&self, data: &[u8]) -> Vec<u8> {
let mut f = Vec::with_capacity(HEADER + data.len());
f.extend_from_slice(&self.id.to_le_bytes());
f.push(self.flags);
f.extend_from_slice(&self.seq.to_le_bytes());
f.extend_from_slice(&self.ack.to_le_bytes());
f.extend_from_slice(&self.sack.to_le_bytes());
f.extend_from_slice(data);
f
}
}
/// A frame given a number, until acknowledged.
struct Flight {
seq: u32,
flags: u8,
data: Vec<u8>,
/// When last sent; None: not yet, or to go again at once.
sent: Option<u64>,
first_sent: Option<u64>,
tries: u32,
}
/// What came in on a stream, in order.
#[derive(Default)]
pub struct Delivered {
pub data: Vec<Vec<u8>>,
/// The other side has finished sending.
pub fin: bool,
}
pub struct Stream {
pub id: u32,
next_seq: u32,
/// Written but not yet numbered: the window was full.
queued: VecDeque<(u8, Vec<u8>)>,
flight: VecDeque<Flight>,
/// The next frame to deliver, and those that came ahead of it.
expected: u32,
early: Vec<(u32, u8, Vec<u8>)>,
srtt: Option<u64>,
rto: u64,
ack_due: bool,
/// This side opened the stream and has had no acknowledgement yet:
/// every frame says OPEN, so the stream begins at the other side
/// whichever arrives first.
opening: bool,
pub fin_sent: bool,
pub fin_received: bool,
/// Since when both sides are finished and everything acknowledged.
pub done_since: Option<u64>,
/// Opened by the other side, and its service tag not yet whole: the
/// bytes of it so far. None once it is (or on the opener's side).
pub tag: Option<Vec<u8>>,
}
impl Stream {
pub fn new(id: u32, opener: bool) -> Stream {
let mut s = Stream {
id,
next_seq: 0,
queued: VecDeque::new(),
flight: VecDeque::new(),
expected: 0,
early: Vec::new(),
srtt: None,
rto: INITIAL_RTO,
ack_due: false,
opening: opener,
fin_sent: false,
fin_received: false,
done_since: None,
tag: (!opener).then(Vec::new),
};
if opener {
// An empty first frame: the other side learns of the stream at
// once, before anything is written.
s.queued.push_back((DATA, Vec::new()));
}
s
}
pub fn write(&mut self, data: &[u8]) {
if self.fin_sent {
return;
}
for chunk in data.chunks(FRAME) {
self.queued.push_back((DATA, chunk.to_vec()));
}
}
/// Ends this side's sending, after what is written.
pub fn finish(&mut self) {
if !self.fin_sent {
self.fin_sent = true;
self.queued.push_back((DATA | FIN, Vec::new()));
}
}
/// Bytes written and not yet acknowledged: what a writer holds back on.
pub fn backlog(&self) -> usize {
self.queued.iter().map(|q| q.1.len()).sum::<usize>()
+ self.flight.iter().map(|f| f.data.len()).sum::<usize>()
}
/// When the oldest unacknowledged frame was first sent.
pub fn oldest_unacked(&self) -> Option<u64> {
self.flight.iter().filter_map(|f| f.first_sent).min()
}
pub fn has_output(&self) -> bool {
!self.queued.is_empty() || !self.flight.is_empty() || self.ack_due
}
/// Everything unacknowledged goes again at the next [`Stream::output`]:
/// a new session is up, the old one's datagrams may be lost.
pub fn resend_all(&mut self) {
for f in &mut self.flight {
f.sent = None;
}
}
fn sack(&self) -> u64 {
let mut bits = 0u64;
for (seq, _, _) in &self.early {
let k = seq.wrapping_sub(self.expected).wrapping_sub(1);
if k < 64 {
bits |= 1 << k;
}
}
bits
}
fn header(&self, flags: u8, seq: u32) -> Header {
Header {
id: self.id,
flags,
seq,
ack: self.expected,
sack: self.sack(),
}
}
/// The frames to send now: new ones the window lets out, those whose
/// timeout ran out, else an acknowledgement if one is owed.
pub fn output(&mut self, now: u64) -> Vec<Vec<u8>> {
// The window runs from the oldest unacknowledged frame, as the
// other side's does from the next it expects: frames past it are
// dropped there however few are in flight.
while self.next_seq - self.flight.front().map_or(self.next_seq, |f| f.seq) < WINDOW
&& let Some((flags, data)) = self.queued.pop_front()
{
self.flight.push_back(Flight {
seq: self.next_seq,
flags,
data,
sent: None,
first_sent: None,
tries: 0,
});
self.next_seq += 1;
}
let mut frames = Vec::new();
for i in 0..self.flight.len() {
let f = &self.flight[i];
let due = match f.sent {
None => true,
Some(at) => now - at >= (self.rto << f.tries.saturating_sub(1).min(6)).min(MAX_RTO),
};
if due {
let frame = self
.header(f.flags | if self.opening { OPEN } else { 0 }, f.seq)
.frame(&f.data);
let f = &mut self.flight[i];
f.sent = Some(now);
f.first_sent.get_or_insert(now);
f.tries += 1;
frames.push(frame);
}
}
if frames.is_empty() && self.ack_due {
frames.push(self.header(0, 0).frame(&[]));
}
self.ack_due = false;
frames
}
/// A frame for this stream: its acknowledgement taken, its data kept
/// in order; returns what can now be delivered.
pub fn receive(&mut self, h: &Header, data: &[u8], now: u64) -> Delivered {
let acked = |seq: u32| {
seq.wrapping_sub(h.ack) >= 1 << 31
|| (seq != h.ack && {
let k = seq.wrapping_sub(h.ack).wrapping_sub(1);
k < 64 && h.sack & (1 << k) != 0
})
};
if h.ack > 0 {
self.opening = false;
}
let mut sample = None;
self.flight.retain(|f| {
if acked(f.seq) {
if f.tries == 1 {
sample = f.sent.map(|at| now - at);
}
false
} else {
true
}
});
if let Some(rtt) = sample {
// Smoothed as TCP does (RFC 6298, a variance left out).
let srtt = self.srtt.map_or(rtt, |s| (7 * s + rtt) / 8);
self.srtt = Some(srtt);
self.rto = (2 * srtt).clamp(MIN_RTO, MAX_RTO);
}
let mut out = Delivered::default();
if h.flags & DATA == 0 {
return out;
}
self.ack_due = true;
let ahead = h.seq.wrapping_sub(self.expected);
if ahead >= WINDOW || self.early.iter().any(|e| e.0 == h.seq) {
// Already delivered, beyond the window, or already held.
return out;
}
self.early.push((h.seq, h.flags, data.to_vec()));
while let Some(i) = self.early.iter().position(|e| e.0 == self.expected) {
let (_, flags, data) = self.early.swap_remove(i);
self.expected += 1;
if !data.is_empty() {
out.data.push(data);
}
if flags & FIN != 0 {
self.fin_received = true;
out.fin = true;
}
}
out
}
/// Both sides finished, everything acknowledged.
pub fn is_done(&self) -> bool {
self.fin_sent && self.fin_received && self.queued.is_empty() && self.flight.is_empty()
}
}