Class: Koderift::Rails::SidekiqMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/koderift/rails/sidekiq_middleware.rb

Overview

Sidekiq server middleware that wraps each job in Instrumentation.capture and writes a single JSON line to Rails.logger. The koderift-agent picks this up via the existing Rails log tailer — the "job_class" key distinguishes it from Lograge request lines.

Instance Method Summary collapse

Instance Method Details

#call(worker, job, queue) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/koderift/rails/sidekiq_middleware.rb', line 14

def call(worker, job, queue)
  config = Koderift::Rails.configuration
  return yield unless config.enabled && config.project_token.present?

  trace_id = job['koderift_trace_id'].to_s
  trace_id = SecureRandom.uuid if trace_id.empty?
  Thread.current[:koderift_trace_id] = trace_id

  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  begin
    result = Instrumentation.capture { yield }
    duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round
    emit_job_log(worker, job, queue, result, duration_ms, trace_id, error: nil)
    result
  rescue StandardError => e
    duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round
    empty_result = { spans: [], query_count: 0, partial_count: 0,
                     search_count: 0, breadcrumbs: [] }
    emit_job_log(worker, job, queue, empty_result, duration_ms, trace_id, error: e)
    raise
  ensure
    Thread.current[:koderift_trace_id] = nil
  end
end