flare 0.5.1 → 0.6.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d9a717e37a1b09780b8430531cb36d7ed8881562522e69e9f7a770710f41ada6
4
- data.tar.gz: a5becacc7ae0e85bd7b29e50f650ffc0c2105c425a190befad58098b85b83bc4
3
+ metadata.gz: 6363c80609634d48a528d6f21284a6829b27f75b1a805ddf622ce376a9949aff
4
+ data.tar.gz: 5710935c06157a298b353f0bad9d37ffb6fca9196f304d08585eb913ab13d82a
5
5
  SHA512:
6
- metadata.gz: 02c2ffb1e25b8b447173ed8e1eba61c80051e91420ffccfa0f002f45e62cf8af832bb35b1776ff9026da6e665eca27992e13f418936d57faa02b36edc85b4292
7
- data.tar.gz: 5579cf57806f815da0c5dd97a45a3397aaa7bd603a695353cd89772704767fea34bbcab4c21a3db75eb292797df56e8bc0272e8fba6aef84c9945f75ba37e383
6
+ metadata.gz: 940242884d417ec1712c3e67fa17141a13dbbe598d12b6f9cf3a916f2e864eaf6dc55aa6fce4e6c245e87f5bf58551b767419af56ed1743a025e893b64841790
7
+ data.tar.gz: 7d1feed86100e2f375df453c45e3cfda7dfa9cadaf9fbfe2233785885994320394450775578143ab9e4fd3e0edfaeb92c2156d32bbc2d7c18486eb41134a6dc4
data/README.md CHANGED
@@ -45,6 +45,7 @@ The setup command will:
45
45
  1. Authenticate with flare.am to configure metrics
46
46
  2. Create a config initializer with sensible defaults
47
47
  3. Update .gitignore
48
+ 4. Offer to connect Claude Code, Codex and Cursor to Flare's MCP server, so you can ask your AI assistant about your app's performance. Each one signs in to Flare the first time it connects.
48
49
 
49
50
  Start your Rails server and visit `/flare` to see the dashboard.
50
51
 
