dead_bro 0.2.38 → 0.2.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4258f98fde5b0e222593ebfadee095b6402576d94a33a2b57ac26c71f0b75d47
4
- data.tar.gz: 4a268f4eb24b882bf2dddd36a45db694f664319d3fa9650c3587eb59dd37f2af
3
+ metadata.gz: 05b20d2dc0ad0c6eaadd48c58c75c824f822a3278e1f9ab08402ef8dc192e307
4
+ data.tar.gz: 2dca3af73fb802b50afee0dee9c03adf90e2a26980d4aeb1ef5543832b8eed05
5
5
  SHA512:
6
- metadata.gz: 94f6cccf6594f0c50467b61a5d2bf53d6b73e7e72e6f042c2eae3cea2bad12e674e8a2f525bb7880f51f3b6cc679e3f3951dfba224b07e9701b48669060ffd51
7
- data.tar.gz: eae0e565ae2d1b43f20df7c3fd14311c7543f29b1680f0495c1fa1b4ca86a30c880b20dc94ba9cc147288dff41fa39eb7aae360dafb76139b751dccc380d02e4
6
+ metadata.gz: 8a5c4d1d91bcd0e4d53353a77249faa3fc7b2edcf359f7c855adf96a44bee17a4637f5b3729c62ed3d4c8a4e0cda6736e935fcd3ab8bc2b0a6edc45466459072
7
+ data.tar.gz: 6f79d4e0c2e1e71ec24bb95a7d04cd468ac0c5eef474d67bd49c743a626babf0f5a9a641df64647357ae3509f358fdb17dcb498f21a6aa4a1551f4e193079631
data/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.2.40] - 2026-11-23
4
+
5
+ ### Added
6
+ - **Super samples.** DeadBro can ask for a number of super samples of a request type (a controller action or a job class), set per request type in the dashboard's Performance table and sent to the gem as the `super_samples_by_type` setting. While any are needed, each request and job is drawn with a 1% chance, and a drawn one whose type still needs a super sample is sent marked `super_sample: true`, with a hundred times the room: about 1 in 100 requests of that type. Every count and length DeadBro caps is a hundred times its usual limit (log entries, spans, cache, Redis, HTTP, Elasticsearch, view, `DeadBro.watch` and transaction events, SQL text, params, job arguments, cache and Redis keys, the user agent, error messages, backtraces and causes, `DeadBro.watch` labels and tags, `max_sql_queries_to_send` and `max_logs_to_send`), and it is sent whatever the sample rate. The one-hour tracking limit stays. A super sample over 4 MB of JSON is sent with the usual limits instead, marked `super_sample_capped: true`, so it still counts. Sensitive values are filtered as in every sample. DeadBro stores each one it receives and answers with the number still needed. Every process holds that number until its next response, so more than one process can send a super sample for the last one needed; DeadBro stores those as super samples too.
7
+
8
+ ## [0.2.39] - 2026-11-15
9
+
10
+ ### Changed
11
+ - **The `dead_bro_hub` pages are never tracked.** Every page of the DeadBro section in BroHub (`DeadBroHub::*` controllers) fetches its data from DeadBro, so tracking them would have counted those reads as the app's own traffic. They are excluded built-in rather than through `excluded_controllers`, which DeadBro replaces wholesale whenever settings arrive; the exclusion can't be edited or removed from the dashboard. Uncaught exceptions from those pages are still reported.
12
+
3
13
  ## [0.2.38] - 2026-10-26
4
14
 
5
15
  ### Added
data/README.md CHANGED
@@ -71,6 +71,8 @@ You can still set `config.enabled` in Ruby if you need to force the integration
71
71
 
72
72
  To control data volume, DeadBro supports request sampling (track a percentage of requests), excluding specific controllers/jobs from tracking, and whitelisting (tracking *only* specific controllers/jobs). All of this is configured in the DeadBro dashboard — sample rate, `excluded_controllers`/`excluded_jobs`, and `exclusive_controllers`/`exclusive_jobs` patterns (wildcards like `Admin::*` and `Admin::*#*` supported). Exclusion always takes precedence over whitelisting when a pattern matches both.
73
73
 
74
+ **Super samples.** In the Performance table of the DeadBro dashboard you can ask for a number of super samples of a request type (a controller action or a job class). While that type still needs any, about 1 in 100 of its requests is sent as a super sample, with a hundred times the usual room: every count and length DeadBro caps (SQL queries, spans, logs, params, backtraces and the rest, `max_sql_queries_to_send` and `max_logs_to_send` included) is a hundred times its usual limit, and it is sent whatever the sample rate. One over 4 MB of JSON is sent with the usual limits instead. Sensitive values are filtered as in every sample. DeadBro stores each one and counts down the number still needed. Requires `dead_bro` ≥ 0.2.40.
75
+
74
76
  ## SQL Query Tracking
75
77
 
76
78
  DeadBro automatically tracks SQL queries executed during each request and job. Each request will include a `sql_queries` array containing:
@@ -54,7 +54,7 @@ module DeadBro
54
54
  return false unless events
55
55
 
56
56
  # Check count limit
57
- return false if events.length >= MAX_TRACKED_EVENTS
57
+ return false if events.length >= DeadBro::SuperSample.limit(MAX_TRACKED_EVENTS)
58
58
 
59
59
  # Check time limit
60
60
  start_time = Thread.current[DeadBro::TRACKING_START_TIME_KEY]
@@ -100,7 +100,7 @@ module DeadBro
100
100
  # Keys often embed request data (e.g. a throttle keyed by user agent);
101
101
  # scrubbing here keeps one bad byte off the client's slow retry path.
102
102
  s = DeadBro::Sanitizer.string(key)
103
- (s.length > 200) ? s[0, 200] + "…" : s
103
+ DeadBro::SuperSample.cut(s, 200, "…")
104
104
  rescue
105
105
  nil
