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