Skip to content

Commit 1cd952b

Browse files
authored
Prevent crashes from get_main_hub when in trap context (#2510)
* Update CHANGELOG * Prevent crashes from get_main_hub when in trap context
1 parent 14ef446 commit 1cd952b

File tree

4 files changed

+47
-0
lines changed

4 files changed

+47
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

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

1415
### Internal
1516

sentry-ruby/lib/sentry-ruby.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,9 @@ def csp_report_uri
308308
# @return [Hub]
309309
def get_main_hub
310310
MUTEX.synchronize { @main_hub }
311+
rescue ThreadError
312+
# In some rare cases this may be called in a trap context so we need to handle it gracefully
313+
@main_hub
311314
end
312315

313316
# Takes an instance of Sentry::Breadcrumb and stores it to the current active scope.

sentry-ruby/spec/sentry_spec.rb

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,45 @@
7070
end
7171
end
7272
end
73+
74+
context "works within a trap context", when: { ruby_engine?: "ruby", ruby_version?: [:>=, "3.4"] } do
75+
it "doesn't raise error when accessing main hub in trap context" do
76+
read_pipe, write_pipe = IO.pipe
77+
78+
pid = fork do
79+
described_class.init do |config|
80+
config.dsn = Sentry::TestHelper::DUMMY_DSN
81+
end
82+
83+
trap('HUP') do
84+
hub = described_class.get_main_hub
85+
86+
write_pipe.write(hub.class.to_s)
87+
write_pipe.close
88+
end
89+
90+
Process.kill('HUP', Process.pid)
91+
end
92+
93+
write_pipe.close
94+
95+
result = nil
96+
retries = 0
97+
98+
while retries < 10
99+
break if Process.wait(pid)
100+
101+
sleep 0.01
102+
103+
retries += 1
104+
end
105+
106+
result = read_pipe.read
107+
read_pipe.close
108+
109+
expect(result).to eq("Sentry::Hub")
110+
end
111+
end
73112
end
74113

75114
describe "#clone_hub_to_current_thread" do

sentry-ruby/spec/spec_helper.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,10 @@ def self.rack_available?
9393
def self.ruby_version?(op, version)
9494
RUBY_VERSION.public_send(op, version)
9595
end
96+
97+
def self.ruby_engine?(engine)
98+
RUBY_ENGINE == engine
99+
end
96100
end
97101

98102
def fixtures_root

0 commit comments

Comments
 (0)