Module: OpenTrace::PayloadBuilder

Defined in:
lib/opentrace/payload_builder.rb

Overview

Materializes deferred log entries (frozen Arrays) into payload Hashes. All heavy work (context merge, timestamp formatting, Hash building) runs on the background dispatch thread, keeping the request thread fast.

Class Method Summary collapse

Class Method Details

.build_request_summary(collector, summary, controller, action, method, path, status, duration_ms) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/opentrace/payload_builder.rb', line 230

def build_request_summary(collector, summary, controller, action, method, path, status, duration_ms)
  rs = {
    controller: controller,
    action: action,
    method: method,
    path: path,
    status: status,
    duration_ms: duration_ms.round(1),
    sql_count: summary[:sql_query_count],
    sql_total_ms: summary[:sql_total_ms],
    sql_slowest_ms: summary[:sql_slowest_ms],
    sql_slowest_name: summary[:sql_slowest_name],
    n_plus_one: summary[:n_plus_one_warning] || false,
    view_count: summary[:view_render_count],
    view_total_ms: summary[:view_total_ms],
    view_slowest_ms: summary[:view_slowest_ms],
    view_slowest_template: summary[:view_slowest_template],
    cache_reads: summary[:cache_reads],
    cache_hits: summary[:cache_hits],
    cache_writes: summary[:cache_writes],
    cache_hit_ratio: summary[:cache_hit_ratio],
    http_external_count: summary[:http_external_count],
    http_external_total_ms: summary[:http_external_total_ms],
    http_slowest_ms: summary[:http_slowest_ms],
    http_slowest_host: summary[:http_slowest_host],
    memory_before_mb: summary[:memory_before_mb],
    memory_after_mb: summary[:memory_after_mb],
    memory_delta_mb: summary[:memory_delta_mb],
    timeline: summary[:timeline]
  }.compact

  # Compute time breakdown
  if duration_ms > 0
    sql_pct = [((collector.sql_total_ms / duration_ms) * 100).round(1), 100.0].min
    view_pct = [((collector.view_total_ms / duration_ms) * 100).round(1), 100.0].min
    http_pct = collector.http_count > 0 ? [((collector.http_total_ms / duration_ms) * 100).round(1), 100.0].min : 0.0
    other_pct = [100 - sql_pct - view_pct - http_pct, 0].max.round(1)
    rs[:time_breakdown] = {
      sql_pct: sql_pct,
      view_pct: view_pct,
      http_pct: http_pct,
      other_pct: other_pct
    }
  end

  rs
end

.clean_backtrace(backtrace) ⇒ Object



192
193
194
195
196
197
198
# File 'lib/opentrace/payload_builder.rb', line 192

def clean_backtrace(backtrace)
  if defined?(::Rails) && ::Rails.respond_to?(:backtrace_cleaner)
    ::Rails.backtrace_cleaner.clean(backtrace)
  else
    backtrace.reject { |line| line.include?("/gems/") }
  end
end

.extract_source_location(backtrace) ⇒ Object

Extract source file and line number from the first app-relevant backtrace line. Format: “app/controllers/users_controller.rb:42:in ‘show’”



178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/opentrace/payload_builder.rb', line 178

def extract_source_location(backtrace)
  return [nil, nil] unless backtrace.is_a?(Array) && !backtrace.empty?

  line = backtrace.first.to_s
  parts = line.split(":", 3)
  return [nil, nil] if parts.length < 2

  file = parts[0]
  line_num = parts[1].to_i
  [file, line_num]
rescue StandardError
  [nil, nil]
end

.format_timestamp(ts) ⇒ Object



165
166
167
168
169
170
171
172
173
174
# File 'lib/opentrace/payload_builder.rb', line 165

def format_timestamp(ts)
  case ts
  when Float
    Time.at(ts).utc.strftime("%Y-%m-%dT%H:%M:%S.%6NZ")
  when Time
    ts.utc.strftime("%Y-%m-%dT%H:%M:%S.%6NZ")
  else
    Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%6NZ")
  end
end

.materialize(entry, config) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/opentrace/payload_builder.rb', line 10

def materialize(entry, config)
  if entry.is_a?(Array)
    entry[0] == :request ? materialize_request(entry, config) : materialize_log(entry, config)
  elsif entry.is_a?(Hash)
    entry # legacy direct payload
  end
rescue StandardError => e
  OpenTrace.stats.increment(:payload_build_errors) if OpenTrace.respond_to?(:stats)
  $stderr.puts "[OpenTrace] PayloadBuilder error: #{e.class}: #{e.message}" if OpenTrace.respond_to?(:config) && OpenTrace.config.respond_to?(:debug) && OpenTrace.config.debug
  nil
end

.materialize_log(entry, config) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/opentrace/payload_builder.rb', line 22

