Skip to main content

rustflexstack/management/
dcc_reactive.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! Reactive Decentralized Congestion Control (DCC) algorithm.
5//!
6//! Implements the reactive approach specified in ETSI TS 102 687 V1.2.1 (2018-04)
7//! clause 5.3 and Annex A.
8//!
9//! The algorithm consists of five states (Relaxed, Active 1, Active 2, Active 3,
10//! Restrictive) arranged in a linear sequence. On each evaluation the state may
11//! advance at most *one* step toward the state dictated by the current Channel
12//! Busy Ratio (CBR), which enforces the "one state can only be reached by a
13//! neighbouring state" adjacency requirement from clause 5.3. Each state maps
14//! directly to a maximum allowed packet rate and a minimum inter-packet gap (T_off).
15//!
16//! Two parameter tables are defined in Annex A depending on the assumed maximum
17//! packet transmission duration (T_on):
18//! - **Table A.1** – used when T_on is at most 1 ms
19//! - **Table A.2** – used when T_on is at most 500 µs
20
21use super::DccError;
22
23/// Ordered states of the reactive DCC algorithm.
24///
25/// As specified in ETSI TS 102 687 V1.2.1 (2018-04) clause 5.3.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub enum DccState {
28    /// Lowest utilisation state. Fewest restrictions on transmissions.
29    Relaxed = 0,
30    /// First active state. Moderate CBR detected.
31    Active1 = 1,
32    /// Second active state. Elevated CBR detected.
33    Active2 = 2,
34    /// Third active state. High CBR detected.
35    Active3 = 3,
36    /// Most stringent state. Very high CBR detected.
37    Restrictive = 4,
38}
39
40impl DccState {
41    /// Ordered list of states used for single-step transitions.
42    pub const ALL: [DccState; 5] = [
43        DccState::Relaxed,
44        DccState::Active1,
45        DccState::Active2,
46        DccState::Active3,
47        DccState::Restrictive,
48    ];
49
50    /// Returns the zero-based numeric index of the state (0 = Relaxed, 4 = Restrictive).
51    pub fn index(self) -> usize {
52        self as usize
53    }
54
55    /// Converts a zero-based numeric index back to a [`DccState`].
56    pub fn from_index(idx: usize) -> Option<Self> {
57        match idx {
58            0 => Some(DccState::Relaxed),
59            1 => Some(DccState::Active1),
60            2 => Some(DccState::Active2),
61            3 => Some(DccState::Active3),
62            4 => Some(DccState::Restrictive),
63            _ => None,
64        }
65    }
66}
67
68/// Channel Busy Ratio thresholds and output parameters for a single state.
69///
70/// As specified in ETSI TS 102 687 V1.2.1 (2018-04) Annex A, Tables A.1 and A.2.
71#[derive(Debug, Clone, Copy, PartialEq)]
72pub struct DccStateConfig {
73    /// Inclusive lower CBR bound for this state (0.0 for Relaxed).
74    pub cbr_min: f64,
75    /// Exclusive upper CBR bound for this state (1.01 for Restrictive).
76    pub cbr_max: f64,
77    /// Maximum allowed packet transmission rate in packets per second.
78    pub packet_rate_hz: f64,
79    /// Minimum required inter-packet gap in milliseconds (T_off).
80    pub t_off_ms: f64,
81}
82
83impl DccStateConfig {
84    pub const fn new(cbr_min: f64, cbr_max: f64, packet_rate_hz: f64, t_off_ms: f64) -> Self {
85        Self {
86            cbr_min,
87            cbr_max,
88            packet_rate_hz,
89            t_off_ms,
90        }
91    }
92}
93
94// ---------------------------------------------------------------------------
95// Standard parameter tables (Annex A)
96// ---------------------------------------------------------------------------
97
98/// Table A.1 – T_on at most 1 ms.
99/// States ordered from RELAXED to RESTRICTIVE.
100pub const TABLE_A1: [DccStateConfig; 5] = [
101    DccStateConfig::new(0.00, 0.30, 10.0, 100.0), // Relaxed
102    DccStateConfig::new(0.30, 0.40, 5.0, 200.0),  // Active1
103    DccStateConfig::new(0.40, 0.50, 2.5, 400.0),  // Active2
104    DccStateConfig::new(0.50, 0.60, 2.0, 500.0),  // Active3
105    DccStateConfig::new(0.60, 1.01, 1.0, 1000.0), // Restrictive
106];
107
108/// Table A.2 – T_on at most 500 µs.
109pub const TABLE_A2: [DccStateConfig; 5] = [
110    DccStateConfig::new(0.00, 0.30, 20.0, 50.0),  // Relaxed
111    DccStateConfig::new(0.30, 0.40, 10.0, 100.0), // Active1
112    DccStateConfig::new(0.40, 0.50, 5.0, 200.0),  // Active2
113    DccStateConfig::new(0.50, 0.65, 4.0, 250.0),  // Active3
114    DccStateConfig::new(0.65, 1.01, 1.0, 1000.0), // Restrictive
115];
116
117/// Output produced by a single reactive DCC evaluation.
118#[derive(Debug, Clone, Copy, PartialEq)]
119pub struct DccReactiveOutput {
120    /// Current DCC state after the evaluation.
121    pub state: DccState,
122    /// Maximum allowed packet transmission rate in packets per second.
123    pub packet_rate_hz: f64,
124    /// Minimum required inter-packet gap in milliseconds (T_off).
125    pub t_off_ms: f64,
126}
127
128/// Reactive DCC algorithm as specified in ETSI TS 102 687 V1.2.1 (2018-04)
129/// clause 5.3 and Annex A.
130///
131/// The algorithm is evaluated periodically (at least every 200 ms, per
132/// clause 5.2) by calling [`DccReactive::update`] with the most recently measured
133/// Channel Busy Ratio (CBR). On each call the state may advance by at most
134/// one step toward the state inferred from the CBR table, enforcing the
135/// adjacency constraint of clause 5.3.
136#[derive(Debug, Clone)]
137pub struct DccReactive {
138    /// Current algorithm state. Starts at [`DccState::Relaxed`].
139    pub state: DccState,
140    table: &'static [DccStateConfig; 5],
141}
142
143impl Default for DccReactive {
144    fn default() -> Self {
145        Self::new(1000)
146    }
147}
148
149impl DccReactive {
150    /// Initialise the reactive DCC algorithm.
151    ///
152    /// # Parameters
153    /// - `t_on_max_us`: Maximum packet transmission duration in microseconds.
154    ///   Values `<= 500` select Annex A Table A.2; all other values select Table A.1.
155    ///   Defaults to 1000 (1 ms) when constructed via [`Default`].
156    pub fn new(t_on_max_us: u32) -> Self {
157        let table = if t_on_max_us <= 500 {
158            &TABLE_A2
159        } else {
160            &TABLE_A1
161        };
162        Self {
163            state: DccState::Relaxed,
164            table,
165        }
166    }
167
168    /// Return the state whose CBR band contains `cbr`.
169    fn target_state(&self, cbr: f64) -> DccState {
170        for (i, cfg) in self.table.iter().enumerate() {
171            if cfg.cbr_min <= cbr && cbr < cfg.cbr_max {
172                return DccState::from_index(i).unwrap_or(DccState::Restrictive);
173            }
174        }
175        // CBR == 1.0 (or floating-point rounding above 1.0) -> Restrictive
176        DccState::Restrictive
177    }
178
179    /// Evaluate the algorithm with the current Channel Busy Ratio.
180    ///
181    /// The state advances by at most one step toward the state implied by
182    /// `cbr`, satisfying the adjacency constraint from clause 5.3.
183    ///
184    /// # Parameters
185    /// - `cbr`: Current Channel Busy Ratio value in the range `[0.0, 1.0]`.
186    ///
187    /// # Returns
188    /// [`DccReactiveOutput`] with updated state and transmission constraints.
189    ///
190    /// # Errors
191    /// Returns [`DccError::InvalidCbr`] if `cbr` is outside `[0.0, 1.0]`.
192    pub fn update(&mut self, cbr: f64) -> Result<DccReactiveOutput, DccError> {
193        if !(0.0..=1.0).contains(&cbr) {
194            return Err(DccError::InvalidCbr {
195                name: "cbr",
196                value: cbr,
197            });
198        }
199
200        let target = self.target_state(cbr);
201        let mut current_idx = self.state.index();
202        let target_idx = target.index();
203
204        if target_idx > current_idx {
205            current_idx += 1;
206        } else if target_idx < current_idx {
207            current_idx -= 1;
208        }
209        // else target_idx == current_idx -> no change
210
211        self.state = DccState::from_index(current_idx).unwrap_or(DccState::Restrictive);
212        let cfg = self.table[self.state.index()];
213        Ok(DccReactiveOutput {
214            state: self.state,
215            packet_rate_hz: cfg.packet_rate_hz,
216            t_off_ms: cfg.t_off_ms,
217        })
218    }
219}
220
221// ---------------------------------------------------------------------------
222// Unit tests
223// ---------------------------------------------------------------------------
224
225#[cfg(test)]
226#[allow(clippy::float_cmp)]
227mod tests {
228    use super::*;
229
230    macro_rules! assert_almost_eq {
231        ($a:expr, $b:expr) => {
232            assert!(
233                ($a - $b).abs() < 1e-9,
234                "assertion failed: ({} - {}) < 1e-9 (left: {}, right: {})",
235                stringify!($a),
236                stringify!($b),
237                $a,
238                $b
239            );
240        };
241    }
242
243    // ── Initialisation ────────────────────────────────────────────────────
244
245    #[test]
246    fn test_initial_state_is_relaxed() {
247        let dcc = DccReactive::default();
248        assert_eq!(dcc.state, DccState::Relaxed);
249    }
250
251    #[test]
252    fn test_table_a1_selected_by_default() {
253        let mut dcc = DccReactive::new(1000);
254        let out = dcc.update(0.0).unwrap();
255        assert_almost_eq!(out.packet_rate_hz, 10.0);
256        assert_almost_eq!(out.t_off_ms, 100.0);
257    }
258
259    #[test]
260    fn test_table_a2_selected_for_500us() {
261        let mut dcc = DccReactive::new(500);
262        let out = dcc.update(0.0).unwrap();
263        assert_almost_eq!(out.packet_rate_hz, 20.0);
264        assert_almost_eq!(out.t_off_ms, 50.0);
265    }
266
267    #[test]
268    fn test_table_a2_selected_for_below_500us() {
269        let mut dcc = DccReactive::new(250);
270        let out = dcc.update(0.0).unwrap();
271        assert_almost_eq!(out.packet_rate_hz, 20.0);
272    }
273
274    // ── Table A.1 Tests ───────────────────────────────────────────────────
275
276    fn make_dcc_a1() -> DccReactive {
277        DccReactive::new(1000)
278    }
279
280    #[test]
281    fn test_relaxed_output_params() {
282        let mut dcc = make_dcc_a1();
283        let out = dcc.update(0.0).unwrap();
284        assert_eq!(out.state, DccState::Relaxed);
285        assert_almost_eq!(out.packet_rate_hz, 10.0);
286        assert_almost_eq!(out.t_off_ms, 100.0);
287    }
288
289    #[test]
290    fn test_active1_output_params() {
291        let mut dcc = make_dcc_a1();
292        let out = dcc.update(0.35).unwrap();
293        assert_eq!(out.state, DccState::Active1);
294        assert_almost_eq!(out.packet_rate_hz, 5.0);
295        assert_almost_eq!(out.t_off_ms, 200.0);
296    }
297
298    #[test]
299    fn test_active2_output_params() {
300        let mut dcc = make_dcc_a1();
301        dcc.update(0.45).unwrap(); // Relaxed -> Active1
302        let out = dcc.update(0.45).unwrap(); // Active1 -> Active2
303        assert_eq!(out.state, DccState::Active2);
304        assert_almost_eq!(out.packet_rate_hz, 2.5);
305        assert_almost_eq!(out.t_off_ms, 400.0);
306    }
307
308    #[test]
309    fn test_active3_output_params() {
310        let mut dcc = make_dcc_a1();
311        for _ in 0..3 {
312            dcc.update(0.55).unwrap();
313        }
314        let out = dcc.update(0.55).unwrap();
315        assert_eq!(out.state, DccState::Active3);
316        assert_almost_eq!(out.packet_rate_hz, 2.0);
317        assert_almost_eq!(out.t_off_ms, 500.0);
318    }
319
320    #[test]
321    fn test_restrictive_output_params() {
322        let mut dcc = make_dcc_a1();
323        for _ in 0..4 {
324            dcc.update(0.65).unwrap();
325        }
326        let out = dcc.update(0.65).unwrap();
327        assert_eq!(out.state, DccState::Restrictive);
328        assert_almost_eq!(out.packet_rate_hz, 1.0);
329        assert_almost_eq!(out.t_off_ms, 1000.0);
330    }
331
332    // ── Transitions ───────────────────────────────────────────────────────
333
334    #[test]
335    fn test_low_cbr_stays_relaxed() {
336        let mut dcc = make_dcc_a1();
337        for _ in 0..5 {
338            let out = dcc.update(0.10).unwrap();
339            assert_eq!(out.state, DccState::Relaxed);
340        }
341    }
342
343    #[test]
344    fn test_cbr_at_lower_threshold_triggers_active1() {
345        let mut dcc = make_dcc_a1();
346        let out = dcc.update(0.30).unwrap();
347        assert_eq!(out.state, DccState::Active1);
348    }
349
350    #[test]
351    fn test_adjacent_only_from_relaxed_to_active1() {
352        let mut dcc = make_dcc_a1();
353        let out = dcc.update(0.99).unwrap();
354        assert_eq!(out.state, DccState::Active1);
355    }
356
357    #[test]
358    fn test_two_steps_from_relaxed_to_active2() {
359        let mut dcc = make_dcc_a1();
360        dcc.update(0.55).unwrap(); // Relaxed -> Active1
361        let out = dcc.update(0.55).unwrap(); // Active1 -> Active2
362        assert_eq!(out.state, DccState::Active2);
363    }
364
365    #[test]
366    fn test_step_down_from_active1_to_relaxed() {
367        let mut dcc = make_dcc_a1();
368        dcc.update(0.35).unwrap(); // -> Active1
369        let out = dcc.update(0.10).unwrap(); // -> Relaxed
370        assert_eq!(out.state, DccState::Relaxed);
371    }
372
373    #[test]
374    fn test_same_state_when_cbr_in_band() {
375        let mut dcc = make_dcc_a1();
376        dcc.update(0.35).unwrap(); // -> Active1
377        let out = dcc.update(0.32).unwrap(); // still in Active1 band
378        assert_eq!(out.state, DccState::Active1);
379    }
380
381    #[test]
382    fn test_upward_then_downward_transition_sequence() {
383        let mut dcc = make_dcc_a1();
384        let states: Vec<DccState> = [0.45, 0.45, 0.10, 0.10]
385            .iter()
386            .map(|&cbr| dcc.update(cbr).unwrap().state)
387            .collect();
388        assert_eq!(
389            states,
390            vec![
391                DccState::Active1,
392                DccState::Active2,
393                DccState::Active1,
394                DccState::Relaxed,
395            ]
396        );
397    }
398
399    #[test]
400    fn test_cannot_skip_states_going_up() {
401        let mut dcc = make_dcc_a1();
402        let mut previous_idx = 0;
403        for _ in 0..6 {
404            let out = dcc.update(1.0).unwrap();
405            let current_idx = out.state.index();
406            assert!(current_idx >= previous_idx);
407            assert!(current_idx - previous_idx <= 1);
408            previous_idx = current_idx;
409        }
410    }
411
412    #[test]
413    fn test_cannot_skip_states_going_down() {
414        let mut dcc = make_dcc_a1();
415        // Drive to Restrictive
416        for _ in 0..5 {
417            dcc.update(1.0).unwrap();
418        }
419        let mut previous_idx = dcc.state.index();
420        for _ in 0..6 {
421            let out = dcc.update(0.0).unwrap();
422            let current_idx = out.state.index();
423            assert!(previous_idx >= current_idx);
424            assert!(previous_idx - current_idx <= 1);
425            previous_idx = current_idx;
426        }
427    }
428
429    #[test]
430    fn test_cbr_boundary_at_060_table_a1() {
431        let mut dcc = make_dcc_a1();
432        // Drive to Active3 first
433        for _ in 0..3 {
434            dcc.update(0.65).unwrap();
435        }
436        let out = dcc.update(0.60).unwrap();
437        assert_eq!(out.state, DccState::Restrictive);
438    }
439
440    // ── Table A.2 Tests ───────────────────────────────────────────────────
441
442    fn make_dcc_a2() -> DccReactive {
443        DccReactive::new(500)
444    }
445
446    #[test]
447    fn test_relaxed_output_params_table_a2() {
448        let mut dcc = make_dcc_a2();
449        let out = dcc.update(0.10).unwrap();
450        assert_eq!(out.state, DccState::Relaxed);
451        assert_almost_eq!(out.packet_rate_hz, 20.0);
452        assert_almost_eq!(out.t_off_ms, 50.0);
453    }
454
455    #[test]
456    fn test_active3_output_params_table_a2() {
457        let mut dcc = make_dcc_a2();
458        for _ in 0..3 {
459            dcc.update(0.60).unwrap();
460        }
461        let out = dcc.update(0.60).unwrap();
462        assert_eq!(out.state, DccState::Active3);
463        assert_almost_eq!(out.packet_rate_hz, 4.0);
464        assert_almost_eq!(out.t_off_ms, 250.0);
465    }
466
467    #[test]
468    fn test_restrictive_threshold_table_a2() {
469        let mut dcc = make_dcc_a2();
470        // Drive to Active3 (0.60 is still in A3 band for Table A.2)
471        for _ in 0..3 {
472            dcc.update(0.70).unwrap();
473        }
474        let out = dcc.update(0.65).unwrap();
475        assert_eq!(out.state, DccState::Restrictive);
476    }
477
478    // ── Validation ────────────────────────────────────────────────────────
479
480    #[test]
481    fn test_cbr_below_zero_raises() {
482        let mut dcc = DccReactive::default();
483        let res = dcc.update(-0.01);
484        assert!(matches!(res, Err(DccError::InvalidCbr { name: "cbr", .. })));
485    }
486
487    #[test]
488    fn test_cbr_above_one_raises() {
489        let mut dcc = DccReactive::default();
490        let res = dcc.update(1.01);
491        assert!(matches!(res, Err(DccError::InvalidCbr { name: "cbr", .. })));
492    }
493
494    #[test]
495    fn test_cbr_zero_valid() {
496        let mut dcc = DccReactive::default();
497        let out = dcc.update(0.0).unwrap();
498        assert_eq!(out.state, DccState::Relaxed);
499    }
500
501    #[test]
502    fn test_cbr_one_valid() {
503        let mut dcc = DccReactive::default();
504        let out = dcc.update(1.0).unwrap();
505        assert_eq!(out.state, DccState::Active1);
506    }
507
508    // ── Output Equality ───────────────────────────────────────────────────
509
510    #[test]
511    fn test_output_equality() {
512        let a = DccReactiveOutput {
513            state: DccState::Active1,
514            packet_rate_hz: 5.0,
515            t_off_ms: 200.0,
516        };
517        let b = DccReactiveOutput {
518            state: DccState::Active1,
519            packet_rate_hz: 5.0,
520            t_off_ms: 200.0,
521        };
522        assert_eq!(a, b);
523    }
524}