sentry-ruby 7.1.0 → 7.3.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.
Files changed (53) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +2 -0
  3. data/gemfiles/ruby-2.7_rack-2_redis-4.gemfile.lock +28 -16
  4. data/gemfiles/ruby-2.7_rack-3.1_redis-4.gemfile.lock +28 -16
  5. data/gemfiles/ruby-2.7_rack-3_redis-4.gemfile.lock +28 -16
  6. data/gemfiles/ruby-3.0_rack-2_redis-4.gemfile.lock +38 -22
  7. data/gemfiles/ruby-3.0_rack-3.1_redis-4.gemfile.lock +38 -22
  8. data/gemfiles/ruby-3.0_rack-3_redis-4.gemfile.lock +38 -22
  9. data/gemfiles/ruby-3.1_rack-2_redis-4.gemfile.lock +66 -43
  10. data/gemfiles/ruby-3.1_rack-3.1_redis-4.gemfile.lock +66 -43
  11. data/gemfiles/ruby-3.1_rack-3_redis-4.gemfile.lock +66 -43
  12. data/gemfiles/ruby-3.2_rack-0_redis-5.gemfile.lock +68 -45
  13. data/gemfiles/ruby-3.2_rack-2_redis-4.gemfile.lock +68 -45
  14. data/gemfiles/ruby-3.2_rack-2_redis-5.gemfile.lock +70 -47
  15. data/gemfiles/ruby-3.2_rack-3.1_redis-4.gemfile.lock +68 -45
  16. data/gemfiles/ruby-3.2_rack-3_redis-4.gemfile.lock +68 -45
  17. data/gemfiles/ruby-3.2_rack-3_redis-5.gemfile.lock +70 -47
  18. data/gemfiles/ruby-3.3_rack-2_redis-4.gemfile.lock +72 -50
  19. data/gemfiles/ruby-3.3_rack-3.1_redis-4.gemfile.lock +72 -50
  20. data/gemfiles/ruby-3.3_rack-3.1_redis-5.3.gemfile.lock +74 -52
  21. data/gemfiles/ruby-3.3_rack-3_redis-4.gemfile.lock +72 -50
  22. data/gemfiles/ruby-3.4_rack-2_redis-4.gemfile.lock +72 -50
  23. data/gemfiles/ruby-3.4_rack-3.1_redis-4.gemfile.lock +72 -50
  24. data/gemfiles/ruby-3.4_rack-3.1_redis-5.3.gemfile.lock +74 -52
  25. data/gemfiles/ruby-3.4_rack-3_redis-4.gemfile.lock +72 -50
  26. data/gemfiles/ruby-4.0_rack-2_redis-4.gemfile.lock +72 -50
  27. data/gemfiles/ruby-4.0_rack-3.1_redis-4.gemfile.lock +72 -50
  28. data/gemfiles/ruby-4.0_rack-3_redis-4.gemfile.lock +72 -50
  29. data/gemfiles/ruby-jruby-9.4.14.0_rack-2_redis-4.gemfile.lock +75 -57
  30. data/gemfiles/ruby-jruby-9.4.14.0_rack-3.1_redis-4.gemfile.lock +75 -57
  31. data/gemfiles/ruby-jruby-9.4.14.0_rack-3_redis-4.gemfile.lock +75 -57
  32. data/lib/sentry/configuration.rb +9 -28
  33. data/lib/sentry/cron/fugit_schedule.rb +117 -0
  34. data/lib/sentry/cron/monitor_check_ins.rb +33 -27
  35. data/lib/sentry/cron/slug.rb +18 -0
  36. data/lib/sentry/data_collection.rb +6 -1
  37. data/lib/sentry/debug_structured_logger.rb +18 -21
  38. data/lib/sentry/job_extensions/extension.rb +348 -0
  39. data/lib/sentry/propagation_context.rb +2 -0
  40. data/lib/sentry/redis.rb +7 -1
  41. data/lib/sentry/rufus_scheduler.rb +125 -0
  42. data/lib/sentry/scope.rb +39 -1
  43. data/lib/sentry/session_flusher.rb +5 -2
  44. data/lib/sentry/span.rb +25 -2
  45. data/lib/sentry/structured_logger.rb +16 -13
  46. data/lib/sentry/transport/debug_transport.rb +75 -15
  47. data/lib/sentry/transport/dummy_transport.rb +7 -4
  48. data/lib/sentry/transport/spotlight_transport.rb +2 -2
  49. data/lib/sentry/utils/latency.rb +18 -0
  50. data/lib/sentry/utils/ring_buffer.rb +38 -0
  51. data/lib/sentry/version.rb +1 -1
  52. data/lib/sentry-ruby.rb +15 -0
  53. metadata +12 -6
