Class: Shugoi::ChallengeLimiter
- Inherits:
-
Object
- Object
- Shugoi::ChallengeLimiter
- Defined in:
- lib/shugoi/challenge_limiter.rb
Constant Summary collapse
- LIMIT =
60- WINDOW_MS =
60_000- MAX_BLOCK_MS =
15 * 60 * 1000
Instance Method Summary collapse
- #allow?(ip) ⇒ Boolean
-
#initialize ⇒ ChallengeLimiter
constructor
A new instance of ChallengeLimiter.
Constructor Details
#initialize ⇒ ChallengeLimiter
Returns a new instance of ChallengeLimiter.
7 8 9 10 |
# File 'lib/shugoi/challenge_limiter.rb', line 7 def initialize @limits = {} @mutex = Mutex.new end |
Instance Method Details
#allow?(ip) ⇒ Boolean
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 |
# File 'lib/shugoi/challenge_limiter.rb', line 12 def allow?(ip) return true if ip.to_s.empty? || ip == "unknown" now = Utils.now_ms @mutex.synchronize do entry = @limits[ip] if entry.nil? || now - entry[:window_start] >= WINDOW_MS @limits[ip] = { count: 1, window_start: now, blocked_until: 0 } next true end entry[:count] += 1 next false if entry[:blocked_until] > now if entry[:count] > LIMIT exponent = [entry[:count] - LIMIT, 10].min backoff = [60_000 * (2**exponent), MAX_BLOCK_MS].min entry[:blocked_until] = now + backoff entry[:count] = 0 next false end true end end |