Class: Profiler::JobProfiler

Inherits:
Object
  • Object
show all
Defined in:
lib/profiler/job_profiler.rb

Constant Summary collapse

JOB_COLLECTOR_CLASSES =
[
  Collectors::DatabaseCollector,
  Collectors::CacheCollector,
  Collectors::HttpCollector
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(job_class:, job_id:, queue:, arguments:, executions:) ⇒ JobProfiler

Returns a new instance of JobProfiler.



29
30
31
32
33
34
35
# File 'lib/profiler/job_profiler.rb', line 29

def initialize(job_class:, job_id:, queue:, arguments:, executions:)
  @job_class = job_class
  @job_id = job_id
  @queue = queue
  @arguments = arguments
  @executions = executions
end

Class Method Details

.profile(job_class:, job_id:, queue:, arguments:, executions:, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/profiler/job_profiler.rb', line 17

def self.profile(job_class:, job_id:, queue:, arguments:, executions:, &block)
  return block.call unless Profiler.enabled? && Profiler.configuration.track_jobs

  new(
    job_class: job_class,
    job_id: job_id,
    queue: queue,
    arguments: arguments,
    executions: executions
  ).run(&block)
end

Instance Method Details

#run(&block) ⇒ Object



37
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
80
81
82
83
84
85
# File 'lib/profiler/job_profiler.rb', line 37

def run(&block)
  profile = Models::Profile.new
  profile.profile_type = "job"
  profile.path = @job_class
  profile.method = "JOB"

  job_collector = Collectors::JobCollector.new(profile, {
    job_class: @job_class,
    job_id: @job_id,
    queue: @queue,
    arguments: sanitize_arguments(@arguments),
    executions: @executions
  })

  collectors = [job_collector] + JOB_COLLECTOR_CLASSES.map { |klass| klass.new(profile) }
  collectors.each { |c| c.subscribe if c.respond_to?(:subscribe) }

  memory_before = current_memory if Profiler.configuration.track_memory

  job_status = "completed"
  error_message = nil

  begin
    result = block.call
    result
  rescue => e
    job_status = "failed"
    error_message = "#{e.class}: #{e.message}"
    raise
  ensure
    if Profiler.configuration.track_memory
      profile.memory = current_memory - memory_before
    end

    job_collector.update_status(job_status, error_message)
    profile.finish(job_status == "completed" ? 200 : 500)

    collectors.each do |collector|
      begin
        collector.collect if collector.respond_to?(:collect)
        profile.(collector)
      rescue => e
        warn "Profiler JobProfiler: Collector #{collector.class} failed: #{e.message}"
      end
    end

    Profiler.storage.save(profile.token, profile)
  end
end