Class: GoodJob::ActiveJobExtensions::Concurrency::Rule

Inherits:
Object
  • Object
show all
Defined in:
lib/good_job/active_job_extensions/concurrency.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Rule

Returns a new instance of Rule.



19
20
21
# File 'lib/good_job/active_job_extensions/concurrency.rb', line 19

def initialize(config)
  @config = config
end

Instance Method Details

#evaluate(job, stage) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/good_job/active_job_extensions/concurrency.rb', line 23

def evaluate(job, stage)
  key = key(job)
  label = label(job)
  return nil if key.blank? && label.blank?

  if stage == :enqueue
    enqueue_limit = limit(job, :enqueue_limit) || limit(job, :total_limit)
    enqueue_throttle = throttle(job, :enqueue_throttle)
    return nil unless enqueue_limit || enqueue_throttle

    check_enqueue(enqueue_limit, enqueue_throttle, job, key, label, enqueue_limit_flag: @config[:enqueue_limit].present?)
  elsif stage == :perform
    perform_limit = limit(job, :perform_limit) || limit(job, :total_limit)
    perform_throttle = throttle(job, :perform_throttle)
    return nil unless perform_limit || perform_throttle

    check_perform(perform_limit, perform_throttle, job, key, label)
  end
end

#key(job) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/good_job/active_job_extensions/concurrency.rb', line 43

def key(job)
  key_spec = @config[:key]
  if key_spec.blank?
    "label:#{label(job)}"
  else
    key_value = key_spec.respond_to?(:call) ? job.instance_exec(&key_spec) : key_spec
    raise TypeError, "Concurrency key must be a String; was a #{key_value.class}" if key_value.present? && VALID_TYPES.none? { |type| key_value.is_a?(type) }

    key_value
  end
end

#label(job) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/good_job/active_job_extensions/concurrency.rb', line 55

def label(job)
  label_spec = @config[:label]

  return if label_spec.blank?

  label_spec.respond_to?(:call) ? job.instance_exec(&label_spec) : label_spec
end

#limit(job, limit_name) ⇒ Object



63
64
65
66
67
68
69
70
# File 'lib/good_job/active_job_extensions/concurrency.rb', line 63

def limit(job, limit_name)
  value = @config[limit_name]
  return nil if value.nil?

  value = job.instance_exec(&value) if value.respond_to?(:call)
  value = nil unless value.present? && (0...Float::INFINITY).cover?(value)
  value
end

#throttle(job, throttle_name) ⇒ Object



72
73
74
75
76
77
78
79
# File 'lib/good_job/active_job_extensions/concurrency.rb', line 72

def throttle(job, throttle_name)
  value = @config[throttle_name]
  return nil if value.nil?

  value = job.instance_exec(&value) if value.respond_to?(:call)
  value = nil unless value.present? && value.is_a?(Array) && value.size == 2
  value
end