Sha256: 90a1c0850903d616e4aa83e16ec8fec85e4bb0e945837e4bee6736a007e8726a

Contents?: true

Size: 954 Bytes

Versions: 1

Compression:

Stored size: 954 Bytes

Contents

require 'pause/helper/timing'

module Pause
  class Analyzer
    include Pause::Helper::Timing

    def check(action)
      timestamp = period_marker(Pause.config.resolution, Time.now.to_i)
      set = adapter.key_history(action.key)
      action.checks.each do |period_check|
        start_time = timestamp - period_check.period_seconds
        set.reverse.inject(0) do |sum, element|
          break if element.ts < start_time
          sum += element.count
          if sum >= period_check.max_allowed
            adapter.rate_limit!(action.key, period_check.block_ttl)
            # Note that Time.now is different from period_marker(resolution, Time.now), which
            # rounds down to the nearest (resolution) seconds
            return Pause::RateLimitedEvent.new(action, period_check, sum, Time.now.to_i)
          end
          sum
        end
      end
      nil
    end

    private

    def adapter
      Pause.adapter
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pause-0.0.6 lib/pause/analyzer.rb