@@ -1,8 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "json"
4
- require "fileutils"
5
- require "pathname"
3
+ require "sentry/transport/debug_transport"
6
4
  require "delegate"
7
5
 
8
6
  module Sentry
@@ -15,9 +13,8 @@ module Sentry
15
13
  attr_reader :log_file, :backend
16
14
 
17
15
  def initialize(configuration)
18
- @log_file = initialize_log_file(
19
- configuration.structured_logging.file_path || DEFAULT_LOG_FILE_PATH
20
- )
16
+ @log = DebugLogFile.new(configuration.structured_logging.file_path, File.basename(DEFAULT_LOG_FILE_PATH, ".log"))
17
+ @log_file = @log.path
21
18
  @backend = initialize_backend(configuration)
22
19
 
23
20
  super(@backend)
@@ -25,14 +22,20 @@ module Sentry
25
22
 
26
23
  # Override all log level methods to capture events
27
24
  %i[trace debug info warn error fatal].each do |level|
28
- define_method(level) do |message, parameters = [], **attributes|
25
+ define_method(level) do |message = nil, parameters = [], **attributes, &block|
26
+ message = block.call if block
27
+ raise ArgumentError, "message or block is required" if message.nil?
28
+
29
29
  log_event = capture_log_event(level, message, parameters, **attributes)
30
30
  backend.public_send(level, message, parameters, **attributes)
31
31
  log_event
32
32
  end
33
33
  end
34
34
 
35
- def log(level, message, parameters:, **attributes)
35
+ def log(level, message = nil, parameters:, **attributes)
36
+ message = yield if block_given?
37
+ raise ArgumentError, "message or block is required" if message.nil?
38
+
36
39
  log_event = capture_log_event(level, message, parameters, **attributes)
37
40
  backend.log(level, message, parameters: parameters, **attributes)
38
41
  log_event
@@ -47,18 +50,20 @@ module Sentry
47
50
  attributes: attributes
48
51
  }
49
52
 
50
- File.open(log_file, "a") { |file| file << JSON.dump(log_event_json) << "\n" }
53
+ @log.append(log_event_json)
51
54
  log_event_json
52
55
  end
53
56
 
54
57
  def logged_events
55
- File.readlines(log_file).map do |line|
56
- JSON.parse(line)
57
- end
58
+ @log.entries
59
+ end
60
+
61
+ def start_run
62
+ @log.start_run
58
63
  end
59
64
 
60
65
  def clear
61
- File.write(log_file, "")
66
+ @log.clear
62
67
  if backend.respond_to?(:config)
63
68
  backend.config.sdk_logger.debug("DebugStructuredLogger: Cleared events from #{log_file}")
64
69
  end
@@ -69,13 +74,5 @@ module Sentry
69
74
  def initialize_backend(configuration)
70
75
  StructuredLogger.new(configuration)
71
76
  end
72
-
73
- def initialize_log_file(log_file_path)
74
- log_file = Pathname(log_file_path)
75
-
76
- FileUtils.mkdir_p(log_file.dirname) unless log_file.dirname.exist?
77
-
78
- log_file
79
- end
80
77
  end
81
78
  end
