flare 0.7.1 → 0.8.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: 06543f8e97440cfbe115d30a0fccc5eb2b3cfe3f1bb19243e6a8b832e2bee9d8
4
- data.tar.gz: d4f2d9fd14fefc4e941fd3d8c1f3786d138ca0c444206d5cce41ccf94fb772d5
3
+ metadata.gz: 2664e89cd118c2dab8c25285165584c85a4ddc6e1d033ebf0466b74ce4ffd016
4
+ data.tar.gz: 836bdb864ccb944c6a8dfa11ab6d96a01507a149d261a42bf8352ffa3caae722
5
5
  SHA512:
6
- metadata.gz: 7191964214be716b81eadef8afb1cebc019e8b5b4fd8cfa30965e6c24f36ae838309f301fb63fce9d947c5cda163bef4fb00cb916e8070088a5fce23f83ef1f7
7
- data.tar.gz: d800c3b5d495b9609c3187874bcaa343035a1a9f9dae9c7f295e2b7c2110191632169990abbed917c333623d9002d671c4979a779c0ec2530acf25b14fa86b7e
6
+ metadata.gz: 9fd6d817b046445a2b4bbda964c4e6bc1ee422d650f8f8ed9792fe55154ae85d0dd27696e1d67c87b4d378fe137e4c1131e9122e0c6709de253609fb7918c23e
7
+ data.tar.gz: f7a34069ea120fbb3b486d51068920cadd2689b4b16573c6a4ac09935ea3a13d085f778822891f0660953c781b6f92afd6c6de0fb2609458833c136554ff08bf
data/README.md CHANGED
@@ -137,7 +137,7 @@ Flare.configure do |config|
137
137
  request.path.start_with?("/health")
138
138
  }
139
139
 
140
- # Exceptions that don't count as errors in metrics (see below)
140
+ # Exceptions Flare ignores (see below)
141
141
  config.ignore_errors << "MyApp::RetryLaterError"
142
142
 
143
143
  # Subscribe to custom notification prefixes (default: ["app."])
@@ -150,13 +150,18 @@ Flare.configure do |config|
150
150
  end
151
151
  ```
152
152
 
153
- ### Errors that aren't failures
153
+ ### Ignored errors
154
154
 
155
- Some exceptions are control flow. A GoodJob job with `perform_limit` or `perform_throttle` raises `GoodJob::ActiveJobExtensions::Concurrency::ConcurrencyExceededError` (or its subclass `ThrottleExceededError`) to wait its turn, then retries. Flare counts a span that ends with an exception in `config.ignore_errors`, or a subclass of one, as a success: it still counts toward throughput and duration, just not the error rate. Traces still record the exception. Append your own class names, or assign a new list to replace the default:
155
+ `config.ignore_errors` is the one list of exceptions Flare ignores: they don't count as failures in metrics and don't become errors. A subclass of a listed class is ignored too. A span that ends with one still counts toward throughput and duration, just not the error rate, and traces still record the exception. A request that returns a 5xx always counts as failed.
156
+
157
+ The defaults cover noise (routing errors, `ActiveRecord::RecordNotFound`, invalid authenticity tokens, malformed params and the like, see `Flare::Configuration::DEFAULT_IGNORE_ERRORS`) and control flow: a GoodJob job with `perform_limit` or `perform_throttle` raises `GoodJob::ActiveJobExtensions::Concurrency::ConcurrencyExceededError` (or its subclass `ThrottleExceededError`) to wait its turn, then retries.
158
+
159
+ Add your own, remove a default, or replace the list:
156
160
 
157
161
  ```ruby
158
162
  config.ignore_errors << "MyApp::RetryLaterError"
