Class: DeadBro::Subscriber

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

Constant Summary collapse

EVENT_NAME =
"process_action.action_controller"
SENSITIVE_SEGMENT_RE =

Matched against a key segment (delimited by start/end, underscore, dash, or bracket) so nested and prefixed/suffixed keys are caught — e.g. user, access_token, client_secret — without redacting innocent keys like passenger_count or cardinality.

/(?:\A|[_\-\[])(password|passwd|secret|token|api_?key|access_?key|auth|authorization|credential|ssn|credit_?card|card_?number|cvv|cvc)(?:\z|[_\-\]])/i

Class Method Summary collapse

Class Method Details

.build_cause_chain(exception) ⇒ Object



469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/dead_bro/subscriber.rb', line 469

def self.build_cause_chain(exception)
  return [] unless exception
  chain = []
  cause = exception.cause
  depth = 0
  while cause && depth < 5
    chain << {
      exception_class: cause.class.name,
      message: cause.message.to_s[0, 500],
      backtrace_top: Array(cause.backtrace).first(3)
    }
    cause = cause.cause
    depth += 1
  end
  chain
rescue
  []
end

.cache_hits(data) ⇒ Object



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'lib/dead_bro/subscriber.rb', line 413

def self.cache_hits(data)
  if data[:cache_hits]
    data[:cache_hits]
  elsif defined?(Rails) && Rails.cache.respond_to?(:stats)
    begin
      Rails.cache.stats[:hits]
    rescue
      0
    end
  else
    0
  end
rescue
  0
end

.cache_misses(data) ⇒ Object



429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/dead_bro/subscriber.rb', line 429

def self.cache_misses(data)
  if data[:cache_misses]
    data[:cache_misses]
  elsif defined?(Rails) && Rails.cache.respond_to?(:stats)
    begin
      Rails.cache.stats[:misses]
    rescue
      0
    end
  else
    0
  end
rescue
  0
end

.compute_error_fingerprint(exception) ⇒ Object



460
461
462
463
464
465
466
467
# File 'lib/dead_bro/subscriber.rb', line 460

def self.compute_error_fingerprint(exception)
  return nil unless exception
  top_frame = Array(exception.backtrace).first.to_s.gsub(/:\d+:in /, ":N:in ")
  input = "#{exception.class.name}|#{normalize_error_message(exception.message)}|#{top_frame}"
  Digest::SHA256.hexdigest(input)[0, 16]
rescue
  nil
end

.drain_request_trackingObject

Release per-subscriber thread-local state when we've decided not to build a payload (disabled / excluded / sampled out). Without this, a subsequent request reusing the same Puma thread would see stale queries/events.



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/dead_bro/subscriber.rb', line 237

def self.drain_request_tracking
  # wait_for_explains: false — the result is discarded, so don't block this
  # thread waiting on pending EXPLAIN plans.
  DeadBro::SqlSubscriber.stop_request_tracking(wait_for_explains: false) if defined?(DeadBro::SqlSubscriber)
  DeadBro::CacheSubscriber.stop_request_tracking if defined?(DeadBro::CacheSubscriber)
  DeadBro::RedisSubscriber.stop_request_tracking if defined?(DeadBro::RedisSubscriber)
  DeadBro::ElasticsearchSubscriber.stop_request_tracking if defined?(DeadBro::ElasticsearchSubscriber)
  DeadBro::ViewRenderingSubscriber.stop_request_tracking if defined?(DeadBro::ViewRenderingSubscriber)
  DeadBro::LightweightMemoryTracker.stop_request_tracking if defined?(DeadBro::LightweightMemoryTracker)
  DeadBro::MemoryPhaseTracker.stop_request_tracking if defined?(DeadBro::MemoryPhaseTracker)
  if Thread.current[:dead_bro_alloc_active]
    DeadBro::MemoryTrackingSubscriber.stop_request_tracking if defined?(DeadBro::MemoryTrackingSubscriber)
    DeadBro::AllocationSourceSampler.stop if defined?(DeadBro::AllocationSourceSampler)
  end
  Thread.current[:dead_bro_alloc_active] = nil
  Thread.current[:dead_bro_http_events] = nil
  DeadBro::DbConnectionSubscriber.stop_request_tracking if defined?(DeadBro::DbConnectionSubscriber)
  DeadBro::GcTracker.stop_request_tracking if defined?(DeadBro::GcTracker)
  DeadBro::ArObjectTracker.stop_request_tracking if defined?(DeadBro::ArObjectTracker)
  DeadBro::CpuTracker.stop_request_tracking if defined?(DeadBro::CpuTracker)
rescue
  # Best effort — draining must never raise from the notifications callback.
end