@@ -0,0 +1,348 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sentry
4
+ module JobExtensions
5
+ # Base class for extensions that let a background-job backend enrich Sentry's
6
+ # job integrations. A backend gem subclasses it and overrides the hooks it can
7
+ # supply; jobs are opaque to Sentry and only interpreted by the extension.
8
+ class Extension
9
+ include LoggingHelper
10
+
11
+ PUBLISH_OP = "queue.publish"
12
+ PROCESS_OP = "queue.process"
13
+
14
+ MESSAGING_DATA_ATTRIBUTES = {
15
+ system: Span::DataConventions::MESSAGING_SYSTEM,
16
+ message_id: Span::DataConventions::MESSAGING_MESSAGE_ID,
17
+ destination: Span::DataConventions::MESSAGING_DESTINATION_NAME,
18
+ receive_latency: Span::DataConventions::MESSAGING_MESSAGE_RECEIVE_LATENCY,
19
+ retry_count: Span::DataConventions::MESSAGING_MESSAGE_RETRY_COUNT,
20
+ body_size: Span::DataConventions::MESSAGING_MESSAGE_BODY_SIZE
21
+ }.freeze
22
+
23
+ EMPTY_HASH = {}.freeze
24
+ private_constant :EMPTY_HASH
25
+
26
+ EMPTY_ERROR_DATA = { contexts: {}.freeze, tags: {}.freeze, extra: {}.freeze }.freeze
27
+ private_constant :EMPTY_ERROR_DATA
28
+
29
+ # The extension's name, used in SDK log messages.
30
+ # @return [Symbol]
31
+ attr_reader :name
32
+
33
+ # Creates an extension. Raises ArgumentError if the name is not a Symbol.
34
+ #
35
+ # @param name [Symbol]
36
+ # @param integration [Module] the integration that captures the job's exceptions
37
+ # @param origin [String] the origin of the job's spans
38
+ def initialize(name:, integration:, origin:)
39
+ raise ArgumentError, "job extension name must be a Symbol, got #{name.inspect}" unless name.is_a?(Symbol)
40
+
41
+ @name = name
42
+ @integration = integration
43
+ @origin = origin
44
+ end
45
+
46
+ # Wraps enqueueing a job in a `queue.publish` span.
47
+ #
48
+ # @param job [Object]
49
+ # @yieldreturn [Object] the result of enqueueing the job
50
+ # @return [Object] the block's result
51
+ def instrument_enqueue(job:, **context, &enqueue)
52
+ return enqueue.call unless safely("decide whether to record the producer span", fallback: true) { record_publish_span?(job: job, **context) }
53
+
54
+ Sentry.with_child_span(op: PUBLISH_OP) do |span|
55
+ if span
56
+ span.set_description(safely("describe the producer span") { publish_description(job: job, **context) })
57
+ span.set_origin(safely("set the producer span origin", fallback: @origin) { publish_span_origin(job: job, **context) })
58
+ set_messaging_data(span, hook_hash("collect the producer messaging data") { publish_messaging_data(job: job, **context) })
59
+ end
60
+
61
+ enqueue.call
62
+ end
63
+ end
64
+
65
+ # Prepares the scope for performing the job and starts its `queue.process`
66
+ # transaction, continuing the trace the job was enqueued in.
67
+ #
68
+ # @param scope [Scope]
69
+ # @param job [Object]
70
+ # @return [Transaction, nil]
71
+ def start_job(scope:, job:, **context)
72
+ data = hook_hash("collect the scope data") { scope_data(job: job, **context) }
73
+ safely("apply the scope data") { apply_scope_data(scope, data) }
74
+
75
+ job_name = safely("name the transaction") { transaction_name(job: job, **context) }
76
+ scope.set_transaction_name(job_name, source: :task) if job_name
77
+
78
+ trace_headers = hook_hash("extract trace headers") { extract_trace_headers(job: job, **context) }
79
+ origin = safely("set the transaction origin", fallback: @origin) { span_origin(job: job, **context) }
80
+ transaction = start_transaction(scope, trace_headers, origin)
81
+ return unless transaction
82
+
83
+ scope.set_span(transaction)
84
+ set_messaging_data(transaction, hook_hash("collect the messaging data") { messaging_data(job: job, **context) })
85
+ transaction
86
+ end
87
+
88
+ # Finishes the job's transaction with the given status.
89
+ #
90
+ # @param transaction [Transaction, nil]
91
+ # @param status [Integer]
92
+ # @return [void]
93
+ def finish_job(transaction:, status:)
94
+ return if !transaction || transaction.timestamp
95
+
96
+ transaction.set_http_status(status)
97
+ transaction.finish
98
+ end
99
+
100
+ # Captures an exception raised by the job, enriched with the extension's error data.
101
+ #
102
+ # @param job [Object]
103
+ # @param exception [Exception]
104
+ # @return [Event, nil]
105
+ def capture_exception(job:, exception:, contexts: {}, tags: {}, extra: {}, **context)
106
+ return unless Sentry.initialized?
107
+
108
+ data = safely("collect the error data", fallback: EMPTY_ERROR_DATA) { normalized_error_data(error_data(job: job, exception: exception, **context)) }
109
+ capturing_integration = safely("pick the capturing integration", fallback: @integration) { integration(job: job, **context) }
110
+
111
+ capturing_integration.capture_exception(exception, **merged_error_data(data, contexts: contexts, tags: tags, extra: extra))
112
+ end
113
+
114
+ # Runs a hook, logging its failure and returning `fallback` instead of raising.
115
+ #
116
+ # @param context [String] what the hook does, used in the log message
117
+ # @return [Object]
118
+ def safely(context, fallback: nil)
119
+ yield
120
+ rescue StandardError => e
121
+ log_failure(context, e)
122
+ fallback
123
+ end
124
+
125
+ ##### Hooks #####
126
+ #
127
+ # Called by job integrations with the job and any extra keyword context.
128
+ # Hooks must not mutate the objects they are given.
129
+
130
+ # Returns whether to record a `queue.publish` span when the job is enqueued.
131
+ #
132
+ # @param job [Object]
133
+ # @return [Boolean]
134
+ def record_publish_span?(job:, **)
135
+ true
136
+ end
137
+
138
+ # Returns data to apply to the scope the job is performed in.
139
+ #
140
+ # @param job [Object]
141
+ # @return [Hash] with optional `:contexts`, `:tags`, `:extra` and `:user`
142
+ def scope_data(job:, **)
143
+ {}
144
+ end
145
+
146
+ # Returns data to add to the event captured for a failed job. Data already on
147
+ # the scope or passed explicitly by the job integration takes precedence.
148
+ #
149
+ # @param job [Object]
150
+ # @param exception [Exception]
151
+ # @return [Hash] with optional `:contexts`, `:tags` and `:extra`
152
+ def error_data(job:, exception:, **)
153
+ {}
154
+ end
155
+
156
+ # Returns whether the backend will retry the failed job.
157
+ #
158
+ # @param job [Object]
159
+ # @return [Boolean]
160
+ def will_retry?(job:, **)
161
+ false
162
+ end
163
+
164
+ # Returns whether to capture the job's exception. By default only when the
165
+ # backend won't retry the job.
166
+ #
167
+ # @param job [Object]
168
+ # @param exception [Exception]
169
+ # @return [Boolean]
170
+ def report_exception?(job:, exception:, **context)
171
+ !will_retry?(job: job, exception: exception, **context)
172
+ end
173
+
174
+ # Returns whether to capture an exception that the job integration's own
175
+ # retry mechanism retries, so the backend never sees it.
176
+ #
177
+ # @param job [Object]
178
+ # @param exception [Exception]
179
+ # @return [Boolean]
180
+ def report_retried_exception?(job:, exception:, **)
181
+ false
182
+ end
183
+
184
+ # Returns the backend's job payload carrying the trace propagation headers.
185
+ #
186
+ # @param job [Object]
187
+ # @param payload [Object]
188
+ # @param headers [Hash{String => String}]
189
+ # @return [Object] a payload of the same class as the one given
190
+ def inject_trace_headers(job:, payload:, headers:, **)
191
+ payload
192
+ end
193
+
194
+ # Returns the trace propagation headers the job carries, so that performing
195
+ # it continues the trace it was enqueued in.
196
+ #
197
+ # @param job [Object]
198
+ # @return [Hash{String => String}]
199
+ def extract_trace_headers(job:, **)
200
+ {}
201
+ end
202
+
203
+ # Returns messaging attributes for the job's spans.
204
+ #
205
+ # @param job [Object]
206
+ # @return [Hash] with optional `:system`, `:message_id`, `:destination`,
207
+ # `:receive_latency`, `:retry_count` and `:body_size`
208
+ def messaging_data(job:, **)
209
+ {}
210
+ end
211
+
212
+ # Returns messaging attributes for the `queue.publish` span. Defaults to
213
+ # {#messaging_data}.
214
+ #
215
+ # @param job [Object]
216
+ # @return [Hash]
217
+ def publish_messaging_data(job:, **context)
218
+ messaging_data(job: job, **context)
219
+ end
220
+
221
+ # Returns the name of the job's transaction. Defaults to the job's class name.
222
+ #
223
+ # @param job [Object]
224
+ # @return [String, nil]
225
+ def transaction_name(job:, **)
226
+ job.class.name
227
+ end
228
+
229
+ # Returns the description of the `queue.publish` span. Defaults to the job's class name.
230
+ #
231
+ # @param job [Object]
232
+ # @return [String, nil]
233
+ def publish_description(job:, **)
234
+ job.class.name
235
+ end
236
+
237
+ # Returns the origin of the job's transaction. Defaults to the extension's origin.
238
+ #
239
+ # @param job [Object]
240
+ # @return [String]
241
+ def span_origin(job:, **)
242
+ @origin
243
+ end
244
+
245
+ # Returns the origin of the `queue.publish` span. Defaults to {#span_origin}.
246
+ #
247
+ # @param job [Object]
248
+ # @return [String]
249
+ def publish_span_origin(job:, **context)
250
+ span_origin(job: job, **context)
251
+ end
252
+
253
+ # Returns the integration that captures the job's exceptions. Defaults to
254
+ # the extension's integration.
255
+ #
256
+ # @param job [Object]
257
+ # @return [Module]
258
+ def integration(job:, **)
259
+ @integration
260
+ end
261
+
262
+ private
263
+
264
+ def hook_hash(description)
265
+ safely(description, fallback: EMPTY_HASH) do
266
+ value = yield
267
+ value.nil? ? EMPTY_HASH : Hash(value)
268
+ end
269
+ end
270
+
271
+ def start_transaction(scope, trace_headers, origin)
272
+ options = {
273
+ name: scope.transaction_name,
274
+ source: scope.transaction_source,
275
+ op: PROCESS_OP,
276
+ origin: origin
277
+ }
278
+
279
+ if trace_headers.empty?
280
+ Sentry.start_transaction(**options)
281
+ else
282
+ Sentry.start_transaction(transaction: Sentry.continue_trace(trace_headers, **options), **options)
283
+ end
284
+ end
285
+
286
+ def apply_scope_data(scope, data)
287
+ scope.set_contexts(data[:contexts]) if data[:contexts]
288
+ scope.set_tags(data[:tags]) if data[:tags]
289
+ scope.set_extras(data[:extra]) if data[:extra]
290
+ scope.set_user(data[:user]) if data[:user]
291
+ end
292
+
293
+ def set_messaging_data(span, data)
294
+ MESSAGING_DATA_ATTRIBUTES.each do |key, attribute|
295
+ span.set_data(attribute, data[key]) if data.key?(key)
296
+ end
297
+ end
298
+
299
+ def normalized_error_data(data)
300
+ data = Hash(data)
301
+
302
+ {
303
+ contexts: Hash(data[:contexts]).transform_values { |context| Hash(context) },
304
+ tags: Hash(data[:tags]),
305
+ extra: Hash(data[:extra])
306
+ }
307
+ end
308
+
309
+ # Builds the capture options so that the caller's contexts, tags and extra
310
+ # take precedence over the scope's, and the scope's over the extension's.
311
+ #
312
+ # Every value passed to capture_exception becomes event data, and
313
+ # Scope#apply_to_event lets event data beat scope data. It also merges
314
+ # contexts by name, so an event context replaces the scope context of the
315
+ # same name entirely. The extension's tags and extra therefore leave out
316
+ # keys the scope already has, and each extension context absorbs the scope
317
+ # context of the same name before the caller's values are merged on top.
318
+ def merged_error_data(data, contexts:, tags:, extra:)
319
+ scope = Sentry.get_current_scope
320
+
321
+ merged_contexts = contexts_with_scope_values(data[:contexts], scope.contexts).merge(contexts)
322
+ options = {
323
+ extra: without_scope_keys(data[:extra], scope.extra).merge(extra),
324
+ tags: without_scope_keys(data[:tags], scope.tags).merge(tags),
325
+ hint: { background: false }
326
+ }
327
+ options[:contexts] = merged_contexts unless merged_contexts.empty?
328
+ options
329
+ end
330
+
331
+ def without_scope_keys(values, scope_values)
332
+ values.reject { |key, _value| scope_values.key?(key) }
333
+ end
334
+
335
+ def contexts_with_scope_values(contexts, scope_contexts)
336
+ contexts.to_h { |name, context| [name, context.merge(scope_contexts.fetch(name, {}))] }
337
+ end
338
+
339
+ def log_failure(context, error)
340
+ log_error("Job extension #{name.inspect} failed to #{context}", error)
341
+ end
342
+
343
+ def sdk_logger
344
+ Sentry.sdk_logger if Sentry.initialized?
345
+ end
346
+ end
347
+ end
348
+ end
@@ -48,6 +48,8 @@ module Sentry
48
48
  return if match.nil?
