Class: Congestion::RateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/congestion/rate_limiter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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.options = opts
  self.options[:interval] *= 1_000
  self.options[:min_delay] *= 1_000
  allowed?
end

Instance Attribute Details

#keyObject

Returns the value of attribute key.



3
4
5
# File 'lib/congestion/rate_limiter.rb', line 3

def key
  @key
end

#optionsObject

Returns the value of attribute options.



3
4
5
# File 'lib/congestion/rate_limiter.rb', line 3

def options
  @options
end

#redisObject

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

Returns:

  • (Boolean)


28
29
30
31
# File 'lib/congestion/rate_limiter.rb', line 28

def allowed?
  add_request unless rejected?
  !rejected?
end

#backoffObject



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_requestObject



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_requestObject



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

Returns:

  • (Boolean)


33
34
35
# File 'lib/congestion/rate_limiter.rb', line 33

def rejected?
  too_many? || too_frequent?
end

#too_frequent?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/congestion/rate_limiter.rb', line 41

def too_frequent?
  last_request && time_since_last_request < options[:min_delay]
end

#too_many?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/congestion/rate_limiter.rb', line 37

def too_many?
  total_requests > options[:max_in_interval]
end

#total_requestsObject



14
15
16
# File 'lib/congestion/rate_limiter.rb', line 14

def total_requests
  get_requests[1]
end