flare 0.4.2 → 0.5.1

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.
Files changed (43) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +72 -1
  3. data/app/controllers/flare/jobs_controller.rb +1 -1
  4. data/app/controllers/flare/requests_controller.rb +1 -1
  5. data/app/controllers/flare/spans_controller.rb +1 -1
  6. data/app/helpers/flare/application_helper.rb +23 -0
  7. data/app/views/flare/jobs/index.html.erb +2 -1
  8. data/app/views/flare/requests/index.html.erb +2 -1
  9. data/app/views/flare/requests/show.html.erb +16 -7
  10. data/app/views/flare/spans/index.html.erb +2 -1
  11. data/lib/flare/cli/doctor_command.rb +4 -11
  12. data/lib/flare/cli/local_spans.rb +110 -0
  13. data/lib/flare/cli/nplus1_command.rb +97 -0
  14. data/lib/flare/cli/project.rb +28 -0
  15. data/lib/flare/cli/request_command.rb +120 -0
  16. data/lib/flare/cli/requests_command.rb +45 -0
  17. data/lib/flare/cli/setup_command.rb +67 -41
  18. data/lib/flare/cli/status_command.rb +5 -2
  19. data/lib/flare/cli.rb +12 -0
  20. data/lib/flare/client_headers.rb +7 -3
  21. data/lib/flare/configuration.rb +28 -0
  22. data/lib/flare/export_filter.rb +273 -0
  23. data/lib/flare/filtering_span_processor.rb +14 -0
  24. data/lib/flare/http_transport.rb +4 -0
  25. data/lib/flare/metric_span_processor.rb +76 -37
  26. data/lib/flare/metric_submitter.rb +9 -1
  27. data/lib/flare/recording_batch_span_processor.rb +9 -1
  28. data/lib/flare/redis_statement_processor.rb +29 -0
  29. data/lib/flare/revision.rb +82 -0
  30. data/lib/flare/source_location.rb +21 -16
  31. data/lib/flare/sql_mask.rb +235 -0
  32. data/lib/flare/sqlite_exporter.rb +12 -8
  33. data/lib/flare/storage/sqlite.rb +195 -144
  34. data/lib/flare/storage.rb +1 -40
  35. data/lib/flare/store_statement.rb +136 -0
  36. data/lib/flare/trace_blob.rb +9 -5
  37. data/lib/flare/trace_exporter.rb +18 -3
  38. data/lib/flare/upload_url_pool.rb +2 -15
  39. data/lib/flare/utf8.rb +20 -0
  40. data/lib/flare/version.rb +1 -1
  41. data/lib/flare.rb +23 -3
  42. data/public/flare-assets/flare.css +10 -60
  43. metadata +45 -32
