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