class ScoutApm::BackgroundJobIntegrations::ShoryukenMiddleware

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

Constants

ACTIVE_JOB_KLASS
UNKNOWN_CLASS_PLACEHOLDER

Public Instance Methods

call(worker_instance, queue, msg, body) { || ... } click to toggle source
# File lib/scout_apm/background_job_integrations/shoryuken.rb, line 60
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) click to toggle source
# File lib/scout_apm/background_job_integrations/shoryuken.rb, line 94
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