Class: RequestMeter::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/request_meter/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.

Parameters:

  • app (#call)

    the next middleware or Rack app

Raises:



17
18
19
20
21
22
23
24
# File 'lib/request_meter/middleware.rb', line 17

def initialize(app)
  @app = app
  @cache_client = RequestMeter.configuration.cache_client

  return unless @cache_client.nil?

  raise MissingCacheClientError, "Cache client is required"
end

Instance Method Details

#call(env) ⇒ Array

Processes an incoming request, enforces quota limits, and forwards it

Parameters:

  • env (Hash)

    Rack environment

Returns:

  • (Array)

    Rack response triplet



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/request_meter/middleware.rb', line 30

def call(env)
  req = Rack::Request.new(env)
  api_key = req.get_header("HTTP_#{RequestMeter.configuration.api_key_header.upcase.gsub("-", "_")}")

  if api_key.nil? || api_key.empty?
    return [400, { "Content-Type" => "application/json" }, [{ error: "API key is required" }.to_json]]
  end

  quota_limit = RequestMeter.configuration.get_quota_limit(api_key)
  quota_period = RequestMeter.configuration.get_quota_period_seconds(api_key)

  if quota_limit.nil? || quota_period.nil?
    return [400, { "Content-Type" => "application/json" },
            [{ error: "Limits are not configured for the provided token" }.to_json]]
  end

  cache_key = "request_meter:#{api_key}"

  current_count = @cache_client.incr(cache_key)

  @cache_client.expire(cache_key, quota_period) if current_count == 1

  if current_count > quota_limit
    reset_in = @cache_client.ttl(cache_key)
    headers = { "Retry-After" => reset_in.to_s }
    return [429, headers, ["Quota exceeded. Try again in #{reset_in} seconds."]]
  end

  @app.call(env)
end