diff --git a/.github/workflows/prepare_raven_release.yml b/.github/workflows/prepare_raven_release.yml deleted file mode 100644 index 871401fcf..000000000 --- a/.github/workflows/prepare_raven_release.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: Prepare Raven Release -on: - workflow_dispatch: - inputs: - version: - description: Version to release - required: true - force: - description: Force a release even when there are release-blockers (optional) - required: false -jobs: - release: - runs-on: ubuntu-latest - name: "Release a new version" - steps: - - name: Get auth token - id: token - uses: actions/create-github-app-token@5d869da34e18e7287c1daad50e0b8ea0f506ce69 # v1.11.0 - with: - app-id: ${{ vars.SENTRY_RELEASE_BOT_CLIENT_ID }} - private-key: ${{ secrets.SENTRY_RELEASE_BOT_PRIVATE_KEY }} - - uses: actions/checkout@v4 - with: - token: ${{ steps.token.outputs.token }} - fetch-depth: 0 - - name: Prepare release - uses: getsentry/action-prepare-release@v1 - env: - GITHUB_TOKEN: ${{ steps.token.outputs.token }} - with: - path: sentry-raven - version: ${{ github.event.inputs.version }} - force: ${{ github.event.inputs.force }} diff --git a/.github/workflows/sentry_raven_test.yml b/.github/workflows/sentry_raven_test.yml deleted file mode 100644 index 5e9cff21a..000000000 --- a/.github/workflows/sentry_raven_test.yml +++ /dev/null @@ -1,69 +0,0 @@ -name: sentry-raven Test - -on: - workflow_dispatch: - push: - branches: - - master - pull_request: - paths: - - "sentry-raven/**" - - ".github/workflows/sentry_raven_test.yml" -# Cancel in progress workflows on pull_requests. -# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-using-a-fallback-value -concurrency: - group: sentry-raven-test-${{ github.head_ref || github.run_id }} - cancel-in-progress: true -jobs: - test: - defaults: - run: - working-directory: sentry-raven - name: Test on ruby ${{ matrix.ruby_version }} and rails ${{ matrix.rails_version }} - runs-on: ubuntu-latest - strategy: - matrix: - rails_version: [0, 4.2, 5.2, 6.0.0] - ruby_version: [2.3, 2.4, 2.5, 2.6, 2.7, "3.0", jruby-9.3] - include: - - ruby_version: "3.0" - rails_version: 0 - - ruby_version: 2.7 - rails_version: 6.0.0 - env: RUBYOPT="--enable-frozen-string-literal --debug=frozen-string-literal" - exclude: - - ruby_version: 2.3 - rails_version: 6.0.0 - - ruby_version: 2.4 - rails_version: 6.0.0 - - ruby_version: 2.7 - rails_version: 4.2 - - ruby_version: jruby-9.3 - rails_version: 4.2 - - ruby_version: "3.0" - rails_version: 4.2 - - ruby_version: "3.0" - rails_version: 5.2 - - ruby_version: "3.0" - rails_version: 6.0.0 - - steps: - - uses: actions/checkout@v4 - - - name: Set up Ruby ${{ matrix.ruby_version }} - uses: ruby/setup-ruby@v1 - with: - bundler: 1 - ruby-version: ${{ matrix.ruby_version }} - - - name: Start Redis - uses: supercharge/redis-github-action@1.1.0 - with: - redis-version: 5 - - - name: Build with Rails ${{ matrix.rails_version }} - env: - RAILS_VERSION: ${{ matrix.rails_version }} - run: | - bundle install --jobs 4 --retry 3 - bundle exec rake diff --git a/.gitignore b/.gitignore index 83704eaa9..f5a971c3b 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ Gemfile.lock .idea *.rdb .rgignore +.claude node_modules .vite diff --git a/.rubocop.yml b/.rubocop.yml index 90aa1da71..3ffbe4177 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -15,7 +15,6 @@ Style/RedundantFreeze: AllCops: Exclude: - - "sentry-raven/**/*" - "sentry-*/tmp/**/*" - "sentry-*/examples/**/*" - "sentry-*/spec/versioned/2.7/**/*" diff --git a/.scripts/bump-version.rb b/.scripts/bump-version.rb deleted file mode 100755 index 57a0b6fc2..000000000 --- a/.scripts/bump-version.rb +++ /dev/null @@ -1,20 +0,0 @@ -ref_name = `git branch --show-current` -sdk_name_capture_regex = /release-(sentry-\w+)\/.*/ - -file_name = - if sdk_name_match = ref_name.match(sdk_name_capture_regex) - case sdk_name = sdk_name_match[1] - when "sentry-ruby" - "lib/sentry/version.rb" - else - integration_name = sdk_name.sub("sentry-", "") - "lib/sentry/#{integration_name}/version.rb" - end - else - # old SDK - "lib/raven/version.rb" - end - -text = File.read(file_name) -new_contents = text.gsub(/VERSION = ".*"/, "VERSION = \"#{ARGV[1]}\"") -File.open(file_name, "w") {|file| file.puts new_contents } diff --git a/CHANGELOG.md b/CHANGELOG.md index 6451cefc9..a52fc6cff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,40 @@ +## Unreleased (6.0.0) + +### Breaking Changes + +- Remove deprecated `config.async` [#1894](https://github.com/getsentry/sentry-ruby/pull/1894) +- Remove deprecated `Sentry::Metrics` and `config.metrics` and all metrics related code ([#2729](https://github.com/getsentry/sentry-ruby/pull/2729)) +- Remove deprecated `config.capture_exception_frame_locals`, use `include_local_variables` instead ([#2730](https://github.com/getsentry/sentry-ruby/pull/2730)) +- Remove deprecated `config.enable_tracing`, use `config.traces_sample_rate = 1.0` instead ([#2731](https://github.com/getsentry/sentry-ruby/pull/2731)) +- Remove deprecated `config.logger=`, use `config.sdk_logger=` instead ([#2732](https://github.com/getsentry/sentry-ruby/pull/2732)) +- Remove deprecated `Sentry::Rails::Tracing::ActionControllerSubscriber` ([#2733](https://github.com/getsentry/sentry-ruby/pull/2733)) +- Remove `:monotonic_active_support_logger` from `config.breadcrumbs_logger` ([#2717](https://github.com/getsentry/sentry-ruby/pull/2717)) +- Migrate from to_hash to to_h ([#2351](https://github.com/getsentry/sentry-ruby/pull/2351)) +- Add `before_send_check_in` for applying to `CheckInEvent` ([#2703](https://github.com/getsentry/sentry-ruby/pull/2703)) +- Returning a hash from `before_send` and `before_send_transaction` is no longer supported and will drop the event. +- Remove stacktrace trimming ([#2714](https://github.com/getsentry/sentry-ruby/pull/2714)) +- `config.enabled_environments` now defaults to `nil` instead of `[]` for sending to all environments ([#2716](https://github.com/getsentry/sentry-ruby/pull/2716)) +- Requests which have response status codes in the inclusive ranges `[(301..303), (305..399), (401..404)]` will no longer create transactions by default. See `config.trace_ignore_status_codes` below to control what gets traced. + +### Features + +- Add `config.trace_ignore_status_codes` to control which response codes to ignore for tracing ([#2725](https://github.com/getsentry/sentry-ruby/pull/2725)) + + You can pass in an Array of individual status codes or ranges of status codes. + + ```ruby + Sentry.init do |config| + # ... + # will ignore 404, 501, 502, 503 + config.trace_ignore_status_codes = [404, (501..503)] + end + ``` + +### Internal + +- Archive [`sentry-raven`](https://github.com/getsentry/raven-ruby) ([#2708](https://github.com/getsentry/sentry-ruby/pull/2708)) +- Don't send `sample_rate` client reports for profiles if profiling is disabled ([#2728](https://github.com/getsentry/sentry-ruby/pull/2728)) + ## 5.28.0 ### Features @@ -7,7 +44,7 @@ ### Miscellaneous - Deprecate all Metrics related APIs [#2726](https://github.com/getsentry/sentry-ruby/pull/2726) - + Sentry [no longer has the Metrics Beta offering](https://sentry.zendesk.com/hc/en-us/articles/26369339769883-Metrics-Beta-Ended-on-October-7th) so all the following APIs linked to Metrics have been deprecated and will be removed in the next major. diff --git a/sentry-delayed_job/spec/sentry/delayed_job_spec.rb b/sentry-delayed_job/spec/sentry/delayed_job_spec.rb index 24a1de77d..4d4febe58 100644 --- a/sentry-delayed_job/spec/sentry/delayed_job_spec.rb +++ b/sentry-delayed_job/spec/sentry/delayed_job_spec.rb @@ -46,7 +46,7 @@ def do_nothing_with_args(a) enqueued_job.invoke_job expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:message]).to eq("report") expect(event[:contexts][:"Delayed-Job"][:id]).to eq(enqueued_job.id.to_s) expect(event[:tags]).to eq({ "delayed_job.id" => enqueued_job.id.to_s, "delayed_job.queue" => nil }) @@ -68,7 +68,7 @@ def do_nothing_with_args(a) enqueued_job.invoke_job expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:message]).to eq("tagged report") expect(event[:tags]).to eq({ "delayed_job.id" => enqueued_job.id.to_s, "delayed_job.queue" => nil, number: 1 }) @@ -77,7 +77,7 @@ def do_nothing_with_args(a) enqueued_job.invoke_job expect(transport.events.count).to eq(2) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:tags]).to eq({ "delayed_job.id" => enqueued_job.id.to_s, "delayed_job.queue" => nil }) end @@ -93,7 +93,7 @@ def do_nothing_with_args(a) end.to raise_error(ZeroDivisionError) expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:sdk]).to eq({ name: "sentry.ruby.delayed_job", version: described_class::VERSION }) expect(event.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") @@ -109,7 +109,7 @@ def do_nothing_with_args(a) end.to raise_error(RuntimeError) expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:tags]).to eq({ "delayed_job.id" => enqueued_job.id.to_s, "delayed_job.queue" => nil, number: 1 }) expect(Sentry.get_current_scope.extra).to eq({}) @@ -123,7 +123,7 @@ def do_nothing_with_args(a) end.to raise_error(ZeroDivisionError) expect(transport.events.count).to eq(2) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:tags]).to eq({ "delayed_job.id" => enqueued_job.id.to_s, "delayed_job.queue" => nil }) expect(Sentry.get_current_scope.extra).to eq({}) expect(Sentry.get_current_scope.tags).to eq({}) @@ -228,7 +228,7 @@ def perform it "injects ActiveJob information to the event" do expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:message]).to eq("report from ActiveJob") expect(event[:tags]).to match({ "delayed_job.id" => anything, "delayed_job.queue" => "default", number: 1 }) expect(event[:contexts][:"Active-Job"][:job_class]).to eq("ReportingJob") @@ -255,7 +255,7 @@ def perform it "injects ActiveJob information to the event" do expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") expect(event[:tags]).to match({ "delayed_job.id" => anything, "delayed_job.queue" => "default", number: 2 }) expect(event[:contexts][:"Active-Job"][:job_class]).to eq("FailedJob") diff --git a/sentry-rails/benchmarks/allocation_comparison.rb b/sentry-rails/benchmarks/allocation_comparison.rb index 15b1e3c4a..4e96eda35 100644 --- a/sentry-rails/benchmarks/allocation_comparison.rb +++ b/sentry-rails/benchmarks/allocation_comparison.rb @@ -11,7 +11,7 @@ end app = create_app do |config| - config.logger = ::Logger.new(STDOUT) + config.sdk_logger = ::Logger.new(STDOUT) config.transport.transport_class = Sentry::BenchmarkTransport config.breadcrumbs_logger = [:active_support_logger] end diff --git a/sentry-rails/benchmarks/allocation_report.rb b/sentry-rails/benchmarks/allocation_report.rb index 9bc691a26..6e0bc1d02 100644 --- a/sentry-rails/benchmarks/allocation_report.rb +++ b/sentry-rails/benchmarks/allocation_report.rb @@ -11,7 +11,7 @@ end app = create_app do |config| - config.logger = ::Logger.new(STDOUT) + config.sdk_logger = ::Logger.new(STDOUT) config.transport.transport_class = Sentry::BenchmarkTransport config.breadcrumbs_logger = [:active_support_logger] end diff --git a/sentry-rails/examples/minimum-rails/app.rb b/sentry-rails/examples/minimum-rails/app.rb index e100e5395..92bab5647 100644 --- a/sentry-rails/examples/minimum-rails/app.rb +++ b/sentry-rails/examples/minimum-rails/app.rb @@ -15,7 +15,7 @@ Sentry.init do |config| config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472' - config.logger = Logger.new($stdout) + config.sdk_logger = Logger.new($stdout) end ActiveSupport::Deprecation.silenced = true diff --git a/sentry-rails/examples/rails-6.0/config/initializers/sentry.rb b/sentry-rails/examples/rails-6.0/config/initializers/sentry.rb index c0b0d08fb..70cb1aa18 100644 --- a/sentry-rails/examples/rails-6.0/config/initializers/sentry.rb +++ b/sentry-rails/examples/rails-6.0/config/initializers/sentry.rb @@ -5,7 +5,7 @@ config.traces_sample_rate = 1.0 # set a float between 0.0 and 1.0 to enable performance monitoring config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472' config.release = `git branch --show-current` - config.capture_exception_frame_locals = true + config.include_local_variables = true # you can use the pre-defined job for the async callback # # config.async = lambda do |event, hint| diff --git a/sentry-rails/examples/rails-7.0/config/initializers/sentry.rb b/sentry-rails/examples/rails-7.0/config/initializers/sentry.rb index c0b0d08fb..70cb1aa18 100644 --- a/sentry-rails/examples/rails-7.0/config/initializers/sentry.rb +++ b/sentry-rails/examples/rails-7.0/config/initializers/sentry.rb @@ -5,7 +5,7 @@ config.traces_sample_rate = 1.0 # set a float between 0.0 and 1.0 to enable performance monitoring config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472' config.release = `git branch --show-current` - config.capture_exception_frame_locals = true + config.include_local_variables = true # you can use the pre-defined job for the async callback # # config.async = lambda do |event, hint| diff --git a/sentry-rails/lib/sentry/rails/active_job.rb b/sentry-rails/lib/sentry/rails/active_job.rb index 2f5a134d0..df7f27ecd 100644 --- a/sentry-rails/lib/sentry/rails/active_job.rb +++ b/sentry-rails/lib/sentry/rails/active_job.rb @@ -32,17 +32,13 @@ def record(job, &block) Sentry.with_scope do |scope| begin scope.set_transaction_name(job.class.name, source: :task) - transaction = - if job.is_a?(::Sentry::SendEventJob) - nil - else - Sentry.start_transaction( - name: scope.transaction_name, - source: scope.transaction_source, - op: OP_NAME, - origin: SPAN_ORIGIN - ) - end + + transaction = Sentry.start_transaction( + name: scope.transaction_name, + source: scope.transaction_source, + op: OP_NAME, + origin: SPAN_ORIGIN + ) scope.set_span(transaction) if transaction diff --git a/sentry-rails/lib/sentry/rails/breadcrumb/monotonic_active_support_logger.rb b/sentry-rails/lib/sentry/rails/breadcrumb/monotonic_active_support_logger.rb deleted file mode 100644 index 541f9bea3..000000000 --- a/sentry-rails/lib/sentry/rails/breadcrumb/monotonic_active_support_logger.rb +++ /dev/null @@ -1,46 +0,0 @@ -# frozen_string_literal: true - -require "sentry/rails/instrument_payload_cleanup_helper" - -module Sentry - module Rails - module Breadcrumb - module MonotonicActiveSupportLogger - class << self - include InstrumentPayloadCleanupHelper - - def add(name, started, _finished, _unique_id, data) - # skip Rails' internal events - return if name.start_with?("!") - - if data.is_a?(Hash) - # we should only mutate the copy of the data - data = data.dup - cleanup_data(data) - end - - crumb = Sentry::Breadcrumb.new( - data: data, - category: name, - timestamp: started.to_i - ) - Sentry.add_breadcrumb(crumb) - end - - def inject - @subscriber = ::ActiveSupport::Notifications.monotonic_subscribe(/.*/) do |name, started, finished, unique_id, data| - # we only record events that has a float as started timestamp - if started.is_a?(Float) - add(name, started, finished, unique_id, data) - end - end - end - - def detach - ::ActiveSupport::Notifications.unsubscribe(@subscriber) - end - end - end - end - end -end diff --git a/sentry-rails/lib/sentry/rails/configuration.rb b/sentry-rails/lib/sentry/rails/configuration.rb index 7b27a9152..42306e07f 100644 --- a/sentry-rails/lib/sentry/rails/configuration.rb +++ b/sentry-rails/lib/sentry/rails/configuration.rb @@ -1,6 +1,5 @@ # frozen_string_literal: true -require "sentry/rails/tracing/action_controller_subscriber" require "sentry/rails/tracing/action_view_subscriber" require "sentry/rails/tracing/active_record_subscriber" require "sentry/rails/tracing/active_storage_subscriber" diff --git a/sentry-rails/lib/sentry/rails/instrument_payload_cleanup_helper.rb b/sentry-rails/lib/sentry/rails/instrument_payload_cleanup_helper.rb deleted file mode 100644 index 07422c5e8..000000000 --- a/sentry-rails/lib/sentry/rails/instrument_payload_cleanup_helper.rb +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true - -module Sentry - module Rails - module InstrumentPayloadCleanupHelper - IGNORED_DATA_TYPES = [:request, :response, :headers, :exception, :exception_object, Tracing::START_TIMESTAMP_NAME] - - def cleanup_data(data) - IGNORED_DATA_TYPES.each do |key| - data.delete(key) if data.key?(key) - end - end - end - end -end diff --git a/sentry-rails/lib/sentry/rails/overrides/streaming_reporter.rb b/sentry-rails/lib/sentry/rails/overrides/streaming_reporter.rb index 1fdd4ad60..d1bc1b1dd 100644 --- a/sentry-rails/lib/sentry/rails/overrides/streaming_reporter.rb +++ b/sentry-rails/lib/sentry/rails/overrides/streaming_reporter.rb @@ -9,17 +9,6 @@ def log_error(exception) super end end - - module OldStreamingReporter - def self.included(base) - base.send(:alias_method_chain, :log_error, :raven) - end - - def log_error_with_raven(exception) - Sentry::Rails.capture_exception(exception) - log_error_without_raven(exception) - end - end end end end diff --git a/sentry-rails/lib/sentry/rails/railtie.rb b/sentry-rails/lib/sentry/rails/railtie.rb index b514df3cd..a86093768 100644 --- a/sentry-rails/lib/sentry/rails/railtie.rb +++ b/sentry-rails/lib/sentry/rails/railtie.rb @@ -101,17 +101,12 @@ def patch_background_worker end def inject_breadcrumbs_logger - if Sentry.configuration.breadcrumbs_logger.include?(:active_support_logger) + if Sentry.configuration.breadcrumbs_logger.include?(:active_support_logger) || + ## legacy name redirected for backwards compat + Sentry.configuration.breadcrumbs_logger.include?(:monotonic_active_support_logger) require "sentry/rails/breadcrumb/active_support_logger" Sentry::Rails::Breadcrumb::ActiveSupportLogger.inject(Sentry.configuration.rails.active_support_logger_subscription_items) end - - if Sentry.configuration.breadcrumbs_logger.include?(:monotonic_active_support_logger) - return warn "Usage of `monotonic_active_support_logger` require a version of Rails >= 6.1, please upgrade your Rails version or use another logger" if ::Rails.version.to_f < 6.1 - - require "sentry/rails/breadcrumb/monotonic_active_support_logger" - Sentry::Rails::Breadcrumb::MonotonicActiveSupportLogger.inject - end end def setup_backtrace_cleanup_callback diff --git a/sentry-rails/lib/sentry/rails/tracing/action_controller_subscriber.rb b/sentry-rails/lib/sentry/rails/tracing/action_controller_subscriber.rb deleted file mode 100644 index 996332bb5..000000000 --- a/sentry-rails/lib/sentry/rails/tracing/action_controller_subscriber.rb +++ /dev/null @@ -1,43 +0,0 @@ -# frozen_string_literal: true - -require "sentry/rails/tracing/abstract_subscriber" -require "sentry/rails/instrument_payload_cleanup_helper" - -module Sentry - module Rails - module Tracing - class ActionControllerSubscriber < AbstractSubscriber - extend InstrumentPayloadCleanupHelper - - EVENT_NAMES = ["process_action.action_controller"].freeze - OP_NAME = "view.process_action.action_controller" - SPAN_ORIGIN = "auto.view.rails" - - def self.subscribe! - Sentry.sdk_logger.warn <<~MSG - DEPRECATION WARNING: sentry-rails has changed its approach on controller span recording and #{self.name} is now depreacted. - Please stop using or referencing #{self.name} as it will be removed in the next major release. - MSG - - subscribe_to_event(EVENT_NAMES) do |event_name, duration, payload| - controller = payload[:controller] - action = payload[:action] - - record_on_current_span( - op: OP_NAME, - origin: SPAN_ORIGIN, - start_timestamp: payload[START_TIMESTAMP_NAME], - description: "#{controller}##{action}", - duration: duration - ) do |span| - payload = payload.dup - cleanup_data(payload) - span.set_data(:payload, payload) - span.set_http_status(payload[:status]) - end - end - end - end - end - end -end diff --git a/sentry-rails/spec/dummy/test_rails_app/app.rb b/sentry-rails/spec/dummy/test_rails_app/app.rb index 42f4d8d04..85eadf39b 100644 --- a/sentry-rails/spec/dummy/test_rails_app/app.rb +++ b/sentry-rails/spec/dummy/test_rails_app/app.rb @@ -105,7 +105,7 @@ def self.name config.transport.transport_class = Sentry::DummyTransport # for sending events synchronously config.background_worker_threads = 0 - config.capture_exception_frame_locals = true + config.include_local_variables = true yield(config, app) if block_given? end end diff --git a/sentry-rails/spec/sentry/rails/activejob_spec.rb b/sentry-rails/spec/sentry/rails/activejob_spec.rb index 8431bffff..c7f6c423a 100644 --- a/sentry-rails/spec/sentry/rails/activejob_spec.rb +++ b/sentry-rails/spec/sentry/rails/activejob_spec.rb @@ -229,50 +229,6 @@ def perform event = transport.events.last.to_json_compatible expect(event.dig("exception", "values", 0, "type")).to eq("ZeroDivisionError") end - - context "and in user-defined reporting job too" do - before do - Sentry.configuration.async = lambda do |event, hint| - UserDefinedReportingJob.perform_now(event, hint) - end - end - - class UserDefinedReportingJob < ActiveJob::Base - def perform(event, hint) - Post.find(0) - rescue - raise ActiveJob::DeserializationError - end - end - - it "doesn't cause infinite loop because of excluded exceptions" do - expect do - DeserializationErrorJob.perform_now - end.to raise_error(ActiveJob::DeserializationError, /divided by 0/) - end - end - - context "and in customized SentryJob too" do - before do - class CustomSentryJob < ::Sentry::SendEventJob - def perform(event, hint) - raise "Not excluded exception" - rescue - raise ActiveJob::DeserializationError - end - end - - Sentry.configuration.async = lambda do |event, hint| - CustomSentryJob.perform_now(event, hint) - end - end - - it "doesn't cause infinite loop" do - expect do - DeserializationErrorJob.perform_now - end.to raise_error(ActiveJob::DeserializationError, /divided by 0/) - end - end end context 'using rescue_from' do @@ -293,7 +249,7 @@ def perform(event, hint) expect(transport.events.size).to eq(1) event = transport.events.first - exceptions_data = event.exception.to_hash[:values] + exceptions_data = event.exception.to_h[:values] expect(exceptions_data.count).to eq(2) expect(exceptions_data[0][:type]).to eq("FailedJob::TestError") @@ -331,7 +287,7 @@ def perform(event, hint) first = transport.events[0] check_in_id = first.check_in_id expect(first).to be_a(Sentry::CheckInEvent) - expect(first.to_hash).to include( + expect(first.to_h).to include( type: 'check_in', check_in_id: check_in_id, monitor_slug: "normaljobwithcron", @@ -340,7 +296,7 @@ def perform(event, hint) second = transport.events[1] expect(second).to be_a(Sentry::CheckInEvent) - expect(second.to_hash).to include( + expect(second.to_h).to include( :duration, type: 'check_in', check_in_id: check_in_id, @@ -359,7 +315,7 @@ def perform(event, hint) first = transport.events[0] check_in_id = first.check_in_id expect(first).to be_a(Sentry::CheckInEvent) - expect(first.to_hash).to include( + expect(first.to_h).to include( type: 'check_in', check_in_id: check_in_id, monitor_slug: "failed_job", @@ -369,7 +325,7 @@ def perform(event, hint) second = transport.events[1] expect(second).to be_a(Sentry::CheckInEvent) - expect(second.to_hash).to include( + expect(second.to_h).to include( :duration, type: 'check_in', check_in_id: check_in_id, diff --git a/sentry-rails/spec/sentry/rails/breadcrumbs/active_support_logger_spec.rb b/sentry-rails/spec/sentry/rails/breadcrumbs/active_support_logger_spec.rb index e6a0ae6e3..2fb493793 100644 --- a/sentry-rails/spec/sentry/rails/breadcrumbs/active_support_logger_spec.rb +++ b/sentry-rails/spec/sentry/rails/breadcrumbs/active_support_logger_spec.rb @@ -93,6 +93,33 @@ end end + context "redirects legacy :monotonic_active_support_logger" do + before do + make_basic_app do |sentry_config| + sentry_config.breadcrumbs_logger = [:monotonic_active_support_logger] + end + end + + it "captures correct data of exception requests" do + get "/exception" + + expect(response.status).to eq(500) + breadcrumbs = event.dig("breadcrumbs", "values") + expect(breadcrumbs.count).to eq(2) + + breadcrumb = breadcrumbs.detect { |b| b["category"] == "process_action.action_controller" } + expect(breadcrumb["data"]).to include( + { + "controller" => "HelloController", + "action" => "exception", + "params" => { "controller" => "hello", "action" => "exception" }, + "format" => "html", + "method" => "GET", "path" => "/exception" + } + ) + end + end + context "with tracing" do before do make_basic_app do |sentry_config| @@ -130,7 +157,7 @@ expect(transport.events.count).to eq(1) - transaction = transport.events.last.to_hash + transaction = transport.events.last.to_h breadcrumbs = transaction[:breadcrumbs][:values] process_action_crumb = breadcrumbs.last expect(process_action_crumb[:category]).to eq("process_action.action_controller") diff --git a/sentry-rails/spec/sentry/rails/breadcrumbs/monotonic_active_support_logger_spec.rb b/sentry-rails/spec/sentry/rails/breadcrumbs/monotonic_active_support_logger_spec.rb deleted file mode 100644 index 031443c25..000000000 --- a/sentry-rails/spec/sentry/rails/breadcrumbs/monotonic_active_support_logger_spec.rb +++ /dev/null @@ -1,145 +0,0 @@ -# frozen_string_literal: true - -require "spec_helper" - - -RSpec.describe "Sentry::Breadcrumbs::MonotonicActiveSupportLogger", type: :request do - after do - # even though we cleanup breadcrumbs in the rack middleware - # Breadcrumbs::MonotonicActiveSupportLogger subscribes to "every" instrumentation - # so it'll create other instrumentations "after" the request is finished - # and we should clear those as well - Sentry.get_current_scope.clear_breadcrumbs - end - - let(:transport) do - Sentry.get_current_client.transport - end - - let(:breadcrumb_buffer) do - Sentry.get_current_scope.breadcrumbs - end - - let(:event) do - transport.events.first.to_json_compatible - end - context "without tracing" do - before do - make_basic_app do |sentry_config| - sentry_config.breadcrumbs_logger = [:monotonic_active_support_logger] - end - end - - context "given a Rails version < 6.1", skip: Rails.version.to_f >= 6.1 do - it "does not run instrumentation" do - get "/exception" - - breadcrumbs = event.dig("breadcrumbs", "values") - expect(breadcrumbs.count).to be_zero - end - end - - context "given a Rails version >= 6.1", skip: Rails.version.to_f < 6.1 do - after do - Sentry::Rails::Breadcrumb::MonotonicActiveSupportLogger.detach - end - - it "captures correct data of exception requests" do - get "/exception" - - expect(response.status).to eq(500) - breadcrumbs = event.dig("breadcrumbs", "values") - expect(breadcrumbs.count).to eq(2) - - breadcrumb = breadcrumbs.detect { |b| b["category"] == "process_action.action_controller" } - expect(breadcrumb["data"]).to include( - { - "controller" => "HelloController", - "action" => "exception", - "params" => { "controller" => "hello", "action" => "exception" }, - "format" => "html", - "method" => "GET", "path" => "/exception" - } - ) - expect(breadcrumb["data"].keys).not_to include("headers") - expect(breadcrumb["data"].keys).not_to include("request") - expect(breadcrumb["data"].keys).not_to include("response") - end - - it "ignores exception data" do - get "/view_exception" - - expect(event.dig("breadcrumbs", "values", -1, "data").keys).not_to include("exception") - expect(event.dig("breadcrumbs", "values", -1, "data").keys).not_to include("exception_object") - end - - it "ignores events that doesn't have a float as started attributes" do - expect do - ActiveSupport::Notifications.publish "foo", Time.now - end.not_to raise_error - - expect(breadcrumb_buffer.count).to be_zero - end - end - end - - context "with tracing" do - before do - make_basic_app do |sentry_config| - sentry_config.breadcrumbs_logger = [:monotonic_active_support_logger] - sentry_config.traces_sample_rate = 1.0 - end - end - - context "given a Rails version < 6.1", skip: Rails.version.to_f >= 6.1 do - it "does not run instrumentation" do - get "/exception" - - breadcrumbs = event.dig("breadcrumbs", "values") - expect(breadcrumbs.count).to be_zero - end - end - - context "given a Rails version >= 6.1", skip: Rails.version.to_f < 6.1 do - after do - Sentry::Rails::Breadcrumb::MonotonicActiveSupportLogger.detach - end - - it "captures correct request data of normal requests" do - p = Post.create! - - get "/posts/#{p.id}" - - breadcrumbs = event.dig("breadcrumbs", "values") - - breadcrumb = breadcrumbs.detect { |b| b["category"] == "process_action.action_controller" } - expect(breadcrumb["data"]).to include( - { - "controller" => "PostsController", - "action" => "show", - "params" => { "controller" => "posts", "action" => "show", "id" => p.id.to_s }, - "format" => "html", - "method" => "GET", "path" => "/posts/#{p.id}" - } - ) - expect(breadcrumb["data"].keys).not_to include("headers") - expect(breadcrumb["data"].keys).not_to include("request") - expect(breadcrumb["data"].keys).not_to include("response") - end - - it "doesn't add internal start timestamp payload to breadcrumbs data" do - p = Post.create! - - get "/posts/#{p.id}" - - expect(transport.events.count).to eq(1) - - transaction = transport.events.last.to_hash - breadcrumbs = transaction[:breadcrumbs][:values] - process_action_crumb = breadcrumbs.last - expect(process_action_crumb[:category]).to eq("process_action.action_controller") - expect(process_action_crumb[:data].has_key?(Sentry::Rails::Tracing::START_TIMESTAMP_NAME)).to eq(false) - end - end - end -end diff --git a/sentry-rails/spec/sentry/rails/controller_methods_spec.rb b/sentry-rails/spec/sentry/rails/controller_methods_spec.rb index 6254dc290..0f9c82af6 100644 --- a/sentry-rails/spec/sentry/rails/controller_methods_spec.rb +++ b/sentry-rails/spec/sentry/rails/controller_methods_spec.rb @@ -37,7 +37,7 @@ def request event = transport.events.last expect(event.message).to eq("foo") expect(event.tags).to eq({ new_tag: true }) - expect(event.to_hash.dig(:request, :url)).to eq("http://example.org/test") + expect(event.to_h.dig(:request, :url)).to eq("http://example.org/test") end end @@ -49,8 +49,8 @@ def request event = transport.events.last expect(event.tags).to eq({ new_tag: true }) - expect(event.to_hash.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") - expect(event.to_hash.dig(:request, :url)).to eq("http://example.org/test") + expect(event.to_h.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") + expect(event.to_h.dig(:request, :url)).to eq("http://example.org/test") end end end diff --git a/sentry-rails/spec/sentry/rails/event_spec.rb b/sentry-rails/spec/sentry/rails/event_spec.rb index 8dc969d08..92db6f0c3 100644 --- a/sentry-rails/spec/sentry/rails/event_spec.rb +++ b/sentry-rails/spec/sentry/rails/event_spec.rb @@ -8,7 +8,7 @@ end it "sets right SDK information" do - event_hash = Sentry::Rails.capture_message("foo").to_hash + event_hash = Sentry::Rails.capture_message("foo").to_h expect(event_hash[:sdk]).to eq(name: "sentry.ruby.rails", version: Sentry::Rails::VERSION) end @@ -27,7 +27,7 @@ e end - let(:hash) { Sentry::Rails.capture_exception(exception).to_hash } + let(:hash) { Sentry::Rails.capture_exception(exception).to_h } it 'marks in_app correctly' do frames = hash[:exception][:values][0][:stacktrace][:frames] diff --git a/sentry-rails/spec/sentry/rails/tracing/action_controller_subscriber_spec.rb b/sentry-rails/spec/sentry/rails/tracing/action_controller_subscriber_spec.rb deleted file mode 100644 index 59c69f849..000000000 --- a/sentry-rails/spec/sentry/rails/tracing/action_controller_subscriber_spec.rb +++ /dev/null @@ -1,65 +0,0 @@ -# frozen_string_literal: true - -require "spec_helper" - -RSpec.describe Sentry::Rails::Tracing::ActionControllerSubscriber, :subscriber, type: :request do - let(:transport) do - Sentry.get_current_client.transport - end - - context "when transaction is sampled" do - let(:string_io) { StringIO.new } - let(:logger) do - ::Logger.new(string_io) - end - - before do - make_basic_app do |config| - config.traces_sample_rate = 1.0 - config.rails.tracing_subscribers = [described_class] - config.sdk_logger = logger - end - end - - it "logs deprecation message" do - expect(string_io.string).to include( - "DEPRECATION WARNING: sentry-rails has changed its approach on controller span recording and Sentry::Rails::Tracing::ActionControllerSubscriber is now depreacted." - ) - end - - it "records controller action processing event" do - get "/world" - - expect(transport.events.count).to eq(1) - - transaction = transport.events.first.to_hash - expect(transaction[:type]).to eq("transaction") - expect(transaction[:spans].count).to eq(2) - - span = transaction[:spans][0] - expect(span[:op]).to eq("view.process_action.action_controller") - expect(span[:origin]).to eq("auto.view.rails") - expect(span[:description]).to eq("HelloController#world") - expect(span[:trace_id]).to eq(transaction.dig(:contexts, :trace, :trace_id)) - expect(span[:data].keys).to match_array(["http.response.status_code", :format, :method, :path, :params]) - end - end - - context "when transaction is not sampled" do - before do - make_basic_app - end - - it "doesn't record spans" do - transaction = Sentry::Transaction.new(sampled: false, hub: Sentry.get_current_hub) - Sentry.get_current_scope.set_span(transaction) - - get "/world" - - transaction.finish - - expect(transport.events.count).to eq(0) - expect(transaction.span_recorder.spans).to eq([transaction]) - end - end -end diff --git a/sentry-rails/spec/sentry/rails/tracing/action_view_subscriber_spec.rb b/sentry-rails/spec/sentry/rails/tracing/action_view_subscriber_spec.rb index 555584024..dba6c9546 100644 --- a/sentry-rails/spec/sentry/rails/tracing/action_view_subscriber_spec.rb +++ b/sentry-rails/spec/sentry/rails/tracing/action_view_subscriber_spec.rb @@ -20,7 +20,7 @@ expect(transport.events.count).to eq(1) - transaction = transport.events.first.to_hash + transaction = transport.events.first.to_h expect(transaction[:type]).to eq("transaction") expect(transaction[:spans].count).to eq(2) diff --git a/sentry-rails/spec/sentry/rails/tracing/active_record_subscriber_spec.rb b/sentry-rails/spec/sentry/rails/tracing/active_record_subscriber_spec.rb index be674869f..026b2121d 100644 --- a/sentry-rails/spec/sentry/rails/tracing/active_record_subscriber_spec.rb +++ b/sentry-rails/spec/sentry/rails/tracing/active_record_subscriber_spec.rb @@ -30,7 +30,7 @@ expect(transport.events.count).to eq(1) - transaction = transport.events.first.to_hash + transaction = transport.events.first.to_h expect(transaction[:type]).to eq("transaction") expect(transaction[:spans].count).to eq(1) @@ -68,7 +68,7 @@ def foo it "doesn't record query's source location" do expect(transport.events.count).to eq(1) - transaction = transport.events.first.to_hash + transaction = transport.events.first.to_h expect(transaction[:type]).to eq("transaction") expect(transaction[:spans].count).to eq(1) @@ -87,7 +87,7 @@ def foo it "records query's source location" do expect(transport.events.count).to eq(1) - transaction = transport.events.first.to_hash + transaction = transport.events.first.to_h expect(transaction[:type]).to eq("transaction") expect(transaction[:spans].count).to eq(1) @@ -106,7 +106,7 @@ def foo it "doesn't record query's source location" do expect(transport.events.count).to eq(1) - transaction = transport.events.first.to_hash + transaction = transport.events.first.to_h expect(transaction[:type]).to eq("transaction") expect(transaction[:spans].count).to eq(1) @@ -133,7 +133,7 @@ def foo expect(transport.events.count).to eq(1) - transaction = transport.events.first.to_hash + transaction = transport.events.first.to_h expect(transaction[:type]).to eq("transaction") expect(transaction[:spans].count).to eq(2) diff --git a/sentry-rails/spec/sentry/rails/tracing/active_storage_subscriber_spec.rb b/sentry-rails/spec/sentry/rails/tracing/active_storage_subscriber_spec.rb index 9e93f2c8f..9a8a63b5a 100644 --- a/sentry-rails/spec/sentry/rails/tracing/active_storage_subscriber_spec.rb +++ b/sentry-rails/spec/sentry/rails/tracing/active_storage_subscriber_spec.rb @@ -25,7 +25,7 @@ expect(response).to have_http_status(:ok) expect(transport.events.count).to eq(2) - analysis_transaction = transport.events.first.to_hash + analysis_transaction = transport.events.first.to_h expect(analysis_transaction[:type]).to eq("transaction") if Rails.version.to_f > 6.1 @@ -40,7 +40,7 @@ expect(analysis_transaction[:spans][0][:origin]).to eq("auto.file.rails") end - request_transaction = transport.events.last.to_hash + request_transaction = transport.events.last.to_h expect(request_transaction[:type]).to eq("transaction") expect(request_transaction[:spans].count).to eq(2) @@ -68,7 +68,7 @@ p = Post.create! get "/posts/#{p.id}/attach" - request_transaction = transport.events.last.to_hash + request_transaction = transport.events.last.to_h expect(request_transaction[:type]).to eq("transaction") expect(request_transaction[:spans].count).to eq(2) diff --git a/sentry-rails/spec/sentry/rails/tracing/active_support_subscriber_spec.rb b/sentry-rails/spec/sentry/rails/tracing/active_support_subscriber_spec.rb index c276063da..0d77fd193 100644 --- a/sentry-rails/spec/sentry/rails/tracing/active_support_subscriber_spec.rb +++ b/sentry-rails/spec/sentry/rails/tracing/active_support_subscriber_spec.rb @@ -23,7 +23,7 @@ transaction.finish expect(transport.events.count).to eq(1) - cache_transaction = transport.events.first.to_hash + cache_transaction = transport.events.first.to_h expect(cache_transaction[:type]).to eq("transaction") expect(cache_transaction[:spans].count).to eq(1) @@ -45,7 +45,7 @@ expect(Rails.cache.read("my_cache_key")).to eq(1) expect(transport.events.count).to eq(1) - cache_transaction = transport.events.first.to_hash + cache_transaction = transport.events.first.to_h expect(cache_transaction[:type]).to eq("transaction") expect(cache_transaction[:spans].count).to eq(1) expect(cache_transaction[:spans][0][:op]).to eq("cache.put") @@ -64,7 +64,7 @@ transaction.finish expect(transport.events.count).to eq(1) - cache_transaction = transport.events.first.to_hash + cache_transaction = transport.events.first.to_h expect(cache_transaction[:type]).to eq("transaction") expect(cache_transaction[:spans].count).to eq(1) expect(cache_transaction[:spans][0][:op]).to eq("cache.put") @@ -79,7 +79,7 @@ transaction.finish expect(transport.events.count).to eq(1) - cache_transaction = transport.events.first.to_hash + cache_transaction = transport.events.first.to_h expect(cache_transaction[:type]).to eq("transaction") expect(cache_transaction[:spans].count).to eq(1) expect(cache_transaction[:spans][0][:op]).to eq("cache.get") @@ -95,7 +95,7 @@ transaction.finish expect(transport.events.count).to eq(1) - cache_transaction = transport.events.first.to_hash + cache_transaction = transport.events.first.to_h expect(cache_transaction[:type]).to eq("transaction") expect(cache_transaction[:spans].count).to eq(1) expect(cache_transaction[:spans][0][:op]).to eq("cache.get") @@ -112,7 +112,7 @@ transaction.finish expect(transport.events.count).to eq(1) - cache_transaction = transport.events.first.to_hash + cache_transaction = transport.events.first.to_h expect(cache_transaction[:type]).to eq("transaction") expect(cache_transaction[:spans].count).to eq(2) expect(cache_transaction[:spans][1][:op]).to eq("cache.flush") @@ -130,7 +130,7 @@ transaction.finish expect(transport.events.count).to eq(1) - cache_transaction = transport.events.first.to_hash + cache_transaction = transport.events.first.to_h expect(cache_transaction[:type]).to eq("transaction") expect(cache_transaction[:spans].count).to eq(2) expect(cache_transaction[:spans][0][:op]).to eq("cache.get") @@ -152,7 +152,7 @@ transaction.finish expect(transport.events.count).to eq(1) - cache_transaction = transport.events.first.to_hash + cache_transaction = transport.events.first.to_h expect(cache_transaction[:type]).to eq("transaction") expect(cache_transaction[:spans].count).to eq(1) expect(cache_transaction[:spans][0][:op]).to eq("cache.remove") diff --git a/sentry-rails/spec/sentry/rails/tracing_spec.rb b/sentry-rails/spec/sentry/rails/tracing_spec.rb index 629f78aa9..f21d8cded 100644 --- a/sentry-rails/spec/sentry/rails/tracing_spec.rb +++ b/sentry-rails/spec/sentry/rails/tracing_spec.rb @@ -26,8 +26,8 @@ expect(response).to have_http_status(:internal_server_error) expect(transport.events.count).to eq(2) - event = transport.events.first.to_hash - transaction = transport.events.last.to_hash + event = transport.events.first.to_h + transaction = transport.events.last.to_h expect(event.dig(:contexts, :trace, :trace_id).length).to eq(32) expect(event.dig(:contexts, :trace, :trace_id)).to eq(transaction.dig(:contexts, :trace, :trace_id)) @@ -67,7 +67,7 @@ expect(response).to have_http_status(:ok) expect(transport.events.count).to eq(1) - transaction = transport.events.last.to_hash + transaction = transport.events.last.to_h expect(transaction[:type]).to eq("transaction") expect(transaction.dig(:contexts, :trace, :op)).to eq("http.server") @@ -123,7 +123,7 @@ it "does not record sensitive params" do get "/posts?foo=bar&password=42&secret=baz" - transaction = transport.events.last.to_hash + transaction = transport.events.last.to_h params = transaction[:spans][0][:data][:params] expect(params["foo"]).to eq("bar") @@ -145,7 +145,7 @@ it "records all params" do get "/posts?foo=bar&password=42&secret=baz" - transaction = transport.events.last.to_hash + transaction = transport.events.last.to_h params = transaction[:spans][0][:data][:params] expect(params["foo"]).to eq("bar") @@ -260,7 +260,7 @@ expect(transport.events.count).to eq(3) - transaction = transport.events.last.to_hash + transaction = transport.events.last.to_h expect(transaction[:type]).to eq("transaction") expect(transaction[:transaction]).to eq("PostsController#show") diff --git a/sentry-rails/spec/sentry/send_event_job_spec.rb b/sentry-rails/spec/sentry/send_event_job_spec.rb deleted file mode 100644 index 00f89b2ed..000000000 --- a/sentry-rails/spec/sentry/send_event_job_spec.rb +++ /dev/null @@ -1,105 +0,0 @@ -# frozen_string_literal: true - -require "active_job" -require "spec_helper" - -RSpec.describe "Sentry::SendEventJob" do - let(:event) do - Sentry.get_current_client.event_from_message("test message") - end - let(:transport) do - Sentry.get_current_client.transport - end - - context "when ActiveJob is not loaded" do - before do - TempActiveJob = ActiveJob - Object.send(:remove_const, "ActiveJob") - reload_send_event_job - end - - after do - ActiveJob = TempActiveJob - reload_send_event_job - end - - it "gets defined as a blank class" do - expect(Sentry::SendEventJob.superclass).to eq(Object) - end - end - - context "when ActiveJob is loaded" do - after do - reload_send_event_job - end - - it "reports events to Sentry" do - make_basic_app - - Sentry.configuration.before_send = lambda do |event, hint| - event.tags[:hint] = hint - event - end - - Sentry::SendEventJob.perform_now(event, { foo: "bar" }) - - expect(transport.events.count).to eq(1) - event = transport.events.first - expect(event.message).to eq("test message") - expect(event.tags[:hint][:foo]).to eq("bar") - end - - it "doesn't create a new transaction" do - make_basic_app do |config| - config.traces_sample_rate = 1.0 - end - - Sentry::SendEventJob.perform_now(event) - - expect(transport.events.count).to eq(1) - event = transport.events.first - expect(event.type).to eq("event") - end - - context "when ApplicationJob is not defined" do - before do - make_basic_app - end - it "uses ActiveJob::Base as the parent class" do - expect(Sentry::SendEventJob.superclass).to eq(ActiveJob::Base) - end - end - - context "when ApplicationJob is defined" do - before do - class ApplicationJob < ActiveJob::Base; end - reload_send_event_job - make_basic_app - end - - after do - Object.send(:remove_const, "ApplicationJob") - end - - it "uses ApplicationJob as the parent class" do - expect(Sentry::SendEventJob.superclass).to eq(ApplicationJob) - end - end - - context "when ApplicationJob is defined but it's something else" do - before do - class ApplicationJob; end - reload_send_event_job - make_basic_app - end - - after do - Object.send(:remove_const, "ApplicationJob") - end - - it "uses ActiveJob::Base as the parent class" do - expect(Sentry::SendEventJob.superclass).to eq(ActiveJob::Base) - end - end - end -end diff --git a/sentry-raven/.craft.yml b/sentry-raven/.craft.yml deleted file mode 100644 index ba6de9cd2..000000000 --- a/sentry-raven/.craft.yml +++ /dev/null @@ -1,19 +0,0 @@ -minVersion: '0.13.2' -github: - owner: getsentry - repo: sentry-ruby -changelogPolicy: simple -preReleaseCommand: ruby .scripts/bump-version.rb -releaseBranchPrefix: release-sentry-raven -statusProvider: - name: github -artifactProvider: - name: github -targets: - - name: gem - - name: registry - type: sdk - config: - canonical: 'gem:sentry-raven' - - name: github - tagPrefix: sentry-raven-v diff --git a/sentry-raven/.scripts/bump-version.rb b/sentry-raven/.scripts/bump-version.rb deleted file mode 100755 index 2526cbab0..000000000 --- a/sentry-raven/.scripts/bump-version.rb +++ /dev/null @@ -1,5 +0,0 @@ -file_name = "lib/raven/version.rb" - -text = File.read(file_name) -new_contents = text.gsub(/VERSION = ".*"/, "VERSION = \"#{ARGV[1]}\"") -File.open(file_name, "w") {|file| file.puts new_contents } diff --git a/sentry-raven/CHANGELOG.md b/sentry-raven/CHANGELOG.md deleted file mode 100644 index 4b186fd9c..000000000 --- a/sentry-raven/CHANGELOG.md +++ /dev/null @@ -1,707 +0,0 @@ -# Changelog - -## Unreleased - -- fix: user_context with block does not reset context after block exits - -## 3.1.2 - -- Fix Delayed::Plugins::Raven when job raises exception [#1057](https://github.com/getsentry/sentry-ruby/pull/1057) -- Merge hash instead of replacing the original value in user_context [#1064](https://github.com/getsentry/sentry-ruby/pull/1064) -- Don't exclude ActionView::MissingTemplate error by default [#1092](https://github.com/getsentry/sentry-ruby/pull/1092) -- Fix typo: much -> must for Raven::Event [#1106](https://github.com/getsentry/sentry-ruby/pull/1106) -- Fix undefined local variable or method logger [#1143](https://github.com/getsentry/sentry-ruby/pull/1143) - - Fixes [#1110](https://github.com/getsentry/sentry-ruby/issues/1110) -- fix format headers for sentry-raven [#1198](https://github.com/getsentry/sentry-ruby/pull/1198) -- Print deprecation message after sentry-raven is installed [#1206](https://github.com/getsentry/sentry-ruby/pull/1206) - -## 3.1.1 - -**Feature** - -- Add request id to headers if exists ([#1033](https://github.com/getsentry/sentry-ruby/pull/1033)) - -- Allow blocks on user_context ([#1023](https://github.com/getsentry/sentry-ruby/pull/1023)) - -- Enable configurable rack environment recorded parameters ([#860](https://github.com/getsentry/sentry-ruby/pull/860)) - -- Remove ActiveJob keys for both Sidekiq and DelayedJob ([#898](https://github.com/getsentry/sentry-ruby/pull/898)) - -**Fix** - -- Remove circular dependency in transport/http.rb ([#1035](https://github.com/getsentry/sentry-ruby/pull/1035)) - -## 3.1.0 - -**Feature** - -- Exclude all 4xx Rails errors ([#1004](https://github.com/getsentry/raven-ruby/pull/1004)) - - See the full list [here](https://github.com/getsentry/raven-ruby/blob/master/lib/raven/configuration.rb#L198-L219) - -- Add some error context in `transport_failure_callback` ([#1003](https://github.com/getsentry/raven-ruby/pull/1003)) - - Before: - - ```ruby - config.transport_failure_callback = lambda { |event| - AdminMailer.email_admins("Oh god, it's on fire!", event).deliver_later - } - ``` - - After: - - ```ruby - config.transport_failure_callback = lambda { |event, error| - AdminMailer.email_admins("Oh god, it's on fire because #{error.message}!", event).deliver_later - } - ``` - -- Support cleaning up exception backtrace with customized backtrace_cleaner ([#1011](https://github.com/getsentry/raven-ruby/pull/1011)) - - The new config `backtrace_cleanup_callback` takes a lambda/proc object (default is `nil`) and will be called with exception's backtrace - - ```ruby - Raven.configure do |config| - config.backtrace_cleanup_callback = lambda do |backtrace| - Rails.backtrace_cleaner.clean(backtrace) - end - end - ``` - - And with the Rails integration, it'll automatically use a customized `Raven::Rails::BacktraceCleaner` to clean up exception's backtrace. It's basically Rails 6's [backtrace cleaner](https://github.com/rails/rails/blob/master/railties/lib/rails/backtrace_cleaner.rb) but without silencers. - - The main reason to add this cleaner is to remove template methods from the trace, e.g. - - ``` - app/views/welcome/view_error.html.erb in _app_views_welcome_view_error_html_erb__2807287320172182514_65600 at line 1 - ``` - - will become - - ``` - app/views/welcome/view_error.html.erb at line 1 - ``` - - This can help Sentry group issues more accurately. See [#957](https://github.com/getsentry/raven-ruby/issues/957) for more information about this. - - If you don't want this change, you can disable it with: - - ```ruby - Raven.configure do |config| - config.backtrace_cleanup_callback = nil - end - ``` - - -- Make dsn value accessable from config ([#1012](https://github.com/getsentry/raven-ruby/pull/1012)) - - You can now access the dsn value via `Raven.configuration.dsn` - -**Deprecation** - -- Deprecate dasherized filenames ([#1006](https://github.com/getsentry/raven-ruby/pull/1006)) - - If you're using - - ```ruby - gem 'sentry-raven', require: 'sentry-raven-without-integrations' - # or - require "sentry-raven-without-integrations" - ``` - - you will start seeing deprecation warnings. Please change them into - - ```ruby - gem 'sentry-raven', require: 'sentry_raven_without_integrations' - # or - require "sentry_raven_without_integrations" - ``` - -- Unify breadcrumb loggers activation ([#1016](https://github.com/getsentry/raven-ruby/pull/1016)) - - Currently, we activate our breadcrumb loggers differently: - - ```ruby - require "raven/breadcrumbs/sentry_logger" - Raven.configuration.rails_activesupport_breadcrumbs = true - ``` - - It's not a nice user interface, so this PR adds a new configuration - option `breadcrumbs_logger` to improve this: - - ```ruby - Raven.configuration.breadcrumbs_logger = :sentry_logger - Raven.configuration.breadcrumbs_logger = :active_support_logger - Raven.configuration.breadcrumbs_logger = [:sentry_logger, :active_support_logger] - ``` - - Please migrate to the new activation apporach, otherwise you'll see depraction warnings. And old ones will be dropped in version 4.0. - -**Refactor** - -- Accept non-string message in Event.from_exception ([#1005](https://github.com/getsentry/raven-ruby/pull/1005)) -- Refactor event initialization ([#1010](https://github.com/getsentry/raven-ruby/pull/1010)) -- Refactor sidekiq integration ([#1019](https://github.com/getsentry/raven-ruby/pull/1019)) - -**Fix** - -- Replace sys_command usages in context.rb ([#1017](https://github.com/getsentry/raven-ruby/pull/1017)) -- Fix merge error from rack-timeout raven_context on old releases ([#1007](https://github.com/getsentry/raven-ruby/pull/1007)) -- Return value of `rescue_with_handler` when intercepting ActiveJob exceptions ([#1027](https://github.com/getsentry/raven-ruby/pull/1027)) - -## 3.0.4 - -- fix: Don't log warning messages when it doesn't need to (#1000) -- fix: Revert "Refactor Raven::Client class" (#1002) - -## 3.0.3 - -- fix: Ensure Processor::Cookie can run after Processor::RemoveCircularReferences (#996) -- fix: Avoid mutating user passed in options (#994) -- fix: Fix/Refactor Raven::Cli (#989) -- ref: Refactor Raven::Client class (#995) - - It adds `Event#message_from_exception` and `Event#log_message` interfaces - -## 3.0.2 - -- fix: Add gem target for craft - -## 3.0.1 - -- fix: Improve SanitizeData processor (#984) -- fix: Masking cookies as key/pair instead of a single string (#983) -- fix: Transports classes' requiring issue (#986) -- fix: Frozen string issues (#977) -- feat: Officially support Rails 6 (#982) - -3.0.0 ----- - -* SDK now requires Ruby >= 2.3 -* REF: Retain any literal "HTTP-" in header names [@elliterate, #950] -* REF: Delete JSON spec for recursive hashes [@ksylvest, #952] -* FEAT: Bump faraday version to latest [@ksylvest, #946] - -2.13.0 ----- - -* FIX: Sanitize event data before they are sent to async job. [@edariedl, #895] -* FIX: Serialization MongoDB ObjectId to JSON problem with gem delayed_job_mongoid conjunction. [@eagleas, #935] -* FEAT: Skip ActiveJob integration if there is a better one [@fsateler, #909] -* FIX: Bugs with send_event in asynchronous mode (#940) [@cstyles, #940] - -2.12.3 ----- - -* FIX: crash when Process.wait is used [@asBrettisay, #895] - -2.12.2 ----- - -* FIX: return tags/extra for [@rivayama, #931] - -2.12.1 ----- - -* FIX: undefined method `[]' for nil:NilClass [@HazAT, #932] - -2.12.0 ----- - -* FIX: Remove duplicate message when exception is emitted -* FIX: Frozen string bug in utf8conversation -* FEATURE: Allow block on tags_context and extra_context - -2.11.3 ----- - -* FIX: infinite backoff under pressure [@Bonias, #886] - -2.11.2 ----- - -* REF: Warn on 4xx error [@iloveitaly, #862] - -2.11.1 ----- - -* FIX: Call `to_s` on breadcrumb message [@halkeye, #914] - -2.11.0 ----- - -* FEATURE: Prepend the transaction around_action so libraries with controllers can alter the value. [@drcapulet, #887] - -2.10.0 ------ - -* FEATURE: Added support for `SENTRY_ENVIRONMENT` [@mtsmfm, #910] -* FEATURE: Added support for `SENTRY_RELEASE` [@coorasse, #911] - -2.9.0 ------ - -* FEATURE: Added `config.inspect_exception_causes_for_exclusion`. Determines if the exception cause should be inspected for `config.excluded_exceptions` option. [@effron, #872] - - -2.8.0 ------ - -* FEATURE: Added `config.before_send`. Provide a lambda or proc to this config setting, which will be `call`ed before sending an event to Sentry. Receives `event` and `hint` as parameters. `hint` is a hash `{:exception => ex | nil, :message => message | nil}`. [@hazat, #882] - -2.7.4 ------ - -* BUGFIX: Correctly handle public only DSNs [@mitsuhiko, #847] -* BUGFIX: context attributes with nil raised error [@joker-777, 824] -* BUGFIX: Suppress warning about enabling dyno metadata in Heroku CI [@meganemura, #833] - -2.7.3 ------ - -* BUGFIX: Fix proxy settings for Faraday [@Strnadj, #820] -* BUGFIX: Fix duplicated events in ActiveJob w/DelayedJob and Sidekiq [@BrentWheeldon, #815] - -2.7.2 ------ - -* BUGFIX: GlobalIDs are now displayed correctly in Sidekiq contexts [@louim, #798] -* BUGFIX: If git is not installed, fail silently during release detection [@nateberkopec] -* BUGFIX: We do not support rack-timeout <= 0.2, fix errors when incompat version present [@nateberkopec] -* BUGFIX: Put cookies in the correct spot of event [@nateberkopec, #812] -* BUGFIX: Exception context is deep_merged [@janklimo, #782] - -2.7.1 ------ - -* BUGFIX: Fixed LocalJumpError in Rails controllers [@nateberkopec w/@frodsan, #774] - -2.7.0 ------ - -* FEATURE: Add random sampling. [@nateberkopec, #734] -* FEATURE: Transactions. See Context docs for usage. [@nateberkopec, #743] -* FEATURE: You can set the current environment for Sentry via `SENTRY_CURRENT_ENV` env variable. Useful if your staging environment's RACK_ENV is "production", for example. [@tijmenb, #736] - -* BUGFIX: Fix wrapped classnames in old versions of Sidekiq and ActiveJob [@nateberkopec, #702] -* BUGFIX: Server names on Heroku were pretty useless before - now they follow the dyno name ("worker.1", "web.2") [@nateberkopec, #703] -* BUGFIX: ActiveJob::DeserializationError is now ignored by default. Not doing so can cause infinite loops if you are using an ActiveJob async callback. [@nateberkopec, #701] -* BUGFIX: Binary conversion to UTF-8 when binary is frozen is fixed [@nateberkopec, #757] -* BUGFIX: Our credit-card regex now matches Sentry's server behavior, which means it does not censor milliseconds since the epoch [@nateberkopec, #771] - -* REFACTOR: We now use an updated port of Rails' deep_merge which should be 5-10% faster [@nateberkopec, #770] -* REFACTOR: Tests have been cleaned up, and now run in random order. [@nateberkopec] -* REFACTOR: Raven::Event has been refactored a bit [@nateberkopec] - -2.6.3 ------ - -* BUGFIX: Fixed typo in the Heroku warning [@greysteil, #728] -* BUGFIX: Swallow IOErrors when reading the Rack request body [@nateberkopec] -* BUGFIX: Fix invalid UTF-8/circular references when using async [@nateberkopec, #730] - -2.6.2 ------ - -* BUGFIX: If using the Sidekiq or DelayedJob adapters with ActiveJob, ActiveJob wouldn't re-raise upon capturing an exception. [@nateberkopec, 5b02ad4ff2] - -* KNOWN ISSUE: When using `async`, Rack integration is not thread-safe [#721] -* KNOWN ISSUE: When using `async`, encoding errors may be raised [#725] - -2.6.1 ------ - -* BUGFIX: Fix cases where ActionDispatch::RemoteIP would blow up during event creation [@cmoylan, #722] -* BUGFIX: In ActiveJob, don't report exceptions which can be rescued by rescue_from handlers [@bensheldon, #719] - -2.6.0 ------ - -* FEATURE: raven-ruby now marks itself as the "ruby" logger by default, to match raven-js behavior [@nateberkopec] -* FEATURE: You may now override the default sanitization parameters [#712, @nateberkopec] -* FEATURE: Breadcrumb buffers are now publicly accessible [#686, @nateberkopec] -* FEATURE: We yell at you now if you're using Heroku but don't have runtime-dyno-metadata enabled [#715, @nateberkopec] -* FEATURE: project_root will always be set, regardless of framework [#716, @nateberkopec] - -* BUGFIX: Request body and message limits now match Sentry server defaults [#714, @nateberkopec] -* BUGFIX: Sidekiq context now works as expected [#713, @nateberkopec] -* BUGFIX: Capture exceptions in ActiveJob when not using Sidekiq adapter [#709, #671, @nateberkopec] - -2.5.3 ------ - -* BUGFIX: Deal properly with ASCII_8BIT/BINARY encodings [#689, #696, @nateberkopec] - -2.5.2 ------ - -* BUGFIX: raven test executable should be available [#691, @nateberkopec] -* BUGFIX: Fix stack overflow when calling Backtrace#inspect [#690, @nateberkopec] - -* KNOWN ISSUE: Character encoding errors [#689] - -2.5.1 ------ - -* BUGFIX: Fix case where Pathname objects are on the load path [@nateberkopec] -* BUGFIX: Fix bad UTF-8 characters in the URL querystring [@nateberkopec] -* BUGFIX: Fix case where rack-timeout could be required twice [@nateberkopec] - -* REFACTOR: Slightly cleaner character encoding fixing [@nateberkopec, @bf4] - -2.5.0 ------ - -* FEATURE: Greatly improved performance (2-3x faster capture) [@nateberkopec] -* FEATURE: Frozen objects are now sanitized [@nateberkopec] - -* BUGFIX: Grabbing Sidekiq context from "wrapped" classes works [@nateberkopec] -* BUGFIX: Relaxed Faraday dependency [@nateberkopec] - -2.4.0 ------ - -* FEATURE: Allow customization of the Faraday adapter [#639, @StupidCodeFactory] - -* BUGFIX: Report the SDK name as "raven-ruby", not "sentry-raven" [#641, @bretthoerner] -* BUGFIX: Sidekiq jobs now clear context/breadcrumbs properly between jobs [#637, @drewish] -* BUGFIX: Overriding the logger in Rails wasn't working [#638, @eugeneius] - -2.3.1 ------ - -* BUGFIX: Backtrace parser fixed for JRuby 9k [#619, @the-michael-toy] -* BUGFIX: Rake tasks should show the correct task name [#621, @Bugagazavr] -* BUGFIX: Formatted messages work if params are `nil` [#625, @miyachik] -* BUGFIX: Backtrace logger on failed event send works with custom formatters [#627, @chulkilee] -* BUGFIX: Fix typo that caused Version headers to not be corrected [#628, @nateberkopec] -* BUGFIX: Faraday errors are more descriptive when no server response [#629, @drewish] -* BUGFIX: DelayedJob handler no longer truncates unneccessarily short [#633, @darrennix] -* BUGFIX: Fix several processors not working correctly w/async jobs stored in backends like Redis [#634, @nateberkopec] - -2.3.0 ------ - -* CHANGE: Log levels of some messages have been changed. Raven logger is INFO level by default. [@nateberkopec] -* BUGFIX: Exception messages are now limited to 10,000 bytes. [#617, @mattrobenolt] - -2.2.0 ------ - -* ENHANCEMENT: Sentry server errors now return some information about the response headers. [#585, @rafadc] -* BUGFIX/ENHANCEMENT: Frozen objects are no longer sanitized. This prevents some bugs, but you can now also freeze objects if you don't want them to be sanitized by the SanitizeData processor. [#594, @nateberkopec] -* ENHANCEMENT: The ability to use Raven::Instance alone is greatly improved. You can now call #capture_exception directly on an Instance (#595), give it it's own Logger (#599), and set it's own config which will be used when creating Events (#601). Thanks to -* ENHANCEMENT: You may now provide your own LineCache-like class to Raven. This is useful if you have source code which is not available on disk. [#606, @nateberkopec] -* BUGFIX: Raven no longer emits anything to STDOUT if a system command fails [#596, @nateberkopec] -* ENHANCEMENT: Raven now tells you exactly why it will not send an event in the logs [#602, @nateberkopec] - -2.1.4 ------ - -* FIX: Remove `contexts` key, because it was disabling browser auto-tagging [#587, @nateberkopec] - -2.1.3 ------ - -* Move `os` context key to `server_os` [@nateberkopec] - -2.1.2 ------ - -* FIX: `sys_command` not falling back to Windows commands properly, logging output [@jmalves, @nateberkopec] - -2.1.1 ------ - -* FIX: Message params should accept nil [@jmalves, #570] - -2.1.0 ------ - -ENHANCEMENTS: - -* Your client version is now included in all Events. [@nateberkopec, #559] -* OS and Ruby runtime information now included in all Events. [@nateberkopec, #560] -* Transport errors (like Sentry 4XX errors) now raise Sentry::Error, not Faraday errors. [@nateberkopec, #565] -* Sidekiq integration is streamlined and improved. Supports Sidekiq 3.x and up. [@nateberkopec, #555] - -FIXES: - -* Heroku release detection is improved and more accurate. You must `heroku labs:enable runtime-dyno-metadata` for it to work. [@nateberkopec, #566] - -2.0.2 ------ - -* FIX: Don't set up Rack-Timeout middleware. [@janraasch, #558] - -2.0.1 ------ - -* FIX: UUIDs were being rejected by Sentry as being too long [@nateberkopec] - -2.0.0 ------ - -BREAKING CHANGES: - -* The object passed to the `async` callback is now a JSON-compatible hash, not a Raven::Event. This fixes many bugs with backend job processors like DelayedJob. [@nateberkopec, #547] -* Several deprecated accessors have been removed [@nateberkopec, #543] -* You can no longer pass an object which cannot be called to `should_capture` [@nateberkopec, #542] - -ENHANCEMENTS: - -* Rack::Timeout exceptions are now fingerprinted by URL, making them more useful [@nateberkopec, #538] -* Added an HTTP header processor by default. We now scrub `Authorization` headers correctly. You can use `config.sanitize_http_headers` to add a list of HTTP headers you don't want sent to Sentry (e.g. ["Via", "Referer", "User-Agent", "Server", "From"]) [@nateberkopec] - -FIXES: - -* User/Event IP addresses are now set more accurately. This will fix many issues with local proxy setups (nginx, etc). [@nateberkopec, #546] -* We now generate a real UUID in the correct format for Event IDs [@nateberkopec, #549] -* If `async` sending fails, we retry with sync sending. [@nateberkopec, #548] -* Changed truncation approach - event messages and HTTP bodies now limited to the same amount of characters they're limited to at the Sentry server [@nateberkopec, #536] - -OTHER: - -* Codebase cleaned up with Rubocop [@nateberkopec, #544] - -1.2.3 ------ - -* ENHANCEMENT: Send the current environment to Sentry [@dcramer, #530] -* BUGFIX: Fix all warnings emitted by Ruby verbose mode [@nateberkopec] -* BUGFIX: Fix compat with `log4r` [@nateberkopec, #535] - -1.2.2 ------ - -* BUGFIX: NameError in DelayedJob integration. [janraasch, #525] - -1.2.1 ------ - -* BUGFIX: Context clearing should now work properly in DelayedJob and Sidekiq. Also, we properly clear context if Sentry causes an exception. [nateberkopec, #520] -* BUGFIX: If Sentry will not send the event (due to environments or no DSN set), it will not attempt to "capture" (construct an event) [nateberkopec, #518] - -1.2.0 ------ - -* FEATURE: Raven now supports Breadcrumbs, though they aren't on by default. Check the docs for how to enable. [dcramer, #497] -* FEATURE: Raven is no longer a singleton, you may have many `Raven::Instance`s. [phillbaker, #504] -* PERFORMANCE: Raven no longer uses a vendored JSON implementation. JSON processing and encoding should be up to 6x faster. [dcramer, #510] -* BUGFIX: silence_ready now works for Rails apps. [ream88, #512] -* BUGFIX: transport_failure_callback now works correctly [nateberkopec, #508] - -1.1.0 ------ - -* The client exposes a ``last_event_id`` accessor at `Raven.last_event_id`. [dcramer, #493] -* PERFORMANCE: Skip identical backtraces from "re-raised" exceptions [databus23, #499] -* Support for ActionController::Live and Rails template streaming [nateberkopec, #486] - -1.0.0 ------ - -We (i.e. @nateberkopec) decided that `raven-ruby` has been stable enough for some time that it's time for a 1.0.0 release! - -BREAKING CHANGES: - -- Dropped support for Ruby 1.8.7 [nateberkopec, #465] -- `raven-ruby` no longer reports form POST data or web cookies by default. To re-enable this behavior, remove the appropriate Processors from your config (see docs or PR) [nateberkopec, #466] -- UDP transport has been removed [dcramer, #472] - -OTHER CHANGES: - -- Improved performance [zanker] -- Deprecated `config.catch_debugged_exceptions`, replaced with `config.rails_report_rescued_exceptions`. `catch_debugged_exceptions` will be removed in 1.1. [nateberkopec, #483] -- Added `config.transport_failure_callback`. Provide a lambda or proc to this config setting, which will be `call`ed when Sentry returns a 4xx/5xx response. [nateberkopec, #484] -- JRuby builds fixed [RobinDaugherty] -- Fix problems with duplicate exceptions and `Exception.cause` [dcramer, #490] -- Added Exception Context. Any Exception class can define a `raven_context` instance variable, which will be merged into any Event's context which contains this exception. [nateberkopec, #491] -+ Documentation from shaneog, squirly, dcramer, ehfeng, nateberkopec. - -0.15.6 ------- - -- Fixed bug where return value of debug middleware was nil [eugeneius, #461] -- Fixed a bug in checking `catch_debugged_exceptions` [greysteil, #458] -- Fixed a deprecation warning for Rails 5 [Elektron1c97, #457] - -0.15.5 ------- - -- DelayedJob integration fixed when last_error not present [dcramer, #454] -- Release detection doesn't overwrite manual release setting in Rails [eugeneius, #450] -- Deal properly with Cap 3.0/3.1 revision logs [timcheadle, #449] -- Rails 5 support [nateberkopec, #423] - -0.15.4 ------- - -- DelayedJob integration now also truncates last_error to 100 characters [nateberkopec] -- Fix several issues with release detection - silence git log message, fix Capistrano detection [nateberkopec, kkumler] - - -0.15.3 ------- - -- Double exception reporting in Rails FIXED! [nateberkopec, #422] -- Rails 3 users having issues with undefined runner fixed [nateberkopec, #428] -- Sidekiq integration works properly when ActiveJob enabled [mattrobenolt] -- Fix problems with invalid UTF-8 in exception messages [nateberkopec, #426] -- Backtraces now consider "exe" directories part of the app [nateberkopec, #420] -- Sinatra::NotFound now ignored by default [drcapulet, #383] -- Release versions now properly set. Support for Heroku, Capistrano, and Git. [iloveitaly #377, Sija #380] -- DelayedJob integration plays well with ActiveJob [kkumler, #378] -- DelayedJob handlers now truncated [nateberkopec, #431] -- Tons of code quality improvements [amatsuda, ddrmanxbxfr, pmbrent, cpizzaia, wdhorton, PepperTeasdale] - -0.15.2 ------- - -- Reverted ActiveJob support due to conflicts [#368] - -0.15.1 ------- - -- Fix ActiveJob support [greysteil, #367] - -0.15.0 ------- - -- Remove Certifi and use default Ruby SSL config [zanker, #352] -- Support for ``fingerprint`` [dcramer] -- Improved documentation and tests around various attributes [dcramer] -- Allow configurable integrations [cthornton] -- Prevent recursion with ``Exception.cause`` [dcramer, #357] -- Use empty hash if false-y value [GeekOnCoffee, #354] -- Correct some behavior with at_exit error capturing [kratob, #355] -- Sanitize matches whole words [alyssa, #361] -- Expose more debugging info to active_job integration [tonywok, #365] -- Capture exceptions swallowed by rails [robertclancy, #343] -- Sanitize the query string when the key is a symbol [jason-o-matic, #349] -- Moved documentation to docs.getsentry.com [mitsuhiko] - -0.14.0 ------- - -- Correct handling of JRuby stacktraces [dcramer] -- Better handling of unreachable file contexts [dcramer, #335] -- SSL is now default ON [dcramer, #338] -- Capture exceptions in runner tasks [eugeneius, #339] -- ActiveJob integration [lucasmazza, #327] -- Cleanup return values of async blocks [lucasmazza, #344] -- Better handling when sending NaN/Infinity JSON values [Alric, #345] -- Fix issues with digest/md5 namespace [lsb, #346] - -0.13.3 ------- - -- Fix a deprecation warning being shown in regular operation [ripta, #332] - -0.13.2 ------- - -- DelayedJob integration now includes the job id [javawizard, #321] -- Rails integration now works properly when you're not using all parts of Rails (e.g. just ActiveRecord) [lucasmazza, #323] -- Bugfix CLI tool when async config is on [if1live, #324] -- Fix and standardize tag hierarchies. Event tags > context tags > configuration tags in all cases. [JonathanBatten, #322 and eugeneius, #330] -- Using #send on Client, Base, and Transports is now deprecated. See [the commit](https://github.com/getsentry/raven-ruby/commit/9f482022a648ab662c22177ba24fd2e2b6794c34) (or the deprecation message) for their replacements. [nateberkopec, #326] -- You can now disable credit-card-like value filtering. [codekitchen, #329] - -0.13.1 ------- - -- Raven::Transports::HTTP#send returns the response now. [eagletmt, #317] -- Filenames now work a lot better when you vendor your gems. [eugeneius, #316] -- Fix raven:test issue when testing non-async configurations. [weynsee, #318] -- Fix blockless Raven#capture. [dinosaurjr, #320] -- Fix some log messages [eagletmt, #319] - -0.13.0 ------- - -- Support exception chaining [javawizard, #312] -- Add support for sending release version [eugeneius, #310] -- Better status reports on configuration [faber, #309] -- Client "send" method accepts an event in object or hash format - this will make it much easier to send Sentry events in a delayed job! [marclennox, #300] -- Fix duplicate fields in SanitizeData [wyattisimo, #294] -- Always preserve filename paths under project_root [eugeneius, #291] -- Truncate project root prefixes from filenames [eagletmt, #278] -- Renamed should_send callback to should_capture [nateberkopec, #270] -- Silencing the ready message now happens in the config as normal [nateberkopec, #260] -- Various internal refactorings [see here](https://github.com/getsentry/raven-ruby/compare/0-12-stable...master) - -0.12.3 ------- - -- URL query parameters are now sanitized for sensitive data [pcorliss, #275] -- Raven::Client can now use a proxy server when sending events to Sentry [dcramer, #277] -- Raven::Client will now use a timed backoff strategy if the server fails [codekitchen, #267] -- Automatic integration loading is now a lot less brittle [dcramer, handlers, #263, #264] -- Fixed some issues with prefixes and DSN strings [nateberkopec, #259] -- If Raven is initialized without a server config, it will no longer send events [nateberkopec, #258] -- Slightly nicer credit-card-like number scrubbing [nateberkopec, #254] -- Fix some exceptions not being caught by Sidekiq middleware [nateberkopec, #251] -- Uncommon types are now encoded correctly [nateberkopec, #249] - -0.12.2 ------- - -- Security fix where exponential numbers in specially crafted params could cause a CPU attack [dcramer, #262] - -0.12.1 ------- - -- Integrations (Sidekiq, DelayedJob, etc) now load independently of your Gemfile order. [nateberkopec, #236] -- Fixed bug where setting tags mutated your configuration [berg, #239] -- Fixed several issues with SanitizeData and UTF8 sanitization processors [nateberkopec, #238, #241, #244] - -0.12.0 ------- - -- You can now give additional fields to the SanitizeData processor. Values matched are replaced by the string mask (*********). Full documentation (and how to use with Rails config.filter_parameters) [here](https://docs.sentry.io/platforms/ruby/config/). [jamescway, #232] -- An additional processor has been added, though it isn't turned on by default: RemoveStacktrace. Use it to remove stacktraces from exception reports. [nateberkopec, #233] -- Dependency on `uuidtools` has been removed. [nateberkopec, #231] - -0.11.2 ------- - -- Fix some issues with the SanitizeData processor when processing strings that look like JSON - - -0.11.1 ------- - -- Raven now captures exceptions in Rake tasks automatically. [nateberkopec, troelskn #222] -- There is now a configuration option called ```should_send``` that can be configured to use a Proc to determine whether or not an event should be sent to Sentry. This can be used to implement rate limiters, etc. [nateberkopec, #221] -- Raven now includes three event processors by default instead of one, which can be turned on and off independently. [nateberkopec, #223] -- Fixed bug with YAJL compatibility. [nateberkopec, #223] - -0.10.1 ------- - -- Updated to RSpec 3. -- Apply filters to encoded JSON data. - - -0.10.0 ------- - -- Events are now sent to Sentry in all environments. To change this behavior, either unset ```SENTRY_DSN``` or explicitly configure it via ```Raven.configure```. -- gzip is now the default encoding -- Removed hashie dependency - - -0.9.0 ------ - -- Native support for Delayed::Job [pkuczynski, #176] -- Updated to Sentry protocol version 5 - - -0.5.0 ------ -- Rails 2 support [sluukonen, #45] -- Controller methods in Rails [jfirebaugh] -- Runs by default in any environment other than test, cucumber, or development. [#81] diff --git a/sentry-raven/CONTRIBUTING.md b/sentry-raven/CONTRIBUTING.md deleted file mode 100644 index 71cb77042..000000000 --- a/sentry-raven/CONTRIBUTING.md +++ /dev/null @@ -1,71 +0,0 @@ -

- - - -
-

- -# Contributing - -You can contribute this project in the following ways: - -- File a [bug report] or propose a feature -- Open a PR for bug fixes or implementing requested features -- Give feedback to opened issues/pull requests -- Test the latest version - `gem 'sentry-raven', github: 'getsentry/raven-ruby'` -- Contribute documentation in the [document repo] - - -And if you have any questions, please feel free to reach out on [Discord]. - - -[bug report]: https://github.com/getsentry/raven-ruby/issues/new?template=bug_report.md -[document repo]: https://github.com/getsentry/sentry-docs -[Discord]: https://discord.gg/Ww9hbqr - -## How To Contribute - -### Running Tests - -#### RAILS_VERSION - -Because this SDK supports multiple versions of Rails, or even without Rails, you might want to run your test against different versions of Rails. - -You can do this by changing the `RAILS_VERSION` environment variable: - - -``` -$ echo RAILS_VERSION=6.0 -$ bundle update # this is necessary if you're switching between Rails versions -$ bundle exec rake -``` - -If not specified, it runs tests against `Rails 5.2`. - -And if you don't want to run the Rails related test cases, you can use `RAILS_VERSION=0` - -``` -$ RAILS_VERSION=0 bundle exec rake # runs without Rails related test cases -``` - -### Testing Your Change Against Example Rails Apps - -We have a few example apps for different Rails versions under the `/examples` folder. You can use them to perform an end-to-end testing on your changes (just remember to change the DSN to your project's). - -At this moment, we recommend testing against the [Rails 6 example](https://github.com/getsentry/raven-ruby/tree/master/examples/rails-6.0) first. Please read its readme to see what kind of testing you can perform with it. - - -## Making a release - -Install and use `craft`: https://github.com/getsentry/craft - -Make sure the `CHANGELOG.md` is update and latest `master` contains all changes. - -Run: - -```bash -craft prepare x.x.x -``` - -Where `x.x.x` stands for the version you want to release. -Afterwards reach out to an employee of Sentry, they will cut a release by running the `publish` process of `craft`. diff --git a/sentry-raven/Gemfile b/sentry-raven/Gemfile deleted file mode 100644 index 5ee60968a..000000000 --- a/sentry-raven/Gemfile +++ /dev/null @@ -1,41 +0,0 @@ -source "https://rubygems.org/" -git_source(:github) { |name| "https://github.com/#{name}.git" } - -gemspec - -rails_version = ENV["RAILS_VERSION"] -rails_version = "5.2" if rails_version.nil? - -if rails_version.to_f != 0 - gem "rails", "~> #{rails_version}" - gem "rspec-rails", "~> 4.0" -end - -gem "delayed_job" -gem "sidekiq", "< 7.0" - -gem "rack", "< 3.0" -gem "rack-timeout" - -# TODO: Remove this if https://github.com/jruby/jruby/issues/6547 is addressed -gem "i18n", "<= 1.8.7" - -gem "pry" -gem "benchmark-ips" -gem "benchmark_driver" -gem "benchmark-ipsa" -gem "benchmark-memory" -gem "ruby-prof", platform: :mri -gem "rake", "> 12" -gem "rspec", "~> 3.9.0" -gem "capybara", "~> 3.15.0" # rspec system tests -gem "puma" # rspec system tests - -# https://github.com/flavorjones/loofah/pull/267 -# loofah changed the required ruby version in a patch so we need to explicitly pin it -gem "loofah", "2.20.0" if RUBY_VERSION.to_f < 2.5 - -gem "timecop" -gem "test-unit" -gem "simplecov" -gem "codecov", "<= 0.2.12" diff --git a/sentry-raven/LICENSE b/sentry-raven/LICENSE deleted file mode 100644 index 40e74dccd..000000000 --- a/sentry-raven/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright 2015 Functional Software, Inc - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/sentry-raven/Makefile b/sentry-raven/Makefile deleted file mode 100644 index d218a238e..000000000 --- a/sentry-raven/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -build: - bundle install - gem build sentry-raven.gemspec diff --git a/sentry-raven/README.md b/sentry-raven/README.md deleted file mode 100644 index 551143426..000000000 --- a/sentry-raven/README.md +++ /dev/null @@ -1,164 +0,0 @@ -

- - - -
-

- -# Raven-Ruby, the Ruby Client for Sentry - -### 🚧 Migrating To The New SDK 🚧 - -We've released our new Ruby SDK, [sentry-ruby](https://github.com/getsentry/sentry-ruby/tree/master/sentry-ruby). Here are the benefits of migrating to it: - -- **Unified Interfaces With Other SDKs:** The design of `sentry-raven` is outdated compared with our modern Sentry SDKs. If you also use other Sentry SDKs, such as Sentry's JavaScript SDK for your frontend application, you'll notice that their interfaces are quite different from the one provided for `sentry-raven`. The new `sentry-ruby` SDK provides a more consistent user experience across all different platforms. - -- **Performance Monitoring:** The Sentry Ruby SDK includes [performance monitoring](https://docs.sentry.io/product/performance/), which you can enable if you haven't already as ([discussed here](https://docs.sentry.io/platforms/ruby/performance/)). - -- **Future Support:** `sentry-raven` has entered maintenance mode, which means it won't receive any new feature supports or aggressive bug fixes. - -- **Better Extensibility:** Unlike `sentry-raven`, `sentry-ruby` is built with extensibility in mind and will allow the community to build extensions for different integrations/features. - -If you're interested in the migration, please also read our [migration guide](https://docs.sentry.io/platforms/ruby/migration/) for more information. - ---- - - -[![Gem Version](https://img.shields.io/gem/v/sentry-raven.svg)](https://rubygems.org/gems/sentry-raven) -![Build Status](https://github.com/getsentry/raven-ruby/workflows/Test/badge.svg) -[![Coverage Status](https://img.shields.io/codecov/c/github/getsentry/sentry-ruby/master?logo=codecov)](https://codecov.io/gh/getsentry/sentry-ruby/branch/master) -[![Gem](https://img.shields.io/gem/dt/sentry-raven.svg)](https://rubygems.org/gems/sentry-raven/) -[![SemVer](https://api.dependabot.com/badges/compatibility_score?dependency-name=sentry-raven&package-manager=bundler&version-scheme=semver)](https://dependabot.com/compatibility-score.html?dependency-name=sentry-raven&package-manager=bundler&version-scheme=semver) - - -[Documentation](https://docs.sentry.io/clients/ruby/) | [Bug Tracker](https://github.com/getsentry/raven-ruby/issues) | [Forum](https://forum.sentry.io/) | IRC: irc.freenode.net, #sentry - -The official Ruby-language client and integration layer for the [Sentry](https://github.com/getsentry/sentry) error reporting API. - - -## Requirements - -We test on Ruby 2.3, 2.4, 2.5, 2.6 and 2.7 at the latest patchlevel/teeny version. We also support JRuby 9.0. Our Rails integration works with Rails 4.2+, including Rails 5 and Rails 6. - -## Getting Started - -### Install - -```ruby -gem "sentry-raven" -``` - -### Raven only runs when Sentry DSN is set - -Raven will capture and send exceptions to the Sentry server whenever its DSN is set. This makes environment-based configuration easy - if you don't want to send errors in a certain environment, just don't set the DSN in that environment! - -```bash -# Set your SENTRY_DSN environment variable. -export SENTRY_DSN=http://public@example.com/project-id -``` -```ruby -# Or you can configure the client in the code. -Raven.configure do |config| - config.dsn = 'http://public@example.com/project-id' -end -``` - -### Raven doesn't report some kinds of data by default - -**Raven ignores some exceptions by default** - most of these are related to 404s or controller actions not being found. [For a complete list, see the `IGNORE_DEFAULT` constant](https://github.com/getsentry/sentry-ruby/blob/master/sentry-raven/lib/raven/configuration.rb). - -Raven doesn't report POST data or cookies by default. In addition, it will attempt to remove any obviously sensitive data, such as credit card or Social Security numbers. For more information about how Sentry processes your data, [check out the documentation on the `processors` config setting.](https://docs.sentry.io/platforms/ruby/configuration/options/) - -### Usage - -**If you use Rails, you're already done - no more configuration required!** Check [Integrations](https://docs.sentry.io/platforms/ruby/configuration/integrations/) for more details on other gems Sentry integrates with automatically. - -Otherwise, Raven supports two methods of capturing exceptions: - -```ruby -Raven.capture do - # capture any exceptions which happen during execution of this block - 1 / 0 -end - -begin - 1 / 0 -rescue ZeroDivisionError => exception - Raven.capture_exception(exception) -end -``` - -### More configuration - -You're all set - but there's a few more settings you may want to know about too! - -#### async - -When an error or message occurs, the notification is immediately sent to Sentry. Raven can be configured to send asynchronously: - -```ruby -config.async = lambda { |event| - Thread.new { Raven.send_event(event) } -} -``` - -Using a thread to send events will be adequate for truly parallel Ruby platforms such as JRuby, though the benefit on MRI/CRuby will be limited. If the async callback raises an exception, Raven will attempt to send synchronously. - -Note that the naive example implementation has a major drawback - it can create an infinite number of threads. We recommend creating a background job, using your background job processor, that will send Sentry notifications in the background. - -```ruby -config.async = lambda { |event| SentryJob.perform_later(event) } - -class SentryJob < ActiveJob::Base - queue_as :default - - def perform(event) - Raven.send_event(event) - end -end -``` - -#### transport_failure_callback - -If Raven fails to send an event to Sentry for any reason (either the Sentry server has returned a 4XX or 5XX response), this Proc or lambda will be called. - -```ruby -config.transport_failure_callback = lambda { |event, error| - AdminMailer.email_admins("Oh god, it's on fire because #{error.message}!", event).deliver_later -} -``` - -#### Context - -Much of the usefulness of Sentry comes from additional context data with the events. Raven makes this very convenient by providing methods to set thread local context data that is then submitted automatically with all events: - -```ruby -Raven.user_context email: 'foo@example.com' - -Raven.tags_context interesting: 'yes' - -Raven.extra_context additional_info: 'foo' -``` - -You can also use `tags_context` and `extra_context` to provide scoped information: - -```ruby -Raven.tags_context(interesting: 'yes') do - # the `interesting: 'yes'` tag will only present in the requests sent inside the block - Raven.capture_exception(exception) -end - -Raven.extra_context(additional_info: 'foo') do - # same as above, the `additional_info` will only present in this request - Raven.capture_exception(exception) -end -``` - -For more information, see [Context](https://docs.sentry.io/platforms/ruby/enriching-events/context/). - -## More Information - -* [Documentation](https://docs.sentry.io/clients/ruby/) -* [Bug Tracker](https://github.com/getsentry/raven-ruby/issues) -* [Forum](https://forum.sentry.io/) -- [Discord](https://discord.gg/ez5KZN7) diff --git a/sentry-raven/Rakefile b/sentry-raven/Rakefile deleted file mode 100644 index f6c30faf6..000000000 --- a/sentry-raven/Rakefile +++ /dev/null @@ -1,24 +0,0 @@ -require 'rake' -require 'raven' -require 'rubygems/package_task' -require 'bundler/gem_tasks' - -gemspec = Gem::Specification.load(Dir['*.gemspec'].first) - -Gem::PackageTask.new(gemspec).define - -begin - require 'rubygems' - require 'rspec/core/rake_task' - - RSpec::Core::RakeTask.new(:spec) do |spec| - spec.pattern = 'spec/**/*_spec.rb' - end - -rescue LoadError - task :spec do - abort "Rspec is not available. bundle install to run unit tests" - end -end - -task :default => [:spec] diff --git a/sentry-raven/benchmarks/allocation_report.rb b/sentry-raven/benchmarks/allocation_report.rb deleted file mode 100644 index 089304ed4..000000000 --- a/sentry-raven/benchmarks/allocation_report.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'benchmark/ips' -require 'benchmark/ipsa' -require 'sentry-raven-without-integrations' - -Raven.configure do |config| - config.logger = Logger.new(nil) - config.dsn = "dummy://12345:67890@sentry.localdomain:3000/sentry/42" -end - -exception = begin - 1/0 - rescue => e - e - end - -Raven.capture_exception(exception) - -report = MemoryProfiler.report do - Raven.capture_exception(exception) -end - -report.pretty_print diff --git a/sentry-raven/benchmarks/application.rb b/sentry-raven/benchmarks/application.rb deleted file mode 100644 index bf74fe120..000000000 --- a/sentry-raven/benchmarks/application.rb +++ /dev/null @@ -1,22 +0,0 @@ -require "active_support/all" -require "action_controller" -require_relative "../spec/support/test_rails_app/app" - -def app(create = false) - @app_integration_instance = nil if create - @app_integration_instance ||= new_session do |sess| - sess.host! "www.example.com" - end -end - -def new_session - app = make_basic_app - session = ActionDispatch::Integration::Session.new(app) - yield session if block_given? - - # This makes app.url_for and app.foo_path available in the console - session.extend(app.routes.url_helpers) - session.extend(app.routes.mounted_helpers) - - session -end diff --git a/sentry-raven/benchmarks/profile.rb b/sentry-raven/benchmarks/profile.rb deleted file mode 100644 index c2eee6351..000000000 --- a/sentry-raven/benchmarks/profile.rb +++ /dev/null @@ -1,26 +0,0 @@ -require 'raven' -require_relative 'application' - -TestApp.configure do |config| - config.middleware.delete ActionDispatch::DebugExceptions - config.middleware.delete ActionDispatch::ShowExceptions -end - -Raven.configure do |config| - config.logger = Logger.new(nil) - config.breadcrumbs_logger = [:active_support_logger] - config.dsn = "dummy://12345:67890@sentry.localdomain:3000/sentry/42" -end - -require 'ruby-prof' - -RubyProf.measure_mode = RubyProf::PROCESS_TIME - -# profile the code -result = RubyProf.profile do - 100.times { app.get("/exception") } -end - -# print a graph profile to text -printer = RubyProf::MultiPrinter.new(result) -printer.print(:path => "./tmp", :profile => "profile") diff --git a/sentry-raven/benchmarks/rails_integration_allocation_comparison.rb b/sentry-raven/benchmarks/rails_integration_allocation_comparison.rb deleted file mode 100644 index 1c5af9d56..000000000 --- a/sentry-raven/benchmarks/rails_integration_allocation_comparison.rb +++ /dev/null @@ -1,25 +0,0 @@ -require "benchmark/memory" -require 'raven' -require_relative 'application' - -Raven.configure do |config| - config.logger = Logger.new(nil) - config.breadcrumbs_logger = [:active_support_logger] - config.dsn = "dummy://12345:67890@sentry.localdomain:3000/sentry/42" -end - -TestApp.configure do |config| - config.middleware.delete ActionDispatch::DebugExceptions - config.middleware.delete ActionDispatch::ShowExceptions -end - -app.get("/exception") - -Benchmark.memory do |x| - x.report("master") { app.get("/exception") } - x.report("branch") { app.get("/exception") } - - x.compare! - x.hold!("/tmp/allocation_comparison.json") -end - diff --git a/sentry-raven/benchmarks/rails_integration_allocation_report.rb b/sentry-raven/benchmarks/rails_integration_allocation_report.rb deleted file mode 100644 index ea1681a96..000000000 --- a/sentry-raven/benchmarks/rails_integration_allocation_report.rb +++ /dev/null @@ -1,24 +0,0 @@ -require 'benchmark/ips' -require 'benchmark/ipsa' -require 'raven' -require 'raven/breadcrumbs/logger' -require_relative 'application' - -Raven.configure do |config| - config.logger = Logger.new(nil) - config.breadcrumbs_logger = [:active_support_logger] - config.dsn = "dummy://12345:67890@sentry.localdomain:3000/sentry/42" -end - -TestApp.configure do |config| - config.middleware.delete ActionDispatch::DebugExceptions - config.middleware.delete ActionDispatch::ShowExceptions -end - -app.get("/exception") - -report = MemoryProfiler.report do - app.get("/exception") -end - -report.pretty_print diff --git a/sentry-raven/exe/raven b/sentry-raven/exe/raven deleted file mode 100755 index 48f2421fc..000000000 --- a/sentry-raven/exe/raven +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env ruby - -require "raven" -require "raven/cli" -require "optparse" - -parser = OptionParser.new do |opt| - opt.banner = "Usage: raven COMMAND [OPTIONS]" - opt.separator "" - opt.separator "Commands" - opt.separator " test: send a test event" - opt.separator "" - opt.separator "Options" - - opt.on("-h", "--help", "help") do - puts parser - end -end - -parser.parse! - -case ARGV[0] -when "test" - dsn = ARGV[1] if ARGV.length > 1 - if !dsn - puts "Usage: raven test " - else - Raven::CLI.test(dsn) - end -else - puts parser -end diff --git a/sentry-raven/lib/raven.rb b/sentry-raven/lib/raven.rb deleted file mode 100644 index 72b913df4..000000000 --- a/sentry-raven/lib/raven.rb +++ /dev/null @@ -1,3 +0,0 @@ -require 'raven/base' - -Raven.inject diff --git a/sentry-raven/lib/raven/backtrace.rb b/sentry-raven/lib/raven/backtrace.rb deleted file mode 100644 index 4afed54db..000000000 --- a/sentry-raven/lib/raven/backtrace.rb +++ /dev/null @@ -1,141 +0,0 @@ -# frozen_string_literal: true - -## Inspired by Rails' and Airbrake's backtrace parsers. - -module Raven - # Front end to parsing the backtrace for each notice - class Backtrace - # Handles backtrace parsing line by line - class Line - RB_EXTENSION = ".rb" - # regexp (optional leading X: on windows, or JRuby9000 class-prefix) - RUBY_INPUT_FORMAT = / - ^ \s* (?: [a-zA-Z]: | uri:classloader: )? ([^:]+ | <.*>): - (\d+) - (?: :in \s `([^']+)')?$ - /x.freeze - - # org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:170) - JAVA_INPUT_FORMAT = /^(.+)\.([^\.]+)\(([^\:]+)\:(\d+)\)$/.freeze - - # The file portion of the line (such as app/models/user.rb) - attr_reader :file - - # The line number portion of the line - attr_reader :number - - # The method of the line (such as index) - attr_reader :method - - # The module name (JRuby) - attr_reader :module_name - - # Parses a single line of a given backtrace - # @param [String] unparsed_line The raw line from +caller+ or some backtrace - # @return [Line] The parsed backtrace line - def self.parse(unparsed_line) - ruby_match = unparsed_line.match(RUBY_INPUT_FORMAT) - if ruby_match - _, file, number, method = ruby_match.to_a - file.sub!(/\.class$/, RB_EXTENSION) - module_name = nil - else - java_match = unparsed_line.match(JAVA_INPUT_FORMAT) - _, module_name, method, file, number = java_match.to_a - end - new(file, number, method, module_name) - end - - def initialize(file, number, method, module_name) - self.file = file - self.module_name = module_name - self.number = number.to_i - self.method = method - end - - def in_app - if file =~ self.class.in_app_pattern - true - else - false - end - end - - # Reconstructs the line in a readable fashion - def to_s - "#{file}:#{number}:in `#{method}'" - end - - def ==(other) - to_s == other.to_s - end - - def inspect - "" - end - - def self.in_app_pattern - @in_app_pattern ||= begin - project_root = Raven.configuration.project_root&.to_s - Regexp.new("^(#{project_root}/)?#{Raven.configuration.app_dirs_pattern || APP_DIRS_PATTERN}") - end - end - - private - - attr_writer :file, :number, :method, :module_name - end - - APP_DIRS_PATTERN = /(bin|exe|app|config|lib|test)/.freeze - - # holder for an Array of Backtrace::Line instances - attr_reader :lines - - def self.parse(backtrace, opts = {}) - ruby_lines = backtrace.is_a?(Array) ? backtrace : backtrace.split(/\n\s*/) - - ruby_lines = opts[:configuration].backtrace_cleanup_callback.call(ruby_lines) if opts[:configuration]&.backtrace_cleanup_callback - - filters = opts[:filters] || [] - filtered_lines = ruby_lines.to_a.map do |line| - filters.reduce(line) do |nested_line, proc| - proc.call(nested_line) - end - end.compact - - lines = filtered_lines.map do |unparsed_line| - Line.parse(unparsed_line) - end - - new(lines) - end - - def initialize(lines) - self.lines = lines - end - - def inspect - "" - end - - def to_s - content = [] - lines.each do |line| - content << line - end - content.join("\n") - end - - def ==(other) - if other.respond_to?(:lines) - lines == other.lines - else - false - end - end - - private - - attr_writer :lines - end -end diff --git a/sentry-raven/lib/raven/base.rb b/sentry-raven/lib/raven/base.rb deleted file mode 100644 index 852c939e6..000000000 --- a/sentry-raven/lib/raven/base.rb +++ /dev/null @@ -1,112 +0,0 @@ -require 'raven/version' -require "raven/helpers/deprecation_helper" -require 'raven/core_ext/object/deep_dup' -require 'raven/backtrace' -require 'raven/breadcrumbs' -require 'raven/processor' -require 'raven/processor/sanitizedata' -require 'raven/processor/removecircularreferences' -require 'raven/processor/utf8conversion' -require 'raven/processor/cookies' -require 'raven/processor/post_data' -require 'raven/processor/http_headers' -require 'raven/configuration' -require 'raven/context' -require 'raven/client' -require 'raven/event' -require 'raven/linecache' -require 'raven/logger' -require 'raven/interfaces/message' -require 'raven/interfaces/exception' -require 'raven/interfaces/single_exception' -require 'raven/interfaces/stack_trace' -require 'raven/interfaces/http' -require 'raven/transports' -require 'raven/transports/http' -require 'raven/utils/deep_merge' -require 'raven/utils/real_ip' -require 'raven/utils/request_id' -require 'raven/utils/exception_cause_chain' -require 'raven/instance' - -require 'forwardable' -require 'English' - -module Raven - AVAILABLE_INTEGRATIONS = %w(delayed_job railties sidekiq rack rack-timeout rake).freeze - - class Error < StandardError - end - - class << self - extend Forwardable - - def instance - @instance ||= Raven::Instance.new - end - - def_delegators :instance, :client=, :configuration=, :context, :logger, :configuration, - :client, :report_status, :configure, :send_event, :capture, :capture_type, - :last_event_id, :annotate_exception, :user_context, - :tags_context, :extra_context, :rack_context, :breadcrumbs - - def_delegator :instance, :report_status, :report_ready - def_delegator :instance, :capture_type, :capture_message - def_delegator :instance, :capture_type, :capture_exception - # For cross-language compatibility - def_delegator :instance, :capture_type, :captureException - def_delegator :instance, :capture_type, :captureMessage - def_delegator :instance, :annotate_exception, :annotateException - def_delegator :instance, :annotate_exception, :annotate - - # Injects various integrations. Default behavior: inject all available integrations - def inject - inject_only(*Raven::AVAILABLE_INTEGRATIONS) - end - - def inject_without(*exclude_integrations) - include_integrations = Raven::AVAILABLE_INTEGRATIONS - exclude_integrations.map(&:to_s) - inject_only(*include_integrations) - end - - def inject_only(*only_integrations) - only_integrations = only_integrations.map(&:to_s) - integrations_to_load = Raven::AVAILABLE_INTEGRATIONS & only_integrations - not_found_integrations = only_integrations - integrations_to_load - if not_found_integrations.any? - logger.warn "Integrations do not exist: #{not_found_integrations.join ', '}" - end - integrations_to_load &= Gem.loaded_specs.keys - # TODO(dcramer): integrations should have some additional checks baked-in - # or we should break them out into their own repos. Specifically both the - # rails and delayed_job checks are not always valid (i.e. Rails 2.3) and - # https://github.com/getsentry/raven-ruby/issues/180 - integrations_to_load.each do |integration| - load_integration(integration) - end - end - - def load_integration(integration) - require "raven/integrations/#{integration}" - rescue Exception => e - logger.warn "Unable to load raven/integrations/#{integration}: #{e}" - end - - def safely_prepend(module_name, opts = {}) - return if opts[:to].nil? || opts[:from].nil? - - if opts[:to].respond_to?(:prepend, true) - opts[:to].send(:prepend, opts[:from].const_get(module_name)) - else - opts[:to].send(:include, opts[:from].const_get("Old" + module_name)) - end - end - - def sys_command(command) - result = `#{command} 2>&1` rescue nil - return if result.nil? || result.empty? || ($CHILD_STATUS && $CHILD_STATUS.exitstatus != 0) - - result.strip - end - end -end diff --git a/sentry-raven/lib/raven/breadcrumbs.rb b/sentry-raven/lib/raven/breadcrumbs.rb deleted file mode 100644 index 01b32e1fd..000000000 --- a/sentry-raven/lib/raven/breadcrumbs.rb +++ /dev/null @@ -1,76 +0,0 @@ -module Raven - class Breadcrumb - attr_accessor :category, :data, :message, :level, :timestamp, :type - - def initialize - @category = nil - @data = {} - @level = nil - @message = nil - @timestamp = Time.now.to_i - @type = nil - end - - def to_hash - { - :category => @category, - :data => @data, - :level => @level, - :message => @message, - :timestamp => @timestamp, - :type => @type - } - end - end -end - -module Raven - class BreadcrumbBuffer - include Enumerable - - attr_accessor :buffer - - def self.current - Thread.current[:sentry_breadcrumbs] ||= new - end - - def self.clear! - Thread.current[:sentry_breadcrumbs] = nil - end - - def initialize(size = 100) - @buffer = Array.new(size) - end - - def record(crumb = nil) - if block_given? - crumb = Breadcrumb.new if crumb.nil? - yield(crumb) - end - @buffer.slice!(0) - @buffer << crumb - end - - def members - @buffer.compact - end - - def peek - members.last - end - - def each(&block) - members.each(&block) - end - - def empty? - members.none? - end - - def to_hash - { - :values => members.map(&:to_hash) - } - end - end -end diff --git a/sentry-raven/lib/raven/breadcrumbs/active_support_logger.rb b/sentry-raven/lib/raven/breadcrumbs/active_support_logger.rb deleted file mode 100644 index f44089215..000000000 --- a/sentry-raven/lib/raven/breadcrumbs/active_support_logger.rb +++ /dev/null @@ -1,25 +0,0 @@ -module Raven - module Breadcrumbs - module ActiveSupportLogger - class << self - def add(name, started, _finished, _unique_id, data) - Raven.breadcrumbs.record do |crumb| - crumb.data = data - crumb.category = name - crumb.timestamp = started.to_i - end - end - - def inject - @subscriber = ::ActiveSupport::Notifications.subscribe(/.*/) do |name, started, finished, unique_id, data| - add(name, started, finished, unique_id, data) - end - end - - def detach - ::ActiveSupport::Notifications.unsubscribe(@subscriber) - end - end - end - end -end diff --git a/sentry-raven/lib/raven/breadcrumbs/logger.rb b/sentry-raven/lib/raven/breadcrumbs/logger.rb deleted file mode 100644 index 6cfa18784..000000000 --- a/sentry-raven/lib/raven/breadcrumbs/logger.rb +++ /dev/null @@ -1,3 +0,0 @@ -DeprecationHelper.deprecate_old_breadcrumbs_configuration(:sentry_logger) - -require "raven/breadcrumbs/sentry_logger" diff --git a/sentry-raven/lib/raven/breadcrumbs/sentry_logger.rb b/sentry-raven/lib/raven/breadcrumbs/sentry_logger.rb deleted file mode 100644 index f03bd46ee..000000000 --- a/sentry-raven/lib/raven/breadcrumbs/sentry_logger.rb +++ /dev/null @@ -1,73 +0,0 @@ -require 'logger' - -module Raven - module Breadcrumbs - module SentryLogger - LEVELS = { - ::Logger::DEBUG => 'debug', - ::Logger::INFO => 'info', - ::Logger::WARN => 'warn', - ::Logger::ERROR => 'error', - ::Logger::FATAL => 'fatal' - }.freeze - - def add(*args) - add_breadcrumb(*args) - super - end - - def add_breadcrumb(severity, message = nil, progname = nil) - message = progname if message.nil? # see Ruby's Logger docs for why - return if ignored_logger?(progname) - return if message.nil? || message == "" - - # some loggers will add leading/trailing space as they (incorrectly, mind you) - # think of logging as a shortcut to std{out,err} - message = message.to_s.strip - - last_crumb = Raven.breadcrumbs.peek - # try to avoid dupes from logger broadcasts - if last_crumb.nil? || last_crumb.message != message - Raven.breadcrumbs.record do |crumb| - crumb.level = Raven::Breadcrumbs::SentryLogger::LEVELS.fetch(severity, nil) - crumb.category = progname || 'logger' - crumb.message = message - crumb.type = - if severity >= 3 - "error" - else - crumb.level - end - end - end - end - - private - - def ignored_logger?(progname) - progname == "sentry" || - Raven.configuration.exclude_loggers.include?(progname) - end - end - module OldBreadcrumbsSentryLogger - def self.included(base) - base.class_eval do - include Raven::Breadcrumbs::SentryLogger - alias_method :add_without_raven, :add - alias_method :add, :add_with_raven - end - end - - def add_with_raven(*args) - add_breadcrumb(*args) - add_without_raven(*args) - end - end - end -end - -Raven.safely_prepend( - "Breadcrumbs::SentryLogger", - :from => Raven, - :to => ::Logger -) diff --git a/sentry-raven/lib/raven/cli.rb b/sentry-raven/lib/raven/cli.rb deleted file mode 100644 index b0215ffab..000000000 --- a/sentry-raven/lib/raven/cli.rb +++ /dev/null @@ -1,48 +0,0 @@ -module Raven - class CLI - def self.test(dsn = nil, silent = false, config = nil) - config ||= Raven.configuration - - config.logger = if silent - ::Logger.new(nil) - else - logger = ::Logger.new(STDOUT) - logger.formatter = proc do |_severity, _datetime, _progname, msg| - "-> #{msg}\n" - end - logger - end - - config.timeout = 5 - config.dsn = dsn if dsn - - # wipe out env settings to ensure we send the event - unless config.capture_allowed? - env_name = config.environments.last || 'production' - config.current_environment = env_name - end - - instance = Raven::Instance.new(nil, config) - - instance.logger.debug "Sending a test event:" - instance.logger.debug "" - - begin - 1 / 0 - rescue ZeroDivisionError => e - evt = instance.capture_exception(e) - end - - if evt - instance.logger.debug "-> event ID: #{evt.id}" - instance.logger.debug "" - instance.logger.debug "Done!" - evt - else - instance.logger.debug "" - instance.logger.debug "An error occurred while attempting to send the event." - false - end - end - end -end diff --git a/sentry-raven/lib/raven/client.rb b/sentry-raven/lib/raven/client.rb deleted file mode 100644 index 2f69019a6..000000000 --- a/sentry-raven/lib/raven/client.rb +++ /dev/null @@ -1,168 +0,0 @@ -# frozen_string_literal: true - -require 'base64' -require 'json' -require 'zlib' - -require "raven/transports" - -module Raven - # Encodes events and sends them to the Sentry server. - class Client - PROTOCOL_VERSION = '5' - USER_AGENT = "raven-ruby/#{Raven::VERSION}" - CONTENT_TYPE = 'application/json' - - attr_accessor :configuration - - def initialize(configuration) - @configuration = configuration - @processors = configuration.processors.map { |v| v.new(self) } - @state = ClientState.new - end - - def send_event(event, hint = nil) - return false unless configuration.sending_allowed?(event) - - event = configuration.before_send.call(event, hint) if configuration.before_send - if event.nil? - configuration.logger.info "Discarded event because before_send returned nil" - return - end - - # Convert to hash - event = event.to_hash - - unless @state.should_try? - failed_send(nil, event) - return - end - - event_id = event[:event_id] || event['event_id'] - configuration.logger.info "Sending event #{event_id} to Sentry" - - content_type, encoded_data = encode(event) - - begin - transport.send_event(generate_auth_header, encoded_data, - :content_type => content_type) - successful_send - rescue => e - failed_send(e, event) - return - end - - event - end - - def transport - @transport ||= - case configuration.scheme - when 'http', 'https' - Transports::HTTP.new(configuration) - when 'stdout' - Transports::Stdout.new(configuration) - when 'dummy' - Transports::Dummy.new(configuration) - else - fail "Unknown transport scheme '#{configuration.scheme}'" - end - end - - private - - def encode(event) - hash = @processors.reduce(event.to_hash) { |a, e| e.process(a) } - encoded = JSON.fast_generate(hash) - - case configuration.encoding - when 'gzip' - ['application/octet-stream', Base64.strict_encode64(Zlib::Deflate.deflate(encoded))] - else - ['application/json', encoded] - end - end - - def get_message_from_exception(event) - ( - event && - event[:exception] && - event[:exception][:values] && - event[:exception][:values][0] && - event[:exception][:values][0][:type] && - event[:exception][:values][0][:value] && - "#{event[:exception][:values][0][:type]}: #{event[:exception][:values][0][:value]}" - ) - end - - def get_log_message(event) - (event && event[:message]) || (event && event['message']) || get_message_from_exception(event) || '' - end - - def generate_auth_header - now = Time.now.to_i.to_s - fields = { - 'sentry_version' => PROTOCOL_VERSION, - 'sentry_client' => USER_AGENT, - 'sentry_timestamp' => now, - 'sentry_key' => configuration.public_key - } - fields['sentry_secret'] = configuration.secret_key unless configuration.secret_key.nil? - 'Sentry ' + fields.map { |key, value| "#{key}=#{value}" }.join(', ') - end - - def successful_send - @state.success - end - - def failed_send(e, event) - if e # exception was raised - @state.failure - configuration.logger.warn "Unable to record event with remote Sentry server (#{e.class} - #{e.message}):\n#{e.backtrace[0..10].join("\n")}" - else - configuration.logger.warn "Not sending event due to previous failure(s)." - end - configuration.logger.warn("Failed to submit event: #{get_log_message(event)}") - - # configuration.transport_failure_callback can be false & nil - configuration.transport_failure_callback.call(event, e) if configuration.transport_failure_callback # rubocop:disable Style/SafeNavigation - end - end - - class ClientState - def initialize - reset - end - - def should_try? - return true if @status == :online - - interval = @retry_after || [@retry_number, 6].min**2 - return true if Time.now - @last_check >= interval - - false - end - - def failure(retry_after = nil) - @status = :error - @retry_number += 1 - @last_check = Time.now - @retry_after = retry_after - end - - def success - reset - end - - def reset - @status = :online - @retry_number = 0 - @last_check = nil - @retry_after = nil - end - - def failed? - @status == :error - end - end -end diff --git a/sentry-raven/lib/raven/configuration.rb b/sentry-raven/lib/raven/configuration.rb deleted file mode 100644 index cf774ad34..000000000 --- a/sentry-raven/lib/raven/configuration.rb +++ /dev/null @@ -1,557 +0,0 @@ -require 'uri' - -module Raven - class Configuration - # Directories to be recognized as part of your app. e.g. if you - # have an `engines` dir at the root of your project, you may want - # to set this to something like /(app|config|engines|lib)/ - attr_accessor :app_dirs_pattern - - # Provide an object that responds to `call` to send events asynchronously. - # E.g.: lambda { |event| Thread.new { Raven.send_event(event) } } - attr_reader :async - alias async? async - - # An array of breadcrumbs loggers to be used. Available options are: - # - :sentry_logger - # - :active_support_logger - attr_reader :breadcrumbs_logger - - # Number of lines of code context to capture, or nil for none - attr_accessor :context_lines - - # RACK_ENV by default. - attr_reader :current_environment - - # Encoding type for event bodies. Must be :json or :gzip. - attr_reader :encoding - - # Whitelist of environments that will send notifications to Sentry. Array of Strings. - attr_accessor :environments - - # Logger 'progname's to exclude from breadcrumbs - attr_accessor :exclude_loggers - - # Array of exception classes that should never be sent. See IGNORE_DEFAULT. - # You should probably append to this rather than overwrite it. - attr_accessor :excluded_exceptions - - # Boolean to check nested exceptions when deciding if to exclude. Defaults to false - attr_accessor :inspect_exception_causes_for_exclusion - alias inspect_exception_causes_for_exclusion? inspect_exception_causes_for_exclusion - - # DSN component - set automatically if DSN provided - attr_accessor :host - - # The Faraday adapter to be used. Will default to Net::HTTP when not set. - attr_accessor :http_adapter - - # A Proc yeilding the faraday builder allowing for further configuration - # of the faraday adapter - attr_accessor :faraday_builder - - # You may provide your own LineCache for matching paths with source files. - # This may be useful if you need to get source code from places other than - # the disk. See Raven::LineCache for the required interface you must implement. - attr_accessor :linecache - - # Logger used by Raven. In Rails, this is the Rails logger, otherwise - # Raven provides its own Raven::Logger. - attr_accessor :logger - - # Timeout waiting for the Sentry server connection to open in seconds - attr_accessor :open_timeout - - # DSN component - set automatically if DSN provided - attr_accessor :path - - # DSN component - set automatically if DSN provided - attr_accessor :port - - # Processors to run on data before sending upstream. See DEFAULT_PROCESSORS. - # You should probably append to this rather than overwrite it. - attr_accessor :processors - - # Project ID number to send to the Sentry server - # If you provide a DSN, this will be set automatically. - attr_accessor :project_id - - # Project directory root for in_app detection. Could be Rails root, etc. - # Set automatically for Rails. - attr_reader :project_root - - # Proxy information to pass to the HTTP adapter (via Faraday) - attr_accessor :proxy - - # Public key for authentication with the Sentry server - # If you provide a DSN, this will be set automatically. - attr_accessor :public_key - - # Turns on ActiveSupport breadcrumbs integration - attr_reader :rails_activesupport_breadcrumbs - - # Rails catches exceptions in the ActionDispatch::ShowExceptions or - # ActionDispatch::DebugExceptions middlewares, depending on the environment. - # When `rails_report_rescued_exceptions` is true (it is by default), Raven - # will report exceptions even when they are rescued by these middlewares. - attr_accessor :rails_report_rescued_exceptions - - # Release tag to be passed with every event sent to Sentry. - # We automatically try to set this to a git SHA or Capistrano release. - attr_accessor :release - - # The sampling factor to apply to events. A value of 0.0 will not send - # any events, and a value of 1.0 will send 100% of events. - attr_accessor :sample_rate - - # Boolean - sanitize values that look like credit card numbers - attr_accessor :sanitize_credit_cards - - # By default, Sentry censors Hash values when their keys match things like - # "secret", "password", etc. Provide an array of Strings that, when matched in - # a hash key, will be censored and not sent to Sentry. - attr_accessor :sanitize_fields - - # If you're sure you want to override the default sanitization values, you can - # add to them to an array of Strings here, e.g. %w(authorization password) - attr_accessor :sanitize_fields_excluded - - # Sanitize additional HTTP headers - only Authorization is removed by default. - attr_accessor :sanitize_http_headers - - # DSN component - set automatically if DSN provided. - # Otherwise, can be one of "http", "https", or "dummy" - attr_accessor :scheme - - # a proc/lambda that takes an array of stack traces - # it'll be used to silence (reduce) backtrace of the exception - # - # for example: - # - # ```ruby - # Raven.configuration.backtrace_cleanup_callback = lambda do |backtrace| - # Rails.backtrace_cleaner.clean(backtrace) - # end - # ``` - # - attr_accessor :backtrace_cleanup_callback - - # Secret key for authentication with the Sentry server - # If you provide a DSN, this will be set automatically. - # - # This is deprecated and not necessary for newer Sentry installations any more. - attr_accessor :secret_key - - # Include module versions in reports - boolean. - attr_accessor :send_modules - - # Simple server string - set this to the DSN found on your Sentry settings. - attr_reader :server - - attr_accessor :server_name - - # Provide a configurable callback to determine event capture. - # Note that the object passed into the block will be a String (messages) or - # an exception. - # e.g. lambda { |exc_or_msg| exc_or_msg.some_attr == false } - attr_reader :should_capture - - # Silences ready message when true. - attr_accessor :silence_ready - - # SSL settings passed directly to Faraday's ssl option - attr_accessor :ssl - - # The path to the SSL certificate file - attr_accessor :ssl_ca_file - - # Should the SSL certificate of the server be verified? - attr_accessor :ssl_verification - - # Default tags for events. Hash. - attr_accessor :tags - - # Timeout when waiting for the server to return data in seconds. - attr_accessor :timeout - - # Optional Proc, called when the Sentry server cannot be contacted for any reason - # E.g. lambda { |event| Thread.new { MyJobProcessor.send_email(event) } } - attr_reader :transport_failure_callback - - # Optional Proc, called before sending an event to the server/ - # E.g.: lambda { |event, hint| event } - # E.g.: lambda { |event, hint| nil } - # E.g.: lambda { |event, hint| - # event[:message] = 'a' - # event - # } - attr_reader :before_send - - # Errors object - an Array that contains error messages. See # - attr_reader :errors - - # the dsn value, whether it's set via `config.dsn=` or `ENV["SENTRY_DSN"]` - attr_reader :dsn - - # Array of rack env parameters to be included in the event sent to sentry. - attr_accessor :rack_env_whitelist - - # Most of these errors generate 4XX responses. In general, Sentry clients - # only automatically report 5xx responses. - IGNORE_DEFAULT = [ - 'AbstractController::ActionNotFound', - 'ActionController::BadRequest', - 'ActionController::InvalidAuthenticityToken', - 'ActionController::InvalidCrossOriginRequest', - 'ActionController::MethodNotAllowed', - 'ActionController::NotImplemented', - 'ActionController::ParameterMissing', - 'ActionController::RoutingError', - 'ActionController::UnknownAction', - 'ActionController::UnknownFormat', - 'ActionController::UnknownHttpMethod', - 'ActionDispatch::Http::Parameters::ParseError', - 'ActiveJob::DeserializationError', # Can cause infinite loops - 'ActiveRecord::RecordNotFound', - 'CGI::Session::CookieStore::TamperedWithCookie', - 'Mongoid::Errors::DocumentNotFound', - 'Rack::QueryParser::InvalidParameterError', - 'Rack::QueryParser::ParameterTypeError', - 'Sinatra::NotFound' - ].freeze - - # Note the order - we have to remove circular references and bad characters - # before passing to other processors. - DEFAULT_PROCESSORS = [ - Raven::Processor::RemoveCircularReferences, - Raven::Processor::UTF8Conversion, - Raven::Processor::SanitizeData, - Raven::Processor::Cookies, - Raven::Processor::PostData, - Raven::Processor::HTTPHeaders - ].freeze - - HEROKU_DYNO_METADATA_MESSAGE = "You are running on Heroku but haven't enabled Dyno Metadata. For Sentry's "\ - "release detection to work correctly, please run `heroku labs:enable runtime-dyno-metadata`".freeze - - RACK_ENV_WHITELIST_DEFAULT = %w( - REMOTE_ADDR - SERVER_NAME - SERVER_PORT - ).freeze - - LOG_PREFIX = "** [Raven] ".freeze - MODULE_SEPARATOR = "::".freeze - - AVAILABLE_BREADCRUMBS_LOGGERS = [:sentry_logger, :active_support_logger].freeze - - def initialize - self.async = false - self.breadcrumbs_logger = [] - self.context_lines = 3 - self.current_environment = current_environment_from_env - self.encoding = 'gzip' - self.environments = [] - self.exclude_loggers = [] - self.excluded_exceptions = IGNORE_DEFAULT.dup - self.inspect_exception_causes_for_exclusion = false - self.linecache = ::Raven::LineCache.new - self.logger = ::Raven::Logger.new(STDOUT) - self.open_timeout = 1 - self.processors = DEFAULT_PROCESSORS.dup - self.project_root = detect_project_root - @rails_activesupport_breadcrumbs = false - - self.rails_report_rescued_exceptions = true - self.release = detect_release - self.sample_rate = 1.0 - self.sanitize_credit_cards = true - self.sanitize_fields = [] - self.sanitize_fields_excluded = [] - self.sanitize_http_headers = [] - self.send_modules = true - self.server = ENV['SENTRY_DSN'] - self.server_name = server_name_from_env - self.should_capture = false - self.ssl_verification = true - self.tags = {} - self.timeout = 2 - self.transport_failure_callback = false - self.before_send = false - self.rack_env_whitelist = RACK_ENV_WHITELIST_DEFAULT - end - - def server=(value) - return if value.nil? - - @dsn = value - - uri = URI.parse(value) - uri_path = uri.path.split('/') - - if uri.user - # DSN-style string - self.project_id = uri_path.pop - self.public_key = uri.user - self.secret_key = !(uri.password.nil? || uri.password.empty?) ? uri.password : nil - end - - self.scheme = uri.scheme - self.host = uri.host - self.port = uri.port if uri.port - self.path = uri_path.join('/') - - # For anyone who wants to read the base server string - @server = "#{scheme}://#{host}" - @server += ":#{port}" unless port == { 'http' => 80, 'https' => 443 }[scheme] - @server += path - end - alias dsn= server= - - def encoding=(encoding) - raise(Error, 'Unsupported encoding') unless %w(gzip json).include? encoding - - @encoding = encoding - end - - def async=(value) - unless value == false || value.respond_to?(:call) - raise(ArgumentError, "async must be callable (or false to disable)") - end - - @async = value - end - - def breadcrumbs_logger=(logger) - loggers = - if logger.is_a?(Array) - logger - else - unless AVAILABLE_BREADCRUMBS_LOGGERS.include?(logger) - raise Raven::Error, "Unsupported breadcrumbs logger. Supported loggers: #{AVAILABLE_BREADCRUMBS_LOGGERS}" - end - - Array(logger) - end - - require "raven/breadcrumbs/sentry_logger" if loggers.include?(:sentry_logger) - - @breadcrumbs_logger = logger - end - - def transport_failure_callback=(value) - unless value == false || value.respond_to?(:call) - raise(ArgumentError, "transport_failure_callback must be callable (or false to disable)") - end - - @transport_failure_callback = value - end - - def should_capture=(value) - unless value == false || value.respond_to?(:call) - raise ArgumentError, "should_capture must be callable (or false to disable)" - end - - @should_capture = value - end - - def before_send=(value) - unless value == false || value.respond_to?(:call) - raise ArgumentError, "before_send must be callable (or false to disable)" - end - - @before_send = value - end - - # Allows config options to be read like a hash - # - # @param [Symbol] option Key for a given attribute - def [](option) - public_send(option) - end - - def current_environment=(environment) - @current_environment = environment.to_s - end - - def capture_allowed?(message_or_exc = nil) - @errors = [] - - valid? && - capture_in_current_environment? && - capture_allowed_by_callback?(message_or_exc) && - sample_allowed? - end - # If we cannot capture, we cannot send. - alias sending_allowed? capture_allowed? - - def error_messages - @errors = [errors[0]] + errors[1..-1].map(&:downcase) # fix case of all but first - errors.join(", ") - end - - def project_root=(root_dir) - @project_root = root_dir - Backtrace::Line.instance_variable_set(:@in_app_pattern, nil) # blow away cache - end - - def rails_activesupport_breadcrumbs=(val) - DeprecationHelper.deprecate_old_breadcrumbs_configuration(:active_support_logger) - @rails_activesupport_breadcrumbs = val - end - - def exception_class_allowed?(exc) - if exc.is_a?(Raven::Error) - # Try to prevent error reporting loops - logger.debug "Refusing to capture Raven error: #{exc.inspect}" - false - elsif excluded_exception?(exc) - logger.debug "User excluded error: #{exc.inspect}" - false - else - true - end - end - - def enabled_in_current_env? - environments.empty? || environments.include?(current_environment) - end - - private - - def detect_project_root - if defined? Rails.root # we are in a Rails application - Rails.root.to_s - else - Dir.pwd - end - end - - def detect_release - detect_release_from_env || - detect_release_from_git || - detect_release_from_capistrano || - detect_release_from_heroku - rescue => e - logger.error "Error detecting release: #{e.message}" - end - - def excluded_exception?(incoming_exception) - excluded_exceptions.any? do |excluded_exception| - matches_exception?(get_exception_class(excluded_exception), incoming_exception) - end - end - - def get_exception_class(x) - x.is_a?(Module) ? x : qualified_const_get(x) - end - - def matches_exception?(excluded_exception_class, incoming_exception) - if inspect_exception_causes_for_exclusion? - Raven::Utils::ExceptionCauseChain.exception_to_array(incoming_exception).any? { |cause| excluded_exception_class === cause } - else - excluded_exception_class === incoming_exception - end - end - - # In Ruby <2.0 const_get can't lookup "SomeModule::SomeClass" in one go - def qualified_const_get(x) - x = x.to_s - if !x.match(/::/) - Object.const_get(x) - else - x.split(MODULE_SEPARATOR).reject(&:empty?).inject(Object) { |a, e| a.const_get(e) } - end - rescue NameError # There's no way to safely ask if a constant exist for an unknown string - nil - end - - def detect_release_from_heroku - return unless running_on_heroku? - return if ENV['CI'] - logger.warn(HEROKU_DYNO_METADATA_MESSAGE) && return unless ENV['HEROKU_SLUG_COMMIT'] - - ENV['HEROKU_SLUG_COMMIT'] - end - - def running_on_heroku? - File.directory?("/etc/heroku") - end - - def detect_release_from_capistrano - revision_file = File.join(project_root, 'REVISION') - revision_log = File.join(project_root, '..', 'revisions.log') - - if File.exist?(revision_file) - File.read(revision_file).strip - elsif File.exist?(revision_log) - File.open(revision_log).to_a.last.strip.sub(/.*as release ([0-9]+).*/, '\1') - end - end - - def detect_release_from_git - Raven.sys_command("git rev-parse --short HEAD") if File.directory?(".git") - end - - def detect_release_from_env - ENV['SENTRY_RELEASE'] - end - - def capture_in_current_environment? - return true if enabled_in_current_env? - - @errors << "Not configured to send/capture in environment '#{current_environment}'" - false - end - - def capture_allowed_by_callback?(message_or_exc) - return true if !should_capture || message_or_exc.nil? || should_capture.call(message_or_exc) - - @errors << "should_capture returned false" - false - end - - def valid? - return true if %w(server host path public_key project_id).all? { |k| public_send(k) } - - if server - %w(server host path public_key project_id).map do |key| - @errors << "No #{key} specified" unless public_send(key) - end - else - @errors << "DSN not set" - end - false - end - - def sample_allowed? - return true if sample_rate == 1.0 - - if Random::DEFAULT.rand >= sample_rate - @errors << "Excluded by random sample" - false - else - true - end - end - - # Try to resolve the hostname to an FQDN, but fall back to whatever - # the load name is. - def resolve_hostname - Socket.gethostname || - Socket.gethostbyname(hostname).first rescue server_name - end - - def current_environment_from_env - ENV['SENTRY_CURRENT_ENV'] || ENV['SENTRY_ENVIRONMENT'] || ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'default' - end - - def server_name_from_env - if running_on_heroku? - ENV['DYNO'] - else - resolve_hostname - end - end - end -end diff --git a/sentry-raven/lib/raven/context.rb b/sentry-raven/lib/raven/context.rb deleted file mode 100644 index 9cd9313bb..000000000 --- a/sentry-raven/lib/raven/context.rb +++ /dev/null @@ -1,48 +0,0 @@ -require 'rbconfig' -require 'etc' - -module Raven - class Context - def self.current - Thread.current[:sentry_context] ||= new - end - - def self.clear! - Thread.current[:sentry_context] = nil - end - - attr_accessor :transaction, :extra, :server_os, :rack_env, :runtime, :tags, :user - - def initialize - self.server_os = self.class.os_context - self.runtime = self.class.runtime_context - self.extra = { :server => { :os => server_os, :runtime => runtime } } - self.rack_env = nil - self.tags = {} - self.user = {} - self.transaction = [] - end - - class << self - def os_context - @os_context ||= - begin - uname = Etc.uname - { - name: uname[:sysname] || RbConfig::CONFIG["host_os"], - version: uname[:version], - build: uname[:release], - kernel_version: uname[:version] - } - end - end - - def runtime_context - @runtime_context ||= { - name: RbConfig::CONFIG["ruby_install_name"], - version: RUBY_DESCRIPTION || Raven.sys_command("ruby -v") - } - end - end - end -end diff --git a/sentry-raven/lib/raven/core_ext/object/deep_dup.rb b/sentry-raven/lib/raven/core_ext/object/deep_dup.rb deleted file mode 100644 index 1458f9046..000000000 --- a/sentry-raven/lib/raven/core_ext/object/deep_dup.rb +++ /dev/null @@ -1,57 +0,0 @@ -require 'raven/core_ext/object/duplicable' - -######################################### -# This file was copied from Rails 5.2 # -######################################### - -class Object - # Returns a deep copy of object if it's duplicable. If it's - # not duplicable, returns +self+. - # - # object = Object.new - # dup = object.deep_dup - # dup.instance_variable_set(:@a, 1) - # - # object.instance_variable_defined?(:@a) # => false - # dup.instance_variable_defined?(:@a) # => true - def deep_dup - duplicable? ? dup : self - end -end - -class Array - # Returns a deep copy of array. - # - # array = [1, [2, 3]] - # dup = array.deep_dup - # dup[1][2] = 4 - # - # array[1][2] # => nil - # dup[1][2] # => 4 - def deep_dup - map(&:deep_dup) - end -end - -class Hash - # Returns a deep copy of hash. - # - # hash = { a: { b: 'b' } } - # dup = hash.deep_dup - # dup[:a][:c] = 'c' - # - # hash[:a][:c] # => nil - # dup[:a][:c] # => "c" - def deep_dup - hash = dup - each_pair do |key, value| - if key.frozen? && ::String === key - hash[key] = value.deep_dup - else - hash.delete(key) - hash[key.deep_dup] = value.deep_dup - end - end - hash - end -end diff --git a/sentry-raven/lib/raven/core_ext/object/duplicable.rb b/sentry-raven/lib/raven/core_ext/object/duplicable.rb deleted file mode 100644 index b70adb5bc..000000000 --- a/sentry-raven/lib/raven/core_ext/object/duplicable.rb +++ /dev/null @@ -1,153 +0,0 @@ -# frozen_string_literal: true - -######################################### -# This file was copied from Rails 5.2 # -######################################### - -#-- -# Most objects are cloneable, but not all. For example you can't dup methods: -# -# method(:puts).dup # => TypeError: allocator undefined for Method -# -# Classes may signal their instances are not duplicable removing +dup+/+clone+ -# or raising exceptions from them. So, to dup an arbitrary object you normally -# use an optimistic approach and are ready to catch an exception, say: -# -# arbitrary_object.dup rescue object -# -# Rails dups objects in a few critical spots where they are not that arbitrary. -# That rescue is very expensive (like 40 times slower than a predicate), and it -# is often triggered. -# -# That's why we hardcode the following cases and check duplicable? instead of -# using that rescue idiom. -#++ -class Object - # Can you safely dup this object? - # - # False for method objects; - # true otherwise. - def duplicable? - true - end -end - -class NilClass - begin - nil.dup - rescue TypeError - # +nil+ is not duplicable: - # - # nil.duplicable? # => false - # nil.dup # => TypeError: can't dup NilClass - def duplicable? - false - end - end -end - -class FalseClass - begin - false.dup - rescue TypeError - # +false+ is not duplicable: - # - # false.duplicable? # => false - # false.dup # => TypeError: can't dup FalseClass - def duplicable? - false - end - end -end - -class TrueClass - begin - true.dup - rescue TypeError - # +true+ is not duplicable: - # - # true.duplicable? # => false - # true.dup # => TypeError: can't dup TrueClass - def duplicable? - false - end - end -end - -class Symbol - begin - :symbol.dup # Ruby 2.4.x. - "symbol_from_string".to_sym.dup # Some symbols can't `dup` in Ruby 2.4.0. - rescue TypeError - # Symbols are not duplicable: - # - # :my_symbol.duplicable? # => false - # :my_symbol.dup # => TypeError: can't dup Symbol - def duplicable? - false - end - end -end - -class Numeric - begin - 1.dup - rescue TypeError - # Numbers are not duplicable: - # - # 3.duplicable? # => false - # 3.dup # => TypeError: can't dup Integer - def duplicable? - false - end - end -end - -require "bigdecimal" -class BigDecimal - # BigDecimals are duplicable: - # - # BigDecimal("1.2").duplicable? # => true - # BigDecimal("1.2").dup # => # - def duplicable? - true - end -end - -class Method - # Methods are not duplicable: - # - # method(:puts).duplicable? # => false - # method(:puts).dup # => TypeError: allocator undefined for Method - def duplicable? - false - end -end - -class Complex - begin - Complex(1).dup - rescue TypeError - # Complexes are not duplicable: - # - # Complex(1).duplicable? # => false - # Complex(1).dup # => TypeError: can't copy Complex - def duplicable? - false - end - end -end - -class Rational - begin - Rational(1).dup - rescue TypeError - # Rationals are not duplicable: - # - # Rational(1).duplicable? # => false - # Rational(1).dup # => TypeError: can't copy Rational - def duplicable? - false - end - end -end diff --git a/sentry-raven/lib/raven/event.rb b/sentry-raven/lib/raven/event.rb deleted file mode 100644 index ec0bdb030..000000000 --- a/sentry-raven/lib/raven/event.rb +++ /dev/null @@ -1,255 +0,0 @@ -# frozen_string_literal: true - -require 'socket' -require 'securerandom' - -module Raven - class Event - # See Sentry server default limits at - # https://github.com/getsentry/sentry/blob/master/src/sentry/conf/server.py - MAX_MESSAGE_SIZE_IN_BYTES = 1024 * 8 - REQUIRED_OPTION_KEYS = [:configuration, :context, :breadcrumbs].freeze - - SDK = { "name" => "raven-ruby", "version" => Raven::VERSION }.freeze - - attr_accessor :id, :logger, :transaction, :server_name, :release, :modules, - :extra, :tags, :context, :configuration, :checksum, - :fingerprint, :environment, :server_os, :runtime, - :breadcrumbs, :user, :backtrace, :platform, :sdk - alias event_id id - - attr_reader :level, :timestamp, :time_spent - - def initialize(options) - # Set some simple default values - self.id = SecureRandom.uuid.delete("-") - self.timestamp = Time.now.utc - self.level = :error - self.logger = :ruby - self.platform = :ruby - self.sdk = SDK - - # Set some attributes with empty hashes to allow merging - @interfaces = {} - self.user = {} # TODO: contexts - self.extra = {} # TODO: contexts - self.server_os = {} # TODO: contexts - self.runtime = {} # TODO: contexts - self.tags = {} # TODO: contexts - - unless REQUIRED_OPTION_KEYS.all? { |key| options.key?(key) } - raise "you must provide configuration, context, and breadcrumbs when initializing a Raven::Event" - end - - self.configuration = options[:configuration] - self.context = options[:context] - self.breadcrumbs = options[:breadcrumbs] - - # Allow attributes to be set on the event at initialization - yield self if block_given? - options.each_pair { |key, val| public_send("#{key}=", val) unless val.nil? } - - set_core_attributes_from_configuration - set_core_attributes_from_context - end - - def self.from_exception(exc, options = {}, &block) - exception_context = if exc.instance_variable_defined?(:@__raven_context) - exc.instance_variable_get(:@__raven_context) - elsif exc.respond_to?(:raven_context) - exc.raven_context - else - {} - end - options = Raven::Utils::DeepMergeHash.deep_merge(exception_context, options) - - return unless options[:configuration].exception_class_allowed?(exc) - - new(options) do |evt| - evt.add_exception_interface(exc) - yield evt if block - end - end - - def self.from_message(message, options = {}) - new(options) do |evt| - evt.message = message, options[:message_params] || [] - if options[:backtrace] - evt.interface(:stacktrace) do |int| - int.frames = evt.stacktrace_interface_from(options[:backtrace]) - end - end - end - end - - def message - @interfaces[:logentry]&.unformatted_message - end - - def message=(args) - if args.is_a?(Array) - message, params = args[0], args[0..-1] - else - message = args - end - - unless message.is_a?(String) - configuration.logger.debug("You're passing a non-string message") - message = message.to_s - end - - interface(:message) do |int| - int.message = message.byteslice(0...MAX_MESSAGE_SIZE_IN_BYTES) # Messages limited to 10kb - int.params = params - end - end - - def timestamp=(time) - @timestamp = time.is_a?(Time) ? time.strftime('%Y-%m-%dT%H:%M:%S') : time - end - - def time_spent=(time) - @time_spent = time.is_a?(Float) ? (time * 1000).to_i : time - end - - def level=(new_level) # needed to meet the Sentry spec - @level = new_level.to_s == "warn" ? :warning : new_level - end - - def interface(name, value = nil, &block) - int = Interface.registered[name] - raise(Error, "Unknown interface: #{name}") unless int - - @interfaces[int.sentry_alias] = int.new(value, &block) if value || block - @interfaces[int.sentry_alias] - end - - def [](key) - interface(key) - end - - def []=(key, value) - interface(key, value) - end - - def to_hash - data = [:checksum, :environment, :event_id, :extra, :fingerprint, :level, - :logger, :message, :modules, :platform, :release, :sdk, :server_name, - :tags, :time_spent, :timestamp, :transaction, :user].each_with_object({}) do |att, memo| - memo[att] = public_send(att) if public_send(att) - end - - data[:breadcrumbs] = @breadcrumbs.to_hash unless @breadcrumbs.empty? - - @interfaces.each_pair do |name, int_data| - data[name.to_sym] = int_data.to_hash - end - data - end - - def to_json_compatible - cleaned_hash = async_json_processors.reduce(to_hash) { |a, e| e.process(a) } - JSON.parse(JSON.generate(cleaned_hash)) - end - - def add_exception_interface(exc) - interface(:exception) do |exc_int| - exceptions = Raven::Utils::ExceptionCauseChain.exception_to_array(exc).reverse - backtraces = Set.new - exc_int.values = exceptions.map do |e| - SingleExceptionInterface.new do |int| - int.type = e.class.to_s - int.value = e.to_s - int.module = e.class.to_s.split('::')[0...-1].join('::') - - int.stacktrace = - if e.backtrace && !backtraces.include?(e.backtrace.object_id) - backtraces << e.backtrace.object_id - StacktraceInterface.new do |stacktrace| - stacktrace.frames = stacktrace_interface_from(e.backtrace) - end - end - end - end - end - end - - def stacktrace_interface_from(backtrace) - Backtrace.parse(backtrace, { configuration: configuration }).lines.reverse.each_with_object([]) do |line, memo| - frame = StacktraceInterface::Frame.new - frame.abs_path = line.file if line.file - frame.function = line.method if line.method - frame.lineno = line.number - frame.in_app = line.in_app - frame.module = line.module_name if line.module_name - - if configuration[:context_lines] && frame.abs_path - frame.pre_context, frame.context_line, frame.post_context = \ - configuration.linecache.get_file_context(frame.abs_path, frame.lineno, configuration[:context_lines]) - end - - memo << frame if frame.filename - end - end - - # For cross-language compat - class << self - alias captureException from_exception - alias captureMessage from_message - alias capture_exception from_exception - alias capture_message from_message - end - - private - - def set_core_attributes_from_configuration - self.server_name ||= configuration.server_name - self.release ||= configuration.release - self.modules = list_gem_specs if configuration.send_modules - self.environment ||= configuration.current_environment - end - - def set_core_attributes_from_context - self.transaction ||= context.transaction.last - - # If this is a Rack event, merge Rack context - add_rack_context if !self[:http] && context.rack_env - - # Merge contexts - self.user = context.user.merge(user) # TODO: contexts - self.extra = context.extra.merge(extra) # TODO: contexts - self.tags = configuration.tags.merge(context.tags).merge!(tags) # TODO: contexts - end - - def add_rack_context - interface :http do |int| - int.from_rack(context.rack_env) - end - context.user[:ip_address] = calculate_real_ip_from_rack - - if request_id = Utils::RequestId.read_from(context.rack_env) - context.tags[:request_id] = request_id - end - end - - # When behind a proxy (or if the user is using a proxy), we can't use - # REMOTE_ADDR to determine the Event IP, and must use other headers instead. - def calculate_real_ip_from_rack - Utils::RealIp.new( - :remote_addr => context.rack_env["REMOTE_ADDR"], - :client_ip => context.rack_env["HTTP_CLIENT_IP"], - :real_ip => context.rack_env["HTTP_X_REAL_IP"], - :forwarded_for => context.rack_env["HTTP_X_FORWARDED_FOR"] - ).calculate_ip - end - - def async_json_processors - configuration.processors.map { |v| v.new(self) } - end - - def list_gem_specs - # Older versions of Rubygems don't support iterating over all specs - Hash[Gem::Specification.map { |spec| [spec.name, spec.version.to_s] }] if Gem::Specification.respond_to?(:map) - end - end -end diff --git a/sentry-raven/lib/raven/helpers/deprecation_helper.rb b/sentry-raven/lib/raven/helpers/deprecation_helper.rb deleted file mode 100644 index bd81d746b..000000000 --- a/sentry-raven/lib/raven/helpers/deprecation_helper.rb +++ /dev/null @@ -1,17 +0,0 @@ -module DeprecationHelper - def self.deprecate_dasherized_filename(correct_filename) - warn "[Deprecation Warning] Dasherized filename \"#{correct_filename.gsub('_', '-')}\" is deprecated and will be removed in 4.0; use \"#{correct_filename}\" instead" # rubocop:disable Style/LineLength - end - - def self.deprecate_old_breadcrumbs_configuration(logger) - deprecated_usage = - if logger == :sentry_logger - "require \"raven/breadcrumbs/logger\"" - else - "Raven.configuration.rails_activesupport_breadcrumbs = true" - end - recommended_usage = "Raven.configuration.breadcrumbs_logger = :#{logger}" - - warn "[Deprecation Warning] The way you enable breadcrumbs logger (#{deprecated_usage}) is deprecated and will be removed in 4.0; use '#{recommended_usage}' instead" # rubocop:disable Style/LineLength - end -end diff --git a/sentry-raven/lib/raven/instance.rb b/sentry-raven/lib/raven/instance.rb deleted file mode 100644 index 116c7391d..000000000 --- a/sentry-raven/lib/raven/instance.rb +++ /dev/null @@ -1,249 +0,0 @@ -module Raven - # A copy of Raven's base module class methods, minus some of the integration - # and global hooks since it's meant to be used explicitly. Useful for - # sending errors to multiple sentry projects in a large application. - # - # @example - # class Foo - # def initialize - # @other_raven = Raven::Instance.new - # @other_raven.configure do |config| - # config.server = 'http://...' - # end - # end - # - # def foo - # # ... - # rescue => e - # @other_raven.capture_exception(e) - # end - # end - class Instance - # See Raven::Client. - attr_writer :client - - # See Raven::Configuration. - attr_accessor :configuration - - def initialize(context = nil, config = nil) - @context = @explicit_context = context - self.configuration = config || Configuration.new - end - - def context - if @explicit_context - @context ||= Context.new - else - Context.current - end - end - - def logger - configuration.logger - end - - # The client object is responsible for delivering formatted data to the - # Sentry server. - def client - @client ||= Client.new(configuration) - end - - # Tell the log that the client is good to go - def report_status - return unless configuration.enabled_in_current_env? - return if configuration.silence_ready - - if configuration.capture_allowed? - logger.info "Raven #{VERSION} ready to catch errors" - else - logger.info "Raven #{VERSION} configured not to capture errors: #{configuration.error_messages}" - end - end - - # Call this method to modify defaults in your initializers. - # - # @example - # Raven.configure do |config| - # config.server = 'http://...' - # end - def configure - yield(configuration) if block_given? - - self.client = Client.new(configuration) - report_status - client - end - - # Send an event to the configured Sentry server - # - # @example - # evt = Raven::Event.new(:message => "An errore) - # Raven.send_event(evt) - def send_event(event, hint = nil) - client.send_event(event, hint) - end - - # Capture and process any exceptions from the given block. - # - # @example - # Raven.capture do - # MyApp.run - # end - def capture(options = {}) - if block_given? - begin - yield - rescue Error - raise # Don't capture Raven errors - rescue Exception => e - capture_type(e, options) - raise - end - else - install_at_exit_hook(options) - end - end - - def capture_type(obj, options = {}) - unless configuration.capture_allowed?(obj) - logger.debug("#{obj} excluded from capture: #{configuration.error_messages}") - return false - end - - message_or_exc = obj.is_a?(String) ? "message" : "exception" - options = options.deep_dup - options[:configuration] = configuration - options[:context] = context - options[:breadcrumbs] = breadcrumbs - - if evt = Event.send("from_" + message_or_exc, obj, options) - yield evt if block_given? - if configuration.async? - begin - # We have to convert to a JSON-like hash, because background job - # processors (esp ActiveJob) may not like weird types in the event hash - configuration.async.call(evt.to_json_compatible) - rescue => e - logger.error("async event sending failed: #{e.message}") - send_event(evt, make_hint(obj)) - end - else - send_event(evt, make_hint(obj)) - end - Thread.current["sentry_#{object_id}_last_event_id".to_sym] = evt.id - evt - end - end - - alias capture_message capture_type - alias capture_exception capture_type - - def last_event_id - Thread.current["sentry_#{object_id}_last_event_id".to_sym] - end - - # Provides extra context to the exception prior to it being handled by - # Raven. An exception can have multiple annotations, which are merged - # together. - # - # The options (annotation) is treated the same as the ``options`` - # parameter to ``capture_exception`` or ``Event.from_exception``, and - # can contain the same ``:user``, ``:tags``, etc. options as these - # methods. - # - # These will be merged with the ``options`` parameter to - # ``Event.from_exception`` at the top of execution. - # - # @example - # begin - # raise "Hello" - # rescue => exc - # Raven.annotate_exception(exc, :user => { 'id' => 1, - # 'email' => 'foo@example.com' }) - # end - def annotate_exception(exc, options = {}) - notes = (exc.instance_variable_defined?(:@__raven_context) && exc.instance_variable_get(:@__raven_context)) || {} - Raven::Utils::DeepMergeHash.deep_merge!(notes, options) - exc.instance_variable_set(:@__raven_context, notes) - exc - end - - # Bind user context. Merges with existing context (if any). - # - # It is recommending that you send at least the ``id`` and ``email`` - # values. All other values are arbitrary. - # - # @example - # Raven.user_context('id' => 1, 'email' => 'foo@example.com') - def user_context(options = nil) - original_user_context = context.user - - if options - context.user = context.user.merge(options) - else - context.user = {} - end - - yield if block_given? - context.user - ensure - context.user = original_user_context if block_given? - end - - # Bind tags context. Merges with existing context (if any). - # - # Tags are key / value pairs which generally represent things like - # application version, environment, role, and server names. - # - # @example - # Raven.tags_context('my_custom_tag' => 'tag_value') - def tags_context(options = nil) - context.tags.merge!(options || {}) - yield if block_given? - context.tags - ensure - context.tags.delete_if { |k, _| options.keys.include? k } if block_given? - end - - # Bind extra context. Merges with existing context (if any). - # - # Extra context shows up as Additional Data within Sentry, and is - # completely arbitrary. - # - # @example - # Raven.extra_context('my_custom_data' => 'value') - def extra_context(options = nil) - context.extra.merge!(options || {}) - yield if block_given? - context.extra - ensure - context.extra.delete_if { |k, _| options.keys.include? k } if block_given? - end - - def rack_context(env) - env = nil if env.empty? - - context.rack_env = env - end - - def breadcrumbs - BreadcrumbBuffer.current - end - - private - - def install_at_exit_hook(options) - at_exit do - exception = $ERROR_INFO - if exception - logger.debug "Caught a post-mortem exception: #{exception.inspect}" - capture_type(exception, options) - end - end - end - - def make_hint(obj) - obj.is_a?(String) ? { :exception => nil, :message => obj } : { :exception => obj, :message => nil } - end - end -end diff --git a/sentry-raven/lib/raven/integrations/delayed_job.rb b/sentry-raven/lib/raven/integrations/delayed_job.rb deleted file mode 100644 index e69c369c4..000000000 --- a/sentry-raven/lib/raven/integrations/delayed_job.rb +++ /dev/null @@ -1,58 +0,0 @@ -require 'delayed_job' -require 'raven/utils/context_filter' - -module Delayed - module Plugins - class Raven < ::Delayed::Plugin - callbacks do |lifecycle| - lifecycle.around(:invoke_job) do |job, *args, &block| - begin - # Forward the call to the next callback in the callback chain - block.call(job, *args) - rescue Exception => e - # Log error to Sentry - extra = { - :delayed_job => { - :id => job.id.to_s, - :priority => job.priority, - :attempts => job.attempts, - :run_at => job.run_at, - :locked_at => job.locked_at, - :locked_by => job.locked_by, - :queue => job.queue, - :created_at => job.created_at - } - } - # last_error can be nil - extra[:last_error] = job.last_error[0...1000] if job.last_error - # handlers are YAML objects in strings, we definitely can't - # report all of that or the event will get truncated randomly - extra[:handler] = job.handler[0...1000] if job.handler - - if job.respond_to?('payload_object') && job.payload_object.respond_to?('job_data') - extra[:active_job] = ::Raven::Utils::ContextFilter.filter_context(job.payload_object.job_data) - end - ::Raven.capture_exception(e, - :logger => 'delayed_job', - :tags => { - :delayed_job_queue => job.queue, - :delayed_job_id => job.id.to_s - }, - :extra => extra) - - # Make sure we propagate the failure! - raise e - ensure - ::Raven::Context.clear! - ::Raven::BreadcrumbBuffer.clear! - end - end - end - end - end -end - -## -# Register DelayedJob Raven plugin -# -Delayed::Worker.plugins << Delayed::Plugins::Raven diff --git a/sentry-raven/lib/raven/integrations/rack-timeout.rb b/sentry-raven/lib/raven/integrations/rack-timeout.rb deleted file mode 100644 index 14952c688..000000000 --- a/sentry-raven/lib/raven/integrations/rack-timeout.rb +++ /dev/null @@ -1,22 +0,0 @@ -# We need to do this because of the way integration loading works -require "rack/timeout/base" unless defined?(Rack::Timeout) - -# This integration is a good example of how to change how exceptions -# get grouped by Sentry's UI. Simply override #raven_context in -# the exception class, and append something to the fingerprint -# that will distinguish exceptions in the way you desire. -module RackTimeoutExtensions - def raven_context - # Only rack-timeout 0.3.0+ provides the request environment, but we can't - # gate this based on a gem version constant because rack-timeout does - # not provide one. - if defined?(env) - { :fingerprint => ["{{ default }}", env["REQUEST_URI"]] } - else - {} - end - end -end - -Rack::Timeout::Error.include(RackTimeoutExtensions) -Rack::Timeout::RequestTimeoutException.include(RackTimeoutExtensions) diff --git a/sentry-raven/lib/raven/integrations/rack.rb b/sentry-raven/lib/raven/integrations/rack.rb deleted file mode 100644 index 73f875c2f..000000000 --- a/sentry-raven/lib/raven/integrations/rack.rb +++ /dev/null @@ -1,141 +0,0 @@ -require 'time' -require 'rack' - -module Raven - # Middleware for Rack applications. Any errors raised by the upstream - # application will be delivered to Sentry and re-raised. - # - # Synopsis: - # - # require 'rack' - # require 'raven' - # - # Raven.configure do |config| - # config.server = 'http://my_dsn' - # end - # - # app = Rack::Builder.app do - # use Raven::Rack - # run lambda { |env| raise "Rack down" } - # end - # - # Use a standard Raven.configure call to configure your server credentials. - class Rack - def self.capture_type(exception, env, options = {}) - if env['raven.requested_at'] - options[:time_spent] = Time.now - env['raven.requested_at'] - end - Raven.capture_type(exception, options) do |evt| - evt.interface :http do |int| - int.from_rack(env) - end - end - end - class << self - alias capture_message capture_type - alias capture_exception capture_type - end - - def initialize(app) - @app = app - end - - def call(env) - # store the current environment in our local context for arbitrary - # callers - env['raven.requested_at'] = Time.now - Raven.rack_context(env) - Raven.context.transaction.push(env["PATH_INFO"]) if env["PATH_INFO"] - - begin - response = @app.call(env) - rescue Error - raise # Don't capture Raven errors - rescue Exception => e - Raven::Rack.capture_exception(e, env) - raise - end - - error = env['rack.exception'] || env['sinatra.error'] - Raven::Rack.capture_exception(error, env) if error - - response - ensure - Context.clear! - BreadcrumbBuffer.clear! - end - end - - module RackInterface - def from_rack(env_hash) - req = ::Rack::Request.new(env_hash) - - self.url = req.scheme && req.url.split('?').first - self.method = req.request_method - self.query_string = req.query_string - self.data = read_data_from(req) - self.cookies = req.cookies - - self.headers = format_headers_for_sentry(env_hash) - self.env = format_env_for_sentry(env_hash) - end - - private - - # See Sentry server default limits at - # https://github.com/getsentry/sentry/blob/master/src/sentry/conf/server.py - def read_data_from(request) - if request.form_data? - request.POST - elsif request.body # JSON requests, etc - data = request.body.read(4096 * 4) # Sentry server limit - request.body.rewind - data - end - rescue IOError => e - e.message - end - - def format_headers_for_sentry(env_hash) - env_hash.each_with_object({}) do |(key, value), memo| - begin - key = key.to_s # rack env can contain symbols - next memo['X-Request-Id'] ||= Utils::RequestId.read_from(env_hash) if Utils::RequestId::REQUEST_ID_HEADERS.include?(key) - next unless key.upcase == key # Non-upper case stuff isn't either - - # Rack adds in an incorrect HTTP_VERSION key, which causes downstream - # to think this is a Version header. Instead, this is mapped to - # env['SERVER_PROTOCOL']. But we don't want to ignore a valid header - # if the request has legitimately sent a Version header themselves. - # See: https://github.com/rack/rack/blob/028438f/lib/rack/handler/cgi.rb#L29 - next if key == 'HTTP_VERSION' && value == env_hash['SERVER_PROTOCOL'] - next if key == 'HTTP_COOKIE' # Cookies don't go here, they go somewhere else - next unless key.start_with?('HTTP_') || %w(CONTENT_TYPE CONTENT_LENGTH).include?(key) - - # Rack stores headers as HTTP_WHAT_EVER, we need What-Ever - key = key.sub(/^HTTP_/, "") - key = key.split('_').map(&:capitalize).join('-') - memo[key] = value.to_s - rescue StandardError => e - # Rails adds objects to the Rack env that can sometimes raise exceptions - # when `to_s` is called. - # See: https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/remote_ip.rb#L134 - Raven.logger.warn("Error raised while formatting headers: #{e.message}") - next - end - end - end - - def format_env_for_sentry(env_hash) - return env_hash if Raven.configuration.rack_env_whitelist.empty? - - env_hash.select do |k, _v| - Raven.configuration.rack_env_whitelist.include? k.to_s - end - end - end - - class HttpInterface - include RackInterface - end -end diff --git a/sentry-raven/lib/raven/integrations/rails.rb b/sentry-raven/lib/raven/integrations/rails.rb deleted file mode 100644 index 42b76491f..000000000 --- a/sentry-raven/lib/raven/integrations/rails.rb +++ /dev/null @@ -1,89 +0,0 @@ -require 'rails' - -module Raven - class Rails < ::Rails::Railtie - require 'raven/integrations/rails/overrides/streaming_reporter' - require 'raven/integrations/rails/controller_methods' - require 'raven/integrations/rails/controller_transaction' - require 'raven/integrations/rails/backtrace_cleaner' - require 'raven/integrations/rack' - - initializer "raven.use_rack_middleware" do |app| - app.config.middleware.insert 0, Raven::Rack - end - - initializer 'raven.action_controller' do - ActiveSupport.on_load :action_controller do - include Raven::Rails::ControllerMethods - include Raven::Rails::ControllerTransaction - if ::Rails::VERSION::STRING >= "4.0.0" - Raven.safely_prepend( - "StreamingReporter", - :from => Raven::Rails::Overrides, - :to => ActionController::Live - ) - end - end - end - - initializer 'raven.action_view' do - ActiveSupport.on_load :action_view do - Raven.safely_prepend( - "StreamingReporter", - :from => Raven::Rails::Overrides, - :to => ActionView::StreamingTemplateRenderer::Body - ) - end - end - - config.before_initialize do - Raven.configuration.logger = ::Rails.logger - - backtrace_cleaner = Raven::Rails::BacktraceCleaner.new - - Raven.configuration.backtrace_cleanup_callback = lambda do |backtrace| - backtrace_cleaner.clean(backtrace) - end - end - - config.after_initialize do - if Raven.configuration.breadcrumbs_logger.include?(:active_support_logger) || - Raven.configuration.rails_activesupport_breadcrumbs - - require 'raven/breadcrumbs/active_support_logger' - Raven::Breadcrumbs::ActiveSupportLogger.inject - end - - if Raven.configuration.rails_report_rescued_exceptions - require 'raven/integrations/rails/overrides/debug_exceptions_catcher' - if defined?(::ActionDispatch::DebugExceptions) - exceptions_class = ::ActionDispatch::DebugExceptions - elsif defined?(::ActionDispatch::ShowExceptions) - exceptions_class = ::ActionDispatch::ShowExceptions - end - - Raven.safely_prepend( - "DebugExceptionsCatcher", - :from => Raven::Rails::Overrides, - :to => exceptions_class - ) - end - end - - initializer 'raven.active_job' do - ActiveSupport.on_load :active_job do - require 'raven/integrations/rails/active_job' - end - end - - rake_tasks do - require 'raven/integrations/tasks' - end - - if defined?(runner) - runner do - Raven.capture - end - end - end -end diff --git a/sentry-raven/lib/raven/integrations/rails/active_job.rb b/sentry-raven/lib/raven/integrations/rails/active_job.rb deleted file mode 100644 index 7bce01fca..000000000 --- a/sentry-raven/lib/raven/integrations/rails/active_job.rb +++ /dev/null @@ -1,63 +0,0 @@ -module Raven - class Rails - module ActiveJobExtensions - ALREADY_SUPPORTED_SENTRY_ADAPTERS = %w( - ActiveJob::QueueAdapters::SidekiqAdapter - ActiveJob::QueueAdapters::DelayedJobAdapter - ).freeze - - def self.included(base) - base.class_eval do - around_perform do |job, block| - if already_supported_by_specific_integration?(job) - block.call - else - capture_and_reraise_with_sentry(job, block) - end - end - end - end - - def capture_and_reraise_with_sentry(job, block) - block.call - rescue Exception => e # rubocop:disable Lint/RescueException - rescue_handler_result = rescue_with_handler(e) - return rescue_handler_result if rescue_handler_result - - Raven.capture_exception(e, :extra => raven_context(job)) - raise e - ensure - Context.clear! - BreadcrumbBuffer.clear! - end - - def already_supported_by_specific_integration?(job) - if ::Rails.version.to_f < 5.0 - ALREADY_SUPPORTED_SENTRY_ADAPTERS.include?(job.class.queue_adapter.to_s) - else - ALREADY_SUPPORTED_SENTRY_ADAPTERS.include?(job.class.queue_adapter.class.to_s) - end - end - - def raven_context(job) - ctx = { - :active_job => job.class.name, - :arguments => job.arguments, - :scheduled_at => job.scheduled_at, - :job_id => job.job_id, - :locale => job.locale - } - # Add provider_job_id details if Rails 5 - if job.respond_to?(:provider_job_id) - ctx[:provider_job_id] = job.provider_job_id - end - - ctx - end - end - end -end - -class ActiveJob::Base - include Raven::Rails::ActiveJobExtensions -end diff --git a/sentry-raven/lib/raven/integrations/rails/backtrace_cleaner.rb b/sentry-raven/lib/raven/integrations/rails/backtrace_cleaner.rb deleted file mode 100644 index 871ca03df..000000000 --- a/sentry-raven/lib/raven/integrations/rails/backtrace_cleaner.rb +++ /dev/null @@ -1,29 +0,0 @@ -require "active_support/backtrace_cleaner" -require "active_support/core_ext/string/access" - -module Raven - class Rails - class BacktraceCleaner < ActiveSupport::BacktraceCleaner - APP_DIRS_PATTERN = /\A(?:\.\/)?(?:app|config|lib|test|\(\w*\))/.freeze - RENDER_TEMPLATE_PATTERN = /:in `.*_\w+_{2,3}\d+_\d+'/.freeze - - def initialize - super - # we don't want any default silencers because they're too aggressive - remove_silencers! - - @root = "#{Raven.configuration.project_root}/" - add_filter do |line| - line.start_with?(@root) ? line.from(@root.size) : line - end - add_filter do |line| - if line =~ RENDER_TEMPLATE_PATTERN - line.sub(RENDER_TEMPLATE_PATTERN, "") - else - line - end - end - end - end - end -end diff --git a/sentry-raven/lib/raven/integrations/rails/controller_methods.rb b/sentry-raven/lib/raven/integrations/rails/controller_methods.rb deleted file mode 100644 index 9275b1538..000000000 --- a/sentry-raven/lib/raven/integrations/rails/controller_methods.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Raven - class Rails - module ControllerMethods - def capture_message(message, options = {}) - Raven::Rack.capture_message(message, request.env, options) - end - - def capture_exception(exception, options = {}) - Raven::Rack.capture_exception(exception, request.env, options) - end - end - end -end diff --git a/sentry-raven/lib/raven/integrations/rails/controller_transaction.rb b/sentry-raven/lib/raven/integrations/rails/controller_transaction.rb deleted file mode 100644 index 5ae0d3b63..000000000 --- a/sentry-raven/lib/raven/integrations/rails/controller_transaction.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Raven - class Rails - module ControllerTransaction - def self.included(base) - base.prepend_around_action do |controller, block| - Raven.context.transaction.push "#{controller.class}##{controller.action_name}" - block.call - Raven.context.transaction.pop - end - end - end - end -end diff --git a/sentry-raven/lib/raven/integrations/rails/overrides/debug_exceptions_catcher.rb b/sentry-raven/lib/raven/integrations/rails/overrides/debug_exceptions_catcher.rb deleted file mode 100644 index d525b2712..000000000 --- a/sentry-raven/lib/raven/integrations/rails/overrides/debug_exceptions_catcher.rb +++ /dev/null @@ -1,31 +0,0 @@ -module Raven - class Rails - module Overrides - module DebugExceptionsCatcher - def render_exception(env_or_request, exception) - begin - env = env_or_request.respond_to?(:env) ? env_or_request.env : env_or_request - Raven::Rack.capture_exception(exception, env) - rescue - end - super - end - end - - module OldDebugExceptionsCatcher - def self.included(base) - base.send(:alias_method_chain, :render_exception, :raven) - end - - def render_exception_with_raven(env_or_request, exception) - begin - env = env_or_request.respond_to?(:env) ? env_or_request.env : env_or_request - Raven::Rack.capture_exception(exception, env) - rescue - end - render_exception_without_raven(env_or_request, exception) - end - end - end - end -end diff --git a/sentry-raven/lib/raven/integrations/rails/overrides/streaming_reporter.rb b/sentry-raven/lib/raven/integrations/rails/overrides/streaming_reporter.rb deleted file mode 100644 index bdfca63ad..000000000 --- a/sentry-raven/lib/raven/integrations/rails/overrides/streaming_reporter.rb +++ /dev/null @@ -1,23 +0,0 @@ -module Raven - class Rails - module Overrides - module StreamingReporter - def log_error(exception) - Raven.capture_exception(exception) - super - end - end - - module OldStreamingReporter - def self.included(base) - base.send(:alias_method_chain, :log_error, :raven) - end - - def log_error_with_raven(exception) - Raven.capture_exception(exception) - log_error_without_raven(exception) - end - end - end - end -end diff --git a/sentry-raven/lib/raven/integrations/railties.rb b/sentry-raven/lib/raven/integrations/railties.rb deleted file mode 100644 index 6e9f91dc8..000000000 --- a/sentry-raven/lib/raven/integrations/railties.rb +++ /dev/null @@ -1 +0,0 @@ -require 'raven/integrations/rails' diff --git a/sentry-raven/lib/raven/integrations/rake.rb b/sentry-raven/lib/raven/integrations/rake.rb deleted file mode 100644 index e14174893..000000000 --- a/sentry-raven/lib/raven/integrations/rake.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'rake' -require 'rake/task' -require 'raven/integrations/tasks' - -module Rake - class Application - alias orig_display_error_messsage display_error_message - def display_error_message(ex) - Raven.capture_exception( - ex, - :transaction => top_level_tasks.join(' '), - :logger => 'rake', - :tags => { 'rake_task' => top_level_tasks.join(' ') } - ) - orig_display_error_messsage(ex) - end - end -end diff --git a/sentry-raven/lib/raven/integrations/sidekiq.rb b/sentry-raven/lib/raven/integrations/sidekiq.rb deleted file mode 100644 index b74c699a3..000000000 --- a/sentry-raven/lib/raven/integrations/sidekiq.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'time' -require 'sidekiq' -require 'raven/integrations/sidekiq/cleanup_middleware' -require 'raven/integrations/sidekiq/error_handler' - -if Sidekiq::VERSION > '3' - Sidekiq.configure_server do |config| - config.error_handlers << Raven::Sidekiq::ErrorHandler.new - config.server_middleware do |chain| - chain.add Raven::Sidekiq::CleanupMiddleware - end - end -end diff --git a/sentry-raven/lib/raven/integrations/sidekiq/cleanup_middleware.rb b/sentry-raven/lib/raven/integrations/sidekiq/cleanup_middleware.rb deleted file mode 100644 index c4ea26f12..000000000 --- a/sentry-raven/lib/raven/integrations/sidekiq/cleanup_middleware.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Raven - module Sidekiq - class CleanupMiddleware - def call(_worker, job, queue) - Raven.context.transaction.push "Sidekiq/#{job['class']}" - Raven.extra_context(:sidekiq => job.merge("queue" => queue)) - yield - Context.clear! - BreadcrumbBuffer.clear! - end - end - end -end diff --git a/sentry-raven/lib/raven/integrations/sidekiq/error_handler.rb b/sentry-raven/lib/raven/integrations/sidekiq/error_handler.rb deleted file mode 100644 index 80aef12da..000000000 --- a/sentry-raven/lib/raven/integrations/sidekiq/error_handler.rb +++ /dev/null @@ -1,38 +0,0 @@ -require 'raven/utils/context_filter' - -module Raven - module Sidekiq - class ErrorHandler - SIDEKIQ_NAME = "Sidekiq".freeze - - def call(ex, context) - context = Utils::ContextFilter.filter_context(context) - Raven.context.transaction.push transaction_from_context(context) - Raven.capture_exception( - ex, - :message => ex.message, - :extra => { :sidekiq => context } - ) - Context.clear! - BreadcrumbBuffer.clear! - end - - private - - # this will change in the future: - # https://github.com/mperham/sidekiq/pull/3161 - def transaction_from_context(context) - classname = (context["wrapped"] || context["class"] || - (context[:job] && (context[:job]["wrapped"] || context[:job]["class"])) - ) - if classname - "#{SIDEKIQ_NAME}/#{classname}" - elsif context[:event] - "#{SIDEKIQ_NAME}/#{context[:event]}" - else - SIDEKIQ_NAME - end - end - end - end -end diff --git a/sentry-raven/lib/raven/integrations/tasks.rb b/sentry-raven/lib/raven/integrations/tasks.rb deleted file mode 100644 index 8f698b95c..000000000 --- a/sentry-raven/lib/raven/integrations/tasks.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'rake' -require 'raven/cli' - -namespace :raven do - desc "Send a test event to the remote Sentry server" - task :test, [:dsn] do |_t, args| - Rake::Task["environment"].invoke if Rake::Task.tasks.map(&:to_s).include?("environment") - - Raven::CLI.test(args.dsn) - end -end diff --git a/sentry-raven/lib/raven/interface.rb b/sentry-raven/lib/raven/interface.rb deleted file mode 100644 index c4366cd1d..000000000 --- a/sentry-raven/lib/raven/interface.rb +++ /dev/null @@ -1,25 +0,0 @@ -module Raven - class Interface - def initialize(attributes = nil) - attributes&.each do |attr, value| - public_send "#{attr}=", value - end - - yield self if block_given? - end - - def self.inherited(klass) - name = klass.name.split("::").last.downcase.gsub("interface", "") - registered[name.to_sym] = klass - super - end - - def self.registered - @@registered ||= {} # rubocop:disable Style/ClassVars - end - - def to_hash - Hash[instance_variables.map { |name| [name[1..-1].to_sym, instance_variable_get(name)] }] - end - end -end diff --git a/sentry-raven/lib/raven/interfaces/exception.rb b/sentry-raven/lib/raven/interfaces/exception.rb deleted file mode 100644 index 97072d4f2..000000000 --- a/sentry-raven/lib/raven/interfaces/exception.rb +++ /dev/null @@ -1,15 +0,0 @@ -module Raven - class ExceptionInterface < Interface - attr_accessor :values - - def self.sentry_alias - :exception - end - - def to_hash(*args) - data = super(*args) - data[:values] = data[:values].map(&:to_hash) if data[:values] - data - end - end -end diff --git a/sentry-raven/lib/raven/interfaces/http.rb b/sentry-raven/lib/raven/interfaces/http.rb deleted file mode 100644 index ef3b70421..000000000 --- a/sentry-raven/lib/raven/interfaces/http.rb +++ /dev/null @@ -1,16 +0,0 @@ -module Raven - class HttpInterface < Interface - attr_accessor :url, :method, :data, :query_string, :cookies, :headers, :env - - def initialize(*arguments) - self.headers = {} - self.env = {} - self.cookies = nil - super(*arguments) - end - - def self.sentry_alias - :request - end - end -end diff --git a/sentry-raven/lib/raven/interfaces/message.rb b/sentry-raven/lib/raven/interfaces/message.rb deleted file mode 100644 index 594cc275c..000000000 --- a/sentry-raven/lib/raven/interfaces/message.rb +++ /dev/null @@ -1,20 +0,0 @@ -require 'raven/interface' - -module Raven - class MessageInterface < Interface - attr_accessor :message, :params - - def initialize(*arguments) - self.params = [] - super(*arguments) - end - - def unformatted_message - Array(params).empty? ? message : message % params - end - - def self.sentry_alias - :logentry - end - end -end diff --git a/sentry-raven/lib/raven/interfaces/single_exception.rb b/sentry-raven/lib/raven/interfaces/single_exception.rb deleted file mode 100644 index c0c3e8c7a..000000000 --- a/sentry-raven/lib/raven/interfaces/single_exception.rb +++ /dev/null @@ -1,14 +0,0 @@ -module Raven - class SingleExceptionInterface < Interface - attr_accessor :type - attr_accessor :value - attr_accessor :module - attr_accessor :stacktrace - - def to_hash(*args) - data = super(*args) - data[:stacktrace] = data[:stacktrace].to_hash if data[:stacktrace] - data - end - end -end diff --git a/sentry-raven/lib/raven/interfaces/stack_trace.rb b/sentry-raven/lib/raven/interfaces/stack_trace.rb deleted file mode 100644 index ec42ff91a..000000000 --- a/sentry-raven/lib/raven/interfaces/stack_trace.rb +++ /dev/null @@ -1,69 +0,0 @@ -module Raven - class StacktraceInterface < Interface - attr_accessor :frames - - def initialize(*arguments) - super(*arguments) - end - - def self.sentry_alias - :stacktrace - end - - def to_hash(*args) - data = super(*args) - data[:frames] = data[:frames].map(&:to_hash) - data - end - - # Not actually an interface, but I want to use the same style - class Frame < Interface - attr_accessor :abs_path, :context_line, :function, :in_app, - :lineno, :module, :pre_context, :post_context, :vars - - def initialize(*arguments) - super(*arguments) - end - - def filename - return if abs_path.nil? - return @filename if instance_variable_defined?(:@filename) - - prefix = - if under_project_root? && in_app - project_root - elsif under_project_root? - longest_load_path || project_root - else - longest_load_path - end - - @filename = prefix ? abs_path[prefix.to_s.chomp(File::SEPARATOR).length + 1..-1] : abs_path - end - - def to_hash(*args) - data = super(*args) - data[:filename] = filename - data.delete(:vars) unless vars && !vars.empty? - data.delete(:pre_context) unless pre_context && !pre_context.empty? - data.delete(:post_context) unless post_context && !post_context.empty? - data.delete(:context_line) unless context_line && !context_line.empty? - data - end - - private - - def under_project_root? - project_root && abs_path.start_with?(project_root) - end - - def project_root - @project_root ||= Raven.configuration.project_root&.to_s - end - - def longest_load_path - $LOAD_PATH.select { |path| abs_path.start_with?(path.to_s) }.max_by(&:size) - end - end - end -end diff --git a/sentry-raven/lib/raven/linecache.rb b/sentry-raven/lib/raven/linecache.rb deleted file mode 100644 index ae1f5b477..000000000 --- a/sentry-raven/lib/raven/linecache.rb +++ /dev/null @@ -1,44 +0,0 @@ -module Raven - class LineCache - def initialize - @cache = {} - end - - # Any linecache you provide to Raven must implement this method. - # Returns an Array of Strings representing the lines in the source - # file. The number of lines retrieved is (2 * context) + 1, the middle - # line should be the line requested by lineno. See specs for more information. - def get_file_context(filename, lineno, context) - return nil, nil, nil unless valid_path?(filename) - - lines = Array.new(2 * context + 1) do |i| - getline(filename, lineno - context + i) - end - [lines[0..(context - 1)], lines[context], lines[(context + 1)..-1]] - end - - private - - def valid_path?(path) - lines = getlines(path) - !lines.nil? - end - - def getlines(path) - @cache[path] ||= begin - File.open(path, "r", &:readlines) - rescue - nil - end - end - - def getline(path, n) - return nil if n < 1 - - lines = getlines(path) - return nil if lines.nil? - - lines[n - 1] - end - end -end diff --git a/sentry-raven/lib/raven/logger.rb b/sentry-raven/lib/raven/logger.rb deleted file mode 100644 index 7450e85b7..000000000 --- a/sentry-raven/lib/raven/logger.rb +++ /dev/null @@ -1,20 +0,0 @@ -# frozen_string_literal: true - -require 'logger' - -module Raven - class Logger < ::Logger - LOG_PREFIX = "** [Raven] " - PROGNAME = "sentry" - - def initialize(*) - super - @level = ::Logger::INFO - original_formatter = ::Logger::Formatter.new - @default_formatter = proc do |severity, datetime, _progname, msg| - msg = "#{LOG_PREFIX}#{msg}" - original_formatter.call(severity, datetime, PROGNAME, msg) - end - end - end -end diff --git a/sentry-raven/lib/raven/processor.rb b/sentry-raven/lib/raven/processor.rb deleted file mode 100644 index 68ad5c2a1..000000000 --- a/sentry-raven/lib/raven/processor.rb +++ /dev/null @@ -1,15 +0,0 @@ -module Raven - class Processor - STRING_MASK = '********'.freeze - INT_MASK = 0 - REGEX_SPECIAL_CHARACTERS = %w(. $ ^ { [ ( | ) * + ?).freeze - - def initialize(client = nil) - @client = client - end - - def process(_data) - raise NotImplementedError - end - end -end diff --git a/sentry-raven/lib/raven/processor/cookies.rb b/sentry-raven/lib/raven/processor/cookies.rb deleted file mode 100644 index 609e41fb4..000000000 --- a/sentry-raven/lib/raven/processor/cookies.rb +++ /dev/null @@ -1,36 +0,0 @@ -module Raven - class Processor::Cookies < Processor - def process(data) - process_if_symbol_keys(data) if data[:request] - process_if_string_keys(data) if data["request"] - - data - end - - private - - def process_if_symbol_keys(data) - if cookies = data.dig(:request, :cookies) - data[:request][:cookies] = generate_masked_cookies(cookies) - end - - if cookies_header = data[:request][:headers]["Cookie"] - data[:request][:headers]["Cookie"] = generate_masked_cookies(cookies_header) - end - end - - def process_if_string_keys(data) - if cookies = data.dig("request", "cookies") - data["request"]["cookies"] = generate_masked_cookies(cookies) - end - - if cookies_header = data.dig("request", "headers", "Cookie") - data["request"]["headers"]["Cookie"] = generate_masked_cookies(cookies_header) - end - end - - def generate_masked_cookies(cookies) - cookies.merge(cookies) { STRING_MASK } if cookies.respond_to?(:merge) - end - end -end diff --git a/sentry-raven/lib/raven/processor/http_headers.rb b/sentry-raven/lib/raven/processor/http_headers.rb deleted file mode 100644 index 95751c28a..000000000 --- a/sentry-raven/lib/raven/processor/http_headers.rb +++ /dev/null @@ -1,55 +0,0 @@ -module Raven - class Processor::HTTPHeaders < Processor - DEFAULT_FIELDS = ["Authorization"].freeze - - attr_accessor :sanitize_http_headers - - def initialize(client) - super - self.sanitize_http_headers = client.configuration.sanitize_http_headers - end - - def process(data) - process_if_symbol_keys(data) if data[:request] - process_if_string_keys(data) if data["request"] - - data - end - - private - - def process_if_symbol_keys(data) - return unless data[:request][:headers] - - data[:request][:headers].keys.select { |k| fields_re.match(k.to_s) }.each do |k| - data[:request][:headers][k] = STRING_MASK - end - end - - def process_if_string_keys(data) - return unless data["request"]["headers"] - - data["request"]["headers"].keys.select { |k| fields_re.match(k) }.each do |k| - data["request"]["headers"][k] = STRING_MASK - end - end - - def matches_regexes?(k) - fields_re.match(k.to_s) - end - - def fields_re - @fields_re ||= /#{(DEFAULT_FIELDS | sanitize_http_headers).map do |f| - use_boundary?(f) ? "\\b#{f}\\b" : f - end.join("|")}/i - end - - def use_boundary?(string) - !DEFAULT_FIELDS.include?(string) && !special_characters?(string) - end - - def special_characters?(string) - REGEX_SPECIAL_CHARACTERS.select { |r| string.include?(r) }.any? - end - end -end diff --git a/sentry-raven/lib/raven/processor/post_data.rb b/sentry-raven/lib/raven/processor/post_data.rb deleted file mode 100644 index 6d7ea2d34..000000000 --- a/sentry-raven/lib/raven/processor/post_data.rb +++ /dev/null @@ -1,24 +0,0 @@ -module Raven - class Processor::PostData < Processor - def process(data) - process_if_symbol_keys(data) if data[:request] - process_if_string_keys(data) if data["request"] - - data - end - - private - - def process_if_symbol_keys(data) - return unless data[:request][:method] == "POST" - - data[:request][:data] = STRING_MASK - end - - def process_if_string_keys(data) - return unless data["request"]["method"] == "POST" - - data["request"]["data"] = STRING_MASK - end - end -end diff --git a/sentry-raven/lib/raven/processor/removecircularreferences.rb b/sentry-raven/lib/raven/processor/removecircularreferences.rb deleted file mode 100644 index a4114bf52..000000000 --- a/sentry-raven/lib/raven/processor/removecircularreferences.rb +++ /dev/null @@ -1,19 +0,0 @@ -module Raven - class Processor::RemoveCircularReferences < Processor - ELISION_STRING = "(...)".freeze - def process(value, visited = []) - return ELISION_STRING if visited.include?(value.__id__) - - visited << value.__id__ if value.is_a?(Array) || value.is_a?(Hash) - - case value - when Hash - !value.frozen? ? value.merge!(value) { |_, v| process v, visited } : value.merge(value) { |_, v| process v, visited } - when Array - !value.frozen? ? value.map! { |v| process v, visited } : value.map { |v| process v, visited } - else - value - end - end - end -end diff --git a/sentry-raven/lib/raven/processor/removestacktrace.rb b/sentry-raven/lib/raven/processor/removestacktrace.rb deleted file mode 100644 index 069b39e17..000000000 --- a/sentry-raven/lib/raven/processor/removestacktrace.rb +++ /dev/null @@ -1,24 +0,0 @@ -module Raven - class Processor::RemoveStacktrace < Processor - def process(data) - process_if_symbol_keys(data) if data[:exception] - process_if_string_keys(data) if data["exception"] - - data - end - - private - - def process_if_symbol_keys(data) - data[:exception][:values].map do |single_exception| - single_exception.delete(:stacktrace) if single_exception[:stacktrace] - end - end - - def process_if_string_keys(data) - data["exception"]["values"].map do |single_exception| - single_exception.delete("stacktrace") if single_exception["stacktrace"] - end - end - end -end diff --git a/sentry-raven/lib/raven/processor/sanitizedata.rb b/sentry-raven/lib/raven/processor/sanitizedata.rb deleted file mode 100644 index bf4cb2f8c..000000000 --- a/sentry-raven/lib/raven/processor/sanitizedata.rb +++ /dev/null @@ -1,136 +0,0 @@ -# frozen_string_literal: true - -require 'json' - -module Raven - class Processor::SanitizeData < Processor - DEFAULT_FIELDS = %w(authorization password passwd secret ssn social(.*)?sec).freeze - CREDIT_CARD_RE = /\b(?:3[47]\d|(?:4\d|5[1-5]|65)\d{2}|6011)\d{12}\b/.freeze - QUERY_STRING = ['query_string', :query_string].freeze - JSON_STARTS_WITH = ["[", "{"].freeze - - attr_accessor :sanitize_fields, :sanitize_credit_cards, :sanitize_fields_excluded - - def initialize(client) - super - self.sanitize_fields = client.configuration.sanitize_fields - self.sanitize_credit_cards = client.configuration.sanitize_credit_cards - self.sanitize_fields_excluded = client.configuration.sanitize_fields_excluded - end - - def process(value, key = nil) - case value - when Hash - sanitize_hash_value(key, value) - when Array - sanitize_array_value(key, value) - when Integer - matches_regexes?(key, value.to_s) ? INT_MASK : value - when String - sanitize_string_value(key, value) - else - value - end - end - - private - - # CGI.parse takes our nice UTF-8 strings and converts them back to ASCII, - # so we have to convert them back, again. - def utf8_processor - @utf8_processor ||= Processor::UTF8Conversion.new - end - - def sanitize_hash_value(key, value) - if key =~ sensitive_fields - STRING_MASK - elsif value.frozen? - value.merge(value) { |k, v| process v, k } - else - value.merge!(value) { |k, v| process v, k } - end - end - - def sanitize_array_value(key, value) - if value.frozen? - value.map { |v| process v, key } - else - value.map! { |v| process v, key } - end - end - - def sanitize_string_value(key, value) - if value =~ sensitive_fields && (json = parse_json_or_nil(value)) - # if this string is actually a json obj, convert and sanitize - process(json).to_json - elsif matches_regexes?(key, value) - STRING_MASK - elsif QUERY_STRING.include?(key) - sanitize_query_string(value) - elsif value =~ sensitive_fields - sanitize_sensitive_string_content(value) - else - value - end - end - - def sanitize_query_string(query_string) - query_hash = CGI.parse(query_string) - sanitized = utf8_processor.process(query_hash) - processed_query_hash = process(sanitized) - URI.encode_www_form(processed_query_hash) - end - - # this scrubs some sensitive info from the string content. for example: - # - # ``` - # unexpected token at '{ - # "role": "admin","password": "Abc@123","foo": "bar" - # }' - # ``` - # - # will become - # - # ``` - # unexpected token at '{ - # "role": "admin","password": *******,"foo": "bar" - # }' - # ``` - # - # it's particularly useful in hash or param-parsing related errors - def sanitize_sensitive_string_content(value) - value.gsub(/(#{sensitive_fields}['":]\s?(:|=>)?\s?)(".*?"|'.*?')/, '\1' + STRING_MASK) - end - - def matches_regexes?(k, v) - (sanitize_credit_cards && v =~ CREDIT_CARD_RE) || - k =~ sensitive_fields - end - - def sensitive_fields - return @sensitive_fields if instance_variable_defined?(:@sensitive_fields) - - fields = DEFAULT_FIELDS | sanitize_fields - fields -= sanitize_fields_excluded - @sensitive_fields = /#{fields.map do |f| - use_boundary?(f) ? "\\b#{f}\\b" : f - end.join("|")}/i - end - - def use_boundary?(string) - !DEFAULT_FIELDS.include?(string) && !special_characters?(string) - end - - def special_characters?(string) - REGEX_SPECIAL_CHARACTERS.select { |r| string.include?(r) }.any? - end - - def parse_json_or_nil(string) - return unless string.start_with?(*JSON_STARTS_WITH) - - JSON.parse(string) - rescue JSON::ParserError, NoMethodError - nil - end - end -end diff --git a/sentry-raven/lib/raven/processor/utf8conversion.rb b/sentry-raven/lib/raven/processor/utf8conversion.rb deleted file mode 100644 index 2fab3bdfb..000000000 --- a/sentry-raven/lib/raven/processor/utf8conversion.rb +++ /dev/null @@ -1,54 +0,0 @@ -module Raven - class Processor::UTF8Conversion < Processor - # Slightly misnamed - actually just removes any bytes with invalid encoding - # Previously, our JSON backend required UTF-8. Since we now use the built-in - # JSON, we can use any encoding, but it must be valid anyway so we can do - # things like call #match and #slice on strings - REPLACE = "".freeze - - def process(value) - case value - when Hash - !value.frozen? ? value.merge!(value) { |_, v| process v } : value.merge(value) { |_, v| process v } - when Array - !value.frozen? ? value.map! { |v| process v } : value.map { |v| process v } - when Exception - return value if value.message.valid_encoding? - - clean_exc = value.class.new(remove_invalid_bytes(value.message)) - clean_exc.set_backtrace(value.backtrace) - clean_exc - when String - # Encoding::BINARY / Encoding::ASCII_8BIT is a special binary encoding. - # valid_encoding? will always return true because it contains all codepoints, - # so instead we check if it only contains actual ASCII codepoints, and if - # not we assume it's actually just UTF8 and scrub accordingly. - if value.encoding == Encoding::BINARY && !value.ascii_only? - value = value.dup - value.force_encoding(Encoding::UTF_8) - end - return value if value.valid_encoding? - - remove_invalid_bytes(value) - else - value - end - end - - private - - # Stolen from RSpec - # https://github.com/rspec/rspec-support/blob/f0af3fd74a94ff7bb700f6ba06dbdc67bba17fbf/lib/rspec/support/encoded_string.rb#L120-L139 - if String.method_defined?(:scrub) # 2.1+ - def remove_invalid_bytes(string) - string.scrub(REPLACE) - end - else - def remove_invalid_bytes(string) - string.chars.map do |char| - char.valid_encoding? ? char : REPLACE - end.join - end - end - end -end diff --git a/sentry-raven/lib/raven/transports.rb b/sentry-raven/lib/raven/transports.rb deleted file mode 100644 index 8fd518464..000000000 --- a/sentry-raven/lib/raven/transports.rb +++ /dev/null @@ -1,19 +0,0 @@ -module Raven - module Transports - class Transport - attr_accessor :configuration - - def initialize(configuration) - @configuration = configuration - end - - def send_event # (auth_header, data, options = {}) - raise NotImplementedError, 'Abstract method not implemented' - end - end - end -end - -require "raven/transports/dummy" -require "raven/transports/http" -require "raven/transports/stdout" diff --git a/sentry-raven/lib/raven/transports/dummy.rb b/sentry-raven/lib/raven/transports/dummy.rb deleted file mode 100644 index 3653b0fa9..000000000 --- a/sentry-raven/lib/raven/transports/dummy.rb +++ /dev/null @@ -1,16 +0,0 @@ -module Raven - module Transports - class Dummy < Transport - attr_accessor :events - - def initialize(*) - super - @events = [] - end - - def send_event(auth_header, data, options = {}) - @events << [auth_header, data, options] - end - end - end -end diff --git a/sentry-raven/lib/raven/transports/http.rb b/sentry-raven/lib/raven/transports/http.rb deleted file mode 100644 index e406bb134..000000000 --- a/sentry-raven/lib/raven/transports/http.rb +++ /dev/null @@ -1,67 +0,0 @@ -require 'faraday' - -module Raven - module Transports - class HTTP < Transport - attr_accessor :conn, :adapter - - def initialize(*args) - super - self.adapter = configuration.http_adapter || Faraday.default_adapter - self.conn = set_conn - end - - def send_event(auth_header, data, options = {}) - unless configuration.sending_allowed? - configuration.logger.debug("Event not sent: #{configuration.error_messages}") - return - end - - project_id = configuration[:project_id] - path = configuration[:path] + "/" - - conn.post "#{path}api/#{project_id}/store/" do |req| - req.headers['Content-Type'] = options[:content_type] - req.headers['X-Sentry-Auth'] = auth_header - req.body = data - end - rescue Faraday::Error => e - error_info = e.message - if e.response && e.response[:headers]['x-sentry-error'] - error_info += " Error in headers is: #{e.response[:headers]['x-sentry-error']}" - end - raise Raven::Error, error_info - end - - private - - def set_conn - configuration.logger.debug "Raven HTTP Transport connecting to #{configuration.server}" - - proxy = configuration.public_send(:proxy) - - Faraday.new(configuration.server, :ssl => ssl_configuration, :proxy => proxy) do |builder| - configuration.faraday_builder&.call(builder) - builder.response :raise_error - builder.options.merge! faraday_opts - builder.headers[:user_agent] = "sentry-ruby/#{Raven::VERSION}" - builder.adapter(*adapter) - end - end - - # TODO: deprecate and replace where possible w/Faraday Builder - def faraday_opts - [:timeout, :open_timeout].each_with_object({}) do |opt, memo| - memo[opt] = configuration.public_send(opt) if configuration.public_send(opt) - end - end - - def ssl_configuration - (configuration.ssl || {}).merge( - :verify => configuration.ssl_verification, - :ca_file => configuration.ssl_ca_file - ) - end - end - end -end diff --git a/sentry-raven/lib/raven/transports/stdout.rb b/sentry-raven/lib/raven/transports/stdout.rb deleted file mode 100644 index ca1df4e52..000000000 --- a/sentry-raven/lib/raven/transports/stdout.rb +++ /dev/null @@ -1,20 +0,0 @@ -module Raven - module Transports - class Stdout < Transport - attr_accessor :events - - def initialize(*) - super - end - - def send_event(_auth_header, data, _options = {}) - unless configuration.sending_allowed? - logger.debug("Event not sent: #{configuration.error_messages}") - end - - $stdout.puts data - $stdout.flush - end - end - end -end diff --git a/sentry-raven/lib/raven/utils/context_filter.rb b/sentry-raven/lib/raven/utils/context_filter.rb deleted file mode 100644 index d46f60181..000000000 --- a/sentry-raven/lib/raven/utils/context_filter.rb +++ /dev/null @@ -1,42 +0,0 @@ -module Raven - module Utils - module ContextFilter - class << self - ACTIVEJOB_RESERVED_PREFIX_REGEX = /^_aj_/.freeze - HAS_GLOBALID = const_defined?('GlobalID') - - # Once an ActiveJob is queued, ActiveRecord references get serialized into - # some internal reserved keys, such as _aj_globalid. - # - # The problem is, if this job in turn gets queued back into ActiveJob with - # these magic reserved keys, ActiveJob will throw up and error. We want to - # capture these and mutate the keys so we can sanely report it. - def filter_context(context) - case context - when Array - context.map { |arg| filter_context(arg) } - when Hash - Hash[context.map { |key, value| filter_context_hash(key, value) }] - else - format_globalid(context) - end - end - - private - - def filter_context_hash(key, value) - key = key.to_s.sub(ACTIVEJOB_RESERVED_PREFIX_REGEX, "") if key.match(ACTIVEJOB_RESERVED_PREFIX_REGEX) - [key, filter_context(value)] - end - - def format_globalid(context) - if HAS_GLOBALID && context.is_a?(GlobalID) - context.to_s - else - context - end - end - end - end - end -end diff --git a/sentry-raven/lib/raven/utils/deep_merge.rb b/sentry-raven/lib/raven/utils/deep_merge.rb deleted file mode 100644 index 0b3f41421..000000000 --- a/sentry-raven/lib/raven/utils/deep_merge.rb +++ /dev/null @@ -1,22 +0,0 @@ -module Raven - module Utils - # ported from ActiveSupport - module DeepMergeHash - def self.deep_merge(hash, other_hash, &block) - deep_merge!(hash, other_hash, &block) - end - - def self.deep_merge!(hash, other_hash, &block) - hash.merge!(other_hash) do |key, this_val, other_val| - if this_val.is_a?(Hash) && other_val.is_a?(Hash) - deep_merge(this_val, other_val, &block) - elsif block_given? - block.call(key, this_val, other_val) - else - other_val - end - end - end - end - end -end diff --git a/sentry-raven/lib/raven/utils/exception_cause_chain.rb b/sentry-raven/lib/raven/utils/exception_cause_chain.rb deleted file mode 100644 index 3b69c866b..000000000 --- a/sentry-raven/lib/raven/utils/exception_cause_chain.rb +++ /dev/null @@ -1,20 +0,0 @@ -module Raven - module Utils - module ExceptionCauseChain - def self.exception_to_array(exception) - if exception.respond_to?(:cause) && exception.cause - exceptions = [exception] - while exception.cause - exception = exception.cause - break if exceptions.any? { |e| e.object_id == exception.object_id } - - exceptions << exception - end - exceptions - else - [exception] - end - end - end - end -end diff --git a/sentry-raven/lib/raven/utils/real_ip.rb b/sentry-raven/lib/raven/utils/real_ip.rb deleted file mode 100644 index 2bec72926..000000000 --- a/sentry-raven/lib/raven/utils/real_ip.rb +++ /dev/null @@ -1,62 +0,0 @@ -require 'ipaddr' - -# Based on ActionDispatch::RemoteIp. All security-related precautions from that -# middleware have been removed, because the Event IP just needs to be accurate, -# and spoofing an IP here only makes data inaccurate, not insecure. Don't re-use -# this module if you have to *trust* the IP address. -module Raven - module Utils - class RealIp - LOCAL_ADDRESSES = [ - "127.0.0.1", # localhost IPv4 - "::1", # localhost IPv6 - "fc00::/7", # private IPv6 range fc00::/7 - "10.0.0.0/8", # private IPv4 range 10.x.x.x - "172.16.0.0/12", # private IPv4 range 172.16.0.0 .. 172.31.255.255 - "192.168.0.0/16" # private IPv4 range 192.168.x.x - ].map { |proxy| IPAddr.new(proxy) } - - attr_accessor :ip, :ip_addresses - - def initialize(ip_addresses) - self.ip_addresses = ip_addresses - end - - def calculate_ip - # CGI environment variable set by Rack - remote_addr = ips_from(ip_addresses[:remote_addr]).last - - # Could be a CSV list and/or repeated headers that were concatenated. - client_ips = ips_from(ip_addresses[:client_ip]) - real_ips = ips_from(ip_addresses[:real_ip]) - forwarded_ips = ips_from(ip_addresses[:forwarded_for]) - - ips = [client_ips, real_ips, forwarded_ips, remote_addr].flatten.compact - - # If every single IP option is in the trusted list, just return REMOTE_ADDR - self.ip = filter_local_addresses(ips).first || remote_addr - end - - protected - - def ips_from(header) - # Split the comma-separated list into an array of strings - ips = header ? header.strip.split(/[,\s]+/) : [] - ips.select do |ip| - begin - # Only return IPs that are valid according to the IPAddr#new method - range = IPAddr.new(ip).to_range - # we want to make sure nobody is sneaking a netmask in - range.begin == range.end - rescue ArgumentError - nil - end - end - end - - def filter_local_addresses(ips) - ips.reject { |ip| LOCAL_ADDRESSES.any? { |proxy| proxy === ip } } - end - end - end -end diff --git a/sentry-raven/lib/raven/utils/request_id.rb b/sentry-raven/lib/raven/utils/request_id.rb deleted file mode 100644 index ff0106dfc..000000000 --- a/sentry-raven/lib/raven/utils/request_id.rb +++ /dev/null @@ -1,16 +0,0 @@ -module Raven - module Utils - module RequestId - REQUEST_ID_HEADERS = %w(action_dispatch.request_id HTTP_X_REQUEST_ID).freeze - - # Request ID based on ActionDispatch::RequestId - def self.read_from(env_hash) - REQUEST_ID_HEADERS.each do |key| - request_id = env_hash[key] - return request_id if request_id - end - nil - end - end - end -end diff --git a/sentry-raven/lib/raven/version.rb b/sentry-raven/lib/raven/version.rb deleted file mode 100644 index 007f6d60c..000000000 --- a/sentry-raven/lib/raven/version.rb +++ /dev/null @@ -1,5 +0,0 @@ -# frozen_string_literal: true - -module Raven - VERSION = "3.1.2" -end diff --git a/sentry-raven/lib/sentry-raven-without-integrations.rb b/sentry-raven/lib/sentry-raven-without-integrations.rb deleted file mode 100644 index 17c2e5782..000000000 --- a/sentry-raven/lib/sentry-raven-without-integrations.rb +++ /dev/null @@ -1,6 +0,0 @@ -require "raven/helpers/deprecation_helper" - -filename = "sentry_raven_without_integrations" -DeprecationHelper.deprecate_dasherized_filename(filename) - -require filename diff --git a/sentry-raven/lib/sentry-raven.rb b/sentry-raven/lib/sentry-raven.rb deleted file mode 100644 index 9ffaeba50..000000000 --- a/sentry-raven/lib/sentry-raven.rb +++ /dev/null @@ -1 +0,0 @@ -require "raven" diff --git a/sentry-raven/lib/sentry_raven_without_integrations.rb b/sentry-raven/lib/sentry_raven_without_integrations.rb deleted file mode 100644 index e639d3b31..000000000 --- a/sentry-raven/lib/sentry_raven_without_integrations.rb +++ /dev/null @@ -1 +0,0 @@ -require 'raven/base' diff --git a/sentry-raven/sentry-raven.gemspec b/sentry-raven/sentry-raven.gemspec deleted file mode 100644 index f1f6b7dfb..000000000 --- a/sentry-raven/sentry-raven.gemspec +++ /dev/null @@ -1,28 +0,0 @@ -$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) -require 'raven/version' - -Gem::Specification.new do |gem| - gem.name = "sentry-raven" - gem.authors = ["Sentry Team"] - gem.description = gem.summary = "A gem that provides a client interface for the Sentry error logger" - gem.email = "accounts@sentry.io" - gem.license = 'Apache-2.0' - gem.homepage = "https://github.com/getsentry/raven-ruby" - - gem.version = Raven::VERSION - gem.platform = Gem::Platform::RUBY - gem.required_ruby_version = '>= 2.3' - gem.extra_rdoc_files = ["README.md", "LICENSE"] - gem.files = `git ls-files | grep -Ev '^(spec|benchmarks|examples)'`.split("\n") - gem.bindir = "exe" - gem.executables = "raven" - - gem.add_dependency "faraday", ">= 1.0" - - gem.post_install_message = <<~EOS - `sentry-raven` is deprecated! Please migrate to `sentry-ruby` - - See https://docs.sentry.io/platforms/ruby/migration for the migration guide. - - EOS -end diff --git a/sentry-raven/spec/raven/backtrace_spec.rb b/sentry-raven/spec/raven/backtrace_spec.rb deleted file mode 100644 index dae416ba1..000000000 --- a/sentry-raven/spec/raven/backtrace_spec.rb +++ /dev/null @@ -1,37 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Backtrace do - before(:each) do - @backtrace = Raven::Backtrace.parse(Thread.current.backtrace) - end - - it "calls backtrace_cleanup_callback if it's present in the configuration" do - called = false - callback = proc do |backtrace| - called = true - backtrace - end - config = Raven.configuration - config.backtrace_cleanup_callback = callback - Raven::Backtrace.parse(Thread.current.backtrace, configuration: config) - - expect(called).to eq(true) - end - - it "#lines" do - expect(@backtrace.lines.first).to be_a(Raven::Backtrace::Line) - end - - it "#inspect" do - expect(@backtrace.inspect).to match(/Backtrace: .*>$/) - end - - it "#to_s" do - expect(@backtrace.to_s).to match(/backtrace_spec.rb:5/) - end - - it "==" do - @backtrace2 = Raven::Backtrace.new(@backtrace.lines) - expect(@backtrace).to be == @backtrace2 - end -end diff --git a/sentry-raven/spec/raven/breadcrumbs/active_support_breadcrumbs_spec.rb b/sentry-raven/spec/raven/breadcrumbs/active_support_breadcrumbs_spec.rb deleted file mode 100644 index f2c8a8103..000000000 --- a/sentry-raven/spec/raven/breadcrumbs/active_support_breadcrumbs_spec.rb +++ /dev/null @@ -1,53 +0,0 @@ -require "spec_helper" - -RSpec.describe "Raven::Breadcrumbs::ActiveSupportLogger", :type => :request, :rails => true do - before(:all) do - Raven.configuration.breadcrumbs_logger = [:active_support_logger] - Rails.application = make_basic_app - end - - after(:all) do - Raven.configuration.breadcrumbs_logger = [] - Raven::Breadcrumbs::ActiveSupportLogger.detach - # even though we cleanup breadcrumbs in the rack middleware - # Breadcrumbs::ActiveSupportLogger subscribes to "every" instrumentation - # so it'll create other instrumentations "after" the request is finished - # and we should clear those as well - Raven::BreadcrumbBuffer.clear! - end - - it "captures correct data" do - get "/exception" - - expect(response.status).to eq(500) - event = JSON.parse!(Raven.client.transport.events.first[1]) - breadcrumbs = event.dig("breadcrumbs", "values") - expect(breadcrumbs.count).to eq(2) - - if Rails.version.to_i >= 5 - expect(breadcrumbs.first["data"]).to match( - { - "controller" => "HelloController", - "action" => "exception", - "params" => { "controller" => "hello", "action" => "exception" }, - "headers" => anything, - "format" => "html", - "method" => "GET", - "path" => "/exception" - } - ) - else - expect(breadcrumbs.first["data"]).to match( - { - "controller" => "HelloController", - "action" => "exception", - "params" => { "controller" => "hello", "action" => "exception" }, - "format" => "html", - "method" => "GET", - "path" => "/exception" - } - ) - - end - end -end diff --git a/sentry-raven/spec/raven/breadcrumbs/sentry_logger_spec.rb b/sentry-raven/spec/raven/breadcrumbs/sentry_logger_spec.rb deleted file mode 100644 index 8781ca404..000000000 --- a/sentry-raven/spec/raven/breadcrumbs/sentry_logger_spec.rb +++ /dev/null @@ -1,37 +0,0 @@ -require "spec_helper" - -RSpec.describe "Raven::Breadcrumbs::SentryLogger", :type => :request, :rails => true do - before(:all) do - Raven.configuration.breadcrumbs_logger = [:sentry_logger] - Rails.application = make_basic_app - end - - after(:all) do - Raven.configuration.breadcrumbs_logger = [] - # revert the injected methods to keep other specs clean - Raven::Breadcrumbs::SentryLogger.module_eval do - def add(*args) - super - end - end - end - - it "captures correct data" do - get "/exception" - - expect(response.status).to eq(500) - event = JSON.parse!(Raven.client.transport.events.first[1]) - breadcrumbs = event.dig("breadcrumbs", "values") - expect(breadcrumbs.count).to eq(1) - expect(breadcrumbs.first).to match( - { - "category" => "Processing by HelloController#exception as HTML", - "data" => {}, - "level" => "info", - "message" => "Processing by HelloController#exception as HTML", - "timestamp" => anything, - "type" => "info" - } - ) - end -end diff --git a/sentry-raven/spec/raven/breadcrumbs_spec.rb b/sentry-raven/spec/raven/breadcrumbs_spec.rb deleted file mode 100644 index df2c2c10d..000000000 --- a/sentry-raven/spec/raven/breadcrumbs_spec.rb +++ /dev/null @@ -1,68 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::BreadcrumbBuffer do - before(:each) do - @breadcrumbs = Raven::BreadcrumbBuffer.new(10) - end - - it "records breadcrumbs w/a block" do - expect(@breadcrumbs.empty?).to be true - - @breadcrumbs.record do - Raven::Breadcrumb.new.tap { |b| b.message = "test" } - end - - expect(@breadcrumbs.members.size).to eq(1) - expect(@breadcrumbs.empty?).to be false - end - - it "records breadcrumbs w/o block" do - crumb = Raven::Breadcrumb.new.tap { |b| b.message = "test" } - @breadcrumbs.record(crumb) - - expect(@breadcrumbs.members[0]).to eq(crumb) - end - - it "allows peeking" do - expect(@breadcrumbs.peek).to eq(nil) - - crumb = Raven::Breadcrumb.new.tap { |b| b.message = "test" } - @breadcrumbs.record(crumb) - - expect(@breadcrumbs.peek).to eq(crumb) - end - - it "is enumerable" do - (0..10).each do |i| - @breadcrumbs.record(Raven::Breadcrumb.new.tap { |b| b.message = i }) - end - - expect(@breadcrumbs.each).to be_a Enumerator - end - - it "evicts when buffer exceeded" do - (0..10).each do |i| - @breadcrumbs.record(Raven::Breadcrumb.new.tap { |b| b.message = i }) - end - - expect(@breadcrumbs.members[0].message).to eq(1) - expect(@breadcrumbs.members[-1].message).to eq(10) - end - - it "converts to a hash" do - expect(@breadcrumbs.peek).to eq(nil) - - crumb = Raven::Breadcrumb.new.tap { |b| b.message = "test" } - @breadcrumbs.record(crumb) - - expect(@breadcrumbs.to_hash[:values]).to eq([crumb.to_hash]) - end - - it "clears in a threaded context" do - crumb = Raven::Breadcrumb.new.tap { |b| b.message = "test" } - Raven::BreadcrumbBuffer.current.record(crumb) - Raven::BreadcrumbBuffer.clear! - - expect(Raven::BreadcrumbBuffer.current.empty?).to be true - end -end diff --git a/sentry-raven/spec/raven/cli_spec.rb b/sentry-raven/spec/raven/cli_spec.rb deleted file mode 100644 index 9a8452e36..000000000 --- a/sentry-raven/spec/raven/cli_spec.rb +++ /dev/null @@ -1,69 +0,0 @@ -require 'spec_helper' -require 'raven/cli' - -RSpec.describe Raven::CLI do - # avoid unexpectedly mutating the shared configuration object - let(:config) { Raven.configuration.dup } - - context "when there's no error" do - it "sends an event" do - event = described_class.test(config.server, true, config) - - expect(event).to be_a(Raven::Event) - hash = event.to_hash - expect(hash[:exception][:values][0][:type]).to eq("ZeroDivisionError") - expect(hash[:exception][:values][0][:value]).to eq("divided by 0") - end - - it "logs correct values" do - logger = spy - allow_any_instance_of(Raven::Instance).to receive(:logger).and_return(logger) - - event = described_class.test(config.server, true, config) - - expect(logger).to have_received(:debug).with("Sending a test event:") - expect(logger).to have_received(:debug).with("-> event ID: #{event.id}") - expect(logger).to have_received(:debug).with("Done!") - end - end - - context "when there's an error" do - before do - # make Configuration#sample_allowed? fail - config.sample_rate = 2.0 - allow(Random::DEFAULT).to receive(:rand).and_return(3.0) - end - - it "returns false" do - event = described_class.test(config.server, true, config) - - expect(event).to eq(false) - end - - it "logs correct values" do - logger = spy - allow_any_instance_of(Raven::Instance).to receive(:logger).and_return(logger) - - described_class.test(config.server, true, config) - - expect(logger).to have_received(:debug).with("Sending a test event:") - expect(logger).to have_received(:debug).with("An error occurred while attempting to send the event.") - expect(logger).not_to have_received(:debug).with("Done!") - end - end - - context "when with custom environments config" do - let(:config) { Raven.configuration.dup } - - before do - config.environments = %w(production test) - end - - it "still sends the test event" do - event = Raven::CLI.test(config.server, true, config) - - expect(event).to be_a(Raven::Event) - expect(config.errors).to be_empty - end - end -end diff --git a/sentry-raven/spec/raven/client_spec.rb b/sentry-raven/spec/raven/client_spec.rb deleted file mode 100644 index 035c54f7a..000000000 --- a/sentry-raven/spec/raven/client_spec.rb +++ /dev/null @@ -1,130 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Client do - let(:configuration) do - Raven::Configuration.new.tap do |config| - config.server = 'http://12345:67890@sentry.localdomain/sentry/42' - end - end - let(:client) { Raven::Client.new(configuration) } - - before do - @fake_time = Time.now - allow(Time).to receive(:now).and_return @fake_time - end - - it "generates an auth header" do - expect(client.send(:generate_auth_header)).to eq( - "Sentry sentry_version=5, sentry_client=raven-ruby/#{Raven::VERSION}, sentry_timestamp=#{@fake_time.to_i}, " \ - "sentry_key=12345, sentry_secret=67890" - ) - end - - it "generates a message with exception" do - event = Raven.capture_exception(ZeroDivisionError.new("divided by 0")).to_hash - expect(client.send(:get_message_from_exception, event)).to eq("ZeroDivisionError: divided by 0") - end - - it "generates a message without exception" do - event = Raven.capture_message("this is an STDOUT transport test").to_hash - expect(client.send(:get_message_from_exception, event)).to eq(nil) - end - - it "generates an auth header without a secret (Sentry 9)" do - client.configuration.server = "https://66260460f09b5940498e24bb7ce093a0@sentry.io/42" - - expect(client.send(:generate_auth_header)).to eq( - "Sentry sentry_version=5, sentry_client=raven-ruby/#{Raven::VERSION}, sentry_timestamp=#{@fake_time.to_i}, " \ - "sentry_key=66260460f09b5940498e24bb7ce093a0" - ) - end - - describe "#send_event" do - let(:event) { Raven.capture_exception(ZeroDivisionError.new("divided by 0")) } - - context "when success" do - before do - allow(client.transport).to receive(:send_event) - end - - it "sends Event object" do - expect(client).not_to receive(:failed_send) - - expect(client.send_event(event)).to eq(event.to_hash) - end - - it "sends Event hash" do - expect(client).not_to receive(:failed_send) - - expect(client.send_event(event.to_json_compatible)).to eq(event.to_json_compatible) - end - end - - context "when failed" do - let(:logger) { spy } - - before do - client.configuration.logger = logger - allow(client.transport).to receive(:send_event).and_raise(StandardError) - - expect(logger).to receive(:warn).exactly(2) - end - - it "sends Event object" do - expect(client.send_event(event)).to eq(nil) - end - - it "sends Event hash" do - expect(client.send_event(event.to_json_compatible)).to eq(nil) - end - end - end - - describe "#transport" do - context "when scheme is not set" do - it "returns HTTP transport object" do - expect(client.transport).to be_a(Raven::Transports::HTTP) - end - end - - context "when scheme is http" do - before do - client.configuration.scheme = "http" - end - - it "returns HTTP transport object" do - expect(client.transport).to be_a(Raven::Transports::HTTP) - end - end - - context "when scheme is https" do - before do - client.configuration.scheme = "https" - end - - it "returns HTTP transport object" do - expect(client.transport).to be_a(Raven::Transports::HTTP) - end - end - - context "when scheme is dummy" do - before do - client.configuration.scheme = "dummy" - end - - it "returns Dummy transport object" do - expect(client.transport).to be_a(Raven::Transports::Dummy) - end - end - - context "when scheme is stdout" do - before do - client.configuration.scheme = "stdout" - end - - it "returns Stdout transport object" do - expect(client.transport).to be_a(Raven::Transports::Stdout) - end - end - end -end diff --git a/sentry-raven/spec/raven/client_state_spec.rb b/sentry-raven/spec/raven/client_state_spec.rb deleted file mode 100644 index 5aa562f88..000000000 --- a/sentry-raven/spec/raven/client_state_spec.rb +++ /dev/null @@ -1,51 +0,0 @@ -require 'spec_helper' -require 'timecop' - -RSpec.describe Raven::ClientState do - let(:state) { Raven::ClientState.new } - - it 'should try when online' do - expect(state.should_try?).to eq(true) - end - - it 'should not try with a new error' do - state.failure - expect(state.should_try?).to eq(false) - end - - it 'should try again after time passes' do - Timecop.freeze(-10) { state.failure } - expect(state.should_try?).to eq(true) - end - - it 'should try again after success' do - state.failure - state.success - expect(state.should_try?).to eq(true) - end - - it 'should try again after retry_after' do - Timecop.freeze(-2) { state.failure(1) } - expect(state.should_try?).to eq(true) - end - - it 'should exponentially backoff' do - Timecop.freeze do - state.failure - Timecop.travel(2) - expect(state.should_try?).to eq(true) - - state.failure - Timecop.travel(3) - expect(state.should_try?).to eq(false) - Timecop.travel(2) - expect(state.should_try?).to eq(true) - - state.failure - Timecop.travel(8) - expect(state.should_try?).to eq(false) - Timecop.travel(2) - expect(state.should_try?).to eq(true) - end - end -end diff --git a/sentry-raven/spec/raven/configuration_spec.rb b/sentry-raven/spec/raven/configuration_spec.rb deleted file mode 100644 index 5ce8bff08..000000000 --- a/sentry-raven/spec/raven/configuration_spec.rb +++ /dev/null @@ -1,400 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Configuration do - before do - # Make sure we reset the env in case something leaks in - ENV.delete('SENTRY_DSN') - ENV.delete('SENTRY_CURRENT_ENV') - ENV.delete('SENTRY_ENVIRONMENT') - ENV.delete('SENTRY_RELEASE') - ENV.delete('RAILS_ENV') - ENV.delete('RACK_ENV') - end - - it "should set some attributes when server is set" do - subject.server = "http://12345:67890@sentry.localdomain:3000/sentry/42" - - expect(subject.project_id).to eq("42") - expect(subject.public_key).to eq("12345") - expect(subject.secret_key).to eq("67890") - - expect(subject.scheme).to eq("http") - expect(subject.host).to eq("sentry.localdomain") - expect(subject.port).to eq(3000) - expect(subject.path).to eq("/sentry") - - expect(subject.server).to eq("http://sentry.localdomain:3000/sentry") - end - - describe "#breadcrumbs_logger=" do - it "raises error when given an invalid option" do - expect { subject.breadcrumbs_logger = :foo }.to raise_error( - Raven::Error, - 'Unsupported breadcrumbs logger. Supported loggers: [:sentry_logger, :active_support_logger]' - ) - end - end - - it "doesnt accept invalid encodings" do - expect { subject.encoding = "apple" }.to raise_error(Raven::Error, 'Unsupported encoding') - end - - it "has hashlike attribute accessors" do - expect(subject.encoding).to eq("gzip") - expect(subject[:encoding]).to eq("gzip") - end - - context 'configuring for async' do - it 'should be configurable to send events async' do - subject.async = ->(_e) { :ok } - expect(subject.async.call('event')).to eq(:ok) - end - - it 'should raise when setting async to anything other than callable or false' do - subject.transport_failure_callback = -> {} - subject.transport_failure_callback = false - expect { subject.async = true }.to raise_error(ArgumentError) - end - end - - it 'should raise when setting transport_failure_callback to anything other than callable or false' do - subject.transport_failure_callback = -> {} - subject.transport_failure_callback = false - expect { subject.transport_failure_callback = true }.to raise_error(ArgumentError) - end - - it 'should raise when setting should_capture to anything other than callable or false' do - subject.should_capture = -> {} - subject.should_capture = false - expect { subject.should_capture = true }.to raise_error(ArgumentError) - end - - it 'should raise when setting before_send to anything other than callable or false' do - subject.before_send = -> {} - subject.before_send = false - expect { subject.before_send = true }.to raise_error(ArgumentError) - end - - context 'being initialized with a current environment' do - before(:each) do - subject.current_environment = 'test' - subject.server = 'http://12345:67890@sentry.localdomain:3000/sentry/42' - end - - it 'should send events if test is whitelisted' do - subject.environments = %w(test) - subject.capture_allowed? - puts subject.errors - expect(subject.capture_allowed?).to eq(true) - end - - it 'should not send events if test is not whitelisted' do - subject.environments = %w(not_test) - expect(subject.capture_allowed?).to eq(false) - expect(subject.errors).to eq(["Not configured to send/capture in environment 'test'"]) - end - end - - context 'being initialized without a current environment' do - after do - ENV.delete('SENTRY_CURRENT_ENV') - ENV.delete('SENTRY_ENVIRONMENT') - ENV.delete('RAILS_ENV') - ENV.delete('RACK_ENV') - end - - it 'defaults to "default"' do - expect(subject.current_environment).to eq('default') - end - - it 'uses `SENTRY_CURRENT_ENV` env variable' do - ENV['SENTRY_CURRENT_ENV'] = 'set-with-sentry-current-env' - ENV['SENTRY_ENVIRONMENT'] = 'set-with-sentry-environment' - ENV['RAILS_ENV'] = 'set-with-rails-env' - ENV['RACK_ENV'] = 'set-with-rack-env' - - expect(subject.current_environment).to eq('set-with-sentry-current-env') - end - - it 'uses `SENTRY_ENVIRONMENT` env variable' do - ENV['SENTRY_ENVIRONMENT'] = 'set-with-sentry-environment' - ENV['RAILS_ENV'] = 'set-with-rails-env' - ENV['RACK_ENV'] = 'set-with-rack-env' - - expect(subject.current_environment).to eq('set-with-sentry-environment') - end - - it 'uses `RAILS_ENV` env variable' do - ENV['SENTRY_CURRENT_ENV'] = nil - ENV['RAILS_ENV'] = 'set-with-rails-env' - ENV['RACK_ENV'] = 'set-with-rack-env' - - expect(subject.current_environment).to eq('set-with-rails-env') - end - - it 'uses `RACK_ENV` env variable' do - ENV['SENTRY_CURRENT_ENV'] = nil - ENV['RAILS_ENV'] = nil - ENV['RACK_ENV'] = 'set-with-rack-env' - - expect(subject.current_environment).to eq('set-with-rack-env') - end - end - - context 'being initialized without a release' do - let(:fake_root) { "/tmp/sentry/" } - - before do - allow(File).to receive(:directory?).and_return(false) - allow_any_instance_of(described_class).to receive(:project_root).and_return(fake_root) - end - - it 'defaults to nil' do - expect(subject.release).to eq(nil) - end - - it 'uses `SENTRY_RELEASE` env variable' do - ENV['SENTRY_RELEASE'] = 'v1' - - expect(subject.release).to eq('v1') - - ENV.delete('SENTRY_CURRENT_ENV') - end - - context "when git is available" do - before do - allow(File).to receive(:directory?).and_return(false) - allow(File).to receive(:directory?).with(".git").and_return(true) - end - it 'gets release from git' do - allow(Raven).to receive(:`).with("git rev-parse --short HEAD 2>&1").and_return("COMMIT_SHA") - - expect(subject.release).to eq('COMMIT_SHA') - end - end - - context "when Capistrano is available" do - let(:revision) { "2019010101000" } - - before do - Dir.mkdir(fake_root) unless Dir.exist?(fake_root) - File.write(filename, file_content) - end - - after do - File.delete(filename) - Dir.delete(fake_root) - end - - context "when the REVISION file is present" do - let(:filename) do - File.join(fake_root, "REVISION") - end - let(:file_content) { revision } - - it "gets release from the REVISION file" do - expect(subject.release).to eq(revision) - end - end - - context "when the revisions.log file is present" do - let(:filename) do - File.join(fake_root, "..", "revisions.log") - end - let(:file_content) do - "Branch master (at COMMIT_SHA) deployed as release #{revision} by alice" - end - - it "gets release from the REVISION file" do - expect(subject.release).to eq(revision) - end - end - end - - context "when running on heroku" do - before do - allow(File).to receive(:directory?).and_return(false) - allow(File).to receive(:directory?).with("/etc/heroku").and_return(true) - end - - context "when it's on heroku ci" do - it "returns nil" do - begin - original_ci_val = ENV["CI"] - ENV["CI"] = "true" - - expect(subject.release).to eq(nil) - ensure - ENV["CI"] = original_ci_val - end - end - end - - context "when it's not on heroku ci" do - around do |example| - begin - original_ci_val = ENV["CI"] - ENV["CI"] = nil - - example.run - ensure - ENV["CI"] = original_ci_val - end - end - - it "returns nil + logs an warning if HEROKU_SLUG_COMMIT is not set" do - logger = double("logger") - expect(::Raven::Logger).to receive(:new).and_return(logger) - expect(logger).to receive(:warn).with(described_class::HEROKU_DYNO_METADATA_MESSAGE) - - expect(described_class.new.release).to eq(nil) - end - - it "returns HEROKU_SLUG_COMMIT" do - begin - ENV["HEROKU_SLUG_COMMIT"] = "REVISION" - - expect(subject.release).to eq("REVISION") - ensure - ENV["HEROKU_SLUG_COMMIT"] = nil - end - end - end - end - end - - describe "config: backtrace_cleanup_callback" do - it "defaults to nil" do - expect(subject.backtrace_cleanup_callback).to eq(nil) - end - - it "takes a proc and store it" do - subject.backtrace_cleanup_callback = proc {} - - expect(subject.backtrace_cleanup_callback).to be_a(Proc) - end - end - - context 'with a should_capture callback configured' do - before(:each) do - subject.should_capture = ->(exc_or_msg) { exc_or_msg != "dont send me" } - subject.server = 'http://12345:67890@sentry.localdomain:3000/sentry/42' - end - - it 'should not send events if should_capture returns false' do - expect(subject.capture_allowed?("dont send me")).to eq(false) - expect(subject.errors).to eq(["should_capture returned false"]) - expect(subject.capture_allowed?("send me")).to eq(true) - end - end - - context "with an invalid server" do - before(:each) do - subject.server = 'dummy://trololo' - end - - it 'captured_allowed returns false' do - expect(subject.capture_allowed?).to eq(false) - expect(subject.errors).to eq(["No public_key specified", "No project_id specified"]) - end - end - - context "with the new Sentry 9 DSN format" do - # Basically the same as before, without a secret - before(:each) do - subject.server = "https://66260460f09b5940498e24bb7ce093a0@sentry.io/42" - end - - it 'captured_allowed is true' do - expect(subject.capture_allowed?).to eq(true) - end - - it "sets the DSN in the way we expect" do - expect(subject.dsn).to eq("https://66260460f09b5940498e24bb7ce093a0@sentry.io/42") - expect(subject.server).to eq("https://sentry.io") - expect(subject.project_id).to eq("42") - expect(subject.public_key).to eq("66260460f09b5940498e24bb7ce093a0") - expect(subject.secret_key).to be_nil - end - end - - context "with a sample rate" do - before(:each) do - subject.server = 'http://12345:67890@sentry.localdomain:3000/sentry/42' - subject.sample_rate = 0.75 - end - - it 'captured_allowed false when sampled' do - allow(Random::DEFAULT).to receive(:rand).and_return(0.76) - expect(subject.capture_allowed?).to eq(false) - expect(subject.errors).to eq(["Excluded by random sample"]) - end - - it 'captured_allowed true when not sampled' do - allow(Random::DEFAULT).to receive(:rand).and_return(0.74) - expect(subject.capture_allowed?).to eq(true) - end - end - - describe '#exception_class_allowed?' do - class MyTestException < RuntimeError; end - - context 'with custom excluded_exceptions' do - before do - subject.excluded_exceptions = ['MyTestException'] - end - - context 'when the raised exception is a Raven::Error' do - let(:incoming_exception) { Raven::Error.new } - it 'returns false' do - expect(subject.exception_class_allowed?(incoming_exception)).to eq false - end - end - - context 'when the raised exception is not in excluded_exceptions' do - let(:incoming_exception) { RuntimeError.new } - it 'returns true' do - expect(subject.exception_class_allowed?(incoming_exception)).to eq true - end - end - - context 'when the raised exception has a cause that is in excluded_exceptions' do - let(:incoming_exception) { build_exception_with_cause(MyTestException.new) } - context 'when inspect_exception_causes_for_exclusion is false' do - it 'returns true' do - expect(subject.exception_class_allowed?(incoming_exception)).to eq true - end - end - - # Only check causes when they're supported by the ruby version - context 'when inspect_exception_causes_for_exclusion is true' do - before do - subject.inspect_exception_causes_for_exclusion = true - end - - if Exception.new.respond_to? :cause - context 'when the language version supports exception causes' do - it 'returns false' do - expect(subject.exception_class_allowed?(incoming_exception)).to eq false - end - end - else - context 'when the language version does not support exception causes' do - it 'returns true' do - expect(subject.exception_class_allowed?(incoming_exception)).to eq true - end - end - end - end - end - - context 'when the raised exception is in excluded_exceptions' do - let(:incoming_exception) { MyTestException.new } - - it 'returns false' do - expect(subject.exception_class_allowed?(incoming_exception)).to eq false - end - end - end - end -end diff --git a/sentry-raven/spec/raven/event_spec.rb b/sentry-raven/spec/raven/event_spec.rb deleted file mode 100644 index daa0c5844..000000000 --- a/sentry-raven/spec/raven/event_spec.rb +++ /dev/null @@ -1,812 +0,0 @@ -require 'spec_helper' -require 'raven/integrations/rack' - -RSpec.describe Raven::Event do - before do - Raven::Context.clear! - Raven::BreadcrumbBuffer.clear! - end - - let(:essential_options) do - { - configuration: Raven.configuration, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs - } - end - - describe "#initialize" do - it "initializes a Event when all required keys are provided" do - expect(described_class.new(essential_options)).to be_a(described_class) - end - - described_class::REQUIRED_OPTION_KEYS.each do |required_key| - it "raises error if #{required_key} is not given" do - essential_options.delete(required_key) - - expect do - described_class.new(essential_options) - end.to raise_error("you must provide configuration, context, and breadcrumbs when initializing a Raven::Event") - end - end - end - - context 'a fully implemented event' do - let(:hash) do - Raven::Event.new( - message: 'test', - level: 'warn', - logger: 'foo', - tags: { - 'foo' => 'bar' - }, - extra: { - 'my_custom_variable' => 'value' - }, - server_name: 'foo.local', - release: '721e41770371db95eee98ca2707686226b993eda', - environment: 'production', - **essential_options - ).to_hash - end - - it 'has message' do - expect(hash[:message]).to eq('test') - end - - it 'has level' do - expect(hash[:level]).to eq(:warning) - end - - it 'has logger' do - expect(hash[:logger]).to eq('foo') - end - - it 'has server name' do - expect(hash[:server_name]).to eq('foo.local') - end - - it 'has release' do - expect(hash[:release]).to eq('721e41770371db95eee98ca2707686226b993eda') - end - - it 'has environment' do - expect(hash[:environment]).to eq('production') - end - - it 'has tag data' do - expect(hash[:tags]).to eq('foo' => 'bar') - end - - it 'has extra data' do - expect(hash[:extra]["my_custom_variable"]).to eq('value') - end - - it 'has platform' do - expect(hash[:platform]).to eq(:ruby) - end - - it 'has SDK' do - expect(hash[:sdk]).to eq("name" => "raven-ruby", "version" => Raven::VERSION) - end - - it 'has server os' do - expect(hash[:extra][:server][:os].keys).to eq([:name, :version, :build, :kernel_version]) - end - - it 'has runtime' do - expect(hash[:extra][:server][:runtime][:version]).to match(/ruby/) - end - end - - context 'parameter entries are nil' do - let(:hash) do - Raven::Event.new( - message: 'test', - level: 'warn', - logger: 'foo', - tags: nil, - extra: nil, - user: nil, - server_name: 'foo.local', - release: '721e41770371db95eee98ca2707686226b993eda', - environment: 'production', - **essential_options - ).to_hash - end - - it "skips nil values" do - expect(hash[:extra]).to eq(Raven.context.extra) - expect(hash[:user]).to eq(Raven.context.user) - expect(hash[:tags]).to eq(Raven.configuration.tags) - end - end - - context 'user context specified' do - let(:hash) do - Raven.user_context('id' => 'hello') - - Raven::Event.new( - level: 'warning', - logger: 'foo', - tags: { - 'foo' => 'bar' - }, - extra: { - 'my_custom_variable' => 'value' - }, - server_name: 'foo.local', - **essential_options - ).to_hash - end - - it "adds user data" do - expect(hash[:user]).to eq('id' => 'hello') - end - end - - context 'tags context specified' do - let(:hash) do - Raven.tags_context('key' => 'value') - - Raven::Event.new(level: 'warning', - logger: 'foo', - tags: { - 'foo' => 'bar' - }, - extra: { - 'my_custom_variable' => 'value' - }, - server_name: 'foo.local', - **essential_options).to_hash - end - - it "merges tags data" do - expect(hash[:tags]).to eq('key' => 'value', - 'foo' => 'bar') - end - end - - context 'extra context specified' do - let(:hash) do - Raven.extra_context('key' => 'value') - - Raven::Event.new(level: 'warning', - logger: 'foo', - tags: { - 'foo' => 'bar' - }, - extra: { - 'my_custom_variable' => 'value' - }, - server_name: 'foo.local', - **essential_options).to_hash - end - - it "merges extra data" do - expect(hash[:extra]['key']).to eq('value') - expect(hash[:extra]['my_custom_variable']).to eq('value') - end - end - - context 'rack context specified' do - require 'stringio' - - let(:hash) do - Raven.rack_context('REQUEST_METHOD' => 'POST', - 'QUERY_STRING' => 'biz=baz', - 'HTTP_HOST' => 'localhost', - 'SERVER_NAME' => 'localhost', - 'SERVER_PORT' => '80', - 'HTTP_X_FORWARDED_FOR' => '1.1.1.1, 2.2.2.2', - 'HTTP_X_REQUEST_ID' => '98765432', - 'REMOTE_ADDR' => '192.168.1.1', - 'PATH_INFO' => '/lol', - 'rack.url_scheme' => 'http', - 'rack.input' => StringIO.new('foo=bar')) - - Raven::Event.new(level: 'warning', - logger: 'foo', - tags: { - 'foo' => 'bar' - }, - extra: { - 'my_custom_variable' => 'value' - }, - server_name: 'foo.local', - **essential_options).to_hash - end - - it "adds http data" do - expect(hash[:request]).to eq(data: { 'foo' => 'bar' }, - env: { 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '80', "REMOTE_ADDR" => "192.168.1.1" }, - headers: { 'Host' => 'localhost', "X-Forwarded-For" => "1.1.1.1, 2.2.2.2", 'X-Request-Id' => '98765432' }, - method: 'POST', - query_string: 'biz=baz', - url: 'http://localhost/lol', - cookies: {}) - end - - it "sets user context ip address correctly" do - expect(hash[:user][:ip_address]).to eq("1.1.1.1") - end - - it "adds request_id to the tags" do - expect(hash[:tags][:request_id]).to eq("98765432") - end - end - - context "rack context, long body" do - let(:hash) do - Raven.rack_context('REQUEST_METHOD' => 'GET', - 'rack.url_scheme' => 'http', - 'rack.input' => StringIO.new('a' * 4096 * 5)) - - Raven::Event.new(essential_options).to_hash - end - - it "truncates http data" do - expect(hash[:request][:data]).to eq("a" * 4096 * 4) - end - end - - context 'configuration tags specified' do - let(:hash) do - config = Raven::Configuration.new - config.tags = { 'key' => 'value' } - config.release = "custom" - config.current_environment = "custom" - - Raven::Event.new( - level: 'warning', - logger: 'foo', - tags: { - 'foo' => 'bar' - }, - server_name: 'foo.local', - configuration: config, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs - ).to_hash - end - - it 'merges tags data' do - expect(hash[:tags]).to eq('key' => 'value', - 'foo' => 'bar') - expect(hash[:release]).to eq("custom") - expect(hash[:environment]).to eq("custom") - end - end - - context 'configuration tags unspecified' do - it 'should not persist tags between unrelated events' do - config = Raven::Configuration.new - config.logger = Logger.new(nil) - - Raven::Event.new( - level: 'warning', - logger: 'foo', - tags: { - 'foo' => 'bar' - }, - server_name: 'foo.local', - configuration: config, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs - ) - - hash = Raven::Event.new( - level: 'warning', - logger: 'foo', - server_name: 'foo.local', - configuration: config, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs - ).to_hash - - expect(hash[:tags]).to eq({}) - end - end - - context 'tags hierarchy respected' do - let(:hash) do - config = Raven::Configuration.new - config.logger = Logger.new(nil) - config.tags = { - 'configuration_context_event_key' => 'configuration_value', - 'configuration_context_key' => 'configuration_value', - 'configuration_event_key' => 'configuration_value', - 'configuration_key' => 'configuration_value' - } - - Raven.tags_context('configuration_context_event_key' => 'context_value', - 'configuration_context_key' => 'context_value', - 'context_event_key' => 'context_value', - 'context_key' => 'context_value') - - Raven::Event.new( - level: 'warning', - logger: 'foo', - tags: { - 'configuration_context_event_key' => 'event_value', - 'configuration_event_key' => 'event_value', - 'context_event_key' => 'event_value', - 'event_key' => 'event_value' - }, - server_name: 'foo.local', - configuration: config, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs - ).to_hash - end - - it 'merges tags data' do - expect(hash[:tags]).to eq('configuration_context_event_key' => 'event_value', - 'configuration_context_key' => 'context_value', - 'configuration_event_key' => 'event_value', - 'context_event_key' => 'event_value', - 'configuration_key' => 'configuration_value', - 'context_key' => 'context_value', - 'event_key' => 'event_value') - end - end - - context 'merging user context' do - before do - Raven.user_context('context_event_key' => 'context_value', - 'context_key' => 'context_value') - end - - let(:hash) do - Raven::Event.new(user: { - 'context_event_key' => 'event_value', - 'event_key' => 'event_value' - }, - configuration: Raven.configuration, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs).to_hash - end - - it 'prioritizes event context over request context' do - expect(hash[:user]).to eq('context_event_key' => 'event_value', - 'context_key' => 'context_value', - 'event_key' => 'event_value') - end - end - - context 'merging extra context' do - before do - Raven.extra_context('context_event_key' => 'context_value', - 'context_key' => 'context_value') - end - - let(:hash) do - Raven::Event.new(extra: { - 'context_event_key' => 'event_value', - 'event_key' => 'event_value' - }, - configuration: Raven.configuration, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs).to_hash - end - - it 'prioritizes event context over request context' do - expect(hash[:extra]['context_event_key']).to eq('event_value') - expect(hash[:extra]['context_key']).to eq('context_value') - expect(hash[:extra]['event_key']).to eq('event_value') - end - end - - context 'merging exception context' do - class ExceptionWithContext < StandardError - def raven_context - { extra: { - 'context_event_key' => 'context_value', - 'context_key' => 'context_value' - } } - end - end - - let(:hash) do - Raven::Event.from_exception( - ExceptionWithContext.new, - extra: { - 'context_event_key' => 'event_value', - 'event_key' => 'event_value' - }, - **essential_options - ).to_hash - end - - it 'prioritizes event context over request context' do - expect(hash[:extra]['context_event_key']).to eq('event_value') - expect(hash[:extra]['context_key']).to eq('context_value') - expect(hash[:extra]['event_key']).to eq('event_value') - end - end - - describe ".from_exception" do - it "proceses string message correctly" do - event = Raven::Event.from_exception(ExceptionWithContext.new, message: "MSG", **essential_options) - expect(event.message).to eq("MSG") - end - - it "slices long string message" do - event = Raven::Event.from_exception(ExceptionWithContext.new, message: "MSG" * 3000, **essential_options) - expect(event.message.length).to eq(8192) - end - - it "converts non-string message into string" do - expect(Raven.configuration.logger).to receive(:debug).with("You're passing a non-string message") - - event = Raven::Event.from_exception(ExceptionWithContext.new, message: { foo: "bar" }, **essential_options) - expect(event.message).to eq("{:foo=>\"bar\"}") - end - end - - describe '.to_json_compatible' do - subject do - Raven::Event.new(extra: { - 'my_custom_variable' => 'value', - 'date' => Time.utc(0), - 'anonymous_module' => Class.new - }, - configuration: Raven.configuration, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs) - end - - it "should coerce non-JSON-compatible types" do - json = subject.to_json_compatible - - expect(json["extra"]['my_custom_variable']).to eq('value') - expect(json["extra"]['date']).to be_a(String) - expect(json["extra"]['anonymous_module']).not_to be_a(Class) - end - - context "with bad data" do - subject do - data = {} - data['data'] = data - data['ary'] = [] - data['ary'].push('x' => data['ary']) - data['ary2'] = data['ary'] - - Raven::Event.new(extra: { - invalid: "invalid\255".dup.force_encoding('UTF-8'), - circular: data - }, - configuration: Raven.configuration, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs) - end - - it "should remove bad UTF-8" do - json = subject.to_json_compatible - - expect(json["extra"]["invalid"]).to eq("invalid") - end - - it "should remove circular references" do - json = subject.to_json_compatible - - expect(json["extra"]["circular"]["ary2"]).to eq("(...)") - end - end - - context "with sensitive data" do - subject do - Raven::Event.new(extra: { - 'password' => 'secretpassword' - }, - configuration: Raven.configuration, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs) - end - - it "should sanitize password" do - json = subject.to_json_compatible - - expect(json["extra"]["password"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - end - end - end - - describe '.capture_message' do - let(:message) { 'This is a message' } - let(:hash) { Raven::Event.capture_message(message, essential_options).to_hash } - - context 'for a Message' do - it 'returns an event' do - expect(Raven::Event.capture_message(message, essential_options)).to be_a(Raven::Event) - end - - it "doesn't change the option hash" do - h_int = { abc: :abc } - h = { k1: h_int, k2: h_int } - Raven.capture_message "Test extra", extra: { h1: h, h2: h_int }, **essential_options - - expect(h).to eq({ k1: h_int, k2: h_int }) - end - - it "sets the message to the value passed" do - expect(hash[:message]).to eq(message) - end - - it 'has level ERROR' do - expect(hash[:level]).to eq(:error) - end - - it 'accepts an options hash' do - expect(Raven::Event.capture_message(message, logger: 'logger', **essential_options).logger).to eq('logger') - end - - it 'accepts a stacktrace' do - backtrace = ["/path/to/some/file:22:in `function_name'", - "/some/other/path:1412:in `other_function'"] - evt = Raven::Event.capture_message(message, backtrace: backtrace, **essential_options) - expect(evt[:stacktrace]).to be_a(Raven::StacktraceInterface) - - frames = evt[:stacktrace].to_hash[:frames] - expect(frames.length).to eq(2) - expect(frames[0][:lineno]).to eq(1412) - expect(frames[0][:function]).to eq('other_function') - expect(frames[0][:filename]).to eq('/some/other/path') - - expect(frames[1][:lineno]).to eq(22) - expect(frames[1][:function]).to eq('function_name') - expect(frames[1][:filename]).to eq('/path/to/some/file') - end - end - end - - describe '.capture_exception' do - let(:message) { 'This is a message' } - let(:exception) { Exception.new(message) } - let(:hash) { Raven::Event.capture_exception(exception, **essential_options).to_hash } - - context 'for an Exception' do - it 'returns an event' do - expect(Raven::Event.capture_exception(exception, **essential_options)).to be_a(Raven::Event) - end - - it "sets the message to the exception's value and type" do - expect(hash[:exception][:values][0][:type]).to eq("Exception") - expect(hash[:exception][:values][0][:value]).to eq(message) - end - - it 'has level ERROR' do - expect(hash[:level]).to eq(:error) - end - - it 'uses the exception class name as the exception type' do - expect(hash[:exception][:values][0][:type]).to eq('Exception') - end - - it 'uses the exception message as the exception value' do - expect(hash[:exception][:values][0][:value]).to eq(message) - end - - it 'does not belong to a module' do - expect(hash[:exception][:values][0][:module]).to eq('') - end - end - - context 'for a nested exception type' do - module Raven::Test - class Exception < RuntimeError; end - end - let(:exception) { Raven::Test::Exception.new(message) } - - it 'sends the module name as part of the exception info' do - expect(hash[:exception][:values][0][:module]).to eq('Raven::Test') - end - end - - context 'for a Raven::Error' do - let(:exception) { Raven::Error.new } - it 'does not create an event' do - expect(Raven::Event.capture_exception(exception, **essential_options)).to be_nil - end - end - - context 'for an excluded exception type' do - module Raven::Test - class BaseExc < RuntimeError; end - class SubExc < BaseExc; end - module ExcTag; end - end - let(:config) do - config = Raven::Configuration.new - config.logger = Logger.new(nil) - config - end - - let(:essential_options) do - { - configuration: config, - context: Raven.context, - breadcrumbs: Raven.breadcrumbs - } - end - - context "invalid exclusion type" do - it 'returns Raven::Event' do - config.excluded_exceptions << nil - config.excluded_exceptions << 1 - config.excluded_exceptions << {} - expect(Raven::Event.capture_exception(Raven::Test::BaseExc.new, essential_options)).to be_a(Raven::Event) - end - end - - context "defined by string type" do - it 'returns nil for a class match' do - config.excluded_exceptions << 'Raven::Test::BaseExc' - expect(Raven::Event.capture_exception(Raven::Test::BaseExc.new, essential_options)).to be_nil - end - - it 'returns nil for a top class match' do - config.excluded_exceptions << '::Raven::Test::BaseExc' - expect(Raven::Event.capture_exception(Raven::Test::BaseExc.new, essential_options)).to be_nil - end - - it 'returns nil for a sub class match' do - config.excluded_exceptions << 'Raven::Test::BaseExc' - expect(Raven::Event.capture_exception(Raven::Test::SubExc.new, essential_options)).to be_nil - end - - it 'returns nil for a tagged class match' do - config.excluded_exceptions << 'Raven::Test::ExcTag' - expect( - Raven::Event.capture_exception( - Raven::Test::SubExc.new.tap { |x| x.extend(Raven::Test::ExcTag) }, - essential_options - ) - ).to be_nil - end - - it 'returns Raven::Event for an undefined exception class' do - config.excluded_exceptions << 'Raven::Test::NonExistentExc' - expect(Raven::Event.capture_exception(Raven::Test::BaseExc.new, essential_options)).to be_a(Raven::Event) - end - end - - context "defined by class type" do - it 'returns nil for a class match' do - config.excluded_exceptions << Raven::Test::BaseExc - expect(Raven::Event.capture_exception(Raven::Test::BaseExc.new, essential_options)).to be_nil - end - - it 'returns nil for a sub class match' do - config.excluded_exceptions << Raven::Test::BaseExc - expect(Raven::Event.capture_exception(Raven::Test::SubExc.new, essential_options)).to be_nil - end - - it 'returns nil for a tagged class match' do - config.excluded_exceptions << Raven::Test::ExcTag - expect(Raven::Event.capture_exception(Raven::Test::SubExc.new.tap { |x| x.extend(Raven::Test::ExcTag) }, essential_options)).to be_nil - end - end - end - - # Only check causes when they're supported - if Exception.new.respond_to? :cause - context 'when the exception has a cause' do - let(:exception) { build_exception_with_cause } - - it 'captures the cause' do - expect(hash[:exception][:values].length).to eq(2) - end - end - - context 'when the exception has nested causes' do - let(:exception) { build_exception_with_two_causes } - - it 'captures nested causes' do - expect(hash[:exception][:values].length).to eq(3) - end - end - end - - context 'when the exception has a recursive cause' do - let(:exception) { build_exception_with_recursive_cause } - - it 'should handle it gracefully' do - expect(hash[:exception][:values].length).to eq(1) - end - end - - if RUBY_PLATFORM == "java" - context 'when running under jRuby' do - let(:exception) do - begin - raise java.lang.OutOfMemoryError, "A Java error" - rescue Exception => e - return e - end - end - - it 'should have a backtrace' do - frames = hash[:exception][:values][0][:stacktrace][:frames] - expect(frames.length).not_to eq(0) - end - end - end - - context 'when the exception has a backtrace' do - let(:exception) do - e = Exception.new(message) - allow(e).to receive(:backtrace).and_return [ - "/path/to/some/file:22:in `function_name'", - "/some/other/path:1412:in `other_function'" - ] - e - end - - it 'parses the backtrace' do - frames = hash[:exception][:values][0][:stacktrace][:frames] - expect(frames.length).to eq(2) - expect(frames[0][:lineno]).to eq(1412) - expect(frames[0][:function]).to eq('other_function') - expect(frames[0][:filename]).to eq('/some/other/path') - - expect(frames[1][:lineno]).to eq(22) - expect(frames[1][:function]).to eq('function_name') - expect(frames[1][:filename]).to eq('/path/to/some/file') - end - - context 'with internal backtrace' do - let(:exception) do - e = Exception.new(message) - allow(e).to receive(:backtrace).and_return([":10:in `synchronize'"]) - e - end - - it 'marks filename and in_app correctly' do - frames = hash[:exception][:values][0][:stacktrace][:frames] - expect(frames[0][:lineno]).to eq(10) - expect(frames[0][:function]).to eq("synchronize") - expect(frames[0][:filename]).to eq("") - end - end - - context 'when a path in the stack trace is on the load path' do - before do - $LOAD_PATH << '/some' - end - - after do - $LOAD_PATH.delete('/some') - end - - it 'strips prefixes in the load path from frame filenames' do - frames = hash[:exception][:values][0][:stacktrace][:frames] - expect(frames[0][:filename]).to eq('other/path') - end - end - end - - it 'uses an annotation if one exists' do - Raven.annotate_exception(exception, logger: 'logger') - expect(Raven::Event.capture_exception(exception, **essential_options).logger).to eq('logger') - end - - it 'accepts a checksum' do - event = Raven::Event.capture_exception(exception, checksum: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', **essential_options) - expect(event.checksum).to eq('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') - end - - it 'accepts a release' do - expect(Raven::Event.capture_exception(exception, release: '1.0', **essential_options).release).to eq('1.0') - end - - it 'accepts a fingerprint' do - event = Raven::Event.capture_exception(exception, fingerprint: ['{{ default }}', 'foo'], **essential_options) - expect(event.fingerprint).to eq(['{{ default }}', 'foo']) - end - - it 'accepts a logger' do - expect(Raven::Event.capture_exception(exception, logger: 'root', **essential_options).logger).to eq('root') - end - end -end diff --git a/sentry-raven/spec/raven/instance_spec.rb b/sentry-raven/spec/raven/instance_spec.rb deleted file mode 100644 index 938822914..000000000 --- a/sentry-raven/spec/raven/instance_spec.rb +++ /dev/null @@ -1,405 +0,0 @@ -require 'spec_helper' -require 'raven/instance' - -RSpec.describe Raven::Instance do - let(:event) { Raven::Event.new(id: "event_id", configuration: configuration, context: Raven.context, breadcrumbs: Raven.breadcrumbs) } - let(:options) { { :key => "value" } } - let(:event_options) { options.merge(:context => subject.context, :configuration => configuration, breadcrumbs: Raven.breadcrumbs) } - let(:context) { nil } - let(:configuration) do - config = Raven::Configuration.new - config.dsn = "dummy://12345:67890@sentry.localdomain:3000/sentry/42" - config.logger = Logger.new(nil) - config - end - - subject { described_class.new(context, configuration) } - - before do - allow(subject).to receive(:send_event) - allow(Raven::Event).to receive(:from_message) { event } - allow(Raven::Event).to receive(:from_exception) { event } - end - - describe '#context' do - it 'is Raven.context by default' do - expect(subject.context).to equal(Raven.context) - end - - context 'initialized with a context' do - let(:context) { :explicit } - - it 'is not Raven.context' do - expect(subject.context).to_not equal(Raven.context) - end - end - end - - describe '#capture_type' do - describe 'as #capture_message' do - before do - expect(Raven::Event).to receive(:from_message).with(message, event_options) - expect(subject).to receive(:send_event).with(event, :exception => nil, :message => message) - end - let(:message) { "Test message" } - - it 'sends the result of Event.capture_message' do - subject.capture_type(message, options) - end - - it 'yields the event to a passed block' do - expect { |b| subject.capture_type(message, options, &b) }.to yield_with_args(event) - end - end - - describe 'as #capture_message when async' do - let(:message) { "Test message" } - - around do |example| - prior_async = subject.configuration.async - subject.configuration.async = proc { :ok } - example.run - subject.configuration.async = prior_async - end - - it 'sends the result of Event.capture_type' do - expect(Raven::Event).to receive(:from_message).with(message, event_options) - expect(subject).not_to receive(:send_event).with(event) - - expect(subject.configuration.async).to receive(:call).with(event.to_json_compatible) - subject.capture_message(message, options) - end - - it 'returns the generated event' do - returned = subject.capture_message(message, options) - expect(returned).to eq(event) - end - end - - describe 'as #capture_exception' do - let(:exception) { build_exception } - - it 'sends the result of Event.capture_exception' do - expect(Raven::Event).to receive(:from_exception).with(exception, event_options) - expect(subject).to receive(:send_event).with(event, :exception => exception, :message => nil) - - subject.capture_exception(exception, options) - end - - it 'has an alias' do - expect(Raven::Event).to receive(:from_exception).with(exception, event_options) - expect(subject).to receive(:send_event).with(event, :exception => exception, :message => nil) - - subject.capture_exception(exception, options) - end - end - - describe 'as #capture_exception when async' do - let(:exception) { build_exception } - - context "when async" do - around do |example| - prior_async = subject.configuration.async - subject.configuration.async = proc { :ok } - example.run - subject.configuration.async = prior_async - end - - it 'sends the result of Event.capture_exception' do - expect(Raven::Event).to receive(:from_exception).with(exception, event_options) - expect(subject).not_to receive(:send_event).with(event) - - expect(subject.configuration.async).to receive(:call).with(event.to_json_compatible) - subject.capture_exception(exception, options) - end - - it 'returns the generated event' do - returned = subject.capture_exception(exception, options) - expect(returned).to eq(event) - end - end - - context "when async raises an exception" do - around do |example| - prior_async = subject.configuration.async - subject.configuration.async = proc { raise TypeError } - example.run - subject.configuration.async = prior_async - end - - it 'sends the result of Event.capture_exception via fallback' do - expect(Raven::Event).to receive(:from_exception).with(exception, event_options) - - expect(subject.configuration.async).to receive(:call).with(event.to_json_compatible) - subject.capture_exception(exception, options) - end - end - end - - describe 'as #capture_exception with a should_capture callback' do - let(:exception) { build_exception } - - it 'sends the result of Event.capture_exception according to the result of should_capture' do - expect(subject).not_to receive(:send_event).with(event) - - subject.configuration.should_capture = proc { false } - expect(subject.configuration.should_capture).to receive(:call).with(exception) - expect(subject.capture_exception(exception, options)).to be false - end - end - end - - describe '#capture' do - context 'given a block' do - it 'yields to the given block' do - expect { |b| subject.capture(&b) }.to yield_with_no_args - end - end - - it 'does not install an at_exit hook' do - expect(Kernel).not_to receive(:at_exit) - subject.capture {} - end - end - - describe '#annotate_exception' do - let(:exception) { build_exception } - - def ivars(object) - object.instance_variables.map(&:to_s) - end - - it 'adds an annotation to the exception' do - expect(ivars(exception)).not_to include("@__raven_context") - subject.annotate_exception(exception, {}) - expect(ivars(exception)).to include("@__raven_context") - expect(exception.instance_variable_get(:@__raven_context)).to \ - be_kind_of Hash - end - - context 'when the exception already has context' do - it 'does a deep merge of options' do - subject.annotate_exception(exception, :extra => { :language => "ruby" }) - subject.annotate_exception(exception, :extra => { :job_title => "engineer" }) - expected_hash = { :extra => { :language => "ruby", :job_title => "engineer" } } - expect(exception.instance_variable_get(:@__raven_context)).to \ - eq expected_hash - end - end - end - - describe '#report_status' do - let(:ready_message) do - "Raven #{Raven::VERSION} ready to catch errors" - end - - let(:not_ready_message) do - "Raven #{Raven::VERSION} configured not to capture errors: DSN not set" - end - - context "when current environment is included in environments" do - before do - subject.configuration.silence_ready = false - subject.configuration.environments = ["default"] - end - - it 'logs a ready message when configured' do - expect(subject.logger).to receive(:info).with(ready_message) - subject.report_status - end - - it 'logs a warning message when not properly configured' do - # dsn not set - subject.configuration = Raven::Configuration.new - - expect(subject.logger).to receive(:info).with(not_ready_message) - subject.report_status - end - - it 'logs nothing if "silence_ready" configuration is true' do - subject.configuration.silence_ready = true - expect(subject.logger).not_to receive(:info) - subject.report_status - end - end - - context "when current environment is not included in environments" do - it "doesn't log any message" do - subject.configuration.silence_ready = false - subject.configuration.environments = ["production"] - expect(subject.logger).not_to receive(:info) - subject.report_status - end - end - end - - describe '.last_event_id' do - let(:message) { "Test message" } - - it 'sends the result of Event.capture_type' do - expect(subject).to receive(:send_event).with(event, :exception => nil, :message => message) - - subject.capture_type("Test message", options) - - expect(subject.last_event_id).to eq(event.id) - end - end - - describe "#user_context" do - context "without a block" do - it "doesn't override previous data" do - subject.user_context(id: 1) - subject.user_context(email: "test@example.com") - - expect(subject.context.user).to eq({ id: 1, email: "test@example.com" }) - end - it "empties the user context when called without options" do - subject.context.user = { id: 1 } - expect(subject.user_context).to eq({}) - end - - it "empties the user context when called with nil" do - subject.context.user = { id: 1 } - expect(subject.user_context(nil)).to eq({}) - end - - it "doesn't empty the user context when called with {}" do - subject.context.user = { id: 1 } - expect(subject.user_context({})).to eq({ id: 1 }) - end - - it "returns the user context when set" do - expected = { id: 1 } - expect(subject.user_context(expected)).to eq(expected) - end - end - - context "with a block" do - it "returns the user context when set" do - expected = { id: 1 } - user_context = subject.user_context(expected) do - # do nothing - end - expect(user_context).to eq expected - end - - it "sets user context only in the block" do - subject.context.user = { id: 9999 } - - subject.user_context(id: 1) do - expect(subject.context.user).to eq(id: 1) - end - expect(subject.context.user).to eq(id: 9999) - end - - it "resets with nested blocks" do - subject.context.user = {} - subject.user_context(id: 9999) do - subject.user_context(email: 'foo@bar.com') do - expect(subject.context.user).to eq(id: 9999, email: 'foo@bar.com') - end - expect(subject.context.user).to eq(id: 9999) - end - expect(subject.context.user).to eq({}) - end - end - end - - describe "#tags_context" do - let(:default) { { :foo => :bar } } - let(:additional) { { :baz => :qux } } - - before do - subject.context.tags = default - end - - it "returns the tags" do - expect(subject.tags_context).to eq default - end - - it "returns the tags" do - expect(subject.tags_context(additional)).to eq default.merge(additional) - end - - it "doesn't set anything if the tags is empty" do - subject.tags_context({}) - expect(subject.context.tags).to eq default - end - - it "adds tags" do - subject.tags_context(additional) - expect(subject.context.tags).to eq default.merge(additional) - end - - context 'when block given' do - it "returns the tags" do - tags = subject.tags_context(additional) do - # do nothing - end - expect(tags).to eq default - end - - it "adds tags only in the block" do - subject.tags_context(additional) do - expect(subject.context.tags).to eq default.merge(additional) - end - expect(subject.context.tags).to eq default - end - end - end - - describe "#extra_context" do - let(:default) { { :foo => :bar } } - let(:additional) { { :baz => :qux } } - - before do - subject.context.extra = default - end - - it "returns the extra" do - expect(subject.extra_context).to eq default - end - - it "returns the extra" do - expect(subject.extra_context(additional)).to eq default.merge(additional) - end - - it "doesn't set anything if the extra is empty" do - subject.extra_context({}) - expect(subject.context.extra).to eq default - end - - it "adds extra" do - subject.extra_context(additional) - expect(subject.context.extra).to eq default.merge(additional) - end - - context 'when block given' do - it "returns the extra" do - extra = subject.extra_context(additional) do - # do nothing - end - expect(extra).to eq default - end - - it "adds extra only in the block" do - subject.extra_context(additional) do - expect(subject.context.extra).to eq default.merge(additional) - end - expect(subject.context.extra).to eq default - end - end - end - - describe "#rack_context" do - it "doesn't set anything if the context is empty" do - subject.rack_context({}) - expect(subject.context.rack_env).to be_nil - end - - it "sets arbitrary rack context" do - subject.rack_context(:foo => :bar) - expect(subject.context.rack_env[:foo]).to eq(:bar) - end - end -end diff --git a/sentry-raven/spec/raven/integration_spec.rb b/sentry-raven/spec/raven/integration_spec.rb deleted file mode 100644 index a3c698f02..000000000 --- a/sentry-raven/spec/raven/integration_spec.rb +++ /dev/null @@ -1,113 +0,0 @@ -require 'spec_helper' - -RSpec.describe "Integration tests" do - before(:each) do - @io = StringIO.new - @logger = Logger.new(@io) - @instance = Raven::Instance.new - @stubs = Faraday::Adapter::Test::Stubs.new - @instance.configuration = Raven::Configuration.new.tap do |config| - config.server = 'http://12345:67890@sentry.localdomain/sentry/42' - config.http_adapter = [:test, @stubs] - config.logger = @logger - end - end - - it "prints deprecation warning when requiring 'sentry-raven-without-integrations'" do - expect do - require "sentry-raven-without-integrations" - end.to output( - "[Deprecation Warning] Dasherized filename \"sentry-raven-without-integrations\" is deprecated and will be removed in 4.0; use \"sentry_raven_without_integrations\" instead\n" # rubocop:disable Style/LineLength - ).to_stderr - end - - it "posting an exception" do - @stubs.post('sentry/api/42/store/') { [200, {}, 'ok'] } - - @instance.capture_exception(build_exception) - - @stubs.verify_stubbed_calls - expect(@io.string).to match(/Sending event [0-9a-f]+ to Sentry$/) - end - - it "posting an exception to a prefixed DSN" do - @stubs.post('/prefix/sentry/api/42/store/') { [200, {}, 'ok'] } - @instance.configuration.server = 'http://12345:67890@sentry.localdomain/prefix/sentry/42' - - @instance.capture_exception(build_exception) - - @stubs.verify_stubbed_calls - end - - # TODO: Not a very good test - # it "hitting quota limit shouldn't swallow exception" do - # @stubs.post('sentry/api/42/store/') { [403, {}, 'Creation of this event was blocked'] } - # - # # sentry error and original error - # expect(@logger).not_to receive(:error) - # @instance.capture_exception(build_exception) - # - # @stubs.verify_stubbed_calls - # end - - it "timed backoff should prevent sends" do - expect(@instance.client.transport).to receive(:send_event).exactly(1).times.and_raise(Faraday::ConnectionFailed, "conn failed") - 2.times { @instance.capture_exception(build_exception) } - expect(@io.string).to match(/Failed to submit event: ZeroDivisionError: divided by 0$/) - end - - it "transport failure should call transport_failure_callback" do - @instance.configuration.transport_failure_callback = proc { |_event, error| @io.puts "OK! - #{error.message}" } - - expect(@instance.client.transport).to receive(:send_event).exactly(1).times.and_raise(Faraday::ConnectionFailed, "conn failed") - @instance.capture_exception(build_exception) - expect(@io.string).to match(/OK! - conn failed$/) - end - - describe '#before_send' do - it "change event before sending (capture_exception)" do - @stubs.post('/prefix/sentry/api/42/store/') { [200, {}, 'ok'] } - - @instance.configuration.server = 'http://12345:67890@sentry.localdomain/prefix/sentry/42' - @instance.configuration.before_send = lambda { |event, hint| - expect(hint[:exception]).not_to be nil - expect(hint[:message]).to be nil - event.environment = 'testxx' - event - } - - event = @instance.capture_exception(build_exception) - expect(event.environment).to eq('testxx') - - @stubs.verify_stubbed_calls - end - - it "change event before sending (capture_message)" do - @stubs.post('/prefix/sentry/api/42/store/') { [200, {}, 'ok'] } - - @instance.configuration.server = 'http://12345:67890@sentry.localdomain/prefix/sentry/42' - @instance.configuration.before_send = lambda { |event, hint| - expect(hint[:exception]).to be nil - expect(hint[:message]).not_to be nil - expect(event.message).to eq('xyz') - event.message = 'abc' - event - } - - event = @instance.capture_message('xyz') - expect(event.message).to eq('abc') - - @stubs.verify_stubbed_calls - end - - it "return nil" do - @instance.configuration.server = 'http://12345:67890@sentry.localdomain/prefix/sentry/42' - @instance.configuration.before_send = lambda { |_event, _hint| - nil - } - - @instance.capture_exception(build_exception) - expect(@instance.client.transport).to receive(:send_event).exactly(0) - end - end -end diff --git a/sentry-raven/spec/raven/integrations/delayed_job_spec.rb b/sentry-raven/spec/raven/integrations/delayed_job_spec.rb deleted file mode 100644 index 3af6f1863..000000000 --- a/sentry-raven/spec/raven/integrations/delayed_job_spec.rb +++ /dev/null @@ -1,62 +0,0 @@ -# frozen_string_literal: true - -require 'spec_helper' -require 'delayed/backend/base' -require 'raven/integrations/delayed_job' - -module Delayed - module Plugins - class Raven - class SampleJob - include Delayed::Backend::Base - - class << self - def db_time_now - Time.now - end - end - - attr_accessor :attempts, :created_at, :error, :handler, :id, :last_error, :locked_at, :locked_by, - :payload_object, :priority, :queue, :run_at - - def initialize - super - - self.attempts = 0 - end - - def save!; end - end - - class RaiseErrorPayload - attr_accessor :job_data - - def perform - raise 'error' - end - end - end - end -end - -RSpec.describe Delayed::Plugins::Raven do - let(:worker) { Delayed::Worker.new } - - context 'ActiveJob' do - context 'when payload#perform raises exception' do - let(:job) { Delayed::Plugins::Raven::SampleJob.new } - - before do - allow(::Raven).to receive(:capture_exception) - - job.payload_object = Delayed::Plugins::Raven::RaiseErrorPayload.new - - worker.run(job) - end - - it 'should capture exception' do - expect(::Raven).to have_received(:capture_exception) - end - end - end -end diff --git a/sentry-raven/spec/raven/integrations/rack_spec.rb b/sentry-raven/spec/raven/integrations/rack_spec.rb deleted file mode 100644 index c7f8a7a2a..000000000 --- a/sentry-raven/spec/raven/integrations/rack_spec.rb +++ /dev/null @@ -1,189 +0,0 @@ -require 'spec_helper' -require 'raven/integrations/rack' - -RSpec.describe Raven::Rack do - let(:exception) { build_exception } - let(:additional_headers) { {} } - let(:env) { Rack::MockRequest.env_for("/test", additional_headers) } - - context "when we expect to capture an exception" do - before do - expect(Raven::Rack).to receive(:capture_exception).with(exception, env) - end - - it 'should capture exceptions' do - app = ->(_e) { raise exception } - stack = Raven::Rack.new(app) - - expect { stack.call(env) }.to raise_error(ZeroDivisionError) - end - - it 'should capture rack.exception' do - app = lambda do |e| - e['rack.exception'] = exception - [200, {}, ['okay']] - end - stack = Raven::Rack.new(app) - - stack.call(env) - end - - it 'should capture sinatra errors' do - app = lambda do |e| - e['sinatra.error'] = exception - [200, {}, ['okay']] - end - stack = Raven::Rack.new(app) - - stack.call(env) - end - end - - it 'should capture context and clear after app is called' do - Raven::Context.current.tags[:environment] = :test - - app = ->(_e) { :ok } - stack = Raven::Rack.new(app) - - stack.call(env) - - expect(Raven::Context.current.tags).to eq({}) - end - - it 'sets transaction' do - app = lambda do |_e| - expect(Raven.context.transaction.last).to eq "/test" - end - stack = Raven::Rack.new(app) - - stack.call(env) - - expect(Raven.context.transaction.last).to be_nil - end - - it 'should allow empty rack env in rspec tests' do - Raven.rack_context({}) # the rack env is empty when running rails/rspec tests - Raven.capture_exception(build_exception) - end - - it 'should bind request context' do - Raven::Context.current.rack_env = nil - - app = lambda do |env| - expect(Raven::Context.current.rack_env).to eq(env) - - ['response', {}, env] - end - stack = Raven::Rack.new(app) - - stack.call({}) - end - - it 'excludes non whitelisted params from rack env' do - interface = Raven::HttpInterface.new - additional_env = { "random_param" => "text", "query_string" => "test" } - new_env = env.merge(additional_env) - interface.from_rack(new_env) - - expect(interface.env).to_not include(additional_env) - end - - it 'formats rack env according to the provided whitelist' do - Raven.configuration.rack_env_whitelist = %w(random_param query_string) - interface = Raven::HttpInterface.new - additional_env = { "random_param" => "text", "query_string" => "test" } - new_env = env.merge(additional_env) - interface.from_rack(new_env) - - expect(interface.env).to eq(additional_env) - end - - it 'keeps the original env intact when an empty whitelist is provided' do - Raven.configuration.rack_env_whitelist = [] - interface = Raven::HttpInterface.new - interface.from_rack(env) - - expect(interface.env).to eq(env) - end - - describe 'format headers' do - let(:additional_headers) { { "HTTP_VERSION" => "HTTP/1.1", "HTTP_COOKIE" => "test", "HTTP_X_REQUEST_ID" => "12345678" } } - - it 'transforms headers to conform with the interface' do - interface = Raven::HttpInterface.new - interface.from_rack(env) - - expect(interface.headers).to eq("Content-Length" => "0", "Version" => "HTTP/1.1", "X-Request-Id" => "12345678") - end - - context 'from Rails middleware' do - let(:additional_headers) { { "action_dispatch.request_id" => "12345678" } } - - it 'transforms headers to conform with the interface' do - interface = Raven::HttpInterface.new - interface.from_rack(env) - - expect(interface.headers).to eq("Content-Length" => "0", "X-Request-Id" => "12345678") - end - end - - context 'with additional env variables' do - let(:mock) { double } - let(:env) { { "some.variable" => mock } } - - it 'does not call #to_s for unnecessary env variables' do - expect(mock).not_to receive(:to_s) - - interface = Raven::HttpInterface.new - interface.from_rack(env) - end - end - end - - it 'puts cookies into the cookies attribute' do - interface = Raven::HttpInterface.new - new_env = env.merge("HTTP_COOKIE" => "test") - interface.from_rack(new_env) - - expect(interface.cookies).to eq("test" => nil) - end - - it 'does not ignore version headers which do not match SERVER_PROTOCOL' do - new_env = env.merge("SERVER_PROTOCOL" => "HTTP/1.1", "HTTP_VERSION" => "HTTP/2.0") - - interface = Raven::HttpInterface.new - interface.from_rack(new_env) - - expect(interface.headers["Version"]).to eq("HTTP/2.0") - end - - it 'retains any literal "HTTP-" in the actual header name' do - interface = Raven::HttpInterface.new - new_env = env.merge("HTTP_HTTP_CUSTOM_HTTP_HEADER" => "test") - interface.from_rack(new_env) - - expect(interface.headers).to include("Http-Custom-Http-Header" => "test") - end - - it 'does not fail if an object in the env cannot be cast to string' do - obj = Class.new do - def to_s - raise 'Could not stringify object!' - end - end.new - - new_env = env.merge("HTTP_FOO" => "BAR", "rails_object" => obj) - interface = Raven::HttpInterface.new - - expect { interface.from_rack(new_env) }.to_not raise_error - end - - it 'should pass rack/lint' do - app = proc do - [200, { 'Content-Type' => 'text/plain' }, ['OK']] - end - - stack = Raven::Rack.new(Rack::Lint.new(app)) - expect { stack.call(env) }.to_not raise_error - end -end diff --git a/sentry-raven/spec/raven/integrations/rack_timeout_spec.rb b/sentry-raven/spec/raven/integrations/rack_timeout_spec.rb deleted file mode 100644 index 66f32699b..000000000 --- a/sentry-raven/spec/raven/integrations/rack_timeout_spec.rb +++ /dev/null @@ -1,18 +0,0 @@ -require "spec_helper" -require "rack/timeout/base" -require "raven/integrations/rack-timeout" - -RSpec.describe "Rack timeout" do - it "should have a raven_context method defined" do - exc = Rack::Timeout::RequestTimeoutException.new("REQUEST_URI" => "This is a URI") - - expect(exc.raven_context[:fingerprint]).to eq(["{{ default }}", "This is a URI"]) - end - - it "should return an empty context if env is missing" do - exception = Object.new - exception.extend(RackTimeoutExtensions) - - expect(exception.raven_context).to eq({}) - end -end diff --git a/sentry-raven/spec/raven/integrations/rails/activejob_spec.rb b/sentry-raven/spec/raven/integrations/rails/activejob_spec.rb deleted file mode 100644 index 207fd8b86..000000000 --- a/sentry-raven/spec/raven/integrations/rails/activejob_spec.rb +++ /dev/null @@ -1,78 +0,0 @@ -require "spec_helper" - -if defined? ActiveJob - class MyActiveJob < ActiveJob::Base - self.logger = nil - - class TestError < RuntimeError - end - - def perform - raise TestError, "Boom!" - end - end - - class RescuedActiveJob < MyActiveJob - rescue_from TestError, :with => :rescue_callback - - def rescue_callback(error); end - end -end - -RSpec.describe "ActiveJob integration", :rails => true do - before(:all) do - require "rspec/rails" - require "raven/integrations/rails" - require "raven/integrations/rails/active_job" - end - - before(:each) do - Raven.client.transport.events = [] - MyActiveJob.queue_adapter = :inline - end - - it_should_behave_like "Raven default capture behavior" do - let(:block) { MyActiveJob.new.perform_now } - let(:captured_class) { MyActiveJob::TestError } - let(:captured_message) { "Boom!" } - end - - it "clears context" do - Raven.extra_context(:foo => :bar) - job = MyActiveJob.new - - expect { job.perform_now }.to raise_error(MyActiveJob::TestError) - event = JSON.parse!(Raven.client.transport.events.first[1]) - - expect(event["extra"]["foo"]).to eq("bar") - - Raven.client.transport.events = [] - expect { job.perform_now }.to raise_error(MyActiveJob::TestError) - event = JSON.parse!(Raven.client.transport.events.first[1]) - - expect(event["extra"]["foo"]).to eq(nil) - end - - context 'using rescue_from' do - it 'does not trigger Sentry' do - job = RescuedActiveJob.new - allow(job).to receive(:rescue_callback) - - expect { job.perform_now }.not_to raise_error - - expect(Raven.client.transport.events.size).to eq(0) - expect(job).to have_received(:rescue_callback).once - end - end - - context "when we are using an adapter which has a specific integration" do - it "does not trigger sentry and re-raises" do - MyActiveJob.queue_adapter = :sidekiq - job = MyActiveJob.new - - expect { job.perform_now }.to raise_error(MyActiveJob::TestError) - - expect(Raven.client.transport.events.size).to eq(0) - end - end -end diff --git a/sentry-raven/spec/raven/integrations/rails/controller_methods_spec.rb b/sentry-raven/spec/raven/integrations/rails/controller_methods_spec.rb deleted file mode 100644 index c503f4f83..000000000 --- a/sentry-raven/spec/raven/integrations/rails/controller_methods_spec.rb +++ /dev/null @@ -1,31 +0,0 @@ -require 'spec_helper' - -RSpec.describe "Raven::Rails::ControllerMethods", :rails => true do - include Raven::Rails::ControllerMethods if defined?(Rails) - - before(:all) do - require 'raven/integrations/rails/controller_methods' - end - - let(:env) { { "foo" => "bar" } } - let(:request) { double('request', :env => env) } - let(:options) { double('options') } - - describe "#capture_message" do - let(:message) { double('message') } - - it "captures a message with the request environment" do - expect(Raven::Rack).to receive(:capture_message).with(message, env, options) - capture_message(message, options) - end - end - - describe "#capture_exception" do - let(:exception) { double('exception') } - - it "captures a exception with the request environment" do - expect(Raven::Rack).to receive(:capture_exception).with(exception, env, options) - capture_exception(exception, options) - end - end -end diff --git a/sentry-raven/spec/raven/integrations/rails/event_spec.rb b/sentry-raven/spec/raven/integrations/rails/event_spec.rb deleted file mode 100644 index 4709575b8..000000000 --- a/sentry-raven/spec/raven/integrations/rails/event_spec.rb +++ /dev/null @@ -1,72 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Event, :rails => true do - context 'in a rails environment' do - let(:configuration) do - config = Raven::Configuration.new - config.dsn = "dummy://12345:67890@sentry.localdomain:3000/sentry/42" - config.logger = Logger.new(nil) - config - end - - let(:instance) { Raven::Instance.new(nil, configuration) } - - context 'with an application stacktrace' do - let(:exception) do - e = Exception.new("Oh no!") - allow(e).to receive(:backtrace).and_return [ - "#{Rails.root}/vendor/bundle/cache/other_gem.rb:10:in `public_method'", - "vendor/bundle/some_gem.rb:10:in `a_method'", - "#{Rails.root}/app/models/user.rb:132:in `new_function'", - "/gem/lib/path:87:in `a_function'", - "/app/some/other/path:1412:in `other_function'", - "test/some/other/path:1412:in `other_function'" - ] - e - end - - let(:hash) { instance.capture_exception(exception).to_hash } - - it 'marks in_app correctly' do - frames = hash[:exception][:values][0][:stacktrace][:frames] - expect(frames[0][:filename]).to eq("test/some/other/path") - expect(frames[0][:in_app]).to eq(true) - expect(frames[1][:filename]).to eq("/app/some/other/path") - expect(frames[1][:in_app]).to eq(false) - expect(frames[2][:filename]).to eq("/gem/lib/path") - expect(frames[2][:in_app]).to eq(false) - expect(frames[3][:filename]).to eq("app/models/user.rb") - expect(frames[3][:in_app]).to eq(true) - expect(frames[4][:filename]).to eq("vendor/bundle/some_gem.rb") - expect(frames[4][:in_app]).to eq(false) - expect(frames[5][:filename]).to eq("vendor/bundle/cache/other_gem.rb") - expect(frames[5][:in_app]).to eq(false) - end - - context 'when an in_app path under project_root is on the load path' do - it 'normalizes the filename using project_root' do - $LOAD_PATH << "#{Rails.root}/app/models" - frames = hash[:exception][:values][0][:stacktrace][:frames] - expect(frames[3][:filename]).to eq("app/models/user.rb") - $LOAD_PATH.delete("#{Rails.root}/app/models") - end - end - - context 'when a non-in_app path under project_root is on the load path' do - it 'normalizes the filename using the load path' do - $LOAD_PATH.push "#{Rails.root}/vendor/bundle" - frames = hash[:exception][:values][0][:stacktrace][:frames] - expect(frames[5][:filename]).to eq("cache/other_gem.rb") - $LOAD_PATH.pop - end - end - - context "when a non-in_app path under project_root isn't on the load path" do - it 'normalizes the filename using project_root' do - frames = hash[:exception][:values][0][:stacktrace][:frames] - expect(frames[5][:filename]).to eq("vendor/bundle/cache/other_gem.rb") - end - end - end - end -end diff --git a/sentry-raven/spec/raven/integrations/rails/overrides/debug_exceptions_catcher_spec.rb b/sentry-raven/spec/raven/integrations/rails/overrides/debug_exceptions_catcher_spec.rb deleted file mode 100644 index b4a14ba00..000000000 --- a/sentry-raven/spec/raven/integrations/rails/overrides/debug_exceptions_catcher_spec.rb +++ /dev/null @@ -1,69 +0,0 @@ -require 'spec_helper' - -RSpec.shared_examples "exception catching middleware" do - let(:middleware) do - Class.new do - def initialize(app) - @app = app - end - - def call(env) - @app.call(env) - rescue => e - render_exception(env, e) - end - - def render_exception(_, exception) - [500, exception.message, {}] - end - end - end - - let(:app) do - lambda { |_| raise "app error" } # rubocop:disable Style/Lambda - end - - let(:env) { {} } - - it "shows the exception" do - expect(middleware.new(app).call(env)).to eq([500, "app error", {}]) - end - - it "captures the exception" do - expect(Raven::Rack).to receive(:capture_exception) - middleware.new(app).call(env) - end - - context "when an error is raised" do - it "shows the original exception" do - allow(Raven::Rack).to receive(:capture_exception).and_raise("raven error") - expect(middleware.new(app).call(env)).to eq([500, "app error", {}]) - end - end -end - -RSpec.describe "Raven::Rails::Overrides::DebugExceptionsCatcher", :rails => true do - before(:all) do - require 'raven/integrations/rails/overrides/debug_exceptions_catcher' - end - - if Class.respond_to?(:alias_method_chain) - context "using include" do - before do - middleware.send(:include, Raven::Rails::Overrides::OldDebugExceptionsCatcher) - end - - include_examples "exception catching middleware" - end - end - - if Class.respond_to?(:prepend) - context "using prepend" do - before do - middleware.send(:prepend, Raven::Rails::Overrides::DebugExceptionsCatcher) - end - - include_examples "exception catching middleware" - end - end -end diff --git a/sentry-raven/spec/raven/integrations/rails_spec.rb b/sentry-raven/spec/raven/integrations/rails_spec.rb deleted file mode 100644 index 5e2fb3137..000000000 --- a/sentry-raven/spec/raven/integrations/rails_spec.rb +++ /dev/null @@ -1,81 +0,0 @@ -require "spec_helper" - -RSpec.describe "Rails Integration", :type => :request, :rails => true do - before(:all) do - make_basic_app - end - - after(:each) do - Raven.client.transport.events = [] - end - - it "inserts middleware" do - expect(Rails.application.middleware).to include(Raven::Rack) - end - - it "doesn't do anything on a normal route" do - get "/" - - expect(response.status).to eq(200) - expect(Raven.client.transport.events.size).to eq(0) - end - - it "should capture exceptions in production" do - get "/exception" - - expect(response.status).to eq(500) - event = JSON.parse!(Raven.client.transport.events.first[1]) - expect(event["exception"]["values"][0]["type"]).to eq("RuntimeError") - expect(event["exception"]["values"][0]["value"]).to eq("An unhandled exception!") - end - - it "should capture exceptions in production" do - get "/exception" - - expect(response.status).to eq(500) - event = JSON.parse!(Raven.client.transport.events.first[1]) - expect(event["exception"]["values"][0]["type"]).to eq("RuntimeError") - expect(event["exception"]["values"][0]["value"]).to eq("An unhandled exception!") - end - - it "filters exception backtrace with with custom BacktraceCleaner" do - get "/view_exception" - - event = JSON.parse!(Raven.client.transport.events.first[1]) - traces = event.dig("exception", "values", 0, "stacktrace", "frames") - expect(traces.dig(-1, "filename")).to eq("inline template") - - # we want to avoid something like "_inline_template__3014794444104730113_10960" - expect(traces.dig(-1, "function")).to be_nil - end - - it "doesn't filters exception backtrace if backtrace_cleanup_callback is overridden" do - Raven.configuration.backtrace_cleanup_callback = nil - - get "/view_exception" - - event = JSON.parse!(Raven.client.transport.events.first[1]) - traces = event.dig("exception", "values", 0, "stacktrace", "frames") - expect(traces.dig(-1, "filename")).to eq("inline template") - expect(traces.dig(-1, "function")).not_to be_nil - end - - it "sets transaction to ControllerName#method" do - get "/exception" - - event = JSON.parse!(Raven.client.transport.events.first[1]) - expect(event['transaction']).to eq("HelloController#exception") - end - - it "sets Raven.configuration.logger correctly" do - expect(Raven.configuration.logger).to eq(Rails.logger) - end - - it "sets Raven.configuration.project_root correctly" do - expect(Raven.configuration.project_root).to eq(Rails.root.to_s) - end - - it "doesn't clobber a manually configured release" do - expect(Raven.configuration.release).to eq('beta') - end -end diff --git a/sentry-raven/spec/raven/integrations/rake_spec.rb b/sentry-raven/spec/raven/integrations/rake_spec.rb deleted file mode 100644 index 2ff3d74ff..000000000 --- a/sentry-raven/spec/raven/integrations/rake_spec.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'spec_helper' - -RSpec.describe 'Rake tasks' do - it "should capture exceptions in Rake tasks" do - expect(`cd spec/support && bundle exec rake raise_exception 2>&1`).to match(/Sending event [abcdef0-9]+ to Sentry/) - end -end diff --git a/sentry-raven/spec/raven/integrations/sidekiq/error_handler_spec.rb b/sentry-raven/spec/raven/integrations/sidekiq/error_handler_spec.rb deleted file mode 100644 index 30262b746..000000000 --- a/sentry-raven/spec/raven/integrations/sidekiq/error_handler_spec.rb +++ /dev/null @@ -1,67 +0,0 @@ -require 'spec_helper' - -require 'raven/integrations/sidekiq/error_handler' - -RSpec.describe "Raven::Sidekiq::ErrorHandler" do - let(:context) do - { - "args" => [true, true], - "class" => "HardWorker", - "created_at" => 1_474_922_824.910579, - "enqueued_at" => 1_474_922_824.910665, - "error_class" => "RuntimeError", - "error_message" => "a wild exception appeared", - "failed_at" => 1_474_922_825.158953, - "jid" => "701ed9cfa51c84a763d56bc4", - "queue" => "default", - "retry" => true, - "retry_count" => 0 - } - end - - it "should capture exceptions based on Sidekiq context" do - exception = build_exception - expected_options = { - :message => exception.message, - :extra => { :sidekiq => context } - } - - expect(Raven).to receive(:capture_exception).with(exception, expected_options) - - Raven::Sidekiq::ErrorHandler.new.call(exception, context) - end - - context "when the captured exception is already annotated" do - it "does a deep merge of options" do - exception = build_exception - Raven.annotate_exception(exception, :extra => { :job_title => "engineer" }) - expected_options = { - :message => exception.message, - :extra => { - :sidekiq => context, - :job_title => "engineer" - } - } - - expect(Raven::Event).to receive(:new).with(hash_including(expected_options)) - - Raven::Sidekiq::ErrorHandler.new.call(exception, context) - end - end - - it "filters out ActiveJob keys", :rails => true do - exception = build_exception - aj_context = context - aj_context["_aj_globalid"] = GlobalID.new('gid://app/model/id') - expected_context = aj_context.dup - expected_context.delete("_aj_globalid") - expected_context["globalid"] = "gid://app/model/id" - expected_options = { - :message => exception.message, - :extra => { :sidekiq => expected_context } - } - expect(Raven).to receive(:capture_exception).with(exception, expected_options) - - Raven::Sidekiq::ErrorHandler.new.call(exception, aj_context) - end -end diff --git a/sentry-raven/spec/raven/integrations/sidekiq_spec.rb b/sentry-raven/spec/raven/integrations/sidekiq_spec.rb deleted file mode 100644 index 3b56ac815..000000000 --- a/sentry-raven/spec/raven/integrations/sidekiq_spec.rb +++ /dev/null @@ -1,136 +0,0 @@ -require 'spec_helper' - -# sidekiq only enables server config when the CLI class is loaded -# so we need to load the CLI class to achieve full integration in test environment -require 'sidekiq/cli' -require 'sidekiq/manager' -require 'sidekiq/api' - -require 'raven/integrations/sidekiq' - -class HappyWorker - include Sidekiq::Worker - - def perform - Raven.breadcrumbs.record do |crumb| - crumb.message = "I'm happy!" - end - Raven.tags_context :mood => 'happy' - end -end - -class SadWorker - include Sidekiq::Worker - - def perform - Raven.breadcrumbs.record do |crumb| - crumb.message = "I'm sad!" - end - Raven.tags_context :mood => 'sad' - - raise "I'm sad!" - end -end - -class VerySadWorker - include Sidekiq::Worker - - def perform - Raven.breadcrumbs.record do |crumb| - crumb.message = "I'm very sad!" - end - Raven.tags_context :mood => 'very sad' - - raise "I'm very sad!" - end -end - -class ReportingWorker - include Sidekiq::Worker - - def perform - Raven.capture_message("I have something to say!") - end -end - -RSpec.describe "Sidekiq full-stack integration" do - before :all do - Sidekiq.logger = Logger.new(nil) - end - - after(:all) do - # those test jobs will go into the real Redis and be visiable to other sidekiq processes - # this can affect local testing and development, so we should clear them after each test - Sidekiq::RetrySet.new.clear - end - - def process_job(klass) - msg = Sidekiq.dump_json("class" => klass) - job = Sidekiq::BasicFetch::UnitOfWork.new('queue:default', msg) - @processor.instance_variable_set(:'@job', job) - - @processor.send(:process, job) - rescue StandardError - # do nothing - end - - before do - options = - if Gem::Version.new(Sidekiq::VERSION) >= Gem::Version.new("6.0") - Sidekiq[:queue] = ['default'] - Sidekiq - else - { queues: ['default'] } - end - - manager = Sidekiq::Manager.new(options) - @processor = manager.workers.first - end - - it "actually captures an exception" do - expect { process_job("SadWorker") }.to change { Raven.client.transport.events.size }.by(1) - - event = JSON.parse(Raven.client.transport.events.last[1]) - expect(event["logentry"]["message"]).to eq("I'm sad!") - end - - it "clears context from other workers and captures its own" do - process_job("HappyWorker") - process_job("SadWorker") - - event = JSON.parse(Raven.client.transport.events.last[1]) - - expect(event["tags"]).to eq("mood" => "sad") - expect(event["transaction"]).to eq("Sidekiq/SadWorker") - expect(event["breadcrumbs"]["values"][0]["message"]).to eq("I'm sad!") - end - - it "clears context after raising" do - process_job("SadWorker") - process_job("VerySadWorker") - - event = JSON.parse(Raven.client.transport.events.last[1]) - - expect(event["tags"]).to eq("mood" => "very sad") - expect(event["breadcrumbs"]["values"][0]["message"]).to eq("I'm very sad!") - end - - it "captures exceptions raised during events" do - Sidekiq.options[:lifecycle_events][:startup] = [proc { raise "Uhoh!" }] - @processor.fire_event(:startup) - - event = JSON.parse(Raven.client.transport.events.last[1]) - - expect(event["logentry"]["message"]).to eq "Uhoh!" - expect(event["transaction"]).to eq "Sidekiq/startup" - end - - it "has some context when capturing, even if no exception raised" do - process_job("ReportingWorker") - - event = JSON.parse(Raven.client.transport.events.last[1]) - - expect(event["logentry"]["message"]).to eq "I have something to say!" - expect(event["extra"]["sidekiq"]).to eq("class" => "ReportingWorker", "queue" => "default") - end -end diff --git a/sentry-raven/spec/raven/interface_spec.rb b/sentry-raven/spec/raven/interface_spec.rb deleted file mode 100644 index 7ae0e467a..000000000 --- a/sentry-raven/spec/raven/interface_spec.rb +++ /dev/null @@ -1,37 +0,0 @@ -require 'spec_helper' - -class TestInterface < Raven::Interface - attr_accessor :some_attr -end - -RSpec.describe Raven::Interface do - it "should register an interface when a new class is defined" do - expect(Raven::Interface.registered[:test]).to eq(TestInterface) - end - - it "can be initialized with some attributes" do - interface = TestInterface.new(:some_attr => "test") - expect(interface.some_attr).to eq("test") - end - - it "can initialize with a block" do - interface = TestInterface.new { |int| int.some_attr = "test" } - expect(interface.some_attr).to eq("test") - end - - it "serializes to a Hash" do - interface = TestInterface.new(:some_attr => "test") - expect(interface.to_hash).to eq(:some_attr => "test") - end -end - -RSpec.describe Raven::MessageInterface do - it "supports invalid format string message when params is not defined" do - interface = Raven::MessageInterface.new(:params => nil, :message => "test '%'") - expect(interface.unformatted_message).to eq("test '%'") - end - it "supports invalid format string message when params is empty" do - interface = Raven::MessageInterface.new(:message => "test '%'") - expect(interface.unformatted_message).to eq("test '%'") - end -end diff --git a/sentry-raven/spec/raven/interfaces/stack_trace_spec.rb b/sentry-raven/spec/raven/interfaces/stack_trace_spec.rb deleted file mode 100644 index f6ad60f71..000000000 --- a/sentry-raven/spec/raven/interfaces/stack_trace_spec.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::StacktraceInterface::Frame do - it "should convert pathnames to strings" do - frame = Raven::StacktraceInterface::Frame.new - $LOAD_PATH.unshift Pathname.pwd # Oh no, a Pathname in the $LOAD_PATH! - frame.abs_path = __FILE__ - expect(frame.filename).to match(/stack_trace_spec.rb/) - $LOAD_PATH.shift - end -end diff --git a/sentry-raven/spec/raven/json_spec.rb b/sentry-raven/spec/raven/json_spec.rb deleted file mode 100644 index 9c511c48b..000000000 --- a/sentry-raven/spec/raven/json_spec.rb +++ /dev/null @@ -1,63 +0,0 @@ -# Raven sometimes has to deal with some weird JSON. This makes sure whatever -# JSON impl we use handles it in the way that we expect. - -require 'spec_helper' -require 'ostruct' - -RSpec.describe JSON do - data = [ - OpenStruct.new(:key => 'foo', :val => 'bar', :enc_key => '"foo"', :enc_val => '"bar"'), - OpenStruct.new(:key => :foo, :val => :bar, :enc_key => '"foo"', :enc_val => '"bar"'), - OpenStruct.new(:key => 1, :val => 1, :enc_key => '"1"', :enc_val => '1') - ] - - data.each do |obj| - it "works with #{obj.key.class} keys" do - expect(JSON.dump(obj.key => 'bar')).to eq "{#{obj.enc_key}:\"bar\"}" - end - - it "works with #{obj.val.class} values" do - expect(JSON.dump('bar' => obj.val)).to eq "{\"bar\":#{obj.enc_val}}" - end - - it "works with an array of #{obj.val.class}s" do - expect(JSON.dump('bar' => [obj.val])).to eq "{\"bar\":[#{obj.enc_val}]}" - end - - it "works with a hash of #{obj.val.class}s" do - expect(JSON.dump('bar' => { obj.key => obj.val })).to eq "{\"bar\":{#{obj.enc_key}:#{obj.enc_val}}}" - end - end - - it 'encodes anything that responds to to_s' do - data = [ - :symbol, - 1 / 0.0, - 0 / 0.0 - ] - expect(JSON.dump(data)).to eq "[\"symbol\",Infinity,NaN]" - end - - it 'resolves large numbers to Infinity' do - expect(JSON.parse("[123e090000000]")).to eq [+1.0 / 0.0] - end - - it 'it raises the correct error on strings that look like incomplete objects' do - expect { JSON.parse("{") }.to raise_error(JSON::ParserError) - expect { JSON.parse("[") }.to raise_error(JSON::ParserError) - end - - it "accepts any encoding which is internally valid" do - expect do - JSON.parse(%({"example": "this is a utf8 or ASCII string"})) - end.not_to raise_error - - expect do - JSON.parse(%({"example": "this is a utf8 or ASCII string"}).encode("utf-16")) - end.not_to raise_error - - expect do - JSON.parse(%({"example": "this is a utf8 or ASCII string"}).encode("US-ASCII")) - end.not_to raise_error - end -end diff --git a/sentry-raven/spec/raven/linecache_spec.rb b/sentry-raven/spec/raven/linecache_spec.rb deleted file mode 100644 index 4edda6e10..000000000 --- a/sentry-raven/spec/raven/linecache_spec.rb +++ /dev/null @@ -1,40 +0,0 @@ -require 'spec_helper' -# rubocop:disable Style/WordArray -RSpec.describe Raven::LineCache do - describe "#get_file_context" do - it "returns an array of nils if the path is not valid" do - expect(subject.get_file_context("/nonexist", 1, 10)).to eq([nil, nil, nil]) - end - - it "returns a variable size depending on context" do - expect(subject.get_file_context("spec/support/linecache.txt", 3, 2)).to eq( - [ - ["foo\n", "bar\n"], - "baz\n", - ["qux\n", "lorem\n"] - ] - ) - end - - it "returns nil if line doesnt exist" do - expect(subject.get_file_context("spec/support/linecache.txt", 1, 2)).to eq( - [ - [nil, nil], - "foo\n", - ["bar\n", "baz\n"] - ] - ) - end - - it "returns a different section of the file based on lineno" do - expect(subject.get_file_context("./spec/support/linecache.txt", 4, 2)).to eq( - [ - ["bar\n", "baz\n"], - "qux\n", - ["lorem\n", "ipsum\n"] - ] - ) - end - end -end -# rubocop:enable Style/WordArray diff --git a/sentry-raven/spec/raven/logger_spec.rb b/sentry-raven/spec/raven/logger_spec.rb deleted file mode 100644 index 638fff8a9..000000000 --- a/sentry-raven/spec/raven/logger_spec.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Logger do - it "should log to a given IO" do - stringio = StringIO.new - log = Raven::Logger.new(stringio) - - log.fatal("Oh noes!") - - expect(stringio.string).to end_with("FATAL -- sentry: ** [Raven] Oh noes!\n") - end - - it "should allow exceptions to be logged" do - stringio = StringIO.new - log = Raven::Logger.new(stringio) - - log.fatal(Exception.new("Oh exceptions")) - - expect(stringio.string).to end_with("FATAL -- sentry: ** [Raven] Oh exceptions\n") - end -end diff --git a/sentry-raven/spec/raven/processors/cookies_spec.rb b/sentry-raven/spec/raven/processors/cookies_spec.rb deleted file mode 100644 index f13bc702f..000000000 --- a/sentry-raven/spec/raven/processors/cookies_spec.rb +++ /dev/null @@ -1,63 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Processor::Cookies do - before do - @client = double("client") - @processor = Raven::Processor::Cookies.new(@client) - end - - it 'should remove cookies' do - test_data = { - :request => { - :headers => { - "Cookie" => { "_sentry-testapp_session" => "SlRKVnNha2Z" }, - "AnotherHeader" => "still_here" - }, - :cookies => { "_sentry-testapp_session" => "SlRKVnNha2Z" }, - :some_other_data => "still_here" - } - } - - result = @processor.process(test_data) - - expect(result[:request][:cookies]).to eq({ "_sentry-testapp_session" => "********" }) - expect(result[:request][:headers]["Cookie"]).to eq({ "_sentry-testapp_session" => "********" }) - expect(result[:request][:some_other_data]).to eq("still_here") - expect(result[:request][:headers]["AnotherHeader"]).to eq("still_here") - end - - it 'should remove cookies even if keys are strings' do - test_data = { - "request" => { - "headers" => { - "Cookie" => { "_sentry-testapp_session" => "SlRKVnNha2Z" }, - "AnotherHeader" => "still_here" - }, - "cookies" => { "_sentry-testapp_session" => "SlRKVnNha2Z" }, - "some_other_data" => "still_here" - } - } - - result = @processor.process(test_data) - - expect(result["request"]["cookies"]).to eq({ "_sentry-testapp_session" => "********" }) - expect(result["request"]["headers"]["Cookie"]).to eq({ "_sentry-testapp_session" => "********" }) - expect(result["request"]["some_other_data"]).to eq("still_here") - expect(result["request"]["headers"]["AnotherHeader"]).to eq("still_here") - end - - it 'does not fail if it runs after Processor::RemoveCircularReferences' do - test_data = { - :request => { - :headers => { - "Cookie" => Raven::Processor::RemoveCircularReferences::ELISION_STRING, - "AnotherHeader" => "still_here" - }, - :cookies => Raven::Processor::RemoveCircularReferences::ELISION_STRING, - :some_other_data => "still_here" - } - } - - @processor.process(test_data) - end -end diff --git a/sentry-raven/spec/raven/processors/http_headers_spec.rb b/sentry-raven/spec/raven/processors/http_headers_spec.rb deleted file mode 100644 index 90979cfb7..000000000 --- a/sentry-raven/spec/raven/processors/http_headers_spec.rb +++ /dev/null @@ -1,57 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Processor::HTTPHeaders do - before do - @client = double("client") - allow(@client).to receive_message_chain(:configuration, :sanitize_http_headers) { ['User-Defined-Header'] } - @processor = Raven::Processor::HTTPHeaders.new(@client) - end - - it 'should remove HTTP headers we dont like' do - data = { - :request => { - :headers => { - "Authorization" => "dontseeme", - "AnotherHeader" => "still_here" - } - } - } - - result = @processor.process(data) - - expect(result[:request][:headers]["Authorization"]).to eq("********") - expect(result[:request][:headers]["AnotherHeader"]).to eq("still_here") - end - - it 'should be configurable' do - data = { - :request => { - :headers => { - "User-Defined-Header" => "dontseeme", - "AnotherHeader" => "still_here" - } - } - } - - result = @processor.process(data) - - expect(result[:request][:headers]["User-Defined-Header"]).to eq("********") - expect(result[:request][:headers]["AnotherHeader"]).to eq("still_here") - end - - it "should remove headers even if the keys are strings" do - data = { - "request" => { - "headers" => { - "Authorization" => "dontseeme", - "AnotherHeader" => "still_here" - } - } - } - - result = @processor.process(data) - - expect(result["request"]["headers"]["Authorization"]).to eq("********") - expect(result["request"]["headers"]["AnotherHeader"]).to eq("still_here") - end -end diff --git a/sentry-raven/spec/raven/processors/post_data_spec.rb b/sentry-raven/spec/raven/processors/post_data_spec.rb deleted file mode 100644 index f6c3e2f75..000000000 --- a/sentry-raven/spec/raven/processors/post_data_spec.rb +++ /dev/null @@ -1,53 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Processor::PostData do - before do - @client = double("client") - @processor = Raven::Processor::PostData.new(@client) - end - - it 'should remove post data when HTTP method is POST' do - data = { - :request => { - :method => "POST", - :data => { - "sensitive_stuff" => "TOP_SECRET-GAMMA" - } - } - } - - result = @processor.process(data) - - expect(result[:request][:data]).to eq("********") - end - - it 'should NOT remove post data when HTTP method is not POST' do - data = { - :request => { - :method => "GET", - :data => { - "sensitive_stuff" => "TOP_SECRET-GAMMA" - } - } - } - - result = @processor.process(data) - - expect(result[:request][:data]).to eq("sensitive_stuff" => "TOP_SECRET-GAMMA") - end - - it 'should remove post data when HTTP method is POST and keys are strings' do - data = { - "request" => { - "method" => "POST", - "data" => { - "sensitive_stuff" => "TOP_SECRET-GAMMA" - } - } - } - - result = @processor.process(data) - - expect(result["request"]["data"]).to eq("********") - end -end diff --git a/sentry-raven/spec/raven/processors/removecirculareferences_spec.rb b/sentry-raven/spec/raven/processors/removecirculareferences_spec.rb deleted file mode 100644 index eb2bc7a94..000000000 --- a/sentry-raven/spec/raven/processors/removecirculareferences_spec.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Processor::RemoveCircularReferences do - before do - @client = double("client") - @processor = Raven::Processor::RemoveCircularReferences.new(@client) - end - - it 'should cleanup circular references' do - data = {} - data['data'] = data - data['ary'] = [] - data['ary'].push('x' => data['ary']) - data['ary2'] = data['ary'] - data['leave intact'] = { 'not a circular reference' => true } - - result = @processor.process(data) - expect(result['data']).to eq('(...)') - expect(result['ary'].first['x']).to eq('(...)') - expect(result['ary2']).to eq("(...)") - expect(result['leave intact']).to eq('not a circular reference' => true) - end -end diff --git a/sentry-raven/spec/raven/processors/removestacktrace_spec.rb b/sentry-raven/spec/raven/processors/removestacktrace_spec.rb deleted file mode 100644 index e77385b81..000000000 --- a/sentry-raven/spec/raven/processors/removestacktrace_spec.rb +++ /dev/null @@ -1,56 +0,0 @@ -require 'spec_helper' -require 'raven/processor/removestacktrace' - -RSpec.describe Raven::Processor::RemoveStacktrace do - before do - @client = double("client") - @processor = Raven::Processor::RemoveStacktrace.new(@client) - end - - it 'should remove stacktraces' do - data = Raven.capture_exception(build_exception).to_hash - - expect(data[:exception][:values][0][:stacktrace]).to_not eq(nil) - result = @processor.process(data) - - expect(result[:exception][:values][0][:stacktrace]).to eq(nil) - end - - # Only check causes when they're supported - if Exception.new.respond_to? :cause - it 'should remove stacktraces from causes' do - data = Raven.capture_exception(build_exception_with_cause).to_hash - - expect(data[:exception][:values][0][:stacktrace]).to_not eq(nil) - expect(data[:exception][:values][1][:stacktrace]).to_not eq(nil) - result = @processor.process(data) - - expect(result[:exception][:values][0][:stacktrace]).to eq(nil) - expect(result[:exception][:values][1][:stacktrace]).to eq(nil) - end - - it 'should remove stacktraces from nested causes' do - data = Raven.capture_exception(build_exception_with_two_causes).to_hash - - expect(data[:exception][:values][0][:stacktrace]).to_not eq(nil) - expect(data[:exception][:values][1][:stacktrace]).to_not eq(nil) - expect(data[:exception][:values][2][:stacktrace]).to_not eq(nil) - result = @processor.process(data) - - expect(result[:exception][:values][0][:stacktrace]).to eq(nil) - expect(result[:exception][:values][1][:stacktrace]).to eq(nil) - expect(result[:exception][:values][2][:stacktrace]).to eq(nil) - end - end - - if defined?(Rails) # depends on activesupport - it 'should remove stacktraces even when keys are strings' do - data = Raven.capture_exception(build_exception).to_hash.deep_stringify_keys - - expect(data["exception"]["values"][0]["stacktrace"]).to_not eq(nil) - result = @processor.process(data) - - expect(result["exception"]["values"][0]["stacktrace"]).to eq(nil) - end - end -end diff --git a/sentry-raven/spec/raven/processors/sanitizedata_processor_spec.rb b/sentry-raven/spec/raven/processors/sanitizedata_processor_spec.rb deleted file mode 100644 index 8097f9e4f..000000000 --- a/sentry-raven/spec/raven/processors/sanitizedata_processor_spec.rb +++ /dev/null @@ -1,298 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Processor::SanitizeData do - before do - config = Struct.new(:sanitize_fields, :sanitize_credit_cards, :sanitize_fields_excluded).new([], true, []) - client = Struct.new(:configuration).new(config) - @processor = Raven::Processor::SanitizeData.new(client) - end - - context 'configuration for sanitize fields' do - it 'should union default sanitize fields with user-defined sanitize fields' do - fields = Raven::Processor::SanitizeData::DEFAULT_FIELDS | %w(test monkeybutt) - - @processor.sanitize_fields = fields - expected_sensitive_fields = /authorization|password|passwd|secret|ssn|social(.*)?sec|\btest\b|\bmonkeybutt\b/i - - expect(@processor.send(:sensitive_fields)).to eq(expected_sensitive_fields) - end - - it 'should remove default fields if specified by sanitize_fields_excluded' do - @processor.sanitize_fields_excluded = %w(authorization) - - expected_sensitive_fields = /password|passwd|secret|ssn|social(.*)?sec/i - - expect(@processor.send(:sensitive_fields)).to eq(expected_sensitive_fields) - end - - it 'accepts regex-like strings' do - @processor.sanitize_fields = ["foo(.*)?bar"] - - expected_sensitive_fields = /authorization|password|passwd|secret|ssn|social(.*)?sec|foo(.*)?bar/i - - expect(@processor.send(:sensitive_fields)).to eq(expected_sensitive_fields) - end - end - - it 'should filter http data' do - @processor.sanitize_fields = ['user_field'] - - data = { - 'sentry.interfaces.Http' => { - 'data' => { - 'foo' => 'bar', - 'password' => 'hello', - 'the_secret' => 'hello', - 'a_password_here' => 'hello', - 'mypasswd' => 'hello', - 'test' => 1, - :ssn => '123-45-6789', # test symbol handling - 'social_security_number' => 123456789, - 'user_field' => 'user', - 'user_field_foo' => 'hello', - 'query_string' => 'foo=bar%E9' # test utf8 handling - } - } - } - - result = @processor.process(data) - - vars = result["sentry.interfaces.Http"]["data"] - expect(vars["foo"]).to eq("bar") - expect(vars["password"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["the_secret"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["a_password_here"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["mypasswd"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["test"]).to eq(1) - expect(vars[:ssn]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["social_security_number"]).to eq(Raven::Processor::SanitizeData::INT_MASK) - expect(vars["user_field"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["user_field_foo"]).to eq('hello') - expect(vars["query_string"]).to match('foo=bar') - end - - it "filters out hash paird under sensitive keys" do - data = { - 'sentry.interfaces.Http' => { - 'data' => { - 'foo' => 'bar', - :password => { - 'new' => 'test' - }, - "passwd" => { - 'new' => 'test' - } - } - } - } - - result = @processor.process(data) - vars = result["sentry.interfaces.Http"]["data"] - expect(vars[:password]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["passwd"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - end - - it 'should filter json data' do - @processor.sanitize_fields = ['user_field'] - - data_with_json = { - 'json' => { - 'foo' => 'bar', - 'password' => 'hello', - 'the_secret' => 'hello', - 'a_password_here' => 'hello', - 'mypasswd' => 'hello', - 'test' => 1, - 'ssn' => '123-45-6789', - 'social_security_number' => 123456789, - 'user_field' => 'user', - 'user_field_foo' => 'hello' - }.to_json - } - - result = JSON.parse(@processor.process(data_with_json)['json']) - - vars = result - expect(vars["foo"]).to eq("bar") - expect(vars["password"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["the_secret"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["a_password_here"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["mypasswd"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["test"]).to eq(1) - expect(vars["ssn"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["social_security_number"]).to eq(Raven::Processor::SanitizeData::INT_MASK) - expect(vars["user_field"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(vars["user_field_foo"]).to eq('hello') - end - - it 'should filter json embedded in a ruby object' do - data_with_embedded_json = { - 'data' => { - 'json' => %w(foo bar).to_json, - 'json_hash' => { 'foo' => 'bar' }.to_json, - 'sensitive' => { 'password' => 'secret' }.to_json - } - } - - result = @processor.process(data_with_embedded_json) - - expect(JSON.parse(result["data"]["json"])).to eq(%w(foo bar)) - expect(JSON.parse(result["data"]["json_hash"])).to eq('foo' => 'bar') - expect(JSON.parse(result["data"]["sensitive"])).to eq('password' => Raven::Processor::SanitizeData::STRING_MASK) - end - - it 'should not fail when json is invalid' do - data_with_invalid_json = { - 'data' => { - 'invalid' => "{\r\n\"key\":\"value\",\r\n \"foo\":{\"bar\":\"baz\"}\r\n" - } - } - - result = @processor.process(data_with_invalid_json) - - expect { JSON.parse(result["data"]["invalid"]) }.to raise_exception(JSON::ParserError) - end - - it 'should filter credit card values' do - data = { - 'ccnumba' => '4242424242424242', - 'ccnumba_int' => 4242424242424242 - } - - result = @processor.process(data) - expect(result["ccnumba"]).to eq(Raven::Processor::SanitizeData::STRING_MASK) - expect(result["ccnumba_int"]).to eq(Raven::Processor::SanitizeData::INT_MASK) - end - - it 'should pass through credit card values if configured' do - @processor.sanitize_credit_cards = false - data = { - 'ccnumba' => '4242424242424242', - 'ccnumba_int' => 4242424242424242 - } - - result = @processor.process(data) - expect(result["ccnumba"]).to eq('4242424242424242') - expect(result["ccnumba_int"]).to eq(4242424242424242) - end - - it 'sanitizes hashes nested in arrays' do - data = { - "empty_array" => [], - "array" => [{ 'password' => 'secret' }] - } - - result = @processor.process(data) - - expect(result["array"][0]['password']).to eq(Raven::Processor::SanitizeData::STRING_MASK) - end - - context "unparseable plain text" do - it "still sanitizes sensitive fields in string data" do - text = <<~ERR - unexpected token at '{ - "role": "admin","password": "Abc@123","foo": "bar" - }' - ERR - result = @processor.process(text) - - expect(result).to eq( - <<~ERR - unexpected token at '{ - "role": "admin","password": #{Raven::Processor::SanitizeData::STRING_MASK},"foo": "bar" - }' - ERR - ) - end - it "sanitizes different types of key/value format" do - texts = [ - "\"password\" => 'Abc@123'", - "\"password\" =>\"Abc@123\"", - "\"password\"=> \"Abc@123\"", - "'password'=> \"Abc@123\"", - "password: \"Abc@123\"", - "password: 'Abc@123'", - "password:'Abc@123'" - ] - - texts.each do |text| - result = @processor.process(text) - expect(result).not_to match(/Abc@123/) - end - end - end - - context "query strings" do - it 'sanitizes' do - data = { - 'sentry.interfaces.Http' => { - 'data' => { - 'query_string' => 'foo=bar&password=secret' - } - } - } - - result = @processor.process(data) - - vars = result["sentry.interfaces.Http"]["data"] - expect(vars["query_string"]).to_not include("secret") - end - - it 'handles :query_string as symbol' do - data = { - 'sentry.interfaces.Http' => { - 'data' => { - :query_string => 'foo=bar&password=secret' - } - } - } - - result = @processor.process(data) - - vars = result["sentry.interfaces.Http"]["data"] - expect(vars[:query_string]).to_not include("secret") - end - - it 'handles multiple values for a key' do - data = { - 'sentry.interfaces.Http' => { - 'data' => { - 'query_string' => 'foo=bar&foo=fubar&foo=barfoo' - } - } - } - - result = @processor.process(data) - - vars = result["sentry.interfaces.Http"]["data"] - query_string = vars["query_string"].split('&') - expect(query_string).to include("foo=bar") - expect(query_string).to include("foo=fubar") - expect(query_string).to include("foo=barfoo") - end - - it 'handles url encoded keys and values' do - encoded_query_string = 'Bio+4%24=cA%24%7C-%7C+M%28%29n3%5E' - data = { - 'sentry.interfaces.Http' => { - 'data' => { - 'query_string' => encoded_query_string - } - } - } - - result = @processor.process(data) - - vars = result["sentry.interfaces.Http"]["data"] - expect(vars["query_string"]).to eq(encoded_query_string) - end - - # Sometimes this sort of thing can show up in request headers, e.g. - # X-REQUEST-START on Heroku - it 'does not censor milliseconds since the epoch' do - result = @processor.process(:millis_since_epoch => 1507671610403.to_s) - - expect(result).to eq(:millis_since_epoch => 1507671610403.to_s) - end - end -end diff --git a/sentry-raven/spec/raven/processors/utf8conversion_spec.rb b/sentry-raven/spec/raven/processors/utf8conversion_spec.rb deleted file mode 100644 index 0737b26b3..000000000 --- a/sentry-raven/spec/raven/processors/utf8conversion_spec.rb +++ /dev/null @@ -1,79 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Processor::UTF8Conversion do - before do - @client = double("client") - @processor = Raven::Processor::UTF8Conversion.new(@client) - @bad_utf8_string = "invalid utf8 string goes here\255".dup.force_encoding('UTF-8') - end - - it "has a utf8 fixture which is not valid utf-8" do - expect(@bad_utf8_string.valid_encoding?).to eq(false) - expect { @bad_utf8_string.match("") }.to raise_error(ArgumentError) - end - - it 'should cleanup invalid UTF-8 bytes' do - data = {} - data['invalid'] = @bad_utf8_string - - results = @processor.process(data) - expect(results['invalid']).to eq("invalid utf8 string goes here") - end - - it "should cleanup invalid UTF-8 bytes in Exception messages" do - data = Exception.new(@bad_utf8_string) - - results = @processor.process(data) - expect(results.message).to eq("invalid utf8 string goes here") - end - - it 'should keep valid UTF-8 bytes after cleaning' do - data = {} - data['invalid'] = "한국, 中國, 日本(にっぽん)\255".dup.force_encoding('UTF-8') - - results = @processor.process(data) - expect(results['invalid']).to eq("한국, 中國, 日本(にっぽん)") - end - - it 'should work recursively on hashes' do - data = { 'nested' => {} } - data['nested']['invalid'] = @bad_utf8_string - - results = @processor.process(data) - expect(results['nested']['invalid']).to eq("invalid utf8 string goes here") - end - - it 'should work recursively on arrays' do - data = ['good string', 'good string', - ['good string', @bad_utf8_string]] - - results = @processor.process(data) - expect(results[2][1]).to eq("invalid utf8 string goes here") - end - - it 'should not blow up on symbols' do - data = { :key => :value } - - results = @processor.process(data) - expect(results[:key]).to eq(:value) - end - - it "deals with unicode hidden in ASCII_8BIT" do - data = ["\xE2\x9C\x89 Hello".dup.force_encoding(Encoding::ASCII_8BIT)] - - results = @processor.process(data) - - # Calling JSON.generate here to simulate this value eventually being fed - # to JSON generator in the client for transport, we're looking to see - # if encoding errors are raised - expect(JSON.generate(results)).to eq("[\"✉ Hello\"]") - end - - it "deals with unicode hidden in ASCII_8BIT when the string is frozen" do - data = ["\xE2\x9C\x89 Hello".dup.force_encoding(Encoding::ASCII_8BIT).freeze] - - results = @processor.process(data) - - expect(JSON.generate(results)).to eq("[\"✉ Hello\"]") - end -end diff --git a/sentry-raven/spec/raven/raven_spec.rb b/sentry-raven/spec/raven/raven_spec.rb deleted file mode 100644 index df2db4ca2..000000000 --- a/sentry-raven/spec/raven/raven_spec.rb +++ /dev/null @@ -1,120 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven do - let(:event) { Raven::Event.new(:id => "event_id") } - let(:options) { double("options") } - - before do - allow(Raven.instance).to receive(:send_event) - allow(Raven::Event).to receive(:from_message) { event } - allow(Raven::Event).to receive(:from_exception) { event } - end - - describe '.capture' do - context 'not given a block' do - let(:options) { { :key => 'value' } } - - def capture_in_separate_process - pipe_in, pipe_out = IO.pipe - - fork do - pipe_in.close - described_class.capture(options) - - allow(Raven.instance).to receive(:capture_type) do |exception, _options| - pipe_out.puts exception.message - end - - # silence process - $stderr.reopen('/dev/null', 'w') - $stdout.reopen('/dev/null', 'w') - - yield - exit - end - - pipe_out.close - captured_messages = pipe_in.read - pipe_in.close - # sometimes the at_exit hook was registered multiple times - captured_messages.split("\n").last - end - - it 'does not yield' do - # As there is no yield matcher that does not require a probe (e.g. this - # is not valid: expect { |b| described_class.capture }.to_not yield_control), - # expect that a LocalJumpError, which is raised when yielding when no - # block is defined, is not raised. - described_class.capture - end - - it 'installs an at exit hook that will capture exceptions' do - skip('fork not supported in jruby') if RUBY_PLATFORM == 'java' - captured_message = capture_in_separate_process { raise 'test error' } - expect(captured_message).to eq('test error') - end - end - end - - describe '.inject_only' do - before do - allow(Gem.loaded_specs).to receive(:keys).and_return(%w(railties rack sidekiq)) - end - - it 'loads integrations when they are valid configurations' do - expect(Raven).to receive(:load_integration).once.with('railties') - expect(Raven).to receive(:load_integration).once.with('sidekiq') - - Raven.inject_only(:railties, :sidekiq) - end - - it 'skips any integrations that are not supported' do - expect(Raven).to receive(:load_integration).once.with('railties') - expect(Raven.logger).to receive(:warn).with('Integrations do not exist: doesnot, exist') - - Raven.inject_only(:railties, :doesnot, :exist) - end - - it 'skips any integrations that are not loaded in the gemspec' do - expect(Raven).to receive(:load_integration).once.with('railties') - - Raven.inject_only(:railties, :delayed_job) - end - end - - describe '.inject_without' do - before do - allow(Gem.loaded_specs).to receive(:keys).and_return(Raven::AVAILABLE_INTEGRATIONS) - end - - it 'injects all integrations except those passed as an argument' do - expect(Raven).to receive(:load_integration).once.with('rake') - - Raven.inject_without(:delayed_job, :logger, :railties, :sidekiq, :rack, :"rack-timeout") - end - end - - describe "#sys_command" do - it "should execute system commands" do - expect(Raven.sys_command("echo 'Sentry'")).to eq("Sentry") - end - - it "should return nil if a system command doesn't exist" do - expect(Raven.sys_command("asdasdasdsa")).to eq(nil) - end - - it "should return nil if the process exits with a non-zero exit status" do - expect(Raven.sys_command("uname -c")).to eq(nil) # non-existent uname option - end - - it "should not output to stdout on failure" do - expect { Raven.sys_command("asdasdasdsa") }.to_not output.to_stdout - expect { Raven.sys_command("uname -c") }.to_not output.to_stdout - end - - it "should tolerate a missing $CHILD_STATUS" do - Signal.trap('CLD', 'DEFAULT') - expect(Raven.sys_command("echo 'Sentry'")).to eq("Sentry") - end - end -end diff --git a/sentry-raven/spec/raven/transports/http_spec.rb b/sentry-raven/spec/raven/transports/http_spec.rb deleted file mode 100644 index 0cd9422e6..000000000 --- a/sentry-raven/spec/raven/transports/http_spec.rb +++ /dev/null @@ -1,74 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Transports::HTTP do - let(:config) { Raven::Configuration.new.tap { |c| c.dsn = 'http://12345@sentry.localdomain/sentry/42' } } - let(:client) { Raven::Client.new(config) } - - it 'should set a custom User-Agent' do - expect(client.send(:transport).conn.headers[:user_agent]).to eq("sentry-ruby/#{Raven::VERSION}") - end - - context "when event is not allowed (by sampling)" do - let(:event) do - JSON.generate(Raven.capture_message("test").to_hash) - end - - before do - config.sample_rate = 0.5 - allow(Random::DEFAULT).to receive(:rand).and_return(0.6) - end - - it "logs correct message" do - expect(config.logger).to receive(:debug).with("Raven HTTP Transport connecting to http://sentry.localdomain/sentry") - expect(config.logger).to receive(:debug).with("Event not sent: Excluded by random sample") - client.transport.send_event("test_auth", event) - end - end - - it 'should raise an error on 4xx responses' do - stubs = Faraday::Adapter::Test::Stubs.new do |stub| - stub.post('sentry/api/42/store/') { [404, {}, 'not found'] } - end - client.configuration.http_adapter = [:test, stubs] - - event = JSON.generate(Raven.capture_message("test").to_hash) - expect { client.send(:transport).send_event("test", event) }.to raise_error(Raven::Error, /the server responded with status 404/) - - stubs.verify_stubbed_calls - end - - it 'should raise an error on 5xx responses' do - stubs = Faraday::Adapter::Test::Stubs.new do |stub| - stub.post('sentry/api/42/store/') { [500, {}, 'error'] } - end - client.configuration.http_adapter = [:test, stubs] - - event = JSON.generate(Raven.capture_message("test").to_hash) - expect { client.send(:transport).send_event("test", event) }.to raise_error(Raven::Error, /the server responded with status 500/) - - stubs.verify_stubbed_calls - end - - it 'should add header info message to the error' do - stubs = Faraday::Adapter::Test::Stubs.new do |stub| - stub.post('sentry/api/42/store/') { [400, { 'x-sentry-error' => 'error_in_header' }, 'error'] } - end - client.configuration.http_adapter = [:test, stubs] - - event = JSON.generate(Raven.capture_message("test").to_hash) - expect { client.send(:transport).send_event("test", event) }.to raise_error(Raven::Error, /error_in_header/) - - stubs.verify_stubbed_calls - end - - it 'allows to customise faraday' do - builder = spy('faraday_builder') - expect(Faraday).to receive(:new).and_yield(builder) - - client.configuration.faraday_builder = proc { |b| b.request :instrumentation } - - client.send(:transport) - - expect(builder).to have_received(:request).with(:instrumentation) - end -end diff --git a/sentry-raven/spec/raven/transports/stdout_spec.rb b/sentry-raven/spec/raven/transports/stdout_spec.rb deleted file mode 100644 index 9430fd313..000000000 --- a/sentry-raven/spec/raven/transports/stdout_spec.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Transports::Stdout do - let(:config) { Raven::Configuration.new.tap { |c| c.dsn = 'stdout://12345:67890@sentry.localdomain/sentry/42' } } - let(:client) { Raven::Client.new(config) } - - it 'should write to stdout' do - event = JSON.generate(Raven.capture_message("this is an STDOUT transport test").to_hash) - expect { client.send(:transport).send_event("stdout test", event) }.to output(/\"message\":\"this is an STDOUT transport test\"/).to_stdout - end -end diff --git a/sentry-raven/spec/raven/utils/context_filter_spec.rb b/sentry-raven/spec/raven/utils/context_filter_spec.rb deleted file mode 100644 index d03e163ca..000000000 --- a/sentry-raven/spec/raven/utils/context_filter_spec.rb +++ /dev/null @@ -1,41 +0,0 @@ -require "spec_helper" - -require "raven/utils/context_filter" - -RSpec.describe Raven::Utils::ContextFilter do - context "filters out ActiveJob keys from context" do - let(:context) do - { :_aj_globalid => "gid://app/model/id", :key => "value" } - end - let(:expected_context) do - { "globalid" => "gid://app/model/id", :key => "value" } - end - - it "removes reserved keys" do - new_context = described_class.filter_context(context) - - expect(new_context).to eq(expected_context) - end - end - - context "filters out ActiveJob keys from nested context" do - let(:context) do - { - :_aj_globalid => "gid://app/model/id", - :arguments => { :key => "value", :_aj_symbol_keys => ["key"] } - } - end - let(:expected_context) do - { - "globalid" => "gid://app/model/id", - :arguments => { :key => "value", "symbol_keys" => ["key"] } - } - end - - it "removes reserved keys" do - new_context = described_class.filter_context(context) - - expect(new_context).to eq(expected_context) - end - end -end diff --git a/sentry-raven/spec/raven/utils/exception_cause_chain_spec.rb b/sentry-raven/spec/raven/utils/exception_cause_chain_spec.rb deleted file mode 100644 index 823c7981f..000000000 --- a/sentry-raven/spec/raven/utils/exception_cause_chain_spec.rb +++ /dev/null @@ -1,42 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Utils::ExceptionCauseChain do - describe '.exception_to_array' do - # Only check causes when they're supported - if Exception.new.respond_to? :cause - context 'when the ruby version supports exception causes' do - context 'when the exception has a cause' do - let(:exception) { build_exception_with_cause } - - it 'captures the cause' do - expect(described_class.exception_to_array(exception).length).to eq(2) - end - end - - context 'when the exception has nested causes' do - let(:exception) { build_exception_with_two_causes } - - it 'captures nested causes' do - expect(described_class.exception_to_array(exception).length).to eq(3) - end - end - - context 'when the exception has a recursive cause' do - let(:exception) { build_exception_with_recursive_cause } - - it 'should handle it gracefully' do - expect(described_class.exception_to_array(exception).length).to eq(1) - end - end - end - else - context 'when the ruby version does not support exception causes' do - let(:exception) { build_exception_with_two_causes } - - it 'returns the passed in exception' do - expect(described_class.exception_to_array(exception)).to eq [exception] - end - end - end - end -end diff --git a/sentry-raven/spec/raven/utils/real_ip_spec.rb b/sentry-raven/spec/raven/utils/real_ip_spec.rb deleted file mode 100644 index 5c821874c..000000000 --- a/sentry-raven/spec/raven/utils/real_ip_spec.rb +++ /dev/null @@ -1,78 +0,0 @@ -require 'spec_helper' - -RSpec.describe Raven::Utils::RealIp do - context "when no ip addresses are provided other than REMOTE_ADDR" do - subject { Raven::Utils::RealIp.new(:remote_addr => "1.1.1.1") } - - it "should return the remote_addr" do - expect(subject.calculate_ip).to eq("1.1.1.1") - end - end - - context "when a list of x-forwarded-for ips is provided" do - subject do - Raven::Utils::RealIp.new( - :forwarded_for => "192.168.0.2, 2.2.2.2, 3.3.3.3, 4.4.4.4", - :remote_addr => "192.168.0.1" - ) - end - - it "should return the oldest ancestor that is not a local IP" do - expect(subject.calculate_ip).to eq("2.2.2.2") - end - end - - context "when client/real ips are provided" do - subject do - Raven::Utils::RealIp.new( - :forwarded_for => "2.2.2.2", - :real_ip => "4.4.4.4", - :client_ip => "3.3.3.3", - :remote_addr => "192.168.0.1" - ) - end - - it "should return the oldest ancestor, preferring client/real ips first" do - expect(subject.calculate_ip).to eq("3.3.3.3") - end - end - - context "all provided ip addresses are actually local addresses" do - subject do - Raven::Utils::RealIp.new( - :forwarded_for => "127.0.0.1, ::1, 10.0.0.0", - :remote_addr => "192.168.0.1" - ) - end - - it "should return REMOTE_ADDR" do - expect(subject.calculate_ip).to eq("192.168.0.1") - end - end - - context "when an invalid IP is provided" do - subject do - Raven::Utils::RealIp.new( - :forwarded_for => "4.4.4.4.4, 2.2.2.2", - :remote_addr => "192.168.0.1" - ) - end - - it "return the eldest valid IP" do - expect(subject.calculate_ip).to eq("2.2.2.2") - end - end - - context "with IPv6 ips" do - subject do - Raven::Utils::RealIp.new( - :forwarded_for => "2001:db8:a0b:12f0::1", - :remote_addr => "192.168.0.1" - ) - end - - it "return the eldest valid IP" do - expect(subject.calculate_ip).to eq("2001:db8:a0b:12f0::1") - end - end -end diff --git a/sentry-raven/spec/raven/utils/request_id_spec.rb b/sentry-raven/spec/raven/utils/request_id_spec.rb deleted file mode 100644 index 176a293b7..000000000 --- a/sentry-raven/spec/raven/utils/request_id_spec.rb +++ /dev/null @@ -1,25 +0,0 @@ -require "spec_helper" - -RSpec.describe Raven::Utils::RequestId do - describe ".read_from" do - subject { Raven::Utils::RequestId.read_from(env_hash) } - - context "when HTTP_X_REQUEST_ID is available" do - let(:env_hash) { { "HTTP_X_REQUEST_ID" => "request-id-sorta" } } - - it { is_expected.to eq("request-id-sorta") } - end - - context "when action_dispatch.request_id is available (from Rails middleware)" do - let(:env_hash) { { "action_dispatch.request_id" => "request-id-kinda" } } - - it { is_expected.to eq("request-id-kinda") } - end - - context "when no request-id is available" do - let(:env_hash) { { "foo" => "bar" } } - - it { is_expected.to be_nil } - end - end -end diff --git a/sentry-raven/spec/spec_helper.rb b/sentry-raven/spec/spec_helper.rb deleted file mode 100644 index e8300d9d2..000000000 --- a/sentry-raven/spec/spec_helper.rb +++ /dev/null @@ -1,90 +0,0 @@ -require 'pry' - -require 'simplecov' -SimpleCov.start do - project_name "sentry-raven" - root File.join(__FILE__, "../../../") - coverage_dir File.join(__FILE__, "../../coverage") -end - -if ENV["CI"] && ENV["CODECOV"] == "1" - require 'codecov' - SimpleCov.formatter = SimpleCov::Formatter::Codecov -end - -require 'sentry_raven_without_integrations' - -Raven.configure do |config| - config.dsn = "dummy://12345:67890@sentry.localdomain/sentry/42" - config.encoding = "json" - config.silence_ready = true - config.logger = Logger.new(nil) -end - -if ENV["RAILS_VERSION"] && (ENV["RAILS_VERSION"].to_i == 0) - RSpec.configure do |config| - config.filter_run_excluding :rails => true - end -else - require File.dirname(__FILE__) + "/support/test_rails_app/app.rb" - require "rspec/rails" -end - -RSpec.configure do |config| - config.mock_with(:rspec) { |mocks| mocks.verify_partial_doubles = true } - config.raise_errors_for_deprecations! - config.disable_monkey_patching! - Kernel.srand config.seed -end - -RSpec.shared_examples "Raven default capture behavior" do - it "captures exceptions" do - expect { block }.to raise_error(captured_class) - - expect(Raven.client.transport.events.size).to eq(1) - - event = JSON.parse!(Raven.client.transport.events.first[1]) - expect(event["exception"]["values"][0]["type"]).to eq(captured_class.name) - expect(event["exception"]["values"][0]["value"]).to eq(captured_message) - end -end - -def build_exception - 1 / 0 -rescue ZeroDivisionError => e - e -end - -def build_exception_with_cause(cause = "exception a") - begin - raise cause - rescue - raise "exception b" - end -rescue RuntimeError => e - e -end - -def build_exception_with_two_causes - begin - begin - raise "exception a" - rescue - raise "exception b" - end - rescue - raise "exception c" - end -rescue RuntimeError => e - e -end - -def build_exception_with_recursive_cause - backtrace = [] - - exception = double("Exception") - allow(exception).to receive(:cause).and_return(exception) - allow(exception).to receive(:message).and_return("example") - allow(exception).to receive(:backtrace).and_return(backtrace) - exception -end diff --git a/sentry-raven/spec/support/Rakefile b/sentry-raven/spec/support/Rakefile deleted file mode 100644 index 287bbea68..000000000 --- a/sentry-raven/spec/support/Rakefile +++ /dev/null @@ -1,12 +0,0 @@ -require 'rake' -require 'rubygems' -require 'raven' -require 'raven/transports/dummy' - -Raven.configure do |config| - config.dsn = 'dummy://12345:67890@sentry.localdomain/sentry/42' -end - -task :raise_exception do - 1 / 0 -end diff --git a/sentry-raven/spec/support/linecache.txt b/sentry-raven/spec/support/linecache.txt deleted file mode 100644 index bfd64c32c..000000000 --- a/sentry-raven/spec/support/linecache.txt +++ /dev/null @@ -1,6 +0,0 @@ -foo -bar -baz -qux -lorem -ipsum diff --git a/sentry-raven/spec/support/test_rails_app/app.rb b/sentry-raven/spec/support/test_rails_app/app.rb deleted file mode 100644 index 9559061b9..000000000 --- a/sentry-raven/spec/support/test_rails_app/app.rb +++ /dev/null @@ -1,59 +0,0 @@ -require 'rails' -# require "active_record/railtie" -require "action_view/railtie" -require "action_controller/railtie" -# require "action_mailer/railtie" -require "active_job/railtie" -# require "action_cable/engine" -# require "sprockets/railtie" -# require "rails/test_unit/railtie" -require 'raven/integrations/rails' - -ActiveSupport::Deprecation.silenced = true - -class TestApp < Rails::Application -end - -class HelloController < ActionController::Base - def exception - raise "An unhandled exception!" - end - - def view_exception - render inline: "<%= foo %>" - end - - def world - render :plain => "Hello World!" - end -end - -def make_basic_app - app = Class.new(TestApp) do - def self.name - "RailsTestApp" - end - end - - app.config.hosts = nil - app.config.secret_key_base = "test" - - # Usually set for us in production.rb - app.config.eager_load = true - app.routes.append do - get "/exception", :to => "hello#exception" - get "/view_exception", :to => "hello#view_exception" - root :to => "hello#world" - end - - app.initializer :configure_release do - Raven.configure do |config| - config.release = 'beta' - end - end - - app.initialize! - - Rails.application = app - app -end diff --git a/sentry-resque/spec/sentry/resque_spec.rb b/sentry-resque/spec/sentry/resque_spec.rb index 993bd87fe..63b4dd354 100644 --- a/sentry-resque/spec/sentry/resque_spec.rb +++ b/sentry-resque/spec/sentry/resque_spec.rb @@ -66,7 +66,7 @@ def self.perform(msg) process_job(worker) expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:message]).to eq("report") expect(event[:tags]).to eq({ "resque.queue" => "default" }) expect(event[:contexts][:"Resque"]).to include({ job_class: "MessageJob", arguments: ["report"], queue: "default" }) @@ -88,7 +88,7 @@ def self.perform(msg) process_job(worker) expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:message]).to eq("tagged report") expect(event[:tags]).to include({ number: 1 }) @@ -97,7 +97,7 @@ def self.perform(msg) process_job(worker) expect(transport.events.count).to eq(2) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:tags]).to eq({ "resque.queue" => "default" }) end @@ -109,7 +109,7 @@ def self.perform(msg) end.to change { Resque::Stat.get("failed") }.by(1) expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:sdk]).to eq({ name: "sentry.ruby.resque", version: described_class::VERSION }) expect(event.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") @@ -123,7 +123,7 @@ def self.perform(msg) end.to change { Resque::Stat.get("failed") }.by(1) expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:tags]).to eq({ "resque.queue" => "default", number: 1 }) expect(Sentry.get_current_scope.extra).to eq({}) @@ -135,7 +135,7 @@ def self.perform(msg) end.to change { Resque::Stat.get("failed") }.by(1) expect(transport.events.count).to eq(2) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:tags]).to eq({ "resque.queue" => "default" }) expect(Sentry.get_current_scope.extra).to eq({}) expect(Sentry.get_current_scope.tags).to eq({}) @@ -161,7 +161,7 @@ def self.perform(msg) end end.to change { transport.events.count }.by(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:sdk]).to eq({ name: "sentry.ruby.resque", version: described_class::VERSION }) expect(event.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") @@ -175,7 +175,7 @@ def self.perform(msg) end.to change { Resque::Stat.get("failed") }.by(1) .and change { transport.events.count }.by(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:sdk]).to eq({ name: "sentry.ruby.resque", version: described_class::VERSION }) expect(event.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") @@ -201,7 +201,7 @@ def self.perform(msg) end end.to change { transport.events.count }.by(3) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:sdk]).to eq({ name: "sentry.ruby.resque", version: described_class::VERSION }) expect(event.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") @@ -222,7 +222,7 @@ def self.perform(msg) process_job(worker) end.not_to raise_error(TypeError) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") end end @@ -284,7 +284,7 @@ def perform it "injects ActiveJob information to the event" do expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:message]).to eq("report from ActiveJob") expect(event[:tags]).to match({ "resque.queue" => "default", number: 1 }) expect(event[:contexts][:"Active-Job"][:job_class]).to eq("AJMessageJob") @@ -309,7 +309,7 @@ def perform it "injects ActiveJob information to the event" do expect(transport.events.count).to eq(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") expect(event[:tags]).to match({ "resque.queue" => "default", number: 2 }) expect(event[:contexts][:"Active-Job"][:job_class]).to eq("AJFailedJob") diff --git a/sentry-resque/spec/sentry/tracing_spec.rb b/sentry-resque/spec/sentry/tracing_spec.rb index bf81f9006..827d4ab20 100644 --- a/sentry-resque/spec/sentry/tracing_spec.rb +++ b/sentry-resque/spec/sentry/tracing_spec.rb @@ -35,10 +35,10 @@ def self.perform(msg) worker.work(0) expect(transport.events.count).to eq(2) - event = transport.events.first.to_hash + event = transport.events.first.to_h expect(event[:message]).to eq("report") - tracing_event = transport.events.last.to_hash + tracing_event = transport.events.last.to_h expect(tracing_event[:transaction]).to eq("MessageJob") expect(tracing_event[:transaction_info]).to eq({ source: :task }) expect(tracing_event[:type]).to eq("transaction") @@ -53,10 +53,10 @@ def self.perform(msg) worker.work(0) expect(transport.events.count).to eq(2) - event = transport.events.first.to_hash + event = transport.events.first.to_h expect(event.dig(:exception, :values, 0, :type)).to eq("ZeroDivisionError") - tracing_event = transport.events.last.to_hash + tracing_event = transport.events.last.to_h expect(tracing_event[:transaction]).to eq("FailedJob") expect(tracing_event[:transaction_info]).to eq({ source: :task }) expect(tracing_event[:type]).to eq("transaction") @@ -78,7 +78,7 @@ def self.perform(msg) worker.work(0) expect(transport.events.count).to eq(1) - event = transport.events.first.to_hash + event = transport.events.first.to_h expect(event[:message]).to eq("report") end end diff --git a/sentry-ruby/benchmarks/allocation_comparison.rb b/sentry-ruby/benchmarks/allocation_comparison.rb index c765b2ff6..9a3b87bd9 100644 --- a/sentry-ruby/benchmarks/allocation_comparison.rb +++ b/sentry-ruby/benchmarks/allocation_comparison.rb @@ -5,7 +5,7 @@ require "sentry/benchmarks/benchmark_transport" Sentry.init do |config| - config.logger = ::Logger.new(nil) + config.sdk_logger = ::Logger.new(nil) config.dsn = "dummy://12345:67890@sentry.localdomain:3000/sentry/42" config.transport.transport_class = Sentry::BenchmarkTransport config.breadcrumbs_logger = [:sentry_logger] diff --git a/sentry-ruby/benchmarks/allocation_report.rb b/sentry-ruby/benchmarks/allocation_report.rb index 54fbd4139..36d7ece57 100644 --- a/sentry-ruby/benchmarks/allocation_report.rb +++ b/sentry-ruby/benchmarks/allocation_report.rb @@ -5,7 +5,7 @@ require "sentry/benchmarks/benchmark_transport" Sentry.init do |config| - config.logger = ::Logger.new(nil) + config.sdk_logger = ::Logger.new(nil) config.dsn = "dummy://12345:67890@sentry.localdomain:3000/sentry/42" config.transport.transport_class = Sentry::BenchmarkTransport config.breadcrumbs_logger = [:sentry_logger] diff --git a/sentry-ruby/examples/crons/README.md b/sentry-ruby/examples/crons/README.md index 7430bde64..ec2951b36 100644 --- a/sentry-ruby/examples/crons/README.md +++ b/sentry-ruby/examples/crons/README.md @@ -1,7 +1,7 @@ # sentry-ruby Crons example Crons monitoring allows you to track that certain that should be performed -on a certain schedule are indeed performed on time and without errors. See +on a certain schedule are indeed performed on time and without errors. See [documentation](https://docs.sentry.io/platforms/ruby/crons/) for more details. This example project has a few rake tasks that manually send monitor check-ins diff --git a/sentry-ruby/lib/sentry-ruby.rb b/sentry-ruby/lib/sentry-ruby.rb index e2b6094f8..de330d64f 100644 --- a/sentry-ruby/lib/sentry-ruby.rb +++ b/sentry-ruby/lib/sentry-ruby.rb @@ -26,7 +26,6 @@ require "sentry/session_flusher" require "sentry/backpressure_monitor" require "sentry/cron/monitor_check_ins" -require "sentry/metrics" require "sentry/vernier/profiler" [ @@ -59,7 +58,6 @@ module Sentry logger session_flusher backpressure_monitor - metrics_aggregator exception_locals_tp ].freeze @@ -93,10 +91,6 @@ def exception_locals_tp # @return [BackpressureMonitor, nil] attr_reader :backpressure_monitor - # @!attribute [r] metrics_aggregator - # @return [Metrics::Aggregator, nil] - attr_reader :metrics_aggregator - ##### Patch Registration ##### # @!visibility private @@ -252,7 +246,6 @@ def init(&block) @background_worker = Sentry::BackgroundWorker.new(config) @session_flusher = config.session_tracking? ? Sentry::SessionFlusher.new(config, client) : nil @backpressure_monitor = config.enable_backpressure_handling ? Sentry::BackpressureMonitor.new(config, client) : nil - @metrics_aggregator = config.metrics.enabled ? Sentry::Metrics::Aggregator.new(config, client) : nil exception_locals_tp.enable if config.include_local_variables at_exit { close } end @@ -273,12 +266,6 @@ def close @backpressure_monitor = nil end - if @metrics_aggregator - @metrics_aggregator.flush(force: true) - @metrics_aggregator.kill - @metrics_aggregator = nil - end - if client = get_current_client client.flush diff --git a/sentry-ruby/lib/sentry/background_worker.rb b/sentry-ruby/lib/sentry/background_worker.rb index 9841230f4..1c8795006 100644 --- a/sentry-ruby/lib/sentry/background_worker.rb +++ b/sentry-ruby/lib/sentry/background_worker.rb @@ -23,10 +23,7 @@ def initialize(configuration) @shutdown_callback = nil @executor = - if configuration.async - log_debug("config.async is set, BackgroundWorker is disabled") - Concurrent::ImmediateExecutor.new - elsif @number_of_threads == 0 + if @number_of_threads == 0 log_debug("config.background_worker_threads is set to 0, all events will be sent synchronously") Concurrent::ImmediateExecutor.new else diff --git a/sentry-ruby/lib/sentry/breadcrumb.rb b/sentry-ruby/lib/sentry/breadcrumb.rb index 69490f78a..489d0bb16 100644 --- a/sentry-ruby/lib/sentry/breadcrumb.rb +++ b/sentry-ruby/lib/sentry/breadcrumb.rb @@ -34,7 +34,7 @@ def initialize(category: nil, data: nil, message: nil, timestamp: nil, level: ni end # @return [Hash] - def to_hash + def to_h { category: @category, data: serialized_data, diff --git a/sentry-ruby/lib/sentry/breadcrumb_buffer.rb b/sentry-ruby/lib/sentry/breadcrumb_buffer.rb index 7f3a2dc04..3a5cc0177 100644 --- a/sentry-ruby/lib/sentry/breadcrumb_buffer.rb +++ b/sentry-ruby/lib/sentry/breadcrumb_buffer.rb @@ -48,9 +48,9 @@ def empty? end # @return [Hash] - def to_hash + def to_h { - values: members.map(&:to_hash) + values: members.map(&:to_h) } end diff --git a/sentry-ruby/lib/sentry/check_in_event.rb b/sentry-ruby/lib/sentry/check_in_event.rb index 758b2432c..9e2b8df29 100644 --- a/sentry-ruby/lib/sentry/check_in_event.rb +++ b/sentry-ruby/lib/sentry/check_in_event.rb @@ -48,13 +48,13 @@ def initialize( end # @return [Hash] - def to_hash + def to_h data = super data[:check_in_id] = check_in_id data[:monitor_slug] = monitor_slug data[:status] = status data[:duration] = duration if duration - data[:monitor_config] = monitor_config.to_hash if monitor_config + data[:monitor_config] = monitor_config.to_h if monitor_config data end end diff --git a/sentry-ruby/lib/sentry/client.rb b/sentry-ruby/lib/sentry/client.rb index d41056aa5..009f05325 100644 --- a/sentry-ruby/lib/sentry/client.rb +++ b/sentry-ruby/lib/sentry/client.rb @@ -60,8 +60,7 @@ def capture_event(event, scope, hint = {}) return end - event_type = event.is_a?(Event) ? event.type : event["type"] - data_category = Envelope::Item.data_category(event_type) + data_category = Envelope::Item.data_category(event.type) is_transaction = event.is_a?(TransactionEvent) spans_before = is_transaction ? event.spans.size : 0 @@ -78,9 +77,7 @@ def capture_event(event, scope, hint = {}) transport.record_lost_event(:event_processor, "span", num: spans_delta) if spans_delta > 0 end - if async_block = configuration.async - dispatch_async_event(async_block, event, hint) - elsif configuration.background_worker_threads != 0 && hint.fetch(:background, true) + if configuration.background_worker_threads != 0 && hint.fetch(:background, true) unless dispatch_background_event(event, hint) transport.record_lost_event(:queue_overflow, data_category) transport.record_lost_event(:queue_overflow, "span", num: spans_before + 1) if is_transaction @@ -210,22 +207,13 @@ def event_from_transaction(transaction) # @!macro send_event def send_event(event, hint = nil) - event_type = event.is_a?(Event) ? event.type : event["type"] - data_category = Envelope::Item.data_category(event_type) + data_category = Envelope::Item.data_category(event.type) spans_before = event.is_a?(TransactionEvent) ? event.spans.size : 0 - if event_type != TransactionEvent::TYPE && configuration.before_send + if event.is_a?(ErrorEvent) && configuration.before_send event = configuration.before_send.call(event, hint) - case event - when ErrorEvent, CheckInEvent - # do nothing - when Hash - log_debug(<<~MSG) - Returning a Hash from before_send is deprecated and will be removed in the next major version. - Please return a Sentry::ErrorEvent object instead. - MSG - else + if !event.is_a?(ErrorEvent) # Avoid serializing the event object in this case because we aren't sure what it is and what it contains log_debug(<<~MSG) Discarded event because before_send didn't return a Sentry::ErrorEvent object but an instance of #{event.class} @@ -235,21 +223,10 @@ def send_event(event, hint = nil) end end - if event_type == TransactionEvent::TYPE && configuration.before_send_transaction + if event.is_a?(TransactionEvent) && configuration.before_send_transaction event = configuration.before_send_transaction.call(event, hint) - if event.is_a?(TransactionEvent) || event.is_a?(Hash) - spans_after = event.is_a?(TransactionEvent) ? event.spans.size : 0 - spans_delta = spans_before - spans_after - transport.record_lost_event(:before_send, "span", num: spans_delta) if spans_delta > 0 - - if event.is_a?(Hash) - log_debug(<<~MSG) - Returning a Hash from before_send_transaction is deprecated and will be removed in the next major version. - Please return a Sentry::TransactionEvent object instead. - MSG - end - else + if !event.is_a?(TransactionEvent) # Avoid serializing the event object in this case because we aren't sure what it is and what it contains log_debug(<<~MSG) Discarded event because before_send_transaction didn't return a Sentry::TransactionEvent object but an instance of #{event.class} @@ -258,6 +235,23 @@ def send_event(event, hint = nil) transport.record_lost_event(:before_send, "span", num: spans_before + 1) return end + + spans_after = event.is_a?(TransactionEvent) ? event.spans.size : 0 + spans_delta = spans_before - spans_after + transport.record_lost_event(:before_send, "span", num: spans_delta) if spans_delta > 0 + end + + if event.is_a?(CheckInEvent) && configuration.before_send_check_in + event = configuration.before_send_check_in.call(event, hint) + + if !event.is_a?(CheckInEvent) + # Avoid serializing the event object in this case because we aren't sure what it is and what it contains + log_debug(<<~MSG) + Discarded event because before_send_check_in didn't return a Sentry::CheckInEvent object but an instance of #{event.class} + MSG + transport.record_lost_event(:before_send, data_category) + return + end end transport.send_event(event) if configuration.sending_to_dsn_allowed? @@ -291,7 +285,7 @@ def send_logs(log_events) processed_log_event = configuration.before_send_log.call(log_event) if processed_log_event - envelope_items << processed_log_event.to_hash + envelope_items << processed_log_event.to_h else discarded_count += 1 end @@ -299,7 +293,7 @@ def send_logs(log_events) envelope_items else - envelope_items = log_events.map(&:to_hash) + envelope_items = log_events.map(&:to_h) end envelope.add_item( @@ -373,28 +367,5 @@ def dispatch_background_event(event, hint) send_event(event, hint) end end - - def dispatch_async_event(async_block, event, hint) - # We have to convert to a JSON-like hash, because background job - # processors (esp ActiveJob) may not like weird types in the event hash - - event_hash = - begin - event.to_json_compatible - rescue => e - log_error("Converting #{event.type} (#{event.event_id}) to JSON compatible hash failed", e, debug: configuration.debug) - return - end - - if async_block.arity == 2 - hint = JSON.parse(JSON.generate(hint)) - async_block.call(event_hash, hint) - else - async_block.call(event_hash) - end - rescue => e - log_error("Async #{event_hash["type"]} sending failed", e, debug: configuration.debug) - send_event(event, hint) - end end end diff --git a/sentry-ruby/lib/sentry/configuration.rb b/sentry-ruby/lib/sentry/configuration.rb index 325134eab..587e71619 100644 --- a/sentry-ruby/lib/sentry/configuration.rb +++ b/sentry-ruby/lib/sentry/configuration.rb @@ -9,7 +9,6 @@ require "sentry/release_detector" require "sentry/transport/configuration" require "sentry/cron/configuration" -require "sentry/metrics/configuration" require "sentry/linecache" require "sentry/interfaces/stacktrace_builder" require "sentry/logger" @@ -31,13 +30,6 @@ class Configuration # @return [Regexp, nil] attr_accessor :app_dirs_pattern - # Provide an object that responds to `call` to send events asynchronously. - # E.g.: lambda { |event| Thread.new { Sentry.send_event(event) } } - # - # @deprecated It will be removed in the next major release. Please read https://github.com/getsentry/sentry-ruby/issues/1522 for more information - # @return [Proc, nil] - attr_reader :async - # to send events in a non-blocking way, sentry-ruby has its own background worker # by default, the worker holds a thread pool that has [the number of processors] threads # but you can configure it with this configuration option @@ -75,11 +67,10 @@ class Configuration # @return [Proc] attr_reader :before_breadcrumb - # Optional Proc, called before sending an event to the server + # Optional Proc, called before sending an error event to the server # @example # config.before_send = lambda do |event, hint| # # skip ZeroDivisionError exceptions - # # note: hint[:exception] would be a String if you use async callback # if hint[:exception].is_a?(ZeroDivisionError) # nil # else @@ -89,7 +80,7 @@ class Configuration # @return [Proc] attr_reader :before_send - # Optional Proc, called before sending an event to the server + # Optional Proc, called before sending a transaction event to the server # @example # config.before_send_transaction = lambda do |event, hint| # # skip unimportant transactions or strip sensitive data @@ -102,6 +93,18 @@ class Configuration # @return [Proc] attr_reader :before_send_transaction + # Optional Proc, called before sending a check-in event to the server + # @example + # config.before_send_check_in = lambda do |event, hint| + # if event.monitor_slug == "unimportant_job" + # nil + # else + # event + # end + # end + # @return [Proc] + attr_reader :before_send_check_in + # Optional Proc, called before sending an event to the server # @example # config.before_send_log = lambda do |log| @@ -118,7 +121,6 @@ class Configuration # # And if you also use sentry-rails: # - :active_support_logger - # - :monotonic_active_support_logger # # @return [Array] attr_reader :breadcrumbs_logger @@ -145,7 +147,7 @@ class Configuration attr_reader :dsn # Whitelist of enabled_environments that will send notifications to Sentry. Array of Strings. - # @return [Array] + # @return [Array, nil] attr_accessor :enabled_environments # Logger 'progname's to exclude from breadcrumbs @@ -174,18 +176,6 @@ class Configuration # @return [Boolean, String] attr_accessor :spotlight - # @deprecated Use {#include_local_variables} instead. - alias_method :capture_exception_frame_locals, :include_local_variables - - # @deprecated Use {#include_local_variables=} instead. - def capture_exception_frame_locals=(value) - log_warn <<~MSG - `capture_exception_frame_locals` is now deprecated in favor of `include_local_variables`. - MSG - - self.include_local_variables = value - end - # You may provide your own LineCache for matching paths with source files. # This may be useful if you need to get source code from places other than the disk. # @see LineCache @@ -202,18 +192,6 @@ def capture_exception_frame_locals=(value) # @return [String, nil] attr_accessor :sdk_debug_transport_log_file - # @deprecated Use {#sdk_logger=} instead. - def logger=(logger) - warn "[sentry] `config.logger=` is deprecated. Please use `config.sdk_logger=` instead." - self.sdk_logger = logger - end - - # @deprecated Use {#sdk_logger} instead. - def logger - warn "[sentry] `config.logger` is deprecated. Please use `config.sdk_logger` instead." - self.sdk_logger - end - # Project directory root for in_app detection. Could be Rails root, etc. # Set automatically for Rails. # @return [String] @@ -273,10 +251,6 @@ def logger # @return [Cron::Configuration] attr_reader :cron - # Metrics related configuration. - # @return [Metrics::Configuration] - attr_reader :metrics - # Take a float between 0.0 and 1.0 as the sample rate for tracing events (transactions). # @return [Float, nil] attr_reader :traces_sample_rate @@ -299,12 +273,6 @@ def logger # @return [StructuredLoggingConfiguration] attr_reader :structured_logging - # Easier way to use performance tracing - # If set to true, will set traces_sample_rate to 1.0 - # @deprecated It will be removed in the next major release. - # @return [Boolean, nil] - attr_reader :enable_tracing - # Send diagnostic client reports about dropped events, true by default # tries to attach to an existing envelope max once every 30s # @return [Boolean] @@ -325,6 +293,18 @@ def logger # @return [Array] attr_accessor :trace_propagation_targets + # Collection of HTTP status codes or ranges of codes to ignore when tracing incoming requests. + # If a transaction's http.response.status_code matches one of these values, + # the transaction will be dropped and marked as not sampled. + # Defaults to TRACE_IGNORE_STATUS_CODES_DEFAULT. + # + # @example + # # ignore 404 and 502 <= status_code <= 511 + # config.trace_ignore_status_codes = [404, (502..511)] + # + # @return [Array, Array] + attr_reader :trace_ignore_status_codes + # The instrumenter to use, :sentry or :otel # @return [Symbol] attr_reader :instrumenter @@ -376,6 +356,8 @@ def logger SERVER_PORT ].freeze + TRACE_IGNORE_STATUS_CODES_DEFAULT = [(301..303), (305..399), (401..404)] + HEROKU_DYNO_METADATA_MESSAGE = "You are running on Heroku but haven't enabled Dyno Metadata. For Sentry's "\ "release detection to work correctly, please run `heroku labs:enable runtime-dyno-metadata`" @@ -473,7 +455,7 @@ def initialize self.context_lines = 3 self.include_local_variables = false self.environment = environment_from_env - self.enabled_environments = [] + self.enabled_environments = nil self.exclude_loggers = [] self.excluded_exceptions = IGNORE_DEFAULT + PUMA_IGNORE_DEFAULT self.inspect_exception_causes_for_exclusion = true @@ -498,21 +480,21 @@ def initialize self.server_name = server_name_from_env self.instrumenter = :sentry self.trace_propagation_targets = [PROPAGATION_TARGETS_MATCH_ALL] + self.trace_ignore_status_codes = TRACE_IGNORE_STATUS_CODES_DEFAULT self.enabled_patches = DEFAULT_PATCHES.dup self.before_send = nil self.before_send_transaction = nil + self.before_send_check_in = nil self.before_send_log = nil self.rack_env_whitelist = RACK_ENV_WHITELIST_DEFAULT self.traces_sampler = nil - self.enable_tracing = nil self.enable_logs = false self.profiler_class = Sentry::Profiler @transport = Transport::Configuration.new @cron = Cron::Configuration.new - @metrics = Metrics::Configuration.new(self.sdk_logger) @structured_logging = StructuredLoggingConfiguration.new @gem_specs = Hash[Gem::Specification.map { |spec| [spec.name, spec.version.to_s] }] if Gem::Specification.respond_to?(:map) @@ -555,22 +537,6 @@ def release=(value) @release = value end - def async=(value) - check_callable!("async", value) - - log_warn <<~MSG - - sentry-ruby now sends events asynchronously by default with its background worker (supported since 4.1.0). - The `config.async` callback has become redundant while continuing to cause issues. - (The problems of `async` are detailed in https://github.com/getsentry/sentry-ruby/issues/1522) - - Therefore, we encourage you to remove it and let the background worker take care of async job sending. - It's deprecation is planned in the next major release (6.0), which is scheduled around the 3rd quarter of 2022. - MSG - - @async = value - end - def breadcrumbs_logger=(logger) loggers = if logger.is_a?(Array) @@ -596,6 +562,12 @@ def before_send_transaction=(value) @before_send_transaction = value end + def before_send_check_in=(value) + check_callable!("before_send_check_in", value) + + @before_send_check_in = value + end + def before_breadcrumb=(value) check_callable!("before_breadcrumb", value) @@ -610,15 +582,12 @@ def instrumenter=(instrumenter) @instrumenter = INSTRUMENTERS.include?(instrumenter) ? instrumenter : :sentry end - def enable_tracing=(enable_tracing) - unless enable_tracing.nil? - log_warn <<~MSG - `enable_tracing` is now deprecated in favor of `traces_sample_rate = 1.0`. - MSG + def trace_ignore_status_codes=(codes) + unless codes.is_a?(Array) && codes.all? { |code| valid_status_code_entry?(code) } + raise ArgumentError, "trace_ignore_status_codes must be an Array of integers or ranges between (100-599) where begin <= end" end - @enable_tracing = enable_tracing - @traces_sample_rate ||= 1.0 if enable_tracing + @trace_ignore_status_codes = codes end def traces_sample_rate=(traces_sample_rate) @@ -674,7 +643,7 @@ def exception_class_allowed?(exc) end def enabled_in_current_env? - enabled_environments.empty? || enabled_environments.include?(environment) + enabled_environments.nil? || enabled_environments.include?(environment) end def valid_sample_rate?(sample_rate) @@ -685,7 +654,7 @@ def valid_sample_rate?(sample_rate) def tracing_enabled? valid_sampler = !!((valid_sample_rate?(@traces_sample_rate)) || @traces_sampler) - (@enable_tracing != false) && valid_sampler && sending_allowed? + valid_sampler && sending_allowed? end def profiling_enabled? @@ -816,6 +785,23 @@ def processor_count available_processor_count = Concurrent.available_processor_count if Concurrent.respond_to?(:available_processor_count) available_processor_count || Concurrent.processor_count end + + def valid_http_status_code?(code) + code.is_a?(Integer) && code >= 100 && code <= 599 + end + + def valid_status_code_entry?(entry) + case entry + when Integer + valid_http_status_code?(entry) + when Range + valid_http_status_code?(entry.begin) && + valid_http_status_code?(entry.end) && + entry.begin <= entry.end + else + false + end + end end class StructuredLoggingConfiguration diff --git a/sentry-ruby/lib/sentry/cron/monitor_check_ins.rb b/sentry-ruby/lib/sentry/cron/monitor_check_ins.rb index df7445286..314733cfb 100644 --- a/sentry-ruby/lib/sentry/cron/monitor_check_ins.rb +++ b/sentry-ruby/lib/sentry/cron/monitor_check_ins.rb @@ -14,12 +14,12 @@ def perform(*args, **opts) :in_progress, monitor_config: monitor_config) - start = Metrics::Timing.duration_start + start = Process.clock_gettime(Process::CLOCK_MONOTONIC) begin # need to do this on ruby <= 2.6 sadly ret = method(:perform).super_method.arity == 0 ? super() : super - duration = Metrics::Timing.duration_end(start) + duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start Sentry.capture_check_in(slug, :ok, @@ -29,7 +29,7 @@ def perform(*args, **opts) ret rescue Exception - duration = Metrics::Timing.duration_end(start) + duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start Sentry.capture_check_in(slug, :error, diff --git a/sentry-ruby/lib/sentry/cron/monitor_config.rb b/sentry-ruby/lib/sentry/cron/monitor_config.rb index dfd28a4bd..36d7b52e8 100644 --- a/sentry-ruby/lib/sentry/cron/monitor_config.rb +++ b/sentry-ruby/lib/sentry/cron/monitor_config.rb @@ -40,9 +40,9 @@ def self.from_interval(num, unit, **options) new(MonitorSchedule::Interval.new(num, unit), **options) end - def to_hash + def to_h { - schedule: schedule.to_hash, + schedule: schedule.to_h, checkin_margin: checkin_margin, max_runtime: max_runtime, timezone: timezone diff --git a/sentry-ruby/lib/sentry/cron/monitor_schedule.rb b/sentry-ruby/lib/sentry/cron/monitor_schedule.rb index d7c80cdd8..cb5423cab 100644 --- a/sentry-ruby/lib/sentry/cron/monitor_schedule.rb +++ b/sentry-ruby/lib/sentry/cron/monitor_schedule.rb @@ -12,7 +12,7 @@ def initialize(value) @value = value end - def to_hash + def to_h { type: :crontab, value: value } end end @@ -33,7 +33,7 @@ def initialize(value, unit) @unit = unit end - def to_hash + def to_h { type: :interval, value: value, unit: unit } end end diff --git a/sentry-ruby/lib/sentry/envelope/item.rb b/sentry-ruby/lib/sentry/envelope/item.rb index 864ad0239..2fe806493 100644 --- a/sentry-ruby/lib/sentry/envelope/item.rb +++ b/sentry-ruby/lib/sentry/envelope/item.rb @@ -3,7 +3,6 @@ module Sentry # @api private class Envelope::Item - STACKTRACE_FRAME_LIMIT_ON_OVERSIZED_PAYLOAD = 500 MAX_SERIALIZED_PAYLOAD_SIZE = 1024 * 1000 SIZE_LIMITS = Hash.new(MAX_SERIALIZED_PAYLOAD_SIZE).update( @@ -18,7 +17,6 @@ def self.data_category(type) when "session", "attachment", "transaction", "profile", "span", "log" then type when "sessions" then "session" when "check_in" then "monitor" - when "statsd", "metric_meta" then "metric_bucket" when "event" then "error" when "client_report" then "internal" else "default" @@ -45,11 +43,6 @@ def serialize result = to_s end - if result.bytesize > size_limit - reduce_stacktrace! - result = to_s - end - [result, result.bytesize > size_limit] end @@ -68,21 +61,5 @@ def remove_breadcrumbs! payload.delete("breadcrumbs") end end - - def reduce_stacktrace! - if exceptions = payload.dig(:exception, :values) || payload.dig("exception", "values") - exceptions.each do |exception| - # in most cases there is only one exception (2 or 3 when have multiple causes), so we won't loop through this double condition much - traces = exception.dig(:stacktrace, :frames) || exception.dig("stacktrace", "frames") - - if traces && traces.size > STACKTRACE_FRAME_LIMIT_ON_OVERSIZED_PAYLOAD - size_on_both_ends = STACKTRACE_FRAME_LIMIT_ON_OVERSIZED_PAYLOAD / 2 - traces.replace( - traces[0..(size_on_both_ends - 1)] + traces[-size_on_both_ends..-1], - ) - end - end - end - end end end diff --git a/sentry-ruby/lib/sentry/error_event.rb b/sentry-ruby/lib/sentry/error_event.rb index 13a891f71..a76e8b2ab 100644 --- a/sentry-ruby/lib/sentry/error_event.rb +++ b/sentry-ruby/lib/sentry/error_event.rb @@ -10,10 +10,10 @@ class ErrorEvent < Event attr_reader :threads # @return [Hash] - def to_hash + def to_h data = super - data[:threads] = threads.to_hash if threads - data[:exception] = exception.to_hash if exception + data[:threads] = threads.to_h if threads + data[:exception] = exception.to_h if exception data end diff --git a/sentry-ruby/lib/sentry/event.rb b/sentry-ruby/lib/sentry/event.rb index d9ad89d44..c7992f5ea 100644 --- a/sentry-ruby/lib/sentry/event.rb +++ b/sentry-ruby/lib/sentry/event.rb @@ -118,16 +118,16 @@ def rack_env=(env) end # @return [Hash] - def to_hash + def to_h data = serialize_attributes - data[:breadcrumbs] = breadcrumbs.to_hash if breadcrumbs - data[:request] = request.to_hash if request + data[:breadcrumbs] = breadcrumbs.to_h if breadcrumbs + data[:request] = request.to_h if request data end # @return [Hash] def to_json_compatible - JSON.parse(JSON.generate(to_hash)) + JSON.parse(JSON.generate(to_h)) end private diff --git a/sentry-ruby/lib/sentry/hub.rb b/sentry-ruby/lib/sentry/hub.rb index 53250288d..cb82939a8 100644 --- a/sentry-ruby/lib/sentry/hub.rb +++ b/sentry-ruby/lib/sentry/hub.rb @@ -119,7 +119,7 @@ def start_transaction(transaction: nil, custom_sampling_context: {}, instrumente transaction ||= Transaction.new(**options.merge(hub: self)) sampling_context = { - transaction_context: transaction.to_hash, + transaction_context: transaction.to_h, parent_sampled: transaction.parent_sampled, parent_sample_rate: transaction.parent_sample_rate } diff --git a/sentry-ruby/lib/sentry/interface.rb b/sentry-ruby/lib/sentry/interface.rb index d54d605b1..ed8f60cb0 100644 --- a/sentry-ruby/lib/sentry/interface.rb +++ b/sentry-ruby/lib/sentry/interface.rb @@ -3,7 +3,7 @@ module Sentry class Interface # @return [Hash] - def to_hash + def to_h Hash[instance_variables.map { |name| [name[1..-1].to_sym, instance_variable_get(name)] }] end end diff --git a/sentry-ruby/lib/sentry/interfaces/exception.rb b/sentry-ruby/lib/sentry/interfaces/exception.rb index 58cb1a576..4ca18d5ae 100644 --- a/sentry-ruby/lib/sentry/interfaces/exception.rb +++ b/sentry-ruby/lib/sentry/interfaces/exception.rb @@ -13,9 +13,9 @@ def initialize(exceptions:) end # @return [Hash] - def to_hash + def to_h data = super - data[:values] = data[:values].map(&:to_hash) if data[:values] + data[:values] = data[:values].map(&:to_h) if data[:values] data end diff --git a/sentry-ruby/lib/sentry/interfaces/single_exception.rb b/sentry-ruby/lib/sentry/interfaces/single_exception.rb index db2d54e7b..1753ed0ae 100644 --- a/sentry-ruby/lib/sentry/interfaces/single_exception.rb +++ b/sentry-ruby/lib/sentry/interfaces/single_exception.rb @@ -32,10 +32,10 @@ def initialize(exception:, mechanism:, stacktrace: nil) @mechanism = mechanism end - def to_hash + def to_h data = super - data[:stacktrace] = data[:stacktrace].to_hash if data[:stacktrace] - data[:mechanism] = data[:mechanism].to_hash + data[:stacktrace] = data[:stacktrace].to_h if data[:stacktrace] + data[:mechanism] = data[:mechanism].to_h data end diff --git a/sentry-ruby/lib/sentry/interfaces/stacktrace.rb b/sentry-ruby/lib/sentry/interfaces/stacktrace.rb index 5f4be3719..104b7a0fb 100644 --- a/sentry-ruby/lib/sentry/interfaces/stacktrace.rb +++ b/sentry-ruby/lib/sentry/interfaces/stacktrace.rb @@ -11,8 +11,8 @@ def initialize(frames:) end # @return [Hash] - def to_hash - { frames: @frames.map(&:to_hash) } + def to_h + { frames: @frames.map(&:to_h) } end # @return [String] @@ -66,7 +66,7 @@ def set_context(linecache, context_lines) linecache.get_file_context(abs_path, lineno, context_lines) end - def to_hash(*args) + def to_h(*args) data = super(*args) data.delete(:vars) unless vars && !vars.empty? data.delete(:pre_context) unless pre_context && !pre_context.empty? diff --git a/sentry-ruby/lib/sentry/interfaces/stacktrace_builder.rb b/sentry-ruby/lib/sentry/interfaces/stacktrace_builder.rb index d2d0758ec..3f4a7f090 100644 --- a/sentry-ruby/lib/sentry/interfaces/stacktrace_builder.rb +++ b/sentry-ruby/lib/sentry/interfaces/stacktrace_builder.rb @@ -75,14 +75,6 @@ def build(backtrace:, &frame_callback) StacktraceInterface.new(frames: frames) end - # Get the code location hash for a single line for where metrics where added. - # @return [Hash] - def metrics_code_location(unparsed_line) - parsed_line = Backtrace::Line.parse(unparsed_line) - frame = convert_parsed_line_into_frame(parsed_line) - frame.to_hash.reject { |k, _| %i[project_root in_app].include?(k) } - end - private def convert_parsed_line_into_frame(line) diff --git a/sentry-ruby/lib/sentry/interfaces/threads.rb b/sentry-ruby/lib/sentry/interfaces/threads.rb index f250050db..bac6e0e25 100644 --- a/sentry-ruby/lib/sentry/interfaces/threads.rb +++ b/sentry-ruby/lib/sentry/interfaces/threads.rb @@ -13,7 +13,7 @@ def initialize(crashed: false, stacktrace: nil) end # @return [Hash] - def to_hash + def to_h { values: [ { @@ -21,7 +21,7 @@ def to_hash name: @name, crashed: @crashed, current: @current, - stacktrace: @stacktrace&.to_hash + stacktrace: @stacktrace&.to_h } ] } diff --git a/sentry-ruby/lib/sentry/log_event.rb b/sentry-ruby/lib/sentry/log_event.rb index 438fb85c2..cc26eb9f9 100644 --- a/sentry-ruby/lib/sentry/log_event.rb +++ b/sentry-ruby/lib/sentry/log_event.rb @@ -87,7 +87,7 @@ def initialize(configuration: Sentry.configuration, **options) @contexts = {} end - def to_hash + def to_h SERIALIZEABLE_ATTRIBUTES.each_with_object({}) do |name, memo| memo[name] = serialize(name) end diff --git a/sentry-ruby/lib/sentry/metrics.rb b/sentry-ruby/lib/sentry/metrics.rb deleted file mode 100644 index 5da299605..000000000 --- a/sentry-ruby/lib/sentry/metrics.rb +++ /dev/null @@ -1,68 +0,0 @@ -# frozen_string_literal: true - -require "sentry/metrics/metric" -require "sentry/metrics/counter_metric" -require "sentry/metrics/distribution_metric" -require "sentry/metrics/gauge_metric" -require "sentry/metrics/set_metric" -require "sentry/metrics/timing" -require "sentry/metrics/aggregator" - -module Sentry - module Metrics - DURATION_UNITS = %w[nanosecond microsecond millisecond second minute hour day week] - INFORMATION_UNITS = %w[bit byte kilobyte kibibyte megabyte mebibyte gigabyte gibibyte terabyte tebibyte petabyte pebibyte exabyte exbibyte] - FRACTIONAL_UNITS = %w[ratio percent] - - OP_NAME = "metric.timing" - SPAN_ORIGIN = "auto.metric.timing" - - class << self - def increment(key, value = 1.0, unit: "none", tags: {}, timestamp: nil) - log_deprecation - Sentry.metrics_aggregator&.add(:c, key, value, unit: unit, tags: tags, timestamp: timestamp) - end - - def distribution(key, value, unit: "none", tags: {}, timestamp: nil) - log_deprecation - Sentry.metrics_aggregator&.add(:d, key, value, unit: unit, tags: tags, timestamp: timestamp) - end - - def set(key, value, unit: "none", tags: {}, timestamp: nil) - log_deprecation - Sentry.metrics_aggregator&.add(:s, key, value, unit: unit, tags: tags, timestamp: timestamp) - end - - def gauge(key, value, unit: "none", tags: {}, timestamp: nil) - log_deprecation - Sentry.metrics_aggregator&.add(:g, key, value, unit: unit, tags: tags, timestamp: timestamp) - end - - def timing(key, unit: "second", tags: {}, timestamp: nil, &block) - log_deprecation - - return unless block_given? - return yield unless DURATION_UNITS.include?(unit) - - result, value = Sentry.with_child_span(op: OP_NAME, description: key, origin: SPAN_ORIGIN) do |span| - tags.each { |k, v| span.set_tag(k, v.is_a?(Array) ? v.join(", ") : v.to_s) } if span - - start = Timing.send(unit.to_sym) - result = yield - value = Timing.send(unit.to_sym) - start - - [result, value] - end - - Sentry.metrics_aggregator&.add(:d, key, value, unit: unit, tags: tags, timestamp: timestamp) - result - end - - def log_deprecation - Sentry.sdk_logger.warn(LOGGER_PROGNAME) do - "`Sentry::Metrics` is now deprecated and will be removed in the next major." - end - end - end - end -end diff --git a/sentry-ruby/lib/sentry/metrics/aggregator.rb b/sentry-ruby/lib/sentry/metrics/aggregator.rb deleted file mode 100644 index ca7e95563..000000000 --- a/sentry-ruby/lib/sentry/metrics/aggregator.rb +++ /dev/null @@ -1,248 +0,0 @@ -# frozen_string_literal: true - -module Sentry - module Metrics - class Aggregator < ThreadedPeriodicWorker - FLUSH_INTERVAL = 5 - ROLLUP_IN_SECONDS = 10 - - # this is how far removed from user code in the backtrace we are - # when we record code locations - DEFAULT_STACKLEVEL = 4 - - KEY_SANITIZATION_REGEX = /[^a-zA-Z0-9_\-.]+/ - UNIT_SANITIZATION_REGEX = /[^a-zA-Z0-9_]+/ - TAG_KEY_SANITIZATION_REGEX = /[^a-zA-Z0-9_\-.\/]+/ - - TAG_VALUE_SANITIZATION_MAP = { - "\n" => "\\n", - "\r" => "\\r", - "\t" => "\\t", - "\\" => "\\\\", - "|" => "\\u{7c}", - "," => "\\u{2c}" - } - - METRIC_TYPES = { - c: CounterMetric, - d: DistributionMetric, - g: GaugeMetric, - s: SetMetric - } - - # exposed only for testing - attr_reader :client, :thread, :buckets, :flush_shift, :code_locations - - def initialize(configuration, client) - super(configuration.sdk_logger, FLUSH_INTERVAL) - @client = client - @before_emit = configuration.metrics.before_emit - @enable_code_locations = configuration.metrics.enable_code_locations - @stacktrace_builder = configuration.stacktrace_builder - - @default_tags = {} - @default_tags["release"] = configuration.release if configuration.release - @default_tags["environment"] = configuration.environment if configuration.environment - - @mutex = Mutex.new - - # a nested hash of timestamp -> bucket keys -> Metric instance - @buckets = {} - - # the flush interval needs to be shifted once per startup to create jittering - @flush_shift = Random.rand * ROLLUP_IN_SECONDS - - # a nested hash of timestamp (start of day) -> meta keys -> frame - @code_locations = {} - end - - def add(type, - key, - value, - unit: "none", - tags: {}, - timestamp: nil, - stacklevel: nil) - return unless ensure_thread - return unless METRIC_TYPES.keys.include?(type) - - updated_tags = get_updated_tags(tags) - return if @before_emit && !@before_emit.call(key, updated_tags) - - timestamp ||= Sentry.utc_now - - # this is integer division and thus takes the floor of the division - # and buckets into 10 second intervals - bucket_timestamp = (timestamp.to_i / ROLLUP_IN_SECONDS) * ROLLUP_IN_SECONDS - - serialized_tags = serialize_tags(updated_tags) - bucket_key = [type, key, unit, serialized_tags] - - added = @mutex.synchronize do - record_code_location(type, key, unit, timestamp, stacklevel: stacklevel) if @enable_code_locations - process_bucket(bucket_timestamp, bucket_key, type, value) - end - - # for sets, we pass on if there was a new entry to the local gauge - local_value = type == :s ? added : value - process_span_aggregator(bucket_key, local_value) - end - - def flush(force: false) - flushable_buckets = get_flushable_buckets!(force) - code_locations = get_code_locations! - return if flushable_buckets.empty? && code_locations.empty? - - envelope = Envelope.new - - unless flushable_buckets.empty? - payload = serialize_buckets(flushable_buckets) - envelope.add_item( - { type: "statsd", length: payload.bytesize }, - payload - ) - end - - unless code_locations.empty? - code_locations.each do |timestamp, locations| - payload = serialize_locations(timestamp, locations) - envelope.add_item( - { type: "metric_meta", content_type: "application/json" }, - payload - ) - end - end - - @client.capture_envelope(envelope) - end - - alias_method :run, :flush - - private - - # important to sort for key consistency - def serialize_tags(tags) - tags.flat_map do |k, v| - if v.is_a?(Array) - v.map { |x| [k.to_s, x.to_s] } - else - [[k.to_s, v.to_s]] - end - end.sort - end - - def get_flushable_buckets!(force) - @mutex.synchronize do - flushable_buckets = {} - - if force - flushable_buckets = @buckets - @buckets = {} - else - cutoff = Sentry.utc_now.to_i - ROLLUP_IN_SECONDS - @flush_shift - flushable_buckets = @buckets.select { |k, _| k <= cutoff } - @buckets.reject! { |k, _| k <= cutoff } - end - - flushable_buckets - end - end - - def get_code_locations! - @mutex.synchronize do - code_locations = @code_locations - @code_locations = {} - code_locations - end - end - - # serialize buckets to statsd format - def serialize_buckets(buckets) - buckets.map do |timestamp, timestamp_buckets| - timestamp_buckets.map do |metric_key, metric| - type, key, unit, tags = metric_key - values = metric.serialize.join(":") - sanitized_tags = tags.map { |k, v| "#{sanitize_tag_key(k)}:#{sanitize_tag_value(v)}" }.join(",") - - "#{sanitize_key(key)}@#{sanitize_unit(unit)}:#{values}|#{type}|\##{sanitized_tags}|T#{timestamp}" - end - end.flatten.join("\n") - end - - def serialize_locations(timestamp, locations) - mapping = locations.map do |meta_key, location| - type, key, unit = meta_key - mri = "#{type}:#{sanitize_key(key)}@#{sanitize_unit(unit)}" - - # note this needs to be an array but it really doesn't serve a purpose right now - [mri, [location.merge(type: "location")]] - end.to_h - - { timestamp: timestamp, mapping: mapping } - end - - def sanitize_key(key) - key.gsub(KEY_SANITIZATION_REGEX, "_") - end - - def sanitize_unit(unit) - unit.gsub(UNIT_SANITIZATION_REGEX, "") - end - - def sanitize_tag_key(key) - key.gsub(TAG_KEY_SANITIZATION_REGEX, "") - end - - def sanitize_tag_value(value) - value.chars.map { |c| TAG_VALUE_SANITIZATION_MAP[c] || c }.join - end - - def get_transaction_name - scope = Sentry.get_current_scope - return nil unless scope && scope.transaction_name - return nil if scope.transaction_source_low_quality? - - scope.transaction_name - end - - def get_updated_tags(tags) - updated_tags = @default_tags.merge(tags) - - transaction_name = get_transaction_name - updated_tags["transaction"] = transaction_name if transaction_name - - updated_tags - end - - def process_span_aggregator(key, value) - scope = Sentry.get_current_scope - return nil unless scope && scope.span - return nil if scope.transaction_source_low_quality? - - scope.span.metrics_local_aggregator.add(key, value) - end - - def process_bucket(timestamp, key, type, value) - @buckets[timestamp] ||= {} - - if (metric = @buckets[timestamp][key]) - old_weight = metric.weight - metric.add(value) - metric.weight - old_weight - else - metric = METRIC_TYPES[type].new(value) - @buckets[timestamp][key] = metric - metric.weight - end - end - - def record_code_location(type, key, unit, timestamp, stacklevel: nil) - meta_key = [type, key, unit] - start_of_day = Time.utc(timestamp.year, timestamp.month, timestamp.day).to_i - - @code_locations[start_of_day] ||= {} - @code_locations[start_of_day][meta_key] ||= @stacktrace_builder.metrics_code_location(caller[stacklevel || DEFAULT_STACKLEVEL]) - end - end - end -end diff --git a/sentry-ruby/lib/sentry/metrics/configuration.rb b/sentry-ruby/lib/sentry/metrics/configuration.rb deleted file mode 100644 index 2e93bf3f0..000000000 --- a/sentry-ruby/lib/sentry/metrics/configuration.rb +++ /dev/null @@ -1,57 +0,0 @@ -# frozen_string_literal: true - -module Sentry - module Metrics - class Configuration - include ArgumentCheckingHelper - include LoggingHelper - - # Enable metrics usage. - # Starts a new {Sentry::Metrics::Aggregator} instance to aggregate metrics - # and a thread to aggregate flush every 5 seconds. - # @return [Boolean] - attr_reader :enabled - - # Enable code location reporting. - # Will be sent once per day. - # True by default. - # @return [Boolean] - attr_accessor :enable_code_locations - - # Optional Proc, called before emitting a metric to the aggregator. - # Use it to filter keys (return false/nil) or update tags. - # Make sure to return true at the end. - # - # @example - # config.metrics.before_emit = lambda do |key, tags| - # return nil if key == 'foo' - # tags[:bar] = 42 - # tags.delete(:baz) - # true - # end - # - # @return [Proc, nil] - attr_reader :before_emit - - def initialize(sdk_logger) - @sdk_logger = sdk_logger - @enabled = false - @enable_code_locations = true - end - - def enabled=(value) - log_warn <<~MSG - `config.metrics` is now deprecated and will be removed in the next major. - MSG - - @enabled = value - end - - def before_emit=(value) - check_callable!("metrics.before_emit", value) - - @before_emit = value - end - end - end -end diff --git a/sentry-ruby/lib/sentry/metrics/counter_metric.rb b/sentry-ruby/lib/sentry/metrics/counter_metric.rb deleted file mode 100644 index 6ef9d4d48..000000000 --- a/sentry-ruby/lib/sentry/metrics/counter_metric.rb +++ /dev/null @@ -1,25 +0,0 @@ -# frozen_string_literal: true - -module Sentry - module Metrics - class CounterMetric < Metric - attr_reader :value - - def initialize(value) - @value = value.to_f - end - - def add(value) - @value += value.to_f - end - - def serialize - [value] - end - - def weight - 1 - end - end - end -end diff --git a/sentry-ruby/lib/sentry/metrics/distribution_metric.rb b/sentry-ruby/lib/sentry/metrics/distribution_metric.rb deleted file mode 100644 index eae9aff2a..000000000 --- a/sentry-ruby/lib/sentry/metrics/distribution_metric.rb +++ /dev/null @@ -1,25 +0,0 @@ -# frozen_string_literal: true - -module Sentry - module Metrics - class DistributionMetric < Metric - attr_reader :value - - def initialize(value) - @value = [value.to_f] - end - - def add(value) - @value << value.to_f - end - - def serialize - value - end - - def weight - value.size - end - end - end -end diff --git a/sentry-ruby/lib/sentry/metrics/gauge_metric.rb b/sentry-ruby/lib/sentry/metrics/gauge_metric.rb deleted file mode 100644 index f0ba98514..000000000 --- a/sentry-ruby/lib/sentry/metrics/gauge_metric.rb +++ /dev/null @@ -1,35 +0,0 @@ -# frozen_string_literal: true - -module Sentry - module Metrics - class GaugeMetric < Metric - attr_reader :last, :min, :max, :sum, :count - - def initialize(value) - value = value.to_f - @last = value - @min = value - @max = value - @sum = value - @count = 1 - end - - def add(value) - value = value.to_f - @last = value - @min = [@min, value].min - @max = [@max, value].max - @sum += value - @count += 1 - end - - def serialize - [last, min, max, sum, count] - end - - def weight - 5 - end - end - end -end diff --git a/sentry-ruby/lib/sentry/metrics/local_aggregator.rb b/sentry-ruby/lib/sentry/metrics/local_aggregator.rb deleted file mode 100644 index 99d50a5b1..000000000 --- a/sentry-ruby/lib/sentry/metrics/local_aggregator.rb +++ /dev/null @@ -1,53 +0,0 @@ -# frozen_string_literal: true - -module Sentry - module Metrics - class LocalAggregator - # exposed only for testing - attr_reader :buckets - - def initialize - @buckets = {} - end - - def add(key, value) - if @buckets[key] - @buckets[key].add(value) - else - @buckets[key] = GaugeMetric.new(value) - end - end - - def to_hash - return nil if @buckets.empty? - - @buckets.map do |bucket_key, metric| - type, key, unit, tags = bucket_key - - payload_key = "#{type}:#{key}@#{unit}" - payload_value = { - tags: deserialize_tags(tags), - min: metric.min, - max: metric.max, - count: metric.count, - sum: metric.sum - } - - [payload_key, payload_value] - end.to_h - end - - private - - def deserialize_tags(tags) - tags.inject({}) do |h, tag| - k, v = tag - old = h[k] - # make it an array if key repeats - h[k] = old ? (old.is_a?(Array) ? old << v : [old, v]) : v - h - end - end - end - end -end diff --git a/sentry-ruby/lib/sentry/metrics/metric.rb b/sentry-ruby/lib/sentry/metrics/metric.rb deleted file mode 100644 index dbf4a17e0..000000000 --- a/sentry-ruby/lib/sentry/metrics/metric.rb +++ /dev/null @@ -1,19 +0,0 @@ -# frozen_string_literal: true - -module Sentry - module Metrics - class Metric - def add(value) - raise NotImplementedError - end - - def serialize - raise NotImplementedError - end - - def weight - raise NotImplementedError - end - end - end -end diff --git a/sentry-ruby/lib/sentry/metrics/set_metric.rb b/sentry-ruby/lib/sentry/metrics/set_metric.rb deleted file mode 100644 index b38af2743..000000000 --- a/sentry-ruby/lib/sentry/metrics/set_metric.rb +++ /dev/null @@ -1,28 +0,0 @@ -# frozen_string_literal: true - -require "set" -require "zlib" - -module Sentry - module Metrics - class SetMetric < Metric - attr_reader :value - - def initialize(value) - @value = Set[value] - end - - def add(value) - @value << value - end - - def serialize - value.map { |x| x.is_a?(String) ? Zlib.crc32(x) : x.to_i } - end - - def weight - value.size - end - end - end -end diff --git a/sentry-ruby/lib/sentry/metrics/timing.rb b/sentry-ruby/lib/sentry/metrics/timing.rb deleted file mode 100644 index 6d4d9b66d..000000000 --- a/sentry-ruby/lib/sentry/metrics/timing.rb +++ /dev/null @@ -1,51 +0,0 @@ -# frozen_string_literal: true - -module Sentry - module Metrics - module Timing - class << self - def nanosecond - time = Sentry.utc_now - time.to_i * (10 ** 9) + time.nsec - end - - def microsecond - time = Sentry.utc_now - time.to_i * (10 ** 6) + time.usec - end - - def millisecond - Sentry.utc_now.to_i * (10 ** 3) - end - - def second - Sentry.utc_now.to_i - end - - def minute - Sentry.utc_now.to_i / 60.0 - end - - def hour - Sentry.utc_now.to_i / 3600.0 - end - - def day - Sentry.utc_now.to_i / (3600.0 * 24.0) - end - - def week - Sentry.utc_now.to_i / (3600.0 * 24.0 * 7.0) - end - - def duration_start - Process.clock_gettime(Process::CLOCK_MONOTONIC) - end - - def duration_end(start) - Process.clock_gettime(Process::CLOCK_MONOTONIC) - start - end - end - end - end -end diff --git a/sentry-ruby/lib/sentry/profiler.rb b/sentry-ruby/lib/sentry/profiler.rb index d1fd733f7..5c5dd28a9 100644 --- a/sentry-ruby/lib/sentry/profiler.rb +++ b/sentry-ruby/lib/sentry/profiler.rb @@ -81,9 +81,9 @@ def set_initial_sample_decision(transaction_sampled) log("Discarding profile due to sampling decision") unless @sampled end - def to_hash + def to_h unless @sampled - record_lost_event(:sample_rate) + record_lost_event(:sample_rate) if @profiling_enabled return {} end diff --git a/sentry-ruby/lib/sentry/rspec.rb b/sentry-ruby/lib/sentry/rspec.rb index 9c7c49730..5eb0e2b4e 100644 --- a/sentry-ruby/lib/sentry/rspec.rb +++ b/sentry-ruby/lib/sentry/rspec.rb @@ -70,7 +70,7 @@ def find_matched_event(event_message, sentry_events) end def dump_events(sentry_events) - sentry_events.map(&Kernel.method(:Hash)).map do |hash| + sentry_events.map(&:to_h).map do |hash| hash.select { |k, _| [:message, :contexts, :tags, :exception].include?(k) } end.map do |hash| JSON.pretty_generate(hash) diff --git a/sentry-ruby/lib/sentry/span.rb b/sentry-ruby/lib/sentry/span.rb index e2c278a2d..5ba4b7cf8 100644 --- a/sentry-ruby/lib/sentry/span.rb +++ b/sentry-ruby/lib/sentry/span.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true require "securerandom" -require "sentry/metrics/local_aggregator" require "sentry/utils/uuid" module Sentry @@ -173,8 +172,8 @@ def get_dynamic_sampling_context end # @return [Hash] - def to_hash - hash = { + def to_h + { trace_id: @trace_id, span_id: @span_id, parent_span_id: @parent_span_id, @@ -187,11 +186,6 @@ def to_hash data: @data, origin: @origin } - - summary = metrics_summary - hash[:_metrics_summary] = summary if summary - - hash end # Returns the span's context that can be used to embed in an Event. @@ -307,14 +301,5 @@ def set_tag(key, value) def set_origin(origin) @origin = origin end - - # Collects gauge metrics on the span for metric summaries. - def metrics_local_aggregator - @metrics_local_aggregator ||= Sentry::Metrics::LocalAggregator.new - end - - def metrics_summary - @metrics_local_aggregator&.to_hash - end end end diff --git a/sentry-ruby/lib/sentry/test_helper.rb b/sentry-ruby/lib/sentry/test_helper.rb index bcee3d9df..288bbc383 100644 --- a/sentry-ruby/lib/sentry/test_helper.rb +++ b/sentry-ruby/lib/sentry/test_helper.rb @@ -27,6 +27,7 @@ def setup_sentry_test(&block) # set transport to DummyTransport, so we can easily intercept the captured events dummy_config.transport.transport_class = Sentry::DummyTransport # make sure SDK allows sending under the current environment + dummy_config.enabled_environments ||= [] dummy_config.enabled_environments += [dummy_config.environment] unless dummy_config.enabled_environments.include?(dummy_config.environment) # disble async event sending dummy_config.background_worker_threads = 0 diff --git a/sentry-ruby/lib/sentry/transaction.rb b/sentry-ruby/lib/sentry/transaction.rb index 91eb3effe..31a84cfd2 100644 --- a/sentry-ruby/lib/sentry/transaction.rb +++ b/sentry-ruby/lib/sentry/transaction.rb @@ -81,6 +81,7 @@ def initialize( @tracing_enabled = hub.configuration.tracing_enabled? @traces_sampler = hub.configuration.traces_sampler @traces_sample_rate = hub.configuration.traces_sample_rate + @trace_ignore_status_codes = hub.configuration.trace_ignore_status_codes @sdk_logger = hub.configuration.sdk_logger @release = hub.configuration.release @environment = hub.configuration.environment @@ -160,7 +161,7 @@ def self.extract_sample_rand_from_baggage(baggage, trace_id, parent_sampled) end # @return [Hash] - def to_hash + def to_h hash = super hash.merge!( @@ -287,7 +288,15 @@ def finish(hub: nil, end_timestamp: nil) @hub.stop_profiler!(self) - if @sampled + if @sampled && ignore_status_code? + @sampled = false + + status_code = get_http_status_code + log_debug("#{MESSAGE_PREFIX} Discarding #{generate_transaction_description} due to ignored HTTP status code: #{status_code}") + + @hub.current_client.transport.record_lost_event(:event_processor, "transaction") + @hub.current_client.transport.record_lost_event(:event_processor, "span") + elsif @sampled event = hub.current_client.event_from_transaction(self) hub.capture_event(event) else @@ -371,6 +380,21 @@ def populate_head_baggage @baggage = Baggage.new(items, mutable: false) end + def ignore_status_code? + return false unless @trace_ignore_status_codes + + status_code = get_http_status_code + return false unless status_code + + @trace_ignore_status_codes.any? do |ignored| + ignored.is_a?(Range) ? ignored.include?(status_code) : status_code == ignored + end + end + + def get_http_status_code + @data && @data[Span::DataConventions::HTTP_STATUS_CODE] + end + class SpanRecorder attr_reader :max_length, :spans diff --git a/sentry-ruby/lib/sentry/transaction_event.rb b/sentry-ruby/lib/sentry/transaction_event.rb index 21741df40..781a078e8 100644 --- a/sentry-ruby/lib/sentry/transaction_event.rb +++ b/sentry-ruby/lib/sentry/transaction_event.rb @@ -17,9 +17,6 @@ class TransactionEvent < Event # @return [Hash, nil] attr_accessor :profile - # @return [Hash, nil] - attr_accessor :metrics_summary - def initialize(transaction:, **options) super(**options) @@ -32,10 +29,9 @@ def initialize(transaction:, **options) self.tags = transaction.tags self.dynamic_sampling_context = transaction.get_baggage.dynamic_sampling_context self.measurements = transaction.measurements - self.metrics_summary = transaction.metrics_summary finished_spans = transaction.span_recorder.spans.select { |span| span.timestamp && span != transaction } - self.spans = finished_spans.map(&:to_hash) + self.spans = finished_spans.map(&:to_h) populate_profile(transaction) end @@ -48,12 +44,11 @@ def start_timestamp=(time) end # @return [Hash] - def to_hash + def to_h data = super - data[:spans] = @spans.map(&:to_hash) if @spans + data[:spans] = @spans.map(&:to_h) if @spans data[:start_timestamp] = @start_timestamp data[:measurements] = @measurements - data[:_metrics_summary] = @metrics_summary if @metrics_summary data end @@ -62,7 +57,7 @@ def to_hash EMPTY_PROFILE = {}.freeze def populate_profile(transaction) - profile_hash = transaction.profiler&.to_hash || EMPTY_PROFILE + profile_hash = transaction.profiler&.to_h || EMPTY_PROFILE return if profile_hash.empty? diff --git a/sentry-ruby/lib/sentry/transport.rb b/sentry-ruby/lib/sentry/transport.rb index 0c93e7dfa..3c2a1ac43 100644 --- a/sentry-ruby/lib/sentry/transport.rb +++ b/sentry-ruby/lib/sentry/transport.rb @@ -113,7 +113,7 @@ def any_rate_limited? def envelope_from_event(event) # Convert to hash - event_payload = event.to_hash + event_payload = event.to_h event_id = event_payload[:event_id] || event_payload["event_id"] item_type = event_payload[:type] || event_payload["type"] @@ -124,10 +124,7 @@ def envelope_from_event(event) sent_at: Sentry.utc_now.iso8601 } - if event.is_a?(Event) && event.dynamic_sampling_context - envelope_headers[:trace] = event.dynamic_sampling_context - end - + envelope_headers[:trace] = event.dynamic_sampling_context if event.dynamic_sampling_context envelope = Envelope.new(envelope_headers) if event.is_a?(LogEvent) diff --git a/sentry-ruby/lib/sentry/vernier/profiler.rb b/sentry-ruby/lib/sentry/vernier/profiler.rb index 450ed496a..c3678eb70 100644 --- a/sentry-ruby/lib/sentry/vernier/profiler.rb +++ b/sentry-ruby/lib/sentry/vernier/profiler.rb @@ -90,9 +90,9 @@ def active_thread_id Thread.current.object_id end - def to_hash + def to_h unless @sampled - record_lost_event(:sample_rate) + record_lost_event(:sample_rate) if @profiling_enabled return EMPTY_RESULT end diff --git a/sentry-ruby/spec/sentry/background_worker_spec.rb b/sentry-ruby/spec/sentry/background_worker_spec.rb index 7295db97d..2e8afd797 100644 --- a/sentry-ruby/spec/sentry/background_worker_spec.rb +++ b/sentry-ruby/spec/sentry/background_worker_spec.rb @@ -10,22 +10,6 @@ end describe "#initialize" do - context "when config.async is set" do - before do - configuration.async = proc { } - end - - it "initializes a background_worker with ImmediateExecutor" do - worker = described_class.new(configuration) - - expect(string_io.string).to match( - /config.async is set, BackgroundWorker is disabled/ - ) - - expect(worker.instance_variable_get(:@executor)).to be_a(Concurrent::ImmediateExecutor) - end - end - context "when config.background_worker_threads is set" do it "initializes a background worker with correct number of threads and queue size" do configuration.background_worker_threads = 4 diff --git a/sentry-ruby/spec/sentry/breadcrumb_buffer_spec.rb b/sentry-ruby/spec/sentry/breadcrumb_buffer_spec.rb index 7efb67ae7..7093a53a3 100644 --- a/sentry-ruby/spec/sentry/breadcrumb_buffer_spec.rb +++ b/sentry-ruby/spec/sentry/breadcrumb_buffer_spec.rb @@ -55,13 +55,13 @@ end end - describe "#to_hash" do + describe "#to_h" do it "doesn't break because of 1 problematic crumb" do subject.record(crumb_1) subject.record(crumb_2) subject.record(problematic_crumb) - result = subject.to_hash[:values] + result = subject.to_h[:values] expect(result[0][:category]).to eq("foo") expect(result[0][:data]).to eq({ "name" => "John", "age" => 25 }) diff --git a/sentry-ruby/spec/sentry/breadcrumb_spec.rb b/sentry-ruby/spec/sentry/breadcrumb_spec.rb index 008f1741e..3e040cfc8 100644 --- a/sentry-ruby/spec/sentry/breadcrumb_spec.rb +++ b/sentry-ruby/spec/sentry/breadcrumb_spec.rb @@ -64,7 +64,7 @@ end end - describe "#to_hash" do + describe "#to_h" do let(:problematic_crumb) do # circular reference a = [] @@ -90,7 +90,7 @@ end it "serializes data correctly" do - result = crumb.to_hash + result = crumb.to_h expect(result[:category]).to eq("foo") expect(result[:message]).to eq("crumb") @@ -98,7 +98,7 @@ end it "rescues data serialization issue and ditch the data" do - result = problematic_crumb.to_hash + result = problematic_crumb.to_h expect(result[:category]).to eq("baz") expect(result[:message]).to eq("I cause issues") @@ -107,7 +107,7 @@ end it "rescues data serialization issue for extremely nested data and ditch the data" do - result = very_deep_crumb.to_hash + result = very_deep_crumb.to_h expect(result[:category]).to eq("cow") expect(result[:message]).to eq("I cause too much recursion") diff --git a/sentry-ruby/spec/sentry/client/event_sending_spec.rb b/sentry-ruby/spec/sentry/client/event_sending_spec.rb index b24739f16..08d9a35ec 100644 --- a/sentry-ruby/spec/sentry/client/event_sending_spec.rb +++ b/sentry-ruby/spec/sentry/client/event_sending_spec.rb @@ -61,84 +61,6 @@ end end - context 'with config.async set' do - let(:async_block) do - lambda do |event| - client.send_event(event) - end - end - - around do |example| - prior_async = configuration.async - configuration.async = async_block - example.run - configuration.async = prior_async - end - - it "executes the given block" do - expect(async_block).to receive(:call).and_call_original - - returned = client.capture_event(event, scope) - - expect(returned).to be_a(Sentry::ErrorEvent) - expect(client.transport.events.first).to eq(event.to_json_compatible) - end - - it "doesn't call the async block if not allow sending events" do - allow(configuration).to receive(:sending_allowed?).and_return(false) - - expect(async_block).not_to receive(:call) - - returned = client.capture_event(event, scope) - - expect(returned).to eq(nil) - end - - context "with to json conversion failed" do - let(:logger) { ::Logger.new(string_io) } - let(:string_io) { StringIO.new } - let(:event) { client.event_from_message("Bad data '\x80\xF8'") } - - it "does not mask the exception" do - configuration.sdk_logger = logger - - client.capture_event(event, scope) - - expect(string_io.string).to match(/Converting event \(#{event.event_id}\) to JSON compatible hash failed:.*illegal\/malformed utf-8/i) - end - end - - context "with nil as value (the legacy way to disable it)" do - let(:async_block) { nil } - - it "doesn't cause any issue" do - returned = client.capture_event(event, scope, { background: false }) - - expect(returned).to be_a(Sentry::ErrorEvent) - expect(client.transport.events.first).to eq(event) - end - end - - context "with 2 arity block" do - let(:async_block) do - lambda do |event, hint| - event["tags"]["hint"] = hint - client.send_event(event) - end - end - - it "serializes hint and supplies it as the second argument" do - expect(configuration.async).to receive(:call).and_call_original - - returned = client.capture_event(event, scope, { foo: "bar" }) - - expect(returned).to be_a(Sentry::ErrorEvent) - event = client.transport.events.first - expect(event.dig("tags", "hint")).to eq({ "foo" => "bar" }) - end - end - end - context "with background_worker enabled (default)" do before do Sentry.background_worker = Sentry::BackgroundWorker.new(configuration) @@ -206,6 +128,8 @@ client.event_from_exception(ZeroDivisionError.new("divided by 0")) end + let(:check_in_event) { client.event_from_check_in("test_slug", :ok) } + shared_examples "Event in send_event" do context "when there's an exception" do before do @@ -218,6 +142,7 @@ end.to raise_error(Sentry::ExternalError, "networking error") end end + it "sends data through the transport" do expect(client.transport).to receive(:send_event).with(event) client.send_event(event) @@ -225,34 +150,12 @@ it "applies before_send callback before sending the event" do configuration.before_send = lambda do |event, _hint| - if event.is_a?(Sentry::Event) - event.tags[:called] = true - else - event["tags"]["called"] = true - end - + event.tags[:called] = true event end client.send_event(event) - - if event.is_a?(Sentry::Event) - expect(event.tags[:called]).to eq(true) - else - expect(event["tags"]["called"]).to eq(true) - end - end - - context "for check in events" do - let(:event_object) { client.event_from_check_in("test_slug", :ok) } - - it "does not fail due to before_send" do - configuration.before_send = lambda { |e, _h| e } - client.send_event(event) - - expect(client.transport).to receive(:send_event).with(event) - client.send_event(event) - end + expect(event.tags[:called]).to eq(true) end it "doesn't apply before_send_transaction to Event" do @@ -288,29 +191,12 @@ expect(string_io.string).to include("Discarded event because before_send didn't return a Sentry::ErrorEvent object but an instance of Integer") expect(return_value).to eq(nil) end - - it "warns about Hash value's deprecation" do - string_io = StringIO.new - logger = Logger.new(string_io, level: :debug) - configuration.sdk_logger = logger - configuration.before_send = lambda do |_event, _hint| - { foo: "bar" } - end - - return_value = client.send_event(event) - expect(string_io.string).to include("Returning a Hash from before_send is deprecated and will be removed in the next major version.") - expect(return_value).to eq({ foo: "bar" }) - end end it_behaves_like "Event in send_event" do let(:event) { event_object } end - it_behaves_like "Event in send_event" do - let(:event) { event_object.to_json_compatible } - end - shared_examples "TransactionEvent in send_event" do it "sends data through the transport" do client.send_event(event) @@ -326,22 +212,12 @@ it "applies before_send_transaction callback before sending the event" do configuration.before_send_transaction = lambda do |event, _hint| - if event.is_a?(Sentry::TransactionEvent) - event.tags[:called] = true - else - event["tags"]["called"] = true - end - + event.tags[:called] = true event end client.send_event(event) - - if event.is_a?(Sentry::Event) - expect(event.tags[:called]).to eq(true) - else - expect(event["tags"]["called"]).to eq(true) - end + expect(event.tags[:called]).to eq(true) end it "warns if before_send_transaction returns nil" do @@ -356,27 +232,60 @@ expect(string_io.string).to include("Discarded event because before_send_transaction didn't return a Sentry::TransactionEvent object but an instance of NilClass") expect(return_value).to be_nil end + end + + it_behaves_like "TransactionEvent in send_event" do + let(:event) { transaction_event } + end + + shared_examples "CheckInEvent in send_event" do + it "sends data through the transport" do + client.send_event(event) + end - it "warns about Hash value's deprecation" do + it "doesn't apply before_send to CheckInEvent" do + configuration.before_send = lambda do |event, _hint| + raise "shouldn't trigger me" + end + + client.send_event(event) + end + + it "doesn't apply before_send_transaction to CheckInEvent" do + configuration.before_send_transaction = lambda do |event, _hint| + raise "shouldn't trigger me" + end + + client.send_event(event) + end + + it "applies before_send_check_in callback before sending the event" do + called = false + configuration.before_send_check_in = lambda do |event, _hint| + called = true + event + end + + client.send_event(event) + expect(called).to eq(true) + end + + it "warns if before_send_check_in returns nil" do string_io = StringIO.new logger = Logger.new(string_io, level: :debug) configuration.sdk_logger = logger - configuration.before_send_transaction = lambda do |_event, _hint| - { foo: "bar" } + configuration.before_send_check_in = lambda do |_event, _hint| + nil end return_value = client.send_event(event) - expect(string_io.string).to include("Returning a Hash from before_send_transaction is deprecated and will be removed in the next major version.") - expect(return_value).to eq({ foo: "bar" }) + expect(string_io.string).to include("Discarded event because before_send_check_in didn't return a Sentry::CheckInEvent object but an instance of NilClass") + expect(return_value).to be_nil end end - it_behaves_like "TransactionEvent in send_event" do - let(:event) { transaction_event } - end - - it_behaves_like "TransactionEvent in send_event" do - let(:event) { transaction_event.to_json_compatible } + it_behaves_like "CheckInEvent in send_event" do + let(:event) { check_in_event } end end @@ -397,12 +306,6 @@ let(:event) { client.event_from_message(message) } describe "#capture_event" do - around do |example| - prior_async = configuration.async - example.run - configuration.async = prior_async - end - context "when scope.apply_to_event returns nil" do before do scope.add_event_processor do |event, hint| @@ -542,28 +445,6 @@ expect(client.transport).to have_recorded_lost_event(:network_error, 'span', num: 6) end end - - context "when config.async causes error" do - before do - expect(client).to receive(:send_event) - end - - it "swallows Redis related error and send the event synchronizely" do - configuration.async = ->(_, _) { raise Redis::ConnectionError } - - client.capture_event(event, scope) - - expect(string_io.string).to match(/Async event sending failed: Redis::ConnectionError/) - end - - it "swallows and logs the exception" do - configuration.async = ->(_, _) { raise TypeError } - - client.capture_event(event, scope) - - expect(string_io.string).to match(/Async event sending failed: TypeError/) - end - end end describe "#send_event" do diff --git a/sentry-ruby/spec/sentry/client_spec.rb b/sentry-ruby/spec/sentry/client_spec.rb index 55b9129ee..de5b8b7ca 100644 --- a/sentry-ruby/spec/sentry/client_spec.rb +++ b/sentry-ruby/spec/sentry/client_spec.rb @@ -99,7 +99,6 @@ def sentry_context let(:envelope) do envelope = Sentry::Envelope.new({ env_header: 1 }) envelope.add_item({ type: 'event' }, { payload: 'test' }) - envelope.add_item({ type: 'statsd' }, { payload: 'test2' }) envelope.add_item({ type: 'transaction' }, { payload: 'test3' }) envelope.add_item({ type: 'log' }, { level: 'info', message: 'test4' }) envelope @@ -159,7 +158,6 @@ def sentry_context end.to raise_error(Sentry::ExternalError) expect(subject.transport).to have_recorded_lost_event(:network_error, 'error') - expect(subject.transport).to have_recorded_lost_event(:network_error, 'metric_bucket') expect(subject.transport).to have_recorded_lost_event(:network_error, 'transaction') expect(subject.transport).to have_recorded_lost_event(:network_error, 'log') end @@ -190,7 +188,7 @@ def sentry_context it 'returns an event' do event = subject.event_from_message(message) - hash = event.to_hash + hash = event.to_h expect(event).to be_a(Sentry::ErrorEvent) expect(hash[:message]).to eq(message) @@ -206,7 +204,7 @@ def sentry_context end t.join - hash = event.to_hash + hash = event.to_h thread = hash[:threads][:values][0] expect(thread[:id]).to eq(t.object_id) @@ -234,7 +232,7 @@ def sentry_context it "initializes a correct event for the transaction" do event = subject.event_from_transaction(transaction) - event_hash = event.to_hash + event_hash = event.to_h expect(event_hash[:type]).to eq("transaction") expect(event_hash[:contexts][:trace]).to eq(transaction.get_trace_context) @@ -286,23 +284,13 @@ def sentry_context event = subject.event_from_transaction(transaction) expect(event.contexts).to include({ foo: { bar: 42 } }) end - - it 'adds metric summary on transaction if any' do - key = [:c, 'incr', 'none', []] - transaction.metrics_local_aggregator.add(key, 10) - hash = subject.event_from_transaction(transaction).to_hash - - expect(hash[:_metrics_summary]).to eq({ - 'c:incr@none' => { count: 1, max: 10.0, min: 10.0, sum: 10.0, tags: {} } - }) - end end describe "#event_from_exception" do let(:message) { 'This is a message' } let(:exception) { Exception.new(message) } let(:event) { subject.event_from_exception(exception) } - let(:hash) { event.to_hash } + let(:hash) { event.to_h } it "sets the message to the exception's value and type" do expect(hash[:exception][:values][0][:type]).to eq("Exception") @@ -351,7 +339,7 @@ def detailed_message(*) end event = subject.event_from_exception(NonStringMessageError.new) - hash = event.to_hash + hash = event.to_h expect(event).to be_a(Sentry::ErrorEvent) if RUBY_VERSION >= "3.4" @@ -372,7 +360,7 @@ def detailed_message(*) t.join - event_hash = event.to_hash + event_hash = event.to_h thread = event_hash[:threads][:values][0] expect(thread[:id]).to eq(t.object_id) @@ -393,7 +381,7 @@ def detailed_message(*) it 'returns an event' do event = subject.event_from_exception(ZeroDivisionError.new("divided by 0")) expect(event).to be_a(Sentry::ErrorEvent) - hash = event.to_hash + hash = event.to_h expect(hash[:exception][:values][0][:type]).to match("ZeroDivisionError") expect(hash[:exception][:values][0][:value]).to match("divided by 0") end @@ -593,7 +581,7 @@ module ExcTag; end context 'when the exception responds to sentry_context' do let(:hash) do event = subject.event_from_exception(ExceptionWithContext.new) - event.to_hash + event.to_h end it "merges the context into event's extra" do @@ -671,7 +659,7 @@ module ExcTag; end it 'has correct custom mechanism when passed' do mech = Sentry::Mechanism.new(type: 'custom', handled: false) event = subject.event_from_exception(exception, mechanism: mech) - hash = event.to_hash + hash = event.to_h mechanism = hash[:exception][:values][0][:mechanism] expect(mechanism).to eq({ type: 'custom', handled: false }) end @@ -686,7 +674,7 @@ module ExcTag; end event = subject.event_from_check_in(slug, status) expect(event).to be_a(Sentry::CheckInEvent) - hash = event.to_hash + hash = event.to_h expect(hash[:monitor_slug]).to eq(slug) expect(hash[:status]).to eq(status) expect(hash[:check_in_id].length).to eq(32) @@ -703,7 +691,7 @@ module ExcTag; end expect(event).to be_a(Sentry::CheckInEvent) - hash = event.to_hash + hash = event.to_h expect(hash[:monitor_slug]).to eq(slug) expect(hash[:status]).to eq(status) expect(hash[:check_in_id]).to eq("xxx-yyy") @@ -722,7 +710,7 @@ module ExcTag; end expect(event).to be_a(Sentry::CheckInEvent) - hash = event.to_hash + hash = event.to_h expect(hash[:monitor_slug]).to eq(slug) expect(hash[:status]).to eq(status) expect(hash[:check_in_id]).to eq("xxx-yyy") diff --git a/sentry-ruby/spec/sentry/configuration_spec.rb b/sentry-ruby/spec/sentry/configuration_spec.rb index 92e831466..e6d94146c 100644 --- a/sentry-ruby/spec/sentry/configuration_spec.rb +++ b/sentry-ruby/spec/sentry/configuration_spec.rb @@ -1,29 +1,6 @@ # frozen_string_literal: true RSpec.describe Sentry::Configuration do - describe "#capture_exception_frame_locals" do - it "passes/received the value to #include_local_variables" do - subject.capture_exception_frame_locals = true - expect(subject.include_local_variables).to eq(true) - expect(subject.capture_exception_frame_locals).to eq(true) - - subject.capture_exception_frame_locals = false - expect(subject.include_local_variables).to eq(false) - expect(subject.capture_exception_frame_locals).to eq(false) - end - - it "prints deprecation message when being assigned" do - string_io = StringIO.new - subject.logger = Logger.new(string_io) - - subject.capture_exception_frame_locals = true - - expect(string_io.string).to include( - "WARN -- sentry: `capture_exception_frame_locals` is now deprecated in favor of `include_local_variables`." - ) - end - end - describe "#background_worker_threads" do it "sets to have of the processors count" do allow_any_instance_of(Sentry::Configuration).to receive(:processor_count).and_return(8) @@ -114,25 +91,6 @@ expect(subject.tracing_enabled?).to eq(false) end end - - context "when enable_tracing is set" do - it "returns false" do - subject.enable_tracing = true - - expect(subject.tracing_enabled?).to eq(false) - end - - it "prints deprecation message when being assigned" do - string_io = StringIO.new - subject.logger = Logger.new(string_io) - - subject.enable_tracing = true - - expect(string_io.string).to include( - "WARN -- sentry: `enable_tracing` is now deprecated in favor of `traces_sample_rate = 1.0`." - ) - end - end end context "when sending allowed" do @@ -175,29 +133,6 @@ expect(subject.tracing_enabled?).to eq(true) end end - - context "when enable_tracing is true" do - it "returns true" do - subject.enable_tracing = true - - expect(subject.tracing_enabled?).to eq(true) - end - end - - context "when enable_tracing is false" do - it "returns false" do - subject.enable_tracing = false - - expect(subject.tracing_enabled?).to eq(false) - end - - it "returns false even with explicit traces_sample_rate" do - subject.traces_sample_rate = 1.0 - subject.enable_tracing = false - - expect(subject.tracing_enabled?).to eq(false) - end - end end end @@ -227,19 +162,19 @@ describe "#profiling_enabled?" do it "returns false unless tracing enabled" do - subject.enable_tracing = false + subject.traces_sample_rate = nil expect(subject.profiling_enabled?).to eq(false) end it "returns false unless sending enabled" do - subject.enable_tracing = true + subject.traces_sample_rate = 1.0 subject.profiles_sample_rate = 1.0 allow(subject).to receive(:sending_allowed?).and_return(false) expect(subject.profiling_enabled?).to eq(false) end context 'when tracing and sending enabled' do - before { subject.enable_tracing = true } + before { subject.traces_sample_rate = 1.0 } before { allow(subject).to receive(:sending_allowed?).and_return(true) } it "returns false if nil sample rate" do @@ -259,19 +194,6 @@ end end - describe "#enable_tracing=" do - it "sets traces_sample_rate to 1.0 automatically" do - subject.enable_tracing = true - expect(subject.traces_sample_rate).to eq(1.0) - end - - it "doesn't override existing traces_sample_rate" do - subject.traces_sample_rate = 0.5 - subject.enable_tracing = true - expect(subject.traces_sample_rate).to eq(0.5) - end - end - describe "#transport" do it "returns an initialized Transport::Configuration object" do transport_config = subject.transport @@ -372,24 +294,11 @@ end end - context 'configuring for async' do - it 'should be configurable to send events async' do - subject.async = ->(_e) { :ok } - expect(subject.async.call('event')).to eq(:ok) - end - end - it 'raises error when setting release to anything other than String' do subject.release = "foo" expect { subject.release = 42 }.to raise_error(ArgumentError, "expect the argument to be a String or NilClass, got Integer (42)") end - it 'raises error when setting async to anything other than callable or nil' do - subject.async = -> { } - subject.async = nil - expect { subject.async = true }.to raise_error(ArgumentError, "async must be callable (or nil to disable)") - end - it 'raises error when setting before_send to anything other than callable or nil' do subject.before_send = -> { } subject.before_send = nil @@ -402,6 +311,12 @@ expect { subject.before_send_transaction = true }.to raise_error(ArgumentError, "before_send_transaction must be callable (or nil to disable)") end + it 'raises error when setting before_send_check_in to anything other than callable or nil' do + subject.before_send_check_in = -> { } + subject.before_send_check_in = nil + expect { subject.before_send_check_in = true }.to raise_error(ArgumentError, "before_send_check_in must be callable (or nil to disable)") + end + it 'raises error when setting before_breadcrumb to anything other than callable or nil' do subject.before_breadcrumb = -> { } subject.before_breadcrumb = nil @@ -416,9 +331,8 @@ it 'should send events if test is whitelisted' do subject.enabled_environments = %w[test] - subject.sending_allowed? - puts subject.errors expect(subject.sending_allowed?).to eq(true) + expect(subject.errors).to be_empty end it 'should not send events if test is not whitelisted' do @@ -798,19 +712,43 @@ class SentryConfigurationSample < Sentry::Configuration end end - describe "#logger" do - it "returns configured sdk_logger and prints deprecation warning" do - expect { - expect(subject.logger).to be(subject.sdk_logger) - }.to output(/`config.logger` is deprecated/).to_stderr + describe "#trace_ignore_status_codes" do + it "has default values" do + expect(subject.trace_ignore_status_codes).to eq([(301..303), (305..399), (401..404)]) end - end - describe "#logger=" do - it "sets sdk_logger and prints deprecation warning" do - expect { - subject.logger = Logger.new($stdout) - }.to output(/`config.logger=` is deprecated/).to_stderr + it "can be configured with individual status codes" do + subject.trace_ignore_status_codes = [404, 500] + expect(subject.trace_ignore_status_codes).to eq([404, 500]) + end + + it "can be configured with ranges" do + subject.trace_ignore_status_codes = [(300..399), (500..599)] + expect(subject.trace_ignore_status_codes).to eq([(300..399), (500..599)]) + end + + it "can be configured with mixed individual codes and ranges" do + subject.trace_ignore_status_codes = [404, (500..599)] + expect(subject.trace_ignore_status_codes).to eq([404, (500..599)]) + end + + it "raises ArgumentError when not an Array" do + expect { subject.trace_ignore_status_codes = 404 }.to raise_error(ArgumentError, /must be an Array/) + expect { subject.trace_ignore_status_codes = "404" }.to raise_error(ArgumentError, /must be an Array/) + end + + it "raises ArgumentError for invalid status codes" do + expect { subject.trace_ignore_status_codes = [99] }.to raise_error(ArgumentError, /must be.* between \(100-599\)/) + expect { subject.trace_ignore_status_codes = [600] }.to raise_error(ArgumentError, /must be.* between \(100-599\)/) + expect { subject.trace_ignore_status_codes = ["404"] }.to raise_error(ArgumentError, /must be an Array of integers/) + end + + it "raises ArgumentError for invalid ranges" do + expect { subject.trace_ignore_status_codes = [[400]] }.to raise_error(ArgumentError, /must be.* ranges/) + expect { subject.trace_ignore_status_codes = [[400, 500, 600]] }.to raise_error(ArgumentError, /must be.* ranges/) + expect { subject.trace_ignore_status_codes = [[500, 400]] }.to raise_error(ArgumentError, /must be.* begin <= end/) + expect { subject.trace_ignore_status_codes = [[99, 200]] }.to raise_error(ArgumentError, /must be.* between \(100-599\)/) + expect { subject.trace_ignore_status_codes = [[400, 600]] }.to raise_error(ArgumentError, /must be.* between \(100-599\)/) end end end diff --git a/sentry-ruby/spec/sentry/cron/monitor_config_spec.rb b/sentry-ruby/spec/sentry/cron/monitor_config_spec.rb index c6266908b..11dd57952 100644 --- a/sentry-ruby/spec/sentry/cron/monitor_config_spec.rb +++ b/sentry-ruby/spec/sentry/cron/monitor_config_spec.rb @@ -43,7 +43,7 @@ end end - describe '#to_hash' do + describe '#to_h' do it 'returns hash with correct attributes for crontab' do subject = described_class.from_crontab( '5 * * * *', @@ -52,7 +52,7 @@ timezone: 'Europe/Vienna' ) - hash = subject.to_hash + hash = subject.to_h expect(hash).to eq({ schedule: { type: :crontab, value: '5 * * * *' }, checkin_margin: 10, @@ -70,7 +70,7 @@ timezone: 'Europe/Vienna' ) - hash = subject.to_hash + hash = subject.to_h expect(hash).to eq({ schedule: { type: :interval, value: 5, unit: :hour }, checkin_margin: 10, diff --git a/sentry-ruby/spec/sentry/cron/monitor_schedule_spec.rb b/sentry-ruby/spec/sentry/cron/monitor_schedule_spec.rb index 9acad1319..fdaf0f549 100644 --- a/sentry-ruby/spec/sentry/cron/monitor_schedule_spec.rb +++ b/sentry-ruby/spec/sentry/cron/monitor_schedule_spec.rb @@ -9,9 +9,9 @@ end end - describe '#to_hash' do + describe '#to_h' do it 'has correct attributes' do - expect(subject.to_hash).to eq({ type: :crontab, value: subject.value }) + expect(subject.to_h).to eq({ type: :crontab, value: subject.value }) end end end @@ -31,9 +31,9 @@ end end - describe '#to_hash' do + describe '#to_h' do it 'has correct attributes' do - expect(subject.to_hash).to eq({ type: :interval, value: subject.value, unit: subject.unit }) + expect(subject.to_h).to eq({ type: :interval, value: subject.value, unit: subject.unit }) end end end diff --git a/sentry-ruby/spec/sentry/envelope/item_spec.rb b/sentry-ruby/spec/sentry/envelope/item_spec.rb index bdf01dd6c..516dfd465 100644 --- a/sentry-ruby/spec/sentry/envelope/item_spec.rb +++ b/sentry-ruby/spec/sentry/envelope/item_spec.rb @@ -11,8 +11,6 @@ ['profile', 'profile'], ['log', 'log'], ['check_in', 'monitor'], - ['statsd', 'metric_bucket'], - ['metric_meta', 'metric_bucket'], ['event', 'error'], ['client_report', 'internal'], ['unknown', 'default'] diff --git a/sentry-ruby/spec/sentry/event_spec.rb b/sentry-ruby/spec/sentry/event_spec.rb index dc8eb9c5c..0f00ced00 100644 --- a/sentry-ruby/spec/sentry/event_spec.rb +++ b/sentry-ruby/spec/sentry/event_spec.rb @@ -97,14 +97,14 @@ it "filters out pii data" do scope.apply_to_event(event) - expect(event.to_hash[:request]).to eq( + expect(event.to_h[:request]).to eq( env: { 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '80' }, headers: { 'Host' => 'localhost', 'X-Request-Id' => 'abcd-1234-abcd-1234' }, method: 'POST', url: 'http://localhost/lol', ) - expect(event.to_hash[:tags][:request_id]).to eq("abcd-1234-abcd-1234") - expect(event.to_hash[:user][:ip_address]).to eq(nil) + expect(event.to_h[:tags][:request_id]).to eq("abcd-1234-abcd-1234") + expect(event.to_h[:user][:ip_address]).to eq(nil) end it "removes ip address headers" do @@ -127,7 +127,7 @@ it "adds correct data" do Sentry.get_current_scope.apply_to_event(event) - expect(event.to_hash[:request]).to eq( + expect(event.to_h[:request]).to eq( data: { 'foo' => 'bar' }, env: { 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '80', "REMOTE_ADDR" => "192.168.1.1" }, headers: { 'Host' => 'localhost', "X-Forwarded-For" => "1.1.1.1, 2.2.2.2", "X-Request-Id" => "abcd-1234-abcd-1234" }, @@ -137,14 +137,14 @@ cookies: {} ) - expect(event.to_hash[:tags][:request_id]).to eq("abcd-1234-abcd-1234") - expect(event.to_hash[:user][:ip_address]).to eq("2.2.2.2") + expect(event.to_h[:tags][:request_id]).to eq("abcd-1234-abcd-1234") + expect(event.to_h[:user][:ip_address]).to eq("2.2.2.2") end it "doesn't overwrite already set ip address" do Sentry.set_user({ ip_address: "3.3.3.3" }) Sentry.get_current_scope.apply_to_event(event) - expect(event.to_hash[:user][:ip_address]).to eq("3.3.3.3") + expect(event.to_h[:user][:ip_address]).to eq("3.3.3.3") end context "with config.trusted_proxies = [\"2.2.2.2\"]" do @@ -155,7 +155,7 @@ it "calculates the correct ip address" do Sentry.get_current_scope.apply_to_event(event) - expect(event.to_hash[:request]).to eq( + expect(event.to_h[:request]).to eq( data: { "foo"=>"bar" }, env: { 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '80', "REMOTE_ADDR" => "192.168.1.1" }, headers: { 'Host' => 'localhost', "X-Forwarded-For" => "1.1.1.1, 2.2.2.2", "X-Request-Id" => "abcd-1234-abcd-1234" }, @@ -165,8 +165,8 @@ cookies: {} ) - expect(event.to_hash[:tags][:request_id]).to eq("abcd-1234-abcd-1234") - expect(event.to_hash[:user][:ip_address]).to eq("1.1.1.1") + expect(event.to_h[:tags][:request_id]).to eq("abcd-1234-abcd-1234") + expect(event.to_h[:user][:ip_address]).to eq("1.1.1.1") end end end diff --git a/sentry-ruby/spec/sentry/hub_spec.rb b/sentry-ruby/spec/sentry/hub_spec.rb index f2f549d0d..b25609fef 100644 --- a/sentry-ruby/spec/sentry/hub_spec.rb +++ b/sentry-ruby/spec/sentry/hub_spec.rb @@ -147,7 +147,7 @@ it "takes backtrace option" do event = subject.capture_message(message, backtrace: ["#{__FILE__}:10:in `foo'"]) - event_hash = event.to_hash + event_hash = event.to_h expect(event_hash.dig(:threads, :values, 0, :stacktrace, :frames, 0, :function)).to eq("foo") end @@ -159,7 +159,7 @@ it "assigns default backtrace with caller" do event = subject.capture_message(message) - event_hash = event.to_hash + event_hash = event.to_h expect(event_hash.dig(:threads, :values, 0, :stacktrace, :frames, 0, :function)).to eq("
") end @@ -211,7 +211,7 @@ monitor_config: Sentry::Cron::MonitorConfig.from_crontab("* * * * *") ) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event).to include( monitor_slug: slug, status: :ok, diff --git a/sentry-ruby/spec/sentry/integrable_spec.rb b/sentry-ruby/spec/sentry/integrable_spec.rb index 02a2ed102..4a6677a87 100644 --- a/sentry-ruby/spec/sentry/integrable_spec.rb +++ b/sentry-ruby/spec/sentry/integrable_spec.rb @@ -82,7 +82,7 @@ module AnotherIntegration; end it "generates Sentry::FakeIntegration.capture_check_in" do hint = nil - Sentry.configuration.before_send = lambda do |event, h| + Sentry.configuration.before_send_check_in = lambda do |event, h| hint = h event end diff --git a/sentry-ruby/spec/sentry/interface_spec.rb b/sentry-ruby/spec/sentry/interface_spec.rb index ade88af2a..e67bd5fbf 100644 --- a/sentry-ruby/spec/sentry/interface_spec.rb +++ b/sentry-ruby/spec/sentry/interface_spec.rb @@ -11,6 +11,6 @@ class TestInterface < Sentry::Interface interface = TestInterface.new interface.some_attr = "test" - expect(interface.to_hash).to eq(some_attr: "test") + expect(interface.to_h).to eq(some_attr: "test") end end diff --git a/sentry-ruby/spec/sentry/interfaces/request_interface_spec.rb b/sentry-ruby/spec/sentry/interfaces/request_interface_spec.rb index 041979e74..1ca2a5b67 100644 --- a/sentry-ruby/spec/sentry/interfaces/request_interface_spec.rb +++ b/sentry-ruby/spec/sentry/interfaces/request_interface_spec.rb @@ -61,7 +61,7 @@ let(:additional_headers) { { "HTTP_FOO" => "Tekirda\xC4" } } it "doesn't cause any issue" do - json = JSON.generate(subject.to_hash) + json = JSON.generate(subject.to_h) expect(JSON.parse(json)["headers"]).to include("Foo"=>"Tekirda�") end @@ -192,7 +192,7 @@ def to_s env.merge!(::Rack::RACK_INPUT => StringIO.new("あ")) expect do - JSON.generate(subject.to_hash) + JSON.generate(subject.to_h) end.not_to raise_error end diff --git a/sentry-ruby/spec/sentry/interfaces/stacktrace_builder_spec.rb b/sentry-ruby/spec/sentry/interfaces/stacktrace_builder_spec.rb index 77a33fee8..fa46f5809 100644 --- a/sentry-ruby/spec/sentry/interfaces/stacktrace_builder_spec.rb +++ b/sentry-ruby/spec/sentry/interfaces/stacktrace_builder_spec.rb @@ -97,17 +97,4 @@ end end end - - describe '#metrics_code_location' do - it 'builds metrics code location hash for line' do - hash = subject.metrics_code_location(backtrace.first) - - expect(hash[:filename]).to match(/stacktrace_test_fixture.rb/) - expect(hash[:function]).to eq("bar") - expect(hash[:lineno]).to eq(8) - expect(hash[:pre_context]).to eq(["end\n", "\n", "def bar\n"]) - expect(hash[:context_line]).to eq(" baz\n") - expect(hash[:post_context]).to eq(["end\n", nil, nil]) - end - end end diff --git a/sentry-ruby/spec/sentry/log_event_spec.rb b/sentry-ruby/spec/sentry/log_event_spec.rb index f2580c495..0591c1dd7 100644 --- a/sentry-ruby/spec/sentry/log_event_spec.rb +++ b/sentry-ruby/spec/sentry/log_event_spec.rb @@ -48,7 +48,7 @@ end end - describe "#to_hash" do + describe "#to_h" do before do configuration.release = "1.2.3" configuration.environment = "test" @@ -65,7 +65,7 @@ attributes: attributes ) - hash = event.to_hash + hash = event.to_h expect(hash[:body]).to eq("Hello John, today is Monday") @@ -82,7 +82,7 @@ body: "User John has logged in!" ) - hash = event.to_hash + hash = event.to_h expect(hash[:level]).to eq("info") expect(hash[:body]).to eq("User John has logged in!") @@ -102,7 +102,7 @@ body: "User John has logged in!" ) - hash = event.to_hash + hash = event.to_h expect(hash[:attributes]).not_to have_key("sentry.message.template") end @@ -114,7 +114,7 @@ body: "Hello %{name}, today is %{day}" ) - hash = event.to_hash + hash = event.to_h expect(hash[:attributes]).not_to have_key("sentry.message.template") expect(hash[:attributes]).not_to have_key("sentry.message.parameter.name") @@ -133,7 +133,7 @@ attributes: attributes ) - hash = event.to_hash + hash = event.to_h expect(hash[:attributes]).to have_key("sentry.message.template") expect(hash[:attributes]["sentry.message.template"]).to eq({ value: "User %s has logged in!", type: "string" }) @@ -155,7 +155,7 @@ attributes: attributes ) - hash = event.to_hash + hash = event.to_h expect(hash[:attributes]["string_attr"]).to eq({ value: "string value", type: "string" }) expect(hash[:attributes]["integer_attr"]).to eq({ value: 42, type: "integer" }) @@ -177,7 +177,7 @@ user: user ) - hash = event.to_hash + hash = event.to_h expect(hash[:attributes]["user.id"]).to eq(123) expect(hash[:attributes]["user.name"]).to eq("john_doe") @@ -192,7 +192,7 @@ origin: "auto.db.rails" ) - hash = event.to_hash + hash = event.to_h expect(hash[:attributes]["sentry.origin"]).to eq({ value: "auto.db.rails", type: "string" }) end @@ -204,7 +204,7 @@ body: "Manual log message" ) - hash = event.to_hash + hash = event.to_h expect(hash[:attributes]).not_to have_key("sentry.origin") end diff --git a/sentry-ruby/spec/sentry/metrics/aggregator_spec.rb b/sentry-ruby/spec/sentry/metrics/aggregator_spec.rb deleted file mode 100644 index 6094578e9..000000000 --- a/sentry-ruby/spec/sentry/metrics/aggregator_spec.rb +++ /dev/null @@ -1,485 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Sentry::Metrics::Aggregator do - let(:string_io) { StringIO.new } - - # fix at 3 second offset to check rollup - let(:fake_time) { Time.new(2024, 1, 1, 1, 1, 3) } - - before do - perform_basic_setup do |config| - config.metrics.enabled = true - config.traces_sample_rate = 1.0 - config.release = 'test-release' - config.environment = 'test' - config.sdk_logger = Logger.new(string_io) - end - end - - subject { Sentry.metrics_aggregator } - - describe '#add' do - it 'spawns new thread' do - expect { subject.add(:c, 'incr', 1) }.to change { Thread.list.count }.by(1) - expect(subject.thread).to be_a(Thread) - end - - it 'spawns only one thread' do - expect { subject.add(:c, 'incr', 1) }.to change { Thread.list.count }.by(1) - - expect(subject.thread).to receive(:alive?).and_call_original - expect { subject.add(:c, 'incr', 1) }.to change { Thread.list.count }.by(0) - end - - context 'when thread creation fails' do - before do - expect(Thread).to receive(:new).and_raise(ThreadError) - end - - it 'does not create new thread' do - expect { subject.add(:c, 'incr', 1) }.to change { Thread.list.count }.by(0) - end - - it 'noops' do - subject.add(:c, 'incr', 1) - expect(subject.buckets).to eq({}) - end - - it 'logs error' do - subject.add(:c, 'incr', 1) - expect(string_io.string).to include("[#{described_class.name}] thread creation failed") - end - end - - context 'when killed' do - before { subject.kill } - - it 'noops' do - subject.add(:c, 'incr', 1) - expect(subject.buckets).to eq({}) - end - - it 'does not create new thread' do - expect(Thread).not_to receive(:new) - expect { subject.add(:c, 'incr', 1) }.to change { Thread.list.count }.by(0) - end - end - - it 'does not add unsupported metric type' do - subject.add(:foo, 'foo', 1) - expect(subject.buckets).to eq({}) - end - - it 'has the correct bucket timestamp key rolled up to 10 seconds' do - allow(Time).to receive(:now).and_return(fake_time) - subject.add(:c, 'incr', 1) - expect(subject.buckets.keys.first).to eq(fake_time.to_i - 3) - end - - it 'has the correct bucket timestamp key rolled up to 10 seconds when passed explicitly' do - subject.add(:c, 'incr', 1, timestamp: fake_time + 9) - expect(subject.buckets.keys.first).to eq(fake_time.to_i + 7) - end - - it 'has the correct type in the bucket metric key' do - subject.add(:c, 'incr', 1) - type, _, _, _ = subject.buckets.values.first.keys.first - expect(type).to eq(:c) - end - - it 'has the correct key in the bucket metric key' do - subject.add(:c, 'incr', 1) - _, key, _, _ = subject.buckets.values.first.keys.first - expect(key).to eq('incr') - end - - it 'has the default unit \'none\' in the bucket metric key' do - subject.add(:c, 'incr', 1) - _, _, unit, _ = subject.buckets.values.first.keys.first - expect(unit).to eq('none') - end - - it 'has the correct custom unit in the bucket metric key' do - subject.add(:c, 'incr', 1, unit: 'second') - _, _, unit, _ = subject.buckets.values.first.keys.first - expect(unit).to eq('second') - end - - it 'has the correct default tags serialized in the bucket metric key' do - subject.add(:c, 'incr', 1) - _, _, _, tags = subject.buckets.values.first.keys.first - expect(tags).to eq([['environment', 'test'], ['release', 'test-release']]) - end - - it 'has the correct custom tags serialized in the bucket metric key' do - subject.add(:c, 'incr', 1, tags: { foo: 42 }) - _, _, _, tags = subject.buckets.values.first.keys.first - expect(tags).to include(['foo', '42']) - end - - it 'has the correct array value tags serialized in the bucket metric key' do - subject.add(:c, 'incr', 1, tags: { foo: [42, 43] }) - _, _, _, tags = subject.buckets.values.first.keys.first - expect(tags).to include(['foo', '42'], ['foo', '43']) - end - - context 'with running transaction' do - it 'has the transaction name in tags serialized in the bucket metric key' do - Sentry.get_current_scope.set_transaction_name('foo') - subject.add(:c, 'incr', 1) - _, _, _, tags = subject.buckets.values.first.keys.first - expect(tags).to include(['transaction', 'foo']) - end - - it 'does not has the low quality transaction name in tags serialized in the bucket metric key' do - Sentry.get_current_scope.set_transaction_name('foo', source: :url) - subject.add(:c, 'incr', 1) - _, _, _, tags = subject.buckets.values.first.keys.first - expect(tags).not_to include(['transaction', 'foo']) - end - end - - it 'creates a new CounterMetric instance if not existing' do - expect(Sentry::Metrics::CounterMetric).to receive(:new).and_call_original - subject.add(:c, 'incr', 1) - - metric = subject.buckets.values.first.values.first - expect(metric).to be_a(Sentry::Metrics::CounterMetric) - expect(metric.value).to eq(1.0) - end - - it 'reuses the existing CounterMetric instance' do - allow(Time).to receive(:now).and_return(fake_time) - - subject.add(:c, 'incr', 1) - metric = subject.buckets.values.first.values.first - expect(metric.value).to eq(1.0) - - expect(Sentry::Metrics::CounterMetric).not_to receive(:new) - expect(metric).to receive(:add).with(2).and_call_original - subject.add(:c, 'incr', 2) - expect(metric.value).to eq(3.0) - end - - it 'creates a new DistributionMetric instance if not existing' do - expect(Sentry::Metrics::DistributionMetric).to receive(:new).and_call_original - subject.add(:d, 'dist', 1) - - metric = subject.buckets.values.first.values.first - expect(metric).to be_a(Sentry::Metrics::DistributionMetric) - expect(metric.value).to eq([1.0]) - end - - it 'creates a new GaugeMetric instance if not existing' do - expect(Sentry::Metrics::GaugeMetric).to receive(:new).and_call_original - subject.add(:g, 'gauge', 1) - - metric = subject.buckets.values.first.values.first - expect(metric).to be_a(Sentry::Metrics::GaugeMetric) - expect(metric.serialize).to eq([1.0, 1.0, 1.0, 1.0, 1]) - end - - it 'creates a new SetMetric instance if not existing' do - expect(Sentry::Metrics::SetMetric).to receive(:new).and_call_original - subject.add(:s, 'set', 1) - - metric = subject.buckets.values.first.values.first - expect(metric).to be_a(Sentry::Metrics::SetMetric) - expect(metric.value).to eq(Set[1]) - end - - describe 'with before_emit callback' do - before do - perform_basic_setup do |config| - config.metrics.enabled = true - config.traces_sample_rate = 1.0 - config.release = 'test-release' - config.environment = 'test' - config.sdk_logger = Logger.new(string_io) - - config.metrics.before_emit = lambda do |key, tags| - return nil if key == 'foo' - tags[:add_tag] = 42 - tags.delete(:remove_tag) - true - end - end - end - - it 'does not emit metric with filtered key' do - expect(Sentry::Metrics::CounterMetric).not_to receive(:new) - subject.add(:c, 'foo', 1) - expect(subject.buckets).to eq({}) - end - - it 'updates the tags according to the callback' do - subject.add(:c, 'bar', 1, tags: { remove_tag: 99 }) - _, _, _, tags = subject.buckets.values.first.keys.first - expect(tags).not_to include(['remove_tag', '99']) - expect(tags).to include(['add_tag', '42']) - end - end - - describe 'local aggregation for span metric summaries' do - it 'does nothing without an active scope span' do - expect_any_instance_of(Sentry::Metrics::LocalAggregator).not_to receive(:add) - subject.add(:c, 'incr', 1) - end - - context 'with running transaction and active span' do - let(:span) { Sentry.start_transaction } - - before do - Sentry.get_current_scope.set_span(span) - Sentry.get_current_scope.set_transaction_name('metric', source: :view) - end - - it 'does nothing if transaction name is low quality' do - expect_any_instance_of(Sentry::Metrics::LocalAggregator).not_to receive(:add) - - Sentry.get_current_scope.set_transaction_name('/123', source: :url) - subject.add(:c, 'incr', 1) - end - - it 'proxies bucket key and value to local aggregator' do - expect(span.metrics_local_aggregator).to receive(:add).with( - array_including(:c, 'incr', 'none'), - 1 - ) - subject.add(:c, 'incr', 1) - end - - context 'for set metrics' do - before { subject.add(:s, 'set', 'foo') } - - it 'proxies bucket key and value 0 when existing element' do - expect(span.metrics_local_aggregator).to receive(:add).with( - array_including(:s, 'set', 'none'), - 0 - ) - subject.add(:s, 'set', 'foo') - end - - it 'proxies bucket key and value 1 when new element' do - expect(span.metrics_local_aggregator).to receive(:add).with( - array_including(:s, 'set', 'none'), - 1 - ) - subject.add(:s, 'set', 'bar') - end - end - end - end - - describe 'code location reporting' do - it 'does not record location if off' do - perform_basic_setup do |config| - config.metrics.enabled = true - config.metrics.enable_code_locations = false - end - - subject.add(:c, 'incr', 1) - expect(subject.code_locations).to eq({}) - end - - it 'records the code location with a timestamp for the day' do - subject.add(:c, 'incr', 1, unit: 'second', stacklevel: 3) - - timestamp = Time.now.utc - start_of_day = Time.utc(timestamp.year, timestamp.month, timestamp.day).to_i - expect(subject.code_locations.keys.first).to eq(start_of_day) - end - - it 'has the code location keyed with mri (metric resource identifier) from type/key/unit' do - subject.add(:c, 'incr', 1, unit: 'second', stacklevel: 3) - mri = subject.code_locations.values.first.keys.first - expect(mri).to eq([:c, 'incr', 'second']) - end - - it 'has the code location information in the hash' do - subject.add(:c, 'incr', 1, unit: 'second', stacklevel: 3) - - location = subject.code_locations.values.first.values.first - expect(location).to include(:abs_path, :filename, :pre_context, :context_line, :post_context, :lineno) - expect(location[:abs_path]).to match(/aggregator_spec.rb/) - expect(location[:filename]).to match(/aggregator_spec.rb/) - expect(location[:context_line]).to include("subject.add(:c, 'incr', 1, unit: 'second', stacklevel: 3)") - end - - it 'does not add code location for the same mri twice' do - subject.add(:c, 'incr', 1, unit: 'second', stacklevel: 3) - subject.add(:c, 'incr', 1, unit: 'second', stacklevel: 3) - expect(subject.code_locations.values.first.size).to eq(1) - end - - it 'adds code location for different mris twice' do - subject.add(:c, 'incr', 1, unit: 'second', stacklevel: 3) - subject.add(:c, 'incr', 1, unit: 'none', stacklevel: 3) - expect(subject.code_locations.values.first.size).to eq(2) - end - end - end - - describe '#flush' do - context 'with empty buckets and empty locations' do - it 'returns early and does nothing' do - expect(sentry_envelopes.count).to eq(0) - subject.flush - end - - it 'returns early and does nothing with force' do - expect(sentry_envelopes.count).to eq(0) - subject.flush(force: true) - end - end - - context 'with pending buckets' do - before do - allow(Time).to receive(:now).and_return(fake_time) - 10.times { subject.add(:c, 'incr', 1) } - 5.times { |i| subject.add(:d, 'disöt', i, unit: 'second', tags: { "foö$-bar" => "snöwmän% 23{}" }) } - - allow(Time).to receive(:now).and_return(fake_time + 9) - 5.times { subject.add(:c, 'incr', 1) } - 5.times { |i| subject.add(:d, 'disöt', i + 5, unit: 'second', tags: { "foö$-bar" => "snöwmän% 23{}" }) } - - expect(subject.buckets.keys).to eq([fake_time.to_i - 3, fake_time.to_i + 7]) - expect(subject.buckets.values[0].length).to eq(2) - expect(subject.buckets.values[1].length).to eq(2) - - # set the time such that the first set of metrics above are picked - allow(Time).to receive(:now).and_return(fake_time + 9 + subject.flush_shift) - end - - context 'without force' do - it 'updates the pending buckets in place' do - subject.flush - - expect(subject.buckets.keys).to eq([fake_time.to_i + 7]) - expect(subject.buckets.values[0].length).to eq(2) - end - - it 'empties the pending code locations in place' do - subject.flush - expect(subject.code_locations).to eq({}) - end - - it 'captures the envelope' do - expect(subject.client).to receive(:capture_envelope) - subject.flush - end - - it 'sends the flushable buckets in statsd envelope item with correct payload' do - subject.flush - - envelope = sentry_envelopes.first - expect(envelope.headers).to eq({}) - - item = envelope.items.first - expect(item.headers).to eq({ type: 'statsd', length: item.payload.bytesize }) - - incr, dist = item.payload.split("\n") - expect(incr).to eq("incr@none:10.0|c|#environment:test,release:test-release|T#{fake_time.to_i - 3}") - expect(dist).to eq("dis_t@second:0.0:1.0:2.0:3.0:4.0|d|" + - "#environment:test,fo-bar:snöwmän% 23{},release:test-release|" + - "T#{fake_time.to_i - 3}") - end - - it 'sends the pending code locations in metric_meta envelope item with correct payload' do - subject.flush - - envelope = sentry_envelopes.first - expect(envelope.headers).to eq({}) - - item = envelope.items.last - expect(item.headers).to eq({ type: 'metric_meta', content_type: 'application/json' }) - expect(item.payload[:timestamp]).to be_a(Integer) - - mapping = item.payload[:mapping] - expect(mapping.keys).to eq(['c:incr@none', 'd:dis_t@second']) - - location_1 = mapping['c:incr@none'].first - expect(location_1[:type]).to eq('location') - expect(location_1).to include(:abs_path, :filename, :lineno) - - location_2 = mapping['d:dis_t@second'].first - expect(location_2[:type]).to eq('location') - expect(location_2).to include(:abs_path, :filename, :lineno) - end - end - - context 'with force' do - it 'empties the pending buckets in place' do - subject.flush(force: true) - expect(subject.buckets).to eq({}) - end - - it 'captures the envelope' do - expect(Sentry.background_worker).to receive(:perform) - subject.flush(force: true) - end - - it 'sends all buckets in statsd envelope item with correct payload' do - subject.flush(force: true) - - envelope = sentry_envelopes.first - expect(envelope.headers).to eq({}) - - item = envelope.items.first - expect(item.headers).to eq({ type: 'statsd', length: item.payload.bytesize }) - - incr1, dist1, incr2, dist2 = item.payload.split("\n") - expect(incr1).to eq("incr@none:10.0|c|#environment:test,release:test-release|T#{fake_time.to_i - 3}") - expect(dist1).to eq("dis_t@second:0.0:1.0:2.0:3.0:4.0|d|" + - "#environment:test,fo-bar:snöwmän% 23{},release:test-release|" + - "T#{fake_time.to_i - 3}") - expect(incr2).to eq("incr@none:5.0|c|#environment:test,release:test-release|T#{fake_time.to_i + 7}") - expect(dist2).to eq("dis_t@second:5.0:6.0:7.0:8.0:9.0|d|" + - "#environment:test,fo-bar:snöwmän% 23{},release:test-release|" + - "T#{fake_time.to_i + 7}") - end - end - end - - context 'sanitization' do - it 'sanitizes the metric key' do - subject.add(:c, 'foo.disöt_12-bar', 1) - subject.flush(force: true) - - sanitized_key = 'foo.dis_t_12-bar' - statsd, metrics_meta = sentry_envelopes.first.items.map(&:payload) - expect(statsd).to include(sanitized_key) - expect(metrics_meta[:mapping].keys.first).to include(sanitized_key) - end - - it 'sanitizes the metric unit' do - subject.add(:c, 'incr', 1, unit: 'disöt_12-/.test') - subject.flush(force: true) - - sanitized_unit = '@dist_12test' - statsd, metrics_meta = sentry_envelopes.first.items.map(&:payload) - expect(statsd).to include(sanitized_unit) - expect(metrics_meta[:mapping].keys.first).to include(sanitized_unit) - end - - it 'sanitizes tag keys and values' do - tags = { "get.foö-$bar/12" => "hello!\n\r\t\\ 42 this | or , that" } - subject.add(:c, 'incr', 1, tags: tags) - subject.flush(force: true) - - sanitized_tags = "get.fo-bar/12:hello!\\n\\r\\t\\\\ 42 this \\u{7c} or \\u{2c} that" - statsd = sentry_envelopes.first.items.first.payload - expect(statsd).to include(sanitized_tags) - end - end - end - - describe '#kill' do - before { subject.add(:c, 'incr', 1) } - it 'logs message when killing the thread' do - expect(subject.thread).to receive(:kill) - subject.kill - expect(string_io.string).to include("[#{described_class.name}] thread killed") - end - end -end diff --git a/sentry-ruby/spec/sentry/metrics/configuration_spec.rb b/sentry-ruby/spec/sentry/metrics/configuration_spec.rb deleted file mode 100644 index ca7e7f9e6..000000000 --- a/sentry-ruby/spec/sentry/metrics/configuration_spec.rb +++ /dev/null @@ -1,26 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Sentry::Metrics::Configuration do - let(:string_io) { StringIO.new } - let(:sdk_logger) { Logger.new(string_io) } - - let(:subject) { described_class.new(sdk_logger) } - - describe '#enabled=' do - it 'logs deprecation warning' do - subject.enabled = true - - expect(string_io.string).to include( - "WARN -- sentry: `config.metrics` is now deprecated and will be removed in the next major." - ) - end - end - - describe '#before_emit=' do - it 'raises error when setting before_emit to anything other than callable or nil' do - subject.before_emit = -> { } - subject.before_emit = nil - expect { subject.before_emit = true }.to raise_error(ArgumentError, 'metrics.before_emit must be callable (or nil to disable)') - end - end -end diff --git a/sentry-ruby/spec/sentry/metrics/counter_metric_spec.rb b/sentry-ruby/spec/sentry/metrics/counter_metric_spec.rb deleted file mode 100644 index 198679ed9..000000000 --- a/sentry-ruby/spec/sentry/metrics/counter_metric_spec.rb +++ /dev/null @@ -1,25 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Sentry::Metrics::CounterMetric do - subject { described_class.new(1) } - before { subject.add(2) } - - describe '#add' do - it 'adds float value' do - subject.add(3.0) - expect(subject.value).to eq(6.0) - end - end - - describe '#serialize' do - it 'returns value in array' do - expect(subject.serialize).to eq([3.0]) - end - end - - describe '#weight' do - it 'returns fixed value of 1' do - expect(subject.weight).to eq(1) - end - end -end diff --git a/sentry-ruby/spec/sentry/metrics/distribution_metric_spec.rb b/sentry-ruby/spec/sentry/metrics/distribution_metric_spec.rb deleted file mode 100644 index 832cb917b..000000000 --- a/sentry-ruby/spec/sentry/metrics/distribution_metric_spec.rb +++ /dev/null @@ -1,25 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Sentry::Metrics::DistributionMetric do - subject { described_class.new(1) } - before { subject.add(2) } - - describe '#add' do - it 'appends float value to array' do - subject.add(3.0) - expect(subject.value).to eq([1.0, 2.0, 3.0]) - end - end - - describe '#serialize' do - it 'returns whole array' do - expect(subject.serialize).to eq([1.0, 2.0]) - end - end - - describe '#weight' do - it 'returns length of array' do - expect(subject.weight).to eq(2) - end - end -end diff --git a/sentry-ruby/spec/sentry/metrics/gauge_metric_spec.rb b/sentry-ruby/spec/sentry/metrics/gauge_metric_spec.rb deleted file mode 100644 index d043bb7f8..000000000 --- a/sentry-ruby/spec/sentry/metrics/gauge_metric_spec.rb +++ /dev/null @@ -1,29 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Sentry::Metrics::GaugeMetric do - subject { described_class.new(0) } - before { 9.times { |i| subject.add(i + 1) } } - - describe '#add' do - it 'appends float value to array' do - subject.add(11) - expect(subject.last).to eq(11.0) - expect(subject.min).to eq(0.0) - expect(subject.max).to eq(11.0) - expect(subject.sum).to eq(56.0) - expect(subject.count).to eq(11) - end - end - - describe '#serialize' do - it 'returns array of statistics' do - expect(subject.serialize).to eq([9.0, 0.0, 9.0, 45.0, 10]) - end - end - - describe '#weight' do - it 'returns fixed value of 5' do - expect(subject.weight).to eq(5) - end - end -end diff --git a/sentry-ruby/spec/sentry/metrics/local_aggregator_spec.rb b/sentry-ruby/spec/sentry/metrics/local_aggregator_spec.rb deleted file mode 100644 index a41280d6e..000000000 --- a/sentry-ruby/spec/sentry/metrics/local_aggregator_spec.rb +++ /dev/null @@ -1,83 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Sentry::Metrics::LocalAggregator do - let(:tags) { [['foo', 1], ['foo', 2], ['bar', 'baz']] } - let(:key) { [:c, 'incr', 'second', tags] } - let(:key2) { [:s, 'set', 'none', []] } - - describe '#add' do - it 'creates new GaugeMetric and adds it to bucket if key not existing' do - expect(Sentry::Metrics::GaugeMetric).to receive(:new).with(10).and_call_original - - subject.add(key, 10) - - metric = subject.buckets[key] - expect(metric).to be_a(Sentry::Metrics::GaugeMetric) - expect(metric.last).to eq(10.0) - expect(metric.min).to eq(10.0) - expect(metric.max).to eq(10.0) - expect(metric.sum).to eq(10.0) - expect(metric.count).to eq(1) - end - - it 'adds value to existing GaugeMetric' do - subject.add(key, 10) - - metric = subject.buckets[key] - expect(metric).to be_a(Sentry::Metrics::GaugeMetric) - expect(metric).to receive(:add).with(20).and_call_original - expect(Sentry::Metrics::GaugeMetric).not_to receive(:new) - - subject.add(key, 20) - expect(metric.last).to eq(20.0) - expect(metric.min).to eq(10.0) - expect(metric.max).to eq(20.0) - expect(metric.sum).to eq(30.0) - expect(metric.count).to eq(2) - end - end - - describe '#to_hash' do - it 'returns nil if empty buckets' do - expect(subject.to_hash).to eq(nil) - end - - context 'with filled buckets' do - before do - subject.add(key, 10) - subject.add(key, 20) - subject.add(key2, 1) - end - - it 'has the correct payload keys in the hash' do - expect(subject.to_hash.keys).to eq([ - 'c:incr@second', - 's:set@none' - ]) - end - - it 'has the tags deserialized correctly with array values' do - expect(subject.to_hash['c:incr@second'][:tags]).to eq({ - 'foo' => [1, 2], - 'bar' => 'baz' - }) - end - - it 'has the correct gauge metric values' do - expect(subject.to_hash['c:incr@second']).to include({ - min: 10.0, - max: 20.0, - count: 2, - sum: 30.0 - }) - - expect(subject.to_hash['s:set@none']).to include({ - min: 1.0, - max: 1.0, - count: 1, - sum: 1.0 - }) - end - end - end -end diff --git a/sentry-ruby/spec/sentry/metrics/metric_spec.rb b/sentry-ruby/spec/sentry/metrics/metric_spec.rb deleted file mode 100644 index 787d1cb24..000000000 --- a/sentry-ruby/spec/sentry/metrics/metric_spec.rb +++ /dev/null @@ -1,21 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Sentry::Metrics::Metric do - describe '#add' do - it 'raises not implemented error' do - expect { subject.add(1) }.to raise_error(NotImplementedError) - end - end - - describe '#serialize' do - it 'raises not implemented error' do - expect { subject.serialize }.to raise_error(NotImplementedError) - end - end - - describe '#weight' do - it 'raises not implemented error' do - expect { subject.weight }.to raise_error(NotImplementedError) - end - end -end diff --git a/sentry-ruby/spec/sentry/metrics/set_metric_spec.rb b/sentry-ruby/spec/sentry/metrics/set_metric_spec.rb deleted file mode 100644 index 59205c7ea..000000000 --- a/sentry-ruby/spec/sentry/metrics/set_metric_spec.rb +++ /dev/null @@ -1,30 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Sentry::Metrics::SetMetric do - subject { described_class.new('foo') } - - before do - 2.times { subject.add('foo') } - 2.times { subject.add('bar') } - 2.times { subject.add(42) } - end - - describe '#add' do - it 'appends new value to set' do - subject.add('baz') - expect(subject.value).to eq(Set['foo', 'bar', 'baz', 42]) - end - end - - describe '#serialize' do - it 'returns array of hashed values' do - expect(subject.serialize).to eq([Zlib.crc32('foo'), Zlib.crc32('bar'), 42]) - end - end - - describe '#weight' do - it 'returns length of set' do - expect(subject.weight).to eq(3) - end - end -end diff --git a/sentry-ruby/spec/sentry/metrics/timing_spec.rb b/sentry-ruby/spec/sentry/metrics/timing_spec.rb deleted file mode 100644 index dbc947e7a..000000000 --- a/sentry-ruby/spec/sentry/metrics/timing_spec.rb +++ /dev/null @@ -1,54 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Sentry::Metrics::Timing do - let(:fake_time) { Time.new(2024, 1, 2, 3, 4, 5) } - before { allow(Time).to receive(:now).and_return(fake_time) } - - describe '.nanosecond' do - it 'returns nanoseconds' do - expect(described_class.nanosecond).to eq(fake_time.to_i * 10 ** 9) - end - end - - describe '.microsecond' do - it 'returns microseconds' do - expect(described_class.microsecond).to eq(fake_time.to_i * 10 ** 6) - end - end - - describe '.millisecond' do - it 'returns milliseconds' do - expect(described_class.millisecond).to eq(fake_time.to_i * 10 ** 3) - end - end - - describe '.second' do - it 'returns seconds' do - expect(described_class.second).to eq(fake_time.to_i) - end - end - - describe '.minute' do - it 'returns minutes' do - expect(described_class.minute).to eq(fake_time.to_i / 60.0) - end - end - - describe '.hour' do - it 'returns hours' do - expect(described_class.hour).to eq(fake_time.to_i / 3600.0) - end - end - - describe '.day' do - it 'returns days' do - expect(described_class.day).to eq(fake_time.to_i / (3600.0 * 24.0)) - end - end - - describe '.week' do - it 'returns weeks' do - expect(described_class.week).to eq(fake_time.to_i / (3600.0 * 24.0 * 7.0)) - end - end -end diff --git a/sentry-ruby/spec/sentry/metrics_spec.rb b/sentry-ruby/spec/sentry/metrics_spec.rb deleted file mode 100644 index bca1aa196..000000000 --- a/sentry-ruby/spec/sentry/metrics_spec.rb +++ /dev/null @@ -1,180 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Sentry::Metrics do - let(:aggregator) { Sentry.metrics_aggregator } - let(:fake_time) { Time.new(2024, 1, 1, 1, 1, 3) } - let(:string_io) { StringIO.new } - let(:sdk_logger) { Logger.new(string_io) } - - before do - perform_basic_setup do |config| - config.metrics.enabled = true - config.sdk_logger = sdk_logger - end - end - - describe '.increment' do - it 'passes default value of 1.0 with only key' do - expect(aggregator).to receive(:add).with( - :c, - 'foo', - 1.0, - unit: 'none', - tags: {}, - timestamp: nil - ) - - described_class.increment('foo') - end - - it 'passes through args to aggregator' do - expect(aggregator).to receive(:add).with( - :c, - 'foo', - 5.0, - unit: 'second', - tags: { fortytwo: 42 }, - timestamp: fake_time - ) - - described_class.increment('foo', 5.0, unit: 'second', tags: { fortytwo: 42 }, timestamp: fake_time) - end - - it 'logs deprecation warning' do - described_class.increment('foo') - - expect(string_io.string).to include( - "WARN -- sentry: `Sentry::Metrics` is now deprecated and will be removed in the next major." - ) - end - end - - describe '.distribution' do - it 'passes through args to aggregator' do - expect(aggregator).to receive(:add).with( - :d, - 'foo', - 5.0, - unit: 'second', - tags: { fortytwo: 42 }, - timestamp: fake_time - ) - - described_class.distribution('foo', 5.0, unit: 'second', tags: { fortytwo: 42 }, timestamp: fake_time) - end - - it 'logs deprecation warning' do - described_class.distribution('foo', 5.0, unit: 'second', tags: { fortytwo: 42 }, timestamp: fake_time) - - expect(string_io.string).to include( - "WARN -- sentry: `Sentry::Metrics` is now deprecated and will be removed in the next major." - ) - end - end - - describe '.set' do - it 'passes through args to aggregator' do - expect(aggregator).to receive(:add).with( - :s, - 'foo', - 'jane', - unit: 'none', - tags: { fortytwo: 42 }, - timestamp: fake_time - ) - - described_class.set('foo', 'jane', tags: { fortytwo: 42 }, timestamp: fake_time) - end - - it 'logs deprecation warning' do - described_class.set('foo', 'jane', tags: { fortytwo: 42 }, timestamp: fake_time) - - expect(string_io.string).to include( - "WARN -- sentry: `Sentry::Metrics` is now deprecated and will be removed in the next major." - ) - end - end - - describe '.gauge' do - it 'passes through args to aggregator' do - expect(aggregator).to receive(:add).with( - :g, - 'foo', - 5.0, - unit: 'second', - tags: { fortytwo: 42 }, - timestamp: fake_time - ) - - described_class.gauge('foo', 5.0, unit: 'second', tags: { fortytwo: 42 }, timestamp: fake_time) - end - - it 'logs deprecation warning' do - described_class.gauge('foo', 5.0, unit: 'second', tags: { fortytwo: 42 }, timestamp: fake_time) - - expect(string_io.string).to include( - "WARN -- sentry: `Sentry::Metrics` is now deprecated and will be removed in the next major." - ) - end - end - - describe '.timing' do - it 'does nothing without a block' do - expect(aggregator).not_to receive(:add) - described_class.timing('foo') - end - - it 'does nothing with a non-duration unit' do - expect(aggregator).not_to receive(:add) - result = described_class.timing('foo', unit: 'ratio') { 42 } - expect(result).to eq(42) - end - - it 'measures time taken as distribution and passes through args to aggregator' do - expect(aggregator).to receive(:add).with( - :d, - 'foo', - an_instance_of(Integer), - unit: 'millisecond', - tags: { fortytwo: 42 }, - timestamp: fake_time - ) - - result = described_class.timing('foo', unit: 'millisecond', tags: { fortytwo: 42 }, timestamp: fake_time) { sleep(0.1); 42 } - expect(result).to eq(42) - end - - it 'logs deprecation warning' do - described_class.timing('foo', unit: 'millisecond', tags: { fortytwo: 42 }, timestamp: fake_time) { sleep(0.1); 42 } - - expect(string_io.string).to include( - "WARN -- sentry: `Sentry::Metrics` is now deprecated and will be removed in the next major." - ) - end - - context 'with running transaction' do - let(:transaction) { transaction = Sentry.start_transaction(name: 'metrics') } - - before do - perform_basic_setup do |config| - config.traces_sample_rate = 1.0 - config.metrics.enabled = true - end - - Sentry.get_current_scope.set_span(transaction) - end - - it 'starts a span' do - expect(Sentry).to receive(:with_child_span).with(op: Sentry::Metrics::OP_NAME, description: 'foo', origin: Sentry::Metrics::SPAN_ORIGIN).and_call_original - - described_class.timing('foo') { sleep(0.1) } - end - - it 'has the correct tags on the new span' do - described_class.timing('foo', tags: { a: 42, b: [1, 2] }) { sleep(0.1) } - span = transaction.span_recorder.spans.last - expect(span.tags).to eq(a: '42', b: '1, 2') - end - end - end -end diff --git a/sentry-ruby/spec/sentry/profiler_spec.rb b/sentry-ruby/spec/sentry/profiler_spec.rb index 310ae0d59..e5ca44cbe 100644 --- a/sentry-ruby/spec/sentry/profiler_spec.rb +++ b/sentry-ruby/spec/sentry/profiler_spec.rb @@ -148,25 +148,25 @@ end end - describe '#to_hash' do + describe '#to_h' do let (:transport) { Sentry.get_current_client.transport } context 'when not sampled' do before { subject.set_initial_sample_decision(false) } it 'returns nil' do - expect(subject.to_hash).to eq({}) + expect(subject.to_h).to eq({}) end it 'records lost event' do expect(transport).to receive(:record_lost_event).with(:sample_rate, 'profile') - subject.to_hash + subject.to_h end end it 'returns nil unless started' do subject.set_initial_sample_decision(true) - expect(subject.to_hash).to eq({}) + expect(subject.to_h).to eq({}) end context 'with empty results' do @@ -179,12 +179,12 @@ end it 'returns empty' do - expect(subject.to_hash).to eq({}) + expect(subject.to_h).to eq({}) end it 'records lost event' do expect(transport).to receive(:record_lost_event).with(:insufficient_data, 'profile') - subject.to_hash + subject.to_h end end @@ -204,12 +204,12 @@ end it 'returns empty' do - expect(subject.to_hash).to eq({}) + expect(subject.to_h).to eq({}) end it 'records lost event' do expect(transport).to receive(:record_lost_event).with(:insufficient_data, 'profile') - subject.to_hash + subject.to_h end end @@ -222,7 +222,7 @@ end it 'has correct attributes' do - hash = subject.to_hash + hash = subject.to_h expect(hash[:event_id]).to eq(subject.event_id) expect(hash[:platform]).to eq('ruby') @@ -231,7 +231,7 @@ end it 'has correct frames' do - frames = subject.to_hash[:profile][:frames] + frames = subject.to_h[:profile][:frames] foo_frame = frames.find { |f| f[:function] =~ /foo/ } expect(foo_frame[:function]).to eq('Foo.foo') @@ -267,7 +267,7 @@ end it 'has correct stacks' do - profile = subject.to_hash[:profile] + profile = subject.to_h[:profile] frames = profile[:frames] stacks = profile[:stacks] @@ -281,7 +281,7 @@ end it 'has correct samples' do - profile = subject.to_hash[:profile] + profile = subject.to_h[:profile] num_stacks = profile[:stacks].size samples = profile[:samples] last_elapsed = 0 diff --git a/sentry-ruby/spec/sentry/rack/capture_exceptions_spec.rb b/sentry-ruby/spec/sentry/rack/capture_exceptions_spec.rb index 10cfa197a..840545557 100644 --- a/sentry-ruby/spec/sentry/rack/capture_exceptions_spec.rb +++ b/sentry-ruby/spec/sentry/rack/capture_exceptions_spec.rb @@ -18,7 +18,7 @@ expect { stack.call(env) }.to raise_error(ZeroDivisionError) - event = last_sentry_event.to_hash + event = last_sentry_event.to_h expect(event.dig(:request, :url)).to eq("http://example.org/test") expect(env["sentry.error_event_id"]).to eq(event[:event_id]) last_frame = event.dig(:exception, :values, 0, :stacktrace, :frames).last @@ -31,7 +31,7 @@ expect { stack.call(env) }.to raise_error(ZeroDivisionError) - event = last_sentry_event.to_hash + event = last_sentry_event.to_h mechanism = event.dig(:exception, :values, 0, :mechanism) expect(mechanism).to eq({ type: 'rack', handled: false }) end @@ -49,7 +49,7 @@ event = last_sentry_event expect(env["sentry.error_event_id"]).to eq(event.event_id) - expect(event.to_hash.dig(:request, :url)).to eq("http://example.org/test") + expect(event.to_h.dig(:request, :url)).to eq("http://example.org/test") end it 'captures the exception from sinatra.error' do @@ -64,7 +64,7 @@ end.to change { sentry_events.count }.by(1) event = last_sentry_event - expect(event.to_hash.dig(:request, :url)).to eq("http://example.org/test") + expect(event.to_h.dig(:request, :url)).to eq("http://example.org/test") end it 'sets the transaction and rack env' do @@ -78,7 +78,7 @@ event = last_sentry_event expect(event.transaction).to eq("/test") - expect(event.to_hash.dig(:request, :url)).to eq("http://example.org/test") + expect(event.to_h.dig(:request, :url)).to eq("http://example.org/test") expect(Sentry.get_current_scope.transaction_name).to be_nil expect(Sentry.get_current_scope.rack_env).to eq({}) end @@ -115,7 +115,7 @@ expect { stack.call(env) }.to raise_error(ZeroDivisionError) - event = last_sentry_event.to_hash + event = last_sentry_event.to_h expect(event.dig(:request, :url)).to eq("http://example.org/test") last_frame = event.dig(:exception, :values, 0, :stacktrace, :frames).last expect(last_frame[:vars]).to include({ a: "1", b: "0" }) @@ -139,7 +139,7 @@ def inspect expect { stack.call(env) }.to raise_error(ZeroDivisionError) - event = last_sentry_event.to_hash + event = last_sentry_event.to_h expect(event.dig(:request, :url)).to eq("http://example.org/test") last_frame = event.dig(:exception, :values, 0, :stacktrace, :frames).last expect(last_frame[:vars]).to include({ a: "1", b: "0", f: "[ignored due to error]" }) @@ -157,7 +157,7 @@ def inspect expect { stack.call(env) }.to raise_error(ZeroDivisionError) - event = last_sentry_event.to_hash + event = last_sentry_event.to_h expect(event.dig(:request, :url)).to eq("http://example.org/test") last_frame = event.dig(:exception, :values, 0, :stacktrace, :frames).last expect(last_frame[:vars]).to include({ a: "1", b: "0", long: "*" * 1024 + "..." }) diff --git a/sentry-ruby/spec/sentry/scope_spec.rb b/sentry-ruby/spec/sentry/scope_spec.rb index 59dec2ee1..e67c1e51c 100644 --- a/sentry-ruby/spec/sentry/scope_spec.rb +++ b/sentry-ruby/spec/sentry/scope_spec.rb @@ -45,7 +45,7 @@ copy.set_transaction_name("foo", source: :url) copy.fingerprint << "bar" - expect(subject.breadcrumbs.to_hash).to eq({ values: [] }) + expect(subject.breadcrumbs.to_h).to eq({ values: [] }) expect(subject.contexts[:os].keys).to match_array([:name, :version, :build, :kernel_version, :machine]) expect(subject.contexts.dig(:runtime, :version)).to match(/ruby/) expect(subject.extra).to eq({}) @@ -246,7 +246,7 @@ scope.apply_to_event(log_event) - log_hash = log_event.to_hash + log_hash = log_event.to_h expect(log_hash[:attributes]["user.id"]).to eq(123) expect(log_hash[:attributes]["user.name"]).to eq("john_doe") @@ -257,7 +257,7 @@ scope = described_class.new scope.apply_to_event(log_event) - log_hash = log_event.to_hash + log_hash = log_event.to_h expect(log_hash[:attributes]).not_to have_key("user.id") expect(log_hash[:attributes]).not_to have_key("user.name") @@ -351,7 +351,7 @@ it "sets the request info the Event" do subject.apply_to_event(event) - expect(event.to_hash.dig(:request, :url)).to eq("http://example.org/test") + expect(event.to_h.dig(:request, :url)).to eq("http://example.org/test") end end end diff --git a/sentry-ruby/spec/sentry/span_spec.rb b/sentry-ruby/spec/sentry/span_spec.rb index 3a74d4673..8d65aeb9d 100644 --- a/sentry-ruby/spec/sentry/span_spec.rb +++ b/sentry-ruby/spec/sentry/span_spec.rb @@ -57,14 +57,14 @@ end end - describe "#to_hash" do + describe "#to_h" do before do subject.set_data("controller", "WelcomeController") subject.set_tag("foo", "bar") end it "returns correct data" do - hash = subject.to_hash + hash = subject.to_h expect(hash[:op]).to eq("sql.query") expect(hash[:description]).to eq("SELECT * FROM users;") @@ -75,16 +75,6 @@ expect(hash[:span_id].length).to eq(16) expect(hash[:origin]).to eq('manual') end - - it 'has metric summary if present' do - key = [:c, 'incr', 'none', []] - subject.metrics_local_aggregator.add(key, 10) - - hash = subject.to_hash - expect(hash[:_metrics_summary]).to eq({ - 'c:incr@none' => { count: 1, max: 10.0, min: 10.0, sum: 10.0, tags: {} } - }) - end end describe "#to_sentry_trace" do diff --git a/sentry-ruby/spec/sentry/transaction_spec.rb b/sentry-ruby/spec/sentry/transaction_spec.rb index 7adc67186..a70eb3aed 100644 --- a/sentry-ruby/spec/sentry/transaction_spec.rb +++ b/sentry-ruby/spec/sentry/transaction_spec.rb @@ -18,6 +18,9 @@ ) end + let(:string_io) { StringIO.new } + let(:sdk_logger) { Logger.new(string_io) } + describe ".from_sentry_trace" do let(:sentry_trace) { subject.to_sentry_trace } @@ -197,14 +200,9 @@ end describe "#set_initial_sample_decision" do - let(:string_io) { StringIO.new } - let(:logger) do - ::Logger.new(string_io) - end - before do perform_basic_setup do |config| - config.sdk_logger = logger + config.sdk_logger = sdk_logger end end @@ -392,9 +390,9 @@ end end - describe "#to_hash" do + describe "#to_h" do it "returns correct data" do - hash = subject.to_hash + hash = subject.to_h expect(hash[:op]).to eq("sql.query") expect(hash[:description]).to eq("SELECT * FROM users;") @@ -421,7 +419,7 @@ subject.finish expect(events.count).to eq(1) - event = events.last.to_hash + event = events.last.to_h # don't contain itself expect(event[:spans]).to be_empty @@ -431,7 +429,7 @@ subject.finish expect(events.count).to eq(1) - event = events.last.to_hash + event = events.last.to_h expect(event[:transaction]).to eq("foo") end @@ -441,7 +439,7 @@ subject.finish(end_timestamp: timestamp) expect(events.count).to eq(1) - event = events.last.to_hash + event = events.last.to_h expect(event[:timestamp]).to eq(timestamp) end @@ -454,7 +452,7 @@ subject.finish expect(events.count).to eq(1) - event = events.last.to_hash + event = events.last.to_h expect(event[:tags]).to eq({ foo: 'bar', name: "apple" }) end @@ -550,12 +548,59 @@ subject.set_measurement("metric.foo", 0.5, "second") subject.finish - transaction = events.last.to_hash + transaction = events.last.to_h expect(transaction[:measurements]).to eq( { "metric.foo" => { value: 0.5, unit: "second" } } ) end end + + describe "with trace_ignore_status_codes" do + before do + perform_basic_setup do |config| + config.traces_sample_rate = 1.0 + config.sdk_logger = sdk_logger + config.trace_ignore_status_codes = [404, (500..503)] + end + end + + it "drops transaction with individual status code match" do + subject.set_http_status(404) + subject.finish + + expect(sentry_events).to be_empty + expect(Sentry.get_current_client.transport).to have_recorded_lost_event(:event_processor, 'transaction') + expect(Sentry.get_current_client.transport).to have_recorded_lost_event(:event_processor, 'span') + expect(string_io.string).to include("Discarding") + expect(string_io.string).to include("due to ignored HTTP status code: 404") + end + + it "drops transaction with range status code match" do + subject.set_http_status(502) + subject.finish + + expect(sentry_events).to be_empty + expect(Sentry.get_current_client.transport).to have_recorded_lost_event(:event_processor, 'transaction') + expect(Sentry.get_current_client.transport).to have_recorded_lost_event(:event_processor, 'span') + expect(string_io.string).to include("Discarding") + expect(string_io.string).to include("due to ignored HTTP status code: 502") + end + + it "does not drop transaction with status code outside ignore list" do + subject.set_http_status(200) + subject.finish + + expect(sentry_events).not_to be_empty + expect(sentry_events.last).to be_a(Sentry::TransactionEvent) + end + + it "does not drop transaction without a status code set" do + subject.finish + + expect(sentry_events).not_to be_empty + expect(sentry_events.first).to be_a(Sentry::TransactionEvent) + end + end end describe "#get_baggage" do diff --git a/sentry-ruby/spec/sentry/transport/http_transport_rate_limiting_spec.rb b/sentry-ruby/spec/sentry/transport/http_transport_rate_limiting_spec.rb index d1c1081d6..02d90f23f 100644 --- a/sentry-ruby/spec/sentry/transport/http_transport_rate_limiting_spec.rb +++ b/sentry-ruby/spec/sentry/transport/http_transport_rate_limiting_spec.rb @@ -15,7 +15,7 @@ let(:configuration) { Sentry.configuration } let(:client) { Sentry.get_current_client } let(:data) do - subject.envelope_from_event(client.event_from_message("foobarbaz").to_hash).to_s + subject.envelope_from_event(client.event_from_message("foobarbaz")).to_s end subject { Sentry::HTTPTransport.new(configuration) } diff --git a/sentry-ruby/spec/sentry/transport/http_transport_spec.rb b/sentry-ruby/spec/sentry/transport/http_transport_spec.rb index 7b4b39b97..170660b76 100644 --- a/sentry-ruby/spec/sentry/transport/http_transport_spec.rb +++ b/sentry-ruby/spec/sentry/transport/http_transport_spec.rb @@ -15,7 +15,7 @@ let(:event) { client.event_from_message("foobarbaz") } let(:fake_time) { Time.now } let(:data) do - subject.serialize_envelope(subject.envelope_from_event(event.to_hash)).first + subject.serialize_envelope(subject.envelope_from_event(event)).first end subject { client.transport } diff --git a/sentry-ruby/spec/sentry/transport/spotlight_transport_spec.rb b/sentry-ruby/spec/sentry/transport/spotlight_transport_spec.rb index 2b54a7fd3..d6ae7bf95 100644 --- a/sentry-ruby/spec/sentry/transport/spotlight_transport_spec.rb +++ b/sentry-ruby/spec/sentry/transport/spotlight_transport_spec.rb @@ -18,7 +18,7 @@ let(:client) { Sentry::Client.new(configuration) } let(:event) { client.event_from_message("foobarbaz") } let(:data) do - subject.serialize_envelope(subject.envelope_from_event(event.to_hash)).first + subject.serialize_envelope(subject.envelope_from_event(event)).first end subject { described_class.new(configuration) } diff --git a/sentry-ruby/spec/sentry/transport_spec.rb b/sentry-ruby/spec/sentry/transport_spec.rb index 002ede4f5..227f27409 100644 --- a/sentry-ruby/spec/sentry/transport_spec.rb +++ b/sentry-ruby/spec/sentry/transport_spec.rb @@ -54,7 +54,7 @@ '{"type":"event","content_type":"application/json"}' ) - expect(item).to eq(event.to_hash.to_json) + expect(item).to eq(event.to_h.to_json) end end @@ -89,7 +89,7 @@ '{"type":"transaction","content_type":"application/json"}' ) - expect(item).to eq(event.to_hash.to_json) + expect(item).to eq(event.to_h.to_json) end context "with profiling on transaction" do @@ -211,30 +211,6 @@ end end - context "metrics/statsd item" do - let(:payload) do - "foo@none:10.0|c|#tag1:42,tag2:bar|T1709042970\n" + - "bar@second:0.3:0.1:0.9:49.8:100|g|#|T1709042980" - end - - let(:envelope) do - envelope = Sentry::Envelope.new - envelope.add_item( - { type: 'statsd', length: payload.bytesize }, - payload - ) - envelope - end - - it "adds raw payload to envelope item" do - result, _ = subject.serialize_envelope(envelope) - item = result.split("\n", 2).last - item_header, item_payload = item.split("\n", 2) - expect(JSON.parse(item_header)).to eq({ 'type' => 'statsd', 'length' => 93 }) - expect(item_payload).to eq(payload) - end - end - context "log events" do let(:log_events) do 5.times.map do |i| @@ -260,7 +236,7 @@ item_count: log_events.size, content_type: "application/vnd.sentry.items.log+json" }, - { items: log_events.map(&:to_hash) } + { items: log_events.map(&:to_h) } ) envelope @@ -309,7 +285,7 @@ it "gracefully removes bad encoding breadcrumb message" do expect do - JSON.generate(event.to_hash) + JSON.generate(event.to_h) end.not_to raise_error end end @@ -324,7 +300,7 @@ 1000.times do |i| event.breadcrumbs.record Sentry::Breadcrumb.new(category: i.to_s, message: "x" * Sentry::Event::MAX_MESSAGE_SIZE_IN_BYTES) end - serialized_result = JSON.generate(event.to_hash) + serialized_result = JSON.generate(event.to_h) expect(serialized_result.bytesize).to be > Sentry::Envelope::Item::MAX_SERIALIZED_PAYLOAD_SIZE end @@ -353,79 +329,6 @@ end end end - - context "due to stacktrace frames" do - let(:event) { client.event_from_exception(SystemStackError.new("stack level too deep")) } - let(:envelope) { subject.envelope_from_event(event) } - - let(:in_app_pattern) do - project_root = "/fake/project_root" - Regexp.new("^(#{project_root}/)?#{Sentry::Configuration::APP_DIRS_PATTERN}") - end - let(:frame_list_limit) { 500 } - let(:frame_list_size) { frame_list_limit * 20 } - - before do - single_exception = event.exception.values[0] - new_stacktrace = Sentry::StacktraceInterface.new( - frames: frame_list_size.times.map do |zero_based_index| - Sentry::StacktraceInterface::Frame.new( - "/fake/path", - Sentry::Backtrace::Line.parse("app.rb:#{zero_based_index + 1}:in `/'", in_app_pattern) - ) - end, - ) - single_exception.instance_variable_set(:@stacktrace, new_stacktrace) - - serialized_result = JSON.generate(event.to_hash) - expect(serialized_result.bytesize).to be > Sentry::Envelope::Item::MAX_SERIALIZED_PAYLOAD_SIZE - end - - it "keeps some stacktrace frames and carry on" do - data, _ = subject.serialize_envelope(envelope) - expect(data.bytesize).to be < Sentry::Envelope::Item::MAX_SERIALIZED_PAYLOAD_SIZE - - expect(envelope.items.count).to eq(1) - - event_item = envelope.items.first - frames = event_item.payload[:exception][:values][0][:stacktrace][:frames] - expect(frames.length).to eq(frame_list_limit) - - # Last N lines kept - # N = Frame limit / 2 - expect(frames[-1][:lineno]).to eq(frame_list_size) - expect(frames[-1][:filename]).to eq('app.rb') - expect(frames[-1][:function]).to eq('/') - # - expect(frames[-(frame_list_limit / 2)][:lineno]).to eq(frame_list_size - ((frame_list_limit / 2) - 1)) - expect(frames[-(frame_list_limit / 2)][:filename]).to eq('app.rb') - expect(frames[-(frame_list_limit / 2)][:function]).to eq('/') - - # First N lines kept - # N = Frame limit / 2 - expect(frames[0][:lineno]).to eq(1) - expect(frames[0][:filename]).to eq('app.rb') - expect(frames[0][:function]).to eq('/') - expect(frames[(frame_list_limit / 2) - 1][:lineno]).to eq(frame_list_limit / 2) - expect(frames[(frame_list_limit / 2) - 1][:filename]).to eq('app.rb') - expect(frames[(frame_list_limit / 2) - 1][:function]).to eq('/') - end - - context "if it's still oversized" do - before do - 1000.times do |i| - event.contexts["context_#{i}"] = "s" * Sentry::Event::MAX_MESSAGE_SIZE_IN_BYTES - end - end - - it "rejects the item and logs attributes size breakdown" do - data, _ = subject.serialize_envelope(envelope) - expect(data).to be_nil - expect(io.string).not_to match(/Sending envelope with items \[event\]/) - expect(io.string).to match(/tags: 2, contexts: 8208891, extra: 2/) - end - end - end end end @@ -487,7 +390,7 @@ 1000.times do |i| event.breadcrumbs.record Sentry::Breadcrumb.new(category: i.to_s, message: "x" * Sentry::Event::MAX_MESSAGE_SIZE_IN_BYTES) end - serialized_result = JSON.generate(event.to_hash) + serialized_result = JSON.generate(event.to_h) expect(serialized_result.bytesize).to be > Sentry::Envelope::Item::MAX_SERIALIZED_PAYLOAD_SIZE end @@ -499,18 +402,6 @@ expect(io.string).to match(/Sending envelope with items \[event\]/) end - context "when the event hash has string keys" do - let(:envelope) { subject.envelope_from_event(event.to_json_compatible) } - - it "deletes the event's breadcrumbs and sends it" do - expect(subject).to receive(:send_data) - - subject.send_envelope(envelope) - - expect(io.string).to match(/Sending envelope with items \[event\]/) - end - end - context "if it's still oversized" do before do 1000.times do |i| @@ -594,7 +485,7 @@ item_count: log_events.size, content_type: "application/vnd.sentry.items.log+json" }, - { items: log_events.map(&:to_hash) } + { items: log_events.map(&:to_h) } ) envelope @@ -625,12 +516,6 @@ expect(subject.send_event(event)).to eq(event) end - it "sends Event hash" do - expect(subject).not_to receive(:failed_send) - - expect(subject.send_event(event.to_json_compatible)).to eq(event.to_json_compatible) - end - it "logs correct message" do expect(subject.send_event(event)).to eq(event) diff --git a/sentry-ruby/spec/sentry/vernier/profiler_spec.rb b/sentry-ruby/spec/sentry/vernier/profiler_spec.rb index b8ef3a105..eeb1222b4 100644 --- a/sentry-ruby/spec/sentry/vernier/profiler_spec.rb +++ b/sentry-ruby/spec/sentry/vernier/profiler_spec.rb @@ -147,7 +147,7 @@ end end - describe "#to_hash" do + describe "#to_h" do let (:transport) { Sentry.get_current_client.transport } it "records lost event if not sampled" do @@ -157,7 +157,7 @@ profiler.start profiler.set_initial_sample_decision(false) - expect(profiler.to_hash).to eq({}) + expect(profiler.to_h).to eq({}) end end @@ -166,9 +166,9 @@ profiler.set_initial_sample_decision(true) end - describe '#to_hash' do + describe '#to_h' do it "returns empty hash if not started" do - expect(profiler.to_hash).to eq({}) + expect(profiler.to_h).to eq({}) end context 'with single-thread profiled code' do @@ -179,7 +179,7 @@ end it 'has correct frames' do - frames = profiler.to_hash[:profile][:frames] + frames = profiler.to_h[:profile][:frames] foo_frame = frames.find { |f| f[:function] =~ /foo/ } @@ -192,7 +192,7 @@ end it 'has correct stacks' do - profile = profiler.to_hash[:profile] + profile = profiler.to_h[:profile] frames = profile[:frames] stacks = profile[:stacks] @@ -210,7 +210,7 @@ end it 'has correct samples' do - profile = profiler.to_hash[:profile] + profile = profiler.to_h[:profile] samples = profile[:samples] last_elapsed = 0 @@ -249,7 +249,7 @@ end it "has correct thread metadata" do - thread_metadata = profiler.to_hash[:profile][:thread_metadata] + thread_metadata = profiler.to_h[:profile][:thread_metadata] main_thread = thread_metadata.values.find { |metadata| metadata[:name].include?("rspec") } thread1 = thread_metadata.values.find { |metadata| metadata[:name] == "thread-bar-0" } @@ -265,7 +265,7 @@ end it 'has correct frames', when: { ruby_version?: [:>=, "3.3"], ruby_engine?: "ruby" } do - frames = profiler.to_hash[:profile][:frames] + frames = profiler.to_h[:profile][:frames] foo_frame = frames.find { |f| f[:function] =~ /foo/ } @@ -278,7 +278,7 @@ end it 'has correct stacks', when: { ruby_version?: [:>=, "3.3"], ruby_engine?: "ruby" } do - profile = profiler.to_hash[:profile] + profile = profiler.to_h[:profile] frames = profile[:frames] stacks = profile[:stacks] @@ -296,7 +296,7 @@ end it 'has correct samples' do - profile = profiler.to_hash[:profile] + profile = profiler.to_h[:profile] samples = profile[:samples] samples.group_by { |sample| sample[:thread_id] }.each do |thread_id, thread_samples| diff --git a/sentry-ruby/spec/sentry_spec.rb b/sentry-ruby/spec/sentry_spec.rb index a2a94c43e..ecb7dedc2 100644 --- a/sentry-ruby/spec/sentry_spec.rb +++ b/sentry-ruby/spec/sentry_spec.rb @@ -280,7 +280,7 @@ described_class.capture_exception(e) end - event = last_sentry_event.to_hash + event = last_sentry_event.to_h last_frame = event.dig(:exception, :values, 0, :stacktrace, :frames).last expect(last_frame[:vars]).to eq(nil) end @@ -306,7 +306,7 @@ described_class.capture_exception(e) end - event = last_sentry_event.to_hash + event = last_sentry_event.to_h last_frame = event.dig(:exception, :values, 0, :stacktrace, :frames).last expect(last_frame[:vars]).to include({ a: "1", b: "0" }) end @@ -390,8 +390,8 @@ Sentry.get_current_client.flush - # 3 envelopes: log, transaction, and client_report about dropped profile - expect(sentry_envelopes.size).to be(3) + # 2 envelopes: log and transaction + expect(sentry_envelopes.size).to be(2) log_event = sentry_logs.first @@ -1355,14 +1355,6 @@ expect(described_class.backpressure_monitor).to eq(nil) end - it "flushes and kills metrics aggregator" do - perform_basic_setup { |c| c.metrics.enabled = true } - expect(described_class.metrics_aggregator).to receive(:flush).with(force: true) - expect(described_class.metrics_aggregator).to receive(:kill) - described_class.close - expect(described_class.metrics_aggregator).to eq(nil) - end - it "flushes transport" do expect(described_class.get_current_client).to receive(:flush) described_class.close diff --git a/sentry-sidekiq/spec/sentry/sidekiq-scheduler/scheduler_spec.rb b/sentry-sidekiq/spec/sentry/sidekiq-scheduler/scheduler_spec.rb index 02efd1ccc..661042fd8 100644 --- a/sentry-sidekiq/spec/sentry/sidekiq-scheduler/scheduler_spec.rb +++ b/sentry-sidekiq/spec/sentry/sidekiq-scheduler/scheduler_spec.rb @@ -57,7 +57,7 @@ expect(EveryHappyWorker.sentry_monitor_slug).to eq('regularly_happy') expect(EveryHappyWorker.sentry_monitor_config).to be_a(Sentry::Cron::MonitorConfig) expect(EveryHappyWorker.sentry_monitor_config.schedule).to be_a(Sentry::Cron::MonitorSchedule::Interval) - expect(EveryHappyWorker.sentry_monitor_config.schedule.to_hash).to eq({ value: 10, type: :interval, unit: :minute }) + expect(EveryHappyWorker.sentry_monitor_config.schedule.to_h).to eq({ value: 10, type: :interval, unit: :minute }) end it "does not add monitors for a one-off job" do diff --git a/sentry-sidekiq/spec/sentry/sidekiq/error_handler_spec.rb b/sentry-sidekiq/spec/sentry/sidekiq/error_handler_spec.rb index d1e835d6b..42acd8615 100644 --- a/sentry-sidekiq/spec/sentry/sidekiq/error_handler_spec.rb +++ b/sentry-sidekiq/spec/sentry/sidekiq/error_handler_spec.rb @@ -59,7 +59,7 @@ processor.fire_event(:startup) end - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:exception][:values][0][:type]).to eq("RuntimeError") expect(event[:exception][:values][0][:value]).to match("Uhoh!") expect(event[:transaction]).to eq "Sidekiq/startup" @@ -71,7 +71,7 @@ subject.call(exception, context) expect(transport.events.count).to eq(1) - event = transport.events.first.to_hash + event = transport.events.first.to_h expect(event[:contexts][:sidekiq]).to eq(context) end @@ -87,7 +87,7 @@ subject.call(exception, aj_context) expect(transport.events.count).to eq(1) - event = transport.events.first.to_hash + event = transport.events.first.to_h expect(event[:contexts][:sidekiq]).to eq(expected_context) end @@ -100,7 +100,7 @@ subject.call(exception, context) expect(transport.events.count).to eq(1) - event = transport.events.first.to_hash + event = transport.events.first.to_h expect(event[:transaction]).to eq("Sidekiq/HardWorker") end end diff --git a/sentry-sidekiq/spec/sentry/sidekiq_spec.rb b/sentry-sidekiq/spec/sentry/sidekiq_spec.rb index de65bb074..cd11d3cd9 100644 --- a/sentry-sidekiq/spec/sentry/sidekiq_spec.rb +++ b/sentry-sidekiq/spec/sentry/sidekiq_spec.rb @@ -54,7 +54,7 @@ it "captures exception raised in the worker" do expect { execute_worker(processor, SadWorker) }.to change { transport.events.size }.by(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:sdk]).to eq({ name: "sentry.ruby.sidekiq", version: described_class::VERSION }) expect(event[:exception][:values][0][:type]).to eq("RuntimeError") expect(event[:exception][:values][0][:value]).to match("I'm sad!") @@ -63,7 +63,7 @@ it "doesn't store the private `_config` context", skip: !WITH_SIDEKIQ_7 do expect { execute_worker(processor, SadWorker) }.to change { transport.events.size }.by(1) - event = transport.events.last.to_hash + event = transport.events.last.to_h expect(event[:contexts][:sidekiq].keys.map(&:to_s)).not_to include("_config") end @@ -317,7 +317,7 @@ def retry_last_failed_job first = transport.events[0] check_in_id = first.check_in_id expect(first).to be_a(Sentry::CheckInEvent) - expect(first.to_hash).to include( + expect(first.to_h).to include( type: 'check_in', check_in_id: check_in_id, monitor_slug: "happyworkerwithcron", @@ -326,7 +326,7 @@ def retry_last_failed_job second = transport.events[1] expect(second).to be_a(Sentry::CheckInEvent) - expect(second.to_hash).to include( + expect(second.to_h).to include( :duration, type: 'check_in', check_in_id: check_in_id, @@ -342,7 +342,7 @@ def retry_last_failed_job first = transport.events[0] check_in_id = first.check_in_id expect(first).to be_a(Sentry::CheckInEvent) - expect(first.to_hash).to include( + expect(first.to_h).to include( type: 'check_in', check_in_id: check_in_id, monitor_slug: "failed_job", @@ -352,7 +352,7 @@ def retry_last_failed_job second = transport.events[1] expect(second).to be_a(Sentry::CheckInEvent) - expect(second.to_hash).to include( + expect(second.to_h).to include( :duration, type: 'check_in', check_in_id: check_in_id,