@@ -0,0 +1,273 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/parameter_filter"
5
+ require "set"
6
+ require "uri"
7
+
8
+ require_relative "sql_mask"
9
+ require_relative "store_statement"
10
+ require_relative "utf8"
11
+
12
+ module Flare
13
+ # Applies the app's filter_parameters and masks SQL values in span names and
14
+ # attributes before a trace leaves the process. Attributes that name the code
15
+ # or describe the request's shape are kept as they are, because the trace view
16
+ # and trace rules read them. Everything else is treated as possibly holding a
17
+ # value the app wouldn't want sent.
18
+ class ExportFilter
19
+ FILTERED = "[FILTERED]"
20
+ MAX_TEXT_BYTES = SqlMask::MAX_BYTES
21
+
22
+ # Applied even if the app's list is empty or was trimmed. Rails' generated
23
+ # list, plus the names credentials go by in URLs and headers.
24
+ DEFAULT_FILTERS = [
25
+ :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc,
26
+ /api.?key/i, /authoriz/i, /oauth/i, /\Aauth\z/i, /cookie/i, /session/i, /credential/i, /signature/i,
27
+ /jwt/i, /bearer/i, /pwd/i, /\Apass\z/i, /\Akey\z/i, /\Asig\z/i, /\Acode\z/i
28
+ ].freeze
29
+
30
+ KEPT = %w[
31
+ name identifier layout count cache_hits record_count class_name
32
+ mailer action message_id hit exist store
33
+ http.method http.request.method http.status_code http.response.status_code
34
+ http.scheme url.scheme http.route http.user_agent user_agent.original
35
+ db.system db.system.name db.name db.namespace
36
+ db.sql.table db.collection.name db.redis.database_index
37
+ exception.type server.port net.peer.port
38
+ ].to_set.freeze
39
+ KEPT_PREFIX = /\A(?:code|messaging|flare|otel)\./
40
+
41
+ # What these hold can't be sorted into safe and unsafe parts: message bodies
42
+ # and recipients, job arguments, request and exception contents.
43
+ OPAQUE = %w[
44
+ to from cc bcc reply_to subject mail
45
+ args arguments params parameters headers cookies body payload request response env session
46
+ exception exception_object exception.message exception.stacktrace
47
+ ].to_set.freeze
48
+ OPAQUE_PREFIX = /\Aemail\./
49
+
50
+ OPERATIONS = %w[db.operation db.operation.name].to_set.freeze
51
+ STATEMENTS = %w[db.statement db.query.text db.query db.sql sql statement query].to_set.freeze
52
+ # A leading comment or parenthesis counts, since a statement can start with one.
53
+ SQL_TEXT = %r{\A[\s(]*(?:/\*|--|(?:select|insert|update|delete|replace|merge|with|set|create|alter|drop|truncate|grant|revoke|explain|describe|show|call|exec|execute|values|copy|pragma|vacuum|lock|begin|prepare)\b)}i
54
+ # With no system to go on, only statements that clearly read as queries get
55
+ # SQL masking, since it keeps bare words like the arguments of SET session:x y.
56
+ QUERY_TEXT = /\A[\s(]*(?:select|insert|update|delete|replace|merge|with|explain|values)\b/i
57
+ STRUCTURED_TEXT = /\A\s*[{\[]/
58
+
59
+ URLS = %w[http.url url.full url.path http.target http.referer url.original].to_set.freeze
60
+ HOSTS = %w[http.host server.address net.peer.name].to_set.freeze
61
+ USERINFO = /\A.*@/m
62
+ MONGO = /mongo/i
63
+
64
+ URL_START = %r{\A((?:[a-z][a-z0-9+.-]*:)?//)([^/?#]*)(.*)\z}im
65
+ NUMERIC_PORT = /\A(?:\[[^\]]*\]|[^:]*)(?::\d*)?\z/
66
+ SCHEMELESS_USERINFO = %r{\A[^/?#]+@}
67
+ PATH_USERINFO = %r{(?<=/|\A)[^/@]+@[^/]*}
68
+
69
+ # One scan over free text, leftmost first, so what a URL contains is never read
70
+ # as a key and value. key or quoted_key holds a pair's name.
71
+ TEXT_TOKEN = %r{
72
+ (?<url>(?<!\w)(?:(?<![.+\-])[a-z][a-z0-9+.-]*+:)?//[^\s'"<>]*+(?:['"](?>[^\s<>@]{0,256})@[^\s<>]*+)?)
73
+ |(?<auth>(?<!\w)(?:bearer\s+\S++|basic\s+[A-Za-z0-9+/=]{8,}))
74
+ |(?:
75
+ (?<!\\)\\*+(?<quote>["'])(?<quoted_key>[\w.\-\[\]%]++)\\*+\k<quote>\]?
76
+ |(?<![\w.\-\[\]%])(?<key>[\w.\-\[\]%]++)
77
+ )\s*+(?:=>|=|:)\s*+
78
+ }xi
79
+ # A value longer than this is masked rather than judged on part of it.
80
+ VALUE_WINDOW = 256
81
+ VALUE = /\A[^\s&;,]*+/
82
+ QUOTED_VALUE = /\A\\*+(?:["']|\z)/
83
+ NESTED_VALUE = %r{=|%3d|//|%2f%2f|@|%40}i
84
+
85
+ class << self
86
+ # Built on use, and rebuilt if the list changes, because initializers and
87
+ # engines can add to filter_parameters at any point during boot.
88
+ def current
89
+ filters = app_filters
90
+ cached = @current
91
+ return cached.last if cached && cached.first == filters
92
+
93
+ filter = new(filters)
94
+ @current = [filters.dup.freeze, filter]
95
+ filter
96
+ end
97
+
98
+ private
99
+
100
+ def app_filters
101
+ return [] unless defined?(Rails) && Rails.respond_to?(:application) && Rails.application
102
+
103
+ Array(Rails.application.config.filter_parameters)
104
+ rescue StandardError
105
+ []
106
+ end
107
+ end
108
+
109
+ def initialize(filters = [])
110
+ @parameter_filter = ActiveSupport::ParameterFilter.new(DEFAULT_FILTERS + filters)
111
+ end
112
+
113
+ def attributes(attrs)
114
+ return {} if attrs.nil?
115
+
116
+ system = attrs["db.system"] || attrs["db.system.name"]
117
+ attrs.each_with_object({}) { |(name, value), out| out[name] = attribute(UTF8.scrub(name.to_s), value, system) }
118
+ end
119
+
120
+ def name(value)
121
+ return value unless value.is_a?(String)
122
+
123
+ free_text(clean(value))
124
+ rescue StandardError
125
+ FILTERED
126
+ end
127
+
128
+ private
129
+
130
+ def attribute(name, value, system)
131
+ return value if KEPT.include?(name) || KEPT_PREFIX.match?(name)
132
+ return FILTERED if OPAQUE.include?(name) || OPAQUE_PREFIX.match?(name)
133
+
134
+ case value
135
+ when String then text_attribute(name, value, system)
136
+ when Array then value.map { |item| attribute(name, item, system) }
137
+ else param_kept?(name, value) ? value : FILTERED
138
+ end
139
+ rescue StandardError
140
+ # A value that can't be processed doesn't go out.
141
+ FILTERED
142
+ end
143
+
144
+ def text_attribute(name, value, system)
145
+ return statement(value, system) if STATEMENTS.include?(name)
146
+ return SqlMask.operation_word(value) || SqlMask::PLACEHOLDER if OPERATIONS.include?(name)
147
+
148
+ text = clean(value)
149
+ if URLS.include?(name) then url(text)
150
+ elsif HOSTS.include?(name) then text.sub(USERINFO, "")
151
+ elsif name == "url.query" then query_string(text)
152
+ elsif name == "key" then StoreStatement.masked_key(text)
153
+ elsif param_kept?(name, text) then free_text(text)
154
+ else FILTERED
155
+ end
156
+ end
157
+
158
+ def clean(value)
159
+ UTF8.scrub(value.bytesize > MAX_TEXT_BYTES ? value.byteslice(0, MAX_TEXT_BYTES) : value)
160
+ end
161
+
162
+ def statement(text, system)
163
+ return StoreStatement.redis(text) if StoreStatement.redis_system?(system)
164
+ return StoreStatement.mongo(text) if MONGO.match?(system.to_s)
165
+
166
+ return command_only(clean(text)) unless SqlMask.sql_system?(system)
167
+
168
+ masked = SqlMask.mask(text, system)
169
+ return SqlMask::PLACEHOLDER if masked.empty?
170
+ return command_only(masked) if system.to_s.empty? && !QUERY_TEXT.match?(masked)
171
+
172
+ masked
173
+ end
174
+
175
+ def command_only(text)
176
+ command = SqlMask.command_word(text)
177
+ command ? "#{command} #{SqlMask::PLACEHOLDER}" : SqlMask::PLACEHOLDER
178
+ end
179
+
180
+ def url(text)
181
+ match = URL_START.match(text)
182
+ return without_fragment_and_query(text.sub(SCHEMELESS_USERINFO, "")) unless match
183
+
184
+ scheme, authority, rest = match.captures
185
+ if authority.include?("@")
186
+ authority = authority.sub(USERINFO, "")
187
+ elsif !NUMERIC_PORT.match?(authority)
188
+ return "#{scheme}#{FILTERED}"
189
+ end
190
+
191
+ "#{scheme}#{authority}#{without_fragment_and_query(rest)}"
192
+ end
193
+
194
+ def without_fragment_and_query(text)
195
+ base, query = text.split("#", 2).first.to_s.split("?", 2)
196
+ base = base.to_s.gsub(PATH_USERINFO, FILTERED)
197
+ query ? "#{base}?#{query_string(query)}" : base
198
+ end
199
+
200
+ def query_string(text)
201
+ text.gsub(/[^&;]+/) { |part| pair(part) }
202
+ end
203
+
204
+ def pair(part)
205
+ key, value = part.split("=", 2)
206
+ return FILTERED if value.nil?
207
+
208
+ pair_kept?(key, value) ? part : "#{key}=#{FILTERED}"
209
+ end
210
+
211
+ def pair_kept?(key, value)
212
+ !NESTED_VALUE.match?(value) && param_kept?(URI.decode_www_form_component(key), value)
213
+ end
214
+
215
+ # user[password]=x is checked as nested params, so filters written as
216
+ # "user.password" apply to it too.
217
+ def param_kept?(key, value)
218
+ unless key.include?("[")
219
+ result = @parameter_filter.filter_param(key, value)
220
+ return result.equal?(value) || result == value
221
+ end
222
+
223
+ path = key.split(/[\[\]]+/).reject(&:empty?)
224
+ nested = path.reverse.inject(value) { |inner, part| { part => inner } }
225
+ @parameter_filter.filter(nested) == nested
226
+ end
227
+
228
+ # Text with no known meaning: custom notification payloads, span names. Masks
229
+ # more than it needs to rather than guess where a value ends.
230
+ def free_text(text)
231
+ return FILTERED if STRUCTURED_TEXT.match?(text)
232
+ # What's left of SQL is still read for pairs, since a word like DROP can also
233
+ # start ordinary text.
234
+ text = SqlMask.mask(text) if SQL_TEXT.match?(text)
235
+
236
+ out = +""
237
+ position = 0
238
+ while (match = TEXT_TOKEN.match(text, position))
239
+ out << text[position...match.begin(0)]
240
+ position = match.end(0)
241
+
242
+ if match[:url] then out << text_url(match[:url])
243
+ elsif match[:auth] then out << match[:auth].split(/\s+/).first << " " << FILTERED
244
+ else
245
+ out << match[0]
246
+ value = text[position, VALUE_WINDOW + 1][VALUE]
247
+ next if value.length <= VALUE_WINDOW && pair_kept?(match[:key] || match[:quoted_key], value)
248
+
249
+ out << FILTERED
250
+ position = sensitive_value_end(text, position)
251
+ end
252
+ end
253
+ out << text[position..]
254
+ end
255
+
256
+ # A quote with an @ after it can't be read as a URL's parts, so none of it is kept.
257
+ def text_url(found)
258
+ scheme = found[/\A[^:\/]+(?=:)/]
259
+ return FILTERED if scheme && !param_kept?(scheme, found)
260
+
261
+ found.match?(/['"]/) ? "#{scheme}#{":" if scheme}//#{FILTERED}" : url(found)
262
+ end
263
+
264
+ # A quoted value may hold escapes and line breaks, so it masks everything after
265
+ # it. Otherwise the line ends it, which covers multi-word values like cookie
266
+ # lists.
267
+ def sensitive_value_end(text, position)
268
+ return text.length if QUOTED_VALUE.match?(text[position, VALUE_WINDOW])
269
+
270
+ text.index("\n", position) || text.length
271
+ end
272
+ end
273
+ end
@@ -82,6 +82,15 @@ module Flare
82
82
  complete: owner_finished || sampled_completion_span?(span_data),
83
83
  delay: owner_finished ? @marked_trace_grace_period : 0
84
84
  )
85
+ rescue StandardError => e
86
+ # The SDK calls processors without a rescue, so a bug here would raise
87
+ # into the app's request or job. Count every failure, warn once
88
+ # per process (keyed by pid so forked workers still warn).
89
+ @exception_count.increment
90
+ return if @on_finish_error_warned_pid == $$
91
+
92
+ @on_finish_error_warned_pid = $$
93
+ @logger.warn("[Flare::FilteringSpanProcessor] on_finish failed: #{e.class}: #{e.message}")
85
94
  end
86
95
 
87
96
  def force_flush(timeout: nil)
@@ -136,6 +145,8 @@ module Flare
136
145
 
137
146
  def enqueue(span_data, complete:, delay: 0)
138
147
  @mutex.synchronize do
148
+ return if @stopped
149
+
139
150
  trace_id = span_data.trace_id
140
151
  @trace_order << trace_id unless @pending_by_trace.key?(trace_id)
141
152
  @pending_by_trace[trace_id] ||= []
@@ -323,6 +334,9 @@ module Flare
323
334
  now = monotonic_now
324
335
  ready_trace_ids = @delayed_ready_by_trace.select { |_, ready_at| ready_at <= now }.keys
325
336
  ready_trace_ids.each do |trace_id|
337
+ # Overflow may have evicted the whole batch, so mark_trace_ready
338
+ # would not clear the entry and next_wait_timeout would return 0 forever.
339
+ @delayed_ready_by_trace.delete(trace_id)
326
340
  mark_trace_ready(trace_id)
327
341
  @marker.unmark(trace_id)
328
342
  end
@@ -55,6 +55,10 @@ module Flare
55
55
  http.open_timeout = effective_timeout(@open_timeout, deadline.remaining)
56
56
  http.read_timeout = effective_timeout(@read_timeout, deadline.remaining)
57
57
  http.write_timeout = effective_timeout(@write_timeout, deadline.remaining) if http.respond_to?(:write_timeout=)
58
+ # Net::HTTP silently resends a GET or PUT once after a read timeout or
59
+ # dropped connection, with a fresh timeout, so a slow server took twice
60
+ # the caller's budget. Callers decide when to try again.
61
+ http.max_retries = 0
58
62
 
59
63
  req = klass.new(uri.request_uri == "" ? "/" : uri.request_uri)
60
64
  headers.each { |k, v| req[k] = v }
@@ -1,7 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "active_support/inflector/methods"
3
4
  require_relative "metric_key"
4
5
  require_relative "http_metrics_config"
6
+ require_relative "sql_mask"
7
+ require_relative "store_statement"
5
8
 
6
9
  module Flare
7
10
  TRANSACTION_NAME_ATTRIBUTE = "flare.transaction_name" unless const_defined?(:TRANSACTION_NAME_ATTRIBUTE)
@@ -9,6 +12,8 @@ module Flare
9
12
  # OpenTelemetry SpanProcessor that extracts metrics from spans.
10
13
  # Aggregates counts, durations, and error rates by namespace/service/target/operation.
11
14
  class MetricSpanProcessor
15
+ MAX_METRIC_STATEMENT_BYTES = 4_096
16
+
12
17
  # Standard OTel span kind symbols
13
18
  SERVER = :server
14
19
  CLIENT = :client
@@ -26,9 +31,12 @@ module Flare
26
31
  "solid_cache" => "solid_cache"
27
32
  }.freeze
28
33
 
29
- def initialize(storage:, http_metrics_config: nil)
34
+ ACTIVE_JOB_ERROR_STATUS = /\AUnexpected ActiveJob Error (\S+)\z/
35
+
36
+ def initialize(storage:, http_metrics_config: nil, ignore_errors: nil)
30
37
  @storage = storage
31
38
  @http_metrics_config = http_metrics_config || HttpMetricsConfig::DEFAULT
39
+ @ignore_errors = ignore_errors || []
32
40
  @pid = $$
33
41
  end
34
42
 
@@ -55,6 +63,14 @@ module Flare
55
63
  elsif view_span?(span)
56
64
  record_view_metric(span)
57
65
  end
66
+ rescue StandardError => e
67
+ # The SDK calls processors without a rescue, so a bug here would raise
68
+ # into the app's request or job. Warn once per process so it can't
69
+ # flood the logs (keyed by pid so forked workers still warn).
70
+ return if @on_finish_error_warned_pid == $$
71
+
72
+ @on_finish_error_warned_pid = $$
73
+ warn "[Flare::MetricSpanProcessor] on_finish failed: #{e.class}: #{e.message}"
58
74
  end
59
75
 
60
76
  def force_flush(timeout: nil)
@@ -169,13 +185,21 @@ module Flare
169
185
 
170
186
  def record_db_metric(span)
171
187
  db_system = span.attributes["db.system"].to_s
188
+ # Read the table and operation from the statement without its values, so
189
+ # the words in a string literal can't become the metric's name. This runs on
190
+ # the request thread and needs only the start of a statement, and a literal
191
+ # the cut lands in is masked like any unterminated one.
192
+ raw_statement = span.attributes["db.statement"]
193
+ if raw_statement && SqlMask.sql_system?(db_system)
194
+ statement = SqlMask.mask(raw_statement.to_s.byteslice(0, MAX_METRIC_STATEMENT_BYTES), db_system)
195
+ end
172
196
 
173
197
  key = MetricKey.new(
174
198
  bucket: bucket_time(span),
175
199
  namespace: "db",
176
200
  service: db_system,
177
- target: extract_db_target(span, db_system),
178
- operation: extract_db_operation(span, db_system)
201
+ target: extract_db_target(span, db_system, statement),
202
+ operation: extract_db_operation(span, db_system, statement)
179
203
  )
180
204
 
181
205
  @storage.increment(
@@ -191,17 +215,18 @@ module Flare
191
215
  span.attributes["net.peer.name"] ||
192
216
  extract_host_from_url(span) ||
193
217
  "unknown"
218
+ host = host.to_s.sub(/\A.*@/m, "").downcase
194
219
 
195
220
  method = span.attributes["http.method"] ||
196
221
  span.attributes["http.request.method"] ||
197
222
  "UNKNOWN"
198
223
 
199
- path = resolve_http_path(span, host.to_s.downcase)
224
+ path = resolve_http_path(span, host)
200
225
 
201
226
  key = MetricKey.new(
202
227
  bucket: bucket_time(span),
203
228
  namespace: "http",
204
- service: host.to_s.downcase,
229
+ service: host,
205
230
  target: "#{method.to_s.upcase} #{path}",
206
231
  operation: http_status_class(span)
207
232
  )
@@ -257,9 +282,14 @@ module Flare
257
282
  ((span.end_timestamp - span.start_timestamp) / 1_000_000.0).round
258
283
  end
259
284
 
285
+ # A 5xx is an error. So is a request that raised before any response
286
+ # (a timeout, a dropped connection): it has no status code, only an error
287
+ # span status. 4xx responses also carry an error span status, so the
288
+ # span status only counts when there was no response at all.
260
289
  def http_error?(span)
261
290
  status = span.attributes["http.status_code"] || span.attributes["http.response.status_code"]
262
- status.to_i >= 500
291
+ code = status.to_i
292
+ code >= 500 || (code.zero? && span_error?(span))
263
293
  end
264
294
 
265
295
  def http_status_class(span)
@@ -275,7 +305,26 @@ module Flare
275
305
  end
276
306
 
277
307
  def span_error?(span)
278
- span.status&.code == OpenTelemetry::Trace::Status::ERROR
308
+ return false if span.status&.code != OpenTelemetry::Trace::Status::ERROR
309
+ return true if @ignore_errors.empty?
310
+
311
+ type = exception_type(span)
312
+ type.nil? || !ignored_exception_type?(type)
313
+ end
314
+
315
+ # A job's retried exception is recorded on its enqueue_retry child span,
316
+ # so the process span only names it in the status description.
317
+ def exception_type(span)
318
+ event = span.events&.reverse_each&.find { |e| e.name == "exception" }
319
+ event&.attributes&.[]("exception.type") ||
320
+ span.status.description.to_s[ACTIVE_JOB_ERROR_STATUS, 1]
321
+ end
322
+
323
+ # Subclasses of an ignored class match when the class is loaded.
324
+ def ignored_exception_type?(type)
325
+ klass = ActiveSupport::Inflector.safe_constantize(type)
326
+ names = klass.is_a?(Class) ? klass.ancestors.map(&:name) : [type]
327
+ names.any? { |name| @ignore_errors.include?(name) }
279
328
  end
280
329
 
281
330
  def extract_job_system(span)
@@ -291,50 +340,40 @@ module Flare
291
340
  end
292
341
  end
293
342
 
294
- def extract_db_target(span, db_system)
295
- case db_system
296
- when "redis"
343
+ def extract_db_target(span, db_system, statement)
344
+ if StoreStatement.redis_system?(db_system)
297
345
  # For Redis, use db.redis.namespace if available, or the database index
298
346
  span.attributes["db.redis.database_index"]&.to_s ||
299
347
  span.attributes["db.name"] ||
300
348
  "default"
301
349
  else
302
- # For SQL databases, prefer table name from attributes or parsed from SQL
350
+ # Prefer the table name from attributes. Only SQL statements are parsed
351
+ # for one; statement is nil for anything else.
303
352
  span.attributes["db.sql.table"] ||
304
- extract_sql_table(span) ||
353
+ span.attributes["db.mongodb.collection"] ||
354
+ span.attributes["db.collection.name"] ||
355
+ extract_sql_table(statement) ||
305
356
  span.attributes["db.name"] ||
306
357
  "unknown"
307
358
  end
308
359
  end
309
360
 
310
- def extract_db_operation(span, db_system)
311
- case db_system
312
- when "redis"
313
- span.attributes["db.operation"]&.to_s&.downcase ||
314
- span.name.to_s.split.last&.downcase ||
315
- "command"
361
+ def extract_db_operation(span, db_system, statement)
362
+ operation = SqlMask.operation_word(span.attributes["db.operation"])
363
+
364
+ if StoreStatement.redis_system?(db_system)
365
+ (operation || SqlMask.operation_word(span.name.to_s.split.last))&.downcase || "query"
316
366
  else
317
- span.attributes["db.operation"]&.to_s&.upcase ||
318
- extract_sql_operation(span) ||
319
- "query"
367
+ # The first word of a masked statement (SELECT, INSERT, UPDATE, etc.)
368
+ word = statement ? statement.split(" ", 2).first : SqlMask.command_word(span.attributes["db.statement"])
369
+ (operation || word)&.upcase || "query"
320
370
  end
321
371
  end
322
372
 
323
- def extract_sql_operation(span)
324
- statement = span.attributes["db.statement"]
325
- return nil unless statement
326
-
327
- # Extract first word (SELECT, INSERT, UPDATE, DELETE, etc.)
328
- statement.to_s.strip.split(/\s+/).first&.upcase
329
- end
330
-
331
- def extract_sql_table(span)
332
- statement = span.attributes["db.statement"]
373
+ def extract_sql_table(statement)
333
374
  return nil unless statement
334
375
 
335
- sql = statement.to_s.strip
336
-
337
- case sql
376
+ case statement
338
377
  when /\bFROM\s+[`"]?(\w+)[`"]?/i
339
378
  $1
340
379
  when /\bINTO\s+[`"]?(\w+)[`"]?/i
@@ -373,7 +412,7 @@ module Flare
373
412
  path = span.attributes["http.target"] ||
374
413
  span.attributes["url.path"] ||
375
414
  extract_path_from_url(span)
376
- path&.to_s&.split("?")&.first || "/"
415
+ path&.to_s&.split(/[?#]/)&.first || "/"
377
416
  end
378
417
 
379
418
  # Normalize URL paths to prevent cardinality explosion.
@@ -395,8 +434,8 @@ module Flare
395
434
  when /\A[0-9a-f]{24}\z/i
396
435
  # MongoDB ObjectId: /items/507f1f77bcf86cd799439011 -> /items/:id
397
436
  ":id"
398
- when /\A[0-9a-f]{32,}\z/i
399
- # Long hex strings (tokens, hashes): -> :token
437
+ when /\A[0-9a-f]{32,}\z/i, /[^@]@/
438
+ # Long hex strings (tokens, hashes), or anything shaped like user@host: -> :token
400
439
  ":token"
401
440
  else
402
441
  segment
@@ -24,6 +24,14 @@ module Flare
24
24
  # Max retries before giving up
25
25
  MAX_RETRIES = 3
26
26
 
27
+ # Network errors worth another try. A DNS failure or an unreachable host
28
+ # fails before anything is sent, like a refused connection.
29
+ RETRIABLE_ERRORS = [
30
+ Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout,
31
+ Errno::ECONNREFUSED, Errno::ECONNRESET,
32
+ SocketError, Errno::EHOSTUNREACH, Errno::ENETUNREACH
33
+ ].freeze
34
+
27
35
  class SubmissionError < StandardError
28
36
  attr_reader :request_id, :response_code, :response_body
29
37
 
@@ -179,7 +187,7 @@ module Flare
179
187
  result, should_retry = yield
180
188
  return [nil, DeadlineExceeded.new("metric submission deadline exceeded")] if deadline.expired?
181
189
  return [result, nil] unless should_retry
182
- rescue SubmissionError, Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout, Errno::ECONNREFUSED, Errno::ECONNRESET => e
190
+ rescue SubmissionError, *RETRIABLE_ERRORS => e
183
191
  last_error = e
184
192
  attempts_remaining -= 1
185
193
 
@@ -35,6 +35,8 @@ module Flare
35
35
  detect_forking
36
36
 
37
37
  @mutex.synchronize do
38
+ return if @stopped
39
+
38
40
  overflow = @queue.length + 1 - @max_queue_size
39
41
  @queue.shift(overflow) if overflow.positive?
40
42
  @queue << span
@@ -160,7 +162,13 @@ module Flare
160
162
  end
161
163
  SUCCESS
162
164
  ensure
163
- @mutex.synchronize { @queue.unshift(*snapshot) } if snapshot&.any?
165
+ if snapshot&.any?
166
+ @mutex.synchronize do
167
+ @queue.unshift(*snapshot)
168
+ overflow = @queue.length - @max_queue_size
169
+ @queue.shift(overflow) if overflow.positive?
170
+ end
171
+ end
164
172
  end
165
173
 
166
174
  def start_flush_export(snapshot, deadline)
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "opentelemetry/sdk"
4
+
5
+ require_relative "store_statement"
6
+
7
+ module Flare
8
+ # Replaces a Redis statement with its shape as the span starts, so raw arguments
9
+ # never reach a finished span: not the development database, not an export, and
10
+ # not another exporter the app has added. The Redis instrumentation sends the
11
+ # key only when it's told to include arguments, which Flare does for this.
12
+ class RedisStatementProcessor < OpenTelemetry::SDK::Trace::SpanProcessor
13
+ STATEMENT = "db.statement"
14
+
15
+ def on_start(span, _parent_context)
16
+ return unless span.kind == :client
17
+
18
+ attributes = span.attributes
19
+ return unless attributes && StoreStatement.redis_system?(attributes["db.system"])
20
+
21
+ statement = attributes[STATEMENT]
22
+ return unless statement
23
+
24
+ span.set_attribute(STATEMENT, StoreStatement.redis(statement, pipelined: span.name == "PIPELINED"))
25
+ rescue StandardError
26
+ span.set_attribute(STATEMENT, StoreStatement::PLACEHOLDER) if span.respond_to?(:set_attribute)
27
+ end
28
+ end
29
+ end