dead_bro 0.2.39 → 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: 90595037bba70d8fbc8d625aebf039f9dde6d37d0dfb85b06ee252cb3647edbb
4
- data.tar.gz: 903c7adb08c0c1403aa050112d1b53973d90587df2fa660c3c70e7cade165f20
3
+ metadata.gz: 05b20d2dc0ad0c6eaadd48c58c75c824f822a3278e1f9ab08402ef8dc192e307
4
+ data.tar.gz: 2dca3af73fb802b50afee0dee9c03adf90e2a26980d4aeb1ef5543832b8eed05
5
5
  SHA512:
6
- metadata.gz: 73ac6e45c5e1bd5983740575254d39973457abf40895a1e9834ddab66c509ef27613d3be6eff66b1249f04a779981e601d9891b641722cc2fa33f0fb44ddaece
7
- data.tar.gz: f1051a45deb850fc4f61cc97b45692c2966acb52631000c8795e84f57db3a143c8e2e26c7fef0925aa189cef2176e85c35a37528a3d8135b8148be1fad196832
6
+ metadata.gz: 8a5c4d1d91bcd0e4d53353a77249faa3fc7b2edcf359f7c855adf96a44bee17a4637f5b3729c62ed3d4c8a4e0cda6736e935fcd3ab8bc2b0a6edc45466459072
7
+ data.tar.gz: 6f79d4e0c2e1e71ec24bb95a7d04cd468ac0c5eef474d67bd49c743a626babf0f5a9a641df64647357ae3509f358fdb17dcb498f21a6aa4a1551f4e193079631
data/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
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
+
3
8
  ## [0.2.39] - 2026-11-15
4
9
 
5
10
  ### Changed
data/FEATURES.md ADDED
@@ -0,0 +1,333 @@
1
+ # ApmBro Feature List
2
+
3
+ A comprehensive feature list for comparing ApmBro with other APM (Application Performance Monitoring) tools.
4
+
5
+ ## Core Architecture
6
+
7
+ - **Rails Integration**: Automatic subscription to Rails events via ActiveSupport::Notifications
8
+ - **Zero-Configuration Setup**: Works out of the box with minimal configuration
9
+ - **Asynchronous Metrics Posting**: Non-blocking HTTP requests using background threads
10
+ - **Thread-Local Storage**: Per-request metric collection using thread-local variables
11
+ - **Circuit Breaker Pattern**: Built-in circuit breaker to prevent cascading failures when APM endpoint is down
12
+ - **Deploy Tracking**: Automatic deploy ID resolution from multiple sources (Rails settings, ENV vars, Heroku, Git)
13
+
14
+ ## Request Tracking
15
+
16
+ ### Controller Action Monitoring
17
+ - **Automatic Tracking**: Tracks all controller actions automatically
18
+ - **Request Duration**: Measures total request processing time
19
+ - **HTTP Method & Path**: Captures HTTP method and request path
20
+ - **Status Codes**: Tracks HTTP response status codes
21
+ - **View Runtime**: Separate tracking of view rendering time
22
+ - **Database Runtime**: Separate tracking of database query time
23
+ - **Request Parameters**: Captures request parameters (with sensitive data filtering)
24
+ - **User Agent**: Tracks user agent strings
25
+ - **User ID Extraction**: Extracts authenticated user ID (supports Warden)
26
+ - **Environment Context**: Tracks Rails environment (development, staging, production)
27
+
28
+ ### Request Sampling
29
+ - **Configurable Sample Rate**: Percentage-based sampling (1-100%)
30
+ - **Random Sampling**: Each request has random chance of being tracked
31
+ - **Consistent Per-Request**: Sampling decision applies to all metrics for a request
32
+ - **Error Override**: Errors are always tracked regardless of sampling
33
+ - **Cost Optimization**: Reduces data volume and costs for high-traffic applications
34
+
35
+ ### Exclusion Rules
36
+ - **Controller Exclusion**: Exclude entire controllers from tracking
37
+ - **Action Exclusion**: Exclude specific controller#action combinations
38
+ - **Wildcard Support**: Pattern matching with `*` wildcards (e.g., `Admin::*`, `Admin::*#*`)
39
+ - **Job Exclusion**: Exclude specific background jobs from tracking
40
+ - **Flexible Configuration**: Configure via initializer, Rails settings, or environment variables
41
+
42
+ ## SQL Query Tracking
43
+
44
+ ### Query Details
45
+ - **Full SQL Tracking**: Captures all SQL queries executed during requests and jobs
46
+ - **Query Sanitization**: Automatically sanitizes SQL to remove sensitive data
47
+ - **Query Name**: Tracks query names (e.g., "User Load", "User Update")
48
+ - **Duration Measurement**: Precise query execution time in milliseconds
49
+ - **Cache Detection**: Identifies cached queries
50
+ - **Connection ID**: Tracks database connection ID
51
+ - **Call Stack Traces**: Full backtrace showing where queries were executed
52
+ - **Object Allocations**: Optional tracking of object allocations per query
53
+
54
+ ### Query Performance Analysis
55
+ - **Slow Query Detection**: Configurable threshold for identifying slow queries
56
+ - **EXPLAIN ANALYZE**: Automatic execution plan capture for slow queries
57
+ - **Background Execution**: EXPLAIN ANALYZE runs in separate thread (non-blocking)
58
+ - **Multi-Database Support**: Works with PostgreSQL, MySQL, SQLite, and others
59
+ - **Smart Filtering**: Automatically skips transaction queries (BEGIN, COMMIT, ROLLBACK)
60
+ - **Execution Plan Details**:
61
+ - PostgreSQL: Full EXPLAIN ANALYZE with buffer usage statistics
62
+ - MySQL: EXPLAIN ANALYZE with actual execution times
63
+ - SQLite: EXPLAIN QUERY PLAN output
64
+ - **Query Optimization Insights**: Helps identify missing indexes, full table scans, JOIN issues
65
+
66
+ ## View Rendering Tracking
67
+
68
+ ### View Performance
69
+ - **Template Rendering**: Tracks main template rendering
70
+ - **Partial Rendering**: Tracks partial template rendering with cache key information
71
+ - **Collection Rendering**: Tracks collection rendering (partials in loops)
72
+ - **Rendering Duration**: Precise timing for each view component
73
+ - **Virtual Path Tracking**: Tracks view virtual paths
74
+ - **Layout Information**: Captures layout usage
75
+
76
+ ### View Analysis
77
+ - **Slow View Detection**: Identifies the slowest rendering views
78
+ - **Frequency Analysis**: Tracks most frequently rendered views
79
+ - **Cache Hit Rate**: Calculates cache hit rates for partials
80
+ - **Collection Cache Analysis**: Tracks cache hit rates for collection rendering
81
+ - **Performance Metrics**:
82
+ - Total views rendered per request
83
+ - Total view rendering duration
84
+ - Average view rendering duration
85
+ - Breakdown by view type (template, partial, collection)
86
+
87
+ ## Memory Tracking & Leak Detection
88
+
89
+ ### Lightweight Memory Tracking (Default)
90
+ - **Memory Usage Monitoring**: Tracks memory consumption per request using GC stats
91
+ - **Memory Growth Tracking**: Measures memory growth during request processing
92
+ - **GC Statistics**: Tracks garbage collection count and heap pages
93
+ - **Minimal Performance Impact**: ~0.1ms overhead per request
94
+ - **Memory Before/After**: Captures memory state at request start and end
95
+
96
+ ### Detailed Allocation Tracking (Optional)
97
+ - **Object Allocation Tracking**: Detailed tracking of object allocations (disabled by default)
98
+ - **Allocation Sampling**: Configurable sampling rate for allocations
99
+ - **Large Object Detection**: Identifies objects larger than 1MB threshold
100
+ - **Memory Snapshots**: Periodic memory snapshots during request processing
101
+ - **Object Count Tracking**: Tracks object counts before and after requests
102
+ - **Performance Impact**: ~2-5ms overhead per request (only when enabled)
103
+
104
+ ### Memory Leak Detection
105
+ - **Pattern Detection**: Detects growing memory patterns over time
106
+ - **GC Efficiency Analysis**: Monitors garbage collection effectiveness
107
+ - **Heap Page Tracking**: Tracks heap page growth
108
+ - **Request Correlation**: Correlates memory growth with specific controllers/actions
109
+
110
+ ## Background Job Tracking
111
+
112
+ ### Job Execution Monitoring
113
+ - **ActiveJob Integration**: Automatic tracking when ActiveJob is available
114
+ - **Job Class Tracking**: Tracks job class names
115
+ - **Job ID**: Captures unique job identifiers
116
+ - **Queue Name**: Tracks which queue processed the job
117
+ - **Job Arguments**: Captures job arguments (with sensitive data filtering)
118
+ - **Duration Measurement**: Precise job execution time in milliseconds
119
+ - **Status Tracking**: Tracks job status (completed or failed)
120
+
121
+ ### Job Error Tracking
122
+ - **Exception Capture**: Captures exceptions from failed jobs
123
+ - **Exception Class**: Tracks exception class names
124
+ - **Exception Messages**: Captures exception messages (truncated to 1000 chars)
125
+ - **Backtraces**: Full exception backtraces (first 50 lines)
126
+ - **SQL Query Context**: Includes SQL queries executed during failed jobs
127
+ - **Memory Context**: Includes memory usage during job execution
128
+
129
+ ### Job SQL Tracking
130
+ - **SQL Query Tracking**: Tracks all SQL queries executed during job processing
131
+ - **Query Details**: Same detailed SQL tracking as request tracking
132
+ - **Query Context**: Full context of database operations in background jobs
133
+
134
+ ## Cache Tracking
135
+
136
+ ### Cache Operations
137
+ - **Read Operations**: Tracks cache read operations
138
+ - **Write Operations**: Tracks cache write operations
139
+ - **Delete Operations**: Tracks cache delete operations
140
+ - **Existence Checks**: Tracks cache existence checks
141
+ - **Fetch Operations**: Tracks cache fetch with hit/miss detection
142
+ - **Multi-Read Operations**: Tracks cache read_multi operations
143
+ - **Multi-Write Operations**: Tracks cache write_multi operations
144
+ - **Cache Generation**: Tracks cache generation events
145
+
146
+ ### Cache Analysis
147
+ - **Cache Hit Detection**: Identifies cache hits vs misses
148
+ - **Cache Key Tracking**: Tracks cache keys (truncated to 200 chars)
149
+ - **Store Information**: Identifies which cache store was used
150
+ - **Namespace Tracking**: Tracks cache namespaces
151
+ - **Duration Measurement**: Precise timing for each cache operation
152
+ - **Hit Rate Calculation**: Calculates cache hit rates per request
153
+
154
+ ## Redis Tracking
155
+
156
+ ### Redis Command Tracking
157
+ - **Command Monitoring**: Tracks all Redis commands executed
158
+ - **Command Name**: Captures Redis command names (GET, SET, etc.)
159
+ - **Key Tracking**: Tracks Redis keys (truncated to 200 chars)
160
+ - **Argument Count**: Tracks number of arguments per command
161
+ - **Database Selection**: Tracks which Redis database is used
162
+ - **Duration Measurement**: Precise timing for each Redis command
163
+ - **Error Tracking**: Captures Redis command errors
164
+
165
+ ### Advanced Redis Features
166
+ - **Pipeline Support**: Tracks Redis pipeline operations with command counts
167
+ - **Multi/Transaction Support**: Tracks Redis MULTI/EXEC transactions
168
+ - **ActiveSupport Integration**: Subscribes to ActiveSupport::Notifications for Redis events
169
+ - **Client Instrumentation**: Direct instrumentation of Redis::Client for comprehensive coverage
170
+
171
+ ## Error Tracking
172
+
173
+ ### Exception Handling
174
+ - **Automatic Exception Capture**: Captures exceptions from controller actions
175
+ - **Exception Class**: Tracks exception class names
176
+ - **Exception Messages**: Captures exception messages (truncated to 1000 chars)
177
+ - **Full Backtraces**: Captures complete exception backtraces (first 50 lines)
178
+ - **Request Context**: Includes full request context with exceptions
179
+ - **Error Flagging**: Errors are marked and always tracked (even with sampling)
180
+
181
+ ### Error Context
182
+ - **Controller/Action**: Identifies where the error occurred
183
+ - **Request Parameters**: Includes request parameters at time of error
184
+ - **User Information**: Includes user ID if available
185
+ - **SQL Queries**: Includes SQL queries executed before error
186
+ - **Memory State**: Includes memory usage at time of error
187
+ - **Log Messages**: Includes application logs captured during request
188
+
189
+ ## HTTP Instrumentation
190
+
191
+ ### Outgoing HTTP Tracking
192
+ - **HTTP Request Tracking**: Tracks outgoing HTTP requests (via middleware)
193
+ - **Request Context**: Captures HTTP request details
194
+ - **Response Context**: Captures HTTP response details
195
+ - **Duration Measurement**: Tracks HTTP request duration
196
+
197
+ ## Configuration & Flexibility
198
+
199
+ ### Configuration Options
200
+ - **API Key Management**: Multiple sources (config, Rails credentials, ENV)
201
+ - **Endpoint Configuration**: Configurable endpoint URL
202
+ - **Timeout Settings**: Configurable open and read timeouts
203
+ - **Enable/Disable Toggle**: Can be enabled/disabled via configuration
204
+ - **Environment Detection**: Automatic Rails environment detection
205
+
206
+ ### Circuit Breaker Configuration
207
+ - **Failure Threshold**: Configurable failure threshold (default: 3)
208
+ - **Recovery Timeout**: Configurable recovery timeout (default: 60 seconds)
209
+ - **Retry Timeout**: Configurable retry timeout (default: 300 seconds)
210
+ - **Enable/Disable**: Can enable/disable circuit breaker
211
+
212
+ ### Memory Tracking Configuration
213
+ - **Memory Tracking Toggle**: Enable/disable memory tracking
214
+ - **Allocation Tracking Toggle**: Enable/disable detailed allocation tracking
215
+ - **Sampling Configuration**: Configurable request sampling rate
216
+
217
+ ### Query Analysis Configuration
218
+ - **Slow Query Threshold**: Configurable threshold in milliseconds (default: 500ms)
219
+ - **EXPLAIN ANALYZE Toggle**: Enable/disable automatic EXPLAIN ANALYZE
220
+
221
+ ## Data Safety & Privacy
222
+
223
+ ### Data Sanitization
224
+ - **SQL Sanitization**: Automatically sanitizes SQL queries
225
+ - **Parameter Filtering**: Filters sensitive parameters (password, token, secret, key)
226
+ - **Argument Truncation**: Limits and truncates job arguments
227
+ - **Key Truncation**: Truncates cache and Redis keys to 200 characters
228
+ - **Value Truncation**: Recursively truncates nested values to prevent huge payloads
229
+ - **String Limits**: Limits string values (e.g., user agent to 200 chars, messages to 1000 chars)
230
+
231
+ ### Data Limits
232
+ - **Array Limits**: Limits array sizes (e.g., first 10 job arguments, first 5 array elements)
233
+ - **Hash Limits**: Limits hash key counts (e.g., first 20 hash keys, first 30 params)
234
+ - **Backtrace Limits**: Limits backtraces to first 50 lines
235
+ - **Allocation Limits**: Limits allocations tracked per request (max 1000)
236
+
237
+ ## Performance & Reliability
238
+
239
+ ### Performance Optimizations
240
+ - **Asynchronous Posting**: Non-blocking HTTP requests
241
+ - **Lightweight Default Mode**: Minimal overhead in default configuration
242
+ - **Sampling Support**: Reduces data volume for high-traffic applications
243
+ - **Thread-Local Storage**: Efficient per-request data collection
244
+ - **Background EXPLAIN**: EXPLAIN ANALYZE runs in background thread
245
+
246
+ ### Reliability Features
247
+ - **Circuit Breaker**: Prevents cascading failures
248
+ - **Error Handling**: Comprehensive error handling to prevent instrumentation failures
249
+ - **Graceful Degradation**: Continues working even if some features fail
250
+ - **Timeout Protection**: Configurable timeouts prevent hanging requests
251
+
252
+ ## Integration & Compatibility
253
+
254
+ ### Framework Support
255
+ - **Rails Integration**: Full Rails integration via Railtie
256
+ - **ActiveSupport Notifications**: Uses ActiveSupport::Notifications for event subscription
257
+ - **ActiveRecord Integration**: Tracks ActiveRecord SQL queries
258
+ - **ActiveJob Integration**: Tracks ActiveJob background jobs
259
+ - **ActionView Integration**: Tracks ActionView rendering
260
+
261
+ ### Database Support
262
+ - **PostgreSQL**: Full support with EXPLAIN ANALYZE
263
+ - **MySQL**: Full support with EXPLAIN ANALYZE
264
+ - **SQLite**: Full support with EXPLAIN QUERY PLAN
265
+ - **Other Databases**: Basic support with standard EXPLAIN
266
+
267
+ ### Cache Store Support
268
+ - **All Cache Stores**: Works with any Rails cache store
269
+ - **Multi-Store Support**: Tracks cache operations across different stores
270
+
271
+ ### Redis Support
272
+ - **Redis Gem**: Works with redis gem
273
+ - **Client Instrumentation**: Direct instrumentation of Redis::Client
274
+ - **Pipeline Support**: Tracks Redis pipelines
275
+ - **Transaction Support**: Tracks Redis MULTI/EXEC transactions
276
+
277
+ ## Logging & Debugging
278
+
279
+ ### Application Logging
280
+ - **Log Capture**: Captures application logs during request processing
281
+ - **Log Context**: Includes logs in metric payloads
282
+ - **Debug Logging**: Optional debug logging for skipped requests
283
+
284
+ ## Deployment & Environment
285
+
286
+ ### Deploy Tracking
287
+ - **Deploy ID Resolution**: Multiple sources for deploy identification (`Configuration#deploy_id=` wins when set, then ENV in `Configuration::DEPLOY_REVISION_ENV_KEYS` order—including `DEAD_BRO_DEPLOY_ID`, git/CI vars, `DD_VERSION`, etc.), otherwise a **per-process UUID** (fine for single dyno/process; unusable alone for fleets like ECS replicas)
288
+ - **Revision Tracking**: Includes deploy/revision ID in all metric payloads
289
+
290
+ ### Environment Support
291
+ - **Rails Environment**: Automatic Rails environment detection
292
+ - **Rack Environment**: Fallback to RACK_ENV or RAILS_ENV
293
+ - **Environment Context**: Includes environment in all metric payloads
294
+
295
+ ## Data Collection & Transmission
296
+
297
+ ### Metric Payload Structure
298
+ - **Structured Data**: Well-structured JSON payloads
299
+ - **Event Names**: Descriptive event names for different metric types
300
+ - **Timestamp Tracking**: ISO8601 timestamps for all metrics
301
+ - **Metadata**: Rich metadata including environment, host, deploy ID
302
+
303
+ ### HTTP Client
304
+ - **HTTPS Support**: Secure HTTPS communication
305
+ - **Bearer Token Auth**: API key authentication via Bearer tokens
306
+ - **JSON Encoding**: JSON-encoded payloads
307
+ - **Custom Headers**: Proper Content-Type and Authorization headers
308
+
309
+ ## Comparison-Ready Features
310
+
311
+ ### Unique Differentiators
312
+ 1. **Automatic EXPLAIN ANALYZE**: Background execution plan capture for slow queries
313
+ 2. **Lightweight Memory Tracking**: Low-overhead memory monitoring by default
314
+ 3. **Comprehensive Cache Tracking**: Detailed cache operation tracking
315
+ 4. **Redis Instrumentation**: Full Redis command tracking including pipelines
316
+ 5. **View Rendering Analysis**: Detailed view performance analysis with cache hit rates
317
+ 6. **Flexible Exclusion Rules**: Wildcard support for controller/job exclusion
318
+ 7. **Request Sampling**: Configurable percentage-based sampling
319
+ 8. **Circuit Breaker**: Built-in resilience for APM endpoint failures
320
+ 9. **Multi-Source Configuration**: Flexible configuration from multiple sources
321
+ 10. **Deploy Tracking**: Automatic deploy ID resolution from multiple sources
322
+
323
+ ### Standard APM Features
324
+ - Request/response tracking
325
+ - SQL query tracking
326
+ - Error tracking
327
+ - Background job tracking
328
+ - Memory tracking
329
+ - Performance metrics
330
+ - Exception handling
331
+ - User context
332
+ - Environment tracking
333
+
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
@@ -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.39"
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.39
4
+ version: 0.2.40
5
5
  platform: ruby
6
6
  authors:
7
7
  - Emanuel Comsa
@@ -18,6 +18,7 @@ extensions: []
18
18
  extra_rdoc_files: []
19
19
  files:
20
20
  - CHANGELOG.md
21
+ - FEATURES.md
21
22
  - README.md
22
23
  - lib/dead_bro.rb
23
24
  - lib/dead_bro/allocation_source_sampler.rb
@@ -59,6 +60,7 @@ files:
59
60
  - lib/dead_bro/sql_subscriber.rb
60
61
  - lib/dead_bro/sql_tracking_middleware.rb
61
62
  - lib/dead_bro/subscriber.rb
63
+ - lib/dead_bro/super_sample.rb
62
64
  - lib/dead_bro/version.rb
63
65
  - lib/dead_bro/view_rendering_subscriber.rb
64
66
  - lib/dead_bro/watch_tracker.rb
@@ -83,7 +85,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
83
85
  - !ruby/object:Gem::Version
84
86
  version: '0'
85
87
  requirements: []
86
- rubygems_version: 4.0.10
88
+ rubygems_version: 4.0.22
87
89
  specification_version: 4
88
90
  summary: Minimal APM for Rails apps.
89
91
  test_files: []