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.

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



10
11
12
13
14
15
16
# File 'lib/rails_ai_bridge/mcp/http_rate_limiter.rb', line 10

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 = Hash.new { |h, k| h[k] = [] }
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



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rails_ai_bridge/mcp/http_rate_limiter.rb', line 20

def allow?(ip)
  key = ip.to_s.presence || 'unknown'
  now = @clock.call
  window_start = now - @window_seconds

  @mutex.synchronize do
    times = @hits[key]
    times.reject! { |t| t < window_start }
    # Drop stale keys so unique IPs that stop requesting do not grow @hits forever.
    @hits.delete(key) if times.empty?

    times = @hits[key]
    return false if times.size >= @max_requests

    times << now
    true
  end
end