Class: Synthra::APIServer::RateLimiter
- Inherits:
-
Object
- Object
- Synthra::APIServer::RateLimiter
- Defined in:
- lib/synthra/api_server.rb
Overview
Simple rate limiter
Instance Method Summary collapse
-
#initialize(limit_per_minute) ⇒ RateLimiter
constructor
A new instance of RateLimiter.
- #limited?(ip) ⇒ Boolean
- #retry_after(ip) ⇒ Object
Constructor Details
#initialize(limit_per_minute) ⇒ RateLimiter
Returns a new instance of RateLimiter.
525 526 527 528 529 |
# File 'lib/synthra/api_server.rb', line 525 def initialize(limit_per_minute) @limit = limit_per_minute @counts = Hash.new { |h, k| h[k] = { count: 0, reset_at: Time.now + 60 } } @mutex = Mutex.new end |
Instance Method Details
#limited?(ip) ⇒ Boolean
531 532 533 534 535 536 537 538 539 540 541 542 543 |
# File 'lib/synthra/api_server.rb', line 531 def limited?(ip) @mutex.synchronize do entry = @counts[ip] if Time.now > entry[:reset_at] entry[:count] = 0 entry[:reset_at] = Time.now + 60 end entry[:count] += 1 entry[:count] > @limit end end |
#retry_after(ip) ⇒ Object
545 546 547 548 549 550 551 |
# File 'lib/synthra/api_server.rb', line 545 def retry_after(ip) # Same mutex as #limited? — @counts has a default block, so even a read can mutate the hash. @mutex.synchronize do entry = @counts[ip] [entry[:reset_at] - Time.now, 0].max.ceil end end |