49
49
 
50
50
  trace_id, parent_span_id, sampled_flag = match[1..3]
51
+ return if trace_id.nil?
52
+
51
53
  parent_sampled = sampled_flag.nil? ? nil : sampled_flag != "0"
52
54
 
53
55
  [trace_id, parent_span_id, parent_sampled]
data/lib/sentry/redis.rb CHANGED
@@ -6,6 +6,10 @@ module Sentry
6
6
  OP_NAME = "db.redis"
7
7
  SPAN_ORIGIN = "auto.db.redis"
8
8
  LOGGER_NAME = :redis_logger
9
+ # Commands that carry credentials from their first argument on.
10
+ SENSITIVE_COMMANDS = %w[AUTH HELLO].freeze
11
+ # Commands whose later arguments can carry credentials. Arguments are never recorded.
12
+ ARGUMENTLESS_COMMANDS = %w[ACL CONFIG MIGRATE SENTINEL].freeze
9
13
 
10
14
  def initialize(commands, host, port, db)
11
15
  @commands, @host, @port, @db = commands, host, port, db
@@ -60,9 +64,11 @@ module Sentry
60
64
  commands.map do |statement|
61
65
  command, key, *arguments = statement
62
66
  command_set = { command: command.to_s.upcase }
67
+ next command_set if SENSITIVE_COMMANDS.include?(command_set[:command])
68
+
63
69
  command_set[:key] = key if Utils::EncodingHelper.valid_utf_8?(key)
