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
//! Throttle events and record event stats with a simple library
//!
//! throttle_timer has no dependencies
//!
//! `ThrottleTimer` struct is created with a max frequency and label
//!
//! ```ThrottleTimer::new(Duration::from_secs(1_u64), &"Once every second");```
//!
//! Calling ```run()``` will check the last call time. If max frequency time has not passed the fn will return false.
//! If max_frequency duration has passed since the last call then the fn will return true
//!
//!
//! # Example
//! ```
//! use std::time::Duration;
//! use throttle_timer::ThrottleTimer;
//!
//! let mut break_timer = ThrottleTimer::new(Duration::from_secs(10_u64), &"Break");
//! let mut val = 0_u8;
//!
//! // timers always run when no previous runs
//! break_timer.run(&mut || val += 1);
//! for _ in 0..100 {
//!     // timer will not run as 10 secs has not passed
//!     // do run will return false
//!     break_timer.run(&mut || val += 1);
//! }
//!
//! break_timer.print_stats();
//! // Break called 0/sec, total calls 1, has been running for 10us
//!
//! assert_eq!(break_timer.total_calls(), &1);
//! assert_eq!(val, 1_u8);
//!
//!
//! ```

use std::thread;
use std::time::Duration;
use std::time::Instant;
use std::time::SystemTime;

#[derive(Debug)]
pub struct ThrottleTimer {
    maybe_last_called_time: Option<Instant>,
    total_calls: usize,
    created_date: SystemTime,
    max_frequency: Duration,
    event_name: &'static str,
}

///
/// # Example
/// ```
/// use std::time::Duration;
/// use throttle_timer::ThrottleTimer;
///
/// let mut break_timer: ThrottleTimer = ThrottleTimer::new(Duration::from_secs(1_u64), &"Break");
/// let do_break_flag = break_timer.run(&mut || {});
///
/// // Timers always run when no previous runs
/// assert!(do_break_flag == true);
/// if do_break_flag {
///     println!("timer do run flag is set to true")
/// }
///
/// // Run flag false as no time has passed
/// assert!(break_timer.run(&mut || {}) == false);
/// ```
impl ThrottleTimer {
    pub fn new(max_frequency: std::time::Duration, event_name: &'static str) -> Self {
        Self {
            maybe_last_called_time: None,
            max_frequency,
            event_name,
            total_calls: 0,
            created_date: SystemTime::now(),
        }
    }
    pub const fn event_name(&self) -> &str {
        self.event_name
    }
    pub const fn total_calls(&self) -> &usize {
        &self.total_calls
    }
    pub const fn max_frequency(&self) -> &Duration {
        &self.max_frequency
    }
    pub const fn created_date(&self) -> SystemTime {
        self.created_date
    }
    pub fn wait_time(&self) -> Duration {
        match self.maybe_last_called_time {
            None => Duration::from_secs(0),
            Some(last_time) => {
                (self.max_frequency
                    - Instant::now()
                        .duration_since(last_time)
                        .min(self.max_frequency))
            }
        }
    }

    /// Prints total calls and calls/sec
    pub fn print_stats(&self) {
        match self.created_date.elapsed() {
            Ok(created_time_elapsed) => {
                println!(
                    "{} called {}/sec, total calls {}, has been running for {:?}",
                    self.event_name,
                    created_time_elapsed.as_secs() / self.total_calls as u64,
                    self.total_calls,
                    created_time_elapsed,
                );
            }
            Err(e) => eprintln!("{:?}", e),
        }
    }

    /// Calling ```run()``` will check the last call time. If max frequency time has not passed the fn will return false.
    /// If max_frequency duration has passed since the last call then the fn will return true
    pub fn can_run(&mut self) -> bool {
        match self.maybe_last_called_time {
            None => true,
            Some(last_time) => Instant::now().duration_since(last_time) >= self.max_frequency,
        }
    }

    pub fn run_throttle_cb(&mut self, success: &mut FnMut(), throttled: &mut FnMut()) -> bool {
        let run_flag: bool = self.can_run();

        if run_flag {
            self.maybe_last_called_time = Some(Instant::now());
            self.total_calls += 1;
            success();
        } else {
            throttled()
        }
        run_flag
    }

    /// Calling ```run()``` will check the last call time. If max frequency time has not passed the fn will return false.
    /// If max_frequency duration has passed since the last call then the fn will return true
    pub fn run(&mut self, success: &mut FnMut()) -> bool {
        self.run_throttle_cb(success, &mut || {})
    }

