Class: RateLimiterMiddleware
- Inherits:
-
Object
- Object
- RateLimiterMiddleware
- Defined in:
- lib/macaw_framework/middlewares/rate_limiter_middleware.rb
Overview
Middleware responsible for implementing rate limiting
Instance Attribute Summary collapse
-
#max_requests ⇒ Object
readonly
Returns the value of attribute max_requests.
-
#window_size ⇒ Object
readonly
Returns the value of attribute window_size.
Instance Method Summary collapse
- #allow?(client_id) ⇒ Boolean
-
#initialize(window_size, max_requests) ⇒ RateLimiterMiddleware
constructor
A new instance of RateLimiterMiddleware.
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_requests ⇒ Object (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_size ⇒ Object (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
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 = @client_timestamps[client_id] .reject! { || <= now - window_size } if .length < max_requests << now true else false end end end |