Skip to main content

rtci_interceptor/pacing/
pacer.rs

1//! The leaky bucket a pacer meters packets through.
2
3use std::time::{Duration, Instant};
4
5/// Smallest burst any pacer allows, in bits.
6///
7/// One maximum-sized packet: 1500 bytes, 12 000 bits. A burst below one packet would mean the
8/// common case never becomes affordable by waiting, so every packet would take the
9/// larger-than-burst path and the rate would stop being enforced at all.
10pub const MIN_BURST_BITS: f64 = 8.0 * 1500.0;
11
12/// The pacing interval: a group of packets leaves every 5 ms
13/// (draft-ietf-rmcat-gcc-02 section 4).
14pub const BURST_TIME: Duration = Duration::from_millis(5);
15
16/// A token bucket in bits, refilled from elapsed time.
17///
18/// Unlike upstream's `rate.Limiter`, nothing here reads a clock: the budget is a pure function of
19/// the instants handed in. That is what makes a release schedule reproducible in a test rather
20/// than merely eventually-correct — pion cannot assert its own schedule without a fake clock.
21#[derive(Debug, Clone)]
22pub struct Pacer {
23    /// Target rate in bits per second.
24    bitrate: f64,
25    /// The burst the caller chose, or `None` to derive it from the rate.
26    ///
27    /// Only the *intent* is stored, never the resulting burst: a burst chosen by the caller is a
28    /// property of the sender — how much it is willing to put on the wire at once — while a
29    /// derived one is a property of the rate and has to follow it. Keeping the computed value in
30    /// a field instead would lose which of the two it was the moment it was written, and
31    /// [`Pacer::set_target_bitrate`] could not tell whether it was allowed to replace it.
32    configured_burst_bits: Option<f64>,
33    /// Currently available budget, in bits.
34    budget_bits: f64,
35    /// When the budget was last brought up to date.
36    last_refill: Option<Instant>,
37}
38
39impl Pacer {
40    /// A bucket paced at `bits_per_second`, starting full.
41    ///
42    /// Starting full rather than empty lets a connection send immediately instead of waiting out
43    /// one burst's worth of accumulation, which is what upstream's limiter does too.
44    pub fn new(bits_per_second: f64) -> Self {
45        Self {
46            bitrate: bits_per_second.max(0.0),
47            configured_burst_bits: None,
48            budget_bits: Self::burst_for(bits_per_second),
49            last_refill: None,
50        }
51    }
52
53    /// Override the burst size, in bits.
54    ///
55    /// A burst set here is kept across rate changes. Deriving it from the rate is only a default;
56    /// once the caller has said how much it is willing to release at once, an estimator raising
57    /// the rate must not quietly widen that.
58    pub fn with_burst_bits(mut self, burst_bits: f64) -> Self {
59        self.configured_burst_bits = Some(burst_bits.max(MIN_BURST_BITS));
60        // A pacer starts with a full bucket, whatever size the bucket is.
61        self.budget_bits = if self.last_refill.is_none() {
62            self.burst_bits()
63        } else {
64            self.budget_bits.min(self.burst_bits())
65        };
66        self
67    }
68
69    /// The burst that goes with a rate: what the target sends in one [`BURST_TIME`], floored
70    /// at one packet (draft-ietf-rmcat-gcc-02 section 4: the pacer sends a group of packets
71    /// every burst_time of 5 ms, of size target bitrate times burst_time).
72    fn burst_for(bits_per_second: f64) -> f64 {
73        (bits_per_second * BURST_TIME.as_secs_f64()).max(MIN_BURST_BITS)
74    }
75
76    /// The rate currently being paced at, in bits per second.
77    pub fn target_bitrate(&self) -> f64 {
78        self.bitrate
79    }
80
81    /// Change the rate.
82    ///
83    /// Synchronous and immediate, because this is what a bandwidth estimator drives: it computes
84    /// a new target and the very next release must respect it. Accumulated budget is kept but
85    /// clamped to the new burst, so lowering the rate cannot leave a large budget behind that
86    /// would let a burst out at the old rate.
87    ///
88    /// A burst set through [`Pacer::with_burst_bits`] survives this; only a burst that was derived
89    /// from the rate follows the rate.
90    pub fn set_target_bitrate(&mut self, bits_per_second: f64) {
91        self.bitrate = bits_per_second.max(0.0);
92        self.budget_bits = self.budget_bits.min(self.burst_bits());
93    }
94
95    /// Bring the budget up to `now`.
96    pub fn refill(&mut self, now: Instant) {
97        if let Some(last) = self.last_refill {
98            let elapsed = now.saturating_duration_since(last).as_secs_f64();
99            self.budget_bits = (self.budget_bits + elapsed * self.bitrate).min(self.burst_bits());
100        }
101        self.last_refill = Some(now);
102    }
103
104    /// Whether `bits` can be sent now.
105    pub fn can_afford(&self, bits: f64) -> bool {
106        self.budget_bits >= bits
107    }
108
109    /// Spend `bits` from the budget.
110    ///
111    /// The budget is allowed to go negative on a packet larger than a full burst; otherwise such
112    /// a packet could never be sent at all, and a stalled queue is worse than a momentary
113    /// overshoot.
114    pub fn consume(&mut self, bits: f64) {
115        self.budget_bits -= bits;
116    }
117
118    /// How long until `bits` becomes affordable.
119    ///
120    /// `Duration::ZERO` when it already is. At a zero rate nothing ever becomes affordable, which
121    /// the caller must treat as "no deadline" rather than waiting forever.
122    pub fn time_until_affordable(&self, bits: f64) -> Option<Duration> {
123        if self.budget_bits >= bits {
124            return Some(Duration::ZERO);
125        }
126        if self.bitrate <= 0.0 {
127            return None;
128        }
129        Some(Duration::from_secs_f64(
130            (bits - self.budget_bits) / self.bitrate,
131        ))
132    }
133
134    /// The instant `bits` becomes affordable, given the last refill.
135    pub fn affordable_at(&self, bits: f64) -> Option<Instant> {
136        let last = self.last_refill?;
137        self.time_until_affordable(bits).map(|wait| last + wait)
138    }
139
140    /// The available budget, in bits.
141    pub fn budget_bits(&self) -> f64 {
142        self.budget_bits
143    }
144
145    /// Whether `bits` may be released now.
146    ///
147    /// A packet larger than a full burst can never be *afforded* — the budget caps at the burst —
148    /// so it is released once the budget has refilled to that cap, which is as long as waiting can
149    /// possibly help. Gating on a full budget rather than releasing unconditionally is what keeps
150    /// a run of oversized packets paced: each drives the budget negative and the next must wait
151    /// for it to recover, so they leave at the target rate instead of all at once.
152    pub fn can_release(&self, bits: f64) -> bool {
153        let burst_bits = self.burst_bits();
154        if bits > burst_bits {
155            return self.budget_bits >= burst_bits;
156        }
157        self.budget_bits >= bits
158    }
159
160    /// The instant `bits` may be released, per [`Pacer::can_release`].
161    pub fn releasable_at(&self, bits: f64) -> Option<Instant> {
162        self.affordable_at(bits.min(self.burst_bits()))
163    }
164
165    /// The maximum the budget can accumulate to, in bits.
166    ///
167    /// Anything larger than this can never be afforded by waiting, however long the wait — the
168    /// budget caps here — which is why release is asked for through [`Pacer::can_release`] rather
169    /// than [`Pacer::can_afford`].
170    pub fn burst_bits(&self) -> f64 {
171        self.configured_burst_bits
172            .unwrap_or_else(|| Self::burst_for(self.bitrate))
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    /// 1 Mb/s, with a burst big enough to be interesting but small enough to exhaust.
181    fn pacer() -> Pacer {
182        Pacer::new(1_000_000.0).with_burst_bits(MIN_BURST_BITS)
183    }
184
185    #[test]
186    fn a_new_bucket_starts_full() {
187        let pacer = pacer();
188        assert_eq!(MIN_BURST_BITS, pacer.budget_bits());
189        assert!(pacer.can_afford(MIN_BURST_BITS));
190    }
191
192    #[test]
193    fn spending_reduces_the_budget() {
194        let mut pacer = pacer();
195        pacer.consume(1000.0);
196        assert_eq!(MIN_BURST_BITS - 1000.0, pacer.budget_bits());
197    }
198
199    /// The budget is a function of elapsed time, not of how often refill happens to be called.
200    #[test]
201    fn the_budget_refills_from_elapsed_time() {
202        let now = Instant::now();
203        let mut pacer = pacer();
204        pacer.refill(now);
205        pacer.consume(pacer.budget_bits());
206        assert_eq!(0.0, pacer.budget_bits());
207
208        // At 1 Mb/s, 10 ms is 10 000 bits.
209        pacer.refill(now + Duration::from_millis(10));
210        assert!(
211            (pacer.budget_bits() - 10_000.0).abs() < 1.0,
212            "{}",
213            pacer.budget_bits()
214        );
215    }
216
217    #[test]
218    fn refilling_in_steps_matches_refilling_at_once() {
219        let now = Instant::now();
220
221        let mut stepped = pacer();
222        stepped.refill(now);
223        stepped.consume(stepped.budget_bits());
224        for step in 1..=10 {
225            stepped.refill(now + Duration::from_millis(step));
226        }
227
228        let mut at_once = pacer();
229        at_once.refill(now);
230        at_once.consume(at_once.budget_bits());
231        at_once.refill(now + Duration::from_millis(10));
232
233        assert!((stepped.budget_bits() - at_once.budget_bits()).abs() < 1.0);
234    }
235
236    /// The bucket cannot fill beyond its burst, or an idle connection would accumulate an
237    /// unbounded allowance and release it all at once the moment it resumed.
238    #[test]
239    fn the_budget_is_capped_at_the_burst() {
240        let now = Instant::now();
241        let mut pacer = pacer();
242        pacer.refill(now);
243        pacer.refill(now + Duration::from_secs(60));
244
245        assert_eq!(MIN_BURST_BITS, pacer.budget_bits());
246    }
247
248    #[test]
249    fn the_time_until_affordable_is_zero_when_it_already_is() {
250        let pacer = pacer();
251        assert_eq!(Some(Duration::ZERO), pacer.time_until_affordable(100.0));
252    }
253
254    #[test]
255    fn the_time_until_affordable_scales_with_the_shortfall() {
256        let now = Instant::now();
257        let mut pacer = pacer();
258        pacer.refill(now);
259        pacer.consume(pacer.budget_bits());
260
261        // 10 000 bits short at 1 Mb/s is 10 ms.
262        let wait = pacer
263            .time_until_affordable(10_000.0)
264            .expect("a finite wait");
265        assert!((wait.as_secs_f64() - 0.010).abs() < 0.0005, "got {wait:?}");
266        assert_eq!(Some(now + wait), pacer.affordable_at(10_000.0));
267    }
268
269    /// At a zero rate nothing ever becomes affordable. Reporting a deadline anyway would have the
270    /// driver wake for a release that can never happen.
271    #[test]
272    fn nothing_becomes_affordable_at_a_zero_rate() {
273        let now = Instant::now();
274        let mut pacer = Pacer::new(0.0);
275        pacer.refill(now);
276        pacer.consume(pacer.budget_bits());
277
278        assert_eq!(None, pacer.time_until_affordable(1000.0));
279        assert_eq!(None, pacer.affordable_at(1000.0));
280    }
281
282    #[test]
283    fn changing_the_rate_changes_how_fast_the_budget_refills() {
284        let now = Instant::now();
285        // A derived burst, so the burst grows with the rate and does not cap what is asserted.
286        let mut pacer = Pacer::new(10_000_000.0);
287        pacer.refill(now);
288        pacer.consume(pacer.budget_bits());
289
290        pacer.set_target_bitrate(20_000_000.0);
291        pacer.refill(now + Duration::from_millis(2));
292
293        // Twice the rate, twice the budget for the same elapsed time (and inside the 5 ms
294        // burst, which would otherwise cap it).
295        assert!(
296            (pacer.budget_bits() - 40_000.0).abs() < 1.0,
297            "{}",
298            pacer.budget_bits()
299        );
300        assert_eq!(20_000_000.0, pacer.target_bitrate());
301    }
302
303    /// Lowering the rate must not leave a budget accumulated at the old one, or the first thing
304    /// after a rate cut would be a burst at the rate that was just abandoned.
305    #[test]
306    fn lowering_the_rate_clamps_the_budget_to_the_new_burst() {
307        let now = Instant::now();
308        let mut pacer = Pacer::new(100_000_000.0);
309        pacer.refill(now);
310        let before = pacer.budget_bits();
311
312        pacer.set_target_bitrate(1000.0);
313
314        assert!(pacer.budget_bits() < before);
315        assert_eq!(
316            MIN_BURST_BITS,
317            pacer.budget_bits(),
318            "clamped to the floor burst"
319        );
320    }
321
322    #[test]
323    fn a_negative_rate_is_treated_as_zero() {
324        let mut pacer = Pacer::new(-5.0);
325        assert_eq!(0.0, pacer.target_bitrate());
326        pacer.set_target_bitrate(-1.0);
327        assert_eq!(0.0, pacer.target_bitrate());
328    }
329
330    /// A burst the caller chose is not a function of the rate. Losing it on the first estimator
331    /// update would silently change how bursty the sender is, long after it was configured.
332    #[test]
333    fn a_configured_burst_survives_a_rate_change() {
334        let mut pacer = Pacer::new(1_000_000.0).with_burst_bits(MIN_BURST_BITS);
335        assert_eq!(MIN_BURST_BITS, pacer.burst_bits());
336
337        pacer.set_target_bitrate(100_000_000.0);
338
339        assert_eq!(
340            MIN_BURST_BITS,
341            pacer.burst_bits(),
342            "a rate change must not widen a burst the caller set"
343        );
344        assert_eq!(100_000_000.0, pacer.target_bitrate());
345    }
346
347    /// The derived default still tracks the rate — pinning is opt-in, not the new default.
348    #[test]
349    fn a_derived_burst_follows_the_rate() {
350        // draft-ietf-rmcat-gcc-02 section 4: group size = target bitrate * burst_time (5 ms).
351        let mut pacer = Pacer::new(10_000_000.0);
352        assert_eq!(50_000.0, pacer.burst_bits());
353
354        pacer.set_target_bitrate(20_000_000.0);
355
356        assert_eq!(100_000.0, pacer.burst_bits());
357
358        // Never less than one full-sized packet, or nothing could ever leave.
359        pacer.set_target_bitrate(300_000.0);
360        assert_eq!(MIN_BURST_BITS, pacer.burst_bits());
361    }
362
363    /// A packet larger than the burst waits for a full budget rather than going unconditionally,
364    /// so a run of them leaves at the target rate instead of all at once.
365    #[test]
366    fn an_oversized_packet_waits_for_a_full_budget() {
367        let now = Instant::now();
368        let mut pacer = pacer();
369        pacer.refill(now);
370        let oversized = MIN_BURST_BITS * 2.0;
371
372        assert!(pacer.can_release(oversized), "a full budget releases it");
373        pacer.consume(oversized);
374        assert!(
375            !pacer.can_release(oversized),
376            "the next one waits for the debt to be repaid"
377        );
378
379        // The wait is the debt at the target rate, which is what paces a run of them.
380        let at = pacer.releasable_at(oversized).expect("a finite wait");
381        assert_eq!(
382            Some(Duration::from_secs_f64(oversized / 1_000_000.0)),
383            pacer.time_until_affordable(MIN_BURST_BITS)
384        );
385        pacer.refill(at);
386        assert!(pacer.can_release(oversized), "and then it goes");
387    }
388
389    /// A packet larger than a full burst must still get out. Refusing it would stall the queue
390    /// permanently behind a packet that can never become affordable.
391    #[test]
392    fn a_packet_larger_than_the_burst_can_still_be_sent() {
393        let now = Instant::now();
394        let mut pacer = pacer();
395        pacer.refill(now);
396
397        let oversized = MIN_BURST_BITS * 2.0;
398        assert!(!pacer.can_afford(oversized));
399
400        // Even after waiting, the budget caps at the burst — so the caller has to spend anyway.
401        pacer.refill(now + Duration::from_secs(10));
402        assert!(!pacer.can_afford(oversized));
403
404        pacer.consume(oversized);
405        assert!(
406            pacer.budget_bits() < 0.0,
407            "the overshoot is paid back over time"
408        );
409
410        pacer.refill(now + Duration::from_secs(20));
411        assert_eq!(
412            MIN_BURST_BITS,
413            pacer.budget_bits(),
414            "and recovers to the burst"
415        );
416    }
417}