use std::collections::BTreeMap;
use std::time::{Duration, Instant};
use sansio::Protocol;
use super::agent_rfc8445_test::*;
use super::*;
use crate::candidate::candidate_host::CandidateHostConfig;
const MS: Duration = Duration::from_millis(1);
const S: Duration = Duration::from_secs(1);
#[derive(Default)]
struct Trace {
requests: Vec<(Instant, TransactionId, SocketAddr)>,
states: Vec<(Instant, ConnectionState)>,
renewed: Vec<(Instant, TransactionId)>,
ignored: Vec<(Instant, TransactionId)>,
most_open_consent_transactions: usize,
}
impl Trace {
fn saw(&self, state: ConnectionState) -> bool {
self.states.iter().any(|(_, s)| *s == state)
}
fn at(&self, state: ConnectionState) -> Option<Instant> {
self.states
.iter()
.find(|(_, s)| *s == state)
.map(|(at, _)| *at)
}
fn sent_at(&self, id: TransactionId) -> Instant {
self.requests.iter().find(|r| r.1 == id).unwrap().0
}
}
#[derive(Default)]
struct SlowPeer {
in_flight: BTreeMap<(Instant, u64), (Message, SocketAddr)>,
sequence: u64,
}
impl SlowPeer {
fn run(
&mut self,
a: &mut Agent,
from: Instant,
until: Instant,
mut round_trip: impl FnMut(Instant, usize, SocketAddr) -> Option<Duration>,
) -> Trace {
let mut trace = Trace::default();
let mut now = from;
loop {
while let Some(entry) = self.in_flight.first_entry() {
if entry.key().0 > now {
break;
}
let (response, peer) = entry.remove();
Self::arrive(a, now, &response, peer, &mut trace);
}
a.handle_timeout(now).unwrap();
while let Some(t) = a.poll_write() {
let mut m = Message {
raw: t.message.to_vec(),
..Message::default()
};
m.decode().unwrap();
if m.typ != BINDING_REQUEST
|| trace.requests.iter().any(|r| r.1 == m.transaction_id)
{
continue;
}
let to = t.transport.peer_addr;
let sent_before = trace.requests.len();
trace.requests.push((now, m.transaction_id, to));
if let Some(round_trip) = round_trip(now, sent_before, to) {
let response =
peer_response(BINDING_SUCCESS, m.transaction_id, addr(LOCAL), None);
if round_trip.is_zero() {
Self::arrive(a, now, &response, to, &mut trace);
} else {
self.sequence += 1;
self.in_flight
.insert((now + round_trip, self.sequence), (response, to));
}
}
}
while let Some(e) = a.poll_event() {
if let Event::ConnectionStateChange(s) = e.event {
trace.states.push((e.now, s));
}
}
trace.most_open_consent_transactions = trace.most_open_consent_transactions.max(
a.pending_binding_requests
.iter()
.filter(|r| r.consent)
.count(),
);
let arrival = self.in_flight.first_key_value().map(|(key, _)| key.0);
let next = match (a.poll_timeout(), arrival) {
(Some(timer), Some(arrival)) => Some(timer.min(arrival)),
(timer, arrival) => timer.or(arrival),
};
match next {
Some(next) if next <= until => now = next.max(now + Duration::from_micros(1)),
_ => return trace,
}
}
}
fn arrive(a: &mut Agent, now: Instant, response: &Message, peer: SocketAddr, t: &mut Trace) {
let consent = |a: &Agent| {
a.find_remote_candidate(peer)
.and_then(|index| a.remote_candidates[index].last_consent())
};
let before = consent(a);
let _ = deliver(a, now, response, &peer.to_string());
if consent(a) == Some(now) && before != Some(now) {
t.renewed.push((now, response.transaction_id));
} else {
t.ignored.push((now, response.transaction_id));
}
}
}
fn connected(config: AgentConfig) -> (Agent, SlowPeer, Instant) {
let start = Instant::now();
let mut a = started_agent(start, config, &[REMOTE_A]);
let mut peer = SlowPeer::default();
peer.run(&mut a, start, start + S, |_, _, _| Some(20 * MS));
assert_eq!(a.state(), ConnectionState::Connected);
(a, peer, start + S)
}
fn fixed(wait: Duration) -> AgentConfig {
AgentConfig {
consent_response_wait: ConsentResponseWait::Fixed(wait),
..config(true)
}
}
fn is_at(at: Option<Instant>, expected: Instant) -> bool {
at.is_some_and(|at| at >= expected && at - expected < MS)
}
fn selected_consent(a: &Agent) -> Instant {
let (_, remote) = a.get_selected_candidate_pair().expect("a selected pair");
remote.last_consent().expect("consent")
}
#[test]
fn test_consent_is_kept_when_the_round_trip_rises_above_the_rto() {
for round_trip in [600 * MS, 800 * MS, 1000 * MS] {
let (mut a, mut peer, now) = connected(config(true));
let trace = peer.run(&mut a, now, now + 300 * S, |_, _, _| Some(round_trip));
assert_eq!(
trace.states,
vec![],
"{round_trip:?}: the state of an answered path changed"
);
assert_eq!(a.state(), ConnectionState::Connected);
assert!(trace.requests.len() >= 45, "{}", trace.requests.len());
assert_eq!(trace.ignored, vec![], "{round_trip:?}");
assert!(trace.renewed.len() + 1 >= trace.requests.len());
assert!(now + 300 * S - selected_consent(&a) < 7 * S);
}
}
#[test]
fn test_a_pair_whose_round_trip_is_long_from_the_first_check_keeps_consent() {
let start = Instant::now();
let mut a = started_agent(start, config(true), &[REMOTE_A]);
let mut peer = SlowPeer::default();
let trace = peer.run(&mut a, start, start + 120 * S, |_, _, _| Some(800 * MS));
assert_eq!(
trace
.states
.iter()
.map(|(_, s)| *s)
.filter(|s| *s != ConnectionState::Checking)
.collect::<Vec<_>>(),
vec![ConnectionState::Connected],
"connected, and nothing else"
);
assert!(start + 120 * S - selected_consent(&a) < 7 * S);
}
#[test]
fn test_consent_is_kept_while_the_round_trip_grows_gradually() {
let (mut a, mut peer, now) = connected(config(true));
let mut round_trip = 20 * MS;
let trace = peer.run(&mut a, now, now + 400 * S, |_, _, _| {
round_trip = (round_trip * 5 / 4).min(4500 * MS);
Some(round_trip)
});
assert_eq!(round_trip, 4500 * MS);
assert_eq!(trace.states, vec![]);
assert_eq!(trace.ignored, vec![]);
assert_eq!(a.state(), ConnectionState::Connected);
}
#[test]
fn test_the_wait_grows_with_the_round_trip_the_responses_show() {
let (mut a, mut peer, now) = connected(config(true));
let mut round_trip = 20 * MS;
let trace = peer.run(&mut a, now, now + 600 * S, |_, _, _| {
round_trip = (round_trip * 5 / 4).min(12 * S);
Some(round_trip)
});
assert_eq!(round_trip, 12 * S);
assert!(!trace.saw(ConnectionState::Failed), "{:?}", trace.states);
assert_eq!(trace.ignored, vec![], "every answer was within its wait");
assert!(now + 600 * S - selected_consent(&a) < 7 * S);
let pair = a.candidate_pairs[a.selected_pair.unwrap()];
assert!(pair.rto.rto() >= 11 * S, "{:?}", pair.rto.rto());
}
#[test]
fn test_consent_is_kept_when_the_round_trip_jumps_to_six_seconds() {
let (mut a, mut peer, now) = connected(config(true));
let trace = peer.run(&mut a, now, now + 300 * S, |_, _, _| Some(6 * S));
assert!(!trace.saw(ConnectionState::Failed), "{:?}", trace.states);
assert_eq!(trace.ignored, vec![]);
assert!(now + 300 * S - selected_consent(&a) < 7 * S);
}
#[test]
fn test_a_consent_request_waits_sixteen_times_the_rto_for_its_response() {
for (after, renews, timer_runs) in [
(7_999 * MS, true, false),
(7_999 * MS, true, true),
(8 * S, false, false),
(8 * S, false, true),
] {
let (mut a, mut peer, now) = connected(config(true));
let before = selected_consent(&a);
let mut sent = None;
let mut at = now;
while sent.is_none() {
at = a.poll_timeout().unwrap().max(at + Duration::from_micros(1));
let trace = peer.run(&mut a, at, at, |_, _, _| None);
sent = trace.requests.first().map(|r| (r.0, r.1));
}
let (sent_at, id) = sent.unwrap();
let arrival = sent_at + after;
if timer_runs {
peer.run(&mut a, sent_at, arrival, |_, _, _| None);
}
let response = peer_response(BINDING_SUCCESS, id, addr(LOCAL), None);
let _ = deliver(&mut a, arrival, &response, REMOTE_A);
let expected = if renews { arrival } else { before };
assert_eq!(
selected_consent(&a),
expected,
"a response {after:?} after its request (timer ran: {timer_runs})"
);
}
}
#[test]
fn test_a_response_after_its_wait_renews_nothing_unless_the_wait_is_fixed() {
let (mut a, mut peer, now) = connected(config(true));
let last = selected_consent(&a);
let trace = peer.run(&mut a, now, now + 120 * S, |_, _, _| Some(9 * S));
assert_eq!(trace.renewed, vec![], "an answer 9 s after its request");
assert!(trace.ignored.len() >= 3);
assert!(
is_at(trace.at(ConnectionState::Failed), last + 30 * S),
"{:?}",
trace.states
);
assert!(a.pending_binding_requests.is_empty());
let (mut a, mut peer, now) = connected(fixed(60 * S));
let trace = peer.run(&mut a, now, now + 300 * S, |_, _, _| Some(9 * S));
assert!(!trace.saw(ConnectionState::Failed), "{:?}", trace.states);
assert_eq!(trace.ignored, vec![]);
assert!(now + 300 * S - selected_consent(&a) < 7 * S);
}
#[test]
fn test_consent_survives_loss_on_a_slow_path() {
let (mut a, mut peer, now) = connected(config(true));
let trace = peer.run(&mut a, now, now + 300 * S, |_, sent_before, _| {
(sent_before % 3 == 2).then_some(800 * MS)
});
assert!(!trace.saw(ConnectionState::Failed), "{:?}", trace.states);
assert_eq!(trace.ignored, vec![]);
assert!(trace.renewed.len() >= 15);
assert!(now + 300 * S - selected_consent(&a) < 19 * S);
let states: Vec<ConnectionState> = trace.states.iter().map(|(_, s)| *s).collect();
assert!(
states
.windows(2)
.any(|w| w == [ConnectionState::Disconnected, ConnectionState::Connected]),
"{states:?}"
);
}
#[test]
fn test_no_consent_transaction_is_kept_past_the_consent_expiry() {
for (cfg, held_renews, most) in [(config(true), false, 8), (fixed(60 * S), true, 15)] {
let (mut a, mut peer, now) = connected(cfg);
peer.run(&mut a, now, now + 60 * S, |_, _, _| Some(3 * S));
assert!(a.candidate_pairs[a.selected_pair.unwrap()].rto.rto() >= 2 * S);
let trace = peer.run(&mut a, now + 60 * S, now + 160 * S, |_, sent_before, _| {
Some(if sent_before == 2 { 31 * S } else { 3 * S })
});
assert!(!trace.saw(ConnectionState::Failed), "{:?}", trace.states);
let held = trace.requests[2].1;
assert_eq!(
trace.renewed.iter().any(|(_, id)| *id == held),
held_renews,
"a response 31 s after its request"
);
assert_eq!(
trace.ignored.iter().map(|(_, id)| *id).collect::<Vec<_>>(),
if held_renews { vec![] } else { vec![held] }
);
assert!(
trace.most_open_consent_transactions <= most,
"{} open consent transactions",
trace.most_open_consent_transactions
);
}
}
#[test]
fn test_unanswered_consent_transactions_are_bounded_and_end_with_the_consent() {
for (cfg, warm_up, open) in [
(config(true), None, 2..=3),
(config(true), Some(3 * S), 5..=8),
(fixed(60 * S), None, 4..=8),
] {
let (mut a, mut peer, mut now) = connected(cfg);
if let Some(round_trip) = warm_up {
peer.run(&mut a, now, now + 60 * S, |_, _, _| Some(round_trip));
now += 60 * S;
}
let before = selected_consent(&a);
let trace = peer.run(&mut a, now, now + 70 * S, |_, _, _| None);
let last = trace.renewed.last().map_or(before, |(at, _)| *at);
assert!(
is_at(trace.at(ConnectionState::Failed), last + 30 * S),
"{:?} after the last response",
trace.at(ConnectionState::Failed).map(|at| at - last)
);
if warm_up.is_none() {
let first_unanswered = trace.requests[0].0;
assert!(
is_at(
trace.at(ConnectionState::Disconnected),
first_unanswered + 5 * S
),
"{:?}",
trace.states
);
}
assert!(
open.contains(&trace.most_open_consent_transactions),
"{} open consent transactions, expected {open:?}",
trace.most_open_consent_transactions
);
assert!(a.pending_binding_requests.is_empty());
}
}
#[test]
fn test_responses_out_of_order_each_renew_consent() {
let (mut a, mut peer, now) = connected(config(true));
let trace = peer.run(&mut a, now, now + 120 * S, |_, sent_before, _| {
Some(if sent_before % 2 == 0 {
7 * S
} else {
200 * MS
})
});
assert!(!trace.saw(ConnectionState::Failed), "{:?}", trace.states);
assert_eq!(trace.ignored, vec![]);
let overtaken = trace
.renewed
.windows(2)
.filter(|w| trace.sent_at(w[1].1) < trace.sent_at(w[0].1))
.count();
assert!(
overtaken >= 5,
"{overtaken} answers arrived after a later one"
);
assert_eq!(selected_consent(&a), trace.renewed.last().unwrap().0);
}
#[test]
fn test_only_a_matching_authenticated_response_renews_consent() {
for cfg in [config(true), fixed(60 * S)] {
let (mut a, mut peer, now) = connected(cfg);
let before = selected_consent(&a);
let mut sent = None;
let mut at = now;
while sent.is_none() {
at = a.poll_timeout().unwrap().max(at + Duration::from_micros(1));
let trace = peer.run(&mut a, at, at, |_, _, _| None);
sent = trace.requests.first().map(|r| (r.0, r.1));
}
let (sent_at, id) = sent.unwrap();
let unsolicited = peer_response(BINDING_SUCCESS, TransactionId::new(), addr(LOCAL), None);
let _ = deliver(&mut a, sent_at + 100 * MS, &unsolicited, REMOTE_A);
assert_eq!(selected_consent(&a), before, "an unsolicited response");
let mut forged = Message::new();
forged
.build(&[
Box::new(BINDING_SUCCESS),
Box::new(id),
Box::new(XorMappedAddress {
ip: addr(LOCAL).ip(),
port: addr(LOCAL).port(),
}),
Box::new(MessageIntegrity::new_short_term_integrity_with_provider(
"notthepeerspassword".to_owned(),
provider().crypto(),
)),
Box::new(FINGERPRINT),
])
.unwrap();
let _ = deliver(&mut a, sent_at + 200 * MS, &forged, REMOTE_A);
assert_eq!(selected_consent(&a), before, "a forged response");
let genuine = peer_response(BINDING_SUCCESS, id, addr(LOCAL), None);
deliver(&mut a, sent_at + 900 * MS, &genuine, REMOTE_A).unwrap();
assert_eq!(selected_consent(&a), sent_at + 900 * MS);
let _ = deliver(&mut a, sent_at + 1500 * MS, &genuine, REMOTE_A);
assert_eq!(
selected_consent(&a),
sent_at + 900 * MS,
"a replayed response"
);
let mut next = None;
at = sent_at + 1500 * MS;
while next.is_none() {
at = a.poll_timeout().unwrap().max(at + Duration::from_micros(1));
let trace = peer.run(&mut a, at, at, |_, _, _| None);
next = trace.requests.first().map(|r| (r.0, r.1));
}
let (next_at, next_id) = next.unwrap();
let elsewhere = peer_response(BINDING_SUCCESS, next_id, addr(LOCAL), None);
let _ = deliver(&mut a, next_at + 100 * MS, &elsewhere, REMOTE_B);
assert_eq!(
selected_consent(&a),
sent_at + 900 * MS,
"from another address"
);
}
}
#[test]
fn test_a_late_response_on_another_pair_does_not_renew_the_selected_pairs_consent() {
let start = Instant::now();
let mut a = bare_agent(start, config(true));
for (remote, priority, foundation) in [(REMOTE_B, 500, "other"), (REMOTE_A, 400, "selected")] {
let candidate = CandidateHostConfig {
base_config: CandidateConfig {
network: "udp".to_owned(),
address: addr(remote).ip().to_string(),
port: addr(remote).port(),
component: 1,
priority,
foundation: foundation.to_owned(),
..Default::default()
},
..Default::default()
}
.new_candidate_host()
.unwrap();
a.add_remote_candidate(candidate).unwrap();
}
a.start_connectivity_checks(start, true, REMOTE_UFRAG.to_owned(), REMOTE_PWD.to_owned())
.unwrap();
let mut peer = SlowPeer::default();
let trace = peer.run(&mut a, start, start + 120 * S, |at, _, to| {
if to == addr(REMOTE_B) {
Some(10 * S)
} else if at < start + 3 * S {
Some(20 * MS)
} else {
None
}
});
let renewed_by = |remote: &str| -> Vec<Instant> {
trace
.renewed
.iter()
.filter(|(_, id)| {
trace
.requests
.iter()
.any(|r| r.1 == *id && r.2 == addr(remote))
})
.map(|(at, _)| *at)
.collect()
};
let selected_last = renewed_by(REMOTE_A).into_iter().max().unwrap();
let other = renewed_by(REMOTE_B);
assert_eq!(other.len(), 1, "the other pair's late response was taken");
assert!(other[0] > selected_last);
assert!(
is_at(trace.at(ConnectionState::Failed), selected_last + 30 * S),
"{:?}",
trace.states
);
}
#[test]
fn test_a_consent_request_open_at_an_ice_restart_is_still_answered() {
let (mut a, mut peer, now) = connected(config(true));
let mut sent = None;
let mut at = now;
while sent.is_none() {
at = a.poll_timeout().unwrap().max(at + Duration::from_micros(1));
let trace = peer.run(&mut a, at, at, |_, _, _| None);
sent = trace.requests.first().map(|r| (r.0, r.1));
}
let (sent_at, id) = sent.unwrap();
let path = a.media_path().unwrap();
a.restart(sent_at + 100 * MS, String::new(), String::new(), true)
.unwrap();
assert_eq!(a.media_path(), Some(path));
let before = a.previous_generation.as_ref().unwrap().last_consent;
let response = peer_response(BINDING_SUCCESS, id, addr(LOCAL), None);
let _ = deliver(&mut a, sent_at + 800 * MS, &response, REMOTE_A);
let previous = a.previous_generation.as_ref().unwrap();
assert_ne!(previous.last_consent, before);
assert_eq!(previous.last_consent, sent_at + 800 * MS);
let _ = deliver(&mut a, sent_at + 900 * MS, &response, REMOTE_A);
let previous = a.previous_generation.as_ref().unwrap();
assert_eq!(previous.last_consent, sent_at + 800 * MS);
}
#[test]
fn test_the_path_kept_across_a_restart_keeps_consent_when_it_is_slow() {
for round_trip in [800 * MS, 6 * S] {
let (mut a, mut peer, now) = connected(config(true));
let path = a.media_path().unwrap();
a.restart(now, String::new(), String::new(), true).unwrap();
let trace = peer.run(&mut a, now, now + 120 * S, |_, _, _| Some(round_trip));
assert_eq!(a.media_path(), Some(path), "{round_trip:?}");
assert!(trace.requests.len() >= 15, "{}", trace.requests.len());
let previous = a.previous_generation.as_ref().unwrap();
assert!(now + 120 * S - previous.last_consent < 7 * S + round_trip);
assert!(previous.pending.len() <= 3, "{}", previous.pending.len());
}
}
#[test]
fn test_the_wait_on_the_path_kept_across_a_restart_grows_with_the_round_trip() {
let (mut a, mut peer, now) = connected(config(true));
let path = a.media_path().unwrap();
a.restart(now, String::new(), String::new(), true).unwrap();
let mut round_trip = 20 * MS;
peer.run(&mut a, now, now + 600 * S, |_, _, _| {
round_trip = (round_trip * 5 / 4).min(12 * S);
Some(round_trip)
});
assert_eq!(round_trip, 12 * S);
assert_eq!(a.media_path(), Some(path));
let previous = a.previous_generation.as_ref().unwrap();
assert!(now + 600 * S - previous.last_consent < 7 * S);
}
#[test]
fn test_a_previous_generation_consent_request_waits_sixteen_times_the_rto() {
for (after, renews) in [(7_999 * MS, true), (8 * S, false)] {
let (mut a, mut peer, now) = connected(config(true));
a.restart(now, String::new(), String::new(), true).unwrap();
let mut sent = None;
let mut at = now;
while sent.is_none() {
at = a.poll_timeout().unwrap().max(at + Duration::from_micros(1));
let trace = peer.run(&mut a, at, at, |_, _, _| None);
sent = trace.requests.first().map(|r| (r.0, r.1));
}
let (sent_at, id) = sent.unwrap();
let before = a.previous_generation.as_ref().unwrap().last_consent;
let response = peer_response(BINDING_SUCCESS, id, addr(LOCAL), None);
let _ = deliver(&mut a, sent_at + after, &response, REMOTE_A);
let previous = a.previous_generation.as_ref().unwrap();
assert_eq!(
previous.last_consent,
if renews { sent_at + after } else { before },
"a response {after:?} after its request"
);
}
}