Class: RailsAiBridge::Mcp::HttpRateLimiter
- Inherits:
-
Object
- Object
- RailsAiBridge::Mcp::HttpRateLimiter
- Defined in:
- lib/rails_ai_bridge/mcp/http_rate_limiter.rb
Overview
Sliding-window request counter per client key (typically request.ip), in-memory per process.
Keeps up to 10,000 active clients; new clients fail closed when capacity is full.
Instance Method Summary collapse
-
#allow?(ip) ⇒ Boolean
trueif the request may proceed. -
#initialize(max_requests:, window_seconds:, clock: nil) ⇒ HttpRateLimiter
constructor
A new instance of HttpRateLimiter.
Constructor Details
#initialize(max_requests:, window_seconds:, clock: nil) ⇒ HttpRateLimiter
Returns a new instance of HttpRateLimiter.
14 15 16 17 18 19 20 |
# File 'lib/rails_ai_bridge/mcp/http_rate_limiter.rb', line 14 def initialize(max_requests:, window_seconds:, clock: nil) @max_requests = max_requests @window_seconds = window_seconds.to_f @clock = clock || -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) } @mutex = Mutex.new @hits = {} end |
Instance Method Details
#allow?(ip) ⇒ Boolean
Returns true if the request may proceed.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/rails_ai_bridge/mcp/http_rate_limiter.rb', line 24 def allow?(ip) key = ip.to_s.presence || 'unknown' @mutex.synchronize do now = @clock.call window_start = now - @window_seconds prune_expired(window_start) return false if !@hits.key?(key) && @hits.size >= MAX_CLIENTS times = @hits[key] || [] times.reject! { |time| time < window_start } return false if times.size >= @max_requests times << now # Keep buckets ordered by their latest accepted hit for expiration. @hits.delete(key) @hits[key] = times true end end |