Module: Chronos::Integrations::ActiveJob

Defined in:
lib/chronos/integrations/active_job.rb

Overview

Propagates bounded Chronos context through Active Job serialization.

Examples:

Chronos::Integrations::ActiveJob.install(ActiveJob::Base)

Defined Under Namespace

Modules: JobExtensions

Constant Summary collapse

CONTEXT_KEY =
"chronos_context".freeze
SCHEMA_VERSION =
"1.0".freeze
MAX_IDENTIFIER_BYTES =
128

Class Method Summary collapse

Class Method Details

.context(value) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/chronos/integrations/active_job.rb', line 53

def context(value)
  return {} unless value.is_a?(Hash)
  return {} unless (value["schema_version"] || value[:schema_version]).to_s == SCHEMA_VERSION

  source = value["context"] || value[:context]
  return {} unless source.is_a?(Hash)

  %w(trace_id request_id).each_with_object({}) do |key, result|
    candidate = source[key] || source[key.to_sym]
    result[key] = bounded(candidate) unless candidate.to_s.empty?
  end
rescue StandardError
  {}
end

.envelope(notifier) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/chronos/integrations/active_job.rb', line 40

def envelope(notifier)
  source = notifier.respond_to?(:propagation_context) ? notifier.propagation_context : {}
  source = {} unless source.is_a?(Hash)
  context = %w(trace_id request_id).each_with_object({}) do |key, result|
    value = source[key] || source[key.to_sym]
    result[key] = bounded(value) unless value.to_s.empty?
  end
  context["trace_id"] = SecureRandom.uuid if context["trace_id"].to_s.empty?
  {"schema_version" => SCHEMA_VERSION, "context" => context}
rescue StandardError
  nil
end

.install(base = nil, notifier = Chronos) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/chronos/integrations/active_job.rb', line 25

def install(base = nil, notifier = Chronos)
  target = base || (::ActiveJob::Base if defined?(::ActiveJob::Base))
  return false unless target && target.respond_to?(:prepend)

  @mutex.synchronize do
    return false if target.ancestors.include?(JobExtensions)

    JobExtensions.notifier = notifier
    target.send(:prepend, JobExtensions)
  end
  true
rescue StandardError
  false
end