tower/retry/budget/
tps_budget.rs

1//! Transactions Per Minute (Tps) Budget implementations
2
3use std::{
4    fmt,
5    sync::{
6        atomic::{AtomicIsize, Ordering},
7        Mutex,
8    },
9    time::Duration,
10};
11use tokio::time::Instant;
12
13use super::Budget;
14
15/// A Transactions Per Minute config for managing retry tokens.
16///
17/// [`TpsBudget`] uses a token bucket to decide if the request should be retried.
18///
19/// [`TpsBudget`] works by checking how much retries have been made in a certain period of time.
20/// Minimum allowed number of retries are effectively reset on an interval. Allowed number of
21/// retries depends on failed request count in recent time frame.
22///
23/// For more info about [`Budget`], please see the [module-level documentation].
24///
25/// [module-level documentation]: super
26pub struct TpsBudget {
27    generation: Mutex<Generation>,
28    /// Initial budget allowed for every second.
29    reserve: isize,
30    /// Slots of a the TTL divided evenly.
31    slots: Box<[AtomicIsize]>,
32    /// The amount of time represented by each slot.
33    window: Duration,
34    /// The changers for the current slot to be committed
35    /// after the slot expires.
36    writer: AtomicIsize,
37    /// Amount of tokens to deposit for each put().
38    deposit_amount: isize,
39    /// Amount of tokens to withdraw for each try_get().
40    withdraw_amount: isize,
41}
42
43#[derive(Debug)]
44struct Generation {
45    /// Slot index of the last generation.
46    index: usize,
47    /// The timestamp since the last generation expired.
48    time: Instant,
49}
50
51// ===== impl TpsBudget =====
52
53impl TpsBudget {
54    /// Create a [`TpsBudget`] that allows for a certain percent of the total
55    /// requests to be retried.
56    ///
57    /// - The `ttl` is the duration of how long a single `deposit` should be
58    ///   considered. Must be between 1 and 60 seconds.
59    /// - The `min_per_sec` is the minimum rate of retries allowed to accommodate
60    ///   clients that have just started issuing requests, or clients that do
61    ///   not issue many requests per window.
62    /// - The `retry_percent` is the percentage of calls to `deposit` that can
63    ///   be retried. This is in addition to any retries allowed for via
64    ///   `min_per_sec`. Must be between 0 and 1000.
65    ///
66    ///   As an example, if `0.1` is used, then for every 10 calls to `deposit`,
67    ///   1 retry will be allowed. If `2.0` is used, then every `deposit`
68    ///   allows for 2 retries.
69    pub fn new(ttl: Duration, min_per_sec: u32, retry_percent: f32) -> Self {
70        // assertions taken from finagle
71        assert!(ttl >= Duration::from_secs(1));
72        assert!(ttl <= Duration::from_secs(60));
73        assert!(retry_percent >= 0.0);
74        assert!(retry_percent <= 1000.0);
75        assert!(min_per_sec < ::std::i32::MAX as u32);
76
77        let (deposit_amount, withdraw_amount) = if retry_percent == 0.0 {
78            // If there is no percent, then you gain nothing from deposits.
79            // Withdrawals can only be made against the reserve, over time.
80            (0, 1)
81        } else if retry_percent <= 1.0 {
82            (1, (1.0 / retry_percent) as isize)
83        } else {
84            // Support for when retry_percent is between 1.0 and 1000.0,
85            // meaning for every deposit D, D * retry_percent withdrawals
86            // can be made.
87            (1000, (1000.0 / retry_percent) as isize)
88        };
89        let reserve = (min_per_sec as isize)
90            .saturating_mul(ttl.as_secs() as isize) // ttl is between 1 and 60 seconds
91            .saturating_mul(withdraw_amount);
92
93        // AtomicIsize isn't clone, so the slots need to be built in a loop...
94        let windows = 10u32;
95        let mut slots = Vec::with_capacity(windows as usize);
96        for _ in 0..windows {
97            slots.push(AtomicIsize::new(0));
98        }
99
100        TpsBudget {
101            generation: Mutex::new(Generation {
102                index: 0,
103                time: Instant::now(),
104            }),
105            reserve,
106            slots: slots.into_boxed_slice(),
107            window: ttl / windows,
108            writer: AtomicIsize::new(0),
109            deposit_amount,
110            withdraw_amount,
111        }
112    }
113
114    fn expire(&self) {
115        let mut gen = self.generation.lock().expect("generation lock");
116
117        let now = Instant::now();
118        let diff = now.saturating_duration_since(gen.time);
119        if diff < self.window {
120            // not expired yet
121            return;
122        }
123
124        let to_commit = self.writer.swap(0, Ordering::SeqCst);
125        self.slots[gen.index].store(to_commit, Ordering::SeqCst);
126
127        let mut diff = diff;
128        let mut idx = (gen.index + 1) % self.slots.len();
129        while diff > self.window {
130            self.slots[idx].store(0, Ordering::SeqCst);
131            diff -= self.window;
132            idx = (idx + 1) % self.slots.len();
133        }
134
135        gen.index = idx;
136        gen.time = now;
137    }
138
139    fn sum(&self) -> isize {
140        let current = self.writer.load(Ordering::SeqCst);
141        let windowed_sum: isize = self
142            .slots
143            .iter()
144            .map(|slot| slot.load(Ordering::SeqCst))
145            // fold() is used instead of sum() to determine overflow behavior
146            .fold(0, isize::saturating_add);
147
148        current
149            .saturating_add(windowed_sum)
150            .saturating_add(self.reserve)
151    }
152
153    fn put(&self, amt: isize) {
154        self.expire();
155        self.writer.fetch_add(amt, Ordering::SeqCst);
156    }
157
158    fn try_get(&self, amt: isize) -> bool {
159        debug_assert!(amt >= 0);
160
161        self.expire();
162
163        let sum = self.sum();
164        if sum >= amt {
165            self.writer.fetch_add(-amt, Ordering::SeqCst);
166            true
167        } else {
168            false
169        }
170    }
171}
172
173impl Budget for TpsBudget {
174    fn deposit(&self) {
175        self.put(self.deposit_amount)
176    }
177
178    fn withdraw(&self) -> bool {
179        self.try_get(self.withdraw_amount)
180    }
181}
182
183impl Default for TpsBudget {
184    fn default() -> Self {
185        TpsBudget::new(Duration::from_secs(10), 10, 0.2)
186    }
187}
188
189impl fmt::Debug for TpsBudget {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        f.debug_struct("Budget")
192            .field("deposit", &self.deposit_amount)
193            .field("withdraw", &self.withdraw_amount)
194            .field("balance", &self.sum())
195            .finish()
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use crate::retry::budget::Budget;
202
203    use super::*;
204    use tokio::time;
205
206    #[test]
207    fn tps_empty() {
208        let bgt = TpsBudget::new(Duration::from_secs(1), 0, 1.0);
209        assert!(!bgt.withdraw());
210    }
211
212    #[tokio::test]
213    async fn tps_leaky() {
214        time::pause();
215
216        let bgt = TpsBudget::new(Duration::from_secs(1), 0, 1.0);
217        bgt.deposit();
218
219        time::advance(Duration::from_secs(3)).await;
220
221        assert!(!bgt.withdraw());
222    }
223
224    #[tokio::test]
225    async fn tps_slots() {
226        time::pause();
227
228        let bgt = TpsBudget::new(Duration::from_secs(1), 0, 0.5);
229        bgt.deposit();
230        bgt.deposit();
231        time::advance(Duration::from_millis(901)).await;
232        // 900ms later, the deposit should still be valid
233        assert!(bgt.withdraw());
234
235        // blank slate
236        time::advance(Duration::from_millis(2001)).await;
237
238        bgt.deposit();
239        time::advance(Duration::from_millis(301)).await;
240        bgt.deposit();
241        time::advance(Duration::from_millis(801)).await;
242        bgt.deposit();
243
244        // the first deposit is expired, but the 2nd should still be valid,
245        // combining with the 3rd
246        assert!(bgt.withdraw());
247    }
248
249    #[tokio::test]
250    async fn tps_reserve() {
251        let bgt = TpsBudget::new(Duration::from_secs(1), 5, 1.0);
252        assert!(bgt.withdraw());
253        assert!(bgt.withdraw());
254        assert!(bgt.withdraw());
255        assert!(bgt.withdraw());
256        assert!(bgt.withdraw());
257
258        assert!(!bgt.withdraw());
259    }
260}