Class: Blazer::Ai::RateLimiter
- Inherits:
-
Object
- Object
- Blazer::Ai::RateLimiter
- Defined in:
- lib/blazer/ai/rate_limiter.rb
Defined Under Namespace
Classes: RateLimitExceeded
Instance Method Summary collapse
-
#check_and_track!(identifier:) ⇒ Object
Atomically increment and check rate limit in one operation This prevents race conditions where concurrent requests bypass the limit.
-
#initialize(cache: Rails.cache, max_requests: nil, window: 1.minute) ⇒ RateLimiter
constructor
A new instance of RateLimiter.
Constructor Details
#initialize(cache: Rails.cache, max_requests: nil, window: 1.minute) ⇒ RateLimiter
Returns a new instance of RateLimiter.
13 14 15 16 17 |
# File 'lib/blazer/ai/rate_limiter.rb', line 13 def initialize(cache: Rails.cache, max_requests: nil, window: 1.minute) @cache = cache @max_requests = max_requests || Blazer::Ai.configuration.rate_limit_per_minute @window = window end |
Instance Method Details
#check_and_track!(identifier:) ⇒ Object
Atomically increment and check rate limit in one operation This prevents race conditions where concurrent requests bypass the limit
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/blazer/ai/rate_limiter.rb', line 21 def check_and_track!(identifier:) key = rate_limit_key(identifier) # Use atomic increment - most cache stores support this # For stores that don't support increment with initial value, # we fall back to a best-effort approach count = atomic_increment(key) if count > @max_requests raise RateLimitExceeded.new( "Rate limit exceeded. Please wait before generating more queries.", retry_after: @window.to_i ) end count end |