Class: Sidekiq::Throttled::Strategy::Threshold

Inherits:
Object
  • Object
show all
Defined in:
lib/sidekiq/throttled/strategy/threshold.rb

Overview

TODO:

Use redis TIME command instead of sending current timestamp from sidekiq manager. See: redis.io/commands/time

Threshold throttling strategy

Instance Method Summary collapse

Constructor Details

#initialize(strategy_key, opts) ⇒ Threshold

Returns a new instance of Threshold.

Parameters:

  • strategy_key (#to_s)
  • opts (Hash)

Options Hash (opts):

  • :limit (#to_i)

    Amount of jobs allowed per period

  • :period (#to_f)

    Period in seconds



36
37
38
39
40
41
# File 'lib/sidekiq/throttled/strategy/threshold.rb', line 36

def initialize(strategy_key, opts)
  @base_key   = "#{strategy_key}:threshold".freeze
  @limit      = opts.fetch(:limit)
  @period     = opts.fetch(:period)
  @key_suffix = opts[:key_suffix]
end

Instance Method Details

#count(*job_args) ⇒ Integer

Returns Current count of jobs.

Returns:

  • (Integer)

    Current count of jobs



69
70
71
# File 'lib/sidekiq/throttled/strategy/threshold.rb', line 69

def count(*job_args)
  Sidekiq.redis { |conn| conn.llen(key(job_args)) }.to_i
end

#dynamic?Boolean

Returns Whenever strategy has dynamic config.

Returns:

  • (Boolean)

    Whenever strategy has dynamic config



56
57
58
# File 'lib/sidekiq/throttled/strategy/threshold.rb', line 56

def dynamic?
  @key_suffix || @limit.respond_to?(:call) || @period.respond_to?(:call)
end

#limit(job_args = nil) ⇒ Integer

Returns Amount of jobs allowed per period.

Returns:

  • (Integer)

    Amount of jobs allowed per period



44
45
46
47
# File 'lib/sidekiq/throttled/strategy/threshold.rb', line 44

def limit(job_args = nil)
  return @limit.to_i unless @limit.respond_to? :call
  @limit.call(*job_args).to_i
end

#period(job_args = nil) ⇒ Float

Returns Period in seconds.

Returns:

  • (Float)

    Period in seconds



50
51
52
53
# File 'lib/sidekiq/throttled/strategy/threshold.rb', line 50

def period(job_args = nil)
  return @period.to_f unless @period.respond_to? :call
  @period.call(*job_args).to_f
end

#reset!(*job_args) ⇒ void

This method returns an undefined value.

Resets count of jobs



75
76
77
# File 'lib/sidekiq/throttled/strategy/threshold.rb', line 75

def reset!(*job_args)
  Sidekiq.redis { |conn| conn.del(key(job_args)) }
end

#throttled?(*job_args) ⇒ Boolean

Returns whenever job is throttled or not.

Returns:

  • (Boolean)

    whenever job is throttled or not



61
62
63
64
65
66
# File 'lib/sidekiq/throttled/strategy/threshold.rb', line 61

def throttled?(*job_args)
  key = key(job_args)
  limit = limit(job_args)
  period = period(job_args)
  1 == SCRIPT.eval([key], [limit, period, Time.now.to_f])
end