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
//! A token bucket ratelimiter for rust which can be used by either a single
//! thread or shared across threads using a mpsc synchronous channel
//!
//!
//! # Goals
//! * a simple token bucket ratelimiter
//! * usable in single or multi thread code
//!
//! # Future work
//! * consider additional types of ratelimiters
//!
//! # Usage
//!
//! Construct a new `Ratelimit` and call block between actions. For multi-thread
//! clone the channel sender to pass to the threads, in a separate thread, call
//! run on the `Ratelimit` in a tight loop.
//!
//! # Example
//!
//! Construct `Ratelimit` and use in single and then multi-thread modes
//!
//! ```
//!
//! extern crate ratelimit;
//!
//! use std::thread;
//! use std::sync::mpsc;
//! use std::time::Duration;
//!
//! let mut ratelimit = ratelimit::Ratelimit::configure()
//!     .capacity(1) //number of tokens the bucket will hold
//!     .quantum(1) //add one token per interval
//!     .interval(Duration::new(1, 0)) //add quantum tokens every 1 second
//!     .build();
//!
//! // count down to ignition
//! println!("Count-down....");
//! for i in -10..0 {
//!     println!("T {}", i);
//!     ratelimit.block(1);
//! }
//! println!("Ignition!");
//!
//! // clone the sender from Ratelimit
//! let sender = ratelimit.clone_sender();
//!
//! // create ratelimited threads
//! for i in 0..2 {
//!     let s = sender.clone();
//!     thread::spawn(move || {
//!         for x in 0..5 {
//!             s.send(());
//!             println!(".");
//!         }
//!     });
//! }
//!
//! // run the ratelimiter
//! thread::spawn(move || {
//!     loop {
//!         ratelimit.run();
//!     }
//! });

#![crate_type = "lib"]

#![crate_name = "ratelimit"]

extern crate shuteye;

use std::time::{Duration, Instant};
use std::sync::mpsc;

use shuteye::sleep;

pub struct Config {
    start: Instant,
    capacity: u32,
    quantum: u32,
    interval: Duration,
}

pub struct Ratelimit {
    config: Config,
    t0: Instant,
    available: i64,
    tick: u64,
    tx: mpsc::SyncSender<()>,
    rx: mpsc::Receiver<()>,
}

impl Config {
    /// returns a Ratelimit from the Config
    ///
    /// # Example
    /// ```
    /// # use ratelimit::Ratelimit;
    ///
    /// let mut r = Ratelimit::configure().build();
    pub fn build(self) -> Ratelimit {
        Ratelimit::configured(self)
    }

    /// sets the number of tokens to add per interval
    ///
    /// # Example
    /// ```
    /// # use ratelimit::Ratelimit;
    ///
    /// let mut r = Ratelimit::configure()
    ///     .quantum(100)
    ///     .build();
    pub fn quantum(mut self, quantum: u32) -> Self {
        self.quantum = quantum;
        self
    }

    /// sets the bucket capacity
    ///
    /// # Example
    /// ```
    /// # use ratelimit::Ratelimit;
    ///
    /// let mut r = Ratelimit::configure()
    ///     .capacity(100)
    ///     .build();
    pub fn capacity(mut self, capacity: u32) -> Self {
        self.capacity = capacity;
        self
    }

    /// set the duration between token adds
    ///
    /// # Example
    /// ```
    /// # use ratelimit::Ratelimit;
    /// # use std::time::Duration;
    ///
    /// let mut r = Ratelimit::configure()
    ///     .interval(Duration::new(2, 0))
    ///     .build();
    pub fn interval(mut self, interval: Duration) -> Self {
        self.interval = interval;
        self
    }

    /// set the frequency in Hz of the ratelimiter
    ///
    /// # Example
    /// ```
    /// # use ratelimit::Ratelimit;
    ///
    /// let mut rate = 100_000; // 100kHz
    /// let mut r = Ratelimit::configure()
    ///     .frequency(rate)
    ///     .build();
    pub fn frequency(mut self, cycles: u32) -> Self {
        let mut interval = Duration::new(1, 0);
        interval /= cycles;
        self.interval = interval;
        self
    }
}

impl Default for Config {
    fn default() -> Config {
        Config {
            start: Instant::now(),
            capacity: 1,
            quantum: 1,
            interval: Duration::new(1, 0),
        }
    }
}

impl Default for Ratelimit {
    fn default() -> Ratelimit {
        Config::default().build()
    }
}

impl Ratelimit {
    /// create a new default ratelimit instance
    ///
    /// # Example
    /// ```
    /// # use ratelimit::Ratelimit;
    ///
    /// let mut r = Ratelimit::new();
    pub fn new() -> Ratelimit {
        Default::default()
    }

    /// create a new `Config` for building a custom `Ratelimit`
    ///
    /// # Example
    /// ```
    /// # use ratelimit::Ratelimit;
    ///
    /// let mut r = Ratelimit::configure().build();
    pub fn configure() -> Config {
        Config::default()
    }

