Skip to main content

buffering_runtime/
stall_memory.rs

1//! Stall memory: a max-hold of the PDV with a hold then a linear decay.
2
3use core::time::Duration;
4
5use crate::time::{duration_add, instant_micros, micros_as_duration};
6
7/// Plain-data snapshot of the stall memory, for session persistence.
8///
9/// **Aging semantics.** `peak` is the raw held peak; `age` is how long ago
10/// (on the controller's arrival clock) that peak was observed. The
11/// decayed value is `peak` while `age <= hold`, then falls linearly to 0 over
12/// `decay`. A snapshot restored after `N` seconds of wall time must be aged by
13/// `N` first: [`StallMemorySnapshot::aged`]. The restored memory is anchored
14/// at the first clock reading the new controller sees, so a restore adds no
15/// extra age of its own.
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[non_exhaustive]
19pub struct StallMemorySnapshot {
20    /// Raw held peak PDV.
21    pub peak: Duration,
22    /// Age of that peak.
23    pub age: Duration,
24}
25
26impl StallMemorySnapshot {
27    /// Build a snapshot. The struct is `#[non_exhaustive]`, so a foreign
28    /// crate or FFI wrapper cannot use a struct literal: this `const fn` is
29    /// the constructor (usable in `const`/`static` context; `Default` is the
30    /// empty memory and the fields stay public for reading).
31    #[must_use]
32    pub const fn new(peak: Duration, age: Duration) -> Self {
33        Self { peak, age }
34    }
35
36    /// The same memory `elapsed` of wall time later (saturating at the end of
37    /// the microsecond range).
38    #[must_use]
39    pub fn aged(self, elapsed: Duration) -> Self {
40        Self {
41            peak: self.peak,
42            age: duration_add(self.age, elapsed),
43        }
44    }
45}
46
47/// Decayed value of a peak of the given age.
48pub(crate) fn decayed(peak: u64, age: u64, hold: u64, decay: u64) -> u64 {
49    if age <= hold {
50        return peak;
51    }
52    let into = age - hold;
53    if into >= decay {
54        return 0;
55    }
56    let v = u128::from(peak) * u128::from(decay - into) / u128::from(decay.max(1));
57    u64::try_from(v).unwrap_or(u64::MAX)
58}
59
60fn age_at(now: u64, at: i128) -> u64 {
61    u64::try_from((i128::from(now) - at).max(0)).unwrap_or(u64::MAX)
62}
63
64#[derive(Clone, Debug)]
65pub(crate) struct MaxHold {
66    peak: u64,
67    at: Option<i128>,
68    pending_age: Option<u64>,
69    hold: u64,
70    decay: u64,
71}
72
73impl MaxHold {
74    pub(crate) fn new(hold: u64, decay: u64) -> Self {
75        Self {
76            peak: 0,
77            at: None,
78            pending_age: None,
79            hold,
80            decay,
81        }
82    }
83
84    /// Anchor a restored-but-unplaced snapshot at the clock reading `now`.
85    pub(crate) fn anchor(&mut self, now: u64) {
86        if let Some(age) = self.pending_age.take() {
87            self.at = Some(i128::from(now) - i128::from(age));
88        }
89    }
90
91    pub(crate) fn value(&self, now: u64) -> u64 {
92        match (self.at, self.pending_age) {
93            (Some(at), _) => decayed(self.peak, age_at(now, at), self.hold, self.decay),
94            (None, Some(age)) => decayed(self.peak, age, self.hold, self.decay),
95            (None, None) => 0,
96        }
97    }
98
99    /// Sample-driven: a sample at least as large as the current decayed
100    /// value replaces the peak (so the memory rises immediately).
101    pub(crate) fn observe(&mut self, now: u64, v: u64) {
102        self.anchor(now);
103        if self.at.is_none() || v >= self.value(now) {
104            self.peak = v;
105            self.at = Some(i128::from(now));
106        }
107    }
108
109    pub(crate) fn snapshot(&self, now: u64) -> StallMemorySnapshot {
110        match (self.at, self.pending_age) {
111            (Some(at), _) => StallMemorySnapshot::new(
112                micros_as_duration(self.peak),
113                micros_as_duration(age_at(now, at)),
114            ),
115            (None, Some(age)) => {
116                StallMemorySnapshot::new(micros_as_duration(self.peak), micros_as_duration(age))
117            }
118            (None, None) => StallMemorySnapshot::default(),
119        }
120    }
121
122    pub(crate) fn restore(&mut self, s: StallMemorySnapshot) {
123        self.peak = instant_micros(s.peak);
124        self.at = None;
125        self.pending_age = Some(instant_micros(s.age));
126    }
127
128    pub(crate) fn clear(&mut self) {
129        self.peak = 0;
130        self.at = None;
131        self.pending_age = None;
132    }
133}