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);
let _join = loop_.spawn();
Ok(Side {
handle,
events,
negotiation: Arc::new(Mutex::new(PerfectNegotiation::new(polite))),
open: 0,
})
}
enum Signal {
Description(Box<RTCSessionDescription>),
Candidate(RTCIceCandidateInit),
}
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 {
let mut outboxes: [VecDeque<Signal>; 2] = [VecDeque::new(), VecDeque::new()];
let mut offered = [false; 2];
for _ in 0..3_000 {
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;
}
_ => {}
}
}
}
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:?}"
);
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(())
}