    /// Calling ```run()``` will check the last call time. If max frequency time has not passed the fn will return false.
    /// If max_frequency duration has passed since the last call then the fn will return true
    pub fn run_wait(&mut self, success: &mut FnMut()) {
        thread::sleep(self.wait_time());
        self.run_throttle_cb(success, &mut || {});
    }

    // Same as run but will print a message if throttled
    pub fn run_with_msg(&mut self, success: &mut FnMut()) -> bool {
        let did_run = self.run(success);
        if !did_run {
            println!(
                "{} throttled, last time {:?}",
                self.event_name(),
                Instant::now().duration_since(self.maybe_last_called_time.unwrap())
            );
        }
        did_run
    }
}

#[cfg(test)]
mod test {
    use super::ThrottleTimer;
    use std::{thread, time::Duration};

    #[test]
    fn test_run() {
        let mut break_timer: ThrottleTimer =
            ThrottleTimer::new(Duration::from_secs(45_000_u64), &"Break");
        let run_flag = break_timer.run(&mut || {});

        // timers always run when no previous runs
        assert!(run_flag);
        if run_flag {
            println!("timer do run flag is set to true")
        }
        break_timer.event_name();
        break_timer.total_calls();
        break_timer.max_frequency();
        break_timer.created_date();
    }

    #[test]
    fn test_run_with_msg() {
        let mut break_timer: ThrottleTimer =
            ThrottleTimer::new(Duration::from_secs(45_000_u64), &"Break");
        let run_flag = break_timer.run_with_msg(&mut || {});

        // timers always run when no previous runs
        assert!(run_flag);
    }

    #[test]
    fn test_call_count() {
        let mut break_timer: ThrottleTimer =
            ThrottleTimer::new(Duration::from_nanos(1_u64), &"Break");

        for _ in 0..100 {
            assert_eq!(break_timer.run(&mut || {}), true);
            thread::sleep(Duration::from_nanos(100_u64));
        }

        // timers always run when no previous runs
        assert_eq!(break_timer.total_calls, 100);
        break_timer.print_stats();
    }

    #[test]
    fn test_can_run() {
        let mut break_timer: ThrottleTimer =
            ThrottleTimer::new(Duration::from_secs(1_u64), &"Break");

        assert!(break_timer.run(&mut || {}));
        for _ in 0..100 {
            assert!(!break_timer.can_run());
            assert!(!break_timer.run(&mut || {}));
        }

        // timers always run when no previous runs
        assert_eq!(break_timer.total_calls, 1);
        break_timer.print_stats();
    }

    #[test]
    fn test_print_debug() {
        println!(
            "{:?}",
            ThrottleTimer::new(Duration::from_nanos(1_u64), &"Break")
        );
    }

    #[test]
    fn test_in_loop() {
        let mut break_timer = ThrottleTimer::new(Duration::from_secs(10_u64), &"Break");

        // timers always run when no previous runs
        assert!(break_timer.run(&mut || {}));
        for _ in 0..100 {
            // timer will not run as 10 secs has not passed
            // do run will return false
            assert!(!break_timer.run(&mut || {}));
        }
        assert_eq!(break_timer.total_calls(), &1);
    }

    #[test]
    fn test_run_wait() {
        let mut break_timer = ThrottleTimer::new(Duration::from_nanos(10_u64), &"Break");

        break_timer.run_wait(&mut || {});
        break_timer.run_wait(&mut || {});
        break_timer.run_wait(&mut || {});
        assert_eq!(break_timer.total_calls(), &3);
    }

    #[test]
    fn test_with_delay() {
        let mut snack_timer: ThrottleTimer =
            ThrottleTimer::new(Duration::from_secs(1_u64), &"Snack");
        let run_flag = snack_timer.run(&mut || {});

        // timers always run when no previous runs
        assert!(run_flag);

        let run_flag2 = snack_timer.run_with_msg(&mut || {});

        // run flag false as no time has passed
        assert_eq!(run_flag2, false);

        thread::sleep(snack_timer.max_frequency);
        assert!(snack_timer.run(&mut || {}));
        thread::sleep(Duration::from_millis(100_u64));
        assert!(!snack_timer.run(&mut || {}));
        thread::sleep(Duration::from_secs(1_u64));
        assert!(snack_timer.run(&mut || {}));
    }
}