Class: Congestion::RateLimiter
- Inherits:
-
Object
- Object
- Congestion::RateLimiter
- Defined in:
- lib/congestion/rate_limiter.rb
Instance Attribute Summary collapse
-
#key ⇒ Object
Returns the value of attribute key.
-
#options ⇒ Object
Returns the value of attribute options.
-
#redis ⇒ Object
Returns the value of attribute redis.
Instance Method Summary collapse
- #allowed? ⇒ Boolean
- #backoff ⇒ Object
- #first_request ⇒ Object
-
#initialize(redis, key, opts = { }) ⇒ RateLimiter
constructor
A new instance of RateLimiter.
- #last_request ⇒ Object
- #rejected? ⇒ Boolean
- #too_frequent? ⇒ Boolean
- #too_many? ⇒ Boolean
- #total_requests ⇒ Object
Constructor Details
#initialize(redis, key, opts = { }) ⇒ RateLimiter
Returns a new instance of RateLimiter.
5 6 7 8 9 10 11 12 |
# File 'lib/congestion/rate_limiter.rb', line 5 def initialize(redis, key, opts = { }) self.redis = redis self.key = "#{ opts[:namespace] }:#{ key }" self. = opts self.[:interval] *= 1_000 self.[:min_delay] *= 1_000 allowed? end |
Instance Attribute Details
#key ⇒ Object
Returns the value of attribute key.
3 4 5 |
# File 'lib/congestion/rate_limiter.rb', line 3 def key @key end |
#options ⇒ Object
Returns the value of attribute options.
3 4 5 |
# File 'lib/congestion/rate_limiter.rb', line 3 def @options end |
#redis ⇒ Object
Returns the value of attribute redis.
3 4 5 |
# File 'lib/congestion/rate_limiter.rb', line 3 def redis @redis end |
Instance Method Details
#allowed? ⇒ Boolean
28 29 30 31 |
# File 'lib/congestion/rate_limiter.rb', line 28 def allowed? add_request unless rejected? !rejected? end |
#backoff ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/congestion/rate_limiter.rb', line 45 def backoff if too_many? && too_frequent? [quantity_backoff, frequency_backoff].max elsif too_many? quantity_backoff elsif too_frequent? frequency_backoff else 0 end end |
#first_request ⇒ Object
18 19 20 21 |
# File 'lib/congestion/rate_limiter.rb', line 18 def first_request first = get_requests[2].first first ? first.to_i : nil end |
#last_request ⇒ Object
23 24 25 26 |
# File 'lib/congestion/rate_limiter.rb', line 23 def last_request last = get_requests[3].first last ? last.to_i : nil end |
#rejected? ⇒ Boolean
33 34 35 |
# File 'lib/congestion/rate_limiter.rb', line 33 def rejected? too_many? || too_frequent? end |
#too_frequent? ⇒ Boolean
41 42 43 |
# File 'lib/congestion/rate_limiter.rb', line 41 def too_frequent? last_request && time_since_last_request < [:min_delay] end |
#too_many? ⇒ Boolean
37 38 39 |
# File 'lib/congestion/rate_limiter.rb', line 37 def too_many? total_requests > [:max_in_interval] end |
#total_requests ⇒ Object
14 15 16 |
# File 'lib/congestion/rate_limiter.rb', line 14 def total_requests get_requests[1] end |