Skip to content

Commit

Permalink
Prevent crashes from get_main_hub when in trap context (#2510)
Browse files Browse the repository at this point in the history
* Update CHANGELOG
* Prevent crashes from get_main_hub when in trap context
  • Loading branch information
solnic authored Jan 17, 2025
1 parent 14ef446 commit 1cd952b
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

- Default to `internal_error` error type for OpenTelemetry spans [#2473](https://github.com/getsentry/sentry-ruby/pull/2473)
- Improve `before_send` and `before_send_transaction`'s return value handling ([#2504](https://github.com/getsentry/sentry-ruby/pull/2504))
- Fix a crash when calling `Sentry.get_main_hub` in a trap context ([#2510](https://github.com/getsentry/sentry-ruby/pull/2510))

### Internal

Expand Down
3 changes: 3 additions & 0 deletions sentry-ruby/lib/sentry-ruby.rb
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ def csp_report_uri
# @return [Hub]
def get_main_hub
MUTEX.synchronize { @main_hub }
rescue ThreadError
# In some rare cases this may be called in a trap context so we need to handle it gracefully
@main_hub
end

# Takes an instance of Sentry::Breadcrumb and stores it to the current active scope.
Expand Down
39 changes: 39 additions & 0 deletions sentry-ruby/spec/sentry_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,45 @@
end
end
end

context "works within a trap context", when: { ruby_engine?: "ruby", ruby_version?: [:>=, "3.4"] } do
it "doesn't raise error when accessing main hub in trap context" do
read_pipe, write_pipe = IO.pipe

pid = fork do
described_class.init do |config|
config.dsn = Sentry::TestHelper::DUMMY_DSN
end

trap('HUP') do
hub = described_class.get_main_hub

write_pipe.write(hub.class.to_s)
write_pipe.close
end

Process.kill('HUP', Process.pid)
end

write_pipe.close

result = nil
retries = 0

while retries < 10
break if Process.wait(pid)

sleep 0.01

retries += 1
end

result = read_pipe.read
read_pipe.close

expect(result).to eq("Sentry::Hub")
end
end
end

describe "#clone_hub_to_current_thread" do
Expand Down
4 changes: 4 additions & 0 deletions sentry-ruby/spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ def self.rack_available?
def self.ruby_version?(op, version)
RUBY_VERSION.public_send(op, version)
end

def self.ruby_engine?(engine)
RUBY_ENGINE == engine
end
end

def fixtures_root
Expand Down

0 comments on commit 1cd952b

Please sign in to comment.