class Sidekiq::Throttled::Strategy::Threshold

Threshold throttling strategy @todo Use redis TIME command instead of sending current timestamp from

sidekiq manager. See: http://redis.io/commands/time

Constants

SCRIPT

LUA script used to limit fetch threshold. Logic behind the scene can be described in following pseudo code:

def exceeded?
  limit <= LLEN(@key) && NOW - LINDEX(@key, -1) < @period
end

def increase!
  LPUSH(@key, NOW)
  LTRIM(@key, 0, @limit - 1)
  EXPIRE(@key, @period)
end

return 1 if exceeded?

increase!
return 0

Public Class Methods

new(strategy_key, limit:, period:, key_suffix: nil) click to toggle source

@param [#to_s] strategy_key @param [#to_i, call] limit Amount of allowed concurrent jobs

per period running for given key.

@param [#to_f, call] :period Period in seconds. @param [Proc] key_suffix Dynamic key suffix generator.

# File lib/sidekiq/throttled/strategy/threshold.rb, line 41
def initialize(strategy_key, limit:, period:, key_suffix: nil)
  @base_key   = "#{strategy_key}:threshold"
  @limit      = limit
  @period     = period
  @key_suffix = key_suffix
end

Public Instance Methods

count(*job_args) click to toggle source

@return [Integer] Current count of jobs

# File lib/sidekiq/throttled/strategy/threshold.rb, line 75
def count(*job_args)
  Sidekiq.redis { |conn| conn.llen(key(job_args)) }.to_i
end
dynamic?() click to toggle source

@return [Boolean] Whenever strategy has dynamic config

# File lib/sidekiq/throttled/strategy/threshold.rb, line 56
def dynamic?
  @key_suffix || @limit.respond_to?(:call) || @period.respond_to?(:call)
end
period(job_args = nil) click to toggle source

@return [Float] Period in seconds

# File lib/sidekiq/throttled/strategy/threshold.rb, line 49
def period(job_args = nil)
  return @period.to_f unless @period.respond_to? :call

  @period.call(*job_args).to_f
end
reset!(*job_args) click to toggle source

Resets count of jobs @return [void]

# File lib/sidekiq/throttled/strategy/threshold.rb, line 81
def reset!(*job_args)
  Sidekiq.redis { |conn| conn.del(key(job_args)) }
end
throttled?(*job_args) click to toggle source

@return [Boolean] whenever job is throttled or not

# File lib/sidekiq/throttled/strategy/threshold.rb, line 61
def throttled?(*job_args)
  job_limit = limit(job_args)
  return false unless job_limit
  return true if job_limit <= 0

  keys = [key(job_args)]
  argv = [job_limit, period(job_args), Time.now.to_f]

  Sidekiq.redis do |redis|
    1 == SCRIPT.eval(redis, :keys => keys, :argv => argv)
  end
end