Sha256: d187642aba95d1b97589f4ecc53dfaebecb3150567d7d45ee05927bf5a8a3e46

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

Contents

require 'digest'

module Prorate
  class Throttle < Ks.strict(:name, :limit, :period, :block_for, :redis, :logger)
    def initialize(*)
      super
      @discriminators = [name.to_s]
      self.redis = NullPool.new(redis) unless redis.respond_to?(:with)
    end
    
    def <<(discriminator)
      @discriminators << discriminator
    end
    
    def throttle!
      discriminator = Digest::SHA1.hexdigest(Marshal.dump(@discriminators))
      identifier = [name, discriminator].join(':')
      
      redis.with do |r|
        logger.info { "Checking throttle block %s" % name }
        raise Throttled.new(block_for) if Prorate::BlockFor.blocked?(id: identifier, redis: r)

        logger.info { "Applying throttle counter %s" % name }
        c = Prorate::Counter.new(redis: r, id: identifier, logger: logger, window_size: period)
        after_increment = c.incr
        if after_increment > limit
          logger.warn { "Throttle %s exceeded limit of %d at %d" % [name, limit, after_increment] }
          Prorate::BlockFor.block!(redis: r, id: identifier, duration: block_for)
          raise Throttled.new(period)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
prorate-0.1.0 lib/prorate/throttle.rb