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,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "local_spans"
5
+ require_relative "output"
6
+
7
+ module Flare
8
+ # Shows what one request did, from the local development spans database, so
9
+ # you (or a coding agent) can read its timeline without opening /flare. Trace
10
+ # ids come from `flare requests`.
11
+ class RequestCommand
12
+ include CLI::LocalSpans
13
+ include CLI::Output
14
+
15
+ USAGE = "Usage: flare request <trace_id> [options]"
16
+
17
+ def initialize(argv)
18
+ arguments = parse_options(argv, banner: USAGE)
19
+
20
+ unless arguments.size == 1
21
+ $stderr.puts USAGE
22
+ exit 1
23
+ end
24
+ @trace_id = arguments.first
25
+ end
26
+
27
+ def run
28
+ request = read_local_spans(@database_path) { |storage| load_request(storage) }
29
+
30
+ unless request
31
+ $stderr.puts "No request with trace id #{@trace_id}. Run `flare requests` to list recent ones."
32
+ exit 1
33
+ end
34
+
35
+ if @json
36
+ puts JSON.pretty_generate(request)
37
+ else
38
+ print_request(request)
39
+ end
40
+ end
41
+
42
+ private
43
+
44
+ def load_request(storage)
45
+ root = storage.find_request(@trace_id)
46
+ return unless root
47
+
48
+ spans = storage.spans_for_trace(@trace_id)
49
+ props = root[:properties]
50
+
51
+ request_summary(root,
52
+ method: props["http.request.method"] || props["http.method"],
53
+ path: props["url.path"] || props["http.target"],
54
+ status: props["http.response.status_code"] || props["http.status_code"],
55
+ controller: props["code.namespace"],
56
+ action: props["code.function"],
57
+ queries: storage.count_queries_by_trace([@trace_id]).fetch(@trace_id, 0)).merge(
58
+ name: root[:name],
59
+ exceptions: spans.flat_map { |span| exceptions(span) },
60
+ spans: spans.reject { |span| span[:id] == root[:id] }.map { |span| timeline_entry(span, root) },
61
+ )
62
+ end
63
+
64
+ def exceptions(span)
65
+ span[:events].select { |event| event[:name] == "exception" }.map do |event|
66
+ {
67
+ type: event[:properties]["exception.type"],
68
+ message: event[:properties]["exception.message"],
69
+ stacktrace: event[:properties]["exception.stacktrace"],
70
+ }
71
+ end
72
+ end
73
+
74
+ def timeline_entry(span, root)
75
+ props = span[:properties]
76
+ {
77
+ name: span[:name],
78
+ offset_ms: ((span[:start_timestamp] - root[:start_timestamp]) / 1_000_000.0).round(1),
79
+ duration_ms: span[:duration_ms].round(1),
80
+ detail: detail(props),
81
+ source: source_location(props),
82
+ }
83
+ end
84
+
85
+ def detail(props)
86
+ statement = props["db.statement"]
87
+ return statement.to_s.gsub(/\s+/, " ").strip if statement
88
+
89
+ identifier = props["identifier"]
90
+ return identifier.to_s.sub(%r{\A.*/app/views/}, "") if identifier
91
+
92
+ props["http.url"] || props["url.full"]
93
+ end
94
+
95
+ def print_request(request)
96
+ title = request[:method] ? "#{request[:method]} #{request[:path]}" : request[:name]
97
+ puts request_heading(request, title)
98
+ puts "Started #{request[:started_at]} #{request[:queries]} queries"
99
+
100
+ request[:exceptions].each do |exception|
101
+ puts red("Exception: #{[exception[:type], exception[:message]].compact.join(": ")}")
102
+ end
103
+
104
+ return if request[:spans].empty?
105
+
106
+ puts
107
+ puts dim(format("%9s %9s", "offset", "duration"))
108
+ request[:spans].each { |span| puts format_span(span) }
109
+ end
110
+
111
+ def format_span(span)
112
+ label = span[:detail] ? "#{span[:name]}: #{span[:detail]}" : span[:name]
113
+ [
114
+ format("%7.1fms %7.1fms", span[:offset_ms], span[:duration_ms]),
115
+ label,
116
+ span[:source] && dim(span[:source]),
117
+ ].compact.join(" ")
118
+ end
119
+ end
120
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "local_spans"
5
+ require_relative "output"
6
+
7
+ module Flare
8
+ # Lists the most recent requests from the local development spans database,
9
+ # so you (or a coding agent) can check a change without opening /flare.
10
+ class RequestsCommand
11
+ include CLI::LocalSpans
12
+ include CLI::Output
13
+
14
+ def initialize(argv)
15
+ parse_options(argv, banner: "Usage: flare requests [options]", last_help: "Number of requests to show")
16
+ end
17
+
18
+ def run
19
+ requests = read_local_spans(@database_path) { |storage| recent_requests(storage, @limit) }
20
+
21
+ if @json
22
+ puts JSON.pretty_generate(requests)
23
+ elsif requests.empty?
24
+ puts "No requests recorded yet."
25
+ else
26
+ requests.each { |request| puts format_row(request) }
27
+ end
28
+ end
29
+
30
+ private
31
+
32
+ def format_row(request)
33
+ [
34
+ dim(request[:started_at]),
35
+ request[:method].to_s.ljust(6),
36
+ request[:status].to_s.ljust(3),
37
+ format("%8.1fms", request[:duration_ms]),
38
+ format("%4d queries", request[:queries]),
39
+ request[:path],
40
+ endpoint(request)&.then { |name| dim(name) },
41
+ dim(request[:trace_id]),
42
+ ].compact.join(" ")
43
+ end
44
+ end
45
+ end
@@ -8,14 +8,20 @@ require "net/http"
8
8
  require "uri"
