Skip to main content

rustflexstack/management/
dcc_entity.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! DCC entity: couples a [`CbrProvider`] (access layer) with a DCC algorithm and
5//! the facilities layer.
6//!
7//! On each evaluation (every 200 ms, aligned to UTC-modulo-200 ms boundaries per
8//! ETSI TS 102 687 V1.2.1 clause 5.2) the entity:
9//! 1. polls the CBR provider;
10//! 2. runs the reactive (clause 5.3) or adaptive (clause 5.4) algorithm;
11//! 3. converts the result into `T_GenCam_DCC`, the minimum CAM generation
12//!    interval provided to the CA basic service (ETSI TS 103 900 §6.1.3),
13//!    bounded to `[T_GenCamMin, T_GenCamMax] = [100, 1000]` ms;
14//! 4. notifies every registered listener with the new `T_GenCam_DCC`.
15//!
16//! Conversion:
17//! - **Reactive**: `T_GenCam_DCC = T_off` of the current state (Annex A tables).
18//! - **Adaptive**: `T_GenCam_DCC = T_on / delta` (gate interval of equation B.1).
19//!
20//! Mirrors `flexstack/management/dcc_entity.py`.
21//!
22//! # Example
23//! ```no_run
24//! use rustflexstack::management::{DccEntity, DccMode, SharedCbr};
25//!
26//! let cbr = SharedCbr::new();
27//! let mut dcc = DccEntity::new(DccMode::reactive(), Box::new(cbr.clone()));
28//! // let ctm = ca_service.cam_transmission_management.clone();
29//! // dcc.add_t_gen_cam_dcc_listener(move |ms| ctm.set_t_gen_cam_dcc(ms));
30//! let handle = dcc.spawn();
31//! cbr.report(0.45); // from the access layer
32//! handle.stop();
33//! ```
34
35use super::cbr::CbrProvider;
36use super::dcc_adaptive::{DccAdaptive, DccAdaptiveParameters};
37use super::dcc_reactive::{DccReactive, DccState};
38use std::sync::atomic::{AtomicBool, Ordering};
39use std::sync::Arc;
40use std::thread::{self, JoinHandle};
41use std::time::{Duration, SystemTime, UNIX_EPOCH};
42
43/// DCC evaluation period in milliseconds (clause 5.2).
44pub const DCC_EVALUATION_PERIOD_MS: u64 = 200;
45/// Lower bound of `T_GenCam_DCC` (`T_GenCamMin`, ETSI TS 103 900 §6.1.3) [ms].
46pub const T_GEN_CAM_DCC_MIN_MS: u64 = 100;
47/// Upper bound of `T_GenCam_DCC` (`T_GenCamMax`, ETSI TS 103 900 §6.1.3) [ms].
48pub const T_GEN_CAM_DCC_MAX_MS: u64 = 1_000;
49
50/// DCC algorithm selection.
51#[derive(Debug, Clone, PartialEq)]
52pub enum DccMode {
53    /// Reactive DCC (clause 5.3, Annex A).
54    Reactive {
55        /// Maximum packet airtime in µs; `<= 500` selects Table A.2, otherwise Table A.1.
56        t_on_max_us: u32,
57    },
58    /// Adaptive DCC / LIMERIC (clause 5.4).
59    Adaptive {
60        /// LIMERIC parameters (Table 3 defaults).
61        parameters: DccAdaptiveParameters,
62        /// Nominal CAM airtime `T_on` in ms used for `T_on / delta`.
63        t_on_ms: f64,
64    },
65}
66
67impl DccMode {
68    /// Reactive DCC with Table A.1 (`T_on` ≤ 1 ms).
69    pub fn reactive() -> Self {
70        DccMode::Reactive { t_on_max_us: 1000 }
71    }
72
73    /// Adaptive DCC with Table 3 default parameters and `T_on` = 1 ms.
74    pub fn adaptive() -> Self {
75        DccMode::Adaptive {
76            parameters: DccAdaptiveParameters::default(),
77            t_on_ms: 1.0,
78        }
79    }
80}
81
82/// Result of one DCC entity evaluation.
83#[derive(Debug, Clone, Copy, PartialEq)]
84pub struct DccEntityOutput {
85    /// CBR used for this evaluation.
86    pub cbr: f64,
87    /// Resulting `T_GenCam_DCC` in ms, within `[100, 1000]`.
88    pub t_gen_cam_dcc_ms: u64,
89    /// Reactive state (reactive mode only).
90    pub state: Option<DccState>,
91    /// Duty-cycle fraction `delta` (adaptive mode only).
92    pub delta: Option<f64>,
93}
94
95enum Algorithm {
96    Reactive(DccReactive),
97    Adaptive { alg: DccAdaptive, t_on_ms: f64 },
98}
99
100type Listener = Box<dyn Fn(u64) + Send>;
101
102/// DCC entity of the ITS-S management layer.
103pub struct DccEntity {
104    algorithm: Algorithm,
105    provider: Box<dyn CbrProvider>,
106    previous_cbr: Option<f64>,
107    last_output: Option<DccEntityOutput>,
108    listeners: Vec<Listener>,
109}
110
111/// Bound an interval in ms to `[T_GEN_CAM_DCC_MIN_MS, T_GEN_CAM_DCC_MAX_MS]`.
112pub fn clamp_t_gen_cam_dcc(interval_ms: f64) -> u64 {
113    if !interval_ms.is_finite() {
114        return T_GEN_CAM_DCC_MAX_MS;
115    }
116    (interval_ms.round().max(0.0) as u64).clamp(T_GEN_CAM_DCC_MIN_MS, T_GEN_CAM_DCC_MAX_MS)
117}
118
119impl DccEntity {
120    /// Create a DCC entity with the given algorithm and CBR source.
121    pub fn new(mode: DccMode, provider: Box<dyn CbrProvider>) -> Self {
122        let algorithm = match mode {
123            DccMode::Reactive { t_on_max_us } => Algorithm::Reactive(DccReactive::new(t_on_max_us)),
124            DccMode::Adaptive {
125                parameters,
126                t_on_ms,
127            } => Algorithm::Adaptive {
128                alg: DccAdaptive::new(parameters),
129                t_on_ms,
130            },
131        };
132        Self {
133            algorithm,
134            provider,
135            previous_cbr: None,
136            last_output: None,
137            listeners: Vec::new(),
138        }
139    }
140
141    /// Register a callback receiving `T_GenCam_DCC` (ms) after every evaluation,
142    /// e.g. `move |ms| ctm.set_t_gen_cam_dcc(ms)`.
143    pub fn add_t_gen_cam_dcc_listener<F>(&mut self, listener: F)
144    where
145        F: Fn(u64) + Send + 'static,
146    {
147        self.listeners.push(Box::new(listener));
148    }
149
150    /// Output of the most recent successful evaluation.
151    pub fn last_output(&self) -> Option<DccEntityOutput> {
152        self.last_output
153    }
154
155    /// Run one evaluation.
156    ///
157    /// Returns `None` (and leaves the previous output in place) when the provider
158    /// has no measurement or returns a value outside `[0.0, 1.0]`.
159    pub fn evaluate(&mut self) -> Option<DccEntityOutput> {
160        let cbr = self.provider.measure_cbr()?;
161        if !(0.0..=1.0).contains(&cbr) {
162            return None;
163        }
164        let output = match &mut self.algorithm {
165            Algorithm::Reactive(alg) => {
166                let out = alg.update(cbr).ok()?;
167                DccEntityOutput {
168                    cbr,
169                    t_gen_cam_dcc_ms: clamp_t_gen_cam_dcc(out.t_off_ms),
170                    state: Some(out.state),
171                    delta: None,
172                }
173            }
174            Algorithm::Adaptive { alg, t_on_ms } => {
175                let previous = self.previous_cbr.unwrap_or(cbr);
176                let delta = alg.update_local(cbr, previous).ok()?;
177                DccEntityOutput {
178                    cbr,
179                    t_gen_cam_dcc_ms: clamp_t_gen_cam_dcc(*t_on_ms / delta),
180                    state: None,
181                    delta: Some(delta),
182                }
183            }
184        };
185        self.previous_cbr = Some(cbr);
186        self.last_output = Some(output);
187        for listener in &self.listeners {
188            listener(output.t_gen_cam_dcc_ms);
189        }
190        Some(output)
191    }
192
193    /// Run the entity on a background thread, evaluating at every
194    /// UTC-modulo-200 ms boundary until [`DccEntityHandle::stop`] is called.
195    pub fn spawn(mut self) -> DccEntityHandle {
196        let stop = Arc::new(AtomicBool::new(false));
197        let stop_flag = stop.clone();
198        let join = thread::spawn(move || {
199            while !stop_flag.load(Ordering::SeqCst) {
200                thread::sleep(Duration::from_millis(ms_to_next_boundary()));
201                if stop_flag.load(Ordering::SeqCst) {
202                    break;
203                }
204                let _ = self.evaluate();
205            }
206        });
207        DccEntityHandle {
208            stop,
209            join: Some(join),
210        }
211    }
212}
213
214fn ms_to_next_boundary() -> u64 {
215    let now_ms = SystemTime::now()
216        .duration_since(UNIX_EPOCH)
217        .unwrap_or_default()
218        .as_millis() as u64;
219    DCC_EVALUATION_PERIOD_MS - (now_ms % DCC_EVALUATION_PERIOD_MS)
220}
221
222/// Handle to a DCC entity running on a background thread.
223pub struct DccEntityHandle {
224    stop: Arc<AtomicBool>,
225    join: Option<JoinHandle<()>>,
226}
227
228impl DccEntityHandle {
229    /// Stop the background thread and wait for it to finish (≤ one period).
230    pub fn stop(mut self) {
231        self.stop.store(true, Ordering::SeqCst);
232        if let Some(join) = self.join.take() {
233            let _ = join.join();
234        }
235    }
236}
237
238impl Drop for DccEntityHandle {
239    fn drop(&mut self) {
240        self.stop.store(true, Ordering::SeqCst);
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    use crate::management::cbr::SharedCbr;
248    use std::sync::atomic::AtomicU64;
249
250    fn entity(mode: DccMode) -> (DccEntity, SharedCbr) {
251        let cbr = SharedCbr::new();
252        (DccEntity::new(mode, Box::new(cbr.clone())), cbr)
253    }
254
255    #[test]
256    fn test_clamp_t_gen_cam_dcc() {
257        assert_eq!(clamp_t_gen_cam_dcc(10.0), 100);
258        assert_eq!(clamp_t_gen_cam_dcc(400.4), 400);
259        assert_eq!(clamp_t_gen_cam_dcc(5000.0), 1000);
260        assert_eq!(clamp_t_gen_cam_dcc(f64::INFINITY), 1000);
261        assert_eq!(clamp_t_gen_cam_dcc(f64::NAN), 1000);
262    }
263
264    #[test]
265    fn test_no_measurement_returns_none() {
266        let (mut dcc, _cbr) = entity(DccMode::reactive());
267        assert_eq!(dcc.evaluate(), None);
268        assert_eq!(dcc.last_output(), None);
269    }
270
271    #[test]
272    fn test_reactive_relaxed_maps_to_t_gen_cam_min() {
273        let (mut dcc, cbr) = entity(DccMode::reactive());
274        cbr.report(0.1);
275        let out = dcc.evaluate().unwrap();
276        assert_eq!(out.state, Some(DccState::Relaxed));
277        assert_eq!(out.t_gen_cam_dcc_ms, 100);
278        assert_eq!(out.delta, None);
279    }
280
281    #[test]
282    fn test_reactive_steps_one_state_per_evaluation() {
283        // Table A.1 T_off: 100, 200, 400, 500, 1000 ms.
284        let (mut dcc, cbr) = entity(DccMode::reactive());
285        cbr.report(0.9);
286        let expected = [200, 400, 500, 1000, 1000];
287        for ms in expected {
288            assert_eq!(dcc.evaluate().unwrap().t_gen_cam_dcc_ms, ms);
289        }
290        assert_eq!(
291            dcc.last_output().unwrap().state,
292            Some(DccState::Restrictive)
293        );
294        // Channel clears: one step down per evaluation.
295        cbr.report(0.0);
296        assert_eq!(dcc.evaluate().unwrap().t_gen_cam_dcc_ms, 500);
297        assert_eq!(dcc.evaluate().unwrap().t_gen_cam_dcc_ms, 400);
298    }
299
300    #[test]
301    fn test_reactive_table_a2() {
302        let (mut dcc, cbr) = entity(DccMode::Reactive { t_on_max_us: 500 });
303        cbr.report(0.35);
304        // Table A.2 Active1 T_off = 100 ms.
305        assert_eq!(dcc.evaluate().unwrap().t_gen_cam_dcc_ms, 100);
306    }
307
308    #[test]
309    fn test_adaptive_low_cbr_allows_t_gen_cam_min() {
310        let (mut dcc, cbr) = entity(DccMode::adaptive());
311        cbr.report(0.0);
312        let mut out = dcc.evaluate().unwrap();
313        for _ in 0..2000 {
314            out = dcc.evaluate().unwrap();
315        }
316        // delta converges to delta_max = 0.03 -> 1 ms / 0.03 = 33 ms -> clamped to 100 ms.
317        assert!((out.delta.unwrap() - 0.03).abs() < 1e-9);
318        assert_eq!(out.t_gen_cam_dcc_ms, 100);
319        assert_eq!(out.state, None);
320    }
321
322    #[test]
323    fn test_adaptive_high_cbr_reaches_t_gen_cam_max() {
324        let (mut dcc, cbr) = entity(DccMode::adaptive());
325        cbr.report(1.0);
326        // The CBR_ITS_S smoothing (step 1) starts below the target, so delta
327        // first rises; it then converges to delta_min under a saturated channel.
328        let mut out = dcc.evaluate().unwrap();
329        for _ in 0..2000 {
330            out = dcc.evaluate().unwrap();
331        }
332        // delta = delta_min = 0.0006 -> 1 ms / 0.0006 = 1667 ms -> clamped to 1000 ms.
333        assert!((out.delta.unwrap() - 0.0006).abs() < 1e-12);
334        assert_eq!(out.t_gen_cam_dcc_ms, 1000);
335    }
336
337    #[test]
338    fn test_adaptive_uses_previous_cbr() {
339        let (mut a, cbr_a) = entity(DccMode::adaptive());
340        let (mut b, _cbr_b) = entity(DccMode::adaptive());
341        cbr_a.report(0.2);
342        a.evaluate().unwrap();
343        cbr_a.report(0.6);
344        let out = a.evaluate().unwrap();
345        // Same sequence through the algorithm directly.
346        let mut alg = DccAdaptive::default();
347        alg.update_local(0.2, 0.2).unwrap();
348        let delta = alg.update_local(0.6, 0.2).unwrap();
349        assert!((out.delta.unwrap() - delta).abs() < 1e-15);
350        assert_eq!(b.evaluate(), None);
351    }
352
353    #[test]
354    fn test_listeners_receive_t_gen_cam_dcc() {
355        let (mut dcc, cbr) = entity(DccMode::reactive());
356        let seen = Arc::new(AtomicU64::new(0));
357        let seen2 = seen.clone();
358        dcc.add_t_gen_cam_dcc_listener(move |ms| seen2.store(ms, Ordering::SeqCst));
359        cbr.report(0.9);
360        dcc.evaluate().unwrap();
361        assert_eq!(seen.load(Ordering::SeqCst), 200);
362    }
363
364    #[test]
365    fn test_spawn_evaluates_periodically_and_stops() {
366        let (mut dcc, cbr) = entity(DccMode::reactive());
367        let seen = Arc::new(AtomicU64::new(0));
368        let seen2 = seen.clone();
369        dcc.add_t_gen_cam_dcc_listener(move |ms| seen2.store(ms, Ordering::SeqCst));
370        cbr.report(0.9);
371        let handle = dcc.spawn();
372        thread::sleep(Duration::from_millis(3 * DCC_EVALUATION_PERIOD_MS + 50));
373        handle.stop();
374        // At least two evaluations happened: Relaxed -> Active1 (200) -> Active2 (400) ...
375        assert!(seen.load(Ordering::SeqCst) >= 400);
376    }
377
378    #[test]
379    fn test_ms_to_next_boundary_in_range() {
380        let ms = ms_to_next_boundary();
381        assert!((1..=DCC_EVALUATION_PERIOD_MS).contains(&ms));
382    }
383}