push
github
11 of 34 new or added lines in 2 files covered. (32.35%)
6050 of 6345 relevant lines covered (95.35%)
918.22 hits per line
|
class RateLimiter |
4✔ |
|
def initialize(cache, interval, limit, max_burst) |
4✔ |
NEW
|
@cache = cache
|
× |
NEW
|
@requests_per_second = limit.to_f / interval
|
× |
NEW
|
@burst_limit = max_burst
|
× |
6 |
end
|
|
7 |
|
|
|
def allow?(key) |
4✔ |
NEW
|
last_update, requests = @cache.get(key)
|
× |
10 |
|
|
NEW
|
if last_update
|
× |
NEW
|
elapsed = Time.now.to_i - last_update
|
× |
13 |
|
|
NEW
|
requests -= elapsed * @requests_per_second
|
× |
15 |
else
|
|
NEW
|
requests = 0.0
|
× |
17 |
end
|
|
18 |
|
|
NEW
|
requests < @burst_limit
|
× |
20 |
end
|
|
21 |
|
|
|
def update(key) |
4✔ |
NEW
|
now = Time.now.to_i
|
× |
24 |
|
|
NEW
|
last_update, requests = @cache.get(key)
|
× |
26 |
|
|
NEW
|
if last_update
|
× |
NEW
|
elapsed = now - last_update |
× |
29 |
|
|
NEW
|
requests -= elapsed * @requests_per_second
|
× |
NEW
|
requests += 1.0
|
× |
32 |
else
|
|
NEW
|
requests = 1.0
|
× |
34 |
end
|
|
35 |
|
|
NEW
|
@cache.set(key, [now, [requests, 1.0].max]) |
× |
37 |
end
|
|
38 |
end
|