106
106
  end
@@ -125,7 +125,8 @@ module DeadBro
125
125
  end
126
126
 
127
127
  def self.safe_namespace(ns)
128
- ns.to_s[0, 100]
128
+ ns = ns.to_s
129
+ DeadBro::SuperSample.cut(ns, 100)
129
130
  rescue
130
131
  nil
131
132
  end
@@ -27,11 +27,26 @@ module DeadBro
27
27
  return if circuit_open?
28
28
 
29
29
  payload = truncate_payload_for_request(payload)
30
- body = {event: event_name, payload: payload, sent_at: Time.now.utc.iso8601, revision: @configuration.resolve_deploy_id, gem_version: DeadBro::VERSION}
30
+ body = metric_body(event_name, payload)
31
+ json = nil
32
+
33
+ # A super sample over the byte ceiling goes out with the usual limits,
34
+ # still marked, so the backend counts it and stops asking for more.
35
+ if payload.is_a?(Hash) && payload[:super_sample]
36
+ json = serialize(body)
37
+ return unless json
38
+
39
+ if json.bytesize > DeadBro::SuperSample::MAX_PAYLOAD_BYTES
40
+ payload = truncate_payload_for_request(payload, factor: 1).merge(super_sample_capped: true)
41
+ body = metric_body(event_name, payload)
42
+ json = nil
43
+ end
44
+ end
31
45
 
32
46
  dispatch_request(
33
47
  url: metrics_endpoint_url,
34
48
  body: body,
49
+ json: json,
35
50
  event_name: event_name,
36
51
  apply_settings: true
37
52
  )
@@ -128,8 +143,13 @@ module DeadBro
128
143
  end
129
144
  end
130
145
 
131
- def dispatch_request(url:, body:, event_name:, apply_settings: false)
132
- json = serialize(body)
146
+ def metric_body(event_name, payload)
147
+ {event: event_name, payload: payload, sent_at: Time.now.utc.iso8601, revision: @configuration.resolve_deploy_id, gem_version: DeadBro::VERSION}
148
+ end
149
+
150
+ # `json`: the body already serialized, when the caller had to measure it.
151
+ def dispatch_request(url:, body:, event_name:, apply_settings: false, json: nil)
152
+ json ||= serialize(body)
133
153
  return unless json
134
154
 
135
155
  uri = URI.parse(url)
@@ -228,11 +248,14 @@ module DeadBro
228
248
  # Malformed response — ignore, settings stay as-is
229
249
  end
230
250
 
231
- def truncate_payload_for_request(payload)
251
+ # A super sample has LIMIT_FACTOR times the room, unless `factor` says
252
+ # otherwise (1: the usual limits, for one over the byte ceiling).
253
+ def truncate_payload_for_request(payload, factor: nil)
232
254
  return payload unless payload.is_a?(Hash)
233
255
 
234
- max_sql = @configuration.max_sql_queries_to_send
235
- max_logs = @configuration.max_logs_to_send
256
+ factor ||= payload[:super_sample] ? DeadBro::SuperSample::LIMIT_FACTOR : 1
257
+ max_sql = @configuration.max_sql_queries_to_send * factor
258
+ max_logs = @configuration.max_logs_to_send * factor
236
259
 
237
260
  out = payload.dup
238
261
 
@@ -41,6 +41,11 @@ module DeadBro
41
41
  # (or "JobClass#perform") strings — same identity ApmRequestType uses server-side.
42
42
  attr_reader :sample_rates_by_type
43
43
 
44
+ # How many super samples each request type still needs, keyed like
45
+ # sample_rates_by_type (see DeadBro::SuperSample). Every settings response
46
+ # replaces it with the numbers the backend still needs.
47
+ attr_reader :super_samples_by_type
48
+
44
49
  # Tracks when we last received settings from the backend (in-memory only)
45
50
  attr_accessor :settings_received_at
46
51
 
@@ -82,6 +87,7 @@ module DeadBro
82
87
  watch_enabled excluded_controllers excluded_jobs exclusive_controllers exclusive_jobs
83
88
  monitor_enabled enable_db_stats enable_process_stats enable_system_stats
84
89
  sample_rates_by_type report_routing_errors middleware_spans_enabled
90
+ super_samples_by_type
85
91
  ].freeze
86
92
 
87
93
  def initialize
@@ -124,6 +130,7 @@ module DeadBro
124
130
  self.exclusive_controllers = []
125
131
  self.exclusive_jobs = []
126
132
  self.sample_rates_by_type = {}
133
+ self.super_samples_by_type = {}
127
134
  @monitor_enabled = false
128
135
  @enable_db_stats = false
129
136
  @enable_process_stats = false
@@ -180,6 +187,14 @@ module DeadBro
180
187
  end
181
188
  end
182
189
 
190
+ def super_samples_by_type=(value)
191
+ return @super_samples_by_type = {} unless value.is_a?(Hash)
192
+
193
+ @super_samples_by_type = value.each_with_object({}) do |(k, v), memo|
194
+ memo[k.to_s] = v.to_i
195
+ end
196
+ end
197
+
183
198
  # Apply a settings hash received from the backend response.
184
199
  # Only known keys are applied; unknown keys are silently ignored.
185
200
  # Serialized so concurrent HTTP threads do not interleave writes with request-thread reads.
@@ -215,7 +230,7 @@ module DeadBro
215
230
  send(:"#{k}=", !!value)
216
231
  when "excluded_controllers", "excluded_jobs", "exclusive_controllers", "exclusive_jobs"
217
232
  send(:"#{k}=", Array(value).map(&:to_s))
218
- when "sample_rates_by_type"
233
+ when "sample_rates_by_type", "super_samples_by_type"
219
234
  send(:"#{k}=", value)
220
235
  end
221
236
  end
@@ -273,7 +288,18 @@ module DeadBro
273
288
  DeadBro.process_deploy_id
