Module: BetterRateLimit::Throttle

Includes:
RedisConnection
Defined in:
lib/better_rate_limit/throttle.rb

Class Method Summary collapse

Methods included from RedisConnection

included

Class Method Details

.clear(key) ⇒ Object



46
47
48
49
# File 'lib/better_rate_limit/throttle.rb', line 46

def clear(key)
  redis_client.del(key)
  redis_client.del("failing-rate-limits:#{key}")
end

.notify(key) ⇒ Object



53
54
55
# File 'lib/better_rate_limit/throttle.rb', line 53

def notify(key)
  ActiveSupport::Notifications.instrument 'rate_limit.notify', { rate_limit_key: key }
end

.throttle(key, limit:, time_window:) ⇒ Object Also known as: allow?



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/better_rate_limit/throttle.rb', line 12

def throttle(key, limit:, time_window:)
  return true if BetterRateLimit.configuration.ignore
  raise MissingRedisConfigError unless redis_client

  now = Time.now.utc
  timestamps_count = redis_client.llen key

  if timestamps_count < limit
    redis_client.multi do |pipeline|
      pipeline.rpush key, now
      pipeline.expire key, time_window.to_i
    end
    true
  else
    first = redis_client.lpop(key)

    redis_client.multi do |pipeline|
      pipeline.rpush key, now
      pipeline.expire key, time_window.to_i
    end

    return false unless first

    passing = first.to_time(:utc) < time_window.ago

    unless passing
      notify(key) unless redis_client.exists?('failing-rate-limits:' + key)
      redis_client.setex('failing-rate-limits:' + key, time_window.to_i, '1')
    end

    passing
  end
end