Files
sure/app/services/api_rate_limiter.rb
RealDiligent c9c484010b fix: use REDIS_URL in ApiRateLimiter for hosted API requests (#2639)
* fix: resolve ApiRateLimiter connecting to wrong Redis instance

Use REDIS_URL for API key rate limiting so hosted deployments share the
configured Redis backend instead of defaulting to localhost.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: align ApiRateLimiter specs with configured redis_url

Use ApiRateLimiter.redis_url for test cleanup and assert the public
redis_url reader instead of inspecting private Redis client internals.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-21 09:59:28 +02:00

104 lines
2.4 KiB
Ruby

class ApiRateLimiter
# Rate limit tiers (requests per hour)
RATE_LIMITS = {
standard: 100,
premium: 1000,
enterprise: 10000
}.freeze
DEFAULT_TIER = :standard
def initialize(api_key)
@api_key = api_key
@redis = Redis.new(url: self.class.redis_url)
end
# Check if the API key has exceeded its rate limit
def rate_limit_exceeded?
current_count >= rate_limit
end
# Increment the request count for this API key
def increment_request_count!
key = redis_key
current_time = Time.current.to_i
window_start = (current_time / 3600) * 3600 # Hourly window
@redis.multi do |transaction|
# Use a sliding window with hourly buckets
transaction.hincrby(key, window_start.to_s, 1)
transaction.expire(key, 7200) # Keep data for 2 hours to handle sliding window
end
end
# Get current request count within the current hour
def current_count
key = redis_key
current_time = Time.current.to_i
window_start = (current_time / 3600) * 3600
count = @redis.hget(key, window_start.to_s)
count.to_i
end
# Get the rate limit for this API key's tier
def rate_limit
tier = determine_tier
RATE_LIMITS[tier]
end
# Calculate seconds until the rate limit resets
def reset_time
current_time = Time.current.to_i
next_window = ((current_time / 3600) + 1) * 3600
next_window - current_time
end
# Get detailed usage information
def usage_info
{
current_count: current_count,
rate_limit: rate_limit,
remaining: [ rate_limit - current_count, 0 ].max,
reset_time: reset_time,
tier: determine_tier
}
end
# Class method to get usage for an API key without incrementing
def self.usage_for(api_key)
limit(api_key).usage_info
end
def self.limit(api_key)
if Rails.application.config.app_mode.self_hosted?
# Use NoopApiRateLimiter for self-hosted mode
# This means no rate limiting is applied
NoopApiRateLimiter.new(api_key)
else
new(api_key)
end
end
def self.redis_url
ENV.fetch("REDIS_URL", "redis://localhost:6379/0")
end
def redis_url
self.class.redis_url
end
private
def redis_key
"api_rate_limit:#{@api_key.id}"
end
def determine_tier
# For now, all API keys are standard tier
# This can be extended later to support different tiers based on user subscription
# or API key configuration
DEFAULT_TIER
end
end