Class: RateLimiterMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/macaw_framework/middlewares/rate_limiter_middleware.rb

Overview

Middleware responsible for implementing rate limiting

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(window_size, max_requests) ⇒ RateLimiterMiddleware

Returns a new instance of RateLimiterMiddleware.



9
10
11
12
13
14
# File 'lib/macaw_framework/middlewares/rate_limiter_middleware.rb', line 9

def initialize(window_size, max_requests)
  @window_size = window_size
  @max_requests = max_requests
  @client_timestamps = Hash.new { |key, value| key[value] = [] }
  @mutex = Mutex.new
end

Instance Attribute Details

#max_requestsObject (readonly)

Returns the value of attribute max_requests.



7
8
9
# File 'lib/macaw_framework/middlewares/rate_limiter_middleware.rb', line 7

def max_requests
  @max_requests
end

#window_sizeObject (readonly)

Returns the value of attribute window_size.



7
8
9
# File 'lib/macaw_framework/middlewares/rate_limiter_middleware.rb', line 7

def window_size
  @window_size
end

Instance Method Details

#allow?(client_id) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/macaw_framework/middlewares/rate_limiter_middleware.rb', line 16

def allow?(client_id)
  @mutex.synchronize do
    now = Time.now.to_i
    timestamps = @client_timestamps[client_id]

    timestamps.reject! { |timestamp| timestamp <= now - window_size }

    if timestamps.length < max_requests
      timestamps << now
      true
    else
      false
    end
  end
end