64
70
 
65
- if Sentry.configuration.data_collection.database_query_data
71
+ if Sentry.configuration.data_collection.database_query_data && !ARGUMENTLESS_COMMANDS.include?(command_set[:command])
66
72
  command_set[:arguments] = arguments
67
73
  .select { |a| Utils::EncodingHelper.valid_utf_8?(a) }
68
74
  .join(" ")
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sentry
4
+ # Sends Crons check-ins for rufus-scheduler `cron` and `every` jobs.
5
+ # Enable with `config.enabled_patches << :rufus_scheduler`.
6
+ module RufusScheduler
7
+ module Job
8
+ protected
9
+
10
+ def do_call(time, do_rescue)
11
+ return super unless Sentry.initialized? && (monitor = sentry_monitor)
12
+
13
+ slug, monitor_config = monitor
14
+ check_in_id = Sentry.capture_check_in(slug, :in_progress, monitor_config: monitor_config)
15
+ start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
16
+
17
+ begin
18
+ # Run without rufus's rescue so the error is seen, then handle it like Job#do_call.
19
+ ret = super(time, false)
20
+ rescue Exception => e
21
+ duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
22
+ Sentry.capture_check_in(slug, :error, check_in_id: check_in_id, duration: duration, monitor_config: monitor_config)
23
+
24
+ raise unless do_rescue && e.is_a?(StandardError)
25
+ return if e.is_a?(::Rufus::Scheduler::Job::KillSignal)
26
+
27
+ return @scheduler.on_error(self, e)
28
+ end
29
+
30
+ duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
31
+ Sentry.capture_check_in(slug, :ok, check_in_id: check_in_id, duration: duration, monitor_config: monitor_config)
32
+
33
+ ret
34
+ end
35
+
36
+ private
37
+
38
+ def sentry_monitor
39
+ return @sentry_monitor if defined?(@sentry_monitor)
40
+
41
+ @sentry_monitor = Sentry::RufusScheduler.monitor_for(self)
42
+ rescue StandardError => e
43
+ Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Not monitoring rufus-scheduler job #{id}: #{e.class}: #{e.message}" }
44
+ @sentry_monitor = nil
45
+ end
46
+ end
47
+
48
+ class << self
49
+ # Returns [slug, monitor_config], or nil for jobs that aren't monitored (like `at`/`in`, or unsupported schedules).
50
+ def monitor_for(job)
51
+ return unless job.is_a?(::Rufus::Scheduler::RepeatJob)
52
+ return if job.opts[:sentry_monitor] == false
53
+ return if sidekiq_scheduler_job?(job)
54
+
55
+ slug = slug_for(job)
56
+ unless slug
57
+ Sentry.sdk_logger.warn(Sentry::LOGGER_PROGNAME) do
58
+ "Not monitoring rufus-scheduler job #{job.id} at #{job.source_location&.join(":")}: " \
59
+ "pass `name:` to give it a stable monitor slug."
60
+ end
61
+ return
62
+ end
63
+
64
+ monitor_config = monitor_config_for(job)
65
+ unless monitor_config
66
+ Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Not monitoring rufus-scheduler job #{slug}: its schedule can't be expressed as a Crons schedule." }
67
+ return
68
+ end
69
+
70
+ [slug, monitor_config]
71
+ end
72
+
73
+ private
74
+
75
+ # sidekiq-scheduler jobs are monitored by the :sidekiq_scheduler patch.
76
+ def sidekiq_scheduler_job?(job)
77
+ file, _ = job.callable.source_location if job.callable.respond_to?(:source_location)
78
+ file&.end_with?("sidekiq-scheduler/scheduler.rb")
79
+ end
80
+
81
+ # Job ids are random per process and block paths change between deploys,
82
+ # so the slug comes from `name:`, then the handler method or class.
83
+ def slug_for(job)
84
+ handler = job.handler
85
+ source =
86
+ if job.name
87
+ job.name.to_s
88
+ elsif handler.is_a?(Method)
89
+ # The receiver's class, not the method owner, so inherited and mixin methods get distinct slugs.
90
+ namespace = handler.receiver.is_a?(Module) ? handler.receiver : handler.receiver.class
91
+ [namespace == Object ? nil : namespace.name, handler.name].compact.join("::")
92
+ elsif !handler.is_a?(Proc)
93
+ handler.class.name
94
+ end
95
+ return unless source
96
+
97
+ Sentry::Cron::Slug.from(source)
98
+ end
99
+
100
+ def monitor_config_for(job)
101
+ case job
102
+ when ::Rufus::Scheduler::CronJob
103
+ Sentry::Cron::FugitSchedule.from_cron(job.cron_line)
104
+ when ::Rufus::Scheduler::EveryJob
105
+ Sentry::Cron::FugitSchedule.from_seconds(job.frequency)
106
+ end
107
+ # IntervalJob waits `interval` after each run ends, so no fixed schedule matches it.
108
+ end
109
+ end
110
+ end
111
+ end
112
+
113
+ Sentry.register_patch(:rufus_scheduler) do |config|
114
+ # Load rufus-scheduler in case it's required after Sentry.init.
115
+ begin
116
+ require "rufus-scheduler"
117
+ rescue LoadError
118
+ end
119
+
120
+ if defined?(::Rufus::Scheduler::RepeatJob)
121
+ ::Rufus::Scheduler::Job.prepend(Sentry::RufusScheduler::Job) unless ::Rufus::Scheduler::Job.ancestors.include?(Sentry::RufusScheduler::Job)
122
+ else
123
+ config.sdk_logger.warn(Sentry::LOGGER_PROGNAME) { "You tried to enable the rufus-scheduler integration but the `rufus-scheduler` gem was not detected." }
124
+ end
125
+ end
data/lib/sentry/scope.rb CHANGED
@@ -4,6 +4,7 @@ require "set"
4
4
  require "sentry/breadcrumb_buffer"
