1use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
44use rtcp::transport_feedbacks::ecn_feedback::EcnCounters;
45use std::time::{Duration, Instant};
46
47pub const PROBE_SPACING: u32 = 10;
49pub const PROBE_INTERVAL: Duration = Duration::from_millis(500);
54pub const CONFIRMATIONS: u32 = 2;
56pub const PROBES_LOST_TO_FAIL: u32 = 4;
59pub const WINDOW: u32 = 32;
61pub const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(60);
63pub const FALLBACKS_TO_DISABLE: u32 = 2;
65pub const PROVISIONAL_MONITOR: Duration = Duration::from_secs(15);
70
71const HISTORY: usize = 2048;
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum EcnState {
77 Initiating,
79 Active,
81 Fallback,
84 Failed {
86 retry_at: Instant,
88 },
89 Disabled,
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum EctPreference {
97 Ect0,
99 Ect1,
101 Random,
103}
104
105impl EctPreference {
106 pub fn from_sdp(value: &str) -> Option<Self> {
109 match value.trim().to_ascii_lowercase().as_str() {
110 "0" => Some(Self::Ect0),
111 "1" => Some(Self::Ect1),
112 "random" => Some(Self::Random),
113 _ => None,
114 }
115 }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
120pub enum EcnMarking {
121 #[default]
124 Rfc6679,
125 L4s,
128}
129
130impl EcnMarking {
131 pub fn codepoint(self, preference: Option<EctPreference>, coin: bool) -> shared::EcnCodepoint {
134 match (self, preference) {
135 (Self::L4s, _) | (Self::Rfc6679, Some(EctPreference::Ect1)) => {
136 shared::EcnCodepoint::Ect1
137 }
138 (Self::Rfc6679, Some(EctPreference::Random)) if coin => shared::EcnCodepoint::Ect1,
139 _ => shared::EcnCodepoint::Ect0,
140 }
141 }
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
146pub enum EcnInitiation {
147 #[default]
150 RtpAndRtcp,
151 LeapOfFaith,
156}
157
158impl EcnInitiation {
159 pub fn one_per_transport<K: PartialEq + Copy>(
165 sections: &[(K, Option<EcnInitiation>)],
166 ) -> Vec<Option<EcnInitiation>> {
167 sections
168 .iter()
169 .map(|(transport, method)| {
170 method.and_then(|_| {
171 sections
172 .iter()
173 .find(|(other, m)| other == transport && m.is_some())
174 .and_then(|(_, m)| *m)
175 })
176 })
177 .collect()
178 }
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185#[non_exhaustive]
186pub enum EcnFailure {
187 ProbeArrivedNotEct,
189 NoProbeArrived,
191 FieldCleared,
193 ProbesCountedNotEct,
195 NoEcnReport,
198 NoReception,
201 EctLost {
204 disabled: bool,
206 },
207}
208
209impl EcnFailure {
210 pub fn is_initiation_failure(&self) -> bool {
212 !matches!(self, EcnFailure::EctLost { .. })
213 }
214}
215
216impl std::fmt::Display for EcnFailure {
217 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218 f.write_str(match self {
219 EcnFailure::ProbeArrivedNotEct => "an ECT probe arrived Not-ECT",
220 EcnFailure::NoProbeArrived => "no ECT probe arrived",
221 EcnFailure::FieldCleared => "the path clears the ECN field",
222 EcnFailure::ProbesCountedNotEct => "ECT probes were counted Not-ECT",
223 EcnFailure::NoEcnReport => {
224 "a receiver reported more than three probes without an ECN report"
225 }
226 EcnFailure::NoReception => "two receiver reports in a row showed no reception",
227 EcnFailure::EctLost { disabled: true } => {
228 "ECT packets were lost again; ECN off for the stream"
229 }
230 EcnFailure::EctLost { disabled: false } => "ECT packets were lost; initiating again",
231 })
232 }
233}
234
235const MAX_KEPT_FAILURES: usize = 16;
237
238#[derive(Debug, Clone, Copy, Default)]
239struct Sent {
240 sequence_number: u16,
241 known: bool,
243 marked: bool,
244 reported: Option<bool>,
246}
247
248#[derive(Debug, Clone, Copy, Default)]
250struct Window {
251 reported: u32,
252 lost: u32,
253 bleached: u32,
254}
255
256#[derive(Debug, Clone)]
259pub struct EcnValidation {
260 state: EcnState,
261 retry_after: Duration,
262 since_probe: u32,
263 last_probe: Option<Instant>,
264 history: Box<[Sent]>,
265 probes_confirmed: u32,
266 probes_lost: u32,
267 window: Window,
268 fallback_from: u32,
270 fallbacks: u32,
271 last_counters: Option<(u32, EcnCounters)>,
274 initiated_at: Option<Instant>,
276 provisional_until: Option<Instant>,
278 receiver_cname: Option<String>,
280 failures: Vec<EcnFailure>,
282 leap_of_faith: bool,
284 reports_without_reception: u32,
286}
287
288impl Default for EcnValidation {
289 fn default() -> Self {
290 Self::new(EcnInitiation::default())
291 }
292}
293
294impl EcnValidation {
295 pub fn new(initiation: EcnInitiation) -> Self {
297 Self {
298 state: match initiation {
299 EcnInitiation::RtpAndRtcp => EcnState::Initiating,
300 EcnInitiation::LeapOfFaith => EcnState::Active,
301 },
302 retry_after: DEFAULT_RETRY_AFTER,
303 since_probe: PROBE_SPACING,
304 last_probe: None,
305 history: vec![Sent::default(); HISTORY].into_boxed_slice(),
306 probes_confirmed: 0,
307 probes_lost: 0,
308 window: Window::default(),
309 fallback_from: 0,
310 fallbacks: 0,
311 last_counters: None,
312 initiated_at: None,
313 provisional_until: None,
314 receiver_cname: None,
315 failures: Vec::new(),
316 leap_of_faith: initiation == EcnInitiation::LeapOfFaith,
317 reports_without_reception: 0,
318 }
319 }
320
321 pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
323 self.retry_after = retry_after;
324 self
325 }
326
327 pub fn state(&self) -> EcnState {
329 self.state
330 }
331
332 pub fn marks_all(&self) -> bool {
336 self.state == EcnState::Active
337 }
338
339 pub fn was_marked(&self, sequence_number: u16) -> bool {
341 let slot = &self.history[usize::from(sequence_number) % HISTORY];
342 slot.known && slot.sequence_number == sequence_number && slot.marked
343 }
344
345 pub fn on_send(&mut self, now: Instant, sequence_number: u16) -> bool {
347 if let EcnState::Failed { retry_at } = self.state
348 && now >= retry_at
349 {
350 self.initiate();
351 }
352 let marked = match self.state {
353 EcnState::Initiating => {
354 let due = self.since_probe + 1 >= PROBE_SPACING
355 || (self.since_probe >= 1
356 && self
357 .last_probe
358 .is_none_or(|at| now.saturating_duration_since(at) >= PROBE_INTERVAL));
359 if due {
360 self.since_probe = 0;
361 self.last_probe = Some(now);
362 self.initiated_at.get_or_insert(now);
363 } else {
364 self.since_probe += 1;
365 }
366 due
367 }
368 EcnState::Active => true,
369 EcnState::Fallback | EcnState::Failed { .. } | EcnState::Disabled => false,
370 };
371 self.history[usize::from(sequence_number) % HISTORY] = Sent {
372 sequence_number,
373 known: true,
374 marked,
375 reported: None,
376 };
377 marked
378 }
379
380 pub fn on_report(&mut self, now: Instant, sequence_number: u16, received: bool, ecn: Ecn) {
383 let slot = &mut self.history[usize::from(sequence_number) % HISTORY];
384 if !slot.known || slot.sequence_number != sequence_number {
385 return;
386 }
387 let undo_loss = match slot.reported {
390 Some(true) => return,
391 Some(false) if !received => return,
392 Some(false) => true,
393 None => false,
394 };
395 slot.reported = Some(received);
396 let marked = slot.marked;
397 let ecn_capable = matches!(ecn, Ecn::Ect0 | Ecn::Ect1 | Ecn::Ce);
398
399 match self.state {
400 EcnState::Initiating if marked => {
401 if undo_loss {
402 self.probes_lost = self.probes_lost.saturating_sub(1);
403 }
404 if !received {
405 self.probes_lost += 1;
406 } else if ecn_capable {
407 self.probes_confirmed += 1;
408 } else {
409 self.fail(now, EcnFailure::ProbeArrivedNotEct);
411 return;
412 }
413 if self.probes_confirmed == 0 && self.probes_lost >= PROBES_LOST_TO_FAIL {
414 self.fail(now, EcnFailure::NoProbeArrived);
415 } else if self.probes_confirmed >= CONFIRMATIONS {
416 self.provisional_success(now);
417 }
418 }
419 EcnState::Active if marked => {
420 self.count(undo_loss, received, !ecn_capable);
421 if self.window.bleached * 4 > WINDOW {
422 self.fail(now, EcnFailure::FieldCleared);
423 } else if self.window.lost * 2 >= WINDOW {
424 log::debug!("ECN: high loss of ECT packets; sending Not-ECT to compare");
425 self.state = EcnState::Fallback;
426 self.fallback_from = self.window.lost;
427 self.window = Window::default();
428 } else if self.window.reported >= WINDOW {
429 self.window = Window::default();
430 }
431 }
432 EcnState::Fallback if !marked => {
433 self.count(undo_loss, received, false);
434 if self.window.reported >= WINDOW {
435 if self.window.lost * 4 < WINDOW && self.window.lost * 2 < self.fallback_from {
436 self.fallbacks += 1;
438 if self.fallbacks >= FALLBACKS_TO_DISABLE {
439 self.record(EcnFailure::EctLost { disabled: true });
440 self.state = EcnState::Disabled;
441 } else {
442 self.record(EcnFailure::EctLost { disabled: false });
443 self.initiate();
444 }
445 } else {
446 self.state = EcnState::Active;
448 self.window = Window::default();
449 }
450 }
451 }
452 _ => {}
453 }
454 }
455
456 pub fn on_counters(&mut self, now: Instant, extended_highest: u32, counters: EcnCounters) {
470 let (previous_highest, previous) = match self.last_counters {
471 Some(last) => last,
472 None => (
473 extended_highest.wrapping_sub(self.known_since(extended_highest)),
474 EcnCounters::default(),
475 ),
476 };
477 let span = extended_highest.wrapping_sub(previous_highest);
479 if span > 0x8000_0000 {
480 return;
481 }
482 self.last_counters = Some((extended_highest, counters));
483 if span == 0 && counters == previous {
484 return;
485 }
486 let ect = u64::from(counters.ect0.wrapping_sub(previous.ect0))
487 + u64::from(counters.ect1.wrapping_sub(previous.ect1))
488 + u64::from(counters.ce.wrapping_sub(previous.ce));
489 let not_ect = u64::from(counters.not_ect.wrapping_sub(previous.not_ect));
490 let duplicates = u64::from(counters.duplicates.wrapping_sub(previous.duplicates));
491 let lost = i64::from(counters.lost.wrapping_sub(previous.lost) as i16).max(0) as u64;
493
494 let (mut marked, mut unmarked) = (0u64, 0u64);
496 let first = previous_highest.wrapping_add(1);
497 for offset in 0..span.min(HISTORY as u32) {
498 let sequence_number = first.wrapping_add(offset) as u16;
499 let slot = &self.history[usize::from(sequence_number) % HISTORY];
500 if slot.known && slot.sequence_number == sequence_number {
501 if slot.marked {
502 marked += 1;
503 } else {
504 unmarked += 1;
505 }
506 }
507 }
508 let bleached = not_ect.saturating_sub(unmarked + duplicates);
509
510 match self.state {
511 EcnState::Initiating => {
512 if bleached > 0 && marked > 0 {
513 self.fail(now, EcnFailure::ProbesCountedNotEct);
514 return;
515 }
516 self.probes_confirmed += ect.min(u64::from(u32::MAX)) as u32;
517 if ect == 0 {
518 self.probes_lost += marked as u32;
519 }
520 if self.probes_confirmed == 0 && self.probes_lost >= PROBES_LOST_TO_FAIL {
521 self.fail(now, EcnFailure::NoProbeArrived);
522 } else if self.probes_confirmed >= CONFIRMATIONS && bleached == 0 {
523 self.provisional_success(now);
524 }
525 }
526 EcnState::Active => {
527 self.window.reported += marked as u32;
528 self.window.lost += lost.min(marked) as u32;
529 self.window.bleached += bleached.min(marked) as u32;
530 if self.window.bleached * 4 > WINDOW {
531 self.fail(now, EcnFailure::FieldCleared);
532 } else if self.window.lost * 2 >= WINDOW {
533 log::debug!("ECN: high loss of ECT packets; sending Not-ECT to compare");
534 self.state = EcnState::Fallback;
535 self.fallback_from = self.window.lost;
536 self.window = Window::default();
537 } else if self.window.reported >= WINDOW {
538 self.window = Window::default();
539 }
540 }
541 EcnState::Fallback => {
542 self.window.reported += unmarked as u32;
543 self.window.lost += lost.min(unmarked) as u32;
544 if self.window.reported >= WINDOW {
545 if self.window.lost * 4 < WINDOW && self.window.lost * 2 < self.fallback_from {
546 self.fallbacks += 1;
547 if self.fallbacks >= FALLBACKS_TO_DISABLE {
548 self.record(EcnFailure::EctLost { disabled: true });
549 self.state = EcnState::Disabled;
550 } else {
551 self.record(EcnFailure::EctLost { disabled: false });
552 self.initiate();
553 }
554 } else {
555 self.state = EcnState::Active;
556 self.window = Window::default();
557 }
558 }
559 }
560 EcnState::Failed { .. } | EcnState::Disabled => {}
561 }
562 }
563
564 fn known_since(&self, extended_highest: u32) -> u32 {
567 let mut span = 0u32;
568 while span < HISTORY as u32 {
569 let sequence_number = extended_highest.wrapping_sub(span) as u16;
570 let slot = &self.history[usize::from(sequence_number) % HISTORY];
571 if !(slot.known && slot.sequence_number == sequence_number) {
572 break;
573 }
574 span += 1;
575 }
576 span
577 }
578
579 fn count(&mut self, undo_loss: bool, received: bool, bleached: bool) {
580 if undo_loss {
581 self.window.lost = self.window.lost.saturating_sub(1);
582 } else {
583 self.window.reported += 1;
584 }
585 if !received {
586 self.window.lost += 1;
587 } else if bleached {
588 self.window.bleached += 1;
589 }
590 }
591
592 fn provisional_success(&mut self, now: Instant) {
596 self.state = EcnState::Active;
597 self.window = Window::default();
598 let started = self.initiated_at.unwrap_or(now);
599 self.provisional_until = Some(started + PROVISIONAL_MONITOR);
600 }
601
602 pub fn on_remote_cname(&mut self, now: Instant, cname: &str) {
607 match &self.receiver_cname {
608 None => self.receiver_cname = Some(cname.to_owned()),
609 Some(known) if known == cname => {}
610 Some(_) => {
611 let provisional = self.state == EcnState::Active
612 && self.provisional_until.is_some_and(|until| now < until);
613 if provisional {
614 log::info!(
615 "ECN: another RTCP CNAME during a provisional success, probing again \
616 (RFC 6679 section 7.2.1)"
617 );
618 self.initiate();
619 }
620 self.receiver_cname = Some(cname.to_owned());
622 }
623 }
624 }
625
626 pub fn on_reception_report_without_ecn(&mut self, now: Instant, extended_highest: u32) {
633 if self.state != EcnState::Initiating {
634 return;
635 }
636 let highest = extended_highest as u16;
637 let due = self
638 .history
639 .iter()
640 .filter(|sent| {
641 sent.known && sent.marked && {
642 let behind = highest.wrapping_sub(sent.sequence_number);
644 usize::from(behind) < HISTORY
645 }
646 })
647 .count();
648 if due > 3 {
649 self.fail(now, EcnFailure::NoEcnReport);
650 }
651 }
652
653 pub fn on_report_without_reception(&mut self, now: Instant) {
662 if !self.leap_of_faith
663 || self.state != EcnState::Active
664 || !self.history.iter().any(|sent| sent.known && sent.marked)
665 {
666 return;
667 }
668 self.reports_without_reception += 1;
669 if self.reports_without_reception >= 2 {
670 self.leap_of_faith = false;
671 self.fail(now, EcnFailure::NoReception);
672 }
673 }
674
675 pub fn on_reception_reported(&mut self) {
677 self.reports_without_reception = 0;
678 self.leap_of_faith = false;
679 }
680
681 pub fn with_receiver_cname(mut self, cname: &str) -> Self {
684 self.receiver_cname = Some(cname.to_owned());
685 self
686 }
687
688 pub fn is_provisional(&self, now: Instant) -> bool {
690 self.state == EcnState::Active && self.provisional_until.is_some_and(|until| now < until)
691 }
692
693 fn initiate(&mut self) {
694 self.provisional_until = None;
695 self.initiated_at = None;
696 self.state = EcnState::Initiating;
697 self.since_probe = PROBE_SPACING;
698 self.last_probe = None;
699 self.probes_confirmed = 0;
700 self.probes_lost = 0;
701 self.window = Window::default();
702 }
703
704 fn record(&mut self, failure: EcnFailure) {
707 if failure.is_initiation_failure() {
708 log::warn!("ECN: {failure}; packets go out Not-ECT");
709 } else {
710 log::warn!("ECN: {failure}");
711 }
712 if self.failures.len() == MAX_KEPT_FAILURES {
713 self.failures.remove(0);
714 }
715 self.failures.push(failure);
716 }
717
718 pub fn take_failures(&mut self) -> Vec<EcnFailure> {
720 std::mem::take(&mut self.failures)
721 }
722
723 fn fail(&mut self, now: Instant, failure: EcnFailure) {
724 self.record(failure);
725 self.state = EcnState::Failed {
726 retry_at: now + self.retry_after,
727 };
728 self.window = Window::default();
729 }
730}
731
732#[cfg(test)]
733mod tests {
734 use super::*;
735
736 fn counters_for(
739 sent: &[u16],
740 marked: &[u16],
741 ect_arrives: bool,
742 lost: u16,
743 base: EcnCounters,
744 ) -> EcnCounters {
745 let marked_count = marked.len() as u32;
746 let unmarked = (sent.len() - marked.len()) as u16;
747 let mut c = base;
748 if ect_arrives {
749 c.ect1 += marked_count - u32::from(lost.min(marked_count as u16));
750 c.not_ect += unmarked;
751 } else {
752 c.not_ect += unmarked + marked_count as u16 - lost;
753 }
754 c.lost += lost;
755 c
756 }
757
758 #[test]
764 fn bundled_sections_use_one_initiation_method() {
765 use EcnInitiation::{LeapOfFaith, RtpAndRtcp};
766 let methods = EcnInitiation::one_per_transport(&[
767 (0, Some(RtpAndRtcp)),
768 (0, Some(LeapOfFaith)),
769 (0, None),
770 (1, Some(LeapOfFaith)),
771 ]);
772 assert_eq!(
773 methods,
774 vec![Some(RtpAndRtcp), Some(RtpAndRtcp), None, Some(LeapOfFaith)]
775 );
776 }
777
778 #[test]
779 fn the_ect_parameter_names_ect0_ect1_or_random_and_nothing_else() {
780 assert_eq!(EctPreference::from_sdp("0"), Some(EctPreference::Ect0));
781 assert_eq!(EctPreference::from_sdp(" 1"), Some(EctPreference::Ect1));
782 assert_eq!(
783 EctPreference::from_sdp("Random"),
784 Some(EctPreference::Random)
785 );
786 assert_eq!(EctPreference::from_sdp("2"), None);
787 assert_eq!(
788 EcnMarking::Rfc6679.codepoint(None, true),
789 shared::EcnCodepoint::Ect0,
790 "RFC 6679 section 7.3.1: ECT(0) unless asked"
791 );
792 assert_eq!(
793 EcnMarking::L4s.codepoint(Some(EctPreference::Ect0), false),
794 shared::EcnCodepoint::Ect1
795 );
796 }
797
798 #[test]
799 fn counted_ect_probes_complete_the_initiation() {
800 let mut v = EcnValidation::default();
801 let mut at = Instant::now();
802 let sent: Vec<u16> = (0..40).collect();
803 let marked = send(&mut v, &mut at, 0, 40);
804 assert!(
805 marked.len() >= 2 && marked.len() < 40,
806 "probes only: {marked:?}"
807 );
808 let c = counters_for(&sent, &marked, true, 0, EcnCounters::default());
809 v.on_counters(at, 39, c);
810 assert_eq!(v.state(), EcnState::Active);
811 assert_eq!(
812 send(&mut v, &mut at, 40, 10).len(),
813 10,
814 "all marked once active"
815 );
816 }
817
818 #[test]
821 fn probes_counted_not_ect_fail_the_initiation() {
822 let mut v = EcnValidation::default().with_retry_after(Duration::from_secs(10));
823 let mut at = Instant::now();
824 let sent: Vec<u16> = (0..40).collect();
825 let marked = send(&mut v, &mut at, 0, 40);
826 let c = counters_for(&sent, &marked, false, 0, EcnCounters::default());
827 v.on_counters(at, 39, c);
828 assert!(
829 matches!(v.state(), EcnState::Failed { .. }),
830 "{:?}",
831 v.state()
832 );
833 assert!(
834 send(&mut v, &mut at, 40, 20).is_empty(),
835 "nothing marked after the failure"
836 );
837 at += Duration::from_secs(11);
838 assert!(
839 !send(&mut v, &mut at, 60, 20).is_empty(),
840 "probing again after the retry time"
841 );
842 }
843
844 #[test]
847 fn bleaching_counted_in_ongoing_use_stops_the_marking() {
848 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
849 let mut at = Instant::now();
850 let sent: Vec<u16> = (0..40).collect();
851 let marked = send(&mut v, &mut at, 0, 40);
852 assert_eq!(marked.len(), 40);
853 let c = counters_for(&sent, &marked, false, 0, EcnCounters::default());
854 v.on_counters(at, 39, c);
855 assert!(
856 matches!(v.state(), EcnState::Failed { .. }),
857 "{:?}",
858 v.state()
859 );
860 }
861
862 #[test]
864 fn counted_loss_of_ect_packets_falls_back_to_not_ect() {
865 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
866 let mut at = Instant::now();
867 let sent: Vec<u16> = (0..40).collect();
868 let marked = send(&mut v, &mut at, 0, 40);
869 let c = counters_for(&sent, &marked, true, 20, EcnCounters::default());
870 v.on_counters(at, 39, c);
871 assert_eq!(v.state(), EcnState::Fallback);
872 assert!(send(&mut v, &mut at, 40, 10).is_empty());
873 }
874
875 fn send(v: &mut EcnValidation, at: &mut Instant, first: u16, count: u16) -> Vec<u16> {
877 let mut marked = vec![];
878 for n in 0..count {
879 let seq = first.wrapping_add(n);
880 if v.on_send(*at, seq) {
881 marked.push(seq);
882 }
883 *at += Duration::from_millis(20);
884 }
885 marked
886 }
887
888 fn report(
890 v: &mut EcnValidation,
891 at: Instant,
892 first: u16,
893 count: u16,
894 path: impl Fn(u16, bool) -> Option<Ecn>,
895 ) {
896 for n in 0..count {
897 let seq = first.wrapping_add(n);
898 let marked = v.was_marked(seq);
899 match path(seq, marked) {
900 Some(ecn) => v.on_report(at, seq, true, ecn),
901 None => v.on_report(at, seq, false, Ecn::NotEct),
902 }
903 }
904 }
905
906 fn carries_ecn(_: u16, marked: bool) -> Option<Ecn> {
907 Some(if marked { Ecn::Ect1 } else { Ecn::NotEct })
908 }
909
910 #[test]
914 fn a_second_cname_during_a_provisional_success_sends_the_stream_back_to_probing() {
915 let mut v = EcnValidation::default();
916 let mut at = Instant::now();
917 v.on_remote_cname(at, "peer");
918 send(&mut v, &mut at, 0, 40);
919 report(&mut v, at, 0, 40, carries_ecn);
920 assert!(v.is_provisional(at));
921 v.on_remote_cname(at, "peer");
922 assert_eq!(v.state(), EcnState::Active, "the same receiver");
923 v.on_remote_cname(at, "another participant");
924 assert_eq!(v.state(), EcnState::Initiating);
925 let probes = send(&mut v, &mut at, 40, 40).len();
926 assert!((1..40).contains(&probes), "a small fraction only: {probes}");
927
928 report(&mut v, at, 40, 40, carries_ecn);
930 assert_eq!(v.state(), EcnState::Active);
931 at += PROVISIONAL_MONITOR;
932 assert!(!v.is_provisional(at));
933 v.on_remote_cname(at, "a third");
934 assert_eq!(v.state(), EcnState::Active);
935 }
936
937 #[test]
938 fn initiation_marks_a_small_fraction_never_all() {
939 let mut v = EcnValidation::default();
940 let mut at = Instant::now();
941 let marked = send(&mut v, &mut at, 0, 100);
942 assert!(marked.len() >= 4, "probes: {marked:?}");
943 assert!(marked.len() <= 100 / 4, "a small fraction: {marked:?}");
944 assert!(
945 marked.windows(2).all(|w| w[1] - w[0] >= 2),
946 "never two in a row: {marked:?}"
947 );
948 assert_eq!(v.state(), EcnState::Initiating);
949 }
950
951 #[test]
952 fn a_slow_stream_still_probes_twice_a_second() {
953 let mut v = EcnValidation::default();
954 let mut at = Instant::now();
955 let mut marked = 0;
956 for seq in 0..10u16 {
958 marked += u32::from(v.on_send(at, seq));
959 at += Duration::from_millis(200);
960 }
961 assert!(marked >= 4, "{marked} probes in two seconds");
962 assert!(marked < 10);
963 }
964
965 #[test]
966 fn confirmed_probes_make_every_packet_ect() {
967 let mut v = EcnValidation::default();
968 let mut at = Instant::now();
969 send(&mut v, &mut at, 0, 40);
970 report(&mut v, at, 0, 40, carries_ecn);
971 assert_eq!(v.state(), EcnState::Active);
972 assert_eq!(send(&mut v, &mut at, 40, 20).len(), 20);
973 assert!(v.marks_all());
974 }
975
976 #[test]
977 fn a_ce_marked_probe_confirms_ecn_too() {
978 let mut v = EcnValidation::default();
979 let mut at = Instant::now();
980 send(&mut v, &mut at, 0, 40);
981 report(&mut v, at, 0, 40, |_, m| {
982 Some(if m { Ecn::Ce } else { Ecn::NotEct })
983 });
984 assert_eq!(v.state(), EcnState::Active);
985 }
986
987 #[test]
988 fn a_bleached_probe_fails_the_initiation_and_a_retry_follows() {
989 let mut v = EcnValidation::default().with_retry_after(Duration::from_secs(10));
990 let mut at = Instant::now();
991 send(&mut v, &mut at, 0, 40);
992 report(&mut v, at, 0, 40, |_, _| Some(Ecn::NotEct));
993 assert!(
994 matches!(v.state(), EcnState::Failed { .. }),
995 "{:?}",
996 v.state()
997 );
998 assert!(send(&mut v, &mut at, 40, 100).is_empty(), "nothing marked");
999 at += Duration::from_secs(10);
1000 assert!(
1001 !send(&mut v, &mut at, 140, 20).is_empty(),
1002 "initiating again"
1003 );
1004 assert_eq!(v.state(), EcnState::Initiating);
1005 }
1006
1007 #[test]
1008 fn a_path_that_drops_ect_packets_fails_the_initiation() {
1009 let mut v = EcnValidation::default();
1010 let mut at = Instant::now();
1011 let probes = send(&mut v, &mut at, 0, 60);
1012 assert!(probes.len() >= 4);
1013 report(&mut v, at, 0, 60, |_, m| (!m).then_some(Ecn::NotEct));
1014 assert!(
1015 matches!(v.state(), EcnState::Failed { .. }),
1016 "{:?}",
1017 v.state()
1018 );
1019 }
1020
1021 #[test]
1022 fn three_lost_probes_are_not_yet_a_failure() {
1023 let mut v = EcnValidation::default();
1024 let mut at = Instant::now();
1025 let probes = send(&mut v, &mut at, 0, 60);
1026 let lost: Vec<u16> = probes[..3].to_vec();
1027 report(&mut v, at, 0, 60, |s, m| {
1028 if lost.contains(&s) {
1029 None
1030 } else {
1031 carries_ecn(s, m)
1032 }
1033 });
1034 assert_eq!(v.state(), EcnState::Active, "the fourth probe arrived ECT");
1035 }
1036
1037 #[test]
1038 fn a_late_packet_reported_lost_then_received_is_not_a_loss() {
1039 let mut v = EcnValidation::default();
1040 let mut at = Instant::now();
1041 let probes = send(&mut v, &mut at, 0, 60);
1042 for &p in &probes {
1043 v.on_report(at, p, false, Ecn::NotEct);
1044 v.on_report(at, p, true, Ecn::Ect1);
1045 v.on_report(at, p, true, Ecn::Ect1);
1047 v.on_report(at, p, false, Ecn::NotEct);
1048 }
1049 assert_eq!(v.state(), EcnState::Active);
1050 }
1051
1052 #[test]
1053 fn bleaching_during_use_stops_the_marking() {
1054 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1055 let mut at = Instant::now();
1056 assert_eq!(
1057 send(&mut v, &mut at, 0, 32).len(),
1058 32,
1059 "leap of faith marks all"
1060 );
1061 report(&mut v, at, 0, 32, |s, _| {
1063 Some(if s % 16 == 0 { Ecn::NotEct } else { Ecn::Ect1 })
1064 });
1065 assert_eq!(v.state(), EcnState::Active);
1066 send(&mut v, &mut at, 32, 32);
1067 report(&mut v, at, 32, 32, |_, _| Some(Ecn::NotEct));
1068 assert!(
1069 matches!(v.state(), EcnState::Failed { .. }),
1070 "{:?}",
1071 v.state()
1072 );
1073 assert!(send(&mut v, &mut at, 64, 50).is_empty());
1074 }
1075
1076 #[test]
1081 fn leap_of_faith_waits_for_a_second_report_without_reception() {
1082 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1083 let mut at = Instant::now();
1084 v.on_report_without_reception(at);
1086 v.on_report_without_reception(at);
1087 assert_eq!(v.state(), EcnState::Active);
1088 assert_eq!(send(&mut v, &mut at, 0, 10).len(), 10);
1089 v.on_report_without_reception(at);
1090 assert_eq!(v.state(), EcnState::Active, "one report is not enough");
1091 v.on_report_without_reception(at);
1092 assert!(
1093 matches!(v.state(), EcnState::Failed { .. }),
1094 "{:?}",
1095 v.state()
1096 );
1097 assert_eq!(v.take_failures(), vec![EcnFailure::NoReception]);
1098 assert!(
1099 send(&mut v, &mut at, 10, 10).is_empty(),
1100 "Not-ECT after the failure"
1101 );
1102
1103 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1104 send(&mut v, &mut at, 0, 10);
1105 v.on_report_without_reception(at);
1106 v.on_reception_reported();
1107 v.on_report_without_reception(at);
1108 v.on_report_without_reception(at);
1109 assert_eq!(v.state(), EcnState::Active, "reception was reported");
1110
1111 let mut v = EcnValidation::new(EcnInitiation::RtpAndRtcp);
1113 send(&mut v, &mut at, 0, 40);
1114 v.on_report_without_reception(at);
1115 v.on_report_without_reception(at);
1116 assert!(v.take_failures().is_empty());
1117 }
1118
1119 #[test]
1120 fn loss_that_goes_with_the_marking_initiates_again_then_disables() {
1121 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1122 let mut at = Instant::now();
1123 let mut seq = 0u16;
1124 for round in 0..FALLBACKS_TO_DISABLE {
1125 if round > 0 {
1127 let n = 40;
1129 send(&mut v, &mut at, seq, n);
1130 report(&mut v, at, seq, n, carries_ecn);
1131 seq += n;
1132 }
1133 assert_eq!(v.state(), EcnState::Active, "round {round}");
1134 send(&mut v, &mut at, seq, 32);
1135 report(&mut v, at, seq, 32, |_, m| (!m).then_some(Ecn::NotEct));
1136 seq += 32;
1137 assert_eq!(v.state(), EcnState::Fallback, "round {round}");
1138 assert!(
1139 send(&mut v, &mut at, seq, 32).is_empty(),
1140 "Not-ECT while comparing"
1141 );
1142 report(&mut v, at, seq, 32, |_, m| (!m).then_some(Ecn::NotEct));
1143 seq += 32;
1144 }
1145 assert_eq!(v.state(), EcnState::Disabled);
1146 at += DEFAULT_RETRY_AFTER * 2;
1147 assert!(
1148 send(&mut v, &mut at, seq, 40).is_empty(),
1149 "disabled for good"
1150 );
1151 let mut expected =
1154 vec![EcnFailure::EctLost { disabled: false }; FALLBACKS_TO_DISABLE as usize - 1];
1155 expected.push(EcnFailure::EctLost { disabled: true });
1156 assert_eq!(v.take_failures(), expected);
1157 assert!(v.take_failures().is_empty(), "taken once");
1158 }
1159
1160 #[test]
1161 fn loss_that_stays_without_the_marking_resumes_it() {
1162 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1163 let mut at = Instant::now();
1164 send(&mut v, &mut at, 0, 32);
1165 report(&mut v, at, 0, 32, |s, _| (s % 2 == 0).then_some(Ecn::Ect1));
1166 assert_eq!(v.state(), EcnState::Fallback);
1167 send(&mut v, &mut at, 32, 32);
1168 report(&mut v, at, 32, 32, |s, _| {
1169 (s % 2 == 0).then_some(Ecn::NotEct)
1170 });
1171 assert_eq!(v.state(), EcnState::Active, "congestion, not ECN");
1172 }
1173
1174 #[test]
1179 fn arbitrary_send_and_report_sequences_keep_the_invariants() {
1180 let mut state = 0x0EC0_0001u32;
1181 let mut next = move || {
1182 state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1183 state >> 8
1184 };
1185 for _ in 0..400 {
1186 let mut v = if next() % 2 == 0 {
1187 EcnValidation::default()
1188 } else {
1189 EcnValidation::new(EcnInitiation::LeapOfFaith)
1190 }
1191 .with_retry_after(Duration::from_millis(u64::from(next() % 3000)));
1192 let mut at = Instant::now();
1193 let mut seq = next() as u16;
1194 let mut sent: Vec<u16> = vec![];
1195 let mut run_marked = 0u32;
1196 let mut initiating = (0u32, 0u32);
1197 for _ in 0..600 {
1198 at += Duration::from_millis(u64::from(next() % 60));
1199 match next() % 10 {
1200 0..=5 => {
1201 seq = match next() % 20 {
1202 0 => seq.wrapping_add(next() as u16),
1203 1 => seq,
1204 _ => seq.wrapping_add(1),
1205 };
1206 let was = v.state();
1207 let marked = v.on_send(at, seq);
1208 sent.push(seq);
1209 if was == EcnState::Disabled {
1210 assert!(!marked, "a disabled stream marks nothing");
1211 }
1212 if v.state() == EcnState::Initiating && was == EcnState::Initiating {
1213 initiating.0 += 1;
1214 initiating.1 += u32::from(marked);
1215 run_marked = if marked { run_marked + 1 } else { 0 };
1216 assert!(run_marked <= 1, "two probes in a row");
1217 } else {
1218 run_marked = 0;
1219 }
1220 }
1221 _ => {
1222 let target = if sent.is_empty() || next() % 8 == 0 {
1223 next() as u16
1224 } else {
1225 sent[(next() as usize) % sent.len()]
1226 };
1227 let ecn = match next() % 4 {
1228 0 => Ecn::NotEct,
1229 1 => Ecn::Ect1,
1230 2 => Ecn::Ect0,
1231 _ => Ecn::Ce,
1232 };
1233 v.on_report(at, target, next() % 5 != 0, ecn);
1234 }
1235 }
1236 }
1237 if initiating.0 >= 40 {
1238 assert!(
1239 initiating.1 * 4 <= initiating.0 + 4,
1240 "a small fraction while initiating: {initiating:?}"
1241 );
1242 }
1243 }
1244 }
1245}