Class: Legion::API::Middleware::RateLimit

Inherits:
Object
  • Object
show all
Defined in:
lib/legion/api/middleware/rate_limit.rb

Defined Under Namespace

Classes: CacheStore, MemoryStore

Constant Summary collapse

SKIP_PATHS =
%w[/api/health /api/ready /api/metrics /api/openapi.json].freeze
WINDOW_SIZE =
60

Instance Method Summary collapse

Constructor Details

#initialize(app, **opts) ⇒ RateLimit

Returns a new instance of RateLimit.



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/legion/api/middleware/rate_limit.rb', line 51

def initialize(app, **opts)
  @app = app
  @enabled = opts.fetch(:enabled, true)
  @limits = {
    per_ip:     opts.fetch(:per_ip, 60),
    per_agent:  opts.fetch(:per_agent, 300),
    per_tenant: opts.fetch(:per_tenant, 3000)
  }
  @store = select_store
  @reap_counter = 0
end

Instance Method Details

#call(env) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/legion/api/middleware/rate_limit.rb', line 63

def call(env)
  return @app.call(env) unless @enabled
  return @app.call(env) if skip_path?(env['PATH_INFO'])

  result = check_limits(env)
  if result[:limited]
    rate_limit_response(result)
  else
    status, headers, body = @app.call(env)
    [status, headers.merge(rate_limit_headers(result)), body]
  end
rescue StandardError => e
  Legion::Logging.warn "RateLimit#call failed, passing through: #{e.message}" if defined?(Legion::Logging)
  @app.call(env)
end