rtci-sctp 0.5.0

Sans-I/O SCTP (RFC 9260) with partial reliability and stream reconfiguration, for WebRTC data channels
Documentation
//! RFC 3758 3.5 F2: "A sender MAY even choose to delay the sending of the FORWARD TSN in the
//! hope of bundling it with an outbound DATA chunk." F3: "Any delay applied to the sending of
//! FORWARD TSN chunk SHOULD NOT exceed 200ms and MUST NOT exceed 500ms." The form is
//! `TransportConfig::with_forward_tsn_delay(Some(delay))`; without it (the default) the FORWARD
//! TSN leaves at the instant the Advanced.Peer.Ack.Point moves
//! (`loss_recovery_test.rs::the_forward_tsn_leaves_as_soon_as_the_ack_point_advances`).

use super::*;
use crate::TransportConfig;
use crate::association::stream::ReliabilityType;
use crate::chunk::chunk_type::{CT_FORWARD_TSN, CT_PAYLOAD_DATA};
use crate::endpoint::link_test::{Link, first_chunk_type};
use std::cell::RefCell;
use std::rc::Rc;

const PPI: PayloadProtocolIdentifier = PayloadProtocolIdentifier::Binary;

/// The chunk types of a datagram (the common header is 12 bytes).
fn types(datagram: &Bytes) -> Vec<u8> {
    let mut out = vec![];
    let mut offset = 12;
    while offset + 4 <= datagram.len() {
        out.push(datagram[offset]);
        let length = u16::from_be_bytes([datagram[offset + 2], datagram[offset + 3]]) as usize;
        offset += length.max(4).next_multiple_of(4);
    }
    out
}

/// A connected link whose client holds FORWARD TSNs back for `delay`, with an ordered stream 1
/// of `maxRetransmits = 0`: its first message ("open") arrives, so the server has the stream
/// (as a data channel's DATA_CHANNEL_OPEN gives it one), and its second is lost: its T3-rtx
/// abandons it, and the FORWARD TSN that skips it finds no DATA to go with. Runs until that
/// FORWARD TSN is held; returns the link, the instant it became due and the chunk types of
/// every client datagram.
fn held_forward_tsn(delay: Duration) -> (Link, Instant, Rc<RefCell<Vec<Vec<u8>>>>) {
    let mut link = Link::new(
        TransportConfig::default().with_forward_tsn_delay(Some(delay)),
        TransportConfig::default(),
        4,
    );
    link.connect();
    let seen: Rc<RefCell<Vec<Vec<u8>>>> = Rc::default();
    let record = seen.clone();
    let mut data_seen = 0;
    link.filter = Some(Box::new(move |from_client: bool, datagram: &Bytes| {
        if !from_client {
            return false;
        }
        record.borrow_mut().push(types(datagram));
        if first_chunk_type(datagram) == Some(CT_PAYLOAD_DATA.0) {
            data_seen += 1;
            return data_seen == 2;
        }
        false
    }));
    let start = link.now;
    link.client
        .conn()
        .open_stream(1, PPI)
        .unwrap()
        .set_reliability_params(false, ReliabilityType::Rexmit, 0)
        .unwrap();
    link.client
        .conn()
        .stream(1)
        .unwrap()
        .write_sctp(start, &Bytes::from_static(b"open"), PPI)
        .unwrap();
    assert!(link.run_until(start + Duration::from_secs(5), |l| {
        !l.server.received.is_empty()
    }));
    let now = link.now;
    link.client
        .conn()
        .stream(1)
        .unwrap()
        .write_sctp(now, &Bytes::from_static(b"lost"), PPI)
        .unwrap();
    assert!(
        link.run_until(start + Duration::from_secs(20), |l| l
            .client
            .conn()
            .forward_tsn_due_at
            .is_some()),
        "the FORWARD TSN is held"
    );
    let client = link.client.conn();
    assert!(client.will_send_forward_tsn);
    assert!(sna32gt(
        client.advanced_peer_tsn_ack_point,
        client.cumulative_tsn_ack_point
    ));
    assert_eq!(0, client.stats.get_num_forward_tsns(), "not sent yet");
    assert!(
        client.timers.get(Timer::T3RTX).is_some(),
        "T3-rtx runs (RFC 3758 3.5 C5)"
    );
    let held_at = link.now;
    (link, held_at, seen)
}

fn with_forward_tsn(seen: &Rc<RefCell<Vec<Vec<u8>>>>) -> Vec<Vec<u8>> {
    seen.borrow()
        .iter()
        .filter(|t| t.contains(&CT_FORWARD_TSN.0))
        .cloned()
        .collect()
}

/// With no DATA to go with, the FORWARD TSN waits its delay and then goes alone; a delay above
/// 200 ms is taken as 200 ms (F3). The receiver then moves past the lost message.
#[test]
fn a_forward_tsn_with_no_data_to_go_with_waits_its_delay_then_goes_alone() {
    for (configured, expected) in [
        (Duration::from_millis(100), Duration::from_millis(100)),
        (Duration::from_secs(1), Duration::from_millis(200)),
    ] {
        let (mut link, held_at, seen) = held_forward_tsn(configured);
        assert!(link.run_until(held_at + Duration::from_secs(1), |l| {
            l.client.conn().stats.get_num_forward_tsns() > 0
        }));
        assert_eq!(expected, link.now - held_at, "configured {configured:?}");
        assert_eq!(vec![vec![CT_FORWARD_TSN.0]], with_forward_tsn(&seen));
        assert!(link.run_until(link.now + Duration::from_secs(5), |l| {
            l.client.conn().inflight_queue.is_empty()
        }));
    }
}

/// DATA written while the FORWARD TSN is held carries it: one packet, the FORWARD TSN ahead
/// of the DATA (RFC 9260 6.10), sent when the DATA is, before the delay runs out; nothing is
/// sent alone. The receiver skips the lost message and delivers the new one.
///
/// (The server has stream 1 before the FORWARD TSN: one naming a stream the receiver has not
/// seen yet is not remembered, and the next ordered message would wait for the skipped
/// number; see the sctp-32 report.)
#[test]
fn a_delayed_forward_tsn_goes_with_data_written_within_its_delay() {
    let (mut link, held_at, seen) = held_forward_tsn(Duration::from_millis(200));
    link.run_for(Duration::from_millis(50));
    assert_eq!(0, link.client.conn().stats.get_num_forward_tsns());
    let now = link.now;
    assert_eq!(held_at + Duration::from_millis(50), now);
    link.client
        .conn()
        .stream(1)
        .unwrap()
        .write_sctp(now, &Bytes::from_static(b"next"), PPI)
        .unwrap();
    assert!(
        link.run_until(now, |l| l.client.conn().stats.get_num_forward_tsns() > 0),
        "the FORWARD TSN left with the DATA, at once"
    );
    assert_eq!(
        vec![vec![CT_FORWARD_TSN.0, CT_PAYLOAD_DATA.0]],
        with_forward_tsn(&seen)
    );
    assert!(
        link.run_until(now + Duration::from_secs(5), |l| l.server.received.len()
            == 2)
    );
    assert_eq!(
        vec![
            (1, Bytes::from_static(b"open")),
            (1, Bytes::from_static(b"next"))
        ],
        link.server.received
    );
    link.run_for(Duration::from_secs(1));
    assert_eq!(1, with_forward_tsn(&seen).len(), "no FORWARD TSN alone");
}