rustflexstack/management/
dcc_entity.rs1use 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
43pub const DCC_EVALUATION_PERIOD_MS: u64 = 200;
45pub const T_GEN_CAM_DCC_MIN_MS: u64 = 100;
47pub const T_GEN_CAM_DCC_MAX_MS: u64 = 1_000;
49
50#[derive(Debug, Clone, PartialEq)]
52pub enum DccMode {
53 Reactive {
55 t_on_max_us: u32,
57 },
58 Adaptive {
60 parameters: DccAdaptiveParameters,
62 t_on_ms: f64,
64 },
65}
66
67impl DccMode {
68 pub fn reactive() -> Self {
70 DccMode::Reactive { t_on_max_us: 1000 }
71 }
72
73 pub fn adaptive() -> Self {
75 DccMode::Adaptive {
76 parameters: DccAdaptiveParameters::default(),
77 t_on_ms: 1.0,
78 }
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq)]
84pub struct DccEntityOutput {
85 pub cbr: f64,
87 pub t_gen_cam_dcc_ms: u64,
89 pub state: Option<DccState>,
91 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
102pub 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
111pub 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 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 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 pub fn last_output(&self) -> Option<DccEntityOutput> {
152 self.last_output
153 }
154
155 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 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
222pub struct DccEntityHandle {
224 stop: Arc<AtomicBool>,
225 join: Option<JoinHandle<()>>,
226}
227
228impl DccEntityHandle {
229 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 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 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 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 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 let mut out = dcc.evaluate().unwrap();
329 for _ in 0..2000 {
330 out = dcc.evaluate().unwrap();
331 }
332 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 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 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}