forked from discourse/discourse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrate_limiter.rb
More file actions
53 lines (41 loc) · 1.02 KB
/
Copy pathrate_limiter.rb
File metadata and controls
53 lines (41 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
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
45
46
47
48
49
50
51
52
53
require_dependency 'rate_limiter/limit_exceeded'
require_dependency 'rate_limiter/on_create_record'
# A redis backed rate limiter.
class RateLimiter
# We don't observe rate limits in test mode
def self.disabled?
Rails.env.test?
end
def initialize(user, key, max, secs)
@user = user
@key = "rate-limit:#{@user.id}:#{key}"
@max = max
@secs = secs
end
def clear!
$redis.del(@key)
end
def can_perform?
return true if RateLimiter.disabled?
return true if @user.staff?
result = $redis.get(@key)
return true if result.blank?
return true if result.to_i < @max
false
end
def performed!
return if RateLimiter.disabled?
return if @user.staff?
result = $redis.incr(@key).to_i
$redis.expire(@key, @secs) if result == 1
if result > @max
# In case we go over, clamp it to the maximum
$redis.decr(@key)
raise LimitExceeded.new($redis.ttl(@key))
end
end
def rollback!
return if RateLimiter.disabled?
$redis.decr(@key)
end
end