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
//! A simple throttle, used for slowing down repeated code. Use this to avoid //! drowning out downstream systems. For example, if I were reading the contents //! of a file repeatedly (polling for data, perhaps), or calling an external //! network resource, I could use a `Throttle` to slow that down to avoid //! resource contention or browning out a downstream service. //! //! This ranges in utility from a simple TPS throttle, "never go faster than *x* //! transactions per second," //! //! ```rust //! # extern crate mysteriouspants_throttle; //! # use std::time::Instant; //! # use mysteriouspants_throttle::Throttle; //! # fn main() { //! // create a new Throttle that rate limits to 10 TPS //! let throttle = Throttle::new_tps_throttle(10.0); //! //! let iteration_start = Instant::now(); //! //! // iterate eleven times, which at 10 TPS should take just over 1 second //! for _i in 0..11 { //! throttle.acquire(()); //! // do the needful //! } //! //! // prove that it did, in fact, take 1 second //! assert_eq!(iteration_start.elapsed().as_secs() == 1, true); //! # } //! ``` //! //! To more complicated variable-rate throttles, which may be as advanced as to slow //! in response to backpressure. //! //! ```rust //! # extern crate mysteriouspants_throttle; //! # use std::time::{Duration, Instant}; //! # use mysteriouspants_throttle::Throttle; //! # fn main() { //! let throttle = Throttle::new_variable_throttle( //! |arg: u64, _| Duration::from_millis(arg)); //! //! let iteration_start = Instant::now(); //! //! for i in 0..5 { //! throttle.acquire(i * 100); //! } //! //! assert_eq!(iteration_start.elapsed().as_secs() == 1, true); //! # } use std::cell::Cell; use std::time::{Duration, Instant}; use std::thread::sleep; #[derive(Copy, Clone)] enum ThrottleState { Uninitialized, Initialized { previous_invocation: Instant } } // A simple configurable throttle for slowing down code. A Throttle pub struct Throttle<TArg> { delay_calculator: Box<Fn(TArg, Duration) -> Duration>, state: Cell<ThrottleState> } impl <TArg> Throttle<TArg> { /// Creates a new `Throttle` with a variable delay controlled by a closure. `delay_calculator` /// itself is an interesting type, any closure which satisfies `Fn(TArg, Duration) -> Duration`. /// It is called to determine how long the `Throttle` ought to wait before resuming execution, /// and allows you to create `Throttle`s which respond to changes in the program or environment. /// /// An example use of a variable-rate throttle might be to wait different periods of time /// depending on whether your program is in backpressure, so "ease up" on your downstream call /// rate, so to speak. /// /// ```rust /// # extern crate mysteriouspants_throttle; /// # use std::time::{Duration, Instant}; /// # use mysteriouspants_throttle::Throttle; /// let throttle = Throttle::new_variable_throttle( /// |in_backpressure: bool, time_since_previous_acquire: Duration| /// match in_backpressure { /// true => Duration::from_millis(2100), /// false => Duration::from_millis(1100) /// }); /// /// // the first one is free! /// throttle.acquire(false); /// /// let start_nopressure = Instant::now(); /// throttle.acquire(false); /// assert_eq!(start_nopressure.elapsed().as_secs() == 1, true); /// /// let start_yespressure = Instant::now(); /// throttle.acquire(true); /// assert_eq!(start_yespressure.elapsed().as_secs() == 2, true); /// ``` pub fn new_variable_throttle<TDelayCalculator: Fn(TArg, Duration) -> Duration + 'static>( delay_calculator: TDelayCalculator) -> Throttle<TArg> { return Throttle { delay_calculator: Box::new(delay_calculator), state: Cell::new(ThrottleState::Uninitialized) }; } /// Creates a new `Throttle` with a constant delay of `tps`<sup>-1</sup> · 1000, or /// `tps`-transactions per second. /// /// ```rust /// # extern crate mysteriouspants_throttle; /// # use std::time::{Duration, Instant}; /// # use mysteriouspants_throttle::Throttle; /// let throttle = Throttle::new_tps_throttle(0.9); /// /// // the first one is free! /// throttle.acquire(()); /// /// let start = Instant::now(); /// throttle.acquire(()); /// assert_eq!(start.elapsed().as_secs() == 1, true); /// ``` pub fn new_tps_throttle(tps: f32) -> Throttle<TArg> { return Throttle { delay_calculator: Box::new(move |_, _| Duration::from_millis(((1.0 / tps) * 1000.0) as u64)), state: Cell::new(ThrottleState::Uninitialized) }; } /// Acquires the throttle, waiting (sleeping the current thread) until enough time has passed /// for the running code to be at or slower than the throttle allows. The first call to /// `acquire` will never wait because there has been an undefined or arguably infinite amount /// of time from the previous time acquire was called. The argument `arg` is passed to the /// closure governing the wait time. pub fn acquire(&self, arg: TArg) { match self.state.get() { ThrottleState::Initialized { previous_invocation } => { let time_since_previous_acquire = Instant::now().duration_since(previous_invocation); let delay_time = (self.delay_calculator)(arg, time_since_previous_acquire); if delay_time > Duration::from_secs(0) { let additional_delay_required = delay_time - time_since_previous_acquire; if additional_delay_required > Duration::from_secs(0) { sleep(additional_delay_required); } } self.state.replace(ThrottleState::Initialized { previous_invocation: Instant::now() }); }, ThrottleState::Uninitialized => { self.state.replace(ThrottleState::Initialized { previous_invocation: Instant::now() }); } } } } #[cfg(test)] mod tests { use std::time::{Duration, Instant}; use Throttle; #[test] fn it_works() { // simple throttle configured for 10 TPS let throttle = Throttle::new_tps_throttle(10.0); // the first one is free throttle.acquire(()); let iteration_start = Instant::now(); for _i in 0..10 { throttle.acquire(()); } assert_eq!(iteration_start.elapsed().as_secs() == 1, true); } #[test] fn it_works_more_complicated() { let throttle = Throttle::new_variable_throttle( |arg: u64, _| Duration::from_millis(arg)); // the first one is free, so the number won't get used throttle.acquire(0); let iteration_start = Instant::now(); for i in 1..5 { throttle.acquire(i * 100); } assert_eq!(iteration_start.elapsed().as_secs() == 1, true); } // from a user-perspective, a delay of zero ought to mean "no delay," and I don't want to // worry about pesky panics trying to subtract durations! #[test] fn it_works_with_no_delay_at_all_tps() { let throttle = Throttle::new_tps_throttle(0.0); throttle.acquire(()); throttle.acquire(()); // no panic, no problem! } #[test] fn it_works_with_no_delay_at_all_variable() { let throttle = Throttle::new_variable_throttle( |_, _| Duration::from_millis(0)); throttle.acquire(()); throttle.acquire(()); // no panic, no problem! } }