rtci-sctp 0.5.0

Sans-I/O SCTP (RFC 9260) with partial reliability and stream reconfiguration, for WebRTC data channels
Documentation
//! RFC 7496 section 3.2, the priority policy: "When storing a user message in the send buffer
//! while there is not enough available space, the SCTP stack at the sender side MAY abandon
//! other user message(s) of the same SCTP association (with the same or a different stream)
//! with a priority lower than the provided one. User messages sent reliably are considered to
//! have a priority higher than all messages sent with the Priority Policy." Section 4.2: "The
//! value of zero is the highest priority, and larger numbers in pr_value denote lower
//! priorities." The send buffer is `TransportConfig::with_send_buffer_size`; a stream sends
//! with the policy after `set_reliability_params(.., ReliabilityType::Priority, priority)`.

use super::*;
use crate::TransportConfig;
use crate::association::stream::ReliabilityType;
use crate::endpoint::link_test::Link;

const PPI: PayloadProtocolIdentifier = PayloadProtocolIdentifier::Binary;
const MESSAGE: usize = 1000;

/// A connected link whose client has a send buffer of `size` bytes.
fn link_with_send_buffer(size: Option<u32>) -> Link {
    let mut link = Link::new(
        TransportConfig::default().with_send_buffer_size(size),
        TransportConfig::default(),
        3,
    );
    link.connect();
    link
}

/// Opens client stream `id`, with the priority policy at `priority` (or reliable for `None`).
fn open(link: &mut Link, id: u16, priority: Option<u32>) {
    let mut stream = link.client.conn().open_stream(id, PPI).unwrap();
    if let Some(priority) = priority {
        stream
            .set_reliability_params(false, ReliabilityType::Priority, priority)
            .unwrap();
    }
}

/// Sets the priority of the next messages of client stream `id`.
fn set_priority(link: &mut Link, id: u16, priority: u32) {
    link.client
        .conn()
        .stream(id)
        .unwrap()
        .set_reliability_params(false, ReliabilityType::Priority, priority)
        .unwrap();
}

/// Writes a message of `len` bytes, all `tag`, on client stream `id`, without running the link.
fn write(link: &mut Link, id: u16, tag: u8, len: usize) -> Result<usize> {
    let now = link.now;
    link.client
        .conn()
        .stream(id)
        .unwrap()
        .write_sctp(now, &Bytes::from(vec![tag; len]), PPI)
}

/// The tags of the messages the server received, in order, with their streams.
fn received(link: &Link) -> Vec<(u16, u8)> {
    link.server
        .received
        .iter()
        .map(|(id, data)| {
            assert!(data.iter().all(|b| *b == data[0]), "one tag per message");
            (*id, data[0])
        })
        .collect()
}

/// The `MessageAbandoned` events the client has seen.
fn abandoned(link: &Link) -> Vec<(u16, bool)> {
    link.client
        .events
        .iter()
        .filter_map(|e| match e {
            Event::Stream(StreamEvent::MessageAbandoned { id, transmitted }) => {
                Some((*id, *transmitted))
            }
            _ => None,
        })
        .collect()
}

/// Runs the link until the client has nothing left to send (bounded).
fn drain(link: &mut Link) {
    let deadline = link.now + Duration::from_secs(10);
    assert!(
        link.run_until(deadline, |l| l.client.conn().buffered_amount() == 0),
        "the client's send buffer did not empty"
    );
    link.run_for(Duration::from_millis(500));
}

