Class: DeadBro::JobSubscriber

Inherits:
Object
  • Object
show all
Defined in:
lib/dead_bro/job_subscriber.rb

Constant Summary collapse

JOB_EVENT_NAME =
"perform.active_job"
JOB_EXCEPTION_EVENT_NAME =
"exception.active_job"

Class Method Summary collapse

Class Method Details

.drain_job_trackingObject

Release job-side thread-local tracking state when we’ve decided not to build a payload (excluded job / sampled out). Matches Subscriber.drain_request_tracking.



196
197
198
199
200
201
202
203
204
# File 'lib/dead_bro/job_subscriber.rb', line 196

def self.drain_job_tracking
  DeadBro::SqlSubscriber.stop_request_tracking if defined?(DeadBro::SqlSubscriber)
  DeadBro::LightweightMemoryTracker.stop_request_tracking if defined?(DeadBro::LightweightMemoryTracker)
  if DeadBro.configuration.allocation_tracking_enabled && defined?(DeadBro::MemoryTrackingSubscriber)
    DeadBro::MemoryTrackingSubscriber.stop_request_tracking
  end
rescue
  # Best effort
end

.gc_statsObject



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/dead_bro/job_subscriber.rb', line 256

def self.gc_stats
  if defined?(GC) && GC.respond_to?(:stat)
    stats = GC.stat
    {
      count: stats[:count] || 0,
      heap_allocated_pages: stats[:heap_allocated_pages] || 0,
      heap_sorted_pages: stats[:heap_sorted_pages] || 0,
      total_allocated_objects: stats[:total_allocated_objects] || 0
    }
  else
    {}
  end
rescue
  {}
end

.memory_usage_mbObject



250
251
252
253
254
# File 'lib/dead_bro/job_subscriber.rb', line 250

def self.memory_usage_mb
  DeadBro::MemoryHelpers.rss_mb
rescue
  0
end

.safe_arguments(arguments) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/dead_bro/job_subscriber.rb', line 208

def self.safe_arguments(arguments)
  return [] unless arguments.is_a?(Array)

  # Limit and sanitize job arguments
  arguments.first(10).map do |arg|
    case arg
    when String
      (arg.length > 200) ? arg[0, 200] + "..." : arg
    when Hash
      # Filter sensitive keys and limit size
      filtered = arg.except(*%w[password token secret key])
      (filtered.keys.size > 20) ? filtered.first(20).to_h : filtered
    when Array
      arg.first(5)
    when ActiveRecord::Base
      # Handle ActiveRecord objects safely
      "#{arg.class.name}##{begin
        arg.id
      rescue
        "unknown"
      end}"
    else
      # Convert to string and truncate, but avoid object inspection
      (arg.to_s.length > 200) ? arg.to_s[0, 200] + "..." : arg.to_s
    end
  end
rescue
  []
end

.safe_hostObject



238
239
240
241
242
243
244
245
246
247
248
# File 'lib/dead_bro/job_subscriber.rb', line 238

def self.safe_host
  if defined?(Rails) && Rails.respond_to?(:application)
    begin
      Rails.application.class.module_parent_name
    rescue
      ""
    end
  else
    ""
  end
end

.subscribe!(client: Client.new) ⇒ 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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/dead_bro/job_subscriber.rb', line 14