274
289
  end
275
290
 
291
+ # Controllers DeadBro never tracks, whatever the exclusion list says. The list is
292
+ # remote-managed and replaced wholesale whenever settings arrive, so a default put
293
+ # in it would be wiped on the first response; this is checked ahead of it instead.
294
+ #
295
+ # DeadBroHub is the dead_bro_hub gem's BroHub section: every page fetches from
296
+ # DeadBro, so tracking it would feed DeadBro's own reads back in as the app's traffic.
297
+ BUILT_IN_EXCLUDED_CONTROLLER_PREFIXES = ["DeadBroHub::"].freeze
298
+
276
299
  def excluded_controller?(controller_name, action_name = nil)
300
+ name = controller_name.to_s
301
+ return true if BUILT_IN_EXCLUDED_CONTROLLER_PREFIXES.any? { |prefix| name.start_with?(prefix) }
302
+
277
303
  compiled = @compiled_excluded_controllers
278
304
  return false if compiled.nil? || compiled.empty?
279
305
 
@@ -35,7 +35,7 @@ module DeadBro
35
35
  def self.should_continue_tracking?
36
36
  events = Thread.current[THREAD_LOCAL_KEY]
37
37
  return false unless events
38
- return false if events.length >= MAX_TRACKED_EVENTS
38
+ return false if events.length >= DeadBro::SuperSample.limit(MAX_TRACKED_EVENTS)
39
39
 
40
40
  start_time = Thread.current[DeadBro::TRACKING_START_TIME_KEY]
41
41
  if start_time
@@ -260,7 +260,7 @@ module DeadBro
260
260
  events = Thread.current[THREAD_LOCAL_KEY]
261
261
  return false unless events
262
262
 
263
- return false if events.length >= MAX_TRACKED_EVENTS
263
+ return false if events.length >= DeadBro::SuperSample.limit(MAX_TRACKED_EVENTS)
264
264
 
265
265
  start_time = Thread.current[DeadBro::TRACKING_START_TIME_KEY]
266
266
  if start_time
@@ -12,7 +12,9 @@ module DeadBro
12
12
 
13
13
  def self.subscribe!(client: Client.new)
14
14
  # Snap GC state before the job runs so stop_request_tracking gets a valid diff
15
- ActiveSupport::Notifications.subscribe("perform_start.active_job") do |_name, _started, _finished, _unique_id, _data|
15
+ ActiveSupport::Notifications.subscribe("perform_start.active_job") do |_name, _started, _finished, _unique_id, data|
16
+ # Picks the jobs sent as super samples.
17
+ DeadBro::SuperSample.start_job(data[:job])
16
18
  DeadBro::GcTracker.start_request_tracking if defined?(DeadBro::GcTracker)
17
19
  DeadBro::ArObjectTracker.start_request_tracking if defined?(DeadBro::ArObjectTracker)
18
20
  rescue *DeadBro::CONTAINED_ERRORS
@@ -41,6 +43,10 @@ module DeadBro
41
43
  # Covering handled attempts would need separate instrumentation on
42
44
  # enqueue_retry.active_job / retry_stopped.active_job / discard.active_job.
43
45
  ActiveSupport::Notifications.subscribe(JOB_EVENT_NAME) do |name, started, finished, _unique_id, data|
46
+ # It stays one until this block is left (see ensure), so what is built
47
+ # for its payload here isn't cut either.
48
+ super_sample = DeadBro::SuperSample.job?
49
+
44
50
  begin
45
51
  if DeadBro.configuration.skip_tracking?
46
52
  drain_job_tracking
@@ -65,9 +71,10 @@ module DeadBro
65
71
 
66
72
  # Skip out via sampling before we build any payload — jobs can be chatty
67
73
  # enough that even the "cheap" stop/analyze work matters under load.
68
- # Errors always ship regardless of sampling, matching Subscriber's web path.
74
+ # Errors always ship regardless of sampling, matching Subscriber's web path,
75
+ # and so does a super sample.
69
76
  job_type_key = "#{job_class_name}#perform"
70
- unless has_error || DeadBro.configuration.should_sample?(job_type_key)
77
+ unless has_error || super_sample || DeadBro.configuration.should_sample?(job_type_key)
71
78
  drain_job_tracking
72
79
  next
73
80
  end
@@ -155,11 +162,14 @@ module DeadBro
155
162
  watch_events: watch_events,
156
163
  logs: DeadBro.logger.logs
157
164
  }.merge(dependency_events)
165
+ payload[:super_sample] = true if super_sample
158
166
 
159
167
  if has_error
160
168
  payload[:exception_class] = exception.class.name
161
- payload[:message] = DeadBro::Sanitizer.string(exception.message.to_s[0, 1000])
162
- payload[:backtrace] = Array(exception.backtrace).first(50).map { |line| DeadBro::Sanitizer.string(line) }
169
+ message = DeadBro::SuperSample.cut(exception.message.to_s, 1000)
170
+ backtrace = Array(exception.backtrace).first(DeadBro::SuperSample.limit(50))
171
+ payload[:message] = DeadBro::Sanitizer.string(message)
172
+ payload[:backtrace] = backtrace.map { |line| DeadBro::Sanitizer.string(line) }
163
173
  payload[:fingerprint] = DeadBro::Subscriber.compute_error_fingerprint(exception)
164
174
  payload[:cause_chain] = DeadBro::Subscriber.build_cause_chain(exception)
165
175
  payload[:error] = true
@@ -174,6 +184,8 @@ module DeadBro
174
184
  # DeadBro::CONTAINED_ERRORS) — drop this job's metrics instead. Jobs have
175
185
  # no Rack middleware to reset thread-locals afterwards, so drain here.
176
186
  drain_job_tracking
187
+ ensure
188
+ DeadBro::SuperSample.finish_job
177
189
  end
178
190
  rescue
