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,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Flare
4
+ # Works out the deployed revision of the app this client runs in, usually a
5
+ # git SHA. Flare.configuration.revision calls it once, the first time the
6
+ # revision is asked for; it's sent as X-Client-Revision so the server can
7
+ # mark deploys on the charts.
8
+ #
9
+ # In order:
10
+ # 1. The configured value (config.revision, which defaults to FLARE_REVISION)
11
+ # 2. A platform's variable (Heroku, Render, Railway, Kamal, Fly, ...)
12
+ # 3. A REVISION file in the app root (Capistrano, many Docker builds)
13
+ # 4. git rev-parse HEAD, only when the app root has a .git directory
14
+ # Nil when none of them answer; the server treats a missing header as
15
+ # "unknown".
16
+ module Revision
17
+ MAX_LENGTH = 64
18
+
19
+ # Variable => how to read a revision from it (nil: the value as is).
20
+ PLATFORM_VARIABLES = {
21
+ "HEROKU_SLUG_COMMIT" => nil,
22
+ "RENDER_GIT_COMMIT" => nil,
23
+ "RAILWAY_GIT_COMMIT_SHA" => nil,
24
+ "KAMAL_VERSION" => nil,
25
+ # The whole image reference ("registry.fly.io/app:deployment-01J...@sha256:...").
26
+ # Its tag names the deploy, and is the git SHA when deployed with --image-label.
27
+ "FLY_IMAGE_REF" => ->(ref) { ref.split("@", 2).first.to_s[%r{:([^:/]+)\z}, 1] },
28
+ "GIT_SHA" => nil,
29
+ "SOURCE_VERSION" => nil
30
+ }.freeze
31
+
32
+ def self.resolve(configured, env: ENV, root: app_root)
33
+ revision = clean(configured) || platform_revision(env) ||
34
+ clean(revision_file(root)) || clean(git_head(root))
35
+ revision&.freeze
36
+ end
37
+
38
+ # The first platform variable that holds a revision. Stops there, so a
39
+ # later variable is never parsed.
40
+ def self.platform_revision(env)
41
+ PLATFORM_VARIABLES.each do |name, extract|
42
+ value = env[name]
43
+ value = clean(extract && value ? extract.call(value) : value)
44
+ return value if value
45
+ end
46
+ nil
47
+ end
48
+
49
+ # Up to the first line break (CR or LF), stripped and capped, since it
50
+ # goes in a header.
51
+ def self.clean(value)
52
+ value = value.to_s.strip.split(/[\r\n]/, 2).first.to_s.strip
53
+ return if value.empty?
54
+
55
+ value[0, MAX_LENGTH]
56
+ end
57
+
58
+ def self.app_root
59
+ if defined?(::Rails) && ::Rails.respond_to?(:root) && ::Rails.root
60
+ ::Rails.root.to_s
61
+ else
62
+ Dir.pwd
63
+ end
64
+ end
65
+
66
+ def self.revision_file(root)
67
+ path = File.join(root, "REVISION")
68
+ File.read(path, 256) if File.file?(path)
69
+ rescue StandardError
70
+ nil
71
+ end
72
+
73
+ def self.git_head(root)
74
+ return unless File.exist?(File.join(root, ".git"))
75
+
76
+ output = IO.popen(["git", "-C", root, "rev-parse", "HEAD"], err: File::NULL, &:read)
77
+ output if $?.success?
78
+ rescue StandardError
79
+ nil
80
+ end
81
+ end
82
+ end
@@ -16,11 +16,13 @@ module Flare
16
16
  /lib\/active_support/,
17
17
  /lib\/action_/,
18
18
  /opentelemetry/,
19
- /flare/,
20
19
  /<internal:/,
21
20
  /\/bin\//,
22
21
  ].freeze
23
22
 
23
+ # Frames from this gem itself (for path: and git: installs outside /gems/).
24
+ GEM_ROOT = "#{File.expand_path("../..", __dir__)}/"
25
+
24
26
  module_function
25
27
 
26
28
  # Find the first app source location from the current backtrace
@@ -39,36 +41,39 @@ module Flare
39
41
  # Find multiple app source locations from the current backtrace
40
42
  # Returns an array of cleaned backtrace lines (up to MAX_TRACE_LINES)
41
43
  def find_trace
