async_rate_limit/
sliding_window.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::sync::Arc;

use crate::limiters::{ThreadsafeRateLimiter, ThreadsafeVariableRateLimiter};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio::time::Duration;

/// A rate limiter that records calls (optionally with a specified cost) during a sliding window `Duration`.
///
/// [`SlidingWindowRateLimiter`] implements both [`RateLimiter`] and [`VariableCostRateLimiter`], so both
/// [`SlidingWindowRateLimiter::wait_until_ready()`] and [`SlidingWindowRateLimiter::wait_with_cost()`] can be used (even together). For instance, `limiter.wait_until_ready().await`
///  and `limiter.wait_with_cost(1).await` would have the same effect.
///
/// # Example: Simple Rate Limiter
///
/// A method that calls an external API with a rate limit should not be called more than three times per second.
/// ```
/// use tokio::time::{Instant, Duration};
/// use async_rate_limit::limiters::RateLimiter;
/// use async_rate_limit::sliding_window::SlidingWindowRateLimiter;
///
/// #[tokio::main]
/// async fn main() -> () {
///     let mut limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 3);
///     
///     for _ in 0..4 {
///         // the 4th call will take place ~1 second after the first call
///         limited_method(&mut limiter).await;
///     }
/// }
///
/// // note the use of the `RateLimiter` trait, rather than the direct type
/// async fn limited_method<T>(limiter: &mut T) where T: RateLimiter {
///     limiter.wait_until_ready().await;
///     println!("{:?}", Instant::now());
/// }
/// ```
///
#[derive(Clone, Debug)]
pub struct SlidingWindowRateLimiter {
    /// Length of the window, i.e. a permit acquired at T is released at T + window
    window: Duration,
    /// Number of calls (or cost thereof) allowed during a given sliding window
    permits: Arc<Semaphore>,
}

impl SlidingWindowRateLimiter {
    /// Creates a new `SlidingWindowRateLimiter` that allows `limit` calls during any `window` Duration.
    pub fn new(window: Duration, limit: usize) -> Self {
        let permits = Arc::new(Semaphore::new(limit));

        SlidingWindowRateLimiter { window, permits }
    }

    /// Creates a new `SlidingWindowRateLimiter` with an externally provided `Arc<Semaphore>` for permits.
    /// # Example: A Shared Variable Cost Rate Limiter
    ///
    /// ```
    /// use std::sync::Arc;
    /// use tokio::sync::Semaphore;
    /// use async_rate_limit::limiters::VariableCostRateLimiter;
    /// use async_rate_limit::sliding_window::SlidingWindowRateLimiter;
    /// use tokio::time::{Instant, Duration};
    ///
    /// #[tokio::main]
    /// async fn main() -> () {
    ///     let permits = Arc::new(Semaphore::new(5));
    ///     let mut limiter1 =
    ///     SlidingWindowRateLimiter::new_with_permits(Duration::from_secs(2), permits.clone());
    ///     let mut limiter2 =
    ///     SlidingWindowRateLimiter::new_with_permits(Duration::from_secs(2), permits.clone());
    ///
    ///     // Note: the above is semantically equivalent to creating `limiter1` with
    ///     //  `SlidingWindowRateLimiter::new`, then cloning it.
    ///
    ///     limiter1.wait_with_cost(3).await;
    ///     // the second call will wait 2s, since the first call consumed 3/5 shared permits
    ///     limiter2.wait_with_cost(3).await;
    /// }
    /// ```
    pub fn new_with_permits(window: Duration, permits: Arc<Semaphore>) -> Self {
        SlidingWindowRateLimiter { window, permits }
    }

    async fn drop_permit_after_window(window: Duration, permit: OwnedSemaphorePermit) {
        tokio::time::sleep(window).await;
        drop(permit);
    }
}

impl ThreadsafeRateLimiter for SlidingWindowRateLimiter {
    /// Wait with an implied cost of 1, see the [initial example](#example-simple-rate-limiter)
    async fn wait_until_ready(&self) {
        let permit = self
            .permits
            .clone()
            .acquire_owned()
            .await
            .expect("Failed to acquire permit for call");

        tokio::spawn(Self::drop_permit_after_window(self.window, permit));
    }
}