179
191
  # Never raise from instrumentation install
@@ -268,17 +280,17 @@ module DeadBro
268
280
 
269
281
  # Limit and sanitize job arguments. Strings are scrubbed to valid UTF-8 here
270
282
  # so one binary argument doesn't send the payload down the client's slow retry path.
271
- arguments.first(10).map do |arg|
283
+ # A super sample's arguments are filtered the same way, with a hundred times the room.
284
+ arguments.first(DeadBro::SuperSample.limit(10)).map do |arg|
272
285
  case arg
273
286
  when String
274
- str = DeadBro::Sanitizer.string(arg)
275
- (str.length > 200) ? str[0, 200] + "..." : str
287
+ DeadBro::SuperSample.cut(DeadBro::Sanitizer.string(arg), 200, "...")
276
288
  when Hash
277
289
  # Filter sensitive keys and limit size
278
290
  filtered = arg.reject { |k, _| %w[password token secret key].include?(k.to_s) }
279
- DeadBro::Sanitizer.deep((filtered.keys.size > 20) ? filtered.first(20).to_h : filtered)
291
+ DeadBro::Sanitizer.deep(filtered.first(DeadBro::SuperSample.limit(20)).to_h)
280
292
  when Array
281
- DeadBro::Sanitizer.deep(arg.first(5))
293
+ DeadBro::Sanitizer.deep(arg.first(DeadBro::SuperSample.limit(5)))
282
294
  when ActiveRecord::Base
283
295
  # Handle ActiveRecord objects safely
284
296
  "#{arg.class.name}##{begin
@@ -288,8 +300,7 @@ module DeadBro
288
300
  end}"
289
301
  else
290
302
  # Convert to string and truncate, but avoid object inspection
291
- str = DeadBro::Sanitizer.string(arg)
292
- (str.length > 200) ? str[0, 200] + "..." : str
303
+ DeadBro::SuperSample.cut(DeadBro::Sanitizer.string(arg), 200, "...")
293
304
  end
294
305
  end
295
306
  rescue
@@ -20,7 +20,8 @@ module DeadBro
20
20
 
21
21
  # Hard cap per-thread buffer size. Prevents unbounded growth when a
22
22
  # request/job logs a lot, or when tracking never gets a chance to flush
23
- # (e.g. code running outside a request lifecycle).
23
+ # (e.g. code running outside a request lifecycle). A super sample
24
+ # (DeadBro::SuperSample) keeps a hundred times as many.
24
25
  MAX_LOG_ENTRIES = 500
25
26
 
26
27
  def initialize
@@ -77,7 +78,7 @@ module DeadBro
77
78
  message = DeadBro::Sanitizer.string(message)
78
79
 
79
80
  buffer = (Thread.current[@thread_logs_key] ||= [])
80
- if buffer.length >= MAX_LOG_ENTRIES
81
+ if buffer.length >= DeadBro::SuperSample.limit(MAX_LOG_ENTRIES)
81
82
  Thread.current[@thread_logs_dropped_key] =
82
83
  (Thread.current[@thread_logs_dropped_key] || 0) + 1
83
84
  else
@@ -212,7 +212,7 @@ module DeadBro
212
212
  return false unless events
213
213
 
214
214
  # Check count limit
215
- return false if events.length >= MAX_TRACKED_EVENTS
215
+ return false if events.length >= DeadBro::SuperSample.limit(MAX_TRACKED_EVENTS)
216
216
 
217
217
  # Check time limit
218
218
  start_time = Thread.current[DeadBro::TRACKING_START_TIME_KEY]
@@ -270,7 +270,8 @@ module DeadBro
270
270
 
271
271
  def self.safe_command(cmd)
272
272
  return nil if cmd.nil?
273
- DeadBro::Sanitizer.string(cmd)[0, 20]
273
+ cmd = DeadBro::Sanitizer.string(cmd)
274
+ DeadBro::SuperSample.cut(cmd, 20)
274
275
  rescue
275
276
  nil
276
277
  end
@@ -280,7 +281,7 @@ module DeadBro
280
281
  def self.safe_key(key)
281
282
  return nil if key.nil?
282
283
  s = DeadBro::Sanitizer.string(key)
283
- (s.length > 200) ? s[0, 200] + "…" : s
284
+ DeadBro::SuperSample.cut(s, 200, "…")
284
285
  rescue
285
286
  nil
286
287
  end
@@ -37,7 +37,8 @@ module DeadBro
37
37
  THREAD_KEY = :dead_bro_span_context
38
38
 
39
39
  # Nodes kept per request; past it, a span's time stays in its parent's self
40
- # time and the request's spans_dropped counts what was left out.
40
+ # time and the request's spans_dropped counts what was left out. A super
41
+ # sample (DeadBro::SuperSample) keeps a hundred times as many.
41
42
  MAX_NODES = 500
42
43
  # Middleware/router frames kept per request (a Rails stack has ~25).
43
44
  MAX_RACK_FRAMES = 200
@@ -356,7 +357,7 @@ module DeadBro
356
357
  end
357
358
 
358
359
  def new_node(kind, parent_id)
359
- if @nodes.size >= MAX_NODES
360
+ if @nodes.size >= DeadBro::SuperSample.limit(MAX_NODES)
360
361
  @dropped += 1
361
362
  return nil
362
363
  end
@@ -118,7 +118,7 @@ module DeadBro
118
118
  return false unless current_queries_array.is_a?(Array)
119
119
 
120
120
  # Check count limit
121
- return false if current_queries_array.length >= max_count
121
+ return false if current_queries_array.length >= DeadBro::SuperSample.limit(max_count)
122
122
 
123
123
  # Check time limit
124
124
  start_time = Thread.current[DeadBro::TRACKING_START_TIME_KEY]
@@ -151,7 +151,7 @@ module DeadBro
151
151
  def self.record_transaction_event(name, started, finished)