def self.subscribe!(client: Client.new)
  # Track job execution
  ActiveSupport::Notifications.subscribe(JOB_EVENT_NAME) do |name, started, finished, _unique_id, data|
    begin
      job_class_name = data[:job].class.name
      if DeadBro.configuration.excluded_job?(job_class_name)
        drain_job_tracking
        next
      end
      # If exclusive_jobs is defined and not empty, only track matching jobs
      unless DeadBro.configuration.exclusive_job?(job_class_name)
        drain_job_tracking
        next
      end
    rescue
    end

    # Skip out via sampling before we build any payload — jobs can be chatty
    # enough that even the "cheap" stop/analyze work matters under load.
    # Completions have no exception attached; the exception subscriber below
    # always sends errors with force: true.
    unless DeadBro.configuration.should_sample?
      drain_job_tracking
      next
    end

    duration_ms = ((finished - started) * 1000.0).round(2)

    # Ensure tracking was started (fallback if perform_start.active_job didn't fire)
    # This handles job backends that don't emit perform_start events
    unless DeadBro::SqlSubscriber.tracking_active?
      DeadBro.logger.clear
      Thread.current[DeadBro::TRACKING_START_TIME_KEY] = Time.now
      DeadBro::SqlSubscriber.start_request_tracking
      if DeadBro.configuration.allocation_tracking_enabled && defined?(DeadBro::MemoryTrackingSubscriber)
        DeadBro::MemoryTrackingSubscriber.start_request_tracking
      else
        DeadBro::LightweightMemoryTracker.start_request_tracking if defined?(DeadBro::LightweightMemoryTracker)
      end
    end

    # Get SQL queries executed during this job
    sql_queries = DeadBro::SqlSubscriber.stop_request_tracking

    # Stop memory tracking and get collected memory data
    if DeadBro.configuration.allocation_tracking_enabled && defined?(DeadBro::MemoryTrackingSubscriber)
      detailed_memory = DeadBro::MemoryTrackingSubscriber.stop_request_tracking
      memory_performance = DeadBro::MemoryTrackingSubscriber.analyze_memory_performance(detailed_memory)
      # Keep memory_events compact and user-friendly (no large raw arrays)
      memory_events = {
        memory_before: detailed_memory[:memory_before],
        memory_after: detailed_memory[:memory_after],
        duration_seconds: detailed_memory[:duration_seconds],
        allocations_count: (detailed_memory[:allocations] || []).length,
        memory_snapshots_count: (detailed_memory[:memory_snapshots] || []).length,
        large_objects_count: (detailed_memory[:large_objects] || []).length
      }
    else
      lightweight_memory = DeadBro::LightweightMemoryTracker.stop_request_tracking
      # Separate raw readings from derived performance metrics to avoid duplicating data
      memory_events = {
        memory_before: lightweight_memory[:memory_before],
        memory_after: lightweight_memory[:memory_after]
      }
      memory_performance = {
        memory_growth_mb: lightweight_memory[:memory_growth_mb],
        gc_count_increase: lightweight_memory[:gc_count_increase],
        heap_pages_increase: lightweight_memory[:heap_pages_increase],
        duration_seconds: lightweight_memory[:duration_seconds]
      }
    end

    payload = {
      job_class: data[:job].class.name,
      job_id: data[:job].job_id,
      queue_name: data[:job].queue_name,
      arguments: safe_arguments(data[:job].arguments),
      duration_ms: duration_ms,
      status: "completed",
      sql_queries: sql_queries,
      rails_env: DeadBro.env,
      host: safe_host,
      memory_usage: memory_usage_mb,
      gc_stats: gc_stats,
      memory_events: memory_events,
      memory_performance: memory_performance,
      logs: DeadBro.logger.logs
    }

    client.post_metric(event_name: name, payload: payload)
  end

  # Track job exceptions
  ActiveSupport::Notifications.subscribe(JOB_EXCEPTION_EVENT_NAME) do |name, started, finished, _unique_id, data|
    begin
      job_class_name = data[:job].class.name
      if DeadBro.configuration.excluded_job?(job_class_name)
        next
      end
      # If exclusive_jobs is defined and not empty, only track matching jobs
      unless DeadBro.configuration.exclusive_job?(job_class_name)
        next
      end
    rescue
    end

    duration_ms = ((finished - started) * 1000.0).round(2)
    exception = data[:exception_object]
    data[:job].class.name

    # Ensure tracking was started (fallback if perform_start.active_job didn't fire)
    unless DeadBro::SqlSubscriber.tracking_active?
      DeadBro.logger.clear
      Thread.current[DeadBro::TRACKING_START_TIME_KEY] = Time.now
      DeadBro::SqlSubscriber.start_request_tracking
      if DeadBro.configuration.allocation_tracking_enabled && defined?(DeadBro::MemoryTrackingSubscriber)
        DeadBro::MemoryTrackingSubscriber.start_request_tracking
      else
        DeadBro::LightweightMemoryTracker.start_request_tracking if defined?(DeadBro::LightweightMemoryTracker)
      end
    end

    # Get SQL queries executed during this job
    sql_queries = DeadBro::SqlSubscriber.stop_request_tracking

    # Stop memory tracking and get collected memory data
    if DeadBro.configuration.allocation_tracking_enabled && defined?(DeadBro::MemoryTrackingSubscriber)
      detailed_memory = DeadBro::MemoryTrackingSubscriber.stop_request_tracking
      memory_performance = DeadBro::MemoryTrackingSubscriber.analyze_memory_performance(detailed_memory)
      # Keep memory_events compact and user-friendly (no large raw arrays)
      memory_events = {
        memory_before: detailed_memory[:memory_before],
        memory_after: detailed_memory[:memory_after],
        duration_seconds: detailed_memory[:duration_seconds],
        allocations_count: (detailed_memory[:allocations] || []).length,
        memory_snapshots_count: (detailed_memory[:memory_snapshots] || []).length,
        large_objects_count: (detailed_memory[:large_objects] || []).length
      }
    else
      lightweight_memory = DeadBro::LightweightMemoryTracker.stop_request_tracking
      # Separate raw readings from derived performance metrics to avoid duplicating data
      memory_events = {
        memory_before: lightweight_memory[:memory_before],
        memory_after: lightweight_memory[:memory_after]
      }
      memory_performance = {
        memory_growth_mb: lightweight_memory[:memory_growth_mb],
        gc_count_increase: lightweight_memory[:gc_count_increase],
        heap_pages_increase: lightweight_memory[:heap_pages_increase],
        duration_seconds: lightweight_memory[:duration_seconds]
      }
    end

    payload = {
      job_class: data[:job].class.name,
      job_id: data[:job].job_id,
      queue_name: data[:job].queue_name,
      arguments: safe_arguments(data[:job].arguments),
      duration_ms: duration_ms,
      status: "failed",
      sql_queries: sql_queries,
      exception_class: exception&.class&.name,
      message: exception&.message&.to_s&.[](0, 1000),
      backtrace: Array(exception&.backtrace).first(50),
      rails_env: DeadBro.env,
      host: safe_host,
      memory_usage: memory_usage_mb,
      gc_stats: gc_stats,
      memory_events: memory_events,
      memory_performance: memory_performance,
      logs: DeadBro.logger.logs
    }

    event_name = exception&.class&.name || "ActiveJob::Exception"
    client.post_metric(event_name: event_name, payload: payload, force: true)
  end
rescue
  # Never raise from instrumentation install
end