impl ThreadsafeVariableRateLimiter for SlidingWindowRateLimiter {
    /// Wait with some variable cost per usage.
    ///
    /// # Example: A Shared Variable Cost Rate Limiter
    ///
    /// An API specifies that you may make 5 "calls" per second, but some endpoints cost more than one call.
    /// - `/lite` costs 1 unit per call
    /// - `/heavy` costs 3 units per call
    /// ```
    /// use tokio::time::{Instant, Duration};
    /// use async_rate_limit::limiters::VariableCostRateLimiter;
    /// use async_rate_limit::sliding_window::SlidingWindowRateLimiter;
    ///
    /// #[tokio::main]
    /// async fn main() -> () {
    ///     let mut limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 5);
    ///     
    ///     for _ in 0..3 {
    ///         // these will proceed immediately, spending 3 units
    ///         get_lite(&mut limiter).await;
    ///     }
    ///
    ///     // 3/5 units are spent, so this will wait for ~1s to proceed since it costs another 3
    ///     get_heavy(&mut limiter).await;
    /// }
    ///
    /// // note the use of the `VariableCostRateLimiter` trait, rather than the direct type
    /// async fn get_lite<T>(limiter: &mut T) where T: VariableCostRateLimiter {
    ///     limiter.wait_with_cost(1).await;
    ///     println!("Lite: {:?}", Instant::now());
    /// }
    ///
    /// async fn get_heavy<T>(limiter: &mut T) where T: VariableCostRateLimiter {
    ///     limiter.wait_with_cost(3).await;
    ///     println!("Heavy: {:?}", Instant::now());
    /// }
    /// ```
    async fn wait_with_cost(&self, cost: usize) {
        let permits = self
            .permits
            .clone()
            .acquire_many_owned(cost as u32)
            .await
            .unwrap_or_else(|_| panic!("Failed to acquire {} permits for call", cost));

        tokio::spawn(Self::drop_permit_after_window(self.window, permits));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::time::{pause, Instant};

    mod rate_limiter_tests {
        use super::*;
        use crate::limiters::{RateLimiter, ThreadsafeRateLimiter};

        #[tokio::test]
        async fn test_proceeds_immediately_below_limit() {
            let limiter = SlidingWindowRateLimiter::new(Duration::from_secs(3), 7);

            let start = Instant::now();

            for _ in 0..7 {
                limiter.wait_until_ready().await;
            }

            let end = Instant::now();

            let duration = end - start;

            assert!(duration > Duration::from_secs(0));
            assert!(duration < Duration::from_millis(100));
        }

        #[tokio::test]
        async fn test_waits_at_limit() {
            pause();

            let limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 3);

            let start = Instant::now();

            for _ in 0..10 {
                limiter.wait_until_ready().await;
            }

            let end = Instant::now();

            let duration = end - start;

            assert!(duration > Duration::from_secs(3));
            assert!(duration < Duration::from_secs(4));
        }

        #[tokio::test]
        async fn test_many_simultaneous_waiters() {
            pause();

            let limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 3);

            let start = Instant::now();

            let mut tasks = vec![];

            for _ in 0..10 {
                let limiter_clone = Arc::new(tokio::sync::Mutex::new(limiter.clone()));

                let task = tokio::spawn(async move {
                    let limiter = limiter_clone.lock().await;

                    (*limiter).wait_until_ready().await;
                });
                tasks.push(task);
            }

            for task in tasks.into_iter() {
                let _ = task.await;
            }

            let end = Instant::now();

            let duration = end - start;

            assert!(duration > Duration::from_secs(3));
            assert!(duration < Duration::from_secs(4));
        }

        #[tokio::test]
        async fn test_trait_threadsafe_bounds() {
            let limiter = SlidingWindowRateLimiter::new(Duration::from_secs(3), 7);

            assert_threadsafe(&limiter).await;
        }

