Class: Readyset::Utils::WindowCounter

Inherits:
Object
  • Object
show all
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

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

#logObject

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

#sizeInteger

Returns the current number of events logged in the configured time_period

Returns:



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.

Returns:



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