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
|