        #[tokio::test]
        async fn test_trait_non_threadsafe_bounds() {
            let mut limiter = SlidingWindowRateLimiter::new(Duration::from_secs(3), 7);

            assert_non_threadsafe(&mut limiter).await;
        }

        async fn assert_threadsafe<T: ThreadsafeRateLimiter>(limiter: &T) {
            let start = Instant::now();

            for _ in 0..7 {
                limiter.wait_until_ready().await;
            }

            let end = Instant::now();

            let duration = end - start;

            assert!(duration > Duration::from_secs(0));
            assert!(duration < Duration::from_millis(100));
        }

        async fn assert_non_threadsafe<T: RateLimiter>(limiter: &mut T) {
            let start = Instant::now();

            for _ in 0..7 {
                limiter.wait_until_ready().await;
            }

            let end = Instant::now();

            let duration = end - start;

            assert!(duration > Duration::from_secs(0));
            assert!(duration < Duration::from_millis(100));
        }
    }

    mod variable_cost_rate_limiter_tests {
        use super::*;
        use crate::limiters::ThreadsafeVariableRateLimiter;

        #[tokio::test]
        async fn test_proceeds_immediately_below_limit() {
            let limiter = SlidingWindowRateLimiter::new(Duration::from_secs(3), 7);

            let start = Instant::now();

            for _ in 0..3 {
                limiter.wait_with_cost(2).await;
            }

            let end = Instant::now();

            let duration = end - start;

            assert!(duration > Duration::from_secs(0));
            assert!(duration < Duration::from_millis(100));
        }

        #[tokio::test]
        async fn test_waits_at_limit() {
            pause();

            let limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 3);

            let start = Instant::now();

            limiter.wait_with_cost(3).await;
            limiter.wait_with_cost(3).await;
            limiter.wait_with_cost(3).await;

            let end = Instant::now();

            let duration = end - start;

            assert!(duration > Duration::from_secs(2));
            assert!(duration < Duration::from_secs(3));
        }

        #[tokio::test]
        async fn test_with_threadsafe_bound() {
            pause();

            let limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 3);

            assert_threadsafe(&limiter).await;
        }

        async fn assert_threadsafe<T>(limiter: &T)
        where
            T: ThreadsafeVariableRateLimiter,
        {
            let start = Instant::now();

            limiter.wait_with_cost(3).await;
            limiter.wait_with_cost(3).await;
            limiter.wait_with_cost(3).await;

            let end = Instant::now();

            let duration = end - start;

            assert!(duration > Duration::from_secs(2));
            assert!(duration < Duration::from_secs(3));
        }

        #[tokio::test]
        async fn test_waiters_with_shared_permits() {
            pause();

            let permits = Arc::new(Semaphore::new(5));
            let limiter1 =
                SlidingWindowRateLimiter::new_with_permits(Duration::from_secs(2), permits.clone());
            let limiter2 =
                SlidingWindowRateLimiter::new_with_permits(Duration::from_secs(2), permits.clone());

            let start = Instant::now();

            limiter1.wait_with_cost(3).await;
            limiter2.wait_with_cost(3).await;

            let end = Instant::now();

            let duration = end - start;

            assert!(duration > Duration::from_secs(2));
            assert!(duration < Duration::from_secs(3));
        }

        #[tokio::test]
        async fn test_many_waiters() {
            pause();

            let limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 3);

            let start = Instant::now();

            let mut tasks = vec![];

            for _ in 0..10 {
                let limiter_clone = Arc::new(tokio::sync::Mutex::new(limiter.clone()));

                let task = tokio::spawn(async move {
                    let limiter = limiter_clone.lock().await;

                    (*limiter).wait_with_cost(3).await;
                });
                tasks.push(task);
            }

            for task in tasks.into_iter() {
                let _ = task.await;
            }

            let end = Instant::now();

            let duration = end - start;

            assert!(duration > Duration::from_secs(9));
            assert!(duration < Duration::from_secs(10));
        }
    }
}