/// A send buffer of 4000 bytes holds four messages of the policy (priorities 5, 1, 5, 3). A
/// message of priority 2 and 1500 bytes does not fit: the two messages of priority 5 (the
/// lowest, the earlier one first) are abandoned, which is enough, and the message of priority 3
/// (lower than 2 as well) is kept. The peer receives the others in order: the abandoned
/// messages took no Stream Sequence Number, so nothing is missing on the ordered stream, and
/// nothing of them was sent.
#[test]
fn with_a_full_send_buffer_a_higher_priority_message_abandons_lower_priority_ones() -> Result<()> {
    let mut link = link_with_send_buffer(Some(4000));
    open(&mut link, 1, Some(5));
    write(&mut link, 1, b'a', MESSAGE)?;
    set_priority(&mut link, 1, 1);
    write(&mut link, 1, b'b', MESSAGE)?;
    set_priority(&mut link, 1, 5);
    write(&mut link, 1, b'c', MESSAGE)?;
    set_priority(&mut link, 1, 3);
    write(&mut link, 1, b'd', MESSAGE)?;
    assert_eq!(
        4000,
        link.client.conn().buffered_amount(),
        "the buffer is full"
    );
    assert!(abandoned(&link).is_empty());

    set_priority(&mut link, 1, 2);
    assert_eq!(
        1500,
        write(&mut link, 1, b'e', 1500)?,
        "room was made for it"
    );
    assert_eq!(3500, link.client.conn().buffered_amount());

    drain(&mut link);
    assert_eq!(
        vec![(1, false), (1, false)],
        abandoned(&link),
        "two messages abandoned before their first transmission"
    );
    assert_eq!(vec![(1, b'b'), (1, b'd'), (1, b'e')], received(&link));
    assert_eq!(0, link.client.conn().stats.get_num_forward_tsns());
    Ok(())
}

/// A message abandons only lower priorities: one of the same priority stays, and when no
/// lower one makes room the write fails with `ErrBufferFull`, nothing abandoned, nothing
/// queued.
#[test]
fn a_message_never_abandons_one_of_equal_or_higher_priority() -> Result<()> {
    let mut link = link_with_send_buffer(Some(2000));
    open(&mut link, 1, Some(1));
    write(&mut link, 1, b'x', MESSAGE)?;
    set_priority(&mut link, 1, 2);
    write(&mut link, 1, b'y', MESSAGE)?;

    assert_eq!(
        Err(Error::ErrBufferFull),
        write(&mut link, 1, b'z', MESSAGE)
    );
    assert_eq!(2000, link.client.conn().buffered_amount());
    // A message larger than the whole buffer cannot be made room for either.
    set_priority(&mut link, 1, 0);
    assert_eq!(Err(Error::ErrBufferFull), write(&mut link, 1, b'w', 3000));
    assert_eq!(2000, link.client.conn().buffered_amount());

    drain(&mut link);
    assert!(abandoned(&link).is_empty());
    assert_eq!(vec![(1, b'x'), (1, b'y')], received(&link));
    Ok(())
}

/// RFC 7496 3.2: a reliable message ranks above every message of the policy, priority 0
/// included, on another stream too: it abandons one of priority 0, and no message of the
/// policy abandons it.
#[test]
fn reliable_messages_rank_above_every_priority_policy_message() -> Result<()> {
    let mut link = link_with_send_buffer(Some(2000));
    open(&mut link, 1, None);
    open(&mut link, 2, Some(0));
    write(&mut link, 1, b'r', MESSAGE)?;
    write(&mut link, 2, b'p', MESSAGE)?;

    assert_eq!(
        Err(Error::ErrBufferFull),
        write(&mut link, 2, b'q', MESSAGE),
        "priority 0 does not abandon a reliable message"
    );
    assert_eq!(MESSAGE, write(&mut link, 1, b's', MESSAGE)?);

    drain(&mut link);
    assert_eq!(vec![(2, false)], abandoned(&link));
    assert_eq!(vec![(1, b'r'), (1, b's')], received(&link));
    Ok(())
}

/// Without a send buffer size (the default) nothing is limited and nothing is abandoned.
#[test]
fn without_a_send_buffer_size_no_priority_message_is_abandoned() -> Result<()> {
    let mut link = link_with_send_buffer(None);
    open(&mut link, 1, Some(9));
    for tag in 0..8u8 {
        write(&mut link, 1, tag, MESSAGE)?;
    }
    set_priority(&mut link, 1, 0);
    write(&mut link, 1, 8, MESSAGE)?;
    assert_eq!(9 * MESSAGE, link.client.conn().buffered_amount());

    drain(&mut link);
    assert!(abandoned(&link).is_empty());
    assert_eq!(
        (0..9u8).map(|tag| (1, tag)).collect::<Vec<_>>(),
        received(&link)
    );
    Ok(())
}