sentry-ruby 5.3.1 → 5.16.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (76) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +11 -0
  3. data/.rspec +2 -0
  4. data/.yardopts +2 -0
  5. data/CHANGELOG.md +313 -0
  6. data/Gemfile +26 -0
  7. data/Makefile +4 -0
  8. data/README.md +11 -8
  9. data/Rakefile +20 -0
  10. data/bin/console +18 -0
  11. data/bin/setup +8 -0
  12. data/lib/sentry/background_worker.rb +79 -0
  13. data/lib/sentry/backpressure_monitor.rb +75 -0
  14. data/lib/sentry/backtrace.rb +124 -0
  15. data/lib/sentry/baggage.rb +70 -0
  16. data/lib/sentry/breadcrumb/sentry_logger.rb +90 -0
  17. data/lib/sentry/breadcrumb.rb +76 -0
  18. data/lib/sentry/breadcrumb_buffer.rb +64 -0
  19. data/lib/sentry/check_in_event.rb +60 -0
  20. data/lib/sentry/client.rb +248 -0
  21. data/lib/sentry/configuration.rb +650 -0
  22. data/lib/sentry/core_ext/object/deep_dup.rb +61 -0
  23. data/lib/sentry/core_ext/object/duplicable.rb +155 -0
  24. data/lib/sentry/cron/configuration.rb +23 -0
  25. data/lib/sentry/cron/monitor_check_ins.rb +75 -0
  26. data/lib/sentry/cron/monitor_config.rb +53 -0
  27. data/lib/sentry/cron/monitor_schedule.rb +42 -0
  28. data/lib/sentry/dsn.rb +53 -0
  29. data/lib/sentry/envelope.rb +93 -0
  30. data/lib/sentry/error_event.rb +38 -0
  31. data/lib/sentry/event.rb +156 -0
  32. data/lib/sentry/exceptions.rb +9 -0
  33. data/lib/sentry/hub.rb +316 -0
  34. data/lib/sentry/integrable.rb +32 -0
  35. data/lib/sentry/interface.rb +16 -0
  36. data/lib/sentry/interfaces/exception.rb +43 -0
  37. data/lib/sentry/interfaces/request.rb +134 -0
  38. data/lib/sentry/interfaces/single_exception.rb +67 -0
  39. data/lib/sentry/interfaces/stacktrace.rb +87 -0
  40. data/lib/sentry/interfaces/stacktrace_builder.rb +79 -0
  41. data/lib/sentry/interfaces/threads.rb +42 -0
  42. data/lib/sentry/linecache.rb +47 -0
  43. data/lib/sentry/logger.rb +20 -0
  44. data/lib/sentry/net/http.rb +106 -0
  45. data/lib/sentry/profiler.rb +233 -0
  46. data/lib/sentry/propagation_context.rb +134 -0
  47. data/lib/sentry/puma.rb +32 -0
  48. data/lib/sentry/rack/capture_exceptions.rb +79 -0
  49. data/lib/sentry/rack.rb +5 -0
  50. data/lib/sentry/rake.rb +28 -0
  51. data/lib/sentry/redis.rb +108 -0
  52. data/lib/sentry/release_detector.rb +39 -0
  53. data/lib/sentry/scope.rb +360 -0
  54. data/lib/sentry/session.rb +33 -0
  55. data/lib/sentry/session_flusher.rb +90 -0
  56. data/lib/sentry/span.rb +273 -0
  57. data/lib/sentry/test_helper.rb +84 -0
  58. data/lib/sentry/transaction.rb +359 -0
  59. data/lib/sentry/transaction_event.rb +80 -0
  60. data/lib/sentry/transport/configuration.rb +98 -0
  61. data/lib/sentry/transport/dummy_transport.rb +21 -0
  62. data/lib/sentry/transport/http_transport.rb +206 -0
  63. data/lib/sentry/transport/spotlight_transport.rb +50 -0
  64. data/lib/sentry/transport.rb +225 -0
  65. data/lib/sentry/utils/argument_checking_helper.rb +19 -0
  66. data/lib/sentry/utils/custom_inspection.rb +14 -0
  67. data/lib/sentry/utils/encoding_helper.rb +22 -0
  68. data/lib/sentry/utils/exception_cause_chain.rb +20 -0
  69. data/lib/sentry/utils/logging_helper.rb +26 -0
  70. data/lib/sentry/utils/real_ip.rb +84 -0
  71. data/lib/sentry/utils/request_id.rb +18 -0
  72. data/lib/sentry/version.rb +5 -0
  73. data/lib/sentry-ruby.rb +580 -0
  74. data/sentry-ruby-core.gemspec +23 -0
  75. data/sentry-ruby.gemspec +24 -0
  76. metadata +75 -16
