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



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
88
89
90
91
92
93
94
95
# 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 => exception
    req.error!
    env = {
      :custom_controller => job_class,
      :custom_action => queue
    }
    context = ScoutApm::Agent.instance.context
    context.error_buffer.capture(exception, env)
    raise
  ensure
    req.stop_layer if started_job
    req.stop_layer if started_queue
  end
end

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



100
101
102
103
104
105
106
107
108
109
110
# File 'lib/scout_apm/background_job_integrations/shoryuken.rb', line 100

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