9
9
  require "json"
10
10
  require "fileutils"
11
+ require "timeout"
11
12
  require_relative "output"
13
+ require_relative "project"
12
14
 
13
15
  module Flare
14
16
  class SetupCommand
15
17
  include CLI::Output
18
+ include CLI::Project
16
19
 
17
20
  DEFAULT_HOST = "https://flare.am"
18
21
  TIMEOUT_SECONDS = 300 # 5 minutes
22
+ CLIENT_READ_TIMEOUT = 1
23
+
24
+ class AuthorizationDenied < StandardError; end
19
25
 
20
26
  INITIALIZER_CONTENT = <<~RUBY
21
27
  # frozen_string_literal: true
@@ -43,6 +49,9 @@ module Flare
43
49
  # request.path.start_with?("/health")
44
50
  # }
45
51
 
52
+ # Exceptions (and subclasses) that don't count as errors in metrics.
53
+ # config.ignore_errors << "MyApp::RetryLaterError"
54
+
46
55
  # ── Metrics (remote monitoring) ────────────────────────────────────
47
56
  # Metrics aggregate span data into counts, durations, and error rates.
48
57
  # Enabled by default in development and production (disabled in test).
@@ -109,9 +118,7 @@ module Flare
109
118
  # --- Auth ---
110
119
 
111
120
  def authenticate
112
- env_path = File.join(Dir.pwd, ".env")
113
-
114
- if !@force && File.exist?(env_path) && File.read(env_path).match?(/^FLARE_KEY=.+/)
121
+ if !@force && key_in_dotenv?
115
122
  puts "#{checkmark} FLARE_KEY already set in .env, skipping auth."
116
123
  puts " Run with --force to re-authenticate."
117
124
  return
@@ -139,7 +146,12 @@ module Flare
139
146
  puts
140
147
  puts "Waiting for authorization (up to 5 minutes)..."
141
148
 
142
- auth_code = wait_for_callback(server, state, TIMEOUT_SECONDS)
149
+ begin
150
+ auth_code = wait_for_callback(server, state, TIMEOUT_SECONDS)
151
+ rescue AuthorizationDenied => e
152
+ puts "Authorization failed: #{e.message}"
153
+ exit 1
154
+ end
143
155
 
144
156
  unless auth_code
145
157
  puts "Timed out waiting for authorization."
@@ -152,50 +164,59 @@ module Flare
152
164
  server&.close
153
165
  end
154
166
 
167
+ # Waits for flare-web to redirect the browser back with a code. Anything
168
+ # else that reaches the port (a stray request, a wrong or missing state,
169
+ # a connection that never sends a request) gets a response and is
170
+ # skipped, so only a matching callback ends the wait.
155
171
  def wait_for_callback(server, expected_state, timeout)
156
172
  deadline = Time.now + timeout
157
173
 
158
174
  while Time.now < deadline
159
- readable = IO.select([server], nil, nil, 1)
160
- next unless readable
175
+ next unless IO.select([server], nil, nil, 1)
161
176
 
162
- client = server.accept
163
- request_line = client.gets
177
+ code = handle_callback(server.accept, expected_state)
178
+ return code if code
179
+ end
164
180
 
165
- unless request_line&.start_with?("GET /callback")
166
- client.print "HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n"
167
- client.close
168
- next
169
- end
181
+ nil
182
+ end
170
183
 
