Skip to main content

qualia_core_db/net/qdnf/session/
pacing.rs

1//! Tokenless send pacing. Eligibility is a deadline, not a credit ledger.
2
3use crate::net::qdnf::errors::QdnfError;
4use crate::net::qdnf::session::rtt::RttEstimator;
5
6#[repr(C)]
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub struct Pacer {
9    pub next_send_us: u64,
10    pub rate_bytes_per_s: u64,
11}
12
13impl Pacer {
14    /// Creates a default `Pacer`.
15    pub const fn new(rate_bytes_per_s: u64) -> Self {
16        Self {
17            next_send_us: 0,
18            rate_bytes_per_s,
19        }
20    }
21}
22
23impl Default for Pacer {
24    fn default() -> Self {
25        Self::new(0)
26    }
27}
28
29/// [`QdnfError::WouldBlock`] when `now_us` is still before the pacing deadline.
30pub fn wait_until(pacer: &Pacer, now_us: u64) -> Result<(), QdnfError> {
31    if now_us < pacer.next_send_us {
32        Err(QdnfError::WouldBlock)
33    } else {
34        Ok(())
35    }
36}
37
38/// Charge `bytes` against the pacing rate and push `next_send_us`.
39pub fn on_paced_send(pacer: &mut Pacer, bytes: u64, now_us: u64) -> Result<(), QdnfError> {
40    wait_until(pacer, now_us)?;
41    if pacer.rate_bytes_per_s == 0 {
42        return Err(QdnfError::Incomplete);
43    }
44    if bytes == 0 {
45        return Err(QdnfError::Range);
46    }
47    let interval = bytes.saturating_mul(1_000_000) / pacer.rate_bytes_per_s;
48    pacer.next_send_us = now_us.saturating_add(interval.max(1));
49    Ok(())
50}
51
52/// Idle send fence. After `idle_us` with no send, further send is Closed.
53/// Reopen with the same generation is Replay (nonce reuse). A new generation
54/// is required. Wired into packet protection via `PacketProtection::seal_paced`.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub struct IdleWatch {
57    last_activity_us: u64,
58    idle_us: u64,
59    generation: u64,
60    closed: bool,
61}
62
63impl IdleWatch {
64    /// Creates a default `IdleWatch`.
65    pub const fn new(idle_us: u64, generation: u64) -> Self {
66        Self {
67            last_activity_us: 0,
68            idle_us,
69            generation,
70            closed: false,
71        }
72    }
73
74    /// Pacing hook on send.
75    pub fn on_send(&mut self, now_us: u64) -> Result<(), QdnfError> {
76        if self.closed {
77            return Err(QdnfError::Closed);
78        }
79        if now_us.saturating_sub(self.last_activity_us) >= self.idle_us && self.last_activity_us > 0
80        {
81            self.closed = true;
82            return Err(QdnfError::Closed);
83        }
84        self.last_activity_us = now_us;
85        Ok(())
86    }
87
88    /// Reopens the pacing window.
89    pub fn reopen(&mut self, generation: u64) -> Result<(), QdnfError> {
90        if generation == self.generation {
91            return Err(QdnfError::Replay);
92        }
93        if generation < self.generation {
94            return Err(QdnfError::StaleGeneration);
95        }
96        self.generation = generation;
97        self.closed = false;
98        self.last_activity_us = 0;
99        Ok(())
100    }
101}
102
103/// Rate ≈ window / smoothed_rtt (RFC 9002 pacing). Unknown RTT fails closed.
104pub fn set_rate_from_window_rtt(
105    pacer: &mut Pacer,
106    window_bytes: u64,
107    rtt: &RttEstimator,
108) -> Result<(), QdnfError> {
109    let rtt_us = crate::net::qdnf::session::rtt::smoothed_or_err(rtt)? as u64;
110    if window_bytes == 0 {
111        return Err(QdnfError::Range);
112    }
113    pacer.rate_bytes_per_s = window_bytes.saturating_mul(1_000_000) / rtt_us;
114    if pacer.rate_bytes_per_s == 0 {
115        pacer.rate_bytes_per_s = 1;
116    }
117    Ok(())
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use crate::net::qdnf::session::rtt::on_ack_sample;
124
125    #[test]
126    fn wait_until_would_block_before_deadline() {
127        let pacer = Pacer {
128            next_send_us: 1000,
129            rate_bytes_per_s: 1200,
130        };
131        assert_eq!(wait_until(&pacer, 999), Err(QdnfError::WouldBlock));
132        assert_eq!(wait_until(&pacer, 1000), Ok(()));
133        assert_eq!(wait_until(&pacer, 1001), Ok(()));
134    }
135
136    #[test]
137    fn paced_send_advances_deadline() {
138        let mut pacer = Pacer::new(1_000_000);
139        on_paced_send(&mut pacer, 500, 0).unwrap();
140        assert_eq!(pacer.next_send_us, 500);
141        assert_eq!(on_paced_send(&mut pacer, 1, 0), Err(QdnfError::WouldBlock));
142        on_paced_send(&mut pacer, 1, 500).unwrap();
143        assert!(pacer.next_send_us > 500);
144    }
145
146    #[test]
147    fn unknown_rtt_does_not_invent_a_rate() {
148        let mut pacer = Pacer::new(0);
149        let rtt = RttEstimator::new();
150        assert_eq!(
151            set_rate_from_window_rtt(&mut pacer, 1200, &rtt),
152            Err(QdnfError::Incomplete)
153        );
154        let mut rtt = RttEstimator::new();
155        on_ack_sample(&mut rtt, 1000);
156        set_rate_from_window_rtt(&mut pacer, 1200, &rtt).unwrap();
157        assert_eq!(pacer.rate_bytes_per_s, 1_200_000);
158    }
159
160    #[test]
161    fn idle_shutdown_closes_without_nonce_reuse() {
162        let mut idle = IdleWatch::new(100, 1);
163        idle.on_send(1).unwrap();
164        idle.on_send(50).unwrap();
165        assert_eq!(idle.on_send(150), Err(QdnfError::Closed));
166        assert_eq!(idle.on_send(151), Err(QdnfError::Closed));
167        assert_eq!(idle.reopen(1), Err(QdnfError::Replay));
168        idle.reopen(2).unwrap();
169        idle.on_send(200).unwrap();
170    }
171
172    #[test]
173    fn fuzz_pacing_and_idle_harness() {
174        let rates = [1, 10, 100, 1_000, 10_000, 1_000_000, 100_000_000];
175        let packet_sizes = [1, 64, 512, 1200, 4096, 65535];
176        let timestamps = [0, 10, 100, 1_000, 50_000, 100_000, 1_000_000];
177
178        for &rate in &rates {
179            let mut pacer = Pacer::new(rate);
180            let mut cur_ts = 0u64;
181            for &sz in &packet_sizes {
182                for &delta in &timestamps {
183                    cur_ts = cur_ts.saturating_add(delta);
184                    if let Ok(()) = wait_until(&pacer, cur_ts) {
185                        let res = on_paced_send(&mut pacer, sz, cur_ts);
186                        assert!(res.is_ok());
187                        assert!(pacer.next_send_us > cur_ts);
188                    }
189                }
190            }
191        }
192
193        // IdleWatch fuzzing
194        let mut idle = IdleWatch::new(500, 1);
195        let mut gen = 1u64;
196        for t in (0..5_000).step_by(50) {
197            match idle.on_send(t) {
198                Ok(()) => {}
199                Err(QdnfError::Closed) => {
200                    gen += 1;
201                    assert!(idle.reopen(gen).is_ok());
202                    assert!(idle.on_send(t).is_ok());
203                }
204                Err(e) => panic!("Unexpected error: {:?}", e),
205            }
206        }
207    }
208}