1use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
44use rtcp::transport_feedbacks::ecn_feedback::EcnCounters;
45use std::collections::BTreeMap;
46use std::time::{Duration, Instant};
47
48pub const PROBE_SPACING: u32 = 10;
50pub const PROBE_INTERVAL: Duration = Duration::from_millis(500);
55pub const CONFIRMATIONS: u32 = 2;
57pub const PROBES_LOST_TO_FAIL: u32 = 4;
60pub const WINDOW: u32 = 32;
62pub const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(60);
64pub const FALLBACKS_TO_DISABLE: u32 = 2;
66pub const PROVISIONAL_MONITOR: Duration = Duration::from_secs(15);
71pub const REPORTING_INTERVAL: Duration = Duration::from_secs(5);
75const MAX_PARTICIPANTS: usize = 16;
78
79const HISTORY: usize = 2048;
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum EcnState {
85 Initiating,
87 Active,
89 Fallback,
92 Failed {
94 retry_at: Instant,
96 },
97 Disabled,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum EctPreference {
105 Ect0,
107 Ect1,
109 Random,
111}
112
113impl EctPreference {
114 pub fn from_sdp(value: &str) -> Option<Self> {
117 match value.trim().to_ascii_lowercase().as_str() {
118 "0" => Some(Self::Ect0),
119 "1" => Some(Self::Ect1),
120 "random" => Some(Self::Random),
121 _ => None,
122 }
123 }
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
128pub enum EcnMarking {
129 #[default]
132 Rfc6679,
133 L4s,
136}
137
138impl EcnMarking {
139 pub fn codepoint(self, preference: Option<EctPreference>, coin: bool) -> shared::EcnCodepoint {
142 match (self, preference) {
143 (Self::L4s, _) | (Self::Rfc6679, Some(EctPreference::Ect1)) => {
144 shared::EcnCodepoint::Ect1
145 }
146 (Self::Rfc6679, Some(EctPreference::Random)) if coin => shared::EcnCodepoint::Ect1,
147 _ => shared::EcnCodepoint::Ect0,
148 }
149 }
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
154pub enum EcnInitiation {
155 #[default]
158 RtpAndRtcp,
159 LeapOfFaith,
164}
165
166impl EcnInitiation {
167 pub fn one_per_transport<K: PartialEq + Copy>(
173 sections: &[(K, Option<EcnInitiation>)],
174 ) -> Vec<Option<EcnInitiation>> {
175 sections
176 .iter()
177 .map(|(transport, method)| {
178 method.and_then(|_| {
179 sections
180 .iter()
181 .find(|(other, m)| other == transport && m.is_some())
182 .and_then(|(_, m)| *m)
183 })
184 })
185 .collect()
186 }
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193#[non_exhaustive]
194pub enum EcnFailure {
195 ProbeArrivedNotEct,
197 NoProbeArrived,
199 FieldCleared,
201 ProbesCountedNotEct,
203 NoEcnReport,
206 NoReception,
209 EctLost {
212 disabled: bool,
214 },
215}
216
217impl EcnFailure {
218 pub fn is_initiation_failure(&self) -> bool {
220 !matches!(self, EcnFailure::EctLost { .. })
221 }
222}
223
224impl std::fmt::Display for EcnFailure {
225 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226 f.write_str(match self {
227 EcnFailure::ProbeArrivedNotEct => "an ECT probe arrived Not-ECT",
228 EcnFailure::NoProbeArrived => "no ECT probe arrived",
229 EcnFailure::FieldCleared => "the path clears the ECN field",
230 EcnFailure::ProbesCountedNotEct => "ECT probes were counted Not-ECT",
231 EcnFailure::NoEcnReport => {
232 "a receiver reported more than three probes without an ECN report"
233 }
234 EcnFailure::NoReception => "two receiver reports in a row showed no reception",
235 EcnFailure::EctLost { disabled: true } => {
236 "ECT packets were lost again; ECN off for the stream"
237 }
238 EcnFailure::EctLost { disabled: false } => "ECT packets were lost; initiating again",
239 })
240 }
241}
242
243const MAX_KEPT_FAILURES: usize = 16;
245
246#[derive(Debug, Clone, Copy, Default)]
247struct Sent {
248 sequence_number: u16,
249 known: bool,
251 marked: bool,
252 reported: Option<bool>,
254}
255
256#[derive(Debug, Clone, Copy, Default)]
258struct Window {
259 reported: u32,
260 lost: u32,
261 bleached: u32,
262}
263
264#[derive(Debug, Clone, Default)]
272struct Group {
273 members: BTreeMap<String, bool>,
275 changed_at: Option<Instant>,
277}
278
279#[derive(Debug, Clone)]
282pub struct EcnValidation {
283 state: EcnState,
284 retry_after: Duration,
285 since_probe: u32,
286 last_probe: Option<Instant>,
287 history: Box<[Sent]>,
288 probes_confirmed: u32,
289 probes_lost: u32,
290 window: Window,
291 fallback_from: u32,
293 fallbacks: u32,
294 last_counters: Vec<(Option<String>, u32, EcnCounters)>,
298 initiated_at: Option<Instant>,
300 provisional_until: Option<Instant>,
302 receiver_cname: Option<String>,
304 group: Option<Group>,
307 failures: Vec<EcnFailure>,
309 leap_of_faith: bool,
311 reports_without_reception: u32,
313}
314
315impl Default for EcnValidation {
316 fn default() -> Self {
317 Self::new(EcnInitiation::default())
318 }
319}
320
321impl EcnValidation {
322 pub fn new(initiation: EcnInitiation) -> Self {
324 Self {
325 state: match initiation {
326 EcnInitiation::RtpAndRtcp => EcnState::Initiating,
327 EcnInitiation::LeapOfFaith => EcnState::Active,
328 },
329 retry_after: DEFAULT_RETRY_AFTER,
330 since_probe: PROBE_SPACING,
331 last_probe: None,
332 history: vec![Sent::default(); HISTORY].into_boxed_slice(),
333 probes_confirmed: 0,
334 probes_lost: 0,
335 window: Window::default(),
336 fallback_from: 0,
337 fallbacks: 0,
338 last_counters: Vec::new(),
339 initiated_at: None,
340 provisional_until: None,
341 receiver_cname: None,
342 group: None,
343 failures: Vec::new(),
344 leap_of_faith: initiation == EcnInitiation::LeapOfFaith,
345 reports_without_reception: 0,
346 }
347 }
348
349 pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
351 self.retry_after = retry_after;
352 self
353 }
354
355 pub fn state(&self) -> EcnState {
357 self.state
358 }
359
360 pub fn marks_all(&self) -> bool {
364 self.state == EcnState::Active
365 }
366
367 pub fn was_marked(&self, sequence_number: u16) -> bool {
369 let slot = &self.history[usize::from(sequence_number) % HISTORY];
370 slot.known && slot.sequence_number == sequence_number && slot.marked
371 }
372
373 pub fn on_send(&mut self, now: Instant, sequence_number: u16) -> bool {
375 if let EcnState::Failed { retry_at } = self.state
376 && now >= retry_at
377 {
378 self.initiate();
379 }
380 let marked = match self.state {
381 EcnState::Initiating => {
382 let due = self.since_probe + 1 >= PROBE_SPACING
383 || (self.since_probe >= 1
384 && self
385 .last_probe
386 .is_none_or(|at| now.saturating_duration_since(at) >= PROBE_INTERVAL));
387 if due {
388 self.since_probe = 0;
389 self.last_probe = Some(now);
390 self.initiated_at.get_or_insert(now);
391 } else {
392 self.since_probe += 1;
393 }
394 if self.group_success(now) { true } else { due }
395 }
396 EcnState::Active => true,
397 EcnState::Fallback | EcnState::Failed { .. } | EcnState::Disabled => false,
398 };
399 self.history[usize::from(sequence_number) % HISTORY] = Sent {
400 sequence_number,
401 known: true,
402 marked,
403 reported: None,
404 };
405 marked
406 }
407
408 pub fn on_report(&mut self, now: Instant, sequence_number: u16, received: bool, ecn: Ecn) {
412 self.on_report_from(now, None, sequence_number, received, ecn);
413 }
414
415 pub fn on_report_from(
419 &mut self,
420 now: Instant,
421 reporter: Option<&str>,
422 sequence_number: u16,
423 received: bool,
424 ecn: Ecn,
425 ) {
426 let slot = &mut self.history[usize::from(sequence_number) % HISTORY];
427 if !slot.known || slot.sequence_number != sequence_number {
428 return;
429 }
430 let ecn_capable = matches!(ecn, Ecn::Ect0 | Ecn::Ect1 | Ecn::Ce);
431 if self.state == EcnState::Initiating && slot.marked && received && ecn_capable {
432 self.confirm(now, reporter);
433 }
434 let slot = &mut self.history[usize::from(sequence_number) % HISTORY];
435 let undo_loss = match slot.reported {
438 Some(true) => return,
439 Some(false) if !received => return,
440 Some(false) => true,
441 None => false,
442 };
443 slot.reported = Some(received);
444 let marked = slot.marked;
445
446 match self.state {
447 EcnState::Initiating if marked => {
448 if undo_loss {
449 self.probes_lost = self.probes_lost.saturating_sub(1);
450 }
451 if !received {
452 self.probes_lost += 1;
453 } else if ecn_capable {
454 self.probes_confirmed += 1;
455 } else {
456 self.fail(now, EcnFailure::ProbeArrivedNotEct);
458 return;
459 }
460 if self.probes_confirmed == 0 && self.probes_lost >= PROBES_LOST_TO_FAIL {
461 self.fail(now, EcnFailure::NoProbeArrived);
462 } else if self.group.is_none() && self.probes_confirmed >= CONFIRMATIONS {
463 self.provisional_success(now);
464 } else {
465 self.group_success(now);
466 }
467 }
468 EcnState::Active if marked => {
469 self.count(undo_loss, received, !ecn_capable);
470 if self.window.bleached * 4 > WINDOW {
471 self.fail(now, EcnFailure::FieldCleared);
472 } else if self.window.lost * 2 >= WINDOW {
473 log::debug!("ECN: high loss of ECT packets; sending Not-ECT to compare");
474 self.state = EcnState::Fallback;
475 self.fallback_from = self.window.lost;
476 self.window = Window::default();
477 } else if self.window.reported >= WINDOW {
478 self.window = Window::default();
479 }
480 }
481 EcnState::Fallback if !marked => {
482 self.count(undo_loss, received, false);
483 if self.window.reported >= WINDOW {
484 if self.window.lost * 4 < WINDOW && self.window.lost * 2 < self.fallback_from {
485 self.fallbacks += 1;
487 if self.fallbacks >= FALLBACKS_TO_DISABLE {
488 self.record(EcnFailure::EctLost { disabled: true });
489 self.state = EcnState::Disabled;
490 } else {
491 self.record(EcnFailure::EctLost { disabled: false });
492 self.initiate();
493 }
494 } else {
495 self.state = EcnState::Active;
497 self.window = Window::default();
498 }
499 }
500 }
501 _ => {}
502 }
503 }
504
505 pub fn on_counters(&mut self, now: Instant, extended_highest: u32, counters: EcnCounters) {
519 self.on_counters_from(now, None, extended_highest, counters);
520 }
521
522 pub fn on_counters_from(
526 &mut self,
527 now: Instant,
528 reporter: Option<&str>,
529 extended_highest: u32,
530 counters: EcnCounters,
531 ) {
532 let known = self
533 .last_counters
534 .iter()
535 .position(|(from, _, _)| from.as_deref() == reporter);
536 let (previous_highest, previous) = match known {
537 Some(index) => (self.last_counters[index].1, self.last_counters[index].2),
538 None => (
539 extended_highest.wrapping_sub(self.known_since(extended_highest)),
540 EcnCounters::default(),
541 ),
542 };
543 let span = extended_highest.wrapping_sub(previous_highest);
545 if span > 0x8000_0000 {
546 return;
547 }
548 match known {
549 Some(index) => {
550 self.last_counters[index].1 = extended_highest;
551 self.last_counters[index].2 = counters;
552 }
553 None => {
554 if self.last_counters.len() >= MAX_PARTICIPANTS {
555 self.last_counters.remove(0);
556 }
557 self.last_counters
558 .push((reporter.map(str::to_owned), extended_highest, counters));
559 }
560 }
561 if span == 0 && counters == previous {
562 return;
563 }
564 let ect = u64::from(counters.ect0.wrapping_sub(previous.ect0))
565 + u64::from(counters.ect1.wrapping_sub(previous.ect1))
566 + u64::from(counters.ce.wrapping_sub(previous.ce));
567 let not_ect = u64::from(counters.not_ect.wrapping_sub(previous.not_ect));
568 let duplicates = u64::from(counters.duplicates.wrapping_sub(previous.duplicates));
569 let lost = i64::from(counters.lost.wrapping_sub(previous.lost) as i16).max(0) as u64;
571
572 let (mut marked, mut unmarked) = (0u64, 0u64);
574 let first = previous_highest.wrapping_add(1);
575 for offset in 0..span.min(HISTORY as u32) {
576 let sequence_number = first.wrapping_add(offset) as u16;
577 let slot = &self.history[usize::from(sequence_number) % HISTORY];
578 if slot.known && slot.sequence_number == sequence_number {
579 if slot.marked {
580 marked += 1;
581 } else {
582 unmarked += 1;
583 }
584 }
585 }
586 let bleached = not_ect.saturating_sub(unmarked + duplicates);
587
588 match self.state {
589 EcnState::Initiating => {
590 if bleached > 0 && marked > 0 {
591 self.fail(now, EcnFailure::ProbesCountedNotEct);
592 return;
593 }
594 self.probes_confirmed += ect.min(u64::from(u32::MAX)) as u32;
595 if ect == 0 {
596 self.probes_lost += marked as u32;
597 } else if bleached == 0 {
598 self.confirm(now, reporter);
599 }
600 if self.probes_confirmed == 0 && self.probes_lost >= PROBES_LOST_TO_FAIL {
601 self.fail(now, EcnFailure::NoProbeArrived);
602 } else if self.group.is_none()
603 && self.probes_confirmed >= CONFIRMATIONS
604 && bleached == 0
605 {
606 self.provisional_success(now);
607 } else {
608 self.group_success(now);
609 }
610 }
611 EcnState::Active => {
612 self.window.reported += marked as u32;
613 self.window.lost += lost.min(marked) as u32;
614 self.window.bleached += bleached.min(marked) as u32;
615 if self.window.bleached * 4 > WINDOW {
616 self.fail(now, EcnFailure::FieldCleared);
617 } else if self.window.lost * 2 >= WINDOW {
618 log::debug!("ECN: high loss of ECT packets; sending Not-ECT to compare");
619 self.state = EcnState::Fallback;
620 self.fallback_from = self.window.lost;
621 self.window = Window::default();
622 } else if self.window.reported >= WINDOW {
623 self.window = Window::default();
624 }
625 }
626 EcnState::Fallback => {
627 self.window.reported += unmarked as u32;
628 self.window.lost += lost.min(unmarked) as u32;
629 if self.window.reported >= WINDOW {
630 if self.window.lost * 4 < WINDOW && self.window.lost * 2 < self.fallback_from {
631 self.fallbacks += 1;
632 if self.fallbacks >= FALLBACKS_TO_DISABLE {
633 self.record(EcnFailure::EctLost { disabled: true });
634 self.state = EcnState::Disabled;
635 } else {
636 self.record(EcnFailure::EctLost { disabled: false });
637 self.initiate();
638 }
639 } else {
640 self.state = EcnState::Active;
641 self.window = Window::default();
642 }
643 }
644 }
645 EcnState::Failed { .. } | EcnState::Disabled => {}
646 }
647 }
648
649 fn known_since(&self, extended_highest: u32) -> u32 {
652 let mut span = 0u32;
653 while span < HISTORY as u32 {
654 let sequence_number = extended_highest.wrapping_sub(span) as u16;
655 let slot = &self.history[usize::from(sequence_number) % HISTORY];
656 if !(slot.known && slot.sequence_number == sequence_number) {
657 break;
658 }
659 span += 1;
660 }
661 span
662 }
663
664 fn count(&mut self, undo_loss: bool, received: bool, bleached: bool) {
665 if undo_loss {
666 self.window.lost = self.window.lost.saturating_sub(1);
667 } else {
668 self.window.reported += 1;
669 }
670 if !received {
671 self.window.lost += 1;
672 } else if bleached {
673 self.window.bleached += 1;
674 }
675 }
676
677 fn provisional_success(&mut self, now: Instant) {
681 self.state = EcnState::Active;
682 self.window = Window::default();
683 let started = self.initiated_at.unwrap_or(now);
684 self.provisional_until = Some(started + PROVISIONAL_MONITOR);
685 }
686
687 pub fn on_remote_cname(&mut self, now: Instant, cname: &str) {
695 if self.group.is_none() {
696 match &self.receiver_cname {
697 None => {
698 self.receiver_cname = Some(cname.to_owned());
699 return;
700 }
701 Some(known) if known == cname => return,
702 Some(_) => {}
703 }
704 let provisional = self.state == EcnState::Active
705 && self.provisional_until.is_some_and(|until| now < until);
706 let mut group = Group::default();
707 if let Some(first) = &self.receiver_cname {
708 group.members.insert(first.clone(), false);
709 }
710 self.group = Some(group);
711 if provisional {
712 log::info!(
713 "ECN: another RTCP CNAME during a provisional success, probing again \
714 (RFC 6679 section 7.2.1)"
715 );
716 self.initiate();
717 }
718 }
719 let Some(group) = self.group.as_mut() else {
720 return;
721 };
722 if group.members.contains_key(cname) || group.members.len() >= MAX_PARTICIPANTS {
723 return;
724 }
725 group.members.insert(cname.to_owned(), false);
726 group.changed_at = Some(now);
727 }
728
729 pub fn with_receiver_cnames<'a>(mut self, cnames: impl IntoIterator<Item = &'a str>) -> Self {
732 for cname in cnames {
733 if self.receiver_cname.is_none() {
734 self.receiver_cname = Some(cname.to_owned());
735 continue;
736 }
737 let group = self.group.get_or_insert_with(|| {
738 let mut group = Group::default();
739 if let Some(first) = &self.receiver_cname {
740 group.members.insert(first.clone(), false);
741 }
742 group
743 });
744 if group.members.len() < MAX_PARTICIPANTS {
745 group.members.insert(cname.to_owned(), false);
746 }
747 }
748 self
749 }
750
751 pub fn is_group(&self) -> bool {
754 self.group.is_some()
755 }
756
757 fn confirm(&mut self, now: Instant, reporter: Option<&str>) {
760 let (Some(group), Some(reporter)) = (self.group.as_mut(), reporter) else {
761 return;
762 };
763 if let Some(confirmed) = group.members.get_mut(reporter) {
764 *confirmed = true;
765 } else if group.members.len() < MAX_PARTICIPANTS {
766 group.members.insert(reporter.to_owned(), true);
767 group.changed_at = Some(now);
768 }
769 }
770
771 fn group_success(&mut self, now: Instant) -> bool {
776 let (Some(group), EcnState::Initiating, Some(started)) =
777 (&self.group, self.state, self.initiated_at)
778 else {
779 return false;
780 };
781 let stable_since = group
782 .changed_at
783 .map_or(started, |changed| changed.max(started));
784 let success = now >= started + PROVISIONAL_MONITOR
785 && now >= stable_since + REPORTING_INTERVAL
786 && !group.members.is_empty()
787 && group.members.values().all(|confirmed| *confirmed);
788 if success {
789 self.state = EcnState::Active;
790 self.window = Window::default();
791 self.provisional_until = None;
792 }
793 success
794 }
795
796 pub fn on_reception_report_without_ecn(&mut self, now: Instant, extended_highest: u32) {
803 if self.state != EcnState::Initiating {
804 return;
805 }
806 let highest = extended_highest as u16;
807 let due = self
808 .history
809 .iter()
810 .filter(|sent| {
811 sent.known && sent.marked && {
812 let behind = highest.wrapping_sub(sent.sequence_number);
814 usize::from(behind) < HISTORY
815 }
816 })
817 .count();
818 if due > 3 {
819 self.fail(now, EcnFailure::NoEcnReport);
820 }
821 }
822
823 pub fn on_report_without_reception(&mut self, now: Instant) {
832 if !self.leap_of_faith
833 || self.state != EcnState::Active
834 || !self.history.iter().any(|sent| sent.known && sent.marked)
835 {
836 return;
837 }
838 self.reports_without_reception += 1;
839 if self.reports_without_reception >= 2 {
840 self.leap_of_faith = false;
841 self.fail(now, EcnFailure::NoReception);
842 }
843 }
844
845 pub fn on_reception_reported(&mut self) {
847 self.reports_without_reception = 0;
848 self.leap_of_faith = false;
849 }
850
851 pub fn with_receiver_cname(mut self, cname: &str) -> Self {
854 self.receiver_cname = Some(cname.to_owned());
855 self
856 }
857
858 pub fn is_provisional(&self, now: Instant) -> bool {
860 self.state == EcnState::Active && self.provisional_until.is_some_and(|until| now < until)
861 }
862
863 fn initiate(&mut self) {
864 if let Some(group) = self.group.as_mut() {
865 group
866 .members
867 .values_mut()
868 .for_each(|confirmed| *confirmed = false);
869 }
870 self.provisional_until = None;
871 self.initiated_at = None;
872 self.state = EcnState::Initiating;
873 self.since_probe = PROBE_SPACING;
874 self.last_probe = None;
875 self.probes_confirmed = 0;
876 self.probes_lost = 0;
877 self.window = Window::default();
878 }
879
880 fn record(&mut self, failure: EcnFailure) {
883 if failure.is_initiation_failure() {
884 log::warn!("ECN: {failure}; packets go out Not-ECT");
885 } else {
886 log::warn!("ECN: {failure}");
887 }
888 if self.failures.len() == MAX_KEPT_FAILURES {
889 self.failures.remove(0);
890 }
891 self.failures.push(failure);
892 }
893
894 pub fn take_failures(&mut self) -> Vec<EcnFailure> {
896 std::mem::take(&mut self.failures)
897 }
898
899 fn fail(&mut self, now: Instant, failure: EcnFailure) {
900 self.record(failure);
901 self.state = EcnState::Failed {
902 retry_at: now + self.retry_after,
903 };
904 self.window = Window::default();
905 }
906}
907
908#[cfg(test)]
909mod tests {
910 use super::*;
911
912 fn counters_for(
915 sent: &[u16],
916 marked: &[u16],
917 ect_arrives: bool,
918 lost: u16,
919 base: EcnCounters,
920 ) -> EcnCounters {
921 let marked_count = marked.len() as u32;
922 let unmarked = (sent.len() - marked.len()) as u16;
923 let mut c = base;
924 if ect_arrives {
925 c.ect1 += marked_count - u32::from(lost.min(marked_count as u16));
926 c.not_ect += unmarked;
927 } else {
928 c.not_ect += unmarked + marked_count as u16 - lost;
929 }
930 c.lost += lost;
931 c
932 }
933
934 #[test]
940 fn bundled_sections_use_one_initiation_method() {
941 use EcnInitiation::{LeapOfFaith, RtpAndRtcp};
942 let methods = EcnInitiation::one_per_transport(&[
943 (0, Some(RtpAndRtcp)),
944 (0, Some(LeapOfFaith)),
945 (0, None),
946 (1, Some(LeapOfFaith)),
947 ]);
948 assert_eq!(
949 methods,
950 vec![Some(RtpAndRtcp), Some(RtpAndRtcp), None, Some(LeapOfFaith)]
951 );
952 }
953
954 #[test]
955 fn the_ect_parameter_names_ect0_ect1_or_random_and_nothing_else() {
956 assert_eq!(EctPreference::from_sdp("0"), Some(EctPreference::Ect0));
957 assert_eq!(EctPreference::from_sdp(" 1"), Some(EctPreference::Ect1));
958 assert_eq!(
959 EctPreference::from_sdp("Random"),
960 Some(EctPreference::Random)
961 );
962 assert_eq!(EctPreference::from_sdp("2"), None);
963 assert_eq!(
964 EcnMarking::Rfc6679.codepoint(None, true),
965 shared::EcnCodepoint::Ect0,
966 "RFC 6679 section 7.3.1: ECT(0) unless asked"
967 );
968 assert_eq!(
969 EcnMarking::L4s.codepoint(Some(EctPreference::Ect0), false),
970 shared::EcnCodepoint::Ect1
971 );
972 }
973
974 #[test]
975 fn counted_ect_probes_complete_the_initiation() {
976 let mut v = EcnValidation::default();
977 let mut at = Instant::now();
978 let sent: Vec<u16> = (0..40).collect();
979 let marked = send(&mut v, &mut at, 0, 40);
980 assert!(
981 marked.len() >= 2 && marked.len() < 40,
982 "probes only: {marked:?}"
983 );
984 let c = counters_for(&sent, &marked, true, 0, EcnCounters::default());
985 v.on_counters(at, 39, c);
986 assert_eq!(v.state(), EcnState::Active);
987 assert_eq!(
988 send(&mut v, &mut at, 40, 10).len(),
989 10,
990 "all marked once active"
991 );
992 }
993
994 #[test]
997 fn probes_counted_not_ect_fail_the_initiation() {
998 let mut v = EcnValidation::default().with_retry_after(Duration::from_secs(10));
999 let mut at = Instant::now();
1000 let sent: Vec<u16> = (0..40).collect();
1001 let marked = send(&mut v, &mut at, 0, 40);
1002 let c = counters_for(&sent, &marked, false, 0, EcnCounters::default());
1003 v.on_counters(at, 39, c);
1004 assert!(
1005 matches!(v.state(), EcnState::Failed { .. }),
1006 "{:?}",
1007 v.state()
1008 );
1009 assert!(
1010 send(&mut v, &mut at, 40, 20).is_empty(),
1011 "nothing marked after the failure"
1012 );
1013 at += Duration::from_secs(11);
1014 assert!(
1015 !send(&mut v, &mut at, 60, 20).is_empty(),
1016 "probing again after the retry time"
1017 );
1018 }
1019
1020 #[test]
1023 fn bleaching_counted_in_ongoing_use_stops_the_marking() {
1024 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1025 let mut at = Instant::now();
1026 let sent: Vec<u16> = (0..40).collect();
1027 let marked = send(&mut v, &mut at, 0, 40);
1028 assert_eq!(marked.len(), 40);
1029 let c = counters_for(&sent, &marked, false, 0, EcnCounters::default());
1030 v.on_counters(at, 39, c);
1031 assert!(
1032 matches!(v.state(), EcnState::Failed { .. }),
1033 "{:?}",
1034 v.state()
1035 );
1036 }
1037
1038 #[test]
1040 fn counted_loss_of_ect_packets_falls_back_to_not_ect() {
1041 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1042 let mut at = Instant::now();
1043 let sent: Vec<u16> = (0..40).collect();
1044 let marked = send(&mut v, &mut at, 0, 40);
1045 let c = counters_for(&sent, &marked, true, 20, EcnCounters::default());
1046 v.on_counters(at, 39, c);
1047 assert_eq!(v.state(), EcnState::Fallback);
1048 assert!(send(&mut v, &mut at, 40, 10).is_empty());
1049 }
1050
1051 fn send(v: &mut EcnValidation, at: &mut Instant, first: u16, count: u16) -> Vec<u16> {
1053 let mut marked = vec![];
1054 for n in 0..count {
1055 let seq = first.wrapping_add(n);
1056 if v.on_send(*at, seq) {
1057 marked.push(seq);
1058 }
1059 *at += Duration::from_millis(20);
1060 }
1061 marked
1062 }
1063
1064 fn report_from(
1066 v: &mut EcnValidation,
1067 at: Instant,
1068 reporter: Option<&str>,
1069 first: u16,
1070 count: u16,
1071 path: impl Fn(u16, bool) -> Option<Ecn>,
1072 ) {
1073 for n in 0..count {
1074 let seq = first.wrapping_add(n);
1075 let marked = v.was_marked(seq);
1076 match path(seq, marked) {
1077 Some(ecn) => v.on_report_from(at, reporter, seq, true, ecn),
1078 None => v.on_report_from(at, reporter, seq, false, Ecn::NotEct),
1079 }
1080 }
1081 }
1082
1083 fn report(
1085 v: &mut EcnValidation,
1086 at: Instant,
1087 first: u16,
1088 count: u16,
1089 path: impl Fn(u16, bool) -> Option<Ecn>,
1090 ) {
1091 for n in 0..count {
1092 let seq = first.wrapping_add(n);
1093 let marked = v.was_marked(seq);
1094 match path(seq, marked) {
1095 Some(ecn) => v.on_report(at, seq, true, ecn),
1096 None => v.on_report(at, seq, false, Ecn::NotEct),
1097 }
1098 }
1099 }
1100
1101 fn carries_ecn(_: u16, marked: bool) -> Option<Ecn> {
1102 Some(if marked { Ecn::Ect1 } else { Ecn::NotEct })
1103 }
1104
1105 #[test]
1109 fn a_second_cname_during_a_provisional_success_sends_the_stream_back_to_probing() {
1110 let mut v = EcnValidation::default();
1111 let mut at = Instant::now();
1112 v.on_remote_cname(at, "peer");
1113 send(&mut v, &mut at, 0, 40);
1114 report(&mut v, at, 0, 40, carries_ecn);
1115 assert!(v.is_provisional(at));
1116 v.on_remote_cname(at, "peer");
1117 assert_eq!(v.state(), EcnState::Active, "the same receiver");
1118 assert!(!v.is_group());
1119 v.on_remote_cname(at, "another participant");
1120 assert_eq!(v.state(), EcnState::Initiating);
1121 assert!(v.is_group());
1122 let probes = send(&mut v, &mut at, 40, 40).len();
1123 assert!((1..40).contains(&probes), "a small fraction only: {probes}");
1124 }
1125
1126 #[test]
1135 fn a_group_initiation_succeeds_only_when_every_participant_confirmed_a_stable_membership() {
1136 let mut v = EcnValidation::default();
1137 let start = Instant::now();
1138 let mut at = start;
1139 v.on_remote_cname(at, "alice");
1140 v.on_remote_cname(at, "bob");
1141 assert!(v.is_group(), "two CNAMEs before the first probe");
1142 let mut seq = 0u16;
1143 fn round(v: &mut EcnValidation, at: &mut Instant, seq: &mut u16, who: &[&str]) {
1145 send(v, at, *seq, 50);
1146 for reporter in who {
1147 report_from(v, *at, Some(reporter), *seq, 50, carries_ecn);
1148 }
1149 *seq = seq.wrapping_add(50);
1150 }
1151
1152 while at < start + PROVISIONAL_MONITOR + REPORTING_INTERVAL {
1154 round(&mut v, &mut at, &mut seq, &["alice"]);
1155 }
1156 assert_eq!(v.state(), EcnState::Initiating, "bob has not confirmed");
1157 let first = seq;
1159 send(&mut v, &mut at, first, 10);
1160 report(&mut v, at, first, 10, carries_ecn);
1161 seq = first + 10;
1162 assert_eq!(v.state(), EcnState::Initiating);
1163
1164 v.on_remote_cname(at, "carol");
1166 let joined = at;
1167 round(&mut v, &mut at, &mut seq, &["alice", "bob"]);
1168 assert_eq!(v.state(), EcnState::Initiating, "carol has not confirmed");
1169 round(&mut v, &mut at, &mut seq, &["carol"]);
1171 assert!(at < joined + REPORTING_INTERVAL);
1172 assert_eq!(v.state(), EcnState::Initiating, "not stable yet");
1173 while at < joined + REPORTING_INTERVAL {
1175 round(&mut v, &mut at, &mut seq, &[]);
1176 }
1177 let marked = send(&mut v, &mut at, seq, 10);
1178 assert_eq!(v.state(), EcnState::Active);
1179 assert_eq!(marked.len(), 10, "all marked once the group confirmed");
1180 assert!(
1181 !v.is_provisional(at),
1182 "a full success, not a provisional one"
1183 );
1184 }
1185
1186 #[test]
1187 fn initiation_marks_a_small_fraction_never_all() {
1188 let mut v = EcnValidation::default();
1189 let mut at = Instant::now();
1190 let marked = send(&mut v, &mut at, 0, 100);
1191 assert!(marked.len() >= 4, "probes: {marked:?}");
1192 assert!(marked.len() <= 100 / 4, "a small fraction: {marked:?}");
1193 assert!(
1194 marked.windows(2).all(|w| w[1] - w[0] >= 2),
1195 "never two in a row: {marked:?}"
1196 );
1197 assert_eq!(v.state(), EcnState::Initiating);
1198 }
1199
1200 #[test]
1201 fn a_slow_stream_still_probes_twice_a_second() {
1202 let mut v = EcnValidation::default();
1203 let mut at = Instant::now();
1204 let mut marked = 0;
1205 for seq in 0..10u16 {
1207 marked += u32::from(v.on_send(at, seq));
1208 at += Duration::from_millis(200);
1209 }
1210 assert!(marked >= 4, "{marked} probes in two seconds");
1211 assert!(marked < 10);
1212 }
1213
1214 #[test]
1215 fn confirmed_probes_make_every_packet_ect() {
1216 let mut v = EcnValidation::default();
1217 let mut at = Instant::now();
1218 send(&mut v, &mut at, 0, 40);
1219 report(&mut v, at, 0, 40, carries_ecn);
1220 assert_eq!(v.state(), EcnState::Active);
1221 assert_eq!(send(&mut v, &mut at, 40, 20).len(), 20);
1222 assert!(v.marks_all());
1223 }
1224
1225 #[test]
1226 fn a_ce_marked_probe_confirms_ecn_too() {
1227 let mut v = EcnValidation::default();
1228 let mut at = Instant::now();
1229 send(&mut v, &mut at, 0, 40);
1230 report(&mut v, at, 0, 40, |_, m| {
1231 Some(if m { Ecn::Ce } else { Ecn::NotEct })
1232 });
1233 assert_eq!(v.state(), EcnState::Active);
1234 }
1235
1236 #[test]
1237 fn a_bleached_probe_fails_the_initiation_and_a_retry_follows() {
1238 let mut v = EcnValidation::default().with_retry_after(Duration::from_secs(10));
1239 let mut at = Instant::now();
1240 send(&mut v, &mut at, 0, 40);
1241 report(&mut v, at, 0, 40, |_, _| Some(Ecn::NotEct));
1242 assert!(
1243 matches!(v.state(), EcnState::Failed { .. }),
1244 "{:?}",
1245 v.state()
1246 );
1247 assert!(send(&mut v, &mut at, 40, 100).is_empty(), "nothing marked");
1248 at += Duration::from_secs(10);
1249 assert!(
1250 !send(&mut v, &mut at, 140, 20).is_empty(),
1251 "initiating again"
1252 );
1253 assert_eq!(v.state(), EcnState::Initiating);
1254 }
1255
1256 #[test]
1257 fn a_path_that_drops_ect_packets_fails_the_initiation() {
1258 let mut v = EcnValidation::default();
1259 let mut at = Instant::now();
1260 let probes = send(&mut v, &mut at, 0, 60);
1261 assert!(probes.len() >= 4);
1262 report(&mut v, at, 0, 60, |_, m| (!m).then_some(Ecn::NotEct));
1263 assert!(
1264 matches!(v.state(), EcnState::Failed { .. }),
1265 "{:?}",
1266 v.state()
1267 );
1268 }
1269
1270 #[test]
1271 fn three_lost_probes_are_not_yet_a_failure() {
1272 let mut v = EcnValidation::default();
1273 let mut at = Instant::now();
1274 let probes = send(&mut v, &mut at, 0, 60);
1275 let lost: Vec<u16> = probes[..3].to_vec();
1276 report(&mut v, at, 0, 60, |s, m| {
1277 if lost.contains(&s) {
1278 None
1279 } else {
1280 carries_ecn(s, m)
1281 }
1282 });
1283 assert_eq!(v.state(), EcnState::Active, "the fourth probe arrived ECT");
1284 }
1285
1286 #[test]
1287 fn a_late_packet_reported_lost_then_received_is_not_a_loss() {
1288 let mut v = EcnValidation::default();
1289 let mut at = Instant::now();
1290 let probes = send(&mut v, &mut at, 0, 60);
1291 for &p in &probes {
1292 v.on_report(at, p, false, Ecn::NotEct);
1293 v.on_report(at, p, true, Ecn::Ect1);
1294 v.on_report(at, p, true, Ecn::Ect1);
1296 v.on_report(at, p, false, Ecn::NotEct);
1297 }
1298 assert_eq!(v.state(), EcnState::Active);
1299 }
1300
1301 #[test]
1302 fn bleaching_during_use_stops_the_marking() {
1303 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1304 let mut at = Instant::now();
1305 assert_eq!(
1306 send(&mut v, &mut at, 0, 32).len(),
1307 32,
1308 "leap of faith marks all"
1309 );
1310 report(&mut v, at, 0, 32, |s, _| {
1312 Some(if s % 16 == 0 { Ecn::NotEct } else { Ecn::Ect1 })
1313 });
1314 assert_eq!(v.state(), EcnState::Active);
1315 send(&mut v, &mut at, 32, 32);
1316 report(&mut v, at, 32, 32, |_, _| Some(Ecn::NotEct));
1317 assert!(
1318 matches!(v.state(), EcnState::Failed { .. }),
1319 "{:?}",
1320 v.state()
1321 );
1322 assert!(send(&mut v, &mut at, 64, 50).is_empty());
1323 }
1324
1325 #[test]
1330 fn leap_of_faith_waits_for_a_second_report_without_reception() {
1331 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1332 let mut at = Instant::now();
1333 v.on_report_without_reception(at);
1335 v.on_report_without_reception(at);
1336 assert_eq!(v.state(), EcnState::Active);
1337 assert_eq!(send(&mut v, &mut at, 0, 10).len(), 10);
1338 v.on_report_without_reception(at);
1339 assert_eq!(v.state(), EcnState::Active, "one report is not enough");
1340 v.on_report_without_reception(at);
1341 assert!(
1342 matches!(v.state(), EcnState::Failed { .. }),
1343 "{:?}",
1344 v.state()
1345 );
1346 assert_eq!(v.take_failures(), vec![EcnFailure::NoReception]);
1347 assert!(
1348 send(&mut v, &mut at, 10, 10).is_empty(),
1349 "Not-ECT after the failure"
1350 );
1351
1352 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1353 send(&mut v, &mut at, 0, 10);
1354 v.on_report_without_reception(at);
1355 v.on_reception_reported();
1356 v.on_report_without_reception(at);
1357 v.on_report_without_reception(at);
1358 assert_eq!(v.state(), EcnState::Active, "reception was reported");
1359
1360 let mut v = EcnValidation::new(EcnInitiation::RtpAndRtcp);
1362 send(&mut v, &mut at, 0, 40);
1363 v.on_report_without_reception(at);
1364 v.on_report_without_reception(at);
1365 assert!(v.take_failures().is_empty());
1366 }
1367
1368 #[test]
1369 fn loss_that_goes_with_the_marking_initiates_again_then_disables() {
1370 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1371 let mut at = Instant::now();
1372 let mut seq = 0u16;
1373 for round in 0..FALLBACKS_TO_DISABLE {
1374 if round > 0 {
1376 let n = 40;
1378 send(&mut v, &mut at, seq, n);
1379 report(&mut v, at, seq, n, carries_ecn);
1380 seq += n;
1381 }
1382 assert_eq!(v.state(), EcnState::Active, "round {round}");
1383 send(&mut v, &mut at, seq, 32);
1384 report(&mut v, at, seq, 32, |_, m| (!m).then_some(Ecn::NotEct));
1385 seq += 32;
1386 assert_eq!(v.state(), EcnState::Fallback, "round {round}");
1387 assert!(
1388 send(&mut v, &mut at, seq, 32).is_empty(),
1389 "Not-ECT while comparing"
1390 );
1391 report(&mut v, at, seq, 32, |_, m| (!m).then_some(Ecn::NotEct));
1392 seq += 32;
1393 }
1394 assert_eq!(v.state(), EcnState::Disabled);
1395 at += DEFAULT_RETRY_AFTER * 2;
1396 assert!(
1397 send(&mut v, &mut at, seq, 40).is_empty(),
1398 "disabled for good"
1399 );
1400 let mut expected =
1403 vec![EcnFailure::EctLost { disabled: false }; FALLBACKS_TO_DISABLE as usize - 1];
1404 expected.push(EcnFailure::EctLost { disabled: true });
1405 assert_eq!(v.take_failures(), expected);
1406 assert!(v.take_failures().is_empty(), "taken once");
1407 }
1408
1409 #[test]
1410 fn loss_that_stays_without_the_marking_resumes_it() {
1411 let mut v = EcnValidation::new(EcnInitiation::LeapOfFaith);
1412 let mut at = Instant::now();
1413 send(&mut v, &mut at, 0, 32);
1414 report(&mut v, at, 0, 32, |s, _| (s % 2 == 0).then_some(Ecn::Ect1));
1415 assert_eq!(v.state(), EcnState::Fallback);
1416 send(&mut v, &mut at, 32, 32);
1417 report(&mut v, at, 32, 32, |s, _| {
1418 (s % 2 == 0).then_some(Ecn::NotEct)
1419 });
1420 assert_eq!(v.state(), EcnState::Active, "congestion, not ECN");
1421 }
1422
1423 #[test]
1428 fn arbitrary_send_and_report_sequences_keep_the_invariants() {
1429 let mut state = 0x0EC0_0001u32;
1430 let mut next = move || {
1431 state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1432 state >> 8
1433 };
1434 for _ in 0..400 {
1435 let mut v = if next() % 2 == 0 {
1436 EcnValidation::default()
1437 } else {
1438 EcnValidation::new(EcnInitiation::LeapOfFaith)
1439 }
1440 .with_retry_after(Duration::from_millis(u64::from(next() % 3000)));
1441 let mut at = Instant::now();
1442 let mut seq = next() as u16;
1443 let mut sent: Vec<u16> = vec![];
1444 let mut run_marked = 0u32;
1445 let mut initiating = (0u32, 0u32);
1446 for _ in 0..600 {
1447 at += Duration::from_millis(u64::from(next() % 60));
1448 match next() % 10 {
1449 0..=5 => {
1450 seq = match next() % 20 {
1451 0 => seq.wrapping_add(next() as u16),
1452 1 => seq,
1453 _ => seq.wrapping_add(1),
1454 };
1455 let was = v.state();
1456 let marked = v.on_send(at, seq);
1457 sent.push(seq);
1458 if was == EcnState::Disabled {
1459 assert!(!marked, "a disabled stream marks nothing");
1460 }
1461 if v.state() == EcnState::Initiating && was == EcnState::Initiating {
1462 initiating.0 += 1;
1463 initiating.1 += u32::from(marked);
1464 run_marked = if marked { run_marked + 1 } else { 0 };
1465 assert!(run_marked <= 1, "two probes in a row");
1466 } else {
1467 run_marked = 0;
1468 }
1469 }
1470 _ => {
1471 let target = if sent.is_empty() || next() % 8 == 0 {
1472 next() as u16
1473 } else {
1474 sent[(next() as usize) % sent.len()]
1475 };
1476 let ecn = match next() % 4 {
1477 0 => Ecn::NotEct,
1478 1 => Ecn::Ect1,
1479 2 => Ecn::Ect0,
1480 _ => Ecn::Ce,
1481 };
1482 v.on_report(at, target, next() % 5 != 0, ecn);
1483 }
1484 }
1485 }
1486 if initiating.0 >= 40 {
1487 assert!(
1488 initiating.1 * 4 <= initiating.0 + 4,
1489 "a small fraction while initiating: {initiating:?}"
1490 );
1491 }
1492 }
1493 }
1494}