Class: Sentry::Sidekiq::SentryContextServerMiddleware

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/sentry/sidekiq/sentry_context_middleware.rb

Constant Summary collapse

OP_NAME =
"queue.process"
SPAN_ORIGIN =
"auto.queue.sidekiq"

Instance Method Summary collapse

Methods included from Helpers

#calculate_latency, #now_in_ms, #set_span_data

Instance Method Details

#build_tags(tags) ⇒ Object



81
82
83
# File 'lib/sentry/sidekiq/sentry_context_middleware.rb', line 81

def build_tags(tags)
  Array(tags).each_with_object({}) { |name, tags_hash| tags_hash[:"sidekiq.#{name}"] = true }
end

#call(worker, job, queue) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/sentry/sidekiq/sentry_context_middleware.rb', line 38

def call(worker, job, queue)
  return yield unless Sentry.initialized?

  context_filter = Sentry::Sidekiq::ContextFilter.new(job)

  Sentry.clone_hub_to_current_thread
  scope = Sentry.get_current_scope
  if (user = job["sentry_user"])
    scope.set_user(user)
  end
  scope.set_tags(queue: queue, jid: job["jid"])
  scope.set_tags(build_tags(job["tags"]))
  scope.set_contexts(sidekiq: job.merge("queue" => queue))
  scope.set_transaction_name(context_filter.transaction_name, source: :task)
  transaction = start_transaction(scope, job["trace_propagation_headers"])

  if transaction
    scope.set_span(transaction)

    latency = calculate_latency(job)

    set_span_data(
      transaction,
      id: job["jid"],
      queue: queue,
      latency: latency,
      retry_count: job["retry_count"] || 0
    )
  end

  begin
    yield
  rescue
    finish_transaction(transaction, 500)
    raise
  end

  finish_transaction(transaction, 200)
  # don't need to use ensure here
  # if the job failed, we need to keep the scope for error handler. and the scope will be cleared there
  scope.clear
end

#finish_transaction(transaction, status) ⇒ Object



97
98
99
100
101
102
# File 'lib/sentry/sidekiq/sentry_context_middleware.rb', line 97

def finish_transaction(transaction, status)
  return unless transaction

  transaction.set_http_status(status)
  transaction.finish
end

#start_transaction(scope, env) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
# File 'lib/sentry/sidekiq/sentry_context_middleware.rb', line 85

def start_transaction(scope, env)
  options = {
    name: scope.transaction_name,
    source: scope.transaction_source,
    op: OP_NAME,
    origin: SPAN_ORIGIN
  }

  transaction = Sentry.continue_trace(env, **options)
  Sentry.start_transaction(transaction: transaction, **options)
end