.extract_user_id(data) ⇒ Object



445
446
447
448
449
# File 'lib/dead_bro/subscriber.rb', line 445

def self.extract_user_id(data)
  data[:headers].env["warden"].user.id
rescue
  nil
end

.gc_statsObject



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/dead_bro/subscriber.rb', line 379

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



373
374
375
376
377
# File 'lib/dead_bro/subscriber.rb', line 373

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

.normalize_error_message(msg) ⇒ Object



451
452
453
454
455
456
457
458
# File 'lib/dead_bro/subscriber.rb', line 451

def self.normalize_error_message(msg)
  msg.to_s
    .gsub(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i, "UUID")
    .gsub(/\b\d+\b/, "N")
    .gsub(/"[^"]*"/, '"?"')
    .gsub(/'[^']*'/, "'?'")
    .strip
end

.safe_params(data) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/dead_bro/subscriber.rb', line 268

def self.safe_params(data)
  return {} unless data[:params]

  params = data[:params]
  begin
    params = params.to_unsafe_h if params.respond_to?(:to_unsafe_h)
  rescue
  end

  unless params.is_a?(Hash)
    return {}
  end

  # Remove router-provided keys that we already send at top-level
  router_keys = %w[controller action format]

  filtered = params.dup
  router_keys.each { |k| filtered.delete(k) || filtered.delete(k.to_sym) }

  # Truncate deeply to keep payload small and safe. truncate_value also redacts
  # sensitive keys at every nesting level (e.g. user[password]).
  truncate_value(filtered)
rescue
  {}
end

.safe_path(data) ⇒ Object



261
262
263
264
265
266
# File 'lib/dead_bro/subscriber.rb', line 261

def self.safe_path(data)
  path = data[:path] || (data[:request] && data[:request].path)
  sanitize_string(path)
rescue
  ""
end

.safe_user_agent(data) ⇒ Object



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/dead_bro/subscriber.rb', line 329

def self.safe_user_agent(data)
  begin
    # Prefer request object if available
    if data[:request]
      ua = nil
      if data[:request].respond_to?(:user_agent)
        ua = data[:request].user_agent
      elsif data[:request].respond_to?(:env)
        ua = data[:request].env && data[:request].env["HTTP_USER_AGENT"]
      end
      return sanitize_string(ua)[0..200]
    end

    # Fallback to headers object/hash if present in notification data
    if data[:headers]
      headers = data[:headers]
      if headers.respond_to?(:[])
        ua = headers["HTTP_USER_AGENT"] || headers["User-Agent"] || headers["user-agent"]
        return sanitize_string(ua)[0..200]
      elsif headers.respond_to?(:to_h)
        h = begin
          headers.to_h
        rescue
          {}
        end
        ua = h["HTTP_USER_AGENT"] || h["User-Agent"] || h["user-agent"]
        return sanitize_string(ua)[0..200]
      end
    end

    # Fallback to env hash if present in notification data
    if data[:env].is_a?(Hash)
      ua = data[:env]["HTTP_USER_AGENT"]
      return sanitize_string(ua)[0..200]
    end

    ""
  rescue
    ""
  end
rescue
  ""
end

.sanitize_string(str) ⇒ Object



294
295
296
# File 'lib/dead_bro/subscriber.rb', line 294

def self.sanitize_string(str)
  str.to_s.gsub("\x00", "")
end

.sensitive_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


304
305
306
# File 'lib/dead_bro/subscriber.rb', line 304

def self.sensitive_key?(key)
  SENSITIVE_SEGMENT_RE.match?(key.to_s)
end

.sql_count(data) ⇒ Object



395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/dead_bro/subscriber.rb', line 395

def self.sql_count(data)
  # Count SQL queries from the payload if available
  if data[:sql_count]
    data[:sql_count]
  elsif defined?(ActiveRecord) && ActiveRecord::Base.connection
    # Try to get from ActiveRecord connection
    begin
      ActiveRecord::Base.connection.query_cache.size
    rescue
      0
    end
  else
    0
  end
rescue
  0
end

.subscribe!(client: Client.new) ⇒ Object



10
11
12
13
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
# File 'lib/dead_bro/subscriber.rb', line 10

