Class: Wikiwiki::SlidingWindow

Inherits:
Object
  • Object
show all
Defined in:
lib/wikiwiki/sliding_window.rb

Overview

Sliding window algorithm for rate limiting

Instance Method Summary collapse

Constructor Details

#initialize(window:, max_requests:) ⇒ SlidingWindow

Initialize a new window limiter

Parameters:

  • window (Integer)

    time window in seconds

  • max_requests (Integer)

    maximum requests allowed in the window



10
11
12
13
14
# File 'lib/wikiwiki/sliding_window.rb', line 10

def initialize(window:, max_requests:)
  @window = window
  @max_requests = max_requests
  @requests = []
end

Instance Method Details

#can_request?Boolean

Check if a request can be made without exceeding the limit

Returns:

  • (Boolean)

    true if request is allowed



19
20
21
22
# File 'lib/wikiwiki/sliding_window.rb', line 19

def can_request?
  cleanup!
  @requests.size < @max_requests
end

#record!void

This method returns an undefined value.

Record a new request timestamp



27
# File 'lib/wikiwiki/sliding_window.rb', line 27

def record! = (@requests << Time.now)

#wait_timeFloat

Get time in seconds until next request can be made

Returns:

  • (Float)

    seconds to wait (0.0 if request can be made now)



32
33
34
35
36
37
38
39
40
# File 'lib/wikiwiki/sliding_window.rb', line 32

def wait_time
  cleanup!
  return 0.0 if @requests.size < @max_requests

  # Time until oldest request expires
  oldest = @requests.first
  time_until_expiry = @window - (Time.now - oldest)
  [time_until_expiry, 0.0].max
end