42
- backtrace = caller(2, 100)
43
- return [] unless backtrace
44
-
45
- # Filter to only app code lines
46
- app_lines = backtrace.select { |line| app_code?(line) }
47
- return [] if app_lines.empty?
48
-
49
- # Clean and format each line, limit to MAX_TRACE_LINES
50
- app_lines.first(MAX_TRACE_LINES).map { |line| clean_backtrace_line(line) }
44
+ app_lines(caller(2, 100)).map { |line| clean_backtrace_line(line) }
51
45
  end
52
46
 
53
- # Add source location attributes to a hash (for span attributes)
47
+ # Add source location attributes to a hash (for span attributes).
48
+ # Captures the backtrace once for both the location and the trace.
54
49
  def add_to_attributes(attrs)
55
- location = find
50
+ lines = app_lines(caller(1, 100))
51
+ location = lines.first && parse_backtrace_line(lines.first)
56
52
  return attrs unless location
57
53
 
58
54
  attrs["code.filepath"] = location[:filepath]
59
55
  attrs["code.lineno"] = location[:lineno]
60
56
  attrs["code.function"] = location[:function] if location[:function]
61
-
62
- # Add full trace as a single string attribute
63
- trace = find_trace
64
- attrs["code.stacktrace"] = trace.join("\n") if trace.any?
57
+ attrs["code.stacktrace"] = lines.map { |line| clean_backtrace_line(line) }.join("\n")
65
58
 
66
59
  attrs
67
60
  end
68
61
 
62
+ # The first MAX_TRACE_LINES app code lines of a backtrace.
63
+ def app_lines(backtrace)
64
+ return [] unless backtrace
65
+
66
+ backtrace.select { |line| app_code?(line) }.first(MAX_TRACE_LINES)
67
+ end
68
+
69
69
  def app_code?(line)
70
70
  # Must contain /app/ (Rails convention) and not match ignore patterns
71
71
  return false unless line.include?("/app/")
72
+ return false if line.start_with?(GEM_ROOT)
73
+
74
+ if defined?(Rails) && Rails.respond_to?(:root) && Rails.root
75
+ return true if line.start_with?("#{Rails.root}/app/")
76
+ end
72
77
 
73
78
  IGNORE_PATTERNS.none? { |pattern| line.match?(pattern) }
74
79
  end