    // internal function for building a Ratelimit from its Config
    fn configured(config: Config) -> Ratelimit {
        let (tx, rx) = mpsc::sync_channel(config.capacity as usize);
        let t0 = config.start;
        Ratelimit {
            config: config,
            t0: t0,
            available: 0,
            tick: 0,
            tx: tx,
            rx: rx,
        }
    }

    /// run the ratelimiter
    ///
    /// # Example
    /// ```
    /// # use ratelimit::Ratelimit;
    ///
    /// let mut r = Ratelimit::new();
    ///
    /// let sender = r.clone_sender();
    /// let _ = sender.try_send(());
    ///
    /// r.run(); // invoke in a tight-loop in its own thread
    pub fn run(&mut self) {
        let quantum = self.config.quantum;
        self.block(quantum);
        let mut unused = 0;
        for _ in 0..self.config.quantum {
            match self.rx.try_recv() {
                Ok(..) => {}
                Err(_) => {
                    unused += 1;
                }
            }
        }
        self.give(unused);
    }

    /// return clone of SyncSender for client use
    ///
    /// # Example
    /// ```
    /// # use ratelimit::*;
    ///
    /// let mut r = Ratelimit::new();
    ///
    /// let sender = r.clone_sender();
    ///
    /// match sender.try_send(()) {
    ///     Ok(_) => {
    ///         println!("not limited");
    ///     },
    ///     Err(_) => {
    ///         println!("was limited");
    ///     },
    /// }
    pub fn clone_sender(&mut self) -> mpsc::SyncSender<()> {
        self.tx.clone()
    }

    /// this call is the blocking API of Ratelimit
    ///
    /// # Example
    /// ```
    /// # use ratelimit::Ratelimit;
    ///
    /// let mut r = Ratelimit::new();
    /// for i in -10..0 {
    ///     println!("T {}...", i);
    ///     r.block(1);
    /// }
    /// println!("Ignition!");
    pub fn block(&mut self, count: u32) {
        if self.config.interval == Duration::new(0, 0) {
            return;
        }
        if let Some(ts) = self.take(Instant::now(), count) {
            let _ = sleep(ts);
        }
    }

    // internal function to give back unused tokens
    fn give(&mut self, count: u32) {
        self.available += count as i64;

        if self.available >= self.config.capacity as i64 {
            self.available = self.config.capacity as i64;
        }
    }

    // return time to sleep until tokens are available
    fn take(&mut self, t1: Instant, tokens: u32) -> Option<Duration> {
        if tokens == 0 {
            return None;
        }

        let _ = self.tick(t1);
        let available = self.available - tokens as i64;
        if available >= 0 {
            self.available = available;
            return None;
        }

        let needed_ticks = -available as u32 / self.config.quantum;
        let mut wait_time = self.config.interval * needed_ticks;
        if t1 > self.t0 {
            wait_time -= t1 - self.t0;
        }
        self.available = available;
        Some(wait_time)
    }

    // move the time forward and do bookkeeping
    fn tick(&mut self, t1: Instant) -> u64 {
        let tick = cycles(t1.duration_since(self.t0), self.config.interval) as u64 + self.tick;

        if self.available >= self.config.capacity as i64 {
            return tick;
        }
        if tick == self.tick {
            return tick;
        }

        self.available += (tick as i64 - self.tick as i64) * self.config.quantum as i64;
        if self.available > self.config.capacity as i64 {
            self.available = self.config.capacity as i64;
        }
        self.tick = tick;
        self.t0 = t1;
        tick
    }
}

// returns the number of cycles of period length within the duration
fn cycles(duration: Duration, period: Duration) -> f64 {
    let d = 1_000_000_000 * duration.as_secs() as u64 + duration.subsec_nanos() as u64;
    let p = 1_000_000_000 * period.as_secs() as u64 + period.subsec_nanos() as u64;
    d as f64 / p as f64
}

#[cfg(test)]
mod tests {
    use super::Ratelimit;
    use std::time::Duration;

    extern crate shuteye;

    #[test]
    fn test_tick_same() {
        let mut r = Ratelimit::new();
        let t0 = r.t0;

        let tick = r.tick(t0);
        assert_eq!(tick, r.tick(t0));
    }

    #[test]
    fn test_tick_next() {
        let mut r = Ratelimit::new();
        let t0 = r.t0;

        assert_eq!(r.tick(t0), 0);
        assert_eq!(r.tick(t0 + Duration::new(0, 1)), 0);
        assert_eq!(r.tick(t0 + Duration::new(0, 999_999_999)), 0);
        assert_eq!(r.tick(t0 + Duration::new(1, 0)), 1);
        assert_eq!(r.tick(t0 + Duration::new(1, 1)), 1);
        assert_eq!(r.tick(t0 + Duration::new(1, 999_999_999)), 1);
        assert_eq!(r.tick(t0 + Duration::new(2, 0)), 2);
    }

    #[test]
    fn test_take() {
        let mut r = Ratelimit::new();
        let mut t = r.t0;
        t += Duration::new(1, 0);

        assert_eq!(r.take(t, 1), None);

        t += Duration::new(0, 1);
        assert_eq!(r.take(t, 1).unwrap().subsec_nanos(), 999_999_999);
    }
}