Class: GrapeThrottler::Middleware::ThrottleMiddleware

Inherits:
Grape::Middleware::Base
  • Object
show all
Defined in:
lib/grape-throttler/middleware/throttle_middleware.rb

Constant Summary collapse

COUNTER_START =
0

Instance Method Summary collapse

Instance Method Details

#beforeObject

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength rubocop:disable Metrics/PerceivedComplexity, Lint/AssignmentInCondition



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/grape-throttler/middleware/throttle_middleware.rb', line 11

def before
  endpoint = env['api.endpoint']
  logger = options[:logger] || Logger.new($stdout)

  return unless throttle_options = endpoint.route_setting(:throttle)

  limit, period = find_limit_and_period(throttle_options)

  check_limit_and_period(limit, period)

  limit = limit.call(env) if limit.is_a?(Proc)
  return true if limit.negative?

  user_value = find_user_value(options) || "ip:#{env['REMOTE_ADDR']}"
  rate_key = generate_rate_key(endpoint, user_value)

  begin
    redis = options[:cache]
    redis.ping

    current = redis.get(rate_key).to_i

    if !current.nil? && current >= limit
      endpoint.error!('Too Many Requests', 429)
    else
      redis.multi do
        redis.set(rate_key, COUNTER_START, nx: true, ex: period.to_i)
        redis.incr(rate_key)
      end
    end
  rescue StandardError => e
    logger.warn(e.message)
  end
end