@@ -0,0 +1,235 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strscan"
4
+
5
+ module Flare
6
+ # Takes the values out of a SQL statement in one left-to-right pass, keeping
7
+ # keywords and names so the same query with different values reads the same.
8
+ #
9
+ # The first delimiter decides the token, so a quote inside a comment or a
10
+ # comment marker inside a string can't change how the rest is read. When the
11
+ # scan can't tell where a value ends (an unterminated literal or comment, or a
12
+ # backslash before a quote, which means different things across databases and
13
+ # server settings), everything after that point is masked.
14
+ module SqlMask
15
+ PLACEHOLDER = "?"
16
+
17
+ # Longer statements are masked up to here and cut, which bounds the work.
18
+ MAX_BYTES = 16_384
19
+ TRUNCATED = " ..."
20
+
21
+ # Systems known to speak SQL. Anything else may not follow its quoting rules,
22
+ # so callers keep only a command word. No system at all is read as SQL, with
23
+ # every quote treated as a value.
24
+ SQL_SYSTEMS = /postgres|postgis|mysql|trilogy|maria|sqlite|cockroach|sqlserver|mssql|oracle|db2/i
25
+
26
+ # Close enough to SQL to mask, with rules that vary: every quoted string counts
27
+ # as a value, and # and // start comments that run to the end of the line.
28
+ # Backticks hold names only where that's known.
29
+ SQL_LIKE_SYSTEMS = /cassandra|clickhouse|bigquery|snowflake/i
30
+ BACKTICK_NAMES = /clickhouse|bigquery/i
31
+
32
+ # Double quotes hold names on these. On MySQL they hold values, and elsewhere
33
+ # they're treated as values too. SQLite reads them as values when no such
34
+ # column exists, so it keeps them only in places that can't hold a value.
35
+ # MySQL also starts comments with #, which is an operator on Postgres.
36
+ DOUBLE_QUOTED_NAMES = /postgres|postgis|cockroach|oracle|db2/i
37
+ SQLITE = /sqlite/i
38
+ HASH_COMMENTS = /mysql|trilogy|maria/i
39
+
40
+ COMMAND_WORD = /\A\s*([A-Z][A-Z_.]{0,31}|[a-z][a-z_.]{0,31})(?=\s|\z)/
41
+ OPERATION_WORD = /\A[A-Za-z][A-Za-z_.]{0,31}\z/
42
+ # Decided from a short tail of the output, so anything spaced too widely to see
43
+ # in it isn't a name. FROM counts only with the word before it in view, because
44
+ # IS DISTINCT FROM takes a value.
45
+ NAME_POSITION = /(?:\b(?:JOIN|INTO|UPDATE|TABLE)\s{1,8}|\.)\z/ni
46
+ FROM_POSITION = /(\S+)\s{1,8}FROM\s{1,8}\z/ni
47
+ DISTINCT_WORD = /DISTINCT\z/ni
48
+ DOUBLE_QUOTED = /"[^"]*+(?:""[^"]*+)*+"/n
49
+ QUALIFIER = /#{DOUBLE_QUOTED.source}(?=\.(?:\*|\w|#{DOUBLE_QUOTED.source}))/n
50
+
51
+ WORD = /[A-Za-z_\x80-\xff][\w$\x80-\xff]*+/n
52
+ UUID = /\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\b/n
53
+ NUMBER = /\.?\d[\w.\x80-\xff]*+(?:(?<=[eE])[+-]\d++)?/n
54
+ DOLLAR_OTHER = /\$\d*+/n
55
+ DOLLAR_TAG = /\$(?:[A-Za-z_\x80-\xff][\w\x80-\xff]*+)?\$/n
56
+ LINE_COMMENT = /(?:--|#|\/\/)[^\n]*+/n
57
+ COMMENT_START = %r{/\*}n
58
+ COMMENT_EDGE = %r{/\*|\*/}n
59
+ LITERAL_PREFIX = /\A(?:[xXbBnNeE]|_\w+)\z/n
60
+ LITERAL_RUNS = { "'" => /[^'\\]*+/n, '"' => /[^"\\]*+/n, "`" => /[^`\\]*+/n }.freeze
61
+ IN_LIST = /\bIN ?\( ?\?(?: ?, ?\?)* ?\)/ni
62
+ OTHER_WHITESPACE = "\t\n\r\f\v"
63
+
64
+ # A run of tokens that are copied as they are, matched in one go because most
65
+ # of a statement is this. It stops at anything that needs a decision: a quote,
66
+ # a number, a $, a comment, or a word that may be a literal's prefix.
67
+ # A word that starts a UUID stops the run, so the whole UUID can be masked.
68
+ word = %q{(?!\h{8}-\h{4}-)[A-Za-z_\x80-\xff][\w$\x80-\xff]*+(?!')}
69
+ other = %q{[^\w\x80-\xff'"`$#./-]++|\.(?!\d)|-(?!-)}
70
+ backtick = "`[^`]*+(?:``[^`]*+)*+`"
71
+ plain = "#{word}|#{other}|#{backtick}|/(?!\\*)"
72
+ PLAIN = Regexp.new("(?:#{plain})++", Regexp::NOENCODING)
73
+ PLAIN_NAMES = Regexp.new(%((?:#{plain}|#{DOUBLE_QUOTED.source}|#)++), Regexp::NOENCODING)
74
+ PLAIN_HASH = Regexp.new("(?:#{plain}|#)++", Regexp::NOENCODING)
75
+ PLAIN_LIKE = Regexp.new("(?:#{word}|#{other}|/(?![*/]))++", Regexp::NOENCODING)
76
+ PLAIN_LIKE_BACKTICKS = Regexp.new("(?:#{word}|#{other}|#{backtick}|/(?![*/]))++", Regexp::NOENCODING)
77
+
78
+ module_function
79
+
80
+ def sql_system?(system)
81
+ system.to_s.empty? || SQL_SYSTEMS.match?(system.to_s) || SQL_LIKE_SYSTEMS.match?(system.to_s)
82
+ end
83
+
84
+ # The first word of a statement, if it could be a command name. Nil otherwise.
85
+ def command_word(statement)
86
+ statement.to_s[COMMAND_WORD, 1]
87
+ end
88
+
89
+ # The value if all of it could be an operation name. Nil otherwise.
90
+ def operation_word(value)
91
+ value.to_s[OPERATION_WORD]
92
+ end
93
+
94
+ def mask(statement, system = nil)
95
+ sql = statement.to_s.b
96
+ truncated = sql.bytesize > MAX_BYTES
97
+ sql = sql.byteslice(0, MAX_BYTES) if truncated
98
+ out = scan(StringScanner.new(sql), system.to_s)
99
+ out.tr!(OTHER_WHITESPACE, " ")
100
+ out.squeeze!(" ")
101
+ out.gsub!(IN_LIST, "IN (?)")
102
+ out.strip!
103
+ out << TRUNCATED if truncated
104
+ out.force_encoding(Encoding::UTF_8).scrub!
105
+ end
106
+
107
+ def scan(scanner, system)
108
+ sqlite = SQLITE.match?(system)
109
+ plain = if SQL_LIKE_SYSTEMS.match?(system) then BACKTICK_NAMES.match?(system) ? PLAIN_LIKE_BACKTICKS : PLAIN_LIKE
110
+ elsif DOUBLE_QUOTED_NAMES.match?(system) then PLAIN_NAMES
111
+ elsif system.empty? || HASH_COMMENTS.match?(system) then PLAIN
112
+ else PLAIN_HASH
113
+ end
114
+ out = String.new(capacity: scanner.string.bytesize, encoding: Encoding::BINARY)
115
+
116
+ until scanner.eos?
117
+ if (run = scanner.scan(plain))
118
+ out << run
119
+ elsif scanner.skip(UUID) || scanner.skip(NUMBER)
120
+ out << PLACEHOLDER
121
+ elsif (word = scanner.scan(WORD))
122
+ if LITERAL_PREFIX.match?(word)
123
+ mask_literal(scanner, out, backslash_escapes: word.casecmp?("e"))
124
+ else
125
+ out << word
126
+ end
127
+ else
128
+ scan_delimiter(scanner, out, plain, sqlite)
129
+ end
130
+ end
131
+
132
+ out
133
+ end
134
+
135
+ # Handles the delimiter the plain run stopped on. Giving up on the rest of the
136
+ # statement means terminating the scanner, which ends the loop above.
137
+ def scan_delimiter(scanner, out, plain, sqlite)
138
+ case scanner.peek(1)
139
+ when "'"
140
+ mask_literal(scanner, out)
141
+ when '"'
142
+ # A closed name would already be part of the plain run where quotes are names.
143
+ if plain == PLAIN_NAMES then mask_rest(scanner, out)
144
+ elsif sqlite && (name = sqlite_name(scanner, out)) then out << name
145
+ else mask_literal(scanner, out)
146
+ end
147
+ when "`"
148
+ # Likewise, where backticks are names.
149
+ plain == PLAIN_LIKE ? mask_literal(scanner, out) : mask_rest(scanner, out)
150
+ when "$"
151
+ mask_dollar(scanner, out)
152
+ else # /* or, where they start a comment, //, -- and #
153
+ if scanner.check(COMMENT_START)
154
+ skip_comment(scanner, out)
155
+ else
156
+ scanner.skip(LINE_COMMENT)
157
+ out << " "
158
+ end
159
+ end
160
+ end
161
+
162
+ # A quoted word right after FROM and the like, or either side of a dot, can
163
+ # only be a name.
164
+ def sqlite_name(scanner, out)
165
+ tail = out.byteslice(-32, 32) || out
166
+ from = FROM_POSITION.match(tail)
167
+ if NAME_POSITION.match?(tail) || (from && !DISTINCT_WORD.match?(from[1]))
168
+ scanner.scan(DOUBLE_QUOTED)
169
+ else
170
+ scanner.scan(QUALIFIER)
171
+ end
172
+ end
173
+
174
+ def mask_rest(scanner, out)
175
+ out << PLACEHOLDER
176
+ scanner.terminate
177
+ end
178
+
179
+ # The scanner is on the opening quote. Reads to the closing one, or masks the
180
+ # rest if there isn't one.
181
+ #
182
+ # An even run of backslashes before a quote closes the literal whether or not
183
+ # the server treats backslash as an escape. An odd run only closes it if the
184
+ # server doesn't, and that depends on the database and its settings, so the
185
+ # literal counts as unterminated. Only E'' strings say for themselves.
186
+ def mask_literal(scanner, out, backslash_escapes: false)
187
+ quote = scanner.getch
188
+ plain = LITERAL_RUNS.fetch(quote)
189
+ out << PLACEHOLDER
190
+
191
+ loop do
192
+ scanner.skip(plain)
193
+ return scanner.terminate if scanner.eos?
194
+
195
+ if scanner.peek(1) == "\\"
196
+ if backslash_escapes
197
+ scanner.skip(/\\.?/mn)
198
+ else
199
+ run = scanner.skip(/\\+/n)
200
+ return scanner.terminate if run.odd? && scanner.peek(1) == quote
201
+ end
202
+ else
203
+ scanner.getch
204
+ return unless scanner.peek(1) == quote
205
+
206
+ scanner.getch
207
+ end
208
+ end
209
+ end
210
+
211
+ def mask_dollar(scanner, out)
212
+ out << PLACEHOLDER
213
+ if (tag = scanner.scan(DOLLAR_TAG))
214
+ scanner.terminate unless scanner.skip_until(Regexp.new(Regexp.escape(tag), Regexp::NOENCODING))
215
+ else
216
+ scanner.skip(DOLLAR_OTHER)
217
+ end
218
+ end
219
+
220
+ # Comments nest on Postgres. Reading them that way elsewhere can only mask
221
+ # more, never less.
222
+ def skip_comment(scanner, out)
223
+ scanner.skip(COMMENT_START)
224
+ depth = 1
225
+ while depth.positive?
226
+ return scanner.terminate unless scanner.skip_until(COMMENT_EDGE)
227
+
228
+ depth += scanner.matched == "/*" ? 1 : -1
229
+ end
230
+ out << " "
231
+ end
232
+
233
+ private_class_method :scan, :scan_delimiter, :sqlite_name, :mask_rest, :mask_literal, :mask_dollar, :skip_comment
234
+ end
235
+ end
@@ -4,6 +4,7 @@ require "sqlite3"
4
4
  require "json"
5
5
 
6
6
  require_relative "deadline"
7
+ require_relative "utf8"
7
8
 
8
9
  module Flare
9
10
  class SQLiteExporter
@@ -128,8 +129,11 @@ module Flare
128
129
  span_data.name&.start_with?("Flare::")
129
130
  end
130
131
 
132
+ # Stored in UTC because readers compare and sort these as strings, which only
133
+ # works when every row has the same offset. Local time breaks that at a clock
134
+ # change: 1:05 after falling back sorts before the 1:50 that came earlier.
131
135
  def create_span(span_data)
132
- now = Time.now.iso8601(6)
136
+ now = Time.now.utc.iso8601(6)
133
137
 
134
138
  sql = <<~SQL
135
139
  INSERT INTO flare_spans (name, kind, span_id, trace_id, parent_span_id, start_timestamp, end_timestamp, total_recorded_links, total_recorded_events, total_recorded_properties, created_at, updated_at)
@@ -137,7 +141,7 @@ module Flare
137
141
  SQL
138
142
 
139
143
  values = [
140
- span_data.name,
144
+ UTF8.scrub(span_data.name),
141
145
  span_data.kind.to_s,
142
146
  span_data.hex_span_id,
143
147
  span_data.hex_trace_id,
@@ -162,15 +166,15 @@ module Flare
162
166
  end
163
167
 
164
168
  def create_event(span_record_id, span_event)
165
- now = Time.now.iso8601(6)
166
- timestamp = span_event.timestamp ? Time.at(span_event.timestamp / 1_000_000_000.0).iso8601(6) : now
169
+ now = Time.now.utc.iso8601(6)
170
+ timestamp = span_event.timestamp ? Time.at(span_event.timestamp / 1_000_000_000.0).utc.iso8601(6) : now
167
171
 
168
172
  sql = <<~SQL
169
173
  INSERT INTO flare_events (span_id, name, created_at, updated_at)
170
174
  VALUES (?, ?, ?, ?)
171
175
  SQL
172
176
 
173
- connection.execute(sql, [span_record_id, span_event.name, timestamp, now])
177
+ connection.execute(sql, [span_record_id, UTF8.scrub(span_event.name), timestamp, now])
174
178
  event_record_id = connection.last_insert_row_id
175
179
  create_properties("Flare::Event", event_record_id, span_event.attributes)
176
180
  end
@@ -178,7 +182,7 @@ module Flare
178
182
  def create_properties(owner_type, owner_id, attributes)
179
183
  return unless attributes
180
184
 
181
- now = Time.now.iso8601(6)
185
+ now = Time.now.utc.iso8601(6)
182
186
 
183
187
  sql = <<~SQL
184
188
  INSERT INTO flare_properties (key, value, value_type, owner_type, owner_id, created_at, updated_at)
@@ -189,8 +193,8 @@ module Flare
189
193
  next if value.nil?
190
194
 
191
195
  value_type = determine_value_type(value)
192
- serialized_value = JSON.generate(value)
193
- connection.execute(sql, [key, serialized_value, value_type, owner_type, owner_id, now, now])
196
+ serialized_value = JSON.generate(UTF8.scrub(value))
197
+ connection.execute(sql, [UTF8.scrub(key), serialized_value, value_type, owner_type, owner_id, now, now])
194
198
  end
195
199
  end
196
200