5
5
  require "sentry/propagation_context"
6
6
  require "sentry/attachment"
7
+ require "sentry/utils/ring_buffer"
7
8
  require "etc"
8
9
 
9
10
  module Sentry
@@ -27,9 +28,13 @@ module Sentry
27
28
  :session,
28
29
  :attachments,
29
30
  :propagation_context,
30
- :attributes
31
+ :attributes,
32
+ :flags
31
33
  ]
32
34
 
35
+ # Maximum number of feature flag evaluations kept on a scope.
36
+ MAX_FLAGS = 100
37
+
33
38
  attr_reader(*ATTRIBUTES)
34
39
 
35
40
  # @param max_breadcrumbs [Integer] the maximum number of breadcrumbs to be stored in the scope.
@@ -61,6 +66,7 @@ module Sentry
61
66
  event.breadcrumbs = breadcrumbs
62
67
  event.rack_env = rack_env if rack_env
63
68
  event.attachments = attachments
69
+ apply_flags_to_event(event)
64
70
  end
65
71
 
66
72
  trace_context = get_trace_context
@@ -151,6 +157,7 @@ module Sentry
151
157
  copy.attachments = attachments.dup
152
158
  copy.event_processors = event_processors.dup
153
159
  copy.attributes = attributes.deep_dup