152
152
  current = current_txn_events_array
153
153
  return unless current
154
- return if current.length >= MAX_TRACKED_TXN_EVENTS
154
+ return if current.length >= DeadBro::SuperSample.limit(MAX_TRACKED_TXN_EVENTS)
155
155
 
156
156
  tracking_start = Thread.current[DeadBro::TRACKING_START_TIME_KEY]
157
157
  start_offset_ms = tracking_start ? ((started - tracking_start) * 1000.0).round(2) : nil
@@ -384,8 +384,9 @@ module DeadBro
384
384
 
385
385
  # Cap length first — most "expensive" queries from the app's perspective
386
386
  # are big UPDATE/INSERT with long literal blobs; don't burn regex time on
387
- # those when we're going to truncate anyway.
388
- sql = sql[0..SANITIZE_MAX_LENGTH] + "..." if sql.length > SANITIZE_MAX_LENGTH
387
+ # those when we're going to truncate anyway. A super sample's SQL isn't cut.
388
+ max_length = DeadBro::SuperSample.limit(SANITIZE_MAX_LENGTH)
389
+ sql = sql[0..max_length] + "..." if sql.length > max_length
389
390
  # The regexes below raise on invalid UTF-8 (e.g. a binary literal inlined
390
391
  # by an adapter without prepared statements).
391
392
  sql = DeadBro::Sanitizer.string(sql)
@@ -671,16 +672,18 @@ module DeadBro
671
672
 
672
673
  # Cheap app-only backtrace for the current query. Uses caller_locations
673
674
  # (lazy frame objects, no string allocations until we render) and keeps
674
- # only frames under app/ (filtering vendor/). Returns at most N frames.
675
+ # only frames under app/ (filtering vendor/). Returns at most N frames of
676
+ # the nearest 100 (both a hundred times as many in a super sample).
675
677
  def self.capture_app_backtrace
676
- locations = caller_locations(1, 100) || []
678
+ locations = caller_locations(1, DeadBro::SuperSample.limit(100)) || []
679
+ max_frames = DeadBro::SuperSample.limit(APP_BACKTRACE_MAX_FRAMES)
677
680
  frames = []
678
681
  locations.each do |loc|
679
682
  path = loc.path.to_s
680
683
  next unless path.include?("app/")
681
684
  next if path.include?("/vendor/")
682
685
  frames << "#{path}:#{loc.lineno}:in `#{loc.label}'".gsub(APP_BACKTRACE_SENSITIVE_RE, "/[FILTERED]/")
683
- break if frames.length >= APP_BACKTRACE_MAX_FRAMES
686
+ break if frames.length >= max_frames
684
687
  end
685
688
  frames
686
689
  rescue
@@ -25,6 +25,9 @@ module DeadBro
25
25
  rack_entry = Time.now
26
26
  Thread.current[DeadBro::TRACKING_START_TIME_KEY] = rack_entry
27
27
 
28
+ # Before anything is recorded: a super sample has no limits from here on.
29
+ DeadBro::SuperSample.start_tracking
30
+
28
31
  # Queue time: gap between when the upstream proxy accepted the connection and when a Rack
29
32
  # worker picked it up. Heroku sets X-Request-Start as "t=<microseconds>"; nginx typically
30
33
  # uses "t=<seconds.ms>". Both are parsed below.
@@ -161,6 +164,8 @@ module DeadBro
161
164
  ensure
162
165
  Thread.current[:dead_bro_alloc_active] = nil
163
166
  Thread.current[DeadBro::TRACKING_START_TIME_KEY] = nil
167
+ # Also for a drawn request that never reached a controller action.
168
+ DeadBro::SuperSample.finish_request
164
169
  # Keeps the spans (and a payload held for the middleware chain) until
165
170
  # the outermost middleware returns.
166
171
  DeadBro::SpanTracker.stop_request if defined?(DeadBro::SpanTracker)
@@ -8,7 +8,14 @@ module DeadBro
8
8
  EVENT_NAME = "process_action.action_controller"
9
9
 
10
10
  def self.subscribe!(client: Client.new)
11
+ # A request drawn as a super sample stays one when its type needs one.
12
+ ActiveSupport::Notifications.subscribe("start_processing.action_controller", DeadBro::SuperSample::RequestListener.new)
13
+
11
14
  ActiveSupport::Notifications.subscribe(EVENT_NAME) do |name, started, finished, _unique_id, data|
15
+ # It stays one until this block is left (see ensure), so what is built
16
+ # for its payload here isn't cut either.
17
+ super_sample = DeadBro::SuperSample.request?
18
+
12
19
  # An exception the action raised is this listener's to report (or to
13
20
  # drop with an excluded request) — ErrorMiddleware must not send it again.
14
21
  mark_reported(data)
@@ -52,8 +59,9 @@ module DeadBro
52
59
 
53
60
  has_error = data[:exception] || data[:exception_object]
54
61
  request_type_key = "#{controller_name}##{action_name}"
55
- # Errors always ship regardless of sampling (this is what the docs promise).
56
- unless has_error || DeadBro.configuration.should_sample?(request_type_key)
62
+ # Errors always ship regardless of sampling (this is what the docs promise),
63
+ # and so does a super sample.
64
+ unless has_error || super_sample || DeadBro.configuration.should_sample?(request_type_key)
57
65
  drain_request_tracking
58
66
  next
59
67
  end
@@ -195,6 +203,7 @@ module DeadBro
195
203
  watch_events: watch_events,
196
204
  logs: DeadBro.logger.logs
197
205
  }
206
+ detail_fields[:super_sample] = true if super_sample
198
207
  # The span tree (see SpanTracker); the middleware spans are added when
199
208
  # the payload is sent.
200
209
  spans = DeadBro::SpanTracker.payload_spans
@@ -209,7 +218,9 @@ module DeadBro
209
218
  begin
