xref: /cloud-hypervisor/rate_limiter/src/lib.rs (revision 9af2968a7dc47b89bf07ea9dc5e735084efcfa3a)
1 // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3 
4 #![deny(missing_docs)]
5 //! # Rate Limiter
6 //!
7 //! Provides a rate limiter written in Rust useful for IO operations that need to
8 //! be throttled.
9 //!
10 //! ## Behavior
11 //!
12 //! The rate limiter starts off as 'unblocked' with two token buckets configured
13 //! with the values passed in the `RateLimiter::new()` constructor.
14 //! All subsequent accounting is done independently for each token bucket based
15 //! on the `TokenType` used. If any of the buckets runs out of budget, the limiter
16 //! goes in the 'blocked' state. At this point an internal timer is set up which
17 //! will later 'wake up' the user in order to retry sending data. The 'wake up'
18 //! notification will be dispatched as an event on the FD provided by the `AsRawFD`
19 //! trait implementation.
20 //!
21 //! The contract is that the user shall also call the `event_handler()` method on
22 //! receipt of such an event.
23 //!
24 //! The token buckets are replenished every time a `consume()` is called, before
25 //! actually trying to consume the requested amount of tokens. The amount of tokens
26 //! replenished is automatically calculated to respect the `complete_refill_time`
27 //! configuration parameter provided by the user. The token buckets will never
28 //! replenish above their respective `size`.
29 //!
30 //! Each token bucket can start off with a `one_time_burst` initial extra capacity
31 //! on top of their `size`. This initial extra credit does not replenish and
32 //! can be used for an initial burst of data.
33 //!
34 //! The granularity for 'wake up' events when the rate limiter is blocked is
35 //! currently hardcoded to `100 milliseconds`.
36 //!
37 //! ## Limitations
38 //!
39 //! This rate limiter implementation relies on the *Linux kernel's timerfd* so its
40 //! usage is limited to Linux systems.
41 //!
42 //! Another particularity of this implementation is that it is not self-driving.
43 //! It is meant to be used in an external event loop and thus implements the `AsRawFd`
44 //! trait and provides an *event-handler* as part of its API. This *event-handler*
45 //! needs to be called by the user on every event on the rate limiter's `AsRawFd` FD.
46 #[macro_use]
47 extern crate log;
48 
49 use std::os::unix::io::{AsRawFd, RawFd};
50 use std::time::{Duration, Instant};
51 use std::{fmt, io};
52 use vmm_sys_util::timerfd::TimerFd;
53 
54 #[derive(Debug)]
55 /// Describes the errors that may occur while handling rate limiter events.
56 pub enum Error {
57     /// The event handler was called spuriously.
58     SpuriousRateLimiterEvent(&'static str),
59     /// The event handler encounters while TimerFd::wait()
60     TimerFdWaitError(std::io::Error),
61 }
62 
63 // Interval at which the refill timer will run when limiter is at capacity.
64 const REFILL_TIMER_INTERVAL_MS: u64 = 100;
65 const TIMER_REFILL_DUR: Duration = Duration::from_millis(REFILL_TIMER_INTERVAL_MS);
66 
67 const NANOSEC_IN_ONE_MILLISEC: u64 = 1_000_000;
68 
69 // Euclid's two-thousand-year-old algorithm for finding the greatest common divisor.
70 fn gcd(x: u64, y: u64) -> u64 {
71     let mut x = x;
72     let mut y = y;
73     while y != 0 {
74         let t = y;
75         y = x % y;
76         x = t;
77     }
78     x
79 }
80 
81 /// Enum describing the outcomes of a `reduce()` call on a `TokenBucket`.
82 #[derive(Clone, Debug, PartialEq)]
83 pub enum BucketReduction {
84     /// There are not enough tokens to complete the operation.
85     Failure,
86     /// A part of the available tokens have been consumed.
87     Success,
88     /// A number of tokens `inner` times larger than the bucket size have been consumed.
89     OverConsumption(f64),
90 }
91 
92 /// TokenBucket provides a lower level interface to rate limiting with a
93 /// configurable capacity, refill-rate and initial burst.
94 #[derive(Clone, Debug, PartialEq)]
95 pub struct TokenBucket {
96     // Bucket defining traits.
97     size: u64,
98     // Initial burst size (number of free initial tokens, that can be consumed at no cost)
99     one_time_burst: u64,
100     // Complete refill time in milliseconds.
101     refill_time: u64,
102 
103     // Internal state descriptors.
104     budget: u64,
105     last_update: Instant,
106 
107     // Fields used for pre-processing optimizations.
108     processed_capacity: u64,
109     processed_refill_time: u64,
110 }
111 
112 impl TokenBucket {
113     /// Creates a `TokenBucket` wrapped in an `Option`.
114     ///
115     /// TokenBucket created is of `size` total capacity and takes `complete_refill_time_ms`
116     /// milliseconds to go from zero tokens to total capacity. The `one_time_burst` is initial
117     /// extra credit on top of total capacity, that does not replenish and which can be used
118     /// for an initial burst of data.
119     ///
120     /// If the `size` or the `complete refill time` are zero, then `None` is returned.
121     pub fn new(size: u64, one_time_burst: u64, complete_refill_time_ms: u64) -> Option<Self> {
122         // If either token bucket capacity or refill time is 0, disable limiting.
123         if size == 0 || complete_refill_time_ms == 0 {
124             return None;
125         }
126         // Formula for computing current refill amount:
127         // refill_token_count = (delta_time * size) / (complete_refill_time_ms * 1_000_000)
128         // In order to avoid overflows, simplify the fractions by computing greatest common divisor.
129 
130         let complete_refill_time_ns = complete_refill_time_ms * NANOSEC_IN_ONE_MILLISEC;
131         // Get the greatest common factor between `size` and `complete_refill_time_ns`.
132         let common_factor = gcd(size, complete_refill_time_ns);
133         // The division will be exact since `common_factor` is a factor of `size`.
134         let processed_capacity: u64 = size / common_factor;
135         // The division will be exact since `common_factor` is a factor of `complete_refill_time_ns`.
136         let processed_refill_time: u64 = complete_refill_time_ns / common_factor;
137 
138         Some(TokenBucket {
139             size,
140             one_time_burst,
141             refill_time: complete_refill_time_ms,
142             // Start off full.
143             budget: size,
144             // Last updated is now.
145             last_update: Instant::now(),
146             processed_capacity,
147             processed_refill_time,
148         })
149     }
150 
151     /// Attempts to consume `tokens` from the bucket and returns whether the action succeeded.
152     // TODO (Issue #259): handle cases where a single request is larger than the full capacity
153     // for such cases we need to support partial fulfilment of requests
154     pub fn reduce(&mut self, mut tokens: u64) -> BucketReduction {
155         // First things first: consume the one-time-burst budget.
156         if self.one_time_burst > 0 {
157             // We still have burst budget for *all* tokens requests.
158             if self.one_time_burst >= tokens {
159                 self.one_time_burst -= tokens;
160                 self.last_update = Instant::now();
161                 // No need to continue to the refill process, we still have burst budget to consume from.
162                 return BucketReduction::Success;
163             } else {
164                 // We still have burst budget for *some* of the tokens requests.
165                 // The tokens left unfulfilled will be consumed from current `self.budget`.
166                 tokens -= self.one_time_burst;
167                 self.one_time_burst = 0;
168             }
169         }
170 
171         // Compute time passed since last refill/update.
172         let time_delta = self.last_update.elapsed().as_nanos() as u64;
173         self.last_update = Instant::now();
174 
175         // At each 'time_delta' nanoseconds the bucket should refill with:
176         // refill_amount = (time_delta * size) / (complete_refill_time_ms * 1_000_000)
177         // `processed_capacity` and `processed_refill_time` are the result of simplifying above
178         // fraction formula with their greatest-common-factor.
179         self.budget += (time_delta * self.processed_capacity) / self.processed_refill_time;
180 
181         if self.budget >= self.size {
182             self.budget = self.size;
183         }
184 
185         if tokens > self.budget {
186             // This operation requests a bandwidth higher than the bucket size
187             if tokens > self.size {
188                 error!(
189                     "Consumed {} tokens from bucket of size {}",
190                     tokens, self.size
191                 );
192                 // Empty the bucket and report an overconsumption of
193                 // (remaining tokens / size) times larger than the bucket size
194                 tokens -= self.budget;
195                 self.budget = 0;
196                 return BucketReduction::OverConsumption(tokens as f64 / self.size as f64);
197             }
198             // If not enough tokens consume() fails, return false.
199             return BucketReduction::Failure;
200         }
201 
202         self.budget -= tokens;
203         BucketReduction::Success
204     }
205 
206     /// "Manually" adds tokens to bucket.
207     pub fn replenish(&mut self, tokens: u64) {
208         // This means we are still during the burst interval.
209         // Of course there is a very small chance  that the last reduce() also used up burst
210         // budget which should now be replenished, but for performance and code-complexity
211         // reasons we're just gonna let that slide since it's practically inconsequential.
212         if self.one_time_burst > 0 {
213             self.one_time_burst += tokens;
214             return;
215         }
216         self.budget = std::cmp::min(self.budget + tokens, self.size);
217     }
218 
219     /// Returns the capacity of the token bucket.
220     pub fn capacity(&self) -> u64 {
221         self.size
222     }
223 
224     /// Returns the remaining one time burst budget.
225     pub fn one_time_burst(&self) -> u64 {
226         self.one_time_burst
227     }
228 
229     /// Returns the time in milliseconds required to to completely fill the bucket.
230     pub fn refill_time_ms(&self) -> u64 {
231         self.refill_time
232     }
233 
234     /// Returns the current budget (one time burst allowance notwithstanding).
235     pub fn budget(&self) -> u64 {
236         self.budget
237     }
238 }
239 
240 /// Enum that describes the type of token used.
241 pub enum TokenType {
242     /// Token type used for bandwidth limiting.
243     Bytes,
244     /// Token type used for operations/second limiting.
245     Ops,
246 }
247 
248 /// Enum that describes the type of token bucket update.
249 pub enum BucketUpdate {
250     /// No Update - same as before.
251     None,
252     /// Rate Limiting is disabled on this bucket.
253     Disabled,
254     /// Rate Limiting enabled with updated bucket.
255     Update(TokenBucket),
256 }
257 
258 /// Rate Limiter that works on both bandwidth and ops/s limiting.
259 ///
260 /// Bandwidth (bytes/s) and ops/s limiting can be used at the same time or individually.
261 ///
262 /// Implementation uses a single timer through TimerFd to refresh either or
263 /// both token buckets.
264 ///
265 /// Its internal buckets are 'passively' replenished as they're being used (as
266 /// part of `consume()` operations).
267 /// A timer is enabled and used to 'actively' replenish the token buckets when
268 /// limiting is in effect and `consume()` operations are disabled.
269 ///
270 /// RateLimiters will generate events on the FDs provided by their `AsRawFd` trait
271 /// implementation. These events are meant to be consumed by the user of this struct.
272 /// On each such event, the user must call the `event_handler()` method.
273 pub struct RateLimiter {
274     bandwidth: Option<TokenBucket>,
275     ops: Option<TokenBucket>,
276 
277     timer_fd: TimerFd,
278     // Internal flag that quickly determines timer state.
279     timer_active: bool,
280 }
281 
282 impl PartialEq for RateLimiter {
283     fn eq(&self, other: &RateLimiter) -> bool {
284         self.bandwidth == other.bandwidth && self.ops == other.ops
285     }
286 }
287 
288 impl fmt::Debug for RateLimiter {
289     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
290         write!(
291             f,
292             "RateLimiter {{ bandwidth: {:?}, ops: {:?} }}",
293             self.bandwidth, self.ops
294         )
295     }
296 }
297 
298 impl RateLimiter {
299     /// Creates a new Rate Limiter that can limit on both bytes/s and ops/s.
300     ///
301     /// # Arguments
302     ///
303     /// * `bytes_total_capacity` - the total capacity of the `TokenType::Bytes` token bucket.
304     /// * `bytes_one_time_burst` - initial extra credit on top of `bytes_total_capacity`,
305     /// that does not replenish and which can be used for an initial burst of data.
306     /// * `bytes_complete_refill_time_ms` - number of milliseconds for the `TokenType::Bytes`
307     /// token bucket to go from zero Bytes to `bytes_total_capacity` Bytes.
308     /// * `ops_total_capacity` - the total capacity of the `TokenType::Ops` token bucket.
309     /// * `ops_one_time_burst` - initial extra credit on top of `ops_total_capacity`,
310     /// that does not replenish and which can be used for an initial burst of data.
311     /// * `ops_complete_refill_time_ms` - number of milliseconds for the `TokenType::Ops` token
312     /// bucket to go from zero Ops to `ops_total_capacity` Ops.
313     ///
314     /// If either bytes/ops *size* or *refill_time* are **zero**, the limiter
315     /// is **disabled** for that respective token type.
316     ///
317     /// # Errors
318     ///
319     /// If the timerfd creation fails, an error is returned.
320     pub fn new(
321         bytes_total_capacity: u64,
322         bytes_one_time_burst: u64,
323         bytes_complete_refill_time_ms: u64,
324         ops_total_capacity: u64,
325         ops_one_time_burst: u64,
326         ops_complete_refill_time_ms: u64,
327     ) -> io::Result<Self> {
328         let bytes_token_bucket = TokenBucket::new(
329             bytes_total_capacity,
330             bytes_one_time_burst,
331             bytes_complete_refill_time_ms,
332         );
333 
334         let ops_token_bucket = TokenBucket::new(
335             ops_total_capacity,
336             ops_one_time_burst,
337             ops_complete_refill_time_ms,
338         );
339 
340         // We'll need a timer_fd, even if our current config effectively disables rate limiting,
341         // because `Self::update_buckets()` might re-enable it later, and we might be
342         // seccomp-blocked from creating the timer_fd at that time.
343         let timer_fd = TimerFd::new()?;
344         // Note: vmm_sys_util::TimerFd::new() open the fd w/o O_NONBLOCK. We manually add this flag
345         // so that `Self::event_handler` won't be blocked with `vmm_sys_util::TimerFd::wait()`.
346         let ret = unsafe {
347             let fd = timer_fd.as_raw_fd();
348             let mut flags = libc::fcntl(fd, libc::F_GETFL);
349             flags |= libc::O_NONBLOCK;
350             libc::fcntl(fd, libc::F_SETFL, flags)
351         };
352         if ret < 0 {
353             return Err(std::io::Error::last_os_error());
354         }
355 
356         Ok(RateLimiter {
357             bandwidth: bytes_token_bucket,
358             ops: ops_token_bucket,
359             timer_fd,
360             timer_active: false,
361         })
362     }
363 
364     // Arm the timer of the rate limiter with the provided `Duration` (which will fire only once).
365     fn activate_timer(&mut self, dur: Duration) {
366         // Panic when failing to arm the timer (same handling in crate TimerFd::set_state())
367         self.timer_fd
368             .reset(dur, None)
369             .expect("Can't arm the timer (unexpected 'timerfd_settime' failure).");
370         self.timer_active = true;
371     }
372 
373     /// Attempts to consume tokens and returns whether that is possible.
374     ///
375     /// If rate limiting is disabled on provided `token_type`, this function will always succeed.
376     pub fn consume(&mut self, tokens: u64, token_type: TokenType) -> bool {
377         // If the timer is active, we can't consume tokens from any bucket and the function fails.
378         if self.timer_active {
379             return false;
380         }
381 
382         // Identify the required token bucket.
383         let token_bucket = match token_type {
384             TokenType::Bytes => self.bandwidth.as_mut(),
385             TokenType::Ops => self.ops.as_mut(),
386         };
387         // Try to consume from the token bucket.
388         if let Some(bucket) = token_bucket {
389             let refill_time = bucket.refill_time_ms();
390             match bucket.reduce(tokens) {
391                 // When we report budget is over, there will be no further calls here,
392                 // register a timer to replenish the bucket and resume processing;
393                 // make sure there is only one running timer for this limiter.
394                 BucketReduction::Failure => {
395                     if !self.timer_active {
396                         self.activate_timer(TIMER_REFILL_DUR);
397                     }
398                     false
399                 }
400                 // The operation succeeded and further calls can be made.
401                 BucketReduction::Success => true,
402                 // The operation succeeded as the tokens have been consumed
403                 // but the timer still needs to be armed.
404                 BucketReduction::OverConsumption(ratio) => {
405                     // The operation "borrowed" a number of tokens `ratio` times
406                     // greater than the size of the bucket, and since it takes
407                     // `refill_time` milliseconds to fill an empty bucket, in
408                     // order to enforce the bandwidth limit we need to prevent
409                     // further calls to the rate limiter for
410                     // `ratio * refill_time` milliseconds.
411                     self.activate_timer(Duration::from_millis((ratio * refill_time as f64) as u64));
412                     true
413                 }
414             }
415         } else {
416             // If bucket is not present rate limiting is disabled on token type,
417             // consume() will always succeed.
418             true
419         }
420     }
421 
422     /// Adds tokens of `token_type` to their respective bucket.
423     ///
424     /// Can be used to *manually* add tokens to a bucket. Useful for reverting a
425     /// `consume()` if needed.
426     pub fn manual_replenish(&mut self, tokens: u64, token_type: TokenType) {
427         // Identify the required token bucket.
428         let token_bucket = match token_type {
429             TokenType::Bytes => self.bandwidth.as_mut(),
430             TokenType::Ops => self.ops.as_mut(),
431         };
432         // Add tokens to the token bucket.
433         if let Some(bucket) = token_bucket {
434             bucket.replenish(tokens);
435         }
436     }
437 
438     /// Returns whether this rate limiter is blocked.
439     ///
440     /// The limiter 'blocks' when a `consume()` operation fails because there was not enough
441     /// budget for it.
442     /// An event will be generated on the exported FD when the limiter 'unblocks'.
443     pub fn is_blocked(&self) -> bool {
444         self.timer_active
445     }
446 
447     /// This function needs to be called every time there is an event on the
448     /// FD provided by this object's `AsRawFd` trait implementation.
449     ///
450     /// # Errors
451     ///
452     /// If the rate limiter is disabled or is not blocked, an error is returned.
453     pub fn event_handler(&mut self) -> Result<(), Error> {
454         loop {
455             // Note: As we manually added the `O_NONBLOCK` flag to the FD, the following
456             // `timer_fd::wait()` won't block (which is different from its default behavior.)
457             match self.timer_fd.wait() {
458                 Err(e) => {
459                     let err: std::io::Error = e.into();
460                     match err.kind() {
461                         std::io::ErrorKind::Interrupted => (),
462                         std::io::ErrorKind::WouldBlock => {
463                             return Err(Error::SpuriousRateLimiterEvent(
464                                 "Rate limiter event handler called without a present timer",
465                             ))
466                         }
467                         _ => return Err(Error::TimerFdWaitError(err)),
468                     }
469                 }
470                 _ => {
471                     self.timer_active = false;
472                     return Ok(());
473                 }
474             }
475         }
476     }
477 
478     /// Updates the parameters of the token buckets associated with this RateLimiter.
479     // TODO: Please note that, right now, the buckets become full after being updated.
480     pub fn update_buckets(&mut self, bytes: BucketUpdate, ops: BucketUpdate) {
481         match bytes {
482             BucketUpdate::Disabled => self.bandwidth = None,
483             BucketUpdate::Update(tb) => self.bandwidth = Some(tb),
484             BucketUpdate::None => (),
485         };
486         match ops {
487             BucketUpdate::Disabled => self.ops = None,
488             BucketUpdate::Update(tb) => self.ops = Some(tb),
489             BucketUpdate::None => (),
490         };
491     }
492 
493     /// Returns an immutable view of the inner bandwidth token bucket.
494     pub fn bandwidth(&self) -> Option<&TokenBucket> {
495         self.bandwidth.as_ref()
496     }
497 
498     /// Returns an immutable view of the inner ops token bucket.
499     pub fn ops(&self) -> Option<&TokenBucket> {
500         self.ops.as_ref()
501     }
502 }
503 
504 impl AsRawFd for RateLimiter {
505     /// Provides a FD which needs to be monitored for POLLIN events.
506     ///
507     /// This object's `event_handler()` method must be called on such events.
508     ///
509     /// Will return a negative value if rate limiting is disabled on both
510     /// token types.
511     fn as_raw_fd(&self) -> RawFd {
512         self.timer_fd.as_raw_fd()
513     }
514 }
515 
516 impl Default for RateLimiter {
517     /// Default RateLimiter is a no-op limiter with infinite budget.
518     fn default() -> Self {
519         // Safe to unwrap since this will not attempt to create timer_fd.
520         RateLimiter::new(0, 0, 0, 0, 0, 0).expect("Failed to build default RateLimiter")
521     }
522 }
523 
524 #[cfg(test)]
525 pub(crate) mod tests {
526     use super::*;
527     use std::thread;
528     use std::time::Duration;
529 
530     impl TokenBucket {
531         // Resets the token bucket: budget set to max capacity and last-updated set to now.
532         fn reset(&mut self) {
533             self.budget = self.size;
534             self.last_update = Instant::now();
535         }
536 
537         fn get_last_update(&self) -> &Instant {
538             &self.last_update
539         }
540 
541         fn get_processed_capacity(&self) -> u64 {
542             self.processed_capacity
543         }
544 
545         fn get_processed_refill_time(&self) -> u64 {
546             self.processed_refill_time
547         }
548 
549         // After a restore, we cannot be certain that the last_update field has the same value.
550         pub fn partial_eq(&self, other: &TokenBucket) -> bool {
551             (other.capacity() == self.capacity())
552                 && (other.one_time_burst() == self.one_time_burst())
553                 && (other.refill_time_ms() == self.refill_time_ms())
554                 && (other.budget() == self.budget())
555         }
556     }
557 
558     impl RateLimiter {
559         fn get_token_bucket(&self, token_type: TokenType) -> Option<&TokenBucket> {
560             match token_type {
561                 TokenType::Bytes => self.bandwidth.as_ref(),
562                 TokenType::Ops => self.ops.as_ref(),
563             }
564         }
565     }
566 
567     #[test]
568     fn test_token_bucket_create() {
569         let before = Instant::now();
570         let tb = TokenBucket::new(1000, 0, 1000).unwrap();
571         assert_eq!(tb.capacity(), 1000);
572         assert_eq!(tb.budget(), 1000);
573         assert!(*tb.get_last_update() >= before);
574         let after = Instant::now();
575         assert!(*tb.get_last_update() <= after);
576         assert_eq!(tb.get_processed_capacity(), 1);
577         assert_eq!(tb.get_processed_refill_time(), 1_000_000);
578 
579         // Verify invalid bucket configurations result in `None`.
580         assert!(TokenBucket::new(0, 1234, 1000).is_none());
581         assert!(TokenBucket::new(100, 1234, 0).is_none());
582         assert!(TokenBucket::new(0, 1234, 0).is_none());
583     }
584 
585     #[test]
586     fn test_token_bucket_preprocess() {
587         let tb = TokenBucket::new(1000, 0, 1000).unwrap();
588         assert_eq!(tb.get_processed_capacity(), 1);
589         assert_eq!(tb.get_processed_refill_time(), NANOSEC_IN_ONE_MILLISEC);
590 
591         let thousand = 1000;
592         let tb = TokenBucket::new(3 * 7 * 11 * 19 * thousand, 0, 7 * 11 * 13 * 17).unwrap();
593         assert_eq!(tb.get_processed_capacity(), 3 * 19);
594         assert_eq!(
595             tb.get_processed_refill_time(),
596             13 * 17 * (NANOSEC_IN_ONE_MILLISEC / thousand)
597         );
598     }
599 
600     #[test]
601     fn test_token_bucket_reduce() {
602         // token bucket with capacity 1000 and refill time of 1000 milliseconds
603         // allowing rate of 1 token/ms.
604         let capacity = 1000;
605         let refill_ms = 1000;
606         let mut tb = TokenBucket::new(capacity, 0, refill_ms as u64).unwrap();
607 
608         assert_eq!(tb.reduce(123), BucketReduction::Success);
609         assert_eq!(tb.budget(), capacity - 123);
610 
611         thread::sleep(Duration::from_millis(123));
612         assert_eq!(tb.reduce(1), BucketReduction::Success);
613         assert_eq!(tb.budget(), capacity - 1);
614         assert_eq!(tb.reduce(100), BucketReduction::Success);
615         assert_eq!(tb.reduce(capacity), BucketReduction::Failure);
616 
617         // token bucket with capacity 1000 and refill time of 1000 milliseconds
618         let mut tb = TokenBucket::new(1000, 1100, 1000).unwrap();
619         // safely assuming the thread can run these 3 commands in less than 500ms
620         assert_eq!(tb.reduce(1000), BucketReduction::Success);
621         assert_eq!(tb.one_time_burst(), 100);
622         assert_eq!(tb.reduce(500), BucketReduction::Success);
623         assert_eq!(tb.one_time_burst(), 0);
624         assert_eq!(tb.reduce(500), BucketReduction::Success);
625         assert_eq!(tb.reduce(500), BucketReduction::Failure);
626         thread::sleep(Duration::from_millis(500));
627         assert_eq!(tb.reduce(500), BucketReduction::Success);
628         thread::sleep(Duration::from_millis(1000));
629         assert_eq!(tb.reduce(2500), BucketReduction::OverConsumption(1.5));
630 
631         let before = Instant::now();
632         tb.reset();
633         assert_eq!(tb.capacity(), 1000);
634         assert_eq!(tb.budget(), 1000);
635         assert!(*tb.get_last_update() >= before);
636         let after = Instant::now();
637         assert!(*tb.get_last_update() <= after);
638     }
639 
640     #[test]
641     fn test_rate_limiter_default() {
642         let mut l = RateLimiter::default();
643 
644         // limiter should not be blocked
645         assert!(!l.is_blocked());
646         // limiter should be disabled so consume(whatever) should work
647         assert!(l.consume(u64::max_value(), TokenType::Ops));
648         assert!(l.consume(u64::max_value(), TokenType::Bytes));
649         // calling the handler without there having been an event should error
650         assert!(l.event_handler().is_err());
651         assert_eq!(
652             format!("{:?}", l.event_handler().err().unwrap()),
653             "SpuriousRateLimiterEvent(\
654              \"Rate limiter event handler called without a present timer\")"
655         );
656     }
657 
658     #[test]
659     fn test_rate_limiter_new() {
660         let l = RateLimiter::new(1000, 1001, 1002, 1003, 1004, 1005).unwrap();
661 
662         let bw = l.bandwidth.unwrap();
663         assert_eq!(bw.capacity(), 1000);
664         assert_eq!(bw.one_time_burst(), 1001);
665         assert_eq!(bw.refill_time_ms(), 1002);
666         assert_eq!(bw.budget(), 1000);
667 
668         let ops = l.ops.unwrap();
669         assert_eq!(ops.capacity(), 1003);
670         assert_eq!(ops.one_time_burst(), 1004);
671         assert_eq!(ops.refill_time_ms(), 1005);
672         assert_eq!(ops.budget(), 1003);
673     }
674 
675     #[test]
676     fn test_rate_limiter_manual_replenish() {
677         // rate limiter with limit of 1000 bytes/s and 1000 ops/s
678         let mut l = RateLimiter::new(1000, 0, 1000, 1000, 0, 1000).unwrap();
679 
680         // consume 123 bytes
681         assert!(l.consume(123, TokenType::Bytes));
682         l.manual_replenish(23, TokenType::Bytes);
683         {
684             let bytes_tb = l.get_token_bucket(TokenType::Bytes).unwrap();
685             assert_eq!(bytes_tb.budget(), 900);
686         }
687         // consume 123 ops
688         assert!(l.consume(123, TokenType::Ops));
689         l.manual_replenish(23, TokenType::Ops);
690         {
691             let bytes_tb = l.get_token_bucket(TokenType::Ops).unwrap();
692             assert_eq!(bytes_tb.budget(), 900);
693         }
694     }
695 
696     #[test]
697     fn test_rate_limiter_bandwidth() {
698         // rate limiter with limit of 1000 bytes/s
699         let mut l = RateLimiter::new(1000, 0, 1000, 0, 0, 0).unwrap();
700 
701         // limiter should not be blocked
702         assert!(!l.is_blocked());
703         // raw FD for this disabled should be valid
704         assert!(l.as_raw_fd() > 0);
705 
706         // ops/s limiter should be disabled so consume(whatever) should work
707         assert!(l.consume(u64::max_value(), TokenType::Ops));
708 
709         // do full 1000 bytes
710         assert!(l.consume(1000, TokenType::Bytes));
711         // try and fail on another 100
712         assert!(!l.consume(100, TokenType::Bytes));
713         // since consume failed, limiter should be blocked now
714         assert!(l.is_blocked());
715         // wait half the timer period
716         thread::sleep(Duration::from_millis(REFILL_TIMER_INTERVAL_MS / 2));
717         // limiter should still be blocked
718         assert!(l.is_blocked());
719         // wait the other half of the timer period
720         thread::sleep(Duration::from_millis(REFILL_TIMER_INTERVAL_MS / 2));
721         // the timer_fd should have an event on it by now
722         assert!(l.event_handler().is_ok());
723         // limiter should now be unblocked
724         assert!(!l.is_blocked());
725         // try and succeed on another 100 bytes this time
726         assert!(l.consume(100, TokenType::Bytes));
727     }
728 
729     #[test]
730     fn test_rate_limiter_ops() {
731         // rate limiter with limit of 1000 ops/s
732         let mut l = RateLimiter::new(0, 0, 0, 1000, 0, 1000).unwrap();
733 
734         // limiter should not be blocked
735         assert!(!l.is_blocked());
736         // raw FD for this disabled should be valid
737         assert!(l.as_raw_fd() > 0);
738 
739         // bytes/s limiter should be disabled so consume(whatever) should work
740         assert!(l.consume(u64::max_value(), TokenType::Bytes));
741 
742         // do full 1000 ops
743         assert!(l.consume(1000, TokenType::Ops));
744         // try and fail on another 100
745         assert!(!l.consume(100, TokenType::Ops));
746         // since consume failed, limiter should be blocked now
747         assert!(l.is_blocked());
748         // wait half the timer period
749         thread::sleep(Duration::from_millis(REFILL_TIMER_INTERVAL_MS / 2));
750         // limiter should still be blocked
751         assert!(l.is_blocked());
752         // wait the other half of the timer period
753         thread::sleep(Duration::from_millis(REFILL_TIMER_INTERVAL_MS / 2));
754         // the timer_fd should have an event on it by now
755         assert!(l.event_handler().is_ok());
756         // limiter should now be unblocked
757         assert!(!l.is_blocked());
758         // try and succeed on another 100 ops this time
759         assert!(l.consume(100, TokenType::Ops));
760     }
761 
762     #[test]
763     fn test_rate_limiter_full() {
764         // rate limiter with limit of 1000 bytes/s and 1000 ops/s
765         let mut l = RateLimiter::new(1000, 0, 1000, 1000, 0, 1000).unwrap();
766 
767         // limiter should not be blocked
768         assert!(!l.is_blocked());
769         // raw FD for this disabled should be valid
770         assert!(l.as_raw_fd() > 0);
771 
772         // do full 1000 bytes
773         assert!(l.consume(1000, TokenType::Ops));
774         // do full 1000 bytes
775         assert!(l.consume(1000, TokenType::Bytes));
776         // try and fail on another 100 ops
777         assert!(!l.consume(100, TokenType::Ops));
778         // try and fail on another 100 bytes
779         assert!(!l.consume(100, TokenType::Bytes));
780         // since consume failed, limiter should be blocked now
781         assert!(l.is_blocked());
782         // wait half the timer period
783         thread::sleep(Duration::from_millis(REFILL_TIMER_INTERVAL_MS / 2));
784         // limiter should still be blocked
785         assert!(l.is_blocked());
786         // wait the other half of the timer period
787         thread::sleep(Duration::from_millis(REFILL_TIMER_INTERVAL_MS / 2));
788         // the timer_fd should have an event on it by now
789         assert!(l.event_handler().is_ok());
790         // limiter should now be unblocked
791         assert!(!l.is_blocked());
792         // try and succeed on another 100 ops this time
793         assert!(l.consume(100, TokenType::Ops));
794         // try and succeed on another 100 bytes this time
795         assert!(l.consume(100, TokenType::Bytes));
796     }
797 
798     #[test]
799     fn test_rate_limiter_overconsumption() {
800         // initialize the rate limiter
801         let mut l = RateLimiter::new(1000, 0, 1000, 1000, 0, 1000).unwrap();
802         // try to consume 2.5x the bucket size
803         // we are "borrowing" 1.5x the bucket size in tokens since
804         // the bucket is full
805         assert!(l.consume(2500, TokenType::Bytes));
806 
807         // check that even after a whole second passes, the rate limiter
808         // is still blocked
809         thread::sleep(Duration::from_millis(1000));
810         assert!(l.event_handler().is_err());
811         assert!(l.is_blocked());
812 
813         // after 1.5x the replenish time has passed, the rate limiter
814         // is available again
815         thread::sleep(Duration::from_millis(500));
816         assert!(l.event_handler().is_ok());
817         assert!(!l.is_blocked());
818 
819         // reset the rate limiter
820         let mut l = RateLimiter::new(1000, 0, 1000, 1000, 0, 1000).unwrap();
821         // try to consume 1.5x the bucket size
822         // we are "borrowing" 1.5x the bucket size in tokens since
823         // the bucket is full, should arm the timer to 0.5x replenish
824         // time, which is 500 ms
825         assert!(l.consume(1500, TokenType::Bytes));
826 
827         // check that after more than the minimum refill time,
828         // the rate limiter is still blocked
829         thread::sleep(Duration::from_millis(200));
830         assert!(l.event_handler().is_err());
831         assert!(l.is_blocked());
832 
833         // try to consume some tokens, which should fail as the timer
834         // is still active
835         assert!(!l.consume(100, TokenType::Bytes));
836         assert!(l.event_handler().is_err());
837         assert!(l.is_blocked());
838 
839         // check that after the minimum refill time, the timer was not
840         // overwritten and the rate limiter is still blocked from the
841         // borrowing we performed earlier
842         thread::sleep(Duration::from_millis(100));
843         assert!(l.event_handler().is_err());
844         assert!(l.is_blocked());
845         assert!(!l.consume(100, TokenType::Bytes));
846 
847         // after waiting out the full duration, rate limiter should be
848         // availale again
849         thread::sleep(Duration::from_millis(200));
850         assert!(l.event_handler().is_ok());
851         assert!(!l.is_blocked());
852         assert!(l.consume(100, TokenType::Bytes));
853     }
854 
855     #[test]
856     fn test_update_buckets() {
857         let mut x = RateLimiter::new(1000, 2000, 1000, 10, 20, 1000).unwrap();
858 
859         let initial_bw = x.bandwidth.clone();
860         let initial_ops = x.ops.clone();
861 
862         x.update_buckets(BucketUpdate::None, BucketUpdate::None);
863         assert_eq!(x.bandwidth, initial_bw);
864         assert_eq!(x.ops, initial_ops);
865 
866         let new_bw = TokenBucket::new(123, 0, 57).unwrap();
867         let new_ops = TokenBucket::new(321, 12346, 89).unwrap();
868         x.update_buckets(
869             BucketUpdate::Update(new_bw.clone()),
870             BucketUpdate::Update(new_ops.clone()),
871         );
872 
873         // We have manually adjust the last_update field, because it changes when update_buckets()
874         // constructs new buckets (and thus gets a different value for last_update). We do this so
875         // it makes sense to test the following assertions.
876         x.bandwidth.as_mut().unwrap().last_update = new_bw.last_update;
877         x.ops.as_mut().unwrap().last_update = new_ops.last_update;
878 
879         assert_eq!(x.bandwidth, Some(new_bw));
880         assert_eq!(x.ops, Some(new_ops));
881 
882         x.update_buckets(BucketUpdate::Disabled, BucketUpdate::Disabled);
883         assert_eq!(x.bandwidth, None);
884         assert_eq!(x.ops, None);
885     }
886 
887     #[test]
888     fn test_rate_limiter_debug() {
889         let l = RateLimiter::new(1, 2, 3, 4, 5, 6).unwrap();
890         assert_eq!(
891             format!("{:?}", l),
892             format!(
893                 "RateLimiter {{ bandwidth: {:?}, ops: {:?} }}",
894                 l.bandwidth(),
895                 l.ops()
896             ),
897         );
898     }
899 }
900