Class: RailsAiBridge::Mcp::CacheRateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_ai_bridge/mcp/cache_rate_limiter.rb

Overview

Distributed, fixed-window rate limiter backed by Rails.cache (or any ActiveSupport::Cache::Store). Use it when the MCP HTTP endpoint runs behind multiple processes and the default in-memory limiter is insufficient.

The limiter relies on the cache's increment operation when available and falls back to read/write for stores that do not support atomic increments.

Instance Method Summary collapse

Constructor Details

#initialize(max_requests:, window_seconds:, cache: nil, key_prefix: 'rab:rl') ⇒ CacheRateLimiter

Returns a new instance of CacheRateLimiter.

Parameters:

  • max_requests (Integer)

    allowed hits per window per client IP

  • window_seconds (Integer)

    TTL for each client's counter

  • cache (Object, nil) (defaults to: nil)

    ActiveSupport::Cache::Store; defaults to Rails.cache

  • key_prefix (String) (defaults to: 'rab:rl')

    prefix for cache keys



16
17
18
19
20
21
# File 'lib/rails_ai_bridge/mcp/cache_rate_limiter.rb', line 16

def initialize(max_requests:, window_seconds:, cache: nil, key_prefix: 'rab:rl')
  @max_requests = max_requests
  @window_seconds = window_seconds.to_i
  @cache = cache
  @key_prefix = key_prefix
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



25
26
27
28
29
30
31
32
# File 'lib/rails_ai_bridge/mcp/cache_rate_limiter.rb', line 25

def allow?(ip)
  store = cache_store
  return true unless store

  key = cache_key(ip)
  count = increment(store, key)
  count <= @max_requests
end