def materialize_log(entry, config)
  ts, level, message, , ctx, request_id, trace_id,
    span_id, parent_span_id, req_summary, event_type = entry

  meta = ctx.is_a?(Hash) ? ctx.dup : {}
  meta.merge!() if .is_a?(Hash)

  static_ctx = OpenTrace.send(:static_context)
  static_ctx.each { |k, v| meta[k] ||= v }

  # Extract trace_id from metadata if user provided it there
  meta_trace_id = meta.delete(:trace_id)
  effective_trace_id = meta_trace_id || trace_id

  # Promote indexed fields to top-level (remove from metadata to avoid duplication)
  commit_hash = meta.delete(:git_sha)
  effective_request_id = meta.delete(:request_id) || request_id
  exception_class = meta.delete(:exception_class)
  error_fingerprint = meta.delete(:error_fingerprint)
  source_file, source_line = extract_source_location(meta[:backtrace])

  payload = {
    timestamp: format_timestamp(ts),
    level: level.to_s.upcase,
    service: config.service,
    environment: config.environment,
    message: message.to_s,
    metadata: meta.compact
  }

  payload[:commit_hash] = commit_hash if commit_hash
  payload[:request_id] = effective_request_id.to_s if effective_request_id
  payload[:exception_class] = exception_class if exception_class
  payload[:error_fingerprint] = error_fingerprint if error_fingerprint
  payload[:source_file] = source_file if source_file
  payload[:source_line] = source_line if source_line && source_line > 0
  payload[:event_type] = event_type.to_s if event_type
  payload[:trace_id] = effective_trace_id.to_s if effective_trace_id
  payload[:span_id] = span_id if span_id
  payload[:parent_span_id] = parent_span_id if parent_span_id
  payload[:request_summary] = req_summary if req_summary
  payload
end

.materialize_request(entry, config) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/opentrace/payload_builder.rb', line 66

def materialize_request(entry, config)
  _, started, finished, controller, action, method, path, status,
    exc_class, exc_message, exc_backtrace, request_id, trace_id,
    span_id, parent_span_id, cached_ctx, collector, extra = entry

  duration_ms = (finished && started) ? (finished - started) * 1000.0 : 0.0

  meta = cached_ctx.is_a?(Hash) ? cached_ctx.dup : {}
  meta.merge!(extra) if extra.is_a?(Hash)

  static_ctx = OpenTrace.send(:static_context)
  static_ctx.each { |k, v| meta[k] ||= v }
  meta[:request_id] ||= request_id if request_id

  if cached_ctx.is_a?(Hash) && cached_ctx.key?(:user_id)
    meta[:user_id] = cached_ctx[:user_id]
  end

  exception_class = nil
  error_fingerprint = nil
  source_file = nil
  source_line = nil

  if exc_class
    exception_class = exc_class
    meta[:exception_message] = exc_message&.slice(0, 500)
    if exc_backtrace
      cleaned = clean_backtrace(exc_backtrace)
      meta[:backtrace] = cleaned.first(15)
      error_fingerprint = OpenTrace.send(:compute_error_fingerprint, exc_class, cleaned)
      source_file, source_line = extract_source_location(cleaned)
    end
  end

  # Run deferred EXPLAIN on background thread
  if extra.is_a?(Hash) && extra[:pending_explains] && defined?(ActiveRecord::Base)
    explain_results = run_pending_explains(extra.delete(:pending_explains))
    meta[:explain_plans] = explain_results unless explain_results.empty?
  end

  # Build request_summary from collector
  request_summary = nil
  if collector
    summary = collector.summary
    request_summary = build_request_summary(collector, summary, controller, action, method, path, status, duration_ms)
  else
    # No collector — include request identity in metadata
    meta[:controller] = controller
    meta[:action] = action
    meta[:method] = method
    meta[:path] = path
    meta[:status] = status
    meta[:duration_ms] = duration_ms.round(1)
  end

  level = if exc_class
            "ERROR"
          elsif status.to_i >= 500
            "ERROR"
          elsif status.to_i >= 400
            "WARN"
          else
            "INFO"
          end

  # Use custom transaction name if set
  transaction_name = meta.delete(:transaction_name)
  message = if transaction_name
              "#{transaction_name} #{status} #{duration_ms.round(1)}ms"
            else
              "#{method} #{path} #{status} #{duration_ms.round(1)}ms"
            end
  meta[:transaction_name] = transaction_name if transaction_name

  # Promote indexed fields to top-level (remove from metadata to avoid duplication)
  commit_hash = meta.delete(:git_sha)
  effective_request_id = meta.delete(:request_id) || request_id

  payload = {
    timestamp: format_timestamp(started),
    level: level,
    service: config.service,
    environment: config.environment,
    message: message,
    metadata: meta.compact
  }
  payload[:commit_hash] = commit_hash if commit_hash
  payload[:request_id] = effective_request_id.to_s if effective_request_id
  payload[:exception_class] = exception_class if exception_class
  payload[:error_fingerprint] = error_fingerprint if error_fingerprint
  payload[:source_file] = source_file if source_file
  payload[:source_line] = source_line if source_line && source_line > 0
  payload[:trace_id] = trace_id.to_s if trace_id
  payload[:span_id] = span_id if span_id
  payload[:parent_span_id] = parent_span_id if parent_span_id
  payload[:request_summary] = request_summary if request_summary
  payload
end

.run_explain(sql) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/opentrace/payload_builder.rb', line 215

def run_explain(sql)
  # Only EXPLAIN simple SELECTs — reject anything suspicious
  normalized = sql.to_s.strip
  return nil unless normalized.match?(/\ASELECT\b/i)
  return nil if normalized.include?(";") # No multi-statement

  ActiveRecord::Base.connection_pool.with_connection do |conn|
    result = conn.execute("EXPLAIN #{normalized}")
    rows = result.respond_to?(:rows) ? result.rows : result.map(&:values)
    rows.flatten.join("\n").slice(0, 2000)
  end
rescue StandardError
  nil
end

.run_pending_explains(pending) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/opentrace/payload_builder.rb', line 200

def run_pending_explains(pending)
  pending.filter_map do |entry|
    plan = run_explain(entry[:sql])
    next unless plan
    {
      sql: entry[:sql].to_s.slice(0, 500),
      duration_ms: entry[:duration_ms],
      name: entry[:name],
      explain_plan: plan
    }
  end
rescue StandardError
  []
end