Class: UserPattern::RateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/userpattern/rate_limiter.rb

Overview

Checks per-user request rates against the limits from ThresholdCache. Counters are stored in an ActiveSupport::Cache::Store (same interface as Rack::Attack), giving multi-process support via Redis/Memcached.

Constant Summary collapse

PERIODS =
{
  minute: { format: '%Y-%m-%dT%H:%M', ttl: 120 },
  hour: { format: '%Y-%m-%dT%H', ttl: 7_200 },
  day: { format: '%Y-%m-%d', ttl: 172_800 }
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(store:, threshold_cache:) ⇒ RateLimiter

Returns a new instance of RateLimiter.



16
17
18
19
# File 'lib/userpattern/rate_limiter.rb', line 16

def initialize(store:, threshold_cache:)
  @store = store
  @threshold_cache = threshold_cache
end

Instance Method Details

#check_and_increment!(user_id, model_type, endpoint) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/userpattern/rate_limiter.rb', line 21

def check_and_increment!(user_id, model_type, endpoint)
  limits = @threshold_cache.limits_for(model_type, endpoint)

  if limits.nil?
    return unless UserPattern.configuration.block_unknown_endpoints

    raise_threshold_exceeded(endpoint, user_id, model_type, 'unknown', 1, 0)
  end

  PERIODS.each do |period, config|
    check_period!(user_id, model_type, endpoint, period, config[:format], limits)
  end
end