Class: ScoutApm::BackgroundJobIntegrations::ShoryukenMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/scout_apm/background_job_integrations/shoryuken.rb

Overview

We insert this middleware into the Shoryuken stack, to capture each job, and time them.

Constant Summary collapse

UNKNOWN_CLASS_PLACEHOLDER =
'UnknownJob'.freeze
ACTIVE_JOB_KLASS =
'ActiveJob::QueueAdapters::ShoryukenAdapter::JobWrapper'.freeze

Instance Method Summary collapse

Instance Method Details

#call(worker_instance, queue, msg, body) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/scout_apm/background_job_integrations/shoryuken.rb', line 58

def call(worker_instance, queue, msg, body)
  job_class =
    begin
      if worker_instance.class.to_s == ACTIVE_JOB_KLASS
        body["job_class"]
      else
        worker_instance.class.to_s
      end
    rescue
      UNKNOWN_CLASS_PLACEHOLDER
    end

  req = ScoutApm::RequestManager.lookup
  req.annotate_request(:queue_latency => latency(msg))

  begin
    req.start_layer(ScoutApm::Layer.new('Queue', queue))
    started_queue = true
    req.start_layer(ScoutApm::Layer.new('Job', job_class))
    started_job = true

    yield
  rescue Exception => e
    req.error!
    raise
  ensure
    req.stop_layer if started_job
    req.stop_layer if started_queue
  end
end

#latency(msg, time = Time.now.to_f) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
# File 'lib/scout_apm/background_job_integrations/shoryuken.rb', line 92

def latency(msg, time = Time.now.to_f)
  ms_since_epoch_str = msg.attributes.fetch('SentTimestamp', 0)
  return 0 if ms_since_epoch_str.nil?

  # Convert from ms to seconds as a float
  created_at = ms_since_epoch_str.to_i / 1000.0

  time - created_at
rescue => e
  0
end