160
+ copy.flags = flags.dup
154
161
  copy
155
162
  end
156
163
 
@@ -170,6 +177,7 @@ module Sentry
170
177
  self.propagation_context = scope.propagation_context
171
178
  self.attachments = scope.attachments
172
179
  self.attributes = scope.attributes
180
+ self.flags = scope.flags.dup
173
181
  end
174
182
 
175
183
  # Updates the scope's data from the given options.
@@ -298,6 +306,22 @@ module Sentry
298
306
  @attributes.delete(key.to_s)
299
307
  end
300
308
 
309
+ # Records a feature flag evaluation on the scope (and the active span, if any).
310
+ # Only boolean results are supported; other values are ignored.
311
+ # The scope keeps the most recent {MAX_FLAGS} distinct flags (oldest evicted first).
312
+ # @param name [String, Symbol] the flag name
313
+ # @param result [Boolean] the evaluation result
314
+ # @return [void]
315
+ def add_feature_flag(name, result)
316
+ return unless result == true || result == false
317
+
318
+ name = name.to_s
319
+ flags.set(name, result)
320
+
321
+ add_feature_flag_to_span(name, result)
322
+ nil
323
+ end
324
+
301
325
  # Sets the scope's level attribute.
302
326
  # @param level [String, Symbol]