def self.subscribe!(client: Client.new)
  ActiveSupport::Notifications.subscribe(EVENT_NAME) do |name, started, finished, _unique_id, data|
    # When disabled remotely, fire a heartbeat at most once per minute so the gem
    # can detect when tracking has been re-enabled, then skip all tracking.
    unless DeadBro.configuration.enabled
      client.post_heartbeat if DeadBro.configuration.heartbeat_due?
      drain_request_tracking
      next
    end

    if DeadBro.configuration.skip_tracking?
      client.post_heartbeat if DeadBro.configuration.heartbeat_due?
      drain_request_tracking
      next
    end

    # Skip excluded controllers or controller#action pairs
    # Also check exclusive_controller_actions - if defined, only track those
    notification = data.is_a?(Hash) ? data : {}
    controller_name = notification[:controller].to_s
    action_name = notification[:action].to_s
    begin
      if DeadBro.configuration.excluded_controller?(controller_name, action_name)
        drain_request_tracking
        next
      end
      unless DeadBro.configuration.exclusive_controller?(controller_name, action_name)
        drain_request_tracking
        next
      end
    rescue
      drain_request_tracking
      next
    end

    has_error = data[:exception] || data[:exception_object]
    request_type_key = "#{controller_name}##{action_name}"
    # Errors always ship regardless of sampling (this is what the docs promise).
    unless has_error || DeadBro.configuration.should_sample?(request_type_key)
      drain_request_tracking
      next
    end

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

    # Time spent in Rack middleware before ActionController took over (routing, session, auth, etc.)
    rack_start = Thread.current[DeadBro::TRACKING_START_TIME_KEY]
    rack_duration_ms = rack_start ? ([((started - rack_start) * 1000.0), 0].max).round(2) : nil

    # Stop SQL tracking and get collected queries (this was started by the request)
    sql_queries = DeadBro::SqlSubscriber.stop_request_tracking

    # Stop cache, redis, and elasticsearch tracking
    cache_events = defined?(DeadBro::CacheSubscriber) ? DeadBro::CacheSubscriber.stop_request_tracking : []
    redis_events = defined?(DeadBro::RedisSubscriber) ? DeadBro::RedisSubscriber.stop_request_tracking : []
    elasticsearch_events = defined?(DeadBro::ElasticsearchSubscriber) ? DeadBro::ElasticsearchSubscriber.stop_request_tracking : []

    # Stop DB connection pool wait tracking
    db_connection_stats = defined?(DeadBro::DbConnectionSubscriber) ? DeadBro::DbConnectionSubscriber.stop_request_tracking : {}

    # Stop GC pressure tracking — diff minor/major runs, objects allocated, GC time
    gc_pressure = defined?(DeadBro::GcTracker) ? DeadBro::GcTracker.stop_request_tracking : {}

    # Stop AR object instantiation tracking
    ar_instantiation_count = defined?(DeadBro::ArObjectTracker) ? DeadBro::ArObjectTracker.stop_request_tracking : nil

    # Stop CPU time tracking — thread CPU time consumed by this request
    cpu_time_ms = defined?(DeadBro::CpuTracker) ? DeadBro::CpuTracker.stop_request_tracking : nil

    # Stop view rendering tracking and get collected view events
    view_events = DeadBro::ViewRenderingSubscriber.stop_request_tracking
    view_performance = DeadBro::ViewRenderingSubscriber.analyze_view_performance(view_events)

    # Per-phase allocation attribution (under memory tracking) — which phase
    # allocated the request's objects (sql / view / elasticsearch).
    allocation_phases = if DeadBro.configuration.memory_tracking_enabled && defined?(DeadBro::MemoryPhaseTracker)
      DeadBro::MemoryPhaseTracker.stop_request_tracking
    else
      {}
    end

    # Stop memory tracking and get collected memory data. The decision to do
    # heavy allocation tracking was made (and sampled) at request start.
    if Thread.current[:dead_bro_alloc_active] && defined?(DeadBro::MemoryTrackingSubscriber)
      detailed_memory = DeadBro::MemoryTrackingSubscriber.stop_request_tracking
      memory_performance = DeadBro::MemoryTrackingSubscriber.analyze_memory_performance(detailed_memory)

      # Allocation-source + by-bytes-type diagnostics. Read the trace data
      # before stopping the sampler (stop clears the source locations).
      if defined?(DeadBro::AllocationSourceSampler)
        growth = (detailed_memory[:memory_after].to_f - detailed_memory[:memory_before].to_f)
        source_analysis = DeadBro::AllocationSourceSampler.analyze(memory_growth_mb: growth)
        DeadBro::AllocationSourceSampler.stop
        if source_analysis.is_a?(Hash) && source_analysis.any?
          memory_performance[:allocation_sources] = source_analysis[:by_source]
          memory_performance[:memsize_by_type] = source_analysis[:by_type_bytes]
          memory_performance[:allocation_sample_rate] = source_analysis[:sample_rate]
          memory_performance[:allocation_sources_skipped] = source_analysis[:skipped] if source_analysis[:skipped]
        end
      end

      # 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

    # Record memory sample for leak detection (only if memory tracking enabled)
    if DeadBro.configuration.memory_tracking_enabled
      DeadBro::MemoryLeakDetector.record_memory_sample({
        memory_usage: memory_usage_mb,
        gc_count: gc_stats[:count],
        heap_pages: gc_stats[:heap_allocated_pages],
        object_count: gc_stats[:heap_live_slots],
        request_id: data[:request_id],
        controller: data[:controller],
        action: data[:action]
      })
    end

    # Report exceptions attached to this action (e.g. controller/view errors)
    if data[:exception] || data[:exception_object]
      begin
        exception_class, exception_message = data[:exception] if data[:exception]
        exception_obj = data[:exception_object]
        backtrace = Array(exception_obj&.backtrace).first(50)

        error_payload = {
          controller: data[:controller],
          action: data[:action],
          format: data[:format],
          method: data[:method],
          path: safe_path(data),
          status: data[:status],
          duration_ms: duration_ms,
          rails_env: DeadBro.env,
          host: DeadBro.safe_hostname,
          process_kind: DeadBro.process_kind,
          params: safe_params(data),
          user_agent: safe_user_agent(data),
          user_id: extract_user_id(data),
          exception_class: exception_class || exception_obj&.class&.name,
          message: (exception_message || exception_obj&.message).to_s[0, 1000],
          backtrace: backtrace,
          fingerprint: compute_error_fingerprint(exception_obj),
          cause_chain: build_cause_chain(exception_obj),
          error: true,
          logs: DeadBro.logger.logs
        }

        event_name = (exception_class || exception_obj&.class&.name || "exception").to_s
        client.post_metric(event_name: event_name, payload: error_payload, force: true)
      rescue
      ensure
        next
      end
    end

    payload = {
      controller: data[:controller],
      action: data[:action],
      format: data[:format],
      method: data[:method],
      path: safe_path(data),
      status: data[:status],
      started_at: started.utc.iso8601(3),
      duration_ms: duration_ms,
      view_runtime_ms: data[:view_runtime],
      db_runtime_ms: data[:db_runtime],
      host: DeadBro.safe_hostname,
      rails_env: DeadBro.env,
      process_kind: DeadBro.process_kind,
      params: safe_params(data),
      user_agent: safe_user_agent(data),
      user_id: extract_user_id(data),
      memory_usage: memory_usage_mb,
      gc_stats: gc_stats,
      sql_count: sql_count(data),
      sql_queries: sql_queries,
      http_outgoing: Thread.current[:dead_bro_http_events] || [],
      cache_events: cache_events,
      redis_events: redis_events,
      elasticsearch_events: elasticsearch_events,
      cache_hits: cache_hits(data),
      cache_misses: cache_misses(data),
      view_events: view_events,
      view_performance: view_performance,
      memory_events: memory_events,
      memory_performance: memory_performance,
      allocation_phases: allocation_phases,
      rack_duration_ms: rack_duration_ms,
      queue_duration_ms: Thread.current[:dead_bro_queue_duration_ms],
      db_connection_wait_ms: db_connection_stats[:wait_ms],
      db_connection_checkouts: db_connection_stats[:checkouts],
      gc_pressure: gc_pressure,
      ar_instantiation_count: ar_instantiation_count,
      cpu_time_ms: cpu_time_ms,
      logs: DeadBro.logger.logs
    }
    # force: true — the sampling decision (global or per-request-type) was
    # already made above; client#post_metric must not re-roll it with the
    # global-only rate, which would silently override a per-type sample rate.
    client.post_metric(event_name: name, payload: payload, force: true)
  end
end

.truncate_value(value, max_str: 200, max_array: 20, max_hash_keys: 30) ⇒ Object

Recursively truncate values to reasonable sizes to avoid huge payloads, and redact values whose key looks sensitive at any nesting level.



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/dead_bro/subscriber.rb', line 310

def self.truncate_value(value, max_str: 200, max_array: 20, max_hash_keys: 30)
  case value
  when String
    sanitized = sanitize_string(value)
    (sanitized.length > max_str) ? sanitized[0, max_str] + "" : sanitized
  when Numeric, TrueClass, FalseClass, NilClass
    value
  when Array
    value[0, max_array].map { |v| truncate_value(v, max_str: max_str, max_array: max_array, max_hash_keys: max_hash_keys) }
  when Hash
    entries = value.to_a[0, max_hash_keys]
    entries.each_with_object({}) do |(k, v), memo|
      memo[k] = sensitive_key?(k) ? "[FILTERED]" : truncate_value(v, max_str: max_str, max_array: max_array, max_hash_keys: max_hash_keys)
    end
  else
    (value.to_s.length > max_str) ? value.to_s[0, max_str] + "" : value.to_s
  end
end