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 16, 2025
1 parent a1d2941 commit cccfc18
Show file tree
Hide file tree
Showing 2 changed files with 41 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

Check warning on line 313 in sentry-ruby/lib/sentry-ruby.rb

View check run for this annotation

Codecov / codecov/patch

sentry-ruby/lib/sentry-ruby.rb#L313

Added line #L313 was not covered by tests
end

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

context "works within a trap context" do
it "reproduces mutex issue in trap handler" 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

start_time = Time.now
timeout = 1.0
result = nil

while Time.now - start_time < timeout
break if Process.wait(pid, Process::WNOHANG)
sleep 0.01
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

0 comments on commit cccfc18

Please sign in to comment.