171
- # Read remaining headers (required by HTTP spec)
172
- while (line = client.gets) && line != "\r\n"; end
173
-
174
- params = parse_query_string(request_line)
175
- returned_state = params["state"]
176
- code = params["code"]
177
- error = params["error"]
178
-
179
- if error
180
- client.print http_response(error_page(error))
181
- client.close
182
- return nil
183
- elsif returned_state != expected_state
184
- client.print http_response(error_page("State mismatch. Please try again."))
185
- client.close
186
- return nil
187
- elsif code.nil? || code.empty?
188
- client.print http_response(error_page("No authorization code received."))
189
- client.close
190
- return nil
191
- else
192
- client.print http_response(success_page)
193
- client.close
194
- return code
184
+ # Returns the code, nil to keep waiting, or raises AuthorizationDenied
185
+ # when flare-web reports an error for this state.
186
+ def handle_callback(client, expected_state)
187
+ request_line = Timeout.timeout(CLIENT_READ_TIMEOUT) do
188
+ client.gets.tap do
189
+ # Read remaining headers (required by HTTP spec)
190
+ while (header = client.gets) && header != "\r\n"; end
195
191
  end
196
192
  end
197
193
 
194
+ unless request_line&.start_with?("GET /callback")
195
+ client.print "HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n"
196
+ return nil
197
+ end
198
+
199
+ params = parse_query_string(request_line)
200
+ code = params["code"]
201
+ error = params["error"]
202
+
203
+ if params["state"] != expected_state
204
+ client.print http_response(error_page("State mismatch. Please try again."))
205
+ nil
206
+ elsif error
207
+ client.print http_response(error_page(error))
208
+ raise AuthorizationDenied, error
209
+ elsif code.nil? || code.empty?
210
+ client.print http_response(error_page("No authorization code received."))
211
+ nil
212
+ else
213
+ client.print http_response(success_page)
214
+ code
215
+ end
216
+ rescue Timeout::Error, IOError, SystemCallError
198
217
  nil
218
+ ensure
219
+ client.close
199
220
  end
200
221
 
201
222
  def parse_query_string(request_line)
@@ -205,6 +226,8 @@ module Flare
205
226
  query = URI(path).query
206
227
  return {} unless query
207
228
  URI.decode_www_form(query).to_h
229
+ rescue URI::InvalidURIError, ArgumentError
230
+ {}
208
231
  end
209
232
 
210
233
  def http_response(body)
@@ -250,9 +273,12 @@ module Flare
250
273
  puts " 3. Print token"
251
274
  print "Choose (1/2/3): "
252
275
 
253
- choice = $stdin.gets&.strip
254
-
255
- case choice
276
+ case $stdin.gets&.strip
277
+ when nil
278
+ # Closed stdin (a script, CI, a coding agent) can't answer. Asking again
279
+ # would never end and lose the token we just got, so show it.
280
+ puts
281
+ print_token(token)
256
282
  when "1"
257
283
  @saved_to_dotenv = true
258
284
  save_to_dotenv(token)
@@ -354,7 +380,7 @@ module Flare
354
380
  contents = File.read(gitignore_path)
355
381
  entries_to_add = []
356
382
 
357
- entries_to_add << ".env" if @saved_to_dotenv && !contents.match?(/^\.env$/)
383
+ entries_to_add << ".env" if (@saved_to_dotenv || key_in_dotenv?) && !env_ignored?(contents)
358
384
  entries_to_add << "flare.sqlite3*" unless contents.include?("flare.sqlite3*")
359
385
 
360
386
  return if entries_to_add.empty?
@@ -1,11 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "output"
4
+ require_relative "project"
4
5
  require_relative "../version"
5
6
 
6
7
  module Flare
7
8
  class StatusCommand
8
9
  include CLI::Output
10
+ include CLI::Project
9
11
 
10
12
  def run
11
13
  puts bold("Flare v#{VERSION}")
@@ -30,9 +32,10 @@ module Flare
30
32
  if ENV["FLARE_KEY"] && !ENV["FLARE_KEY"].empty?
31
33
  green("set via ENV")
32
34
  else
33
- env_path = File.join(Dir.pwd, ".env")
34
- if File.exist?(env_path) && File.read(env_path).match?(/^FLARE_KEY=.+/)
35
+ if key_in_dotenv?
35
36
  green("set in .env")
37
+ elsif credentials_exist?
38
+ dim("not in ENV or .env (may be in Rails credentials)")
36
39
  else
37
40
  red("not configured")
38
41
  end
data/lib/flare/cli.rb CHANGED
@@ -8,6 +8,9 @@ module Flare
8
8
  "setup" => "Authenticate and configure Flare for this project",
9
9
  "doctor" => "Check your Flare setup for issues",
10
10
  "status" => "Show current Flare configuration",
11
+ "requests" => "List recent requests from local development spans",
12
+ "request" => "Show one request's timeline from local development spans",
13
+ "nplus1" => "Find queries repeated within recent requests from local development spans",
11
14
  "version" => "Print the Flare version",
12
15
  "help" => "Show this help message",
13
16
  }.freeze
@@ -26,6 +29,15 @@ module Flare
26
29
  when "status"
27
30
  require_relative "cli/status_command"
28
31
  StatusCommand.new.run
