rtci-sctp 0.5.0

Sans-I/O SCTP (RFC 9260) with partial reliability and stream reconfiguration, for WebRTC data channels
Documentation
//! Long-run soak: an association whose TSNs cross 2^32 (RFC 9260 section 1.6, serial number
//! arithmetic) while its Stream Sequence Numbers (section 6.5) or, with I-DATA, its Message
//! Identifiers (RFC 8260 section 2.1) wrap, on a lossy path that reorders, with a partially
//! reliable stream (RFC 3758) abandoning what it loses and moving the peer on with FORWARD-TSN
//! (I-FORWARD-TSN). Deterministic (seeded link), virtual time, no sleeping.

use super::robustness_test::*;
use super::*;
use crate::chunk::chunk_type::{CT_FORWARD_TSN, CT_I_FORWARD_TSN};
use crate::endpoint::link_test::Link;
use std::cell::Cell;
use std::rc::Rc;

const PPI: PayloadProtocolIdentifier = PayloadProtocolIdentifier::Binary;
const RELIABLE: u16 = 1;
const PARTIAL: u16 = 2;
/// Messages written on each stream.
const MESSAGES: u32 = 3_000;
/// Where each stream's counters start: its SSN (DATA) and MID (I-DATA) are this many messages
/// before their wrap, on both ends.
const BEFORE_WRAP: [u32; 2] = [700, 600];

fn message(stream: u16, index: u32) -> Bytes {
    let mut bytes = vec![0u8; 16];
    bytes[..2].copy_from_slice(&stream.to_be_bytes());
    bytes[2..6].copy_from_slice(&index.to_be_bytes());
    Bytes::from(bytes)
}

fn indexes(received: &[(StreamId, Bytes)], stream: u16) -> Vec<u32> {
    received
        .iter()
        .filter(|(id, _)| *id == stream)
        .map(|(_, bytes)| {
            assert_eq!(&stream.to_be_bytes()[..], &bytes[..2], "on its own stream");
            u32::from_be_bytes(bytes[2..6].try_into().unwrap())
        })
        .collect()
}

/// 3000 messages on a reliable ordered stream and 3000 on an ordered stream that never
/// retransmits (RFC 3758 / RFC 8831 `maxRetransmits` 0), 3 % of the datagrams lost each way,
/// 2 % overtaking, up to 2 ms of jitter. The client's TSNs start 3000 before 2^32 and its
/// streams' SSNs (or MIDs) 700 and 600 before their wrap. Every reliable message arrives once,
/// in order; the partial stream delivers most of its messages, in order, none twice, and
/// abandons the rest with forward TSNs; the TSNs and both counters wrapped; neither end closed.
fn soak(interleaving: bool, seed: u64) {
    let config = TransportConfig::default().with_message_interleaving(interleaving);
    let mut link = Link::new(config.clone(), config, seed);
    link.begin_connect();
    let first_tsn = u32::MAX - 3_000;
    {
        // The client's TSNs start 3000 before the wrap, before its INIT leaves.
        let a = link.client.conn();
        a.my_next_tsn = first_tsn;
        a.min_tsn2measure_rtt = first_tsn;
        a.cumulative_tsn_ack_point = first_tsn.wrapping_sub(1);
        a.advanced_peer_tsn_ack_point = first_tsn.wrapping_sub(1);
        a.stored_init.as_mut().unwrap().initial_tsn = first_tsn;
        a.control_queue.clear();
        a.send_init().unwrap();
    }
    let deadline = link.now + Duration::from_secs(60);
    assert!(link.run_until(deadline, |l| l.client.connected() && l.server.connected()));

    for peer in [&mut link.client, &mut link.server] {
        let conn = peer.conn();
        for (id, before) in [RELIABLE, PARTIAL].into_iter().zip(BEFORE_WRAP) {
            conn.open_stream(id, PPI).unwrap();
            let stream = conn.streams.get_mut(&id).unwrap();
            stream.sequence_number = (65_536 - before) as u16;
            stream.ordered_mid = before.wrapping_neg();
            stream.reassembly_queue.next_ssn = (65_536 - before) as u16;
            stream.reassembly_queue.next_mid = before.wrapping_neg();
        }
    }
    link.client
        .conn()
        .stream(PARTIAL)
        .unwrap()
        .set_reliability_params(false, ReliabilityType::Rexmit, 0)
        .unwrap();

    let forward_tsns = Rc::new(Cell::new(0usize));
    let counter = forward_tsns.clone();
    link.filter = Some(Box::new(move |from_client, datagram: &Bytes| {
        if from_client {
            let forwards = chunks_of(datagram)
                .iter()
                .filter(|chunk| chunk[0] == CT_FORWARD_TSN.0 || chunk[0] == CT_I_FORWARD_TSN.0)
                .count();
            counter.set(counter.get() + forwards);
        }
        false
    }));
    link.loss_percent = 3;
    link.reorder_percent = 2;
    link.jitter = Duration::from_millis(2);

    let mut written = 0;
    while written < MESSAGES {
        let now = link.now;
        let until = (written + 50).min(MESSAGES);
        let a = link.client.conn();
        for index in written..until {
            for id in [RELIABLE, PARTIAL] {
                a.stream(id)
                    .unwrap()
                    .write_sctp(now, &message(id, index), PPI)
                    .unwrap();
            }
        }
        written = until;
        link.run_for(Duration::from_millis(20));
    }
    let deadline = link.now + Duration::from_secs(120);
    let all = |l: &mut Link| indexes(&l.server.received, RELIABLE).len() == MESSAGES as usize;
    assert!(
        link.run_until(deadline, all),
        "interleaving {interleaving}: {} of {MESSAGES} reliable messages",
        indexes(&link.server.received, RELIABLE).len()
    );
    link.run_for(Duration::from_secs(5));

    assert_eq!(
        (0..MESSAGES).collect::<Vec<_>>(),
        indexes(&link.server.received, RELIABLE),
        "interleaving {interleaving}: every reliable message once, in order"
    );
    let partial = indexes(&link.server.received, PARTIAL);
    assert!(
        partial.windows(2).all(|pair| pair[0] < pair[1]),
        "interleaving {interleaving}: the partial stream in order, none twice"
    );
    assert!(
        partial.len() < MESSAGES as usize && partial.len() > MESSAGES as usize * 3 / 4,
        "interleaving {interleaving}: {} partial messages delivered",
        partial.len()
    );
    assert!(
        forward_tsns.get() > 0,
        "abandoned messages were forwarded over"
    );

    let a = link.client.conn();
    assert!(
        (2_000..first_tsn).contains(&a.my_next_tsn),
        "the TSNs wrapped: next {}",
        a.my_next_tsn
    );
    for (id, before) in [RELIABLE, PARTIAL].into_iter().zip(BEFORE_WRAP) {
        let stream = &a.streams[&id];
        let counter = if interleaving {
            stream.ordered_mid
        } else {
            u32::from(stream.sequence_number)
        };
        assert_eq!(
            MESSAGES - before,
            counter,
            "stream {id}: its counter wrapped"
        );
    }
    assert!(!a.is_ended(), "the client closed");
    assert!(!link.server.conn().is_ended(), "the server closed");
}

#[test]
fn data_streams_run_on_across_the_tsn_and_ssn_wraps_under_loss() {
    soak(false, 11);
}

#[test]
fn i_data_streams_run_on_across_the_tsn_and_mid_wraps_under_loss() {
    soak(true, 12);
}