redis_rate_limiter 0.0.8 → 0.0.9
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/lib/redis_rate_limiter.rb +24 -8
- metadata +2 -2
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA1:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 05bc20f9ac3908cfa3c1b5e459e32b9a19e2bd58
|
4
|
+
data.tar.gz: 1929511d7ef79dcb0831aa153cb4d89fca456682
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: e41ecbc1374c2b4cd22dba9887eecb6a4cc85b8a9a66c4e5a3802b8c96471cd5d00f744c82bbae7c39ce0cb3a0617b8fad64bcf3f28c8c36da1dee13845b0242
|
7
|
+
data.tar.gz: f9a74c5d35be39f298a9f2c71e38eab8104b149c2def08879ae8675a465cc8a2dfaceab9c77ce167dd740adf18fa4e4567e5d4b715eac5756d27b7d5e77e4538
|
data/lib/redis_rate_limiter.rb
CHANGED
@@ -31,11 +31,11 @@ class RedisRateLimiter
|
|
31
31
|
# @param [String] subject A name to uniquely identify subject
|
32
32
|
# @param [time] time UNIX timestamp of event
|
33
33
|
def add subject, time = Time.now.to_f
|
34
|
-
|
34
|
+
subject_key = "#{@key}:#{subject}"
|
35
35
|
@redis.multi do
|
36
|
-
@redis.lpush(
|
37
|
-
@redis.ltrim(
|
38
|
-
@redis.expire(
|
36
|
+
@redis.lpush(subject_key, time)
|
37
|
+
@redis.ltrim(subject_key, 0, @limit - 1)
|
38
|
+
@redis.expire(subject_key, @interval)
|
39
39
|
end
|
40
40
|
end
|
41
41
|
|
@@ -44,9 +44,25 @@ class RedisRateLimiter
|
|
44
44
|
# @param [String] subject Name which uniquely identifies subject
|
45
45
|
# @return [Boolean] Returns true if subject has exceeded count
|
46
46
|
def exceeded? subject
|
47
|
-
|
48
|
-
return false if @redis.llen(
|
49
|
-
|
50
|
-
|
47
|
+
subject_key = "#{@key}:#{subject}"
|
48
|
+
return false if @redis.llen(subject_key) < @limit
|
49
|
+
time_since_oldest(subject_key) < @interval
|
50
|
+
end
|
51
|
+
|
52
|
+
# Get time in seconds until subject is not rate limited
|
53
|
+
#
|
54
|
+
# @param [String] subject Name which uniquely identifies subject
|
55
|
+
# @return [Float] Returns time in seconds until subject is not rate limited
|
56
|
+
def retry_in? subject
|
57
|
+
subject_key = "#{@key}:#{subject}"
|
58
|
+
return 0.0 if @redis.llen(subject_key) < @limit
|
59
|
+
elapsed = time_since_oldest(subject_key)
|
60
|
+
elapsed > @interval ? 0.0 : @interval - elapsed
|
61
|
+
end
|
62
|
+
|
63
|
+
private
|
64
|
+
|
65
|
+
def time_since_oldest subject_key
|
66
|
+
Time.now.to_f - @redis.lindex(subject_key, -1).to_f
|
51
67
|
end
|
52
68
|
end
|
metadata
CHANGED
@@ -1,14 +1,14 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: redis_rate_limiter
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version: 0.0.
|
4
|
+
version: 0.0.9
|
5
5
|
platform: ruby
|
6
6
|
authors:
|
7
7
|
- Sean Xie
|
8
8
|
autorequire:
|
9
9
|
bindir: bin
|
10
10
|
cert_chain: []
|
11
|
-
date:
|
11
|
+
date: 2015-05-11 00:00:00.000000000 Z
|
12
12
|
dependencies:
|
13
13
|
- !ruby/object:Gem::Dependency
|
14
14
|
name: redis
|