303
327
  # @return [void]
@@ -389,6 +413,19 @@ module Sentry
389
413
 
390
414
  private
391
415
 
416
+ def add_feature_flag_to_span(name, result)
417
+ return unless span
418
+
419
+ span.set_flag(name, result)
420
+ end
421
+
422
+ def apply_flags_to_event(event)
423
+ return unless event.is_a?(ErrorEvent) && !flags.empty?
424
+
425
+ values = flags.values.map { |flag, result| { flag: flag, result: result } }
426
+ event.contexts[:flags] = { values: values }
427
+ end
428
+
392
429
  def set_default_value
393
430
  @contexts = { os: self.class.os_context, runtime: self.class.runtime_context }
394
431
  @extra = {}
@@ -404,6 +441,7 @@ module Sentry
404
441
  @session = nil
405
442
  @attachments = []
406
443
  @attributes = {}
444
+ @flags = Utils::RingBuffer.new(MAX_FLAGS)
407
445
  generate_propagation_context
408
446
  set_new_breadcrumb_buffer
409
447
  end
@@ -29,8 +29,11 @@ module Sentry
29
29
  return unless ensure_thread
30
30
 
31
31
  return unless Session::AGGREGATE_STATUSES.include?(session.status)
32
- @pending_aggregates[session.aggregation_key] ||= init_aggregates(session.aggregation_key)
33
- @pending_aggregates[session.aggregation_key][session.status] += 1
32
+
33
+ @mutex.synchronize do
34
+ @pending_aggregates[session.aggregation_key] ||= init_aggregates(session.aggregation_key)
35
+ @pending_aggregates[session.aggregation_key][session.status] += 1
36
+ end
34
37
  end
35
38
 
36
39
  private