rails_why 0.1.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 +7 -0
- data/.github/workflows/ci.yml +24 -0
- data/CHANGELOG.md +22 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/DOCKER_INTEGRATION.md +109 -0
- data/LICENSE.txt +21 -0
- data/README.md +107 -0
- data/Rakefile +8 -0
- data/lib/rails_why/condition_analyzer.rb +298 -0
- data/lib/rails_why/configuration.rb +49 -0
- data/lib/rails_why/diagnostic_engine.rb +177 -0
- data/lib/rails_why/node.rb +62 -0
- data/lib/rails_why/rails_integration.rb +222 -0
- data/lib/rails_why/redactor.rb +114 -0
- data/lib/rails_why/report.rb +77 -0
- data/lib/rails_why/text_formatter.rb +90 -0
- data/lib/rails_why/tracer.rb +200 -0
- data/lib/rails_why/version.rb +5 -0
- data/lib/rails_why.rb +86 -0
- data/sig/rails_why.rbs +4 -0
- metadata +86 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RailsWhy
|
|
4
|
+
module RailsIntegration
|
|
5
|
+
if defined?(::Rails::Railtie)
|
|
6
|
+
class Railtie < ::Rails::Railtie
|
|
7
|
+
initializer "rails_why.configure" do |app|
|
|
8
|
+
RailsWhy.configure do |config|
|
|
9
|
+
config.root = app.root.to_s
|
|
10
|
+
config.excluded_paths += [
|
|
11
|
+
"vendor/",
|
|
12
|
+
"bundle/",
|
|
13
|
+
".gem/",
|
|
14
|
+
"node_modules/",
|
|
15
|
+
"tmp/",
|
|
16
|
+
"log/"
|
|
17
|
+
]
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
ActiveSupport.on_load(:active_record) do
|
|
21
|
+
RailsWhy::RailsIntegration.install_active_record_hooks!
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
ActiveSupport.on_load(:active_job) do
|
|
25
|
+
RailsWhy::RailsIntegration.install_active_job_hooks!
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
if defined?(::Sidekiq)
|
|
29
|
+
RailsWhy::RailsIntegration.install_sidekiq_hooks!
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
if ENV["RAILS_WHY_MIDDLEWARE"] == "1"
|
|
33
|
+
app.middleware.use RailsWhy::RailsIntegration::Middleware
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Trace correlation store for asynchronous jobs (ActiveJob / Sidekiq)
|
|
40
|
+
class AsyncCorrelator
|
|
41
|
+
@store = {}
|
|
42
|
+
@lock = Monitor.new
|
|
43
|
+
|
|
44
|
+
class << self
|
|
45
|
+
def store_trace(correlation_id, trace_data)
|
|
46
|
+
@lock.synchronize do
|
|
47
|
+
@store[correlation_id] = trace_data
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def retrieve_trace(correlation_id)
|
|
52
|
+
@lock.synchronize do
|
|
53
|
+
@store[correlation_id]
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def clear!
|
|
58
|
+
@lock.synchronize do
|
|
59
|
+
@store.clear
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def self.install_active_record_hooks!
|
|
66
|
+
return if @ar_hooks_installed
|
|
67
|
+
@ar_hooks_installed = true
|
|
68
|
+
|
|
69
|
+
::ActiveRecord::Base.prepend(ActiveRecordDiagnostics)
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def self.install_active_job_hooks!
|
|
73
|
+
return if @aj_hooks_installed
|
|
74
|
+
@aj_hooks_installed = true
|
|
75
|
+
|
|
76
|
+
::ActiveJob::Base.include(ActiveJobDiagnostics)
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def self.install_sidekiq_hooks!
|
|
80
|
+
return if @sidekiq_hooks_installed
|
|
81
|
+
@sidekiq_hooks_installed = true
|
|
82
|
+
|
|
83
|
+
::Sidekiq.configure_client do |config|
|
|
84
|
+
config.client_middleware do |chain|
|
|
85
|
+
chain.add(SidekiqClientMiddleware)
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
::Sidekiq.configure_server do |config|
|
|
90
|
+
config.server_middleware do |chain|
|
|
91
|
+
chain.add(SidekiqServerMiddleware)
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
module ActiveJobDiagnostics
|
|
97
|
+
def self.included(base)
|
|
98
|
+
base.class_eval do
|
|
99
|
+
attr_accessor :rails_why_correlation_id
|
|
100
|
+
|
|
101
|
+
around_enqueue do |job, block|
|
|
102
|
+
if Thread.current[RailsWhy::Tracer::THREAD_LOCAL_ACTIVE]
|
|
103
|
+
correlation_id = SecureRandom.uuid
|
|
104
|
+
job.rails_why_correlation_id = correlation_id
|
|
105
|
+
AsyncCorrelator.store_trace(correlation_id, {
|
|
106
|
+
job_class: job.class.name,
|
|
107
|
+
job_id: job.job_id,
|
|
108
|
+
enqueued_at: Time.now.utc.iso8601,
|
|
109
|
+
queue_name: job.queue_name
|
|
110
|
+
})
|
|
111
|
+
end
|
|
112
|
+
block.call
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
around_perform do |job, block|
|
|
116
|
+
if job.rails_why_correlation_id && AsyncCorrelator.retrieve_trace(job.rails_why_correlation_id)
|
|
117
|
+
RailsWhy.explain { block.call }
|
|
118
|
+
else
|
|
119
|
+
block.call
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# Native ActiveJob serialization hooks - preserves business arguments intact!
|
|
126
|
+
def serialize
|
|
127
|
+
data = super
|
|
128
|
+
if @rails_why_correlation_id
|
|
129
|
+
data["rails_why_correlation_id"] = @rails_why_correlation_id
|
|
130
|
+
end
|
|
131
|
+
data
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def deserialize(job_data)
|
|
135
|
+
super
|
|
136
|
+
if job_data["rails_why_correlation_id"]
|
|
137
|
+
@rails_why_correlation_id = job_data["rails_why_correlation_id"]
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
class SidekiqClientMiddleware
|
|
143
|
+
def call(worker_class, job, queue, redis_pool)
|
|
144
|
+
if Thread.current[RailsWhy::Tracer::THREAD_LOCAL_ACTIVE]
|
|
145
|
+
correlation_id = SecureRandom.uuid
|
|
146
|
+
job["rails_why_correlation_id"] = correlation_id
|
|
147
|
+
AsyncCorrelator.store_trace(correlation_id, {
|
|
148
|
+
worker_class: worker_class.to_s,
|
|
149
|
+
jid: job["jid"],
|
|
150
|
+
enqueued_at: Time.now.to_f,
|
|
151
|
+
queue: queue
|
|
152
|
+
})
|
|
153
|
+
end
|
|
154
|
+
yield
|
|
155
|
+
end
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
class SidekiqServerMiddleware
|
|
159
|
+
def call(worker, job, queue)
|
|
160
|
+
correlation_id = job["rails_why_correlation_id"]
|
|
161
|
+
if correlation_id && AsyncCorrelator.retrieve_trace(correlation_id)
|
|
162
|
+
RailsWhy.explain { yield }
|
|
163
|
+
else
|
|
164
|
+
yield
|
|
165
|
+
end
|
|
166
|
+
end
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
module ActiveRecordDiagnostics
|
|
170
|
+
def valid?(context = nil)
|
|
171
|
+
result = super
|
|
172
|
+
if !result && errors.any?
|
|
173
|
+
report_diagnostic_error(errors.full_messages)
|
|
174
|
+
end
|
|
175
|
+
result
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
def run_callbacks(kind, &block)
|
|
179
|
+
super(kind) do
|
|
180
|
+
yield if block_given?
|
|
181
|
+
end
|
|
182
|
+
rescue StandardError => e
|
|
183
|
+
raise e
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
private
|
|
187
|
+
|
|
188
|
+
def report_diagnostic_error(msgs)
|
|
189
|
+
# Store on active tracer thread storage so report can capture it even if model method wasn't app-traced
|
|
190
|
+
stack = Thread.current[RailsWhy::Tracer::THREAD_LOCAL_STACK]
|
|
191
|
+
current_node = stack&.last
|
|
192
|
+
if current_node
|
|
193
|
+
current_node.validation_errors.concat(msgs)
|
|
194
|
+
end
|
|
195
|
+
# Also store on thread-level for Rails diagnostics
|
|
196
|
+
Thread.current[:__rails_why_ar_errors] ||= []
|
|
197
|
+
Thread.current[:__rails_why_ar_errors].concat(msgs)
|
|
198
|
+
end
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
class Middleware
|
|
202
|
+
def initialize(app)
|
|
203
|
+
@app = app
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
def call(env)
|
|
207
|
+
# Check if tracing is requested via header or query param
|
|
208
|
+
req = Rack::Request.new(env)
|
|
209
|
+
if req.params["explain"] == "1" || env["HTTP_X_RAILS_WHY"] == "1"
|
|
210
|
+
report = nil
|
|
211
|
+
res = RailsWhy.explain do
|
|
212
|
+
@app.call(env)
|
|
213
|
+
end
|
|
214
|
+
# Log or attach report
|
|
215
|
+
res
|
|
216
|
+
else
|
|
217
|
+
@app.call(env)
|
|
218
|
+
end
|
|
219
|
+
end
|
|
220
|
+
end
|
|
221
|
+
end
|
|
222
|
+
end
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RailsWhy
|
|
4
|
+
class Redactor
|
|
5
|
+
REDACTED = "[FILTERED]"
|
|
6
|
+
|
|
7
|
+
def initialize(config)
|
|
8
|
+
@config = config
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
def redact(value, key = nil)
|
|
12
|
+
return value unless @config.redact_sensitive_data
|
|
13
|
+
|
|
14
|
+
if key && sensitive_key?(key)
|
|
15
|
+
return REDACTED
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
case value
|
|
19
|
+
when Hash
|
|
20
|
+
redact_hash(value)
|
|
21
|
+
when Array
|
|
22
|
+
value.map { |item| redact(item) }
|
|
23
|
+
when String
|
|
24
|
+
redact_string(value, key)
|
|
25
|
+
when Numeric, TrueClass, FalseClass, NilClass, Symbol
|
|
26
|
+
value
|
|
27
|
+
else
|
|
28
|
+
safe_inspect(value)
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def redact_sensitive_snippet(snippet_text)
|
|
33
|
+
return snippet_text unless @config.redact_sensitive_data
|
|
34
|
+
return snippet_text if snippet_text.nil?
|
|
35
|
+
|
|
36
|
+
cleaned = snippet_text.dup
|
|
37
|
+
cleaned.gsub!(/["'][a-zA-Z0-9_\-\.]{15,}["']/, "\"#{REDACTED}\"")
|
|
38
|
+
cleaned.gsub!(/["']tok_[a-zA-Z0-9_]+["']/, "\"#{REDACTED}\"")
|
|
39
|
+
cleaned.gsub!(/Bearer\s+[a-zA-Z0-9_\-\.]+/i, "Bearer #{REDACTED}")
|
|
40
|
+
|
|
41
|
+
@config.sensitive_patterns.each do |pattern|
|
|
42
|
+
# If a string literal matches the sensitive pattern, redact it
|
|
43
|
+
cleaned.gsub!(/["'][^"']*#{pattern.source}[^"']*["']/i, "\"#{REDACTED}\"")
|
|
44
|
+
end
|
|
45
|
+
cleaned
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def safe_inspect(value)
|
|
49
|
+
return "nil" if value.nil?
|
|
50
|
+
|
|
51
|
+
# If it's an ActiveRecord model or similar with sensitive attributes
|
|
52
|
+
if defined?(ActiveRecord::Base) && value.is_a?(ActiveRecord::Base)
|
|
53
|
+
return "#<#{value.class.name} id: #{value.id || 'new'}>"
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# For arbitrary custom objects, avoid invoking custom inspect or to_s by default if they could execute side effects
|
|
57
|
+
# Instead, use standard Kernel#to_s or safe Object inspection
|
|
58
|
+
inspected = begin
|
|
59
|
+
if value.is_a?(Numeric) || value.is_a?(Symbol) || value.is_a?(TrueClass) || value.is_a?(FalseClass)
|
|
60
|
+
value.inspect
|
|
61
|
+
elsif value.is_a?(String)
|
|
62
|
+
redact_string(value)
|
|
63
|
+
else
|
|
64
|
+
# Inspect safely using Kernel format to avoid calling custom overridden inspect methods with side-effects
|
|
65
|
+
"#<#{value.class.name}:0x#{value.object_id.to_s(16)}>"
|
|
66
|
+
end
|
|
67
|
+
rescue StandardError => e
|
|
68
|
+
"#<Uninspectable: #{e.class}>"
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
if inspected.length > @config.max_string_length
|
|
72
|
+
"#{inspected[0...@config.max_string_length]}... [truncated]"
|
|
73
|
+
else
|
|
74
|
+
inspected
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
private
|
|
79
|
+
|
|
80
|
+
def sensitive_key?(key)
|
|
81
|
+
key_str = key.to_s
|
|
82
|
+
@config.sensitive_patterns.any? { |pattern| pattern.match?(key_str) }
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def redact_hash(hash)
|
|
86
|
+
hash.each_with_object({}) do |(k, v), result|
|
|
87
|
+
result[k] = sensitive_key?(k) ? REDACTED : redact(v, k)
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def redact_string(str, key = nil)
|
|
92
|
+
return REDACTED if key && sensitive_key?(key)
|
|
93
|
+
|
|
94
|
+
# Check for credit card patterns, bearer tokens, or password/token values
|
|
95
|
+
if str =~ /bearer\s+[a-z0-9_\-\.]+/i ||
|
|
96
|
+
str =~ /\b\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}\b/ ||
|
|
97
|
+
str =~ /\btok_[a-zA-Z0-9_]+\b/ || # token prefixes like tok_
|
|
98
|
+
str =~ /eyJ[a-zA-Z0-9_\-]+\.eyJ[a-zA-Z0-9_\-]+\.[a-zA-Z0-9_\-]+/ # JWT token pattern
|
|
99
|
+
return REDACTED
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# Check if string itself matches any sensitive patterns (e.g. "secret123", "password")
|
|
103
|
+
if @config.sensitive_patterns.any? { |pattern| pattern.match?(str) }
|
|
104
|
+
return REDACTED
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
if str.length > @config.max_string_length
|
|
108
|
+
"#{str[0...@config.max_string_length]}... [truncated]"
|
|
109
|
+
else
|
|
110
|
+
str
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
end
|
|
114
|
+
end
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module RailsWhy
|
|
6
|
+
class Report
|
|
7
|
+
attr_reader :result, :raised_exception, :root_nodes, :total_events,
|
|
8
|
+
:duration_ms, :expected_result, :config
|
|
9
|
+
|
|
10
|
+
def initialize(result:, raised_exception:, root_nodes:, total_events:, duration_ms:, expected_result: :not_specified, config: nil)
|
|
11
|
+
@config = config || RailsWhy.configuration
|
|
12
|
+
@redactor = Redactor.new(@config)
|
|
13
|
+
@result = result
|
|
14
|
+
@raised_exception = raised_exception
|
|
15
|
+
@root_nodes = root_nodes
|
|
16
|
+
@total_events = total_events
|
|
17
|
+
@duration_ms = duration_ms
|
|
18
|
+
@expected_result = expected_result
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def safe_result
|
|
22
|
+
@redactor.redact(@result)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def to_h
|
|
26
|
+
redactor = Redactor.new(@config)
|
|
27
|
+
{
|
|
28
|
+
result: redactor.safe_inspect(@result),
|
|
29
|
+
exception: @raised_exception ? { class: @raised_exception.class.name, message: @raised_exception.message } : nil,
|
|
30
|
+
expected: @expected_result == :not_specified ? nil : @expected_result,
|
|
31
|
+
duration_ms: @duration_ms,
|
|
32
|
+
total_events: @total_events,
|
|
33
|
+
root_causes: root_causes.map { |node| node_to_h(node, redactor) },
|
|
34
|
+
trace_tree: @root_nodes.map { |node| node_to_h(node, redactor, recursive: true) }
|
|
35
|
+
}
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def to_json(*args)
|
|
39
|
+
JSON.pretty_generate(to_h)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def root_causes
|
|
43
|
+
all_nodes = @root_nodes.flat_map { |n| [n, *n.all_descendants] }
|
|
44
|
+
all_nodes.select(&:is_root_cause_candidate)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
private
|
|
48
|
+
|
|
49
|
+
def node_to_h(node, redactor, recursive: false)
|
|
50
|
+
h = {
|
|
51
|
+
id: node.id,
|
|
52
|
+
call: node.call_signature,
|
|
53
|
+
file: relative_path(node.path),
|
|
54
|
+
line: node.line,
|
|
55
|
+
return_value: redactor.safe_inspect(node.return_value),
|
|
56
|
+
arguments: node.arguments,
|
|
57
|
+
duration_ms: node.duration_ms,
|
|
58
|
+
explanation: node.explanation,
|
|
59
|
+
conditions: node.conditions.map { |c| { code: c.code, status: c.status, branch: c.branch_taken, location: c.location } },
|
|
60
|
+
sql_queries: node.sql_queries,
|
|
61
|
+
validation_errors: node.validation_errors,
|
|
62
|
+
aborted_callbacks: node.aborted_callbacks
|
|
63
|
+
}
|
|
64
|
+
h[:exception] = node.exception if node.exception
|
|
65
|
+
if recursive
|
|
66
|
+
h[:children] = node.children.map { |c| node_to_h(c, redactor, recursive: true) }
|
|
67
|
+
end
|
|
68
|
+
h
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def relative_path(path)
|
|
72
|
+
return path unless path
|
|
73
|
+
root = File.expand_path(@config.root)
|
|
74
|
+
path.delete_prefix("#{root}/")
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RailsWhy
|
|
4
|
+
class TextFormatter
|
|
5
|
+
def initialize(report, config)
|
|
6
|
+
@report = report
|
|
7
|
+
@config = config
|
|
8
|
+
@redactor = Redactor.new(config)
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
def format
|
|
12
|
+
lines = []
|
|
13
|
+
lines << "\n" + "=" * 65
|
|
14
|
+
lines << " RAILS WHY EXPLANATION"
|
|
15
|
+
lines << "=" * 65
|
|
16
|
+
|
|
17
|
+
# Summary header
|
|
18
|
+
lines << "Result: #{@redactor.safe_inspect(@report.result)}"
|
|
19
|
+
if @report.expected_result != :not_specified
|
|
20
|
+
lines << "Expected: #{@report.expected_result.inspect}"
|
|
21
|
+
end
|
|
22
|
+
if @report.raised_exception
|
|
23
|
+
lines << "Raised: #{@report.raised_exception.class}: #{@report.raised_exception.message}"
|
|
24
|
+
end
|
|
25
|
+
lines << "Duration: #{@report.duration_ms} ms | Traced Events: #{@report.total_events}"
|
|
26
|
+
lines << "-" * 65
|
|
27
|
+
|
|
28
|
+
# Root causes
|
|
29
|
+
causes = @report.root_causes
|
|
30
|
+
if causes.any?
|
|
31
|
+
lines << "\n[!] POTENTIAL ROOT CAUSES & FAILING CONDITIONS:"
|
|
32
|
+
causes.each do |c|
|
|
33
|
+
lines << " • #{c.call_signature} (#{relative_path(c.path)}:#{c.line})"
|
|
34
|
+
lines << " Reason: #{c.explanation}" if c.explanation
|
|
35
|
+
if c.validation_errors.any?
|
|
36
|
+
lines << " ActiveRecord Errors: #{c.validation_errors.join(', ')}"
|
|
37
|
+
end
|
|
38
|
+
if c.aborted_callbacks.any?
|
|
39
|
+
lines << " Aborted Callback: #{c.aborted_callbacks.join(', ')}"
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
lines << "-" * 65
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# Execution Tree
|
|
46
|
+
lines << "\n[>] EXECUTION TREE:"
|
|
47
|
+
@report.root_nodes.each do |root_node|
|
|
48
|
+
format_node(root_node, lines, 0)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
lines << "=" * 65
|
|
52
|
+
lines.join("\n")
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
private
|
|
56
|
+
|
|
57
|
+
def format_node(node, lines, depth)
|
|
58
|
+
indent = " " * depth
|
|
59
|
+
prefix = depth.zero? ? "┌─ " : "├─ "
|
|
60
|
+
status_marker = node.is_root_cause_candidate ? " [FAIL]" : ""
|
|
61
|
+
ret = @redactor.safe_inspect(node.return_value)
|
|
62
|
+
|
|
63
|
+
lines << "#{indent}#{prefix}#{node.call_signature} => #{ret}#{status_marker}"
|
|
64
|
+
lines << "#{indent}│ at #{relative_path(node.path)}:#{node.line}"
|
|
65
|
+
|
|
66
|
+
if node.arguments.any?
|
|
67
|
+
args_str = node.arguments.map { |k, v| "#{k}: #{v}" }.join(", ")
|
|
68
|
+
lines << "#{indent}│ args: (#{args_str})"
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
node.conditions.each do |cond|
|
|
72
|
+
lines << "#{indent}│ condition [#{cond.status}]: #{cond.code}"
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
node.sql_queries.each do |query|
|
|
76
|
+
lines << "#{indent}│ sql: #{query[:sql]}"
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
node.children.each do |child|
|
|
80
|
+
format_node(child, lines, depth + 1)
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def relative_path(path)
|
|
85
|
+
return path unless path
|
|
86
|
+
root = File.expand_path(@config.root)
|
|
87
|
+
path.delete_prefix("#{root}/")
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
end
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "securerandom"
|
|
4
|
+
|
|
5
|
+
module RailsWhy
|
|
6
|
+
class Tracer
|
|
7
|
+
THREAD_LOCAL_ACTIVE = :__rails_why_active
|
|
8
|
+
THREAD_LOCAL_STACK = :__rails_why_stack
|
|
9
|
+
THREAD_LOCAL_EVENTS = :__rails_why_events
|
|
10
|
+
THREAD_LOCAL_NODES = :__rails_why_nodes
|
|
11
|
+
THREAD_LOCAL_EXCEPTION = :__rails_why_raised_exception
|
|
12
|
+
|
|
13
|
+
def initialize(config)
|
|
14
|
+
@config = config
|
|
15
|
+
@redactor = Redactor.new(config)
|
|
16
|
+
@condition_analyzer = ConditionAnalyzer.new(config)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def trace
|
|
20
|
+
# Support nested/re-entrant tracing safely: if already active in this thread, do not double-instrument
|
|
21
|
+
if Thread.current[THREAD_LOCAL_ACTIVE]
|
|
22
|
+
result = yield
|
|
23
|
+
return {
|
|
24
|
+
result: result,
|
|
25
|
+
raised_exception: nil,
|
|
26
|
+
root_nodes: [],
|
|
27
|
+
total_events: 0,
|
|
28
|
+
duration_ms: 0.0
|
|
29
|
+
}
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
Thread.current[THREAD_LOCAL_ACTIVE] = true
|
|
33
|
+
Thread.current[THREAD_LOCAL_STACK] = []
|
|
34
|
+
Thread.current[THREAD_LOCAL_EVENTS] = []
|
|
35
|
+
Thread.current[THREAD_LOCAL_NODES] = []
|
|
36
|
+
Thread.current[THREAD_LOCAL_EXCEPTION] = nil
|
|
37
|
+
|
|
38
|
+
node_counter = 0
|
|
39
|
+
event_count = 0
|
|
40
|
+
root_nodes = []
|
|
41
|
+
|
|
42
|
+
# Thread-local storage references
|
|
43
|
+
stack = Thread.current[THREAD_LOCAL_STACK]
|
|
44
|
+
|
|
45
|
+
tracer = TracePoint.new(:call, :return, :line, :raise) do |tp|
|
|
46
|
+
next unless Thread.current[THREAD_LOCAL_ACTIVE]
|
|
47
|
+
|
|
48
|
+
path = tp.path
|
|
49
|
+
next unless @config.path_included?(path)
|
|
50
|
+
|
|
51
|
+
if event_count >= @config.max_events
|
|
52
|
+
tracer.disable
|
|
53
|
+
next
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
event_count += 1
|
|
57
|
+
|
|
58
|
+
case tp.event
|
|
59
|
+
when :call
|
|
60
|
+
# Ignore internal rspec calls if they are happening inside block evaluation
|
|
61
|
+
next if tp.defined_class.to_s.start_with?("RSpec::")
|
|
62
|
+
next if stack.size >= @config.max_depth
|
|
63
|
+
|
|
64
|
+
node_counter += 1
|
|
65
|
+
parent = stack.last
|
|
66
|
+
|
|
67
|
+
node = Node.new(
|
|
68
|
+
id: node_counter,
|
|
69
|
+
parent_id: parent&.id,
|
|
70
|
+
defined_class: tp.defined_class.to_s,
|
|
71
|
+
method_name: tp.method_id,
|
|
72
|
+
path: path,
|
|
73
|
+
line: tp.lineno,
|
|
74
|
+
call_type: :method
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# Capture method parameters safely if available
|
|
78
|
+
begin
|
|
79
|
+
params = tp.parameters
|
|
80
|
+
# We don't have argument values directly from TracePoint tp.parameters (only names),
|
|
81
|
+
# but we can capture binding local variables if safe
|
|
82
|
+
if tp.binding
|
|
83
|
+
params.each do |(_type, name)|
|
|
84
|
+
next unless name
|
|
85
|
+
begin
|
|
86
|
+
val = tp.binding.local_variable_get(name)
|
|
87
|
+
node.arguments[name] = @redactor.safe_inspect(@redactor.redact(val, name))
|
|
88
|
+
rescue StandardError
|
|
89
|
+
# ignore binding extraction errors
|
|
90
|
+
end
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
rescue StandardError
|
|
94
|
+
# Safe degradation
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
if parent
|
|
98
|
+
parent.add_child(node)
|
|
99
|
+
else
|
|
100
|
+
root_nodes << node
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
stack.push(node)
|
|
104
|
+
|
|
105
|
+
when :line
|
|
106
|
+
current_node = stack.last
|
|
107
|
+
current_node&.record_line(tp.lineno)
|
|
108
|
+
|
|
109
|
+
when :return
|
|
110
|
+
next if stack.empty?
|
|
111
|
+
|
|
112
|
+
node = stack.pop
|
|
113
|
+
val = tp.return_value
|
|
114
|
+
node.return_value = @redactor.redact(val)
|
|
115
|
+
|
|
116
|
+
when :raise
|
|
117
|
+
current_node = stack.last
|
|
118
|
+
raised = tp.raised_exception
|
|
119
|
+
if current_node && raised
|
|
120
|
+
current_node.exception = {
|
|
121
|
+
class: raised.class.name,
|
|
122
|
+
message: @redactor.redact(raised.message),
|
|
123
|
+
backtrace: raised.backtrace&.first(5)
|
|
124
|
+
}
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
# Hook Rails notifications if enabled and available
|
|
130
|
+
rails_cleanup = setup_rails_notifications
|
|
131
|
+
|
|
132
|
+
result = nil
|
|
133
|
+
raised_error = nil
|
|
134
|
+
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
135
|
+
|
|
136
|
+
begin
|
|
137
|
+
tracer.enable(target_thread: Thread.current) do
|
|
138
|
+
result = yield
|
|
139
|
+
end
|
|
140
|
+
rescue StandardError, ScriptError => e
|
|
141
|
+
raised_error = e
|
|
142
|
+
Thread.current[THREAD_LOCAL_EXCEPTION] = e
|
|
143
|
+
ensure
|
|
144
|
+
tracer.disable
|
|
145
|
+
rails_cleanup&.call
|
|
146
|
+
Thread.current[THREAD_LOCAL_ACTIVE] = nil
|
|
147
|
+
Thread.current[THREAD_LOCAL_STACK] = nil
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000.0).round(2)
|
|
151
|
+
|
|
152
|
+
# Analyze conditions for all executed nodes using Prism
|
|
153
|
+
all_nodes = root_nodes.flat_map { |n| [n, *n.all_descendants] }
|
|
154
|
+
all_nodes.each do |n|
|
|
155
|
+
n.conditions = @condition_analyzer.analyze_node(n)
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# Re-raise error if occurred, after building trace
|
|
159
|
+
{
|
|
160
|
+
result: result,
|
|
161
|
+
raised_exception: raised_error,
|
|
162
|
+
root_nodes: root_nodes,
|
|
163
|
+
total_events: event_count,
|
|
164
|
+
duration_ms: duration_ms
|
|
165
|
+
}
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
private
|
|
169
|
+
|
|
170
|
+
def setup_rails_notifications
|
|
171
|
+
return nil unless @config.enable_rails_notifications && defined?(ActiveSupport::Notifications)
|
|
172
|
+
|
|
173
|
+
subscriptions = []
|
|
174
|
+
|
|
175
|
+
subscriptions << ActiveSupport::Notifications.subscribe("sql.active_record") do |_name, _start, _finish, _id, payload|
|
|
176
|
+
stack = Thread.current[THREAD_LOCAL_STACK]
|
|
177
|
+
current_node = stack&.last
|
|
178
|
+
sql = payload[:sql]
|
|
179
|
+
if sql
|
|
180
|
+
query_info = {
|
|
181
|
+
sql: @redactor.redact(sql),
|
|
182
|
+
name: payload[:name],
|
|
183
|
+
cached: payload[:cached] || false
|
|
184
|
+
}
|
|
185
|
+
if current_node
|
|
186
|
+
current_node.sql_queries << query_info
|
|
187
|
+
end
|
|
188
|
+
Thread.current[:__rails_why_sql_queries] ||= []
|
|
189
|
+
Thread.current[:__rails_why_sql_queries] << query_info
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
-> {
|
|
194
|
+
subscriptions.each { |sub| ActiveSupport::Notifications.unsubscribe(sub) }
|
|
195
|
+
}
|
|
196
|
+
rescue StandardError
|
|
197
|
+
nil
|
|
198
|
+
end
|
|
199
|
+
end
|
|
200
|
+
end
|