Class: Readyset::Utils::WindowCounter
- Inherits:
-
Object
- Object
- Readyset::Utils::WindowCounter
- Defined in:
- lib/readyset/utils/window_counter.rb
Overview
Keeps track of events that occur over time to see if the number of logged events exceeds a
preconfigured threshold in a preconfigured window of time. For example, if window_size is
10 and time_period is 1 minute, the number of events logged in the last minute must exceed
10 in order for WindowCounter#threshold_crossed? to return true.
Instance Method Summary collapse
-
#initialize(window_size: 10, time_period: 1.minute) ⇒ WindowCounter
constructor
A new instance of WindowCounter.
-
#log ⇒ Object
Logs a new event.
-
#size ⇒ Integer
Returns the current number of events logged in the configured
time_period. -
#threshold_crossed? ⇒ Boolean
Returns true only if the number of events logged in the configured
time_periodhas exceeded the configuredwindow_size.
Constructor Details
#initialize(window_size: 10, time_period: 1.minute) ⇒ WindowCounter
Returns a new instance of WindowCounter.
8 9 10 11 12 13 |
# File 'lib/readyset/utils/window_counter.rb', line 8 def initialize(window_size: 10, time_period: 1.minute) @lock = Mutex.new @time_period = time_period @times = [] @window_size = window_size end |
Instance Method Details
#log ⇒ Object
Logs a new event
18 19 20 21 22 23 24 25 |
# File 'lib/readyset/utils/window_counter.rb', line 18 def log lock.synchronize do remove_times_out_of_threshold! times << Time.zone.now end nil end |
#size ⇒ Integer
Returns the current number of events logged in the configured time_period
30 31 32 33 34 35 |
# File 'lib/readyset/utils/window_counter.rb', line 30 def size lock.synchronize do remove_times_out_of_threshold! times.size end end |
#threshold_crossed? ⇒ Boolean
Returns true only if the number of events logged in the configured time_period has
exceeded the configured window_size.
41 42 43 44 45 46 |
# File 'lib/readyset/utils/window_counter.rb', line 41 def threshold_crossed? lock.synchronize do remove_times_out_of_threshold! times.size > window_size end end |