@@ -0,0 +1,650 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "concurrent/utility/processor_counter"
4
+
5
+ require "sentry/utils/exception_cause_chain"
6
+ require 'sentry/utils/custom_inspection'
7
+ require "sentry/dsn"
8
+ require "sentry/release_detector"
9
+ require "sentry/transport/configuration"
10
+ require "sentry/cron/configuration"
11
+ require "sentry/linecache"
12
+ require "sentry/interfaces/stacktrace_builder"
13
+
14
+ module Sentry
15
+ class Configuration
16
+ include CustomInspection
17
+ include LoggingHelper
18
+ include ArgumentCheckingHelper
19
+
20
+ # Directories to be recognized as part of your app. e.g. if you
21
+ # have an `engines` dir at the root of your project, you may want
22
+ # to set this to something like /(app|config|engines|lib)/
23
+ #
24
+ # @return [Regexp, nil]
25
+ attr_accessor :app_dirs_pattern
26
+
27
+ # Provide an object that responds to `call` to send events asynchronously.
28
+ # E.g.: lambda { |event| Thread.new { Sentry.send_event(event) } }
29
+ #
30
+ # @deprecated It will be removed in the next major release. Please read https://github.com/getsentry/sentry-ruby/issues/1522 for more information
31
+ # @return [Proc, nil]
32
+ attr_reader :async
33
+
34
+ # to send events in a non-blocking way, sentry-ruby has its own background worker
35
+ # by default, the worker holds a thread pool that has [the number of processors] threads
36
+ # but you can configure it with this configuration option
37
+ # E.g.: config.background_worker_threads = 5
38
+ #
39
+ # if you want to send events synchronously, set the value to 0
40
+ # E.g.: config.background_worker_threads = 0
41
+ # @return [Integer]
42
+ attr_accessor :background_worker_threads
43
+
44
+ # The maximum queue size for the background worker.
45
+ # Jobs will be rejected above this limit.
46
+ #
47
+ # Default is {BackgroundWorker::DEFAULT_MAX_QUEUE}.
48
+ # @return [Integer]
49
+ attr_accessor :background_worker_max_queue
50
+
51
+ # a proc/lambda that takes an array of stack traces
52
+ # it'll be used to silence (reduce) backtrace of the exception
53
+ #
54
+ # @example
55
+ # config.backtrace_cleanup_callback = lambda do |backtrace|
56
+ # Rails.backtrace_cleaner.clean(backtrace)
57
+ # end
58
+ #
59
+ # @return [Proc, nil]
60
+ attr_accessor :backtrace_cleanup_callback
61
+
62
+ # Optional Proc, called before adding the breadcrumb to the current scope
63
+ # @example
64
+ # config.before = lambda do |breadcrumb, hint|
65
+ # breadcrumb.message = 'a'
66
+ # breadcrumb
67
+ # end
68
+ # @return [Proc]
69
+ attr_reader :before_breadcrumb
70
+
71
+ # Optional Proc, called before sending an event to the server
72
+ # @example
73
+ # config.before_send = lambda do |event, hint|
74
+ # # skip ZeroDivisionError exceptions
75
+ # # note: hint[:exception] would be a String if you use async callback
76
+ # if hint[:exception].is_a?(ZeroDivisionError)
77
+ # nil
78
+ # else
79
+ # event
80
+ # end
81
+ # end
82
+ # @return [Proc]
83
+ attr_reader :before_send
84
+
85
+ # Optional Proc, called before sending an event to the server
86
+ # @example
87
+ # config.before_send_transaction = lambda do |event, hint|
88
+ # # skip unimportant transactions or strip sensitive data
89
+ # if event.transaction == "/healthcheck/route"
90
+ # nil
91
+ # else
92
+ # event
93
+ # end
94
+ # end
95
+ # @return [Proc]
96
+ attr_reader :before_send_transaction
97
+
98
+ # An array of breadcrumbs loggers to be used. Available options are:
99
+ # - :sentry_logger
100
+ # - :http_logger
101
+ # - :redis_logger
102
+ #
103
+ # And if you also use sentry-rails:
104
+ # - :active_support_logger
105
+ # - :monotonic_active_support_logger
106
+ #
107
+ # @return [Array<Symbol>]
108
+ attr_reader :breadcrumbs_logger
109
+
110
+ # Max number of breadcrumbs a breadcrumb buffer can hold
111
+ # @return [Integer]
112
+ attr_accessor :max_breadcrumbs
113
+
114
+ # Number of lines of code context to capture, or nil for none
115
+ # @return [Integer, nil]
116
+ attr_accessor :context_lines
117
+
118
+ # RACK_ENV by default.
119
+ # @return [String]
120
+ attr_reader :environment
121
+
122
+ # Whether the SDK should run in the debugging mode. Default is false.
123
+ # If set to true, SDK errors will be logged with backtrace
124
+ # @return [Boolean]
125
+ attr_accessor :debug
126
+
127
+ # the dsn value, whether it's set via `config.dsn=` or `ENV["SENTRY_DSN"]`
128
+ # @return [String]
129
+ attr_reader :dsn
130
+
131
+ # Whitelist of enabled_environments that will send notifications to Sentry. Array of Strings.
132
+ # @return [Array<String>]
133
+ attr_accessor :enabled_environments
134
+
135
+ # Logger 'progname's to exclude from breadcrumbs
136
+ # @return [Array<String>]
137
+ attr_accessor :exclude_loggers
138
+
139
+ # Array of exception classes that should never be sent. See IGNORE_DEFAULT.
140
+ # You should probably append to this rather than overwrite it.
141
+ # @return [Array<String>]
142
+ attr_accessor :excluded_exceptions
143
+
144
+ # Boolean to check nested exceptions when deciding if to exclude. Defaults to true
145
+ # @return [Boolean]
146
+ attr_accessor :inspect_exception_causes_for_exclusion
147
+ alias inspect_exception_causes_for_exclusion? inspect_exception_causes_for_exclusion
148
+
149
+ # Whether to capture local variables from the raised exception's frame. Default is false.
150
+ # @return [Boolean]
151
+ attr_accessor :include_local_variables
152
+
153
+ # Whether to capture events and traces into Spotlight. Default is false.
154
+ # If you set this to true, Sentry will send events and traces to the local
155
+ # Sidecar proxy at http://localhost:8969/stream.
156
+ # If you want to use a different Sidecar proxy address, set this to String
157
+ # with the proxy URL.
158
+ # @return [Boolean, String]
159
+ attr_accessor :spotlight
160
+
161
+ # @deprecated Use {#include_local_variables} instead.
162
+ alias_method :capture_exception_frame_locals, :include_local_variables
163
+
164
+ # @deprecated Use {#include_local_variables=} instead.
165
+ def capture_exception_frame_locals=(value)
166
+ log_warn <<~MSG
167
+ `capture_exception_frame_locals` is now deprecated in favor of `include_local_variables`.
168
+ MSG
169
+
170
+ self.include_local_variables = value
171
+ end
172
+
173
+ # You may provide your own LineCache for matching paths with source files.
174
+ # This may be useful if you need to get source code from places other than the disk.
175
+ # @see LineCache
176
+ # @return [LineCache]
177
+ attr_accessor :linecache
178
+
179
+ # Logger used by Sentry. In Rails, this is the Rails logger, otherwise
180
+ # Sentry provides its own Sentry::Logger.
181
+ # @return [Logger]
182
+ attr_accessor :logger
183
+
184
+ # Project directory root for in_app detection. Could be Rails root, etc.
185
+ # Set automatically for Rails.
186
+ # @return [String]
187
+ attr_accessor :project_root
188
+
189
+ # Insert sentry-trace to outgoing requests' headers
190
+ # @return [Boolean]
191
+ attr_accessor :propagate_traces
192
+
193
+ # Array of rack env parameters to be included in the event sent to sentry.
194
+ # @return [Array<String>]
195
+ attr_accessor :rack_env_whitelist
196
+
197
+ # Release tag to be passed with every event sent to Sentry.
198
+ # We automatically try to set this to a git SHA or Capistrano release.
199
+ # @return [String]
200
+ attr_reader :release
201
+
202
+ # The sampling factor to apply to events. A value of 0.0 will not send
203
+ # any events, and a value of 1.0 will send 100% of events.
204
+ # @return [Float]
205
+ attr_accessor :sample_rate
206
+
207
+ # Include module versions in reports - boolean.
208
+ # @return [Boolean]
209
+ attr_accessor :send_modules
210
+
211
+ # When send_default_pii's value is false (default), sensitive information like
212
+ # - user ip
213
+ # - user cookie
214
+ # - request body
215
+ # - query string
216
+ # will not be sent to Sentry.
217
+ # @return [Boolean]
218
+ attr_accessor :send_default_pii
219
+
220
+ # Allow to skip Sentry emails within rake tasks
221
+ # @return [Boolean]
222
+ attr_accessor :skip_rake_integration
223
+
224
+ # IP ranges for trusted proxies that will be skipped when calculating IP address.
225
+ attr_accessor :trusted_proxies
226
+
227
+ # @return [String]
228
+ attr_accessor :server_name
229
+
230
+ # Transport related configuration.
231
+ # @return [Transport::Configuration]
232
+ attr_reader :transport
233
+
234
+ # Cron related configuration.
235
+ # @return [Cron::Configuration]
236
+ attr_reader :cron
237
+
238
+ # Take a float between 0.0 and 1.0 as the sample rate for tracing events (transactions).
239
+ # @return [Float, nil]
240
+ attr_reader :traces_sample_rate
241
+
242
+ # Take a Proc that controls the sample rate for every tracing event, e.g.
243
+ # @example
244
+ # config.traces_sampler = lambda do |tracing_context|
245
+ # # tracing_context[:transaction_context] contains the information about the transaction
246
+ # # tracing_context[:parent_sampled] contains the transaction's parent's sample decision
247
+ # true # return value can be a boolean or a float between 0.0 and 1.0
248
+ # end
249
+ # @return [Proc]
250
+ attr_accessor :traces_sampler
251
+
252
+ # Easier way to use performance tracing
253
+ # If set to true, will set traces_sample_rate to 1.0
254
+ # @return [Boolean, nil]
255
+ attr_reader :enable_tracing
256
+
257
+ # Send diagnostic client reports about dropped events, true by default
258
+ # tries to attach to an existing envelope max once every 30s
259
+ # @return [Boolean]
260
+ attr_accessor :send_client_reports
261
+
262
+ # Track sessions in request/response cycles automatically
263
+ # @return [Boolean]
264
+ attr_accessor :auto_session_tracking
265
+
266
+ # Whether to downsample transactions automatically because of backpressure.
267
+ # Starts a new monitor thread to check health of the SDK every 10 seconds.
268
+ # Default is false
269
+ # @return [Boolean]
270
+ attr_accessor :enable_backpressure_handling
271
+
272
+ # Allowlist of outgoing request targets to which sentry-trace and baggage headers are attached.
273
+ # Default is all (/.*/)
274
+ # @return [Array<String, Regexp>]
275
+ attr_accessor :trace_propagation_targets
276
+
277
+ # The instrumenter to use, :sentry or :otel
278
+ # @return [Symbol]
279
+ attr_reader :instrumenter
280
+
281
+ # Take a float between 0.0 and 1.0 as the sample rate for capturing profiles.
282
+ # Note that this rate is relative to traces_sample_rate / traces_sampler,
283
+ # i.e. the profile is sampled by this rate after the transaction is sampled.
284
+ # @return [Float, nil]
285
+ attr_reader :profiles_sample_rate
286
+
287
+ # Array of patches to apply.
288
+ # Default is {DEFAULT_PATCHES}
289
+ # @return [Array<Symbol>]
290
+ attr_accessor :enabled_patches
291
+
292
+ # these are not config options
293
+ # @!visibility private
294
+ attr_reader :errors, :gem_specs
295
+
296
+ # These exceptions could enter Puma's `lowlevel_error_handler` callback and the SDK's Puma integration
297
+ # But they are mostly considered as noise and should be ignored by default
298
+ # Please see https://github.com/getsentry/sentry-ruby/pull/2026 for more information
299
+ PUMA_IGNORE_DEFAULT = [
300
+ 'Puma::MiniSSL::SSLError',
301
+ 'Puma::HttpParserError',
302
+ 'Puma::HttpParserError501'
303
+ ].freeze
304
+
305
+ # Most of these errors generate 4XX responses. In general, Sentry clients
306
+ # only automatically report 5xx responses.
307
+ IGNORE_DEFAULT = [
308
+ 'Mongoid::Errors::DocumentNotFound',
309
+ 'Rack::QueryParser::InvalidParameterError',
310
+ 'Rack::QueryParser::ParameterTypeError',
311
+ 'Sinatra::NotFound'
312
+ ].freeze
313
+
314
+ RACK_ENV_WHITELIST_DEFAULT = %w(
315
+ REMOTE_ADDR
316
+ SERVER_NAME
317
+ SERVER_PORT
318
+ ).freeze
319
+
320
+ HEROKU_DYNO_METADATA_MESSAGE = "You are running on Heroku but haven't enabled Dyno Metadata. For Sentry's "\
321
+ "release detection to work correctly, please run `heroku labs:enable runtime-dyno-metadata`".freeze
322
+
323
+ LOG_PREFIX = "** [Sentry] ".freeze
324
+ MODULE_SEPARATOR = "::".freeze
325
+ SKIP_INSPECTION_ATTRIBUTES = [:@linecache, :@stacktrace_builder]
326
+
327
+ INSTRUMENTERS = [:sentry, :otel]
328
+
329
+ PROPAGATION_TARGETS_MATCH_ALL = /.*/.freeze
330
+
331
+ DEFAULT_PATCHES = %i(redis puma http).freeze
332
+
333
+ class << self
334
+ # Post initialization callbacks are called at the end of initialization process
335
+ # allowing extending the configuration of sentry-ruby by multiple extensions
336
+ def post_initialization_callbacks
337
+ @post_initialization_callbacks ||= []
338
+ end
339
+
340
+ # allow extensions to add their hooks to the Configuration class
341
+ def add_post_initialization_callback(&block)
342
+ post_initialization_callbacks << block
343
+ end
344
+ end
345
+
346
+ def initialize
347
+ self.app_dirs_pattern = nil
348
+ self.debug = false
349
+ self.background_worker_threads = Concurrent.processor_count
350
+ self.background_worker_max_queue = BackgroundWorker::DEFAULT_MAX_QUEUE
351
+ self.backtrace_cleanup_callback = nil
352
+ self.max_breadcrumbs = BreadcrumbBuffer::DEFAULT_SIZE
353
+ self.breadcrumbs_logger = []
354
+ self.context_lines = 3
355
+ self.include_local_variables = false
356
+ self.environment = environment_from_env
357
+ self.enabled_environments = []
358
+ self.exclude_loggers = []
359
+ self.excluded_exceptions = IGNORE_DEFAULT + PUMA_IGNORE_DEFAULT
360
+ self.inspect_exception_causes_for_exclusion = true
361
+ self.linecache = ::Sentry::LineCache.new
362
+ self.logger = ::Sentry::Logger.new(STDOUT)
363
+ self.project_root = Dir.pwd
364
+ self.propagate_traces = true
365
+
366
+ self.sample_rate = 1.0
367
+ self.send_modules = true
368
+ self.send_default_pii = false
369
+ self.skip_rake_integration = false
370
+ self.send_client_reports = true
371
+ self.auto_session_tracking = true
372
+ self.enable_backpressure_handling = false
373
+ self.trusted_proxies = []
374
+ self.dsn = ENV['SENTRY_DSN']
375
+ self.spotlight = false
376
+ self.server_name = server_name_from_env
377
+ self.instrumenter = :sentry
378
+ self.trace_propagation_targets = [PROPAGATION_TARGETS_MATCH_ALL]
379
+ self.enabled_patches = DEFAULT_PATCHES.dup
380
+
381
+ self.before_send = nil
382
+ self.before_send_transaction = nil
383
+ self.rack_env_whitelist = RACK_ENV_WHITELIST_DEFAULT
384
+ self.traces_sampler = nil
385
+ self.enable_tracing = nil
386
+
387
+ @transport = Transport::Configuration.new
388
+ @cron = Cron::Configuration.new
389
+ @gem_specs = Hash[Gem::Specification.map { |spec| [spec.name, spec.version.to_s] }] if Gem::Specification.respond_to?(:map)
390
+
391
+ run_post_initialization_callbacks
392
+ end
393
+
394
+ def dsn=(value)
395
+ @dsn = init_dsn(value)
396
+ end
397
+
398
+ alias server= dsn=
399
+
400
+ def release=(value)
401
+ check_argument_type!(value, String, NilClass)
402
+
403
+ @release = value
404
+ end
405
+
406
+ def async=(value)
407
+ check_callable!("async", value)
408
+
409
+ log_warn <<~MSG
410
+
411
+ sentry-ruby now sends events asynchronously by default with its background worker (supported since 4.1.0).
412
+ The `config.async` callback has become redundant while continuing to cause issues.
413
+ (The problems of `async` are detailed in https://github.com/getsentry/sentry-ruby/issues/1522)
414
+
415
+ Therefore, we encourage you to remove it and let the background worker take care of async job sending.
416
+ It's deprecation is planned in the next major release (6.0), which is scheduled around the 3rd quarter of 2022.
417
+ MSG
418
+
419
+ @async = value
420
+ end
421
+
422
+ def breadcrumbs_logger=(logger)
423
+ loggers =
424
+ if logger.is_a?(Array)
425
+ logger
426
+ else
427
+ Array(logger)
428
+ end
429
+
430
+ require "sentry/breadcrumb/sentry_logger" if loggers.include?(:sentry_logger)
431
+
432
+ @breadcrumbs_logger = logger
433
+ end
434
+
435
+ def before_send=(value)
436
+ check_callable!("before_send", value)
437
+
438
+ @before_send = value
439
+ end
440
+
441
+ def before_send_transaction=(value)
442
+ check_callable!("before_send_transaction", value)
443
+
444
+ @before_send_transaction = value
445
+ end
446
+
447
+ def before_breadcrumb=(value)
448
+ check_callable!("before_breadcrumb", value)
449
+
450
+ @before_breadcrumb = value
451
+ end
452
+
453
+ def environment=(environment)
454
+ @environment = environment.to_s
455
+ end
456
+
457
+ def instrumenter=(instrumenter)
458
+ @instrumenter = INSTRUMENTERS.include?(instrumenter) ? instrumenter : :sentry
459
+ end
460
+
461
+ def enable_tracing=(enable_tracing)
462
+ @enable_tracing = enable_tracing
463
+ @traces_sample_rate ||= 1.0 if enable_tracing
464
+ end
465
+
466
+ def is_numeric_or_nil?(value)
467
+ value.is_a?(Numeric) || value.nil?
468
+ end
469
+
470
+ def traces_sample_rate=(traces_sample_rate)
471
+ raise ArgumentError, "traces_sample_rate must be a Numeric or nil" unless is_numeric_or_nil?(traces_sample_rate)
472
+ @traces_sample_rate = traces_sample_rate
473
+ end
474
+
475
+ def profiles_sample_rate=(profiles_sample_rate)
476
+ raise ArgumentError, "profiles_sample_rate must be a Numeric or nil" unless is_numeric_or_nil?(profiles_sample_rate)
477
+ log_warn("Please make sure to include the 'stackprof' gem in your Gemfile to use Profiling with Sentry.") unless defined?(StackProf)
478
+ @profiles_sample_rate = profiles_sample_rate
479
+ end
480
+
481
+ def sending_allowed?
482
+ @errors = []
483
+
484
+ spotlight || (valid? && capture_in_environment?)
485
+ end
486
+
487
+ def sample_allowed?
488
+ return true if sample_rate == 1.0
489
+
490
+ Random.rand < sample_rate
491
+ end
492
+
493
+ def exception_class_allowed?(exc)
494
+ if exc.is_a?(Sentry::Error)
495
+ # Try to prevent error reporting loops
496
+ log_debug("Refusing to capture Sentry error: #{exc.inspect}")
497
+ false
498
+ elsif excluded_exception?(exc)
499
+ log_debug("User excluded error: #{exc.inspect}")
500
+ false
501
+ else
502
+ true
503
+ end
504
+ end
505
+
506
+ def enabled_in_current_env?
507
+ enabled_environments.empty? || enabled_environments.include?(environment)
508
+ end
509
+
510
+ def valid_sample_rate?(sample_rate)
511
+ return false unless sample_rate.is_a?(Numeric)
512
+ sample_rate >= 0.0 && sample_rate <= 1.0
513
+ end
514
+
515
+ def tracing_enabled?
516
+ valid_sampler = !!((valid_sample_rate?(@traces_sample_rate)) || @traces_sampler)
517
+
518
+ (@enable_tracing != false) && valid_sampler && sending_allowed?
519
+ end
520
+
521
+ def profiling_enabled?
522
+ valid_sampler = !!(valid_sample_rate?(@profiles_sample_rate))
523
+
524
+ tracing_enabled? && valid_sampler && sending_allowed?
525
+ end
526
+
527
+ # @return [String, nil]
528
+ def csp_report_uri
529
+ if dsn && dsn.valid?
530
+ uri = dsn.csp_report_uri
531
+ uri += "&sentry_release=#{CGI.escape(release)}" if release && !release.empty?
532
+ uri += "&sentry_environment=#{CGI.escape(environment)}" if environment && !environment.empty?
533
+ uri
534
+ end
535
+ end
536
+
537
+ # @api private
538
+ def stacktrace_builder
539
+ @stacktrace_builder ||= StacktraceBuilder.new(
540
+ project_root: @project_root.to_s,
541
+ app_dirs_pattern: @app_dirs_pattern,
542
+ linecache: @linecache,
543
+ context_lines: @context_lines,
544
+ backtrace_cleanup_callback: @backtrace_cleanup_callback
545
+ )
546
+ end
547
+
548
+ # @api private
549
+ def detect_release
550
+ return unless sending_allowed?
551
+
552
+ @release ||= ReleaseDetector.detect_release(project_root: project_root, running_on_heroku: running_on_heroku?)
553
+
554
+ if running_on_heroku? && release.nil?
555
+ log_warn(HEROKU_DYNO_METADATA_MESSAGE)
556
+ end
557
+ rescue => e
558
+ log_error("Error detecting release", e, debug: debug)
559
+ end
560
+
561
+ # @api private
562
+ def error_messages
563
+ @errors = [@errors[0]] + @errors[1..-1].map(&:downcase) # fix case of all but first
564
+ @errors.join(", ")
565
+ end
566
+
567
+ private
568
+
569
+ def check_callable!(name, value)
570
+ unless value == nil || value.respond_to?(:call)
571
+ raise ArgumentError, "#{name} must be callable (or nil to disable)"
572
+ end
573
+ end
574
+
575
+ def init_dsn(dsn_string)
576
+ return if dsn_string.nil? || dsn_string.empty?
577
+
578
+ DSN.new(dsn_string)
579
+ end
580
+
581
+ def excluded_exception?(incoming_exception)
582
+ excluded_exception_classes.any? do |excluded_exception|
583
+ matches_exception?(excluded_exception, incoming_exception)
584
+ end
585
+ end
586
+
587
+ def excluded_exception_classes
588
+ @excluded_exception_classes ||= excluded_exceptions.map { |e| get_exception_class(e) }
589
+ end
590
+
591
+ def get_exception_class(x)
592
+ x.is_a?(Module) ? x : safe_const_get(x)
593
+ end
594
+
595
+ def matches_exception?(excluded_exception_class, incoming_exception)
596
+ if inspect_exception_causes_for_exclusion?
597
+ Sentry::Utils::ExceptionCauseChain.exception_to_array(incoming_exception).any? { |cause| excluded_exception_class === cause }
598
+ else
599
+ excluded_exception_class === incoming_exception
600
+ end
601
+ end
602
+
603
+ def safe_const_get(x)
604
+ x = x.to_s unless x.is_a?(String)
605
+ Object.const_get(x)
606
+ rescue NameError # There's no way to safely ask if a constant exist for an unknown string
607
+ nil
608
+ end
609
+
610
+ def capture_in_environment?
611
+ return true if enabled_in_current_env?
612
+
613
+ @errors << "Not configured to send/capture in environment '#{environment}'"
614
+ false
615
+ end
616
+
617
+ def valid?
618
+ if @dsn&.valid?
619
+ true
620
+ else
621
+ @errors << "DSN not set or not valid"
622
+ false
623
+ end
624
+ end
625
+
626
+ def environment_from_env
627
+ ENV['SENTRY_CURRENT_ENV'] || ENV['SENTRY_ENVIRONMENT'] || ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
628
+ end
629
+
630
+ def server_name_from_env
631
+ if running_on_heroku?
632
+ ENV['DYNO']
633
+ else
634
+ # Try to resolve the hostname to an FQDN, but fall back to whatever
635
+ # the load name is.
636
+ Socket.gethostname || Socket.gethostbyname(hostname).first rescue server_name
637
+ end
638
+ end
639
+
640
+ def running_on_heroku?
641
+ File.directory?("/etc/heroku") && !ENV["CI"]
642
+ end
643
+
644
+ def run_post_initialization_callbacks
645
+ self.class.post_initialization_callbacks.each do |hook|
646
+ instance_eval(&hook)
647
+ end
648
+ end
649
+ end
650
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ return if Object.method_defined?(:deep_dup)
4
+
5
+ require 'sentry/core_ext/object/duplicable'
6
+
7
+ #########################################
8
+ # This file was copied from Rails 5.2 #
9
+ #########################################
10
+
11
+ class Object
12
+ # Returns a deep copy of object if it's duplicable. If it's
13
+ # not duplicable, returns +self+.
14
+ #
15
+ # object = Object.new
16
+ # dup = object.deep_dup
17
+ # dup.instance_variable_set(:@a, 1)
18
+ #
19
+ # object.instance_variable_defined?(:@a) # => false
20
+ # dup.instance_variable_defined?(:@a) # => true
21
+ def deep_dup
22
+ duplicable? ? dup : self
23
+ end
24
+ end
25
+
26
+ class Array
27
+ # Returns a deep copy of array.
28
+ #
29
+ # array = [1, [2, 3]]
30
+ # dup = array.deep_dup
31
+ # dup[1][2] = 4
32
+ #
33
+ # array[1][2] # => nil
34
+ # dup[1][2] # => 4
35
+ def deep_dup
36
+ map(&:deep_dup)
37
+ end
38
+ end
39
+
40
+ class Hash
41
+ # Returns a deep copy of hash.
42
+ #
43
+ # hash = { a: { b: 'b' } }
44
+ # dup = hash.deep_dup
45
+ # dup[:a][:c] = 'c'
46
+ #
47
+ # hash[:a][:c] # => nil
48
+ # dup[:a][:c] # => "c"
49
+ def deep_dup
50
+ hash = dup
51
+ each_pair do |key, value|
52
+ if key.frozen? && ::String === key
53
+ hash[key] = value.deep_dup
54
+ else
55
+ hash.delete(key)
56
+ hash[key.deep_dup] = value.deep_dup
57
+ end
58
+ end
59
+ hash
60
+ end
61
+ end