159
- config.ignore_errors = [] # count every exception as an error
163
+ config.ignore_errors.delete("ActiveRecord::RecordNotFound") # count missing records again
164
+ config.ignore_errors = [] # count every exception
160
165
  ```
161
166
 
162
167
  ## Custom Instrumentation
@@ -52,8 +52,11 @@ module Flare
52
52
  # request.path.start_with?("/health")
53
53
  # }
54
54
 
55
- # Exceptions (and subclasses) that don't count as errors in metrics.
55
+ # Exceptions (and subclasses) Flare ignores: they don't count as
56
+ # failures in metrics and don't become errors. The defaults cover
57
+ # routing errors, missing records, bad tokens and the like.
56
58
  # config.ignore_errors << "MyApp::RetryLaterError"
59
+ # config.ignore_errors.delete("ActiveRecord::RecordNotFound")
57
60
 
58
61
  # ── Metrics (remote monitoring) ────────────────────────────────────
59
62
  # Metrics aggregate span data into counts, durations, and error rates.
@@ -41,10 +41,34 @@ module Flare
41
41
 
42
42
  attr_accessor :subscribe_patterns
43
43
 
44
- # Exceptions that jobs raise to wait or retry rather than to fail. A span
45
- # that ends with one of these (or a subclass) counts as a success.
44
+ # Exceptions Flare ignores: they don't count as failures in metrics and
45
+ # don't become errors. Subclasses match too. GoodJob raises its entry to
46
+ # wait its turn; the rest are Honeybadger's noise defaults (bad routes,
47
+ # missing records, bad tokens, malformed requests). A request that
48
+ # returns a 5xx still counts as a failure in metrics, so
49
+ # ActionController::NotImplemented (501) counts as a failed request but,
50
+ # as a subclass of MethodNotAllowed, is still ignored as an error.
46
51
  DEFAULT_IGNORE_ERRORS = %w[
52
+ AbstractController::ActionNotFound
53
+ ActionController::BadRequest
54
+ ActionController::InvalidAuthenticityToken
55
+ ActionController::InvalidCrossOriginRequest
56
+ ActionController::MethodNotAllowed
57
+ ActionController::ParameterMissing
58
+ ActionController::RoutingError
59
+ ActionController::UnknownAction
60
+ ActionController::UnknownFormat
61
+ ActionController::UnknownHttpMethod
62
+ ActionDispatch::Http::MimeNegotiation::InvalidType
63
+ ActionDispatch::Http::Parameters::ParseError
64
+ ActiveRecord::RecordNotFound
65
+ CGI::Session::CookieStore::TamperedWithCookie
47
66
  GoodJob::ActiveJobExtensions::Concurrency::ConcurrencyExceededError
67
+ Mongoid::Errors::DocumentNotFound
68
+ Rack::QueryParser::InvalidParameterError
69
+ Rack::QueryParser::ParameterTypeError
70
+ Sidekiq::JobRetry::Skip
71
+ Sinatra::NotFound
48
72
  ].freeze
49
73
 
50
74
  # HTTP metrics path tracking configuration.
data/lib/flare/engine.rb CHANGED
@@ -32,6 +32,7 @@ module Flare
32
32
  Flare.subscribe_to_custom_patterns
33
33
  Flare.start_rule_manager
34
34
  Flare.start_metrics_flusher
35
+ Flare.subscribe_to_error_reporter
35
36
  end
36
37
 
37
38
  # Auto-mount routes in development/test
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ module Flare
6
+ # Groups occurrences of the same bug. The fingerprint is the error class plus
7
+ # the top app frames, by file and method only. Line numbers, messages and
8
+ # anything volatile (GUIDs, numbers, generated template method names) stay
9
+ # out, so editing a file or a new record id can't split one bug into many
10
+ # groups.
11
+ module ErrorFingerprint
12
+ FINGERPRINT_FRAMES = 3
13
+
14
+ Frame = Struct.new(:file, :line, :method, :app, keyword_init: true) do
15
+ # File and method with the volatile parts taken out, e.g.
16
+ # "app/models/user.rb:save".
17
+ def normalized
18
+ "#{ErrorFingerprint.normalize_file(file)}:#{ErrorFingerprint.normalize_method(method)}"
19
+ end
20
+ end
21
+
22
+ # "/path/file.rb:12:in `method'" (Ruby < 3.4) or "in 'Klass#method'" (3.4+).
23
+ BACKTRACE_LINE = /\A(.+?):(\d+)(?::in [`'](.*)')?\z/
24
+ # "block (2 levels) in ", "rescue in ", "ensure in " in front of a label.
25
+ LABEL_PREFIX = /\A(?:(?:block|rescue|ensure)(?: \(\d+ levels\))? in )+/
26
+ UUID = /\h{8}-\h{4}-\h{4}-\h{4}-\h{12}/
27
+ LONG_HEX = /\b\h{16,}\b/
28
+ DIGITS = /\d+/
29
+ # ".../gems/3.4.0/gems/activerecord-7.2.3/lib/..." -> "activerecord-7.2.3/lib/..."
30
+ GEM_PATH = %r{\A.*/gems/(?:\d[^/]*/gems/)?}
31
+ GEM_VERSION = %r{\A([^/]+?)-\d[^/]*/}
32
+ RUBY_LIB_PATH = %r{\A.*/lib/ruby/(?:\d[^/]*/)?}
33
+ VENDORED = %r{\A(?:vendor|node_modules|tmp)/|/gems/}
34
+ FLARE_LIB = "#{File.expand_path("..", __dir__)}/"
35
+
36
+ module_function
37
+
38
+ def fingerprint(class_name, frames)
39
+ app = frames.select(&:app)
40
+ # A block around code adds a "block in foo" frame next to "foo"; collapse
41
+ # repeats so wrapping a line in a block doesn't change the group.
42
+ picked = []
43
+ (app.empty? ? frames : app).each do |frame|
44
+ normalized = frame.normalized
45
+ picked << normalized unless picked.last == normalized
46
+ break if picked.size == FINGERPRINT_FRAMES
47
+ end
48
+ Digest::SHA256.hexdigest([normalize_class(class_name), *picked].join("\n"))[0, 16]
49
+ end
50
+
51
+ def frames(exception, root: app_root)
52
+ locations = exception.backtrace_locations
53
+ if locations && !locations.empty?
54
+ locations.map { |location| frame(location.absolute_path || location.path, location.lineno, location.label, root) }
55
+ else
56
+ Array(exception.backtrace).filter_map do |line|
57
+ match = BACKTRACE_LINE.match(line.to_s)
58
+ frame(match[1], match[2].to_i, match[3], root) if match
59
+ end
60
+ end
61
+ end
62
+
63
+ def frame(path, line, label, root)
64
+ path = path.to_s
65
+ app = app_path?(path, root)
66
+ Frame.new(file: display_path(path, root, app), line: line, method: label.to_s, app: app)
67
+ end
68
+
69
+ def app_path?(path, root)
70
+ return false if root.nil? || path.start_with?(FLARE_LIB)
71
+ return false unless path.start_with?(root)
72
+
73
+ !path.delete_prefix(root).match?(VENDORED)
74
+ end
75
+
76
+ def display_path(path, root, app)
77
+ return path.delete_prefix(root) if app
78
+
79
+ if path.match?(GEM_PATH)
80
+ path.sub(GEM_PATH, "")
81
+ elsif path.match?(RUBY_LIB_PATH)
82
+ "ruby/#{path.sub(RUBY_LIB_PATH, "")}"
83
+ elsif root && path.start_with?(root)
84
+ path.delete_prefix(root)
85
+ else
86
+ path
87
+ end
88
+ end
89
+
90
+ # Gem versions change on every bundle update; the code that raised doesn't.
91
+ def normalize_file(file)
92
+ file.to_s.sub(GEM_VERSION, '\1/').gsub(UUID, "").gsub(LONG_HEX, "")
93
+ end
94
+
95
+ # Bare method name: "block (2 levels) in Users#show" -> "show",
96
+ # "_app_views_users_show_html_erb__1234_5678" -> "_app_views_users_show_html_erb__".
97
+ def normalize_method(label)
98
+ name = label.to_s.sub(LABEL_PREFIX, "")
99
+ name = name.split(/[#.]/).last.to_s if name.match?(/\A[A-Z][\w:]*[#.]/)
100
+ name.gsub(UUID, "").gsub(DIGITS, "")
101
+ end
102
+
103
+ # Anonymous classes print as "#<Class:0x000...>".
104
+ def normalize_class(class_name)
105
+ class_name.to_s.gsub(/0x\h+/, "")
106
+ end
107
+
108
+ def app_root
109
+ @app_root ||= begin
110
+ root = (Rails.root.to_s if defined?(Rails) && Rails.respond_to?(:root) && Rails.root)
111
+ root ||= Dir.pwd
112
+ root.end_with?("/") ? root : "#{root}/"
113
+ end
114
+ rescue StandardError
115
+ nil
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "zlib"
5
+
6
+ require_relative "error_fingerprint"
7
+ require_relative "utf8"
8
+ require_relative "version"
9
+
10
+ module Flare
11
+ # One stored copy of an error occurrence, uploaded to R2 the first time a
12
+ # process sees a fingerprint. No values leave the process: the message keeps
13
+ # only plain words, and params are names only.
14
+ module ErrorSample
15
+ MAX_FRAMES = 200
16
+ MAX_BYTES = 256 * 1024
17
+ MAX_MESSAGE_BYTES = 4_096
18
+ MAX_PARAM_NAMES = 100
19
+ MAX_NAME_BYTES = 200
20
+ MASK = "?"
21
+
22
+ # Messages keep plain words and mask every other token, so a value can't
23
+ # slip through a pattern nobody thought of: "Couldn't find User with
24
+ # 'id'=123" -> "Couldn't find User with ?=?". A plain word is letters
25
+ # (with _ and inner apostrophes or hyphens), plus sentence punctuation
26
+ # around it.
27
+ PLAIN_WORD = /\A[\p{L}_]+(?:['’-][\p{L}_]+)*\z/
28
+ LEADING = /\A[(\[{]*/
29
+ TRAILING = /[.,;:!?)\]}]*\z/
30
+ # Plain words can still be data when they're quoted or assigned, so those
31
+ # are masked whole first. A quote right after a letter is an apostrophe
32
+ # ("Couldn't"). One that never closes (or was cut off) masks to the end; a
33
+ # lone backslash at the end counts as part of it.
34
+ QUOTED = /(?<!\w)(?:"(?:[^"\\]|\\.?)*+(?:"|\z)|'(?:[^'\\]|\\.?)*+(?:'|\z)|`(?:[^`\\]|\\.?)*+(?:`|\z))/m
35
+ # Whatever follows "=": Postgres' "Key (email)=(jane smith)", "token = abc".
36
+ # A parenthesized value runs to the last ")" in the message (the value can
37
+ # hold one or span lines), or to the end.
38
+ ASSIGNED = /(?<==)[ \t]*(?:#{QUOTED}[^\s,;)\]}]*|\((?m:.*)\)|\((?m:.*)|[^\s,;)\]}]+)/
39
+ QUOTED_OR_ASSIGNED = /#{ASSIGNED}|#{QUOTED}/
40
+
41
+ # Param keys are usually identifiers. Anything else, or an identifier
42
+ # that's really an id or digest, may be data.
43
+ PARAM_KEY = /\A[A-Za-z_][\w\-.]{0,99}\z/
44
+ ID_KEY = /\A(?:\h{8}-\h{4}-\h{4}-\h{4}-\h{12}|(?:0x)?(?=\h*\d)(?=\h*[a-f])\h{8,})\z/i
45
+
46
+ module_function
47
+
48
+ def scrub_message(message)
49
+ text = UTF8.scrub(message.to_s)
50
+ text = "#{text.byteslice(0, MAX_MESSAGE_BYTES).scrub("")} ..." if text.bytesize > MAX_MESSAGE_BYTES
51
+
52
+ text.gsub(QUOTED_OR_ASSIGNED, MASK).gsub(/\S+/) do |token|
53
+ token.split(/(=)/).map { |part| part == "=" ? part : scrub_word(part) }.join
54
+ end
55
+ end
56
+
57
+ # A word with its punctuation: kept when plain or already masked.
58
+ def scrub_word(word)
59
+ lead = word[LEADING]
60
+ rest = word.delete_prefix(lead)
61
+ trail = rest[TRAILING]
62
+ core = rest.delete_suffix(trail)
63
+ return word if core.empty? || core == MASK || core.match?(PLAIN_WORD)
64
+
65
+ "#{lead}#{MASK}#{trail}"
66
+ end
67
+
68
+ # Up to MAX_FRAMES frames. Every app frame stays; when there are too many,
69
+ # gem frames are cut from the middle, keeping those nearest the top (where
70
+ # it raised) and the bottom (how it got there).
71
+ def trim_frames(frames, max = MAX_FRAMES)
72
+ return [frames, 0] if frames.size <= max
73
+
74
+ app_indexes = frames.each_index.select { |i| frames[i].app }
75
+ if app_indexes.size >= max
76
+ keep = app_indexes.first(max - max / 2) + app_indexes.last(max / 2)
77
+ else
78
+ other = frames.each_index.reject { |i| frames[i].app }
79
+ room = max - app_indexes.size
80
+ keep = app_indexes + other.first(room - room / 2) + other.last(room / 2)
81
+ end
82
+ kept = keep.uniq.sort.map { |i| frames[i] }
83
+ [kept, frames.size - kept.size]
84
+ end
85
+
86
+ # Flattens nested params into names only: {"user" => {"email" => "a"}}
87
+ # -> ["user[email]"].
88
+ def param_names(params, prefix = nil, depth = 0, names = [])
89
+ return names unless params.respond_to?(:each_pair)
90
+
91
+ params.each_pair do |key, value|
92
+ break if names.size >= MAX_PARAM_NAMES
93
+
94
+ key = key.to_s
95
+ key = MASK if !key.match?(PARAM_KEY) || key.match?(ID_KEY)
96
+ name = prefix ? "#{prefix}[#{key}]" : key
97
+ next if prefix.nil? && %w[controller action].include?(name)
98
+
99
+ if value.respond_to?(:each_pair) && depth < 3
100
+ param_names(value, name, depth + 1, names)
101
+ else
102
+ names << "#{name}#{"[]" if value.is_a?(Array)}".byteslice(0, MAX_NAME_BYTES)
103
+ end
104
+ end
105
+ names
106
+ end
107
+
108
+ def build(exception:, class_name:, fingerprint:, frames:, handled:, operation:, occurred_at:,
109
+ revision: nil, host: nil, hex_trace_id: nil, route: nil, params: [], source: nil)
110
+ sample = {
111
+ schema_version: 1,
112
+ fingerprint: fingerprint,
113
+ class: class_name,
114
+ message: scrub_message(exception.message),
115
+ handled: handled,
116
+ operation: operation,
117
+ route: route,
118
+ params: params,
119
+ occurred_at: occurred_at.utc.iso8601(3),
120
+ revision: revision,
121
+ host: host,
122
+ hex_trace_id: hex_trace_id,
123
+ source: source,
124
+ language: "ruby",
125
+ language_version: RUBY_VERSION,
126
+ sdk_version: Flare::VERSION,
127
+ frames: frames.select(&:app).map(&:normalized).uniq.first(ErrorFingerprint::FINGERPRINT_FRAMES * 4),
128
+ }
129
+ cause = exception.cause
130
+ sample[:cause] = { class: cause.class.name, message: scrub_message(cause.message) } if cause
131
+ fit(UTF8.scrub(sample), frames)
132
+ end
133
+
134
+ # The JSON for a sample, or nil when it can't be brought under MAX_BYTES.
135
+ # Shrinks the parts that can be big before giving up.
136
+ def fit(sample, frames)
137
+ json = with_backtrace(sample, frames, MAX_FRAMES)
138
+ return json if json.bytesize <= MAX_BYTES
139
+
140
+ sample = sample.except(:cause).merge(message: sample[:message].to_s.byteslice(0, 1_024).scrub(""))
141
+ json = with_backtrace(sample, frames, MAX_FRAMES)
142
+ return json if json.bytesize <= MAX_BYTES
143
+
144
+ [50, 10].each do |max|
145
+ json = with_backtrace(sample.merge(params: []), frames, max)
146
+ return json if json.bytesize <= MAX_BYTES
147
+ end
148
+ nil
149
+ end
150
+
151
+ def with_backtrace(sample, frames, max)
152
+ kept, omitted = trim_frames(frames, max)
153
+ JSON.generate(sample.merge(backtrace: UTF8.scrub(kept.map(&:to_h)), omitted_frames: omitted))
154
+ end
155
+
156
+ def gzip(json)
157
+ Zlib.gzip(json)
158
+ end
159
+ end
160
+ end
@@ -0,0 +1,441 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "logger"
5
+ require "set"
6
+ require "time"
7
+ require "concurrent/atomic/atomic_boolean"
8
+ require "concurrent/atomic/atomic_fixnum"
9
+ require "concurrent/executor/single_thread_executor"
10
+
11
+ require_relative "client_headers"
12
+ require_relative "error_fingerprint"
13
+ require_relative "error_sample"
14
+ require_relative "metric_key"
15
+ require_relative "metric_storage"
16
+ require_relative "metric_span_processor"
17
+
18
+ module Flare
19
+ # Counts errors by fingerprint and holds one sample of each new one.
20
+ #
21
+ # Errors come in three ways: the Rails error reporter (handled and
22
+ # unhandled), Flare.report, and failed web requests and jobs whose spans
23
+ # recorded an exception the reporter didn't see. Each exception object
24
+ # counts once, whichever way it arrives first.
25
+ #
26
+ # Counts go out with the metrics flush as namespace "error" rows; the
27
+ # MetricFlusher calls #record before it drains. Samples wait here until
28
+ # the next /api/rules poll asks for upload URLs (RuleManager sends the
29
+ # Flare-Error-Samples header), then upload in the background.
30
+ #
31
+ # Inert until /api/rules says error_tracking: true: nothing is counted,
32
+ # held, asked for or sent while the gate is off.
33
+ class ErrorTracker
34
+ NAMESPACE = "error"
35
+ SAMPLES_HEADER = "Flare-Error-Samples"
36
+ MAX_FINGERPRINTS_PER_FLUSH = 100
37
+ # Fingerprints past the per-flush cap count here.
38
+ OVERFLOW_FINGERPRINT = "ffffffffffffffff"
39
+ OVERFLOW_SERVICE = "overflow"
40
+ MAX_SERVICE_LENGTH = 100
41
+ MAX_OPERATION_LENGTH = 100
42
+ MAX_WAITING_SAMPLES = 20
43
+ MAX_REQUESTED_SAMPLES = 10
44
+ MAX_SEEN_FINGERPRINTS = 10_000
45
+ # Distinct rows held between flushes; new ones past this count as overflow.
46
+ MAX_KEYS = 1_000
47
+ FINGERPRINT_PATTERN = /\A[0-9a-f]{16}\z/
48
+ # Rails reports cache store errors it already rescued and fell back from.
49
+ SKIP_SOURCES = /_cache_store\.active_support\z/
50
+ WRAPPER_CLASSES = %w[ActionView::Template::Error].freeze
51
+ SPAN_EXCEPTION_KEY = :__flare_span_exception
52
+
53
+ class << self
54
+ # The process's tracker, set by Flare.setup_error_tracker. Read by
55
+ # SpanExceptionCapture and Flare.report.
56
+ attr_accessor :current
57
+ end
58
+
59
+ attr_reader :refused_count, :upload_count
60
+
61
+ def initialize(configuration: Flare.configuration, uploader: nil, executor: nil,
62
+ clock: Time, logger: nil)
63
+ @configuration = configuration
64
+ @uploader = uploader
65
+ @executor_override = executor
66
+ @clock = clock
67
+ @logger = logger || Logger.new($stderr, level: Logger::WARN)
68
+ @enabled = Concurrent::AtomicBoolean.new(false)
69
+ @refused_count = Concurrent::AtomicFixnum.new(0)
70
+ @upload_count = Concurrent::AtomicFixnum.new(0)
71
+ reset_state
72
+ end
73
+
74
+ def enabled?
75
+ @enabled.true?
76
+ end
77
+
78
+ # Set from each /api/rules response. Turning off drops whatever is
79
+ # waiting so nothing is sent until it's back on.
80
+ def enabled=(value)
81
+ if value
82
+ @enabled.make_true
83
+ elsif @enabled.make_false
84
+ @counts.drain
85
+ @mutex.synchronize { @waiting.clear }
86
+ end
87
+ end
88
+
89
+ # Records one occurrence. Returns true when it counted, false when the
90
+ # gate is off, the error is ignored, or this exception already counted.
91
+ # Never raises into the app.
92
+ def report(exception, handled:, context: nil, source: nil, span: nil, operation: nil)
93
+ return false unless enabled? && exception.is_a?(Exception)
94
+ return false if source && SKIP_SOURCES.match?(source.to_s)
95
+
96
+ detect_forking
97
+ error = unwrap(exception)
98
+ return false if ignored?(error)
99
+ return false unless claim(exception, error)
100
+
101
+ record_occurrence(error, handled: handled, context: context || {}, source: source, span: span, operation: operation)
102
+ true
103
+ rescue StandardError => e
104
+ warn_once(e)
105
+ false
106
+ end
107
+
108
+ # Called by MetricSpanProcessor for every web request and job span.
109
+ # A failed one counts when its exception is known and wasn't reported.
110
+ def entry_span_finished(span, operation:, error:)
111
+ exception = span_exception(span) if error && enabled?
112
+ Thread.current[SPAN_EXCEPTION_KEY] = nil if Thread.current[SPAN_EXCEPTION_KEY]
113
+ report(exception, handled: false, span: span, operation: operation) if exception
114
+ end
115
+
116
+ # From SpanExceptionCapture: the exception object behind a span's
117
+ # exception event, so spans and the reporter can dedupe on it.
118
+ def remember_span_exception(span, exception)
119
+ return unless enabled?
120
+
121
+ span.instance_variable_set(:@flare_exception, exception)
122
+ Thread.current[SPAN_EXCEPTION_KEY] = [span.context.trace_id, exception]
123
+ rescue StandardError
124
+ nil
125
+ end
126
+
127
+ # MetricFlusher hook, called before each drain: moves this flush's error
128
+ # counts into the metric storage, at most MAX_FINGERPRINTS_PER_FLUSH
129
+ # fingerprints, the rest under OVERFLOW_FINGERPRINT.
130
+ def record(storage, **)
131
+ detect_forking
132
+ drained = @counts.drain
133
+ return if drained.empty? || !enabled?
134
+
135
+ totals = Hash.new(0)
136
+ drained.each { |key, values| totals[key.target] += values[:count] unless key.target == OVERFLOW_FINGERPRINT }
137
+ kept = totals.size > MAX_FINGERPRINTS_PER_FLUSH ? totals.max_by(MAX_FINGERPRINTS_PER_FLUSH, &:last).to_set(&:first) : nil
138
+
139
+ drained.each do |key, values|
140
+ key = overflow_key(key) if kept && !kept.include?(key.target)
141
+ storage.add(key, count: values[:count], sum_ms: 0, error_count: values[:error_count])
142
+ end
143
+ end
144
+
145
+ # Fingerprints to ask upload URLs for on this poll (sent as
146
+ # Flare-Error-Samples). Empty when nothing waits, so the poll keeps its
147
+ # ETag / 304 behavior.
148
+ def sample_request
149
+ return [] unless enabled?
150
+
151
+ detect_forking
152
+ @mutex.synchronize { @waiting.select { |_, sample| sample }.keys.first(MAX_REQUESTED_SAMPLES) }
153
+ end
154
+
155
+ # Applies a 200 /api/rules response. `requested` is what this poll asked
156
+ # for; any of those without an entry in error_uploads was refused, and
157
+ # its sample is dropped (the fingerprint stays seen, so it isn't asked
158
+ # for again until the process restarts).
159
+ def apply_rules(payload, requested: [])
160
+ self.enabled = payload["error_tracking"] == true
161
+ return unless enabled?
162
+
163
+ granted = {}
164
+ Array(payload["error_uploads"]).each do |raw|
165
+ entry = upload_entry(raw)
166
+ granted[entry[:fingerprint]] ||= entry if entry
167
+ end
168
+
169
+ uploads = @mutex.synchronize do
170
+ requested.filter_map do |fingerprint|
171
+ sample = @waiting.delete(fingerprint)
172
+ next unless sample
173
+
174
+ if granted[fingerprint]
175
+ [sample, granted[fingerprint]]
176
+ else
177
+ @refused_count.increment
178
+ nil
179
+ end
180
+ end
181
+ end
182
+ uploads.each { |sample, entry| upload(sample, entry) }
183
+ end
184
+
185
+ def waiting_count
186
+ @mutex.synchronize { @waiting.count { |_, sample| sample } }
187
+ end
188
+
189
+ def after_fork
190
+ return if @pid == $$
191
+
192
+ reset_state
193
+ end
194
+
195
+ private
196
+
197
+ def reset_state
198
+ @pid = $$
199
+ @counts = MetricStorage.new
200
+ @mutex = Mutex.new
201
+ @claimed = ObjectSpace::WeakMap.new
202
+ @waiting = {}
203
+ @seen = Set.new
204
+ @executor = nil
205
+ end
206
+
207
+ def detect_forking
208
+ after_fork if @pid != $$
209
+ end
210
+
211
+ def record_occurrence(error, handled:, context:, source:, span:, operation:)
212
+ now = @clock.now
213
+ frames = ErrorFingerprint.frames(error)
214
+ class_name = error.class.name || ErrorFingerprint.normalize_class(error.class.to_s)
215
+ fingerprint = ErrorFingerprint.fingerprint(class_name, frames)
216
+ span ||= current_span
217
+ operation = (operation || operation_for(context, span)).to_s.dup.force_encoding(Encoding::UTF_8).scrub("?")[0, MAX_OPERATION_LENGTH]
218
+ bucket = now.utc
219
+
220
+ key = MetricKey.new(
221
+ bucket: Time.utc(bucket.year, bucket.month, bucket.day, bucket.hour, bucket.min, 0),
222
+ namespace: NAMESPACE,
223
+ service: class_name[0, MAX_SERVICE_LENGTH],
224
+ target: fingerprint,
225
+ operation: operation
226
+ )
227
+ key = overflow_key(key, operation: OVERFLOW_SERVICE) if @counts.size >= MAX_KEYS && !@counts[key]
228
+ @counts.increment(key, duration_ms: 0, error: !handled)
229
+
230
+ trace_id = hex_trace_id(span)
231
+ revision = @configuration.revision
232
+ meta = { fingerprint: fingerprint, occurred_at: now.utc.iso8601(3), revision: revision, hex_trace_id: trace_id }
233
+ controller = context[:controller]
234
+ hold_sample(fingerprint, meta) do
235
+ ErrorSample.build(
236
+ exception: error,
237
+ class_name: class_name,
238
+ fingerprint: fingerprint,
239
+ frames: frames,
240
+ handled: handled ? true : false,
241
+ operation: operation,
242
+ occurred_at: now,
243
+ revision: revision,
244
+ host: ClientHeaders.hostname,
245
+ hex_trace_id: trace_id,
246
+ route: route_for(controller, span),
247
+ params: param_names_for(controller, context),
248
+ source: source&.to_s
249
+ )
250
+ end
251
+ end
252
+
253
+ # One sample per fingerprint per process, at most MAX_WAITING_SAMPLES
254
+ # waiting. The slot is taken before the (slower) build so concurrent
255
+ # errors can't overfill it.
256
+ def hold_sample(fingerprint, meta)
257
+ @mutex.synchronize do
258
+ return if @seen.include?(fingerprint) || @waiting.size >= MAX_WAITING_SAMPLES || @seen.size >= MAX_SEEN_FINGERPRINTS
259
+
260
+ @seen << fingerprint
261
+ @waiting[fingerprint] = nil
262
+ end
263
+
264
+ json = yield
265
+ @mutex.synchronize do
266
+ if json && enabled?
267
+ @waiting[fingerprint] = meta.merge(json: json)
268
+ else
269
+ @waiting.delete(fingerprint)
270
+ end
271
+ end
272
+ rescue StandardError
273
+ @mutex.synchronize { @waiting.delete(fingerprint) unless @waiting[fingerprint] }
274
+ raise
275
+ end
276
+
277
+ def upload(sample, entry)
278
+ return unless @uploader
279
+
280
+ executor.post do
281
+ next unless enabled?
282
+
283
+ @upload_count.increment if @uploader.upload(sample, entry)
284
+ rescue StandardError => e
285
+ @logger.warn("[Flare::ErrorTracker] upload raised: #{e.class}: #{e.message}")
286
+ end
287
+ end
288
+
289
+ def executor
290
+ @executor_override || @executor ||= Concurrent::SingleThreadExecutor.new(
291
+ max_queue: MAX_REQUESTED_SAMPLES * 2,
292
+ fallback_policy: :discard
293
+ )
294
+ end
295
+
296
+ def upload_entry(raw)
297
+ return nil unless raw.is_a?(Hash)
298
+
299
+ entry = raw.transform_keys(&:to_s).slice("fingerprint", "upload_id", "key", "put_url", "expires_at")
300
+ return nil unless entry["fingerprint"].to_s.match?(FINGERPRINT_PATTERN)
301
+ return nil if entry["upload_id"].to_s.empty? || entry["key"].to_s.empty? || entry["put_url"].to_s.empty?
302
+
303
+ entry.transform_keys(&:to_sym)
304
+ end
305
+
306
+ def overflow_key(key, operation: key.operation)
307
+ MetricKey.new(bucket: key.bucket, namespace: NAMESPACE, service: OVERFLOW_SERVICE,
308
+ target: OVERFLOW_FINGERPRINT, operation: operation)
309
+ end
310
+
311
+ # Marks the exception (and what it wraps) as counted. False when it
312
+ # already was.
313
+ def claim(exception, error)
314
+ @mutex.synchronize do
315
+ return false if @claimed.key?(exception) || @claimed.key?(error)
316
+
317
+ @claimed[exception] = true
318
+ @claimed[error] = true
319
+ end
320
+ true
321
+ end
322
+
323
+ # ActionView::Template::Error wraps the error the view raised.
324
+ def unwrap(exception)
325
+ if WRAPPER_CLASSES.include?(exception.class.name) && exception.cause
326
+ exception.cause
327
+ else
328
+ exception
329
+ end
330
+ end
331
+
332
+ def ignored?(error)
333
+ ignored = Array(@configuration.ignore_errors)
334
+ return false if ignored.empty?
335
+
336
+ error.class.ancestors.any? { |ancestor| ignored.include?(ancestor.name) }
337
+ end
338
+
339
+ # The span's own exception, or for a job whose retry recorded it on a
340
+ # child span, the one this thread recorded last in the same trace when
341
+ # the span names its class. That fallback only holds the latest one per
342
+ # thread, which covers ActiveJob retries (same thread, child ends first).
343
+ def span_exception(span)
344
+ own = span.instance_variable_get(:@flare_exception)
345
+ return own if own
346
+
347
+ trace_id, exception = Thread.current[SPAN_EXCEPTION_KEY]
348
+ return nil unless exception && trace_id == span.context.trace_id
349
+
350
+ exception if MetricSpanProcessor.exception_type(span) == exception.class.name
351
+ end
352
+
353
+ def operation_for(context, span)
354
+ controller = context[:controller]
355
+ if controller.respond_to?(:action_name) && controller.action_name
356
+ "#{controller.class.name}##{controller.action_name}"
357
+ elsif context[:job]
358
+ context[:job].class.name
359
+ elsif context[:operation]
360
+ context[:operation]
361
+ else
362
+ span_operation(span) || "unknown"
363
+ end
364
+ end
365
+
366
+ def span_operation(span)
367
+ attributes = span_attributes(span)
368
+ return nil unless attributes
369
+
370
+ transaction = attributes[Flare::TRANSACTION_NAME_ATTRIBUTE] if defined?(Flare::TRANSACTION_NAME_ATTRIBUTE)
371
+ return transaction if transaction
372
+
373
+ namespace = attributes["code.namespace"]
374
+ function = attributes["code.function"]
375
+ namespace && (function ? "#{namespace}##{function}" : namespace)
376
+ end
377
+
378
+ def route_for(controller, span)
379
+ route = span_attributes(span)&.[]("http.route")
380
+ return route.to_s if route
381
+
382
+ request = controller.request if controller.respond_to?(:request)
383
+ request.route_uri_pattern if request.respond_to?(:route_uri_pattern)
384
+ rescue StandardError
385
+ nil
386
+ end
387
+
388
+ def param_names_for(controller, context)
389
+ params = context[:params]
390
+ if params.nil? && controller.respond_to?(:request)
391
+ params = controller.request.parameters
392
+ end
393
+ params = params.to_unsafe_h if params.respond_to?(:to_unsafe_h)
394
+ ErrorSample.param_names(params)
395
+ rescue StandardError
396
+ []
397
+ end
398
+
399
+ def span_attributes(span)
400
+ span.attributes if span.respond_to?(:attributes)
401
+ end
402
+
403
+ def current_span
404
+ OpenTelemetry::Trace.current_span if defined?(OpenTelemetry::Trace)
405
+ end
406
+
407
+ def hex_trace_id(span)
408
+ context = span&.context
409
+ context.hex_trace_id if context.respond_to?(:valid?) && context.valid?
410
+ end
411
+
412
+ def warn_once(error)
413
+ return if @warned_pid == $$
414
+
415
+ @warned_pid = $$
416
+ @logger.warn("[Flare::ErrorTracker] report failed: #{error.class}: #{error.message}")
417
+ end
418
+
419
+ # Rails.error subscriber. Rails 7.0 passes handled/severity/context;
420
+ # 7.1+ adds source.
421
+ class ReporterSubscriber
422
+ def initialize(tracker)
423
+ @tracker = tracker
424
+ end
425
+
426
+ def report(error, handled:, severity: nil, context: {}, source: nil, **)
427
+ @tracker.report(error, handled: handled, context: context, source: source)
428
+ nil
429
+ end
430
+ end
431
+
432
+ # Prepended to the OTel SDK span so the exception object behind an
433
+ # exception event is known when the span finishes.
434
+ module SpanExceptionCapture
435
+ def record_exception(exception, attributes: nil)
436
+ ErrorTracker.current&.remember_span_exception(self, exception)
437
+ super
438
+ end
439
+ end
440
+ end
441
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "logger"
5
+ require "concurrent/atomic/atomic_fixnum"
6
+
7
+ require_relative "client_headers"
8
+ require_relative "error_sample"
9
+ require_relative "http_transport"
10
+ require_relative "trace_exporter"
11
+
12
+ module Flare
13
+ # Uploads one error sample the way TraceExporter uploads a trace: PUT the
14
+ # gzipped JSON to the presigned R2 URL from /api/rules, then
15
+ # POST /api/errors so ingest picks it up.
16
+ #
17
+ # A failed PUT drops the sample (the URL was its quota). A failed notify
18
+ # leaves the blob in incoming/, which expires after an hour.
19
+ class ErrorUploader
20
+ PUT_HEADERS = TraceExporter::PUT_HEADERS
21
+
22
+ attr_reader :put_failure_count
23
+
24
+ def initialize(notify_url:, api_key:, project:, environment:, transport: nil, logger: nil)
25
+ @notify_url = notify_url.to_s
26
+ @api_key = api_key
27
+ @project = project
28
+ @environment = environment
29
+ @transport = transport || HttpTransport.new
30
+ @logger = logger || Logger.new($stderr, level: Logger::WARN)
31
+ @put_failure_count = Concurrent::AtomicFixnum.new(0)
32
+ end
33
+
34
+ # sample: { fingerprint:, json:, occurred_at:, revision:, hex_trace_id: }
35
+ # entry: { fingerprint:, upload_id:, key:, put_url:, expires_at: }
36
+ # True once the sample is in R2 and ingest was told.
37
+ def upload(sample, entry)
38
+ response = @transport.put(entry[:put_url], ErrorSample.gzip(sample[:json]), PUT_HEADERS)
39
+ return failed("PUT failed: HTTP #{response.code}", @put_failure_count) unless %w[200 204].include?(response.code)
40
+
41
+ notify(sample, entry)
42
+ rescue StandardError => e
43
+ failed("upload raised: #{e.class}: #{e.message}", @put_failure_count)
44
+ end
45
+
46
+ private
47
+
48
+ def notify(sample, entry)
49
+ body = JSON.generate(
50
+ upload_id: entry[:upload_id],
51
+ fingerprint: sample[:fingerprint],
52
+ key: entry[:key],
53
+ occurred_at: sample[:occurred_at],
54
+ revision: sample[:revision],
55
+ hex_trace_id: sample[:hex_trace_id]
56
+ )
57
+ response = @transport.post(@notify_url, body, notify_headers)
58
+ response.code.start_with?("2") || failed("notify failed: HTTP #{response.code}")
59
+ rescue StandardError => e
60
+ failed("notify raised: #{e.class}: #{e.message}")
61
+ end
62
+
63
+ def failed(message, counter = nil)
64
+ counter&.increment
65
+ @logger.warn("[Flare::ErrorUploader] #{message}")
66
+ false
67
+ end
68
+
69
+ # Same identity as the trace notify. Never sent on the R2 PUT, where they
70
+ # could break the signed-header set.
71
+ def notify_headers
72
+ ClientHeaders.to_h.merge(
73
+ "Content-Type" => "application/json",
74
+ "Authorization" => "Bearer #{@api_key}",
75
+ "Flare-Project" => @project,
76
+ "Flare-Environment" => @environment
77
+ )
78
+ end
79
+ end
80
+ end
@@ -268,10 +268,14 @@ module Flare
268
268
  defined?(MetricSubmitter::DeadlineExceeded) && error.is_a?(MetricSubmitter::DeadlineExceeded)
269
269
  end
270
270
 
271
+ # Each reporter (trace health, error counts) on its own, so one raising
272
+ # can't skip the others.
271
273
  def record_health_metrics
272
- @health_reporters.each { |reporter| reporter.record(@storage) }
273
- rescue => e
274
- warn "[Flare] Health metric recording error: #{e.message}"
274
+ @health_reporters.each do |reporter|
275
+ reporter.record(@storage)
276
+ rescue => e
277
+ warn "[Flare] Health metric recording error: #{e.message}"
278
+ end
275
279
  end
276
280
 
277
281
  def log(message)
@@ -48,8 +48,9 @@ module Flare
48
48
  }.freeze
49
49
  READ_TABLE = /\bFROM\s+[`"]?(\w+)[`"]?/i
50
50
 
51
- def initialize(storage:, http_metrics_config: nil, ignore_errors: nil, slo_manager: nil)
51
+ def initialize(storage:, http_metrics_config: nil, ignore_errors: nil, slo_manager: nil, error_tracker: nil)
52
52
  @storage = storage
53
+ @error_tracker = error_tracker
53
54
  @http_metrics_config = http_metrics_config || HttpMetricsConfig::DEFAULT
54
55
  @ignore_errors = ignore_errors || []
55
56
  @slo_manager = slo_manager || SloManager.new
@@ -172,6 +173,7 @@ module Flare
172
173
 
173
174
  duration = duration_ms(span)
174
175
  @storage.increment(key, duration_ms: duration, error: error, slow: slow?(key, duration, error))
176
+ @error_tracker&.entry_span_finished(span, operation: key.target, error: error)
175
177
  end
176
178
 
177
179
  # [metric key, error?] for a web request or job span, nil for anything
@@ -353,12 +355,16 @@ module Flare
353
355
  type.nil? || !ignored_exception_type?(type)
354
356
  end
355
357
 
358
+ def exception_type(span)
359
+ self.class.exception_type(span)
360
+ end
361
+
356
362
  # A job's retried exception is recorded on its enqueue_retry child span,
357
363
  # so the process span only names it in the status description.
358
- def exception_type(span)
364
+ def self.exception_type(span)
359
365
  event = span.events&.reverse_each&.find { |e| e.name == "exception" }
360
366
  event&.attributes&.[]("exception.type") ||
361
- span.status.description.to_s[ACTIVE_JOB_ERROR_STATUS, 1]
367
+ span.status&.description.to_s[ACTIVE_JOB_ERROR_STATUS, 1]
362
368
  end
363
369
 
364
370
  # Subclasses of an ignored class match when the class is loaded.
@@ -7,6 +7,7 @@ require "concurrent/atomic/atomic_fixnum"
7
7
 
8
8
  require_relative "client_headers"
9
9
  require_relative "http_transport"
10
+ require_relative "error_tracker"
10
11
 
11
12
  module Flare
12
13
  # The SDK's only poll. Every interval seconds (default 30) it does a
@@ -30,11 +31,13 @@ module Flare
30
31
  attr_reader :poll_count, :etag, :stopped_due_to_auth, :last_error_count
31
32
 
32
33
  def initialize(sampler:, marker:, pool:, base_url:, api_key:, project:, environment:,
33
- slo_manager: nil, interval: DEFAULT_INTERVAL, transport: nil, logger: nil)
34
+ slo_manager: nil, error_tracker: nil, interval: DEFAULT_INTERVAL, transport: nil, logger: nil)
34
35
  @sampler = sampler
35
36
  @marker = marker
36
37
  @pool = pool
37
38
  @slo_manager = slo_manager
39
+ @error_tracker = error_tracker
40
+ @requested_samples = []
38
41
  @rules_url = "#{base_url.to_s.chomp('/')}/api/rules"
39
42
  @api_key = api_key
40
43
  @project = project
@@ -126,12 +129,18 @@ module Flare
126
129
  "Flare-Environment" => @environment
127
130
  )
128
131
  headers["If-None-Match"] = @etag if @etag
132
+ # Asks for upload URLs for waiting error samples. Left off when none
133
+ # wait, so an unchanged poll still gets a 304.
134
+ @requested_samples = @error_tracker ? @error_tracker.sample_request : []
135
+ headers[ErrorTracker::SAMPLES_HEADER] = @requested_samples.join(",") unless @requested_samples.empty?
129
136
  headers
130
137
  end
131
138
 
132
139
  # Server payload shape (see tirana-v2 Api::RulesController):
133
140
  # { "trace_rules": [{ "id", "match_attributes", "rate", ..., "urls": [...] }],
134
- # "slo_rules": [{ "namespace", "service"?, "target"?, "threshold_ms" }] }
141
+ # "slo_rules": [{ "namespace", "service"?, "target"?, "threshold_ms" }],
142
+ # "error_tracking": true,
143
+ # "error_uploads": [{ "fingerprint", "upload_id", "key", "put_url", "expires_at" }] }
135
144
  # The `slo_rules` key is optional; the rules poll is authoritative, so an
136
145
  # absent array clears any prior SLO config (update treats nil as empty).
137
146
  def apply(payload)
@@ -142,6 +151,8 @@ module Flare
142
151
  @pool.replace(url_entries)
143
152
 
144
153
  @slo_manager&.update(payload["slo_rules"])
154
+ # Error tracking is off unless this response says otherwise.
155
+ @error_tracker&.apply_rules(payload, requested: @requested_samples)
145
156
  end
146
157
  end
147
158
  end
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.7.1"
4
+ VERSION = "0.8.0"
5
5
  end
data/lib/flare.rb CHANGED
@@ -26,6 +26,8 @@ require_relative "flare/upload_url_pool"
26
26
  require_relative "flare/trace_exporter"
27
27
  require_relative "flare/rule_manager"
28
28
  require_relative "flare/trace_health_reporter"
29
+ require_relative "flare/error_tracker"
30
+ require_relative "flare/error_uploader"
29
31
 
30
32
  module Flare
31
33
  class Error < StandardError; end
@@ -142,6 +144,20 @@ module Flare
142
144
  end
143
145
 
144
146
  def trace_span_processor = @trace_span_processor
147
+ def error_tracker = ErrorTracker.current
148
+
149
+ # Report an error you rescued, outside Rails or wherever Rails.error isn't
150
+ # used. Same idea as Rails.error.report: counted as handled.
151
+ #
152
+ # rescue => e
153
+ # Flare.report(e, context: { operation: "ImportFeeds#run" })
154
+ #
155
+ # Does nothing until Flare's server turns error tracking on for the
156
+ # environment. Never raises.
157
+ def report(exception, context: {})
158
+ ErrorTracker.current&.report(exception, handled: true, context: context)
159
+ nil
160
+ end
145
161
  def trace_health_reporter = @trace_health_reporter
146
162
 
147
163
  # Manually flush metrics (useful for testing or forced flushes).
@@ -173,6 +189,7 @@ module Flare
173
189
  def after_fork
174
190
  @metric_flusher&.after_fork
175
191
  @rule_manager&.after_fork
192
+ ErrorTracker.current&.after_fork
176
193
  end
177
194
 
178
195
  # Configure OpenTelemetry SDK and instrumentations. Must run before the
@@ -270,11 +287,14 @@ module Flare
270
287
  setup_tracing_components
271
288
  return unless @sampler && @marker && @upload_url_pool
272
289
 
290
+ setup_error_tracker
291
+
273
292
  @rule_manager = RuleManager.new(
274
293
  sampler: @sampler,
275
294
  marker: @marker,
276
295
  pool: @upload_url_pool,
277
296
  slo_manager: slo_manager,
297
+ error_tracker: error_tracker,
278
298
  base_url: configuration.url,
279
299
  api_key: configuration.key,
280
300
  project: service_name_for_app,
@@ -343,15 +363,48 @@ module Flare
343
363
  log "Tracing enabled (poll=#{configuration.tracing_poll_interval}s)"
344
364
  end
345
365
 
366
+ # Error tracking needs the rules poll (its on/off switch and upload URLs)
367
+ # and the metrics flush (its counts), so it exists only when both run. It
368
+ # stays off until /api/rules says error_tracking: true.
369
+ # Built from start_rule_manager, which the engine runs before
370
+ # start_metrics_flusher picks it up.
371
+ def setup_error_tracker
372
+ return if ErrorTracker.current || !configuration.metrics_enabled
373
+
374
+ ErrorTracker.current = ErrorTracker.new(
375
+ uploader: ErrorUploader.new(
376
+ notify_url: "#{configuration.url.to_s.chomp('/')}/api/errors",
377
+ api_key: configuration.key,
378
+ project: service_name_for_app,
379
+ environment: rails_env_name
380
+ )
381
+ )
382
+ unless OpenTelemetry::SDK::Trace::Span < ErrorTracker::SpanExceptionCapture
383
+ OpenTelemetry::SDK::Trace::Span.prepend(ErrorTracker::SpanExceptionCapture)
384
+ end
385
+ end
386
+
387
+ # Counts errors Rails reports: Rails.error.report/handle/record calls and
388
+ # the unhandled errors Rails reports from requests and jobs. Called after
389
+ # initializers so the tracker exists.
390
+ def subscribe_to_error_reporter
391
+ return if @error_subscriber || error_tracker.nil?
392
+ return unless defined?(Rails) && Rails.respond_to?(:error) && Rails.error.respond_to?(:subscribe)
393
+
394
+ @error_subscriber = ErrorTracker::ReporterSubscriber.new(error_tracker)
395
+ Rails.error.subscribe(@error_subscriber)
396
+ end
397
+
346
398
  # Metrics and the failures-only trace check both judge spans with these
347
399
  # settings, so a trace is kept exactly when its request counts as failing.
348
400
  # The trace check passes nil storage: it only calls slo_failure.
349
- def metric_span_processor(storage)
401
+ def metric_span_processor(storage, error_tracker: nil)
350
402
  MetricSpanProcessor.new(
351
403
  storage: storage,
352
404
  http_metrics_config: configuration.http_metrics_config,
353
405
  ignore_errors: configuration.ignore_errors,
354
- slo_manager: slo_manager
406
+ slo_manager: slo_manager,
407
+ error_tracker: error_tracker
355
408
  )
356
409
  end
357
410
 
@@ -361,7 +414,7 @@ module Flare
361
414
  return unless configuration.metrics_enabled
362
415
 
363
416
  @metric_storage ||= MetricStorage.new
364
- OpenTelemetry.tracer_provider.add_span_processor(metric_span_processor(@metric_storage))
417
+ OpenTelemetry.tracer_provider.add_span_processor(metric_span_processor(@metric_storage, error_tracker: error_tracker))
365
418
 
366
419
  log "Metrics enabled (endpoint=#{configuration.url} key=#{configuration.key ? 'present' : 'missing'})"
367
420
 
@@ -374,7 +427,7 @@ module Flare
374
427
  storage: @metric_storage,
375
428
  submitter: submitter,
376
429
  interval: configuration.metrics_flush_interval,
377
- health_reporters: @trace_health_reporter ? [@trace_health_reporter] : []
430
+ health_reporters: [@trace_health_reporter, error_tracker].compact
378
431
  )
379
432
  @metric_flusher.start
380
433
  log "Metrics flusher started (interval=#{configuration.metrics_flush_interval}s)"
@@ -570,6 +623,8 @@ module Flare
570
623
  @metric_flusher = nil
571
624
  @metric_storage = nil
572
625
  @slo_manager = nil
626
+ ErrorTracker.current = nil
627
+ @error_subscriber = nil
573
628
  @otel_configured = false
574
629
  end
575
630
  end
metadata CHANGED
@@ -1,13 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: flare
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.1
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - John Nunemaker
8
+ autorequire:
8
9
  bindir: exe
9
10
  cert_chain: []
10
- date: 1980-01-02 00:00:00.000000000 Z
11
+ date: 2026-11-26 00:00:00.000000000 Z
11
12
  dependencies:
12
13
  - !ruby/object:Gem::Dependency
13
14
  name: railties
@@ -206,6 +207,10 @@ files:
206
207
  - lib/flare/configuration.rb
207
208
  - lib/flare/deadline.rb
208
209
  - lib/flare/engine.rb
210
+ - lib/flare/error_fingerprint.rb
211
+ - lib/flare/error_sample.rb
212
+ - lib/flare/error_tracker.rb
213
+ - lib/flare/error_uploader.rb
209
214
  - lib/flare/export_filter.rb
210
215
  - lib/flare/filtering_span_processor.rb
211
216
  - lib/flare/http_metrics_config.rb
@@ -250,6 +255,7 @@ metadata:
250
255
  changelog_uri: https://github.com/verygoodsoftwarellc/flare-gem/releases
251
256
  bug_tracker_uri: https://github.com/verygoodsoftwarellc/flare-gem/issues
252
257
  documentation_uri: https://github.com/verygoodsoftwarellc/flare-gem#readme
258
+ post_install_message:
253
259
  rdoc_options: []
254
260
  require_paths:
255
261
  - lib
@@ -264,7 +270,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
264
270
  - !ruby/object:Gem::Version
265
271
  version: '0'
266
272
  requirements: []
267
- rubygems_version: 4.0.18
273
+ rubygems_version: 3.5.22
274
+ signing_key:
268
275
  specification_version: 4
269
276
  summary: Light up what's slowing you down
270
277
  test_files: []