210
219
  exception_class, exception_message = data[:exception] if data[:exception]
211
220
  exception_obj = data[:exception_object]
212
- backtrace = Array(exception_obj&.backtrace).first(50).map { |line| sanitize_string(line) }
221
+ backtrace = Array(exception_obj&.backtrace).first(DeadBro::SuperSample.limit(50))
222
+ backtrace = backtrace.map { |line| sanitize_string(line) }
223
+ message = DeadBro::SuperSample.cut((exception_message || exception_obj&.message).to_s, 1000)
213
224
 
214
225
  error_payload = detail_fields.merge(
215
226
  controller: data[:controller],
@@ -227,7 +238,7 @@ module DeadBro
227
238
  user_agent: safe_user_agent(data),
228
239
  user_id: extract_user_id(data),
229
240
  exception_class: exception_class || exception_obj&.class&.name,
230
- message: sanitize_string((exception_message || exception_obj&.message).to_s[0, 1000]),
241
+ message: sanitize_string(message),
231
242
  backtrace: backtrace,
232
243
  fingerprint: compute_error_fingerprint(exception_obj),
233
244
  cause_chain: build_cause_chain(exception_obj),
@@ -269,6 +280,8 @@ module DeadBro
269
280
  # Anything raised here would fail the host's request (see
270
281
  # DeadBro::CONTAINED_ERRORS) — drop this request's metrics instead.
271
282
  drain_request_tracking
283
+ ensure
284
+ DeadBro::SuperSample.finish_request
272
285
  end
273
286
  end
274
287
 
@@ -345,8 +358,14 @@ module DeadBro
345
358
  router_keys.each { |k| filtered.delete(k) || filtered.delete(k.to_sym) }
346
359
 
347
360
  # Truncate deeply to keep payload small and safe. truncate_value also redacts
348
- # sensitive keys at every nesting level (e.g. user[password]).
349
- truncate_value(filtered)
361
+ # sensitive keys at every nesting level (e.g. user[password]). A super
362
+ # sample's params are redacted the same way, with a hundred times the room.
363
+ truncate_value(
364
+ filtered,
365
+ max_str: DeadBro::SuperSample.limit(200),
366
+ max_array: DeadBro::SuperSample.limit(20),
367
+ max_hash_keys: DeadBro::SuperSample.limit(30)
368
+ )
350
369
  rescue
351
370
  {}
352
371
  end
@@ -366,18 +385,19 @@ module DeadBro
366
385
  end
367
386
 
368
387
  # Recursively truncate values to reasonable sizes to avoid huge payloads, and
369
- # redact values whose key looks sensitive at any nesting level.
388
+ # redact values whose key looks sensitive at any nesting level. A nil limit
389
+ # cuts nothing.
370
390
  def self.truncate_value(value, max_str: 200, max_array: 20, max_hash_keys: 30)
371
391
  case value
372
392
  when String
373
393
  sanitized = sanitize_string(value)
374
- (sanitized.length > max_str) ? sanitized[0, max_str] + "…" : sanitized
394
+ (max_str && sanitized.length > max_str) ? sanitized[0, max_str] + "…" : sanitized
375
395
  when Numeric, TrueClass, FalseClass, NilClass
376
396
  value
377
397
  when Array
378
- value[0, max_array].map { |v| truncate_value(v, max_str: max_str, max_array: max_array, max_hash_keys: max_hash_keys) }
398
+ (max_array ? value[0, max_array] : value).map { |v| truncate_value(v, max_str: max_str, max_array: max_array, max_hash_keys: max_hash_keys) }
379
399
  when Hash
380
- entries = value.to_a[0, max_hash_keys]
400
+ entries = max_hash_keys ? value.to_a[0, max_hash_keys] : value.to_a
381
401
  entries.each_with_object({}) do |(k, v), memo|
382
402
  # Scrubbed first: the sensitive-key regex raises on a key that isn't
383
403
  # valid UTF-8, which would drop the whole params hash.
@@ -385,7 +405,7 @@ module DeadBro
385
405
  memo[k] = sensitive_key?(k) ? "[FILTERED]" : truncate_value(v, max_str: max_str, max_array: max_array, max_hash_keys: max_hash_keys)
386
406
  end
387
407
  else
388
- (value.to_s.length > max_str) ? value.to_s[0, max_str] + "…" : value.to_s
408
+ (max_str && value.to_s.length > max_str) ? value.to_s[0, max_str] + "…" : value.to_s
389
409
  end
390
410
  end
391
411
 
@@ -414,12 +434,17 @@ module DeadBro
414
434
  # Strip any userinfo@ and a trailing :port so only the hostname remains.
415
435
  # Only a numeric trailing port is removed, so IPv6 literals ([::1]) survive.
416
436
  host = host.split("@").last.to_s
417
- host = host.sub(/:\d+\z/, "")
418
- host.downcase[0, 255]
437
+ host = host.sub(/:\d+\z/, "").downcase
438
+ host[0, 255]
419
439
  rescue
420
440
  ""
421
441
  end
422
442
 
443
+ # A hundred times as long in a super sample.
444
+ def self.cut_user_agent(user_agent)
445
+ DeadBro::SuperSample.cut(sanitize_string(user_agent), 201)
446
+ end
447
+
423
448
  def self.safe_user_agent(data)
424
449
  begin
425
450
  # Prefer request object if available
@@ -430,7 +455,7 @@ module DeadBro
430
455
  elsif data[:request].respond_to?(:env)
431
456
  ua = data[:request].env && data[:request].env["HTTP_USER_AGENT"]
432
457
  end
433
- return sanitize_string(ua)[0..200]
458
+ return cut_user_agent(ua)
434
459
  end
435
460
 
436
461
  # Fallback to headers object/hash if present in notification data
@@ -438,7 +463,7 @@ module DeadBro
438
463
  headers = data[:headers]
439
464
  if headers.respond_to?(:[])
440
465
  ua = headers["HTTP_USER_AGENT"] || headers["User-Agent"] || headers["user-agent"]
441
- return sanitize_string(ua)[0..200]
466
+ return cut_user_agent(ua)
442
467
  elsif headers.respond_to?(:to_h)
443
468
  h = begin
444
469
  headers.to_h
@@ -446,14 +471,14 @@ module DeadBro
446
471
  {}
447
472
  end
448
473
  ua = h["HTTP_USER_AGENT"] || h["User-Agent"] || h["user-agent"]
449
- return sanitize_string(ua)[0..200]
474
+ return cut_user_agent(ua)
450
475
  end
451
476
  end
452
477
 
453
478
  # Fallback to env hash if present in notification data
454
479
  if data[:env].is_a?(Hash)
455
480
  ua = data[:env]["HTTP_USER_AGENT"]
456
- return sanitize_string(ua)[0..200]
481
+ return cut_user_agent(ua)
457
482
  end
458
483
 
459
484
  ""
@@ -567,14 +592,17 @@ module DeadBro
567
592
 
568
593
  def self.build_cause_chain(exception)
569
594
  return [] unless exception
595
+ # A super sample gets a hundred times as many causes, each with a hundred times as
596
+ # much of its message and backtrace.
597
+ max_depth = DeadBro::SuperSample.limit(5)
570
598
  chain = []
571
599
  cause = exception.cause
572
600
  depth = 0
573
- while cause && depth < 5
601
+ while cause && depth < max_depth
574
602
  chain << {
575
603
  exception_class: cause.class.name,
576
- message: sanitize_string(cause.message.to_s[0, 500]),
577
- backtrace_top: Array(cause.backtrace).first(3).map { |line| sanitize_string(line) }
604
+ message: sanitize_string(DeadBro::SuperSample.cut(cause.message.to_s, 500)),
605
+ backtrace_top: Array(cause.backtrace).first(DeadBro::SuperSample.limit(3)).map { |line| sanitize_string(line) }
578
606
  }
579
607
  cause = cause.cause
580
608
  depth += 1
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DeadBro
4
+ # A super sample is one request or job sent with far more room than usual:
5
+ # every count and length DeadBro caps is LIMIT_FACTOR times its usual limit,
6
+ # and it is sent whatever the sample rate. The payload says so with
7
+ # `super_sample: true`.
8
+ #
9
+ # The limits stay, only higher: a long batch job would otherwise hold every
10
+ # query it ran in the host's memory and send it in one body. The tracking
11
+ # time limit (DeadBro::MAX_TRACKING_DURATION_SECONDS) is the usual one, and a
12
+ # payload over MAX_PAYLOAD_BYTES is sent with the usual limits instead
13
+ # (DeadBro::Client), marked `super_sample_capped: true`.
14
+ #
15
+ # The dashboard asks for them per request type: `super_samples_by_type` holds
16
+ # how many each type still needs. While any are needed, each request and job
17
+ # is drawn with a 1% chance (CHANCE_PERCENT), and a drawn one whose type
18
+ # needs a super sample is sent as one: about 1 in 100 requests of that type.
19
+ # DeadBro stores each super sample it receives and answers with the number
20
+ # still needed. Every process holds that number on its own until the next
21
+ # response, so the low chance also keeps several processes from each sending
22
+ # one at the same moment.
23
+ module SuperSample
24
+ # The request a thread is serving and the job it is running are drawn
25
+ # apart: a job performed inline in a controller action is its own sample.
26
+ REQUEST_KEY = :dead_bro_super_sample_request
27
+ JOB_KEY = :dead_bro_super_sample_job
28
+
29
+ CHANCE_PERCENT = 1
30
+
31
+ # How many times its usual limit each cap is in a super sample: 100,000 SQL
32
+ # queries instead of 1,000, 50,000 spans instead of 500, 20,000 characters
33
+ # instead of 200.
34
+ LIMIT_FACTOR = 100
35
+
36
+ # The largest super sample body sent as recorded (serialized JSON). A usual
37
+ # payload stays well under 1 MB.
38
+ MAX_PAYLOAD_BYTES = 4 * 1024 * 1024
39
+
40
+ # start_processing.action_controller is the first point of a request where
41
+ # its controller and action are known.
42
+ class RequestListener
43
+ def start(_name, _id, payload)
44
+ SuperSample.start_request(payload)
45
+ end
46
+
47
+ def finish(_name, _id, _payload)
48
+ end
49
+ end
50
+
51
+ module_function
52
+
53
+ # A request enters DeadBro's middleware. The draw is made here, before
54
+ # anything is recorded for the request, so that what runs between the
55
+ # middleware and the controller action isn't capped or cut either.
56
+ def start_tracking
57
+ Thread.current[REQUEST_KEY] = draw?
58
+ rescue *DeadBro::CONTAINED_ERRORS
59
+ end
60
+
61
+ # A drawn request goes on as a super sample only when its type needs one.
62
+ def start_request(payload)
63
+ return unless Thread.current[REQUEST_KEY]
64
+
65
+ Thread.current[REQUEST_KEY] = needed?("#{payload[:controller]}##{payload[:action]}")
66
+ rescue *DeadBro::CONTAINED_ERRORS
67
+ end
68
+
69
+ def start_job(job)
70
+ Thread.current[JOB_KEY] = draw? && needed?("#{job.class.name}#perform")
71
+ rescue *DeadBro::CONTAINED_ERRORS
72
+ end
73
+
74
+ # Whether the request (or job) the thread is finishing is a super sample.
75
+ def request?
76
+ Thread.current[REQUEST_KEY] == true
77
+ end
78
+
79
+ def job?
80
+ Thread.current[JOB_KEY] == true
81
+ end
82
+
83
+ # The request (or job) is over: what the thread runs next has its limits again.
84
+ def finish_request
85
+ Thread.current[REQUEST_KEY] = nil
86
+ end
87
+
88
+ def finish_job
89
+ Thread.current[JOB_KEY] = nil
90
+ end
91
+
92
+ # True while this thread runs a super sample: what it records has the
93
+ # higher limits (see .limit).
94
+ def active?
95
+ Thread.current[REQUEST_KEY] || Thread.current[JOB_KEY] || false
96
+ end
97
+
98
+ # A cap as it applies to what this thread records: LIMIT_FACTOR times
99
+ # `usual` while it runs a super sample, `usual` otherwise.
100
+ def limit(usual)
101
+ active? ? usual * LIMIT_FACTOR : usual
102
+ end
103
+
104
+ # A string cut to its limit (see .limit), with `suffix` when it was cut.
105
+ def cut(string, usual, suffix = "")
106
+ max = limit(usual)
107
+ (string.length > max) ? string[0, max] + suffix : string
108
+ end
109
+
110
+ # No draw is made while no type needs a super sample.
111
+ def draw?
112
+ !DeadBro.configuration.super_samples_by_type.empty? && rand(1..100) <= CHANCE_PERCENT
113
+ end
114
+
115
+ def needed?(type)
116
+ DeadBro.configuration.super_samples_by_type[type].to_i > 0
117
+ end
118
+ end
119
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeadBro
4
- VERSION = "0.2.38"
4
+ VERSION = "0.2.40"
5
5
  end
@@ -77,7 +77,7 @@ module DeadBro
77
77
  agg[:collection_count] += view_info[:collection_count].to_i
78
78
  agg[:collection_cached_count] += view_info[:collection_cached_count].to_i
79
79
  else
80
- return if aggregates.size >= MAX_TRACKED_EVENTS
80
+ return if aggregates.size >= DeadBro::SuperSample.limit(MAX_TRACKED_EVENTS)
81
81
  aggregates[key] = {
82
82
  identifier: key,
83
83
  type: view_info[:type],
@@ -65,8 +65,8 @@ module DeadBro
65
65
  return yield unless events.is_a?(Array) && active_stack.is_a?(Array)
66
66
 
67
67
  depth = active_stack.length
68
- return yield if depth > MAX_DEPTH
69
- return yield if events.length >= MAX_SPANS_PER_REQUEST
68
+ return yield if depth > DeadBro::SuperSample.limit(MAX_DEPTH)
69
+ return yield if events.length >= DeadBro::SuperSample.limit(MAX_SPANS_PER_REQUEST)
70
70
 
71
71
  sanitized_label = sanitize_label(label)
72
72
  sanitized_tags = sanitize_tags(tags)
@@ -102,7 +102,9 @@ module DeadBro
102
102
  # field unset rather than shipping an empty string the dashboard would
103
103
  # render as a blank exception.
104
104
  class_name = e.class.name
105
- frame[:exception_class] = class_name[0, 200] if class_name
105
+ if class_name
106
+ frame[:exception_class] = DeadBro::SuperSample.cut(class_name, 200)
107
+ end
106
108
  raise
107
109
  ensure
108
110
  active_stack.pop if active_stack.last.equal?(frame)
@@ -115,7 +117,7 @@ module DeadBro
115
117
  def sanitize_label(label)
116
118
  text = label.to_s.strip
117
119
  text = "block" if text.empty?
118
- (text.length > MAX_LABEL_LENGTH) ? text[0, MAX_LABEL_LENGTH] + "..." : text
120
+ DeadBro::SuperSample.cut(text, MAX_LABEL_LENGTH, "...")
119
121
  rescue StandardError
120
122
  "block"
121
123
  end
@@ -123,12 +125,12 @@ module DeadBro
123
125
  def sanitize_tags(tags)
124
126
  return {} unless tags.is_a?(Hash) && tags.any?
125
127
 
126
- tags.first(MAX_TAGS).each_with_object({}) do |(key, value), out|
127
- k = key.to_s.strip[0, 50]
128
+ # A super sample keeps a hundred times as many tags, and as much of each.
129
+ tags.first(DeadBro::SuperSample.limit(MAX_TAGS)).each_with_object({}) do |(key, value), out|
130
+ k = DeadBro::SuperSample.cut(key.to_s.strip, 50)
128
131
  next if k.empty?
129
132
 
130
- v = value.to_s.strip
131
- v = v[0, MAX_TAG_VALUE_LENGTH] + "..." if v.length > MAX_TAG_VALUE_LENGTH
133
+ v = DeadBro::SuperSample.cut(value.to_s.strip, MAX_TAG_VALUE_LENGTH, "...")
132
134
  out[k] = v
133
135
  end
134
136
  rescue StandardError
data/lib/dead_bro.rb CHANGED
@@ -31,6 +31,7 @@ module DeadBro
31
31
  autoload :Logger, "dead_bro/logger"
32
32
  autoload :WatchTracker, "dead_bro/watch_tracker"
33
33
  autoload :SpanTracker, "dead_bro/span_tracker"
34
+ autoload :SuperSample, "dead_bro/super_sample"
34
35
  autoload :MiddlewareProbe, "dead_bro/middleware_probe"
35
36
  autoload :Sanitizer, "dead_bro/sanitizer"
36
37
  begin
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: dead_bro
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.38
4
+ version: 0.2.40
5
5
  platform: ruby
6
6
  authors:
7
7
  - Emanuel Comsa
@@ -60,6 +60,7 @@ files:
60
60
  - lib/dead_bro/sql_subscriber.rb
61
61
  - lib/dead_bro/sql_tracking_middleware.rb
62
62
  - lib/dead_bro/subscriber.rb
63
+ - lib/dead_bro/super_sample.rb
63
64
  - lib/dead_bro/version.rb
64
65
  - lib/dead_bro/view_rendering_subscriber.rb
65
66
  - lib/dead_bro/watch_tracker.rb