Class: RailsAiBridge::Mcp::HttpRateLimiter

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(max_requests:, window_seconds:, clock: nil) ⇒ HttpRateLimiter

Returns a new instance of HttpRateLimiter.

Parameters:

  • max_requests (Integer) —

    allowed hits per window (must be positive)

  • window_seconds (Integer) —

    window length in seconds

  • clock (Proc, nil) (defaults to: nil) —

    -> { Float } seconds timestamp; defaults to monotonic clock



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.

Parameters:

  • ip (String, nil) —

    client identifier (blank values share the unknown bucket)

Returns:

  • (Boolean) —

    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