@@ -58,6 +59,7 @@ To enable metrics, set `FLARE_KEY` in your environment (get one at [flare.am](ht
58
59
 
59
60
  ```bash
60
61
  flare setup # Authenticate and configure Flare
62
+ flare connect # Connect your AI assistants to Flare
61
63
  flare doctor # Check your setup for issues
62
64
  flare status # Show current configuration
63
65
  flare requests # List recent requests from local development spans
data/exe/flare CHANGED
@@ -4,6 +4,10 @@
4
4
  $stdout.sync = true
5
5
  $stderr.sync = true
6
6
 
7
+ # Read the app's files as UTF-8, as Rails does, even in a shell without a
8
+ # UTF-8 locale (LANG unset or LC_ALL=C), where Ruby would read them as ASCII.
9
+ Encoding.default_external = Encoding::UTF_8
10
+
7
11
  require_relative "../lib/flare/cli"
8
12
 
9
13
  Flare::CLI.start(ARGV)
@@ -0,0 +1,249 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "open3"
5
+ require "fileutils"
6
+ require "securerandom"
7
+ require_relative "output"
8
+
9
+ module Flare
10
+ # Points the AI clients on this machine at Flare's hosted MCP server, as
11
+ # `flare-cli setup` does. Each client signs in to Flare itself the first
12
+ # time it connects, so no token is written anywhere. A client that already
13
+ # has a different `flare` server is left alone.
14
+ class AIClientsSetup
15
+ include CLI::Output
16
+
17
+ DEFAULT_HOST = "https://flare.am"
18
+ SERVER_NAME = "flare"
19
+ FIRST_PROMPT = "Using Flare, what's slowest in production over the last 24 hours?"
20
+ CLIENTS = {
21
+ claude: "Claude Code",
22
+ codex: "Codex",
23
+ cursor: "Cursor",
24
+ claude_desktop: "Claude Desktop",
25
+ }.freeze
26
+
27
+ # Runs the clients' own CLIs. `capture` returns [output, success];
28
+ # `attached` shares the terminal, because Codex may start its sign-in
29
+ # right away and print a URL to open.
30
+ class Runner
31
+ def capture(*command)
32
+ output, status = Open3.capture2e(*command)
33
+ [output, status.success?]
34
+ rescue SystemCallError => e
35
+ [e.message, false]
36
+ end
37
+
38
+ def attached(*command)
39
+ system(*command) == true
40
+ end
41
+ end
42
+
43
+ def initialize(host: ENV.fetch("FLARE_HOST", DEFAULT_HOST), input: $stdin, env: ENV, home: Dir.home, platform: RUBY_PLATFORM, runner: Runner.new)
44
+ @host = host.chomp("/")
45
+ @url = "#{@host}/mcp"
46
+ @input = input
47
+ @env = env
48
+ @home = home
49
+ @platform = platform
50
+ @runner = runner
51
+ end
52
+
53
+ # `flare setup` asks first, since this changes other apps' settings.
54
+ # `flare connect` is the asking. Returns false if any client failed to
55
+ # connect, so `flare connect` can exit non-zero.
56
+ def run(ask: true)
57
+ @failed = false
58
+ puts
59
+ puts bold("Connect your AI assistant")
60
+
61
+ clients = CLIENTS.keys.select { |client| installed?(client) }
62
+ if clients.empty?
63
+ puts " No AI clients found. To connect one later, add #{url} to it as a remote MCP server."
64
+ puts " See #{@host}/docs/mcp"
65
+ elsif !ask || confirmed?(clients)
66
+ connect(clients)
67
+ end
68
+ !@failed
69
+ end
70
+
71
+ private
72
+
73
+ attr_reader :url
74
+
75
+ # A closed stdin (a script, an agent) counts as no.
76
+ def confirmed?(clients)
77
+ print " Found #{clients.map { |client| CLIENTS[client] }.join(", ")}. Connect #{clients.one? ? "it" : "them"} to Flare? (Y/n): "
78
+ answer = @input.gets
79
+ reply = answer.to_s.strip.downcase
80
+ return true if answer && (reply.empty? || reply.start_with?("y"))
81
+
82
+ puts if answer.nil?
83
+ puts " Skipped. Run #{bold("flare connect")} #{answer.nil? ? "in a terminal" : "any time"} to connect them."
84
+ false
85
+ end
86
+
87
+ # Suggests a first question only when some client is, or is about to be,
88
+ # pointed at Flare.
89
+ def connect(clients)
90
+ @ready = false
91
+ next_steps = clients.filter_map do |client|
92
+ hint = send("connect_#{client}")
93
+ "#{CLIENTS[client]}: #{hint}" if hint
94
+ end
95
+
96
+ puts
97
+ if next_steps.any?
98
+ puts " Next:"
99
+ next_steps.each { |line| puts " #{line}" }
100
+ puts
101
+ puts " Then ask: #{FIRST_PROMPT.inspect}"
102
+ elsif @ready
103
+ puts " Ask: #{FIRST_PROMPT.inspect}"
104
+ end
105
+ end
106
+
107
+ def installed?(client)
108
+ case client
109
+ when :claude then executable?("claude")
110
+ when :codex then executable?("codex")
111
+ when :cursor then executable?("cursor") || File.directory?(File.join(@home, ".cursor"))
112
+ when :claude_desktop then File.directory?(claude_desktop_directory)
113
+ end
114
+ end
115
+
116
+ def connect_claude
117
+ current = claude_config.dig("mcpServers", SERVER_NAME)
118
+ if current
119
+ return already(:claude) if current["type"] == "http" && current["url"] == url
120
+ return different(:claude, "run #{bold("claude mcp remove #{SERVER_NAME} -s user")}")
121
+ end
122
+
123
+ command = ["claude", "mcp", "add", "--transport", "http", "-s", "user", SERVER_NAME, url]
124
+ output, success = @runner.capture(*command)
125
+ return failed(:claude, command: command, output: output) unless success
126
+
127
+ connected(:claude, "run /mcp, choose #{SERVER_NAME}, and sign in")
128
+ end
129
+
130
+ def connect_codex
131
+ output, success = @runner.capture("codex", "mcp", "get", SERVER_NAME, "--json")
132
+ if success
133
+ current = parse_json(output)
134
+ transport = current["transport"] || {}
135
+ matching = transport["type"] == "streamable_http" && transport["url"] == url
136
+ return different(:codex, "run #{bold("codex mcp remove #{SERVER_NAME}")}") unless matching
137
+ return already(:codex) unless current["enabled"] == false
138
+ elsif !output.downcase.match?(/not found|no mcp server/)
139
+ return failed(:codex, command: ["codex", "mcp", "get", SERVER_NAME], output: output)
140
+ end
141
+
142
+ command = ["codex", "mcp", "add", SERVER_NAME, "--url", url]
143
+ return failed(:codex, command: command) unless @runner.attached(*command)
144
+
145
+ connected(:codex, "run `codex mcp login #{SERVER_NAME}` if it hasn't asked you to sign in")
146
+ end
147
+
148
+ # Sets mcpServers.flare in ~/.cursor/mcp.json, keeping everything else in it.
149
+ def connect_cursor
150
+ path = File.join(@home, ".cursor", "mcp.json")
151
+ document = File.exist?(path) ? JSON.parse(File.read(path)) : {}
152
+ servers = document["mcpServers"] ||= {}
153
+ entry = { "url" => url }
154
+
155
+ if servers.key?(SERVER_NAME)
156
+ return already(:cursor) if servers[SERVER_NAME] == entry
157
+ return different(:cursor, "remove #{SERVER_NAME} from ~/.cursor/mcp.json")
158
+ end
159
+
160
+ servers[SERVER_NAME] = entry
161
+ write_atomically(path, JSON.pretty_generate(document) + "\n")
162
+ connected(:cursor, "open Cursor Settings → MCP and sign in to #{SERVER_NAME}", where: "~/.cursor/mcp.json")
163
+ rescue JSON::ParserError, SystemCallError => e
164
+ failed(:cursor, output: e.message)
165
+ end
166
+
167
+ # Claude Desktop keeps remote servers in your account, not a file.
168
+ def connect_claude_desktop
169
+ "in Settings, add a custom connector with the URL #{url}"
170
+ end
171
+
172
+ # Each outcome prints one line and returns what's left to do in the client.
173
+ def connected(client, hint, where: nil)
174
+ @ready = true
175
+ puts " #{checkmark} Connected #{CLIENTS[client]}#{" in #{where}" if where}"
176
+ hint
177
+ end
178
+
179
+ def already(client)
180
+ @ready = true
181
+ puts " #{checkmark} #{CLIENTS[client]} is already connected to Flare"
182
+ nil
183
+ end
184
+
185
+ # Nothing broke, but this client isn't pointed at Flare, so it counts as
186
+ # a failure for `flare connect`'s exit status.
187
+ def different(client, how)
188
+ @failed = true
189
+ puts " #{warn_mark} #{CLIENTS[client]} already has a different #{SERVER_NAME} server, so it was left alone."
190
+ puts " To replace it, #{how}, then run #{bold("flare connect")}."
191
+ nil
192
+ end
193
+
194
+ def failed(client, command: nil, output: nil)
195
+ @failed = true
196
+ reason = output.to_s.lines.map(&:strip).reject(&:empty?).first
197
+ puts " #{xmark} Couldn't connect #{CLIENTS[client]}#{": #{reason}" if reason}"
198
+ puts " Run it yourself: #{command.join(" ")}" if command
199
+ nil
200
+ end
201
+
202
+ def claude_config
203
+ directory = @env.fetch("CLAUDE_CONFIG_DIR", "").empty? ? @home : @env["CLAUDE_CONFIG_DIR"]
204
+ path = File.join(directory, ".claude.json")
205
+ File.exist?(path) ? parse_json(File.read(path)) : {}
206
+ end
207
+
208
+ def parse_json(text)
209
+ value = JSON.parse(text)
210
+ value.is_a?(Hash) ? value : {}
211
+ rescue JSON::ParserError
212
+ {}
213
+ end
214
+
215
+ def claude_desktop_directory
216
+ case @platform
217
+ when /darwin/ then File.join(@home, "Library", "Application Support", "Claude")
218
+ when /mingw|mswin/ then File.join(@env.fetch("APPDATA", File.join(@home, "AppData", "Roaming")), "Claude")
219
+ else File.join(@env.fetch("XDG_CONFIG_HOME", File.join(@home, ".config")), "Claude")
220
+ end
221
+ end
222
+
223
+ def executable?(name)
224
+ @env.fetch("PATH", "").split(File::PATH_SEPARATOR).any? do |directory|
225
+ path = File.join(directory, name)
226
+ File.file?(path) && File.executable?(path)
227
+ end
228
+ end
229
+
230
+ # Writes to a temporary file and renames it, so a crash never leaves the
231
+ # client with half a config. The temporary file is created with the
232
+ # original's permissions, so a private config is never readable by others.
233
+ def write_atomically(path, contents)
234
+ FileUtils.mkdir_p(File.dirname(path))
235
+ mode = File.exist?(path) ? File.stat(path).mode & 0o777 : 0o644
236
+ temporary = "#{path}.flare-#{SecureRandom.hex(8)}"
237
+ created = false
238
+ File.open(temporary, File::WRONLY | File::CREAT | File::EXCL, mode) do |file|
239
+ created = true
240
+ file.write(contents)
241
+ end
242
+ File.chmod(mode, temporary)
243
+ File.rename(temporary, path)
244
+ created = false
245
+ ensure
246
+ File.delete(temporary) if created && File.exist?(temporary)
247
+ end
248
+ end
249
+ end
@@ -49,12 +49,10 @@ module Flare
49
49
 
50
50
  def query?(span)
51
51
  props = span[:properties]
52
- statement = props["db.statement"]
53
- return false unless statement && Storage::SQLite::SPAN_CATEGORIES["queries"].any? { |pattern| span[:name].downcase.include?(pattern) }
52
+ return false unless props["db.statement"] && Storage::SQLite::SPAN_CATEGORIES["queries"].any? { |pattern| span[:name].downcase.include?(pattern) }
54
53
 
55
- # Active Record's bookkeeping repeats by design. Transaction statements
56
- # from elsewhere have no name, so they're also matched by their text.
57
- !Storage::SQLite::BOOKKEEPING_QUERY_NAMES.include?(props["name"]) && !Storage::SQLite::TRANSACTION_STATEMENTS.include?(statement.to_s.strip.upcase)
54
+ # Active Record's bookkeeping repeats by design.
55
+ !Storage::SQLite.bookkeeping_query?(props)
58
56
  end
59
57
 
60
58
  # The statement with its values taken out, so one query run with different
@@ -11,15 +11,18 @@ require "fileutils"
11
11
  require "timeout"
12
12
  require_relative "output"
13
13
  require_relative "project"
14
+ require_relative "ai_clients_setup"
14
15
 
15
16
  module Flare
16
17
  class SetupCommand
17
18
  include CLI::Output
18
19
  include CLI::Project
19
20
 
20
- DEFAULT_HOST = "https://flare.am"
21
+ DEFAULT_HOST = AIClientsSetup::DEFAULT_HOST
21
22
  TIMEOUT_SECONDS = 300 # 5 minutes
22
23
  CLIENT_READ_TIMEOUT = 1
24
+ EXCHANGE_OPEN_TIMEOUT = 10
25
+ EXCHANGE_READ_TIMEOUT = 30
23
26
 
24
27
  class AuthorizationDenied < StandardError; end
25
28
 
@@ -85,14 +88,16 @@ module Flare
85
88
  # end
86
89
  RUBY
87
90
 
88
- def initialize(force: false)
91
+ def initialize(force: false, ai_clients: AIClientsSetup.new)
89
92
  @force = force
93
+ @ai_clients = ai_clients
90
94
  end
91
95
 
92
96
  def run
93
97
  authenticate
94
98
  create_initializer
95
99
  add_gitignore_entries
100
+ @ai_clients.run
96
101
 
97
102
  puts
98
103
  puts "#{green("Setup complete!")}"
@@ -234,11 +239,16 @@ module Flare
234
239
  "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: #{body.bytesize}\r\nConnection: close\r\n\r\n#{body}"
235
240
  end
236
241
 
242
+ # The browser step's code works once, so when this fails, setup has to
243
+ # start over. Say so, instead of printing a backtrace.
237
244
  def exchange_code(auth_code, code_verifier)
238
245
  host = ENV.fetch("FLARE_HOST", DEFAULT_HOST)
239
246
  uri = URI("#{host}/api/cli/exchange")
240
247
  http = Net::HTTP.new(uri.host, uri.port)
241
248
  http.use_ssl = uri.scheme == "https"
249
+ http.open_timeout = EXCHANGE_OPEN_TIMEOUT
250
+ http.read_timeout = EXCHANGE_READ_TIMEOUT
251
+ http.write_timeout = EXCHANGE_READ_TIMEOUT
242
252
 
243
253
  request = Net::HTTP::Post.new(uri.path)
244
254
  request["Content-Type"] = "application/x-www-form-urlencoded"
@@ -253,14 +263,24 @@ module Flare
253
263
  end
254
264
 
255
265
  data = JSON.parse(response.body)
256
- token = data["token"]
266
+ token = data["token"] if data.is_a?(Hash)
257
267
 
258
- if token.nil? || token.empty?
268
+ if !token.is_a?(String) || token.empty?
259
269
  $stderr.puts "No token received from server."
260
270
  exit 1
261
271
  end
262
272
 
263
273
  token
274
+ rescue Timeout::Error
275
+ exchange_failed("Flare didn't answer in time")
276
+ rescue JSON::ParserError, IOError, SystemCallError, SocketError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError => e
277
+ exchange_failed(e.message)
278
+ end
279
+
280
+ def exchange_failed(reason)
281
+ $stderr.puts "Couldn't finish signing in to Flare: #{reason}"
282
+ $stderr.puts "Run #{bold("flare setup")} again."
283
+ exit 1
264
284
  end
265
285
 
266
286
  # --- Token storage ---
data/lib/flare/cli.rb CHANGED
@@ -6,6 +6,7 @@ module Flare
6
6
  module CLI
7
7
  COMMANDS = {
8
8
  "setup" => "Authenticate and configure Flare for this project",
9
+ "connect" => "Connect your AI assistants to Flare",
9
10
  "doctor" => "Check your Flare setup for issues",
10
11
  "status" => "Show current Flare configuration",
11
12
  "requests" => "List recent requests from local development spans",
@@ -23,6 +24,9 @@ module Flare
23
24
  require_relative "cli/setup_command"
24
25
  force = argv.include?("--force")
25
26
  SetupCommand.new(force: force).run
27
+ when "connect"
28
+ require_relative "cli/ai_clients_setup"
29
+ exit 1 unless AIClientsSetup.new.run(ask: false)
26
30
  when "doctor"
27
31
  require_relative "cli/doctor_command"
28
32
  DoctorCommand.new.run
data/lib/flare/engine.rb CHANGED
@@ -27,8 +27,9 @@ module Flare
27
27
 
28
28
  # Phase 2: Start background threads after all initializers have run
29
29
  # so user config (metrics_enabled, tracing_enabled, flush_interval,
30
- # tracing_poll_interval, etc.) is applied.
30
+ # tracing_poll_interval, subscribe_patterns, etc.) is applied.
31
31
  config.after_initialize do
32
+ Flare.subscribe_to_custom_patterns
32
33
  Flare.start_rule_manager
33
34
  Flare.start_metrics_flusher
34
35
  end
@@ -14,18 +14,21 @@ module Flare
14
14
  @count = Concurrent::AtomicFixnum.new(0)
15
15
  @sum_ms = Concurrent::AtomicFixnum.new(0)
16
16
  @error_count = Concurrent::AtomicFixnum.new(0)
17
+ @slow_count = Concurrent::AtomicFixnum.new(0)
17
18
  end
18
19
 
19
- def increment(duration_ms:, error: false)
20
+ def increment(duration_ms:, error: false, slow: false)
20
21
  @count.increment
21
22
  @sum_ms.increment(duration_ms.to_i)
22
23
  @error_count.increment if error
24
+ @slow_count.increment if slow
23
25
  end
24
26
 
25
- def add(count:, sum_ms:, error_count: 0)
27
+ def add(count:, sum_ms:, error_count: 0, slow_count: 0)
26
28
  @count.increment(count.to_i)
27
29
  @sum_ms.increment(sum_ms.to_i)
28
30
  @error_count.increment(error_count.to_i)
31
+ @slow_count.increment(slow_count.to_i)
29
32
  end
30
33
 
31
34
  def count
@@ -40,11 +43,16 @@ module Flare
40
43
  @error_count.value
41
44
  end
42
45
 
46
+ def slow_count
47
+ @slow_count.value
48
+ end
49
+
43
50
  def to_h
44
51
  {
45
52
  count: @count.value,
46
53
  sum_ms: @sum_ms.value,
47
- error_count: @error_count.value
54
+ error_count: @error_count.value,
55
+ slow_count: @slow_count.value
48
56
  }
49
57
  end
50
58
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "active_support/inflector/methods"
4
4
  require_relative "metric_key"
5
+ require_relative "slo_manager"
5
6
  require_relative "http_metrics_config"
6
7
  require_relative "sql_mask"
7
8
  require_relative "store_statement"
@@ -19,7 +20,9 @@ module Flare
19
20
  CLIENT = :client
20
21
  CONSUMER = :consumer
21
22
 
22
- # Cache store class name patterns mapped to short service names
23
+ # Cache store name patterns mapped to short service names. Patterns are
24
+ # matched against the downcased store name, which is usually a class name
25
+ # with no underscores (SolidCache::Store is "solidcache::store").
23
26
  CACHE_STORE_MAP = {
24
27
  "redis" => "redis",
25
28
  "mem_cache" => "memcache",
@@ -28,15 +31,28 @@ module Flare
28
31
  "file" => "file",
29
32
  "memory" => "memory",
30
33
  "null" => "null",
31
- "solid_cache" => "solid_cache"
34
+ "solid_cache" => "solid_cache",
35
+ "solidcache" => "solid_cache"
32
36
  }.freeze
33
37
 
34
38
  ACTIVE_JOB_ERROR_STATUS = /\AUnexpected ActiveJob Error (\S+)\z/
35
39
 
36
- def initialize(storage:, http_metrics_config: nil, ignore_errors: nil)
40
+ # Where a statement names the table it writes, by its first word. Every
41
+ # other statement is named for the table it reads FROM.
42
+ INTO_TABLE = /\bINTO\s+[`"]?(\w+)[`"]?/i
43
+ WRITE_TABLES = {
44
+ "INSERT" => INTO_TABLE,
45
+ "REPLACE" => INTO_TABLE,
46
+ "MERGE" => INTO_TABLE,
47
+ "UPDATE" => /\bUPDATE\s+[`"]?(\w+)[`"]?/i
48
+ }.freeze
49
+ READ_TABLE = /\bFROM\s+[`"]?(\w+)[`"]?/i
50
+
51
+ def initialize(storage:, http_metrics_config: nil, ignore_errors: nil, slo_manager: nil)
37
52
  @storage = storage
38
53
  @http_metrics_config = http_metrics_config || HttpMetricsConfig::DEFAULT
39
54
  @ignore_errors = ignore_errors || []
55
+ @slo_manager = slo_manager || SloManager.new
40
56
  @pid = $$
41
57
  end
42
58
 
@@ -158,11 +174,7 @@ module Flare
158
174
  operation: http_status_class(span)
159
175
  )
160
176
 
161
- @storage.increment(
162
- key,
163
- duration_ms: duration_ms(span),
164
- error: http_error?(span)
165
- )
177
+ increment_with_slo(key, duration_ms: duration_ms(span), error: http_error?(span))
166
178
  end
167
179
 
168
180
  def record_background_metric(span)
@@ -176,11 +188,15 @@ module Flare
176
188
  operation: transaction_name ? "perform" : (span.attributes["code.function"] || span.name)
177
189
  )
178
190
 
179
- @storage.increment(
180
- key,
181
- duration_ms: duration_ms(span),
182
- error: span_error?(span)
183
- )
191
+ increment_with_slo(key, duration_ms: duration_ms(span), error: span_error?(span))
192
+ end
193
+
194
+ # Web and job entry points also count toward the latency SLO: slow means
195
+ # over the operation's threshold without erroring.
196
+ def increment_with_slo(key, duration_ms:, error:)
197
+ slow = @slo_manager.slow?(namespace: key.namespace, service: key.service, target: key.target,
198
+ duration_ms: duration_ms, error: error)
199
+ @storage.increment(key, duration_ms: duration_ms, error: error, slow: slow)
184
200
  end
185
201
 
186
202
  def record_db_metric(span)
@@ -365,22 +381,42 @@ module Flare
365
381
  (operation || SqlMask.operation_word(span.name.to_s.split.last))&.downcase || "query"
366
382
  else
367
383
  # 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"])
384
+ word = statement ? first_word(statement) : SqlMask.command_word(span.attributes["db.statement"])
369
385
  (operation || word)&.upcase || "query"
370
386
  end
371
387
  end
372
388
 
389
+ # The table the statement works on: an INSERT's INTO, an UPDATE's own
390
+ # table, otherwise the first FROM outside parentheses, so an upsert's
391
+ # "IS NOT DISTINCT FROM excluded.x" or a subquery in the select list can't
392
+ # name it. With no FROM outside parentheses (SELECT COUNT(*) FROM
393
+ # (SELECT ...)), and for a WITH, the first one anywhere counts.
373
394
  def extract_sql_table(statement)
374
395
  return nil unless statement
375
396
 
376
- case statement
377
- when /\bFROM\s+[`"]?(\w+)[`"]?/i
378
- $1
379
- when /\bINTO\s+[`"]?(\w+)[`"]?/i
380
- $1
381
- when /\bUPDATE\s+[`"]?(\w+)[`"]?/i
382
- $1
397
+ word = first_word(statement)&.upcase
398
+ pattern = WRITE_TABLES.fetch(word, READ_TABLE)
399
+ return statement[pattern, 1] if word == "WITH"
400
+
401
+ scanner = StringScanner.new(statement)
402
+ first = nil
403
+ depth = 0
404
+ counted = 0
405
+ while scanner.skip_until(pattern)
406
+ # Masked SQL has no parentheses inside values. Count only the text
407
+ # since the last match, so a long statement is read once.
408
+ between = statement.byteslice(counted, scanner.pos - scanner.matched_size - counted)
409
+ depth += between.count("(") - between.count(")")
410
+ return scanner[1] if depth <= 0
411
+
412
+ first ||= scanner[1]
413
+ counted = scanner.pos
383
414
  end
415
+ first
416
+ end
417
+
418
+ def first_word(statement)
419
+ statement[/\S+/]
384
420
  end
385
421
 
386
422
  def extract_host_from_url(span)
@@ -12,16 +12,16 @@ module Flare
12
12
  @pid = $$
13
13
  end
14
14
 
15
- def increment(key, duration_ms:, error: false)
15
+ def increment(key, duration_ms:, error: false, slow: false)
16
16
  detect_forking
17
17
  counter = @storage.compute_if_absent(key) { MetricCounter.new }
18
- counter.increment(duration_ms: duration_ms, error: error)
18
+ counter.increment(duration_ms: duration_ms, error: error, slow: slow)
19
19
  end
20
20
 
21
- def add(key, count:, sum_ms:, error_count: 0)
21
+ def add(key, count:, sum_ms:, error_count: 0, slow_count: 0)
22
22
  detect_forking
23
23
  counter = @storage.compute_if_absent(key) { MetricCounter.new }
24
- counter.add(count: count, sum_ms: sum_ms, error_count: error_count)
24
+ counter.add(count: count, sum_ms: sum_ms, error_count: error_count, slow_count: slow_count)
25
25
  end
26
26
 
27
27
  # Atomically retrieves and clears all metrics.
@@ -109,7 +109,8 @@ module Flare
109
109
  operation: key.operation,
110
110
  count: values[:count],
111
111
  sum_ms: values[:sum_ms],
112
- error_count: values[:error_count]
112
+ error_count: values[:error_count],
113
+ slow_count: values.fetch(:slow_count, 0)
113
114
  }
114
115
  end
115
116
 
@@ -18,6 +18,9 @@ module Flare
18
18
 
19
19
  # Variable => how to read a revision from it (nil: the value as is).
20
20
  PLATFORM_VARIABLES = {
21
+ # Heroku sets HEROKU_BUILD_COMMIT with the runtime-dyno-build-metadata
22
+ # lab, and the deprecated HEROKU_SLUG_COMMIT with runtime-dyno-metadata.
23
+ "HEROKU_BUILD_COMMIT" => nil,
21
24
  "HEROKU_SLUG_COMMIT" => nil,
22
25
  "RENDER_GIT_COMMIT" => nil,
23
26
  "RAILWAY_GIT_COMMIT_SHA" => nil,
@@ -30,10 +30,11 @@ module Flare
30
30
  attr_reader :poll_count, :etag, :stopped_due_to_auth, :last_error_count
31
31
 
32
32
  def initialize(sampler:, marker:, pool:, base_url:, api_key:, project:, environment:,
33
- interval: DEFAULT_INTERVAL, transport: nil, logger: nil)
33
+ slo_manager: nil, interval: DEFAULT_INTERVAL, transport: nil, logger: nil)
34
34
  @sampler = sampler
35
35
  @marker = marker
36
36
  @pool = pool
37
+ @slo_manager = slo_manager
37
38
  @rules_url = "#{base_url.to_s.chomp('/')}/api/rules"
38
39
  @api_key = api_key
39
40
  @project = project
@@ -129,13 +130,18 @@ module Flare
129
130
  end
130
131
 
131
132
  # Server payload shape (see tirana-v2 Api::RulesController):
132
- # { "trace_rules": [{ "id", "match_attributes", "rate", ..., "urls": [...] }] }
133
+ # { "trace_rules": [{ "id", "match_attributes", "rate", ..., "urls": [...] }],
134
+ # "slo_rules": [{ "namespace", "service"?, "target"?, "threshold_ms" }] }
135
+ # The `slo_rules` key is optional; the rules poll is authoritative, so an
136
+ # absent array clears any prior SLO config (update treats nil as empty).
133
137
  def apply(payload)
134
138
  rules = payload["trace_rules"] || []
135
139
  @sampler.update_rules(rules)
136
140
 
137
141
  url_entries = rules.flat_map { |r| Array(r["urls"]) }
138
142
  @pool.replace(url_entries)
143
+
144
+ @slo_manager&.update(payload["slo_rules"])
139
145
  end
140
146
  end
141
147
  end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "concurrent/atomic/atomic_reference"
4
+
5
+ module Flare
6
+ # Holds the latency SLO thresholds delivered by the server in the `slo_rules`
7
+ # array of GET /api/rules. MetricSpanProcessor asks slow? at every web/job
8
+ # span end to decide whether the operation was "too slow" -- the latency SLI
9
+ # counterpart to error_count.
10
+ #
11
+ # The wire shape is a flat array of rules, each { namespace, service?, target?,
12
+ # threshold_ms }:
13
+ # - a namespace-only rule sets that namespace's default (e.g. web => 1000);
14
+ # - a rule that also carries service + target is a per-operation override.
15
+ # Internally these split into a defaults hash (keyed by namespace) and an
16
+ # overrides hash (keyed by [namespace, service, target]).
17
+ #
18
+ # Precedence: exact override -> namespace default -> nil.
19
+ # nil means "untracked" -- the processor records no slow_count for it.
20
+ #
21
+ # The whole config is swapped atomically (like Sampler#update_rules) so a
22
+ # mid-poll read always sees a consistent defaults+overrides pair. Malformed
23
+ # rules from a bad server payload are dropped rather than raising.
24
+ class SloManager
25
+ Config = Struct.new(:defaults, :overrides, keyword_init: true)
26
+
27
+ EMPTY = Config.new(defaults: {}.freeze, overrides: {}.freeze).freeze
28
+
29
+ def initialize
30
+ @config_ref = Concurrent::AtomicReference.new(EMPTY)
31
+ end
32
+
33
+ # slo_rules: flat array of { "namespace", "service"?, "target"?,
34
+ # "threshold_ms" } hashes (string or symbol keys accepted). A namespace-only
35
+ # rule is that namespace's default; namespace + service + target is an
36
+ # override. Rules missing namespace/threshold, or with only one of
37
+ # service/target, are skipped. An absent/empty array clears the config.
38
+ def update(slo_rules)
39
+ defaults = {}
40
+ overrides = {}
41
+
42
+ Array(slo_rules).each do |rule|
43
+ next unless rule.is_a?(Hash)
44
+
45
+ namespace = stringify(rule["namespace"] || rule[:namespace])
46
+ service = stringify(rule["service"] || rule[:service])
47
+ target = stringify(rule["target"] || rule[:target])
48
+ threshold = coerce_threshold(rule["threshold_ms"] || rule[:threshold_ms])
49
+
50
+ next if namespace.nil? || threshold.nil?
51
+
52
+ if service && target
53
+ overrides[[namespace, service, target]] = threshold
54
+ elsif service.nil? && target.nil?
55
+ defaults[namespace] = threshold
56
+ end
57
+ end
58
+
59
+ @config_ref.set(Config.new(defaults: defaults.freeze, overrides: overrides.freeze).freeze)
60
+ end
61
+
62
+ # Returns the threshold in integer milliseconds for this operation, or nil
63
+ # when the operation is untracked (no override and no namespace default).
64
+ def threshold_for(namespace:, service:, target:)
65
+ lookup(@config_ref.get, namespace, service, target)
66
+ end
67
+
68
+ # Latency SLI predicate: true when the operation exceeded its SLO threshold
69
+ # and did not error. Kept disjoint from errors so error_count + slow_count
70
+ # never double-counts. Untracked operations (no threshold) are never slow.
71
+ def slow?(namespace:, service:, target:, duration_ms:, error:)
72
+ return false if error
73
+
74
+ threshold = lookup(@config_ref.get, namespace, service, target)
75
+ !threshold.nil? && duration_ms > threshold
76
+ end
77
+
78
+ private
79
+
80
+ # Skips the override lookup, and the Array key it allocates, when there are
81
+ # no overrides: the common case is namespace defaults only, or no SLOs.
82
+ def lookup(config, namespace, service, target)
83
+ threshold = config.overrides[[namespace, service, target]] unless config.overrides.empty?
84
+ threshold || config.defaults[namespace]
85
+ end
86
+
87
+ def stringify(value)
88
+ return nil if value.nil?
89
+
90
+ str = value.to_s
91
+ str.empty? ? nil : str
92
+ end
93
+
94
+ def coerce_threshold(value)
95
+ return nil if value.nil?
96
+ # Infinity and NaN (JSON 1e400 parses as Infinity) would raise in to_i
97
+ # and abort the whole update, so they are dropped like any bad rule.
98
+ return nil if value.is_a?(Float) && !value.finite?
99
+ return nil unless value.is_a?(Numeric) || value.to_s.match?(/\A\d+\z/)
100
+
101
+ ms = value.to_i
102
+ ms.positive? ? ms : nil
103
+ end
104
+ end
105
+ end
@@ -276,8 +276,8 @@ module Flare
276
276
 
277
277
  # List spans that have exception events
278
278
  def list_exception_spans(name: nil, sort: nil, limit: 50, offset: 0)
279
- conditions = []
280
- values = []
279
+ conditions = ["e.name = ?"]
280
+ values = ["exception"]
281
281
 
282
282
  if name
283
283
  conditions << "e.name LIKE ?"
@@ -315,8 +315,8 @@ module Flare
315
315
  end
316
316
 
317
317
  def count_exception_spans(name: nil)
318
- conditions = []
319
- values = []
318
+ conditions = ["e.name = ?"]
319
+ values = ["exception"]
320
320
 
321
321
  if name
322
322
  conditions << "e.name LIKE ?"
data/lib/flare/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Flare
4
- VERSION = "0.5.1"
4
+ VERSION = "0.6.0"
5
5
  end
data/lib/flare.rb CHANGED
@@ -17,6 +17,7 @@ require_relative "flare/metric_submitter"
17
17
  require_relative "flare/recording_batch_span_processor"
18
18
  require_relative "flare/lifecycle"
19
19
 
20
+ require_relative "flare/slo_manager"
20
21
  require_relative "flare/sampler"
21
22
  require_relative "flare/marker"
22
23
  require_relative "flare/web_marker_subscriber"
@@ -132,6 +133,14 @@ module Flare
132
133
  def marker = @marker
133
134
  def upload_url_pool = @upload_url_pool
134
135
  def rule_manager = @rule_manager
136
+
137
+ # Shared latency-SLO config. Updated by RuleManager from the /api/rules
138
+ # `slo_rules` array and read by MetricSpanProcessor to compute slow_count. Memoized so a
139
+ # single instance is shared whether or not tracing submission is configured.
140
+ def slo_manager
141
+ @slo_manager ||= SloManager.new
142
+ end
143
+
135
144
  def trace_span_processor = @trace_span_processor
136
145
  def trace_health_reporter = @trace_health_reporter
137
146
 
@@ -265,6 +274,7 @@ module Flare
265
274
  sampler: @sampler,
266
275
  marker: @marker,
267
276
  pool: @upload_url_pool,
277
+ slo_manager: slo_manager,
268
278
  base_url: configuration.url,
269
279
  api_key: configuration.key,
270
280
  project: service_name_for_app,
@@ -340,7 +350,8 @@ module Flare
340
350
  metric_processor = MetricSpanProcessor.new(
341
351
  storage: @metric_storage,
342
352
  http_metrics_config: configuration.http_metrics_config,
343
- ignore_errors: configuration.ignore_errors
353
+ ignore_errors: configuration.ignore_errors,
354
+ slo_manager: slo_manager
344
355
  )
345
356
  OpenTelemetry.tracer_provider.add_span_processor(metric_processor)
346
357
 
@@ -438,11 +449,18 @@ module Flare
438
449
 
439
450
  # Auto-subscribe to custom patterns (default: "app.*")
440
451
  # This lets users just do: ActiveSupport::Notifications.instrument("app.whatever") { }
452
+ @subscribed_patterns = []
441
453
  subscribe_to_custom_patterns
442
454
  end
443
455
 
456
+ # Runs again after the app's initializers, which Rails loads after
457
+ # configure_opentelemetry, for any prefixes they added. Each prefix is
458
+ # subscribed once.
444
459
  def subscribe_to_custom_patterns
445
- configuration.subscribe_patterns.each do |prefix|
460
+ return unless @subscribed_patterns
461
+
462
+ (configuration.subscribe_patterns.uniq - @subscribed_patterns).each do |prefix|
463
+ @subscribed_patterns << prefix
446
464
  # Subscribe to all notifications starting with this prefix
447
465
  pattern = /\A#{Regexp.escape(prefix)}/
448
466
  default_transformer = ->(payload) {
@@ -543,6 +561,7 @@ module Flare
543
561
  @metric_flusher&.stop
544
562
  @metric_flusher = nil
545
563
  @metric_storage = nil
564
+ @slo_manager = nil
546
565
  @otel_configured = false
547
566
  end
548
567
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: flare
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.1
4
+ version: 0.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - John Nunemaker
@@ -192,6 +192,7 @@ files:
192
192
  - lib/flare.rb
193
193
  - lib/flare/backoff_policy.rb
194
194
  - lib/flare/cli.rb
195
+ - lib/flare/cli/ai_clients_setup.rb
195
196
  - lib/flare/cli/doctor_command.rb
196
197
  - lib/flare/cli/local_spans.rb
197
198
  - lib/flare/cli/nplus1_command.rb
@@ -222,6 +223,7 @@ files:
222
223
  - lib/flare/revision.rb
223
224
  - lib/flare/rule_manager.rb
224
225
  - lib/flare/sampler.rb
226
+ - lib/flare/slo_manager.rb
225
227
  - lib/flare/source_location.rb
226
228
  - lib/flare/sql_mask.rb
227
229
  - lib/flare/sqlite_exporter.rb