32
+ when "requests"
33
+ require_relative "cli/requests_command"
34
+ RequestsCommand.new(argv.drop(1)).run
35
+ when "request"
36
+ require_relative "cli/request_command"
37
+ RequestCommand.new(argv.drop(1)).run
38
+ when "nplus1"
39
+ require_relative "cli/nplus1_command"
40
+ Nplus1Command.new(argv.drop(1)).run
29
41
  when "version", "-v", "--version"
30
42
  puts "flare #{Flare::VERSION}"
31
43
  when "help", nil, "-h", "--help"
@@ -8,7 +8,8 @@ module Flare
8
8
  # Single source of truth for the headers that identify this client and its
9
9
  # version to the Flare API. The server parses the gem version out of the
10
10
  # User-Agent ("Flare Ruby/X.Y.Z") to gate version-dependent features, and
11
- # uses the X-Client-* headers to build a per-client picture.
11
+ # uses the X-Client-* headers to build a per-client picture. X-Client-Revision
12
+ # (when one resolves, see Configuration#revision) marks deploys on the charts.
12
13
  #
13
14
  # Safe to send on any request that targets the Flare API (metrics POST,
14
15
  # rules GET, trace-notify POST). Do NOT send these on the presigned R2 blob
@@ -19,8 +20,8 @@ module Flare
19
20
  module ClientHeaders
20
21
  USER_AGENT = "Flare Ruby/#{Flare::VERSION}"
21
22
 
22
- def self.to_h
23
- {
23
+ def self.to_h(configuration = Flare.configuration)
24
+ headers = {
24
25
  "User-Agent" => USER_AGENT,
25
26
  "X-Client-Language" => "ruby",
26
27
  "X-Client-Language-Version" => RUBY_VERSION,
@@ -28,6 +29,9 @@ module Flare
28
29
  "X-Client-Pid" => Process.pid.to_s,
29
30
  "X-Client-Hostname" => hostname
30
31
  }
32
+ revision = configuration.revision
33
+ headers["X-Client-Revision"] = revision if revision
34
+ headers
31
35
  end
32
36
 
33
37
  def self.hostname
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "http_metrics_config"
4
+ require_relative "revision"
4
5
 
5
6
  module Flare
6
7
  class Configuration
@@ -8,6 +9,7 @@ module Flare
8
9
  attr_accessor :retention_hours
9
10
  attr_accessor :max_spans
10
11
  attr_accessor :ignore_request
12
+ attr_accessor :ignore_errors
11
13
  attr_writer :database_path
12
14
 
13
15
  # Spans: detailed trace data stored in SQLite (default: development only)
@@ -34,6 +36,12 @@ module Flare
34
36
 
35
37
  attr_accessor :subscribe_patterns
36
38
 
39
+ # Exceptions that jobs raise to wait or retry rather than to fail. A span
40
+ # that ends with one of these (or a subclass) counts as a success.
41
+ DEFAULT_IGNORE_ERRORS = %w[
42
+ GoodJob::ActiveJobExtensions::Concurrency::ConcurrencyExceededError
43
+ ].freeze
44
+
37
45
  # HTTP metrics path tracking configuration.
38
46
  # Controls which outgoing HTTP paths are tracked with detail vs collapsed to "*".
39
47
  attr_reader :http_metrics_config
@@ -48,8 +56,10 @@ module Flare
48
56
  @max_spans = 10_000
49
57
  @database_path = nil
50
58
  @ignore_request = ->(request) { false }
59
+ @ignore_errors = DEFAULT_IGNORE_ERRORS.dup
51
60
  @subscribe_patterns = DEFAULT_SUBSCRIBE_PATTERNS.dup
52
61
  @debug = ENV["FLARE_DEBUG"] == "1"
62
+ @revision = ENV["FLARE_REVISION"]
53
63
  @http_metrics_config = HttpMetricsConfig::DEFAULT
54
64
 
55
65
  # Environment-based defaults:
@@ -103,6 +113,24 @@ module Flare
103
113
  yield @http_metrics_config
104
114
  end
105
115
 
116
+ # The deployed revision, usually a git SHA, sent so Flare can mark deploys.
117
+ # Defaults to FLARE_REVISION; when neither is set, the first read asks
118
+ # Flare::Revision (platform variables, a REVISION file, then git).
119
+ def revision
120
+ return @revision if @revision_resolved
121
+
122
+ # Flag after the value, so a racing reader never sees the unresolved one.
123
+ # Two first readers may both resolve; they get the same answer.
124
+ @revision = Revision.resolve(@revision)
125
+ @revision_resolved = true
126
+ @revision
127
+ end
128
+
129
+ def revision=(value)
130
+ @revision_resolved = false
131
+ @revision = value
132
+ end
133
+
106
134
  private
107
135
 
108
136
  def rails_development?