Class: RosettAi::Mcp::Middleware::RateLimit

Inherits:
Object
  • Object
show all
Defined in:
lib/rosett_ai/mcp/middleware/rate_limit.rb

Overview

Rack middleware for token bucket rate limiting.

Per-IP/per-key rate limiting with separate limits for authenticated and unauthenticated requests. Returns 429 Too Many Requests when exhausted.

Author:

  • hugo

  • claude

Constant Summary collapse

DEFAULT_UNAUTH_RPM =
60
DEFAULT_AUTH_RPM =
300
BUCKET_WINDOW =

seconds

60
CLEANUP_INTERVAL =
100

Instance Method Summary collapse

Constructor Details

#initialize(app, config: nil) ⇒ RateLimit

Returns a new instance of RateLimit.

Parameters:

  • app (#call)

    the next Rack application

  • config (#unauthenticated_rpm, #authenticated_rpm) (defaults to: nil)

    rate config



25
26
27
28
29
30
31
32
# File 'lib/rosett_ai/mcp/middleware/rate_limit.rb', line 25

def initialize(app, config: nil)
  @app = app
  @unauth_rpm = config.respond_to?(:unauthenticated_rpm) ? config.unauthenticated_rpm : DEFAULT_UNAUTH_RPM
  @auth_rpm = config.respond_to?(:authenticated_rpm) ? config.authenticated_rpm : DEFAULT_AUTH_RPM
  @buckets = {}
  @mutex = Mutex.new
  @request_count = 0
end

Instance Method Details

#call(env) ⇒ Array

Returns Rack response triplet.

Parameters:

  • env (Hash)

    Rack environment

Returns:

  • (Array)

    Rack response triplet



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rosett_ai/mcp/middleware/rate_limit.rb', line 36

def call(env)
  key = bucket_key(env)
  limit = rate_limit_for(env)

  if allowed?(key, limit)
    @app.call(env)
  else
    SecurityLogger.rate_limited(key)
    too_many_requests
  end
end