Skip to content

Commit

Permalink
Prevent crashes from get_main_hub when in trap context
Browse files Browse the repository at this point in the history
  • Loading branch information
solnic committed Jan 17, 2025
1 parent 3d7c0d1 commit 5fce129
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
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
40 changes: 40 additions & 0 deletions sentry-ruby/spec/sentry_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,46 @@
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
read_pipe.close

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 unless read_pipe.closed?
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 5fce129

Please sign in to comment.