rtci-stream-driver 0.6.0

A socket driver for a sans-I/O WebRTC engine (ICE-TCP, TURN over TCP and TLS, whole peer connections) on an async runtime of your choice
Documentation
//! Two drivers run as tasks (`task::task`), driven only through their handles and event
//! channels, negotiating with `negotiation::PerfectNegotiation` while both offer at once
//! (glare): the polite side rolls back and answers, both data channels open. Signalling keeps
//! each direction's order (a candidate follows the description it belongs to), as the W3C
//! pattern assumes. On `MockRuntime`: virtual time, the in-memory network.

use rtci::peer_connection::RTCPeerConnectionBuilder;
use rtci::peer_connection::configuration::setting_engine::SettingEngineBuilder;
use rtci::peer_connection::event::{RTCDataChannelEvent, RTCPeerConnectionEvent};
use rtci::peer_connection::sdp::RTCSessionDescription;
use rtci::peer_connection::transport::RTCIceCandidateInit;
use rtci_stream_driver::negotiation::PerfectNegotiation;
use rtci_stream_driver::peer::{PeerDriver, PeerDriverConfig};
use rtci_stream_driver::runtime::{self, MockRuntime, Runtime};
use rtci_stream_driver::task::{PeerEvents, PeerHandle, PeerTaskEvent, task};
use std::collections::VecDeque;
use std::net::{IpAddr, Ipv4Addr};
use std::sync::{Arc, Mutex};
use std::time::Duration;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

const A: IpAddr = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
const B: IpAddr = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2));

struct Side {
    handle: PeerHandle,
    events: PeerEvents,
    negotiation: Arc<Mutex<PerfectNegotiation>>,
    open: usize,
}

fn side(runtime: &Arc<dyn Runtime>, ip: IpAddr, polite: bool, label: &str) -> Result<Side> {
    let mut pc = RTCPeerConnectionBuilder::new()
        .with_setting_engine(
            SettingEngineBuilder::new()
                .with_tcp_candidate_gathering(false)
                .build(),
        )
        .build(runtime.now())?;
    pc.create_data_channel(label, None)?;
    let driver = PeerDriver::with_runtime(runtime.clone(), pc, PeerDriverConfig::on(vec![ip]));
    let (loop_, handle, events) = task(driver);
    // Detached: the loop runs until its handle shuts it down.
    let _join = loop_.spawn();
    Ok(Side {
        handle,
        events,
        negotiation: Arc::new(Mutex::new(PerfectNegotiation::new(polite))),
        open: 0,
    })
}

/// What one side signals to the other.
enum Signal {
    Description(Box<RTCSessionDescription>),
    Candidate(RTCIceCandidateInit),
}

/// Hands `signal` to `to`'s negotiation; the answer it makes to an offer.
async fn deliver(to: &Side, signal: Signal) -> Result<Option<RTCSessionDescription>> {
    let negotiation = to.negotiation.clone();
    Ok(to
        .handle
        .call(move |d| {
            let now = d.runtime().now();
            let mut negotiation = negotiation.lock().unwrap();
            match signal {
                Signal::Description(description) => {
                    negotiation.on_remote_description(d.pc_mut(), now, *description)
                }
                Signal::Candidate(candidate) => negotiation
                    .on_remote_candidate(d.pc_mut(), candidate)
                    .map(|()| None),
            }
        })
        .await??)
}

#[test]
fn two_tasks_negotiate_through_glare_with_perfect_negotiation_and_open_both_channels() -> Result<()>
{
    let mock = MockRuntime::new();
    let runtime: Arc<dyn Runtime> = Arc::new(mock.clone());
    let mut sides = [
        side(&runtime, A, true, "from-a")?,
        side(&runtime, B, false, "from-b")?,
    ];
    mock.run(async {
        // Each direction's signalling, in the order it was sent (an ordered channel, as the
        // W3C pattern assumes): a candidate never overtakes the description it follows.
        let mut outboxes: [VecDeque<Signal>; 2] = [VecDeque::new(), VecDeque::new()];
        // Nothing is delivered until both sides have offered: the first offers always cross,
        // whichever task reports its negotiation-needed first.
        let mut offered = [false; 2];
        for _ in 0..3_000 {
            // Everything both sides reported (their offers too) before anything is delivered.
            for i in 0..2 {
                while let Some(event) = sides[i].events.try_recv() {
                    let PeerTaskEvent::Connection(event) = event else {
                        continue;
                    };
                    match *event {
                        RTCPeerConnectionEvent::OnNegotiationNeededEvent => {
                            let negotiation = sides[i].negotiation.clone();
                            let offer = sides[i]
                                .handle
                                .call(move |d| {
                                    let now = d.runtime().now();
                                    negotiation
                                        .lock()
                                        .unwrap()
                                        .on_negotiation_needed(d.pc_mut(), now)
                                })
                                .await??;
                            offered[i] |= offer.is_some();
                            outboxes[i].extend(offer.map(|o| Signal::Description(Box::new(o))));
                        }
                        RTCPeerConnectionEvent::OnIceCandidateEvent(event) => {
                            let Some(candidate) = event.candidate else {
                                continue;
                            };
                            outboxes[i].push_back(Signal::Candidate(candidate.to_json()?));
                        }
                        RTCPeerConnectionEvent::OnDataChannel(RTCDataChannelEvent::OnOpen(_)) => {
                            sides[i].open += 1;
                        }
                        _ => {}
                    }
                }
            }
            // Then each direction in order; an answer joins its sender's queue behind what
            // that side sent before it.
            while offered.iter().all(|o| *o) && outboxes.iter().any(|o| !o.is_empty()) {
                for from in 0..2 {
                    while let Some(signal) = outboxes[from].pop_front() {
                        if let Some(answer) = deliver(&sides[1 - from], signal).await? {
                            outboxes[1 - from].push_back(Signal::Description(Box::new(answer)));
                        }
                    }
                }
            }
            if sides.iter().all(|s| s.open >= 2) {
                break;
            }
            runtime::sleep(runtime.as_ref(), Duration::from_millis(10)).await;
        }
        Ok::<_, Box<dyn std::error::Error>>(())
    })?;
    assert!(
        sides.iter().all(|s| s.open >= 2),
        "both channels open on both sides: {} {}",
        sides[0].open,
        sides[1].open
    );
    let collisions: Vec<u64> = sides
        .iter()
        .map(|s| s.negotiation.lock().unwrap().collisions())
        .collect();
    assert!(
        collisions.iter().all(|c| *c >= 1),
        "the offers crossed: {collisions:?}"
    );

    // The handle ends the loop in order; the events say so, and later calls fail.
    let ended = mock.run(async {
        sides[0].handle.shutdown(Duration::from_millis(100)).await?;
        let mut ended = false;
        while let Some(event) = sides[0].events.recv().await {
            ended |= matches!(event, PeerTaskEvent::Ended);
        }
        Ok::<_, Box<dyn std::error::Error>>(ended)
    })?;
    assert!(ended);
    assert!(mock.run(sides[0].handle.call(|_| ())).is_err());
    Ok(())
}