dead_bro 0.2.0

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 2d751a73992758c9392fbf0a89445536ce1a97cd2aea29470e54c4da62075e6b
4
+ data.tar.gz: e868200d7940c736922ea80e0a5d98fd665a86f1258725e9db33098ccbe75927
5
+ SHA512:
6
+ metadata.gz: 2ae9d9a17ca3975e68fdd762dd1f93eb173fca163ba01fdd6bea4813c0e7fca6566fee6943ee518b20f5f7b624cbc96b17dc0afcb45837cca703a94cfdde5e4b
7
+ data.tar.gz: 631e395e237463d6d76b0bc08868ee28712f90450a1c22935f21c05e1ff766c3b2b6f906249cbe6f29e8217c73a5bd196e746c6fab614e9f722f199f64e60eaa
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-08-28
4
+
5
+ - Initial release
data/FEATURES.md ADDED
@@ -0,0 +1,338 @@
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
288
+ - Explicit configuration
289
+ - Rails settings/credentials
290
+ - Environment variables (APM_BRO_DEPLOY_ID, GIT_REV)
291
+ - Heroku (HEROKU_SLUG_COMMIT)
292
+ - Process-stable UUID fallback
293
+ - **Revision Tracking**: Includes deploy/revision ID in all metric payloads
294
+
295
+ ### Environment Support
296
+ - **Rails Environment**: Automatic Rails environment detection
297
+ - **Rack Environment**: Fallback to RACK_ENV or RAILS_ENV
298
+ - **Environment Context**: Includes environment in all metric payloads
299
+
300
+ ## Data Collection & Transmission
301
+
302
+ ### Metric Payload Structure
303
+ - **Structured Data**: Well-structured JSON payloads
304
+ - **Event Names**: Descriptive event names for different metric types
305
+ - **Timestamp Tracking**: ISO8601 timestamps for all metrics
306
+ - **Metadata**: Rich metadata including environment, host, deploy ID
307
+
308
+ ### HTTP Client
309
+ - **HTTPS Support**: Secure HTTPS communication
310
+ - **Bearer Token Auth**: API key authentication via Bearer tokens
311
+ - **JSON Encoding**: JSON-encoded payloads
312
+ - **Custom Headers**: Proper Content-Type and Authorization headers
313
+
314
+ ## Comparison-Ready Features
315
+
316
+ ### Unique Differentiators
317
+ 1. **Automatic EXPLAIN ANALYZE**: Background execution plan capture for slow queries
318
+ 2. **Lightweight Memory Tracking**: Low-overhead memory monitoring by default
319
+ 3. **Comprehensive Cache Tracking**: Detailed cache operation tracking
320
+ 4. **Redis Instrumentation**: Full Redis command tracking including pipelines
321
+ 5. **View Rendering Analysis**: Detailed view performance analysis with cache hit rates
322
+ 6. **Flexible Exclusion Rules**: Wildcard support for controller/job exclusion
323
+ 7. **Request Sampling**: Configurable percentage-based sampling
324
+ 8. **Circuit Breaker**: Built-in resilience for APM endpoint failures
325
+ 9. **Multi-Source Configuration**: Flexible configuration from multiple sources
326
+ 10. **Deploy Tracking**: Automatic deploy ID resolution from multiple sources
327
+
328
+ ### Standard APM Features
329
+ - Request/response tracking
330
+ - SQL query tracking
331
+ - Error tracking
332
+ - Background job tracking
333
+ - Memory tracking
334
+ - Performance metrics
335
+ - Exception handling
336
+ - User context
337
+ - Environment tracking
338
+
data/README.md ADDED
@@ -0,0 +1,274 @@
1
+ # DeadBro (Beta Version)
2
+
3
+ Minimal APM for Rails apps. Automatically measures each controller action's total time, tracks SQL queries, monitors view rendering performance, tracks memory usage and detects leaks, monitors background jobs, and posts metrics to a remote endpoint with an API key read from your app's settings/credentials/env.
4
+
5
+ To use the gem you need to have a free account with [DeadBro - Rails APM](https://www.deadbro.com)
6
+
7
+ ## Installation
8
+
9
+ Add to your Gemfile:
10
+
11
+ ```ruby
12
+ gem "dead_bro", git: "https://github.com/rubydevro/dead_bro.git"
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ By default, if Rails is present, DeadBro auto-subscribes to `process_action.action_controller` and posts metrics asynchronously.
18
+
19
+ ### Configuration settings
20
+
21
+ You can set via an initializer:
22
+
23
+
24
+ ```ruby
25
+ DeadBro.configure do |cfg|
26
+ cfg.api_key = ENV["dead_bro_API_KEY"]
27
+ cfg.enabled = true
28
+ end
29
+ ```
30
+
31
+ ## Request Sampling
32
+
33
+ DeadBro supports configurable request sampling to reduce the volume of metrics sent to your APM endpoint, which is useful for high-traffic applications.
34
+
35
+ ### Configuration
36
+
37
+ Set the sample rate as a percentage (1-100):
38
+
39
+ ```ruby
40
+ # Track 50% of requests
41
+ DeadBro.configure do |config|
42
+ config.sample_rate = 50
43
+ end
44
+
45
+ # Track 10% of requests (useful for high-traffic apps)
46
+ DeadBro.configure do |config|
47
+ config.sample_rate = 10
48
+ end
49
+
50
+ # Track all requests (default)
51
+ DeadBro.configure do |config|
52
+ config.sample_rate = 100
53
+ end
54
+ ```
55
+
56
+ ### How It Works
57
+
58
+ - **Random Sampling**: Each request has a random chance of being tracked based on the sample rate
59
+ - **Consistent Per-Request**: The sampling decision is made once per request and applies to all metrics for that request
60
+ - **Debug Logging**: Skipped requests do not count towards the montly limit
61
+ - **Error Tracking**: Errors are still tracked regardless of sampling
62
+
63
+ ### Use Cases
64
+
65
+ - **High-Traffic Applications**: Reduce APM data volume and costs
66
+ - **Development/Staging**: Sample fewer requests to reduce noise
67
+ - **Performance Testing**: Track a subset of requests during load testing
68
+ - **Cost Optimization**: Balance monitoring coverage with data costs
69
+
70
+
71
+ ## Excluding Controllers and Jobs
72
+
73
+ You can exclude specific controllers and jobs from APM tracking.
74
+
75
+ ### Configuration
76
+
77
+
78
+ ```ruby
79
+ DeadBro.configure do |config|
80
+ config.excluded_controllers = [
81
+ "HealthChecksController",
82
+ "Admin::*" # wildcard supported
83
+ ]
84
+
85
+ config.excluded_controller_actions = [
86
+ "UsersController#show",
87
+ "Admin::ReportsController#index",
88
+ "Admin::*#*" # wildcard supported for controller and action
89
+ ]
90
+
91
+ config.excluded_jobs = [
92
+ "ActiveStorage::AnalyzeJob",
93
+ "Admin::*"
94
+ ]
95
+ end
96
+ ```
97
+
98
+ Notes:
99
+ - Wildcards `*` are supported for controller and action (e.g., `Admin::*#*`).
100
+ - Matching is done against full names like `UsersController`, `Admin::ReportsController#index`, `MyJob`.
101
+
102
+ ## Exclusive Tracking (Whitelist Mode)
103
+
104
+ You can configure DeadBro to **only** track specific controllers, actions, or jobs. This is useful when you want to focus monitoring on a subset of your application.
105
+
106
+ ### Configuration
107
+
108
+ ```ruby
109
+ DeadBro.configure do |config|
110
+ # Only track these specific controller actions
111
+ config.exclusive_controller_actions = [
112
+ "UsersController#show",
113
+ "UsersController#index",
114
+ "Admin::ReportsController#*", # all actions in this controller
115
+ "Api::*#*" # all actions in all Api controllers
116
+ ]
117
+
118
+ # Only track these specific jobs
119
+ config.exclusive_jobs = [
120
+ "PaymentProcessingJob",
121
+ "EmailDeliveryJob",
122
+ "Admin::*" # all jobs in Admin namespace
123
+ ]
124
+ end
125
+ ```
126
+
127
+ ### How It Works
128
+
129
+ - **If `exclusive_controller_actions` or `exclusive_jobs` is empty/not defined**: All controllers/actions/jobs are tracked (default behavior)
130
+ - **If `exclusive_controller_actions` or `exclusive_jobs` is defined with values**: Only matching controllers/actions/jobs are tracked
131
+ - **Exclusion takes precedence**: If something is in both `excluded_*` and `exclusive_*`, it will be excluded (exclusion is checked first)
132
+
133
+ ### Use Cases
134
+
135
+ - **Focus on Critical Paths**: Monitor only your most important endpoints
136
+ - **Cost Optimization**: Track only specific high-value operations
137
+ - **Debugging**: Temporarily focus on specific controllers/jobs during investigation
138
+ - **Compliance**: Track only operations that require monitoring for compliance reasons
139
+
140
+ ### Environment Variables
141
+
142
+ You can also configure exclusive tracking via environment variables:
143
+
144
+ ```bash
145
+ # Comma-separated list of controller#action patterns
146
+ dead_bro_EXCLUSIVE_CONTROLLER_ACTIONS="UsersController#show,Admin::*#*"
147
+
148
+ # Comma-separated list of job patterns
149
+ dead_bro_EXCLUSIVE_JOBS="PaymentProcessingJob,EmailDeliveryJob"
150
+ ```
151
+
152
+ ## SQL Query Tracking
153
+
154
+ DeadBro automatically tracks SQL queries executed during each request and job. Each request will include a `sql_queries` array containing:
155
+ - `sql` - The SQL query (always sanitized)
156
+ - `name` - Query name (e.g., "User Load", "User Update")
157
+ - `duration_ms` - Query execution time in milliseconds
158
+ - `cached` - Whether the query was cached
159
+ - `connection_id` - Database connection ID
160
+ - `trace` - Call stack showing where the query was executed
161
+ - `explain_plan` - Query execution plan (when EXPLAIN ANALYZE is enabled, see below)
162
+
163
+ ## Automatic EXPLAIN ANALYZE for Slow Queries
164
+
165
+ DeadBro can automatically run `EXPLAIN ANALYZE` on slow SQL queries to help you understand query performance and identify optimization opportunities. This feature runs in the background and doesn't block your application requests.
166
+
167
+ ### How It Works
168
+
169
+ - **Automatic Detection**: When a query exceeds the configured threshold, DeadBro automatically captures its execution plan
170
+ - **Background Execution**: EXPLAIN ANALYZE runs in a separate thread using a dedicated database connection, so it never blocks your application
171
+ - **Database Support**: Works with PostgreSQL, MySQL, SQLite, and other databases
172
+ - **Smart Filtering**: Automatically skips transaction queries (BEGIN, COMMIT, ROLLBACK) and other queries that don't benefit from EXPLAIN
173
+
174
+ ### Configuration
175
+
176
+ - **`explain_analyze_enabled`** (default: `false`) - Set to `true` to enable automatic EXPLAIN ANALYZE
177
+ - **`slow_query_threshold_ms`** (default: `500`) - Queries taking longer than this threshold will have their execution plan captured
178
+
179
+ ### Example Configuration
180
+
181
+ ```ruby
182
+ DeadBro.configure do |config|
183
+ config.api_key = ENV['dead_bro_API_KEY']
184
+ config.enabled = true
185
+
186
+ # Enable EXPLAIN ANALYZE for queries slower than 500ms
187
+ config.explain_analyze_enabled = true
188
+ config.slow_query_threshold_ms = 500
189
+
190
+ # Or use a higher threshold for production
191
+ # config.slow_query_threshold_ms = 1000 # Only explain queries > 1 second
192
+ end
193
+ ```
194
+
195
+ ### What You Get
196
+
197
+ When a slow query is detected, the `explain_plan` field in the SQL query data will contain:
198
+ - **PostgreSQL**: Full EXPLAIN ANALYZE output with buffer usage statistics
199
+ - **MySQL**: EXPLAIN ANALYZE output showing actual execution times
200
+ - **SQLite**: EXPLAIN QUERY PLAN output
201
+ - **Other databases**: Standard EXPLAIN output
202
+
203
+ This execution plan helps you:
204
+ - Identify missing indexes
205
+ - Understand query execution order
206
+ - Spot full table scans
207
+ - Optimize JOIN operations
208
+ - Analyze buffer and cache usage (PostgreSQL)
209
+
210
+ ## View Rendering Tracking
211
+
212
+ DeadBro automatically tracks view rendering performance for each request. This includes:
213
+
214
+ - **Individual view events**: Templates, partials, and collections rendered
215
+ - **Performance metrics**: Rendering times for each view component
216
+ - **Cache analysis**: Cache hit rates for partials and collections
217
+ - **Slow view detection**: Identification of the slowest rendering views
218
+ - **Frequency analysis**: Most frequently rendered views
219
+
220
+ ## Memory Tracking & Leak Detection
221
+
222
+ DeadBro automatically tracks memory usage and detects memory leaks with minimal performance impact. This includes:
223
+
224
+ ### Performance-Optimized Memory Tracking
225
+
226
+ By default, DeadBro uses **lightweight memory tracking** that has minimal performance impact:
227
+
228
+ - **Memory Usage Monitoring**: Track memory consumption per request (using GC stats, not system calls)
229
+ - **Memory Leak Detection**: Detect growing memory patterns over time
230
+ - **GC Efficiency Analysis**: Monitor garbage collection effectiveness
231
+ - **Zero Allocation Tracking**: No object allocation tracking by default (can be enabled)
232
+
233
+ ### Configuration Options
234
+
235
+ ```ruby
236
+ # In your Rails configuration
237
+ DeadBro.configure do |config|
238
+ config.memory_tracking_enabled = true # Enable lightweight memory tracking (default: true)
239
+ config.allocation_tracking_enabled = false # Enable detailed allocation tracking (default: false)
240
+
241
+ # Sampling configuration
242
+ config.sample_rate = 100 # Percentage of requests to track (1-100, default: 100)
243
+ end
244
+ ```
245
+
246
+ **Performance Impact:**
247
+ - **Lightweight mode**: ~0.1ms overhead per request
248
+ - **Allocation tracking**: ~2-5ms overhead per request (only enable when needed)
249
+
250
+ ## Job Tracking
251
+
252
+ DeadBro automatically tracks ActiveJob background jobs when ActiveJob is available. Each job execution is tracked with:
253
+
254
+ - `job_class` - The job class name (e.g., "UserMailer::WelcomeEmail")
255
+ - `job_id` - Unique job identifier
256
+ - `queue_name` - The queue the job was processed from
257
+ - `arguments` - Sanitized job arguments (sensitive data filtered)
258
+ - `duration_ms` - Job execution time in milliseconds
259
+ - `status` - "completed" or "failed"
260
+ - `sql_queries` - Array of SQL queries executed during the job
261
+ - `exception_class` - Exception class name (for failed jobs)
262
+ - `message` - Exception message (for failed jobs)
263
+ - `backtrace` - Exception backtrace (for failed jobs)
264
+
265
+
266
+ ## Development
267
+
268
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
269
+
270
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`.
271
+
272
+ ## Contributing
273
+
274
+ Bug reports and pull requests are welcome on